From 37e3f9edb2f012a6ec12fcf6054c1a8ba64937e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Mon, 30 Nov 2026 12:02:26 +0100 Subject: [PATCH] Fix #15290 (donate-cpu-server-rest: handle triage results and suggest warnings to triage) --- test/tools/donate_cpu_server_rest_test.py | 227 +++++++++++- tools/donate-cpu-server-rest.py | 404 +++++++++++++++++++++- 2 files changed, 625 insertions(+), 6 deletions(-) diff --git a/test/tools/donate_cpu_server_rest_test.py b/test/tools/donate_cpu_server_rest_test.py index c07f104aef6..84989b6598c 100644 --- a/test/tools/donate_cpu_server_rest_test.py +++ b/test/tools/donate_cpu_server_rest_test.py @@ -1,4 +1,5 @@ from importlib import import_module +import json import time import warnings @@ -233,7 +234,7 @@ def test_html_pages(client): client.post('/api/v1/results', content=RESULT_CRASH) client.post('/api/v1/info', content=INFO) pages = ['/', '/crash.html', '/timeout.html', '/stale.html', '/diff.html', '/diff-knownConditionTrueFalse', - '/head.html', '/headinfo.html', '/head-syntaxError', '/headtoday-syntaxError', '/headinfo-checkLibraryFunction', + '/head.html', '/headinfo.html', '/head-syntaxError', '/headtoday-syntaxError', '/headinfo-checkLibraryFunction', '/triage.html', '/latest.html', '/time_lt.html', '/time_gt.html', '/time_slow.html', '/clients.html', '/check_library_function_report.html', '/check_library_check_type_report.html', '/unknown_macro.html', '/value_flow_bailout_incomplete_var.html'] @@ -295,3 +296,227 @@ def test_raw_files(client): assert client.get('/info_output/aaa').status_code == 200 assert client.get('/nonexistent').status_code == 404 assert client.get('/..%2F..%2Fetc%2Fpasswd').status_code == 404 + + +WARNING_OOB = "ccc/a.c:1:2: error: Array 'a[2]' accessed at index 2, which is out of bounds. [arrayIndexOutOfBounds]" +WARNING_MACRO = 'ccc/b.c:4:1: error: There is an unknown macro here somewhere. Configuration is required. ' \ + 'If FOO is a macro then please configure it. [unknownMacro]' +WARNING_OLD = server.OLD_VERSION + ' ccc/c.c:1:2: style: blah [knownConditionTrueFalse]' + + +def triage(warning, verdict, url=PKG_C): + return {'url': url, 'warning': warning, 'verdict': verdict} + + +def triage_warnings(work_path): + return [item['warning'] for item in json.loads((work_path / 'triage.json').read_text())] + + +def upload_triage(client): + r = client.post('/api/v1/triage', json=[ + triage('head ' + WARNING_OOB, 'Unintentional ; True positive - not a False positive \u00e5'), + triage(WARNING_MACRO, 'Intentional ; False positive - x'), + triage(WARNING_OLD, 'False positive'), + triage(WARNING_OOB + '\n' + WARNING_OLD, 'rephrazed')]) + assert r.status_code == 200 + assert r.json() == {'added': 4, 'updated': 0, 'unchanged': 0, 'skipped': 0} + + +def test_triage_report(client): + upload_triage(client) + data = client.get('/api/v1/reports/triage').json() + assert data['head']['message_ids'] == { + 'arrayIndexOutOfBounds': {'tp': 1, 'fp': 0, 'other': 1, 'tp_ratio': 1.0, 'fp_ratio': 0.0}, + 'unknownMacro': {'tp': 0, 'fp': 1, 'other': 0, 'tp_ratio': 0.0, 'fp_ratio': 1.0}, + } + assert data['head']['total'] == {'tp': 1, 'fp': 1, 'other': 1, 'tp_ratio': 0.5, 'fp_ratio': 0.5} + assert list(data['old']['message_ids']) == ['knownConditionTrueFalse'] + html = client.get('/triage.html').text + assert '/head-arrayIndexOutOfBounds' in html and '/diff-knownConditionTrueFalse' in html and '50%' in html + + +def test_triage_merge(client, work_path): + upload_triage(client) + # with and without 'head' is the same warning, and notes are ignored + r = client.post('/api/v1/triage', json=[ + triage(WARNING_OOB + '\nccc/a.c:1:1: note: array a [arrayIndexOutOfBounds]', 'False positive'), + triage(WARNING_OLD, 'False positive'), + triage('ccc/a.c:1:1: note: array a', 'True positive'), + triage('no message id', 'True positive'), + triage(WARNING_OOB, 'True positive', PKG_C.replace('ccc_1.0', 'ccc_9.0')), + triage(WARNING_OOB, 'True positive', 'http://example.com/x.tar.gz')]) + assert r.json() == {'added': 0, 'updated': 1, 'unchanged': 1, 'skipped': 4} + assert len(triage_warnings(work_path)) == 4 + assert client.get('/api/v1/reports/triage').json()['head']['total']['fp'] == 2 + + # the triage results are loaded after a restart + with TestClient(server.create_app(str(work_path), rescan_interval=0.2)) as client2: + assert client2.get('/api/v1/reports/triage').json()['head']['total']['fp'] == 2 + + +def test_triage_upload_errors(client, work_path, monkeypatch): + for data in ('', '{}', '[{"url": "x"}]', '[{"url": "x", "warning": 1, "verdict": "x"}]', '[1'): + assert client.post('/api/v1/triage', content=data).status_code == 422 + monkeypatch.setattr(server, 'MAX_TRIAGE_SIZE', 10) + assert client.post('/api/v1/triage', json=[triage(WARNING_OOB, 'True positive')]).status_code == 413 + assert not (work_path / 'triage.json').exists() + + +def test_triage_broken_file(work_path): + for text in ('[{', '[1]', '[{"url": "x"}]', '{"a": 1}'): + (work_path / 'triage.json').write_text(text) + with pytest.raises(RuntimeError): + server.create_app(str(work_path)) + assert (work_path / 'triage.json').read_text() == text + + +def test_triage_removed_when_results_are_uploaded(client, work_path): + upload_triage(client) + results = RESULT_FILE_C.split('\n', 1)[1] + + # results for another package, or same results => nothing is removed + assert client.post('/api/v1/results', content=RESULT_CRASH).status_code == 201 + assert client.post('/api/v1/results', content=results).status_code == 201 + assert len(triage_warnings(work_path)) == 4 + + # a missing warning says nothing if there was a crash or a timeout + for count in ('Crash! 2', '3 TO!'): + data = results.replace('count: 3 2', 'count: ' + count).replace(WARNING_OOB, '') + assert client.post('/api/v1/results', content=data).status_code == 201 + assert len(triage_warnings(work_path)) == 4 + + # the old warning is not in the diff anymore + data = results.replace(WARNING_OLD + '\n', '') + assert client.post('/api/v1/results', content=data).status_code == 201 + assert triage_warnings(work_path) == [WARNING_OOB, WARNING_MACRO] + + data = data.replace(WARNING_OOB, WARNING_OOB.replace(':1:2:', ':2:2:')) + assert client.post('/api/v1/results', content=data).status_code == 201 + assert triage_warnings(work_path) == [WARNING_MACRO] + assert client.get('/api/v1/reports/triage').json()['head']['total']['fp'] == 1 + + +def test_triage_removed_when_old_server_stores_results(client, work_path): + upload_triage(client) + (work_path / 'donated-results' / 'ccc').write_text(RESULT_FILE_C.replace(WARNING_MACRO, '')) + for _ in range(100): + if len(triage_warnings(work_path)) == 3: + break + time.sleep(0.05) + assert WARNING_MACRO not in triage_warnings(work_path) + assert len(triage_warnings(work_path)) == 3 + + +def test_triage_removed_when_package_url_changes(work_path): + new_url = PKG_C.replace('ccc_1.0', 'ccc_1.1') + with open(str(work_path / 'packages.txt'), 'at') as f: + f.write(new_url + '\n') + with TestClient(server.create_app(str(work_path), rescan_interval=0.2)) as client: + upload_triage(client) + results = RESULT_FILE_C.split('\n', 1)[1].replace(PKG_C, new_url) + assert client.post('/api/v1/results', content=results).status_code == 201 + assert triage_warnings(work_path) == [] + + +def suggestions(client): + r = client.get('/api/v1/triage/suggestions') + assert r.status_code == 200 + assert r.json()['complete'] is True + return r.json()['warnings'] + + +def result_file(head, diff, count='3 2', url=PKG_C): + return '2026-11-01 10:00\n{}\ncppcheck: head {}\ncount: {}\nelapsed-time: 1.0 1.0\nhead results:\n{}\n\ndiff:\n{}\n'.format( + url, server.OLD_VERSION, count, '\n'.join(head), '\n'.join(diff)) + + +def style(line, message_id='id1'): + return 'ccc/a.c:{}:1: style: x [{}]'.format(line, message_id) + + +def test_triage_suggestions(client): + assert suggestions(client) == [ + {'message_id': 'arrayIndexOutOfBounds', 'section': 'diff', 'package': 'ccc', 'url': PKG_C, 'warning': 'head ' + WARNING_OOB}, + {'message_id': 'knownConditionTrueFalse', 'section': 'diff', 'package': 'ccc', 'url': PKG_C, 'warning': WARNING_OLD}, + {'message_id': 'unknownMacro', 'section': 'head', 'package': 'ccc', 'url': PKG_C, 'warning': WARNING_MACRO}, + ] + # the suggestions can be uploaded when there is a verdict; after that they are not suggested anymore + items = [dict(w, verdict='True positive') for w in suggestions(client)] + assert client.post('/api/v1/triage', json=items[:1]).json()['added'] == 1 + assert [w['warning'] for w in suggestions(client)] == [WARNING_OLD, WARNING_MACRO] + assert client.post('/api/v1/triage', json=items[1:]).json()['added'] == 2 + assert suggestions(client) == [] + + +def test_triage_suggestions_triaged(client): + upload_triage(client) + assert suggestions(client) == [] + + +def test_triage_suggestions_selection(client, work_path, monkeypatch): + head = [style(n) for n in range(1, 31)] + [style(n, 'id2') for n in range(1, 31)] + [style(7, 'id2')] + head += ['ccc/a.c:1:1: debug: x [dbg]', 'ccc/a.c:9:1: note: x [id1]'] + diff = ['head ' + style(n) for n in (1, 2)] + [server.OLD_VERSION + ' ' + style(99)] + diff += ['head ' + style(n, 'id2') for n in range(1, 21)] + client.post('/api/v1/results', content=result_file(head, diff).split('\n', 1)[1]) + client.post('/api/v1/triage', json=[triage(style(2), 'False positive')]) + + first = suggestions(client) + id1 = [w for w in first if w['message_id'] == 'id1'] + id2 = [w for w in first if w['message_id'] == 'id2'] + assert len(first) == 10 and len(id1) == 5 and len(id2) == 5 + # all the diff warnings without triage result, and then head warnings. No duplicates. + assert {w['warning'] for w in id1 if w['section'] == 'diff'} == {'head ' + style(1), server.OLD_VERSION + ' ' + style(99)} + assert len({w['warning'] for w in id1 if w['section'] == 'head'} - {style(1), style(2)}) == 3 + # enough warnings in the diff + assert {w['section'] for w in id2} == {'diff'} + assert len({w['warning'] for w in id2}) == 5 + + # same list the same day, new random list the next day + assert suggestions(client) == first + monkeypatch.setattr(server, 'today_str', lambda: '2100-01-01') + lists = [suggestions(client)] + assert suggestions(client) == lists[0] + for day in range(2, 7): + monkeypatch.setattr(server, 'today_str', lambda day=day: '2100-01-0{}'.format(day)) + lists.append(suggestions(client)) + assert any(x != first for x in lists) + + +@pytest.mark.parametrize('old,new', [ + ('count: 3 2', 'count: Crash! 2'), + ('count: 3 2', 'count: 3 TO!'), + ('cppcheck: head ' + server.OLD_VERSION, 'cppcheck: head 1.0'), + ('ccc_1.0', 'ccc_9.0')]) +def test_triage_suggestions_ignored_results(work_path, old, new): + # incomplete results, results for another old version, unknown package url + assert old in RESULT_FILE_C + (work_path / 'donated-results' / 'ccc').write_text(RESULT_FILE_C.replace(old, new)) + with TestClient(server.create_app(str(work_path), rescan_interval=0.2)) as client: + for _ in range(100): + if client.get('/api/v1/status').json()['index_ready']: + break + time.sleep(0.05) + assert client.get('/api/v1/status').json()['results'] == 1 + assert suggestions(client) == [] + + +def test_triage_suggestions_index_not_ready(work_path): + # without lifespan the index is not built => incomplete and not reused + client = TestClient(server.create_app(str(work_path))) + data = client.get('/api/v1/triage/suggestions').json() + assert data['complete'] is False and data['warnings'] == [] + with client: + for _ in range(100): + if client.get('/api/v1/status').json()['index_ready']: + break + time.sleep(0.05) + assert len(suggestions(client)) == 3 + + +def test_random_order(): + rng = server.random.Random(1) + assert list(server.random_order(0, rng)) == [] + orders = {tuple(server.random_order(4, rng)) for _ in range(1000)} + assert len(orders) == 24 + assert all(sorted(order) == [0, 1, 2, 3] for order in orders) diff --git a/tools/donate-cpu-server-rest.py b/tools/donate-cpu-server-rest.py index 519a95463f0..4479d499253 100755 --- a/tools/donate-cpu-server-rest.py +++ b/tools/donate-cpu-server-rest.py @@ -18,32 +18,40 @@ # Pages that list the actual warning lines for a message id read only the result files that the # index says contain that message id, and those listings are cached as well. # +# Triage results (is a warning a true positive or a false positive?) can be uploaded. They are +# merged into /triage.json. When new results for a package arrive, the triage results +# for warnings that are no longer reported for that package are removed. Random warnings that should +# be triaged are suggested in a list that is generated once per day. +# # Requirements: see donate-cpu-server-requirements.txt # Usage: donate-cpu-server-rest.py [--test] [--host HOST] [--port PORT] [--work-path PATH] # The REST API documentation is available at /docs when the server is running. import argparse +import bisect import datetime +import itertools import json import logging import os +import random import re import sys import threading import time import urllib.parse from contextlib import asynccontextmanager -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple +from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Set, Tuple import jinja2 import uvicorn from fastapi import FastAPI, HTTPException, Query, Request from fastapi.concurrency import run_in_threadpool from fastapi.responses import HTMLResponse, PlainTextResponse -from pydantic import BaseModel +from pydantic import BaseModel, TypeAdapter, ValidationError # Version scheme (MAJOR.MINOR.PATCH) should orientate on "Semantic Versioning" https://semver.org/ -SERVER_VERSION = '2.0.0' +SERVER_VERSION = '2.1.0' # TODO: fetch from GitHub tags OLD_VERSION = '2.22.0' @@ -53,7 +61,10 @@ MAX_RESULT_SIZE = 1024 * 1024 MAX_INFO_SIZE = 7 * 1024 * 1024 +MAX_TRIAGE_SIZE = 16 * 1024 * 1024 MAX_LATEST = 20 +# number of warnings per message id in the list of warnings that should be triaged +TRIAGE_SUGGESTIONS_PER_ID = 5 # Bump this when the parsing changes, so that all persisted summaries are regenerated. PARSER_VERSION = 2 @@ -68,6 +79,11 @@ RE_DEBIAN_URL = re.compile(r'ftp://.*pool/main/[^/]+/([^/]+)/[^/]*tar.(gz|bz2|xz)') RE_CPPCHECK_URL = re.compile(r'https?://cppcheck\.sf\.net/([a-z]+).tgz') +# 'head ' / '2.22.0 ' before a warning in the diff section +RE_VERSION_PREFIX = re.compile(r'(head|\d+(?:\.\d+)+) ') +# the verdict can be followed by an explanation: 'Intentional ; False positive - the pointer is ...' +RE_VERDICT = re.compile(r'(?:(?:un)?intentional\s*;\s*)?(true|false) positive\b', re.IGNORECASE) + # message id -> (kind of result file, name of the extracted item) NAME_REPORTS = { 'checkLibraryFunction': ('info', 'function'), @@ -366,6 +382,8 @@ def __init__(self, result_path: str, index_path: str) -> None: self.write_lock = threading.Lock() self.generation = 0 self.ready = False + # called with (kind, package, entry, text) when the text of a new/modified file was parsed + self.on_parsed: Optional[Callable[[str, str, Dict[str, Any], str], None]] = None def data_file(self, kind: str, package: str) -> str: return safe_path(self.data_dirs[kind], package) @@ -434,6 +452,14 @@ def _parse_file(self, kind: str, package: str, text: Optional[str] = None) -> Di entry['stamp'] = [st.st_mtime_ns, st.st_size] os.makedirs(self.sidecar_dirs[kind], exist_ok=True) write_atomic(self._sidecar_file(kind, package), json.dumps(entry)) + if self.on_parsed is not None: + st = os.stat(path) + # if the file was modified while it was read then the text might be incomplete + if entry['stamp'] == [st.st_mtime_ns, st.st_size]: + try: + self.on_parsed(kind, package, entry, text) + except Exception: + logger.exception('processing of new %s for %s failed', kind, package) return entry def reconcile(self) -> None: @@ -483,6 +509,285 @@ def remove(self, kind: str, package: str) -> None: self._set(kind, package, None) +# --------------------------------------------------------------------------------------------- +# Triage results +# --------------------------------------------------------------------------------------------- + +def package_of_url(url: str) -> Optional[str]: + res = RE_DEBIAN_URL.match(url) or RE_CPPCHECK_URL.match(url) + return res.group(1) if res else None + + +def is_note(line: str) -> bool: + return ': note: ' in line + + +def triage_lines(warning: str) -> Tuple[str, ...]: + """The warning lines of a triage result. Notes are ignored. 'head X' is the same warning as 'X'.""" + lines = [line.strip() for line in warning.splitlines()] + return tuple(line[len('head '):] if line.startswith('head ') else line + for line in lines if line and not is_note(line)) + + +def is_old_warning(line: str) -> bool: + """Is this triage line (see triage_lines) about a warning that only the old version reports""" + return RE_VERSION_PREFIX.match(line) is not None + + +def verdict_of(text: str) -> str: + m = RE_VERDICT.match(text.strip()) + if m is None: + return 'other' + return 'tp' if m.group(1).lower() == 'true' else 'fp' + + +def has_complete_results(entry: Dict[str, Any]) -> bool: + """There was no crash, timeout, ...""" + count = entry['count'] + return len(count) >= 2 and all(c.isdigit() for c in count) + + +def reported_warnings(entry: Dict[str, Any], text: str) -> Optional[Set[str]]: + """All warnings in a result file: head warnings without prefix, and warnings that only the old + version reports with the version as prefix. Returns None if the results are incomplete.""" + if not has_complete_results(entry): + # crash, timeout, ...: a missing warning does not mean that it is fixed + return None + warnings = set() + section = 'header' + for line in text.split('\n'): + line = line.strip() + if section == 'header': + if line.startswith(HEAD_MARKER): + section = 'head' + elif section == 'head': + if line.startswith('diff:'): + section = 'diff' + else: + warnings.add(line) + elif is_old_warning(line): + # 'head' lines in the diff are also in the head results + warnings.add(line) + return warnings if section == 'diff' else None + + +class TriageResult(BaseModel): + url: str + warning: str + verdict: str + + +class TriageStore: + """Triage results. Persisted in a JSON file that has the same format as the uploaded data.""" + + def __init__(self, path: str) -> None: + self.path = path + self.lock = threading.Lock() + # package -> {(url, warning lines): triage result}; never modified in place, only replaced + self.packages: Dict[str, Dict[Any, Dict[str, str]]] = {} + if os.path.isfile(path): + # do not start with an empty database if the file is broken, it would be overwritten + try: + with open(path, 'rt', encoding='utf-8') as f: + self.packages = self._merge({}, json.load(f), lambda _: True)[0] + except (ValueError, TypeError, KeyError, AttributeError) as e: + raise RuntimeError("failed to load '{}': {!r}".format(path, e)) from e + + @staticmethod + def _merge(old: Dict[str, Dict[Any, Dict[str, str]]], results: List[Dict[str, str]], + known_url: Callable[[str], bool]) -> Tuple[Dict[str, Dict[Any, Dict[str, str]]], Dict[str, int]]: + new = dict(old) + copied = set() + stats = {'added': 0, 'updated': 0, 'unchanged': 0, 'skipped': 0} + for result in results: + url = result['url'].strip() + package = package_of_url(url) + lines = triage_lines(result['warning']) + if package is None or not known_url(url) or not lines or any(message_id_of(line) is None for line in lines): + stats['skipped'] += 1 + continue + if package not in copied: + copied.add(package) + new[package] = dict(new.get(package, {})) + item = {'url': url, 'warning': '\n'.join(lines), 'verdict': result['verdict'].strip()} + previous = new[package].get((url, lines)) + if previous is None: + stats['added'] += 1 + else: + stats['unchanged' if previous == item else 'updated'] += 1 + new[package][(url, lines)] = item + return new, stats + + def _save(self, new: Dict[str, Dict[Any, Dict[str, str]]]) -> None: + results = [item for package in sorted(new) for item in new[package].values()] + write_atomic(self.path, json.dumps(results, indent=1) + '\n') + self.packages = new + + def results(self) -> List[Dict[str, str]]: + with self.lock: + packages = self.packages + return [item for items in packages.values() for item in items.values()] + + def merge(self, results: List[Dict[str, str]], known_url: Callable[[str], bool]) -> Dict[str, int]: + """Merge triage results. A new verdict for a warning replaces the previous one.""" + with self.lock: + new, stats = self._merge(self.packages, results, known_url) + if stats['added'] or stats['updated']: + self._save(new) + return stats + + def remove_unmatched(self, package: str, entry: Dict[str, Any], text: str) -> None: + """Remove triage results that do not match the new results of a package.""" + with self.lock: + items = self.packages.get(package) + if not items: + return + warnings = reported_warnings(entry, text) + if warnings is None: + return + # the source code is different if the url is different + keep = {key: item for key, item in items.items() + if key[0] == entry['url'] and warnings.issuperset(key[1])} + if len(keep) == len(items): + return + new = dict(self.packages) + if keep: + new[package] = keep + else: + del new[package] + self._save(new) + logger.info('removed %d of %d triage results for %s', len(items) - len(keep), len(items), package) + + +# --------------------------------------------------------------------------------------------- +# Suggestions: warnings that should be triaged +# --------------------------------------------------------------------------------------------- + +def is_debug_or_information(line: str) -> bool: + return ': debug: ' in line or ': information: ' in line + + +def warnings_with_id(text: str, message_id: str) -> Dict[str, List[str]]: + """The warning lines with the given message id in the sections of a result file. The lines in the + diff section include the version prefix.""" + warnings: Dict[str, List[str]] = {'diff': [], 'head': []} + section = None + for line in text.split('\n'): + line = line.strip() + if section is None: + if line.startswith(HEAD_MARKER): + section = 'head' + elif section == 'head' and line.startswith('diff:'): + section = 'diff' + elif message_id_of(line) == message_id and (section == 'head' or RE_VERSION_PREFIX.match(line)): + warnings[section].append(line) + return warnings + + +def random_order(total: int, rng: random.Random) -> Iterator[int]: + """The numbers 0..total-1 in random order (shuffled lazily, normally only a few are needed).""" + swapped: Dict[int, int] = {} + for i in range(total): + j = rng.randrange(i, total) + yield swapped.get(j, j) + swapped[j] = swapped.get(i, i) + + +def _pick_warnings(message_id: str, candidates: Dict[str, Dict[str, Dict[str, Any]]], read: Callable[[str], str], + triaged: Set[Tuple[str, str]], limit: int, rng: random.Random) -> List[Dict[str, Any]]: + """candidates: section -> {package: index entry} for the packages that have warnings with the message id""" + files: Dict[str, Dict[str, List[str]]] = {} + picked: List[Dict[str, Any]] = [] + seen = set(triaged) + for section, count in (('diff', lambda e: sum(e['diff'][message_id])), ('head', lambda e: e['head_ids'][message_id])): + # every warning has the same probability, packages with many warnings are picked more often + packages = list(candidates[section]) + ends = list(itertools.accumulate(count(candidates[section][package]) for package in packages)) + for position in random_order(ends[-1] if ends else 0, rng): + if len(picked) >= limit: + return picked + i = bisect.bisect_right(ends, position) + package, n = packages[i], position - (ends[i - 1] if i > 0 else 0) + if package not in files: + try: + files[package] = warnings_with_id(read(package), message_id) + except OSError: + files[package] = {'diff': [], 'head': []} + lines = files[package][section] + if n >= len(lines): + # the file was modified after it was indexed + continue + if is_debug_or_information(lines[n]): + # all messages with this id are like this, do not read all the files + return picked + url = candidates[section][package]['url'] + # 'head X' in the diff is the same warning as 'X' in the head results + key = (url, triage_lines(lines[n])[0]) + if key in seen: + continue + seen.add(key) + picked.append({'message_id': message_id, 'section': section, 'package': package, 'url': url, 'warning': lines[n]}) + return picked + + +def triage_suggestions(entries: Dict[str, Dict[str, Any]], read: Callable[[str], str], triaged: Set[Tuple[str, str]], + known_url: Callable[[str], bool], limit: int, rng: random.Random) -> List[Dict[str, Any]]: + """Random warnings without triage result, at most 'limit' per message id. Warnings in the head results + are only picked if there are not enough warnings in the diff.""" + candidates: Dict[str, Dict[str, Dict[str, Dict[str, Any]]]] = {} + for package, entry in entries.items(): + # a crash or timeout means that the diff is wrong. Triage results for unknown urls are not accepted. + url = entry['url'] + if not is_current(entry) or not has_complete_results(entry) or \ + url is None or package_of_url(url) is None or not known_url(url): + continue + for section, key in (('diff', 'diff'), ('head', 'head_ids')): + for message_id in entry[key]: + candidates.setdefault(message_id, {'diff': {}, 'head': {}})[section][package] = entry + out = [] + for message_id in sorted(candidates): + out.extend(_pick_warnings(message_id, candidates[message_id], read, triaged, limit, rng)) + return out + + +class TriageSuggestions: + """The list of warnings that should be triaged. A new list is generated once per day.""" + + def __init__(self, index: ResultIndex, triage: TriageStore, known_url: Callable[[str], bool]) -> None: + self.index = index + self.triage = triage + self.known_url = known_url + self.lock = threading.Lock() + self.date: Optional[str] = None + self.data: Dict[str, Any] = {} + + def _triaged(self) -> Set[Tuple[str, str]]: + return {(item['url'], line) for item in self.triage.results() for line in triage_lines(item['warning'])} + + def _generate(self) -> Dict[str, Any]: + t_start = time.perf_counter() + warnings = triage_suggestions(self.index.snapshot('results'), + lambda package: read_text(self.index.data_file('results', package)), + self._triaged(), self.known_url, TRIAGE_SUGGESTIONS_PER_ID, random.Random()) + logger.info('%d triage suggestions generated in %.1fs', len(warnings), time.perf_counter() - t_start) + return {'generated': datetime.datetime.now().isoformat(sep=' ', timespec='seconds'), 'warnings': warnings} + + def get(self) -> Dict[str, Any]: + with self.lock: + # only one thread generates the list + complete = self.index.ready + data = self.data + today = today_str() + if self.date != today: + data = self._generate() + if complete: + self.data, self.date = data, today + # warnings might have been triaged after the list was generated + triaged = self._triaged() + warnings = [w for w in data['warnings'] if (w['url'], triage_lines(w['warning'])[0]) not in triaged] + return {'complete': complete, 'old_version': OLD_VERSION, **data, 'warnings': warnings} + + # --------------------------------------------------------------------------------------------- # Package list # --------------------------------------------------------------------------------------------- @@ -803,6 +1108,26 @@ def clients_report(entries: Dict[str, Dict[str, Any]]) -> Dict[str, Any]: return {k: dict(sorted(v.items())) for k, v in out.items()} +def triage_report(results: List[Dict[str, str]]) -> Dict[str, Any]: + # 'head': warnings that head reports, 'old': warnings that only the old version reports + counts: Dict[str, Dict[str, Dict[str, Any]]] = {'head': {}, 'old': {}} + for result in results: + lines = triage_lines(result['warning']) + part = counts['old' if all(is_old_warning(line) for line in lines) else 'head'] + item = part.setdefault(message_id_of(lines[0]) or '', {'tp': 0, 'fp': 0, 'other': 0}) + item[verdict_of(result['verdict'])] += 1 + + def with_ratio(item: Dict[str, int]) -> Dict[str, Any]: + judged = item['tp'] + item['fp'] + return dict(item, tp_ratio=item['tp'] / judged if judged else None, fp_ratio=item['fp'] / judged if judged else None) + + def to_json(part: Dict[str, Dict[str, int]]) -> Dict[str, Any]: + total = {key: sum(item[key] for item in part.values()) for key in ('tp', 'fp', 'other')} + return {'message_ids': {mid: with_ratio(part[mid]) for mid in sorted(part)}, 'total': with_ratio(total)} + + return {'old_version': OLD_VERSION, **{key: to_json(part) for key, part in counts.items()}} + + # Listings of the actual warning lines. These read the result files, but only those that the # index says contain the message id. @@ -1001,6 +1326,7 @@ def with_query(request: Request, **params: str) -> str: ('Timeout report', '/timeout.html', []), ('Stale report', '/stale.html', []), ('Diff report', '/diff.html', []), + ('Triage report (TP/FP ratios)', '/triage.html', []), ('HEAD report', '/head.html', []), ('HEAD (information) report', '/headinfo.html', []), ('Latest results', '/latest.html', []), @@ -1028,6 +1354,7 @@ def with_query(request: Request, **params: str) -> str: ('REST API', [ ('API documentation', '/docs', []), ('Status', '/api/v1/status', []), + ('Triage suggestions', '/api/v1/triage/suggestions', []), ]), ] @@ -1056,7 +1383,7 @@ def _safe_package_name(package: str) -> str: return package -async def _read_body(request: Request, limit: int) -> Tuple[str, bool]: +async def _read_body(request: Request, limit: int, encoding: str = 'ascii') -> Tuple[str, bool]: """Returns the body (at most 'limit' bytes) and whether it was truncated.""" chunks = [] size = 0 @@ -1067,7 +1394,7 @@ async def _read_body(request: Request, limit: int) -> Tuple[str, bool]: if size >= limit: truncated = True break - data = b''.join(chunks)[:limit].decode('ascii', 'ignore') + data = b''.join(chunks)[:limit].decode(encoding, 'ignore') if data.endswith('\nDONE'): # sent by the socket based client data = data[:-len('\nDONE')] @@ -1116,6 +1443,15 @@ def create_app(work_path: str, rescan_interval: float = DEFAULT_RESCAN_INTERVAL) packages = PackageQueue(work_path) index = ResultIndex(result_path, os.path.join(work_path, 'report-index')) cache = ReportCache(index, REPORT_MAX_AGE) + triage_adapter = TypeAdapter(List[TriageResult]) + triage = TriageStore(os.path.join(work_path, 'triage.json')) + suggestions = TriageSuggestions(index, triage, packages.contains) + + def on_parsed(kind: str, package: str, entry: Dict[str, Any], text: str) -> None: + if kind == 'results': + triage.remove_unmatched(package, entry, text) + + index.on_parsed = on_parsed def maintenance(stop: threading.Event) -> None: while True: @@ -1179,6 +1515,10 @@ def get_clients() -> Dict[str, Any]: def get_diff() -> Dict[str, Any]: return report('diff', lambda: diff_report(index.snapshot('results'))) + def get_triage() -> Dict[str, Any]: + # not cached: this is cheap and does not depend on the index + return {'generated': datetime.datetime.now().isoformat(sep=' ', timespec='seconds'), **triage_report(triage.results())} + def get_summary(kind: str) -> Dict[str, Any]: ids_key = 'head_ids' if kind == 'results' else 'info_ids' return report(('summary', kind), lambda: summary_report(index.snapshot(kind), ids_key)) @@ -1289,6 +1629,37 @@ def api_upload_nodata(body: NoDataRequest) -> Dict[str, Any]: logger.info('nodata: %s', body.url) return {'url': body.url} + @app.post('/api/v1/triage', tags=['triage'], openapi_extra={ + 'requestBody': {'required': True, 'content': {'application/json': {'schema': { + 'type': 'array', 'items': TriageResult.model_json_schema()}}}}}) + async def api_upload_triage(request: Request) -> Dict[str, int]: + """Upload triage results. They are merged into the existing triage results. + + 'url' is the package url and 'warning' is the warning line(s) as shown in the diff/head + reports. Notes are ignored. 'verdict' should start with '[Intentional|Unintentional ;] True positive' or + '... False positive', other verdicts are stored but not included in the ratios. + Results with an unknown package url or without a warning with a message id are skipped.""" + data, truncated = await _read_body(request, MAX_TRIAGE_SIZE, 'utf-8') + if truncated: + raise HTTPException(status_code=413, detail='data is too large (max {} bytes)'.format(MAX_TRIAGE_SIZE)) + try: + results = triage_adapter.validate_json(data) + except ValidationError as e: + raise HTTPException(status_code=422, detail=e.errors(include_url=False, include_context=False, include_input=False)) from None + stats = await run_in_threadpool(triage.merge, [r.model_dump() for r in results], packages.contains) + logger.info('triage results uploaded: %s', stats) + return stats + + @app.get('/api/v1/triage/suggestions', tags=['triage']) + def api_triage_suggestions() -> Dict[str, Any]: + """Randomly selected warnings that should be triaged, at most 5 per message id. + + Warnings in the diff are preferred ('section' is 'diff'), if there are not enough then warnings + in the head results are selected ('section' is 'head'). Debug and information messages, and + warnings that have a triage result, are not included. The list is generated once per day. To + upload the triage results, add a 'verdict' to the items and post them to /api/v1/triage.""" + return suggestions.get() + # ========================================================================================= # REST API: data and reports # ========================================================================================= @@ -1358,6 +1729,10 @@ def api_report_clients() -> Dict[str, Any]: def api_report_diff() -> Dict[str, Any]: return get_diff() + @app.get('/api/v1/reports/triage', tags=['reports']) + def api_report_triage() -> Dict[str, Any]: + return get_triage() + @app.get('/api/v1/reports/head', tags=['reports']) def api_report_head() -> Dict[str, Any]: return get_summary('results') @@ -1488,6 +1863,25 @@ def html_diff(): return render('tables.html', 'Diff report', data, [('JSON', '/api/v1/reports/diff')], sections=counts_sections(data, 'diff', True)) + @app.get('/triage.html', response_class=HTMLResponse, include_in_schema=False) + def html_triage(): + data = get_triage() + + def cells(item: Dict[str, Any]) -> List[Any]: + ratios = [num('' if item[key] is None else '{:.0%}'.format(item[key])) for key in ('tp_ratio', 'fp_ratio')] + return [num(item['tp']), num(item['fp'])] + ratios + [num(item['other'])] + + sections = [] + for key, heading, href in (('head', 'Warnings in head', '/head-'), + ('old', 'Lost warnings (only reported by {})'.format(OLD_VERSION), '/diff-')): + part = data[key] + rows = [[link(mid, href + urllib.parse.quote(mid))] + cells(item) for mid, item in part['message_ids'].items()] + sections.append({'heading': heading, + 'columns': ['Message id', num('TP'), num('FP'), num('TP %'), num('FP %'), num('Other')], + 'rows': rows, 'footer': ['Total'] + cells(part['total'])}) + sections[0]['note'] = 'The ratios are calculated from the TP and FP verdicts. Other verdicts (rephrased, not verified, ...) are not included.' + return render('tables.html', 'Triage report', data, [('JSON', '/api/v1/reports/triage')], sections=sections) + @app.get('/head.html', response_class=HTMLResponse, include_in_schema=False) def html_head(): data = get_summary('results')