~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
ci: preserve CodeQL evidence within upload limits (#8214)
LearningCircuitd79745ace6e5
diff --git a/.github/scripts/prepare_codeql_sarif.py b/.github/scripts/prepare_codeql_sarif.pynew file mode 100644index 0000000000..effeeddb71--- /dev/null+++ b/.github/scripts/prepare_codeql_sarif.py@@ -0,0 +1,406 @@+"""Fit optional CodeQL location metadata to GitHub's display limit.++Keep native result grouping, identities, and dataflow paths. Remove unused+overflow metadata; linked overflow locations use commit-pinned source links.+Preserve reports whose links cannot safely be converted. PR and diff-informed+reports retain every location used by diff filtering.+"""++import argparse+import copy+import json+import re+from string import Formatter+from pathlib import Path+from urllib.parse import quote, unquote, urlsplit+++RELATED_LOCATION_LIMIT = 100+LOCATION_LINK = re.compile(r"\]\(\s*([0-9]+)(?:\s+[\"'][^\n]*?[\"'])?\s*\)")+++def _reject_constant(name: str) -> None:+ raise ValueError(f"non-standard JSON constant {name} in report")+++def _message_templates(run: dict) -> dict[str, set[str]]:+ templates = {}+ pending = [run.get("tool", {})]+ while pending:+ value = pending.pop()+ if isinstance(value, list):+ pending.extend(value)+ elif isinstance(value, dict):+ for key in ("messageStrings", "globalMessageStrings"):+ table = value.get(key, {})+ if not isinstance(table, dict):+ continue+ for identifier, message in table.items():+ if isinstance(message, dict):+ templates.setdefault(identifier, set()).update(+ message[field]+ for field in ("text", "markdown")+ if isinstance(message.get(field), str)+ )+ pending.extend(value.values())+ return templates+++def _render_message(template: str, arguments: list[str]) -> str | None:+ if not arguments:+ return template+ parts = []+ try:+ for literal, field, format_spec, conversion in Formatter().parse(+ template+ ):+ parts.append(literal)+ if field is not None:+ if (+ not re.fullmatch(r"[0-9]+", field)+ or format_spec+ or conversion+ or int(field) >= len(arguments)+ ):+ return None+ parts.append(arguments[int(field)])+ except ValueError:+ return None+ return "".join(parts)+++def _referenced_locations(+ result: dict, templates: dict[str, set[str]]+) -> set[int] | None:+ pending = [result]+ referenced = set()+ while pending:+ value = pending.pop()+ if isinstance(value, list):+ pending.extend(value)+ continue+ if not isinstance(value, dict):+ continue+ if any(+ key in value+ for key in ("relationships", "graphs", "graphTraversals")+ ):+ print("Preserving native locations: relationships or graphs")+ return None+ if "message" in value:+ message = value["message"]+ if not isinstance(message, dict):+ return None+ candidates = []+ if isinstance(message.get("text"), str):+ candidates.append(message["text"])+ else:+ candidates.extend(templates.get(message.get("id"), ()))+ if not candidates:+ print(+ "Preserving native locations: unresolved message template"+ )+ return None+ if "markdown" in message:+ if not isinstance(message["markdown"], str):+ raise ValueError("invalid Markdown message")+ # Reference-style Markdown links need a different resolver.+ if re.search(r"(?m)^\s*\[[^\]]+\]:", message["markdown"]):+ print(+ "Preserving native locations: reference-style Markdown"+ )+ return None+ candidates.append(message["markdown"])+ arguments = message.get("arguments", [])+ if not isinstance(arguments, list) or any(+ not isinstance(argument, str) for argument in arguments+ ):+ raise ValueError("invalid message arguments")+ texts = [+ rendered+ for candidate in candidates+ if (rendered := _render_message(candidate, arguments))+ is not None+ ]+ if not texts:+ print(+ "Preserving native locations: unresolved message arguments"+ )+ return None+ texts.extend(arguments)+ if any(r"\](" in text for text in texts):+ print("Preserving native locations: escaped link syntax")+ return None+ referenced.update(+ int(match.group(1))+ for text in texts+ for match in LOCATION_LINK.finditer(text)+ )+ pending.extend(+ child+ for key, child in value.items()+ if key not in ("message", "properties")+ )+ return referenced+++def _source_link(location: dict, source_base_url: str) -> str | None:+ physical = location.get("physicalLocation", {})+ artifact = physical.get("artifactLocation", {})+ uri = artifact.get("uri")+ if not isinstance(uri, str):+ return None+ parsed = urlsplit(uri)+ path = unquote(parsed.path)+ if (+ parsed.scheme+ or parsed.netloc+ or parsed.query+ or parsed.fragment+ or artifact.get("uriBaseId") not in (None, "%SRCROOT%")+ or any(part in ("", ".", "..") for part in path.split("/"))+ or "\\" in path+ or any(ord(character) < 32 for character in path)+ ):+ return None+ region = physical.get("region", {})+ start = region.get("startLine")+ end = region.get("endLine", start)+ if (+ not isinstance(start, int)+ or isinstance(start, bool)+ or start < 1+ or not isinstance(end, int)+ or isinstance(end, bool)+ or end < start+ ):+ return None+ anchor = f"L{start}" if start == end else f"L{start}-L{end}"+ return f"{source_base_url}/{quote(path, safe='/')}#{anchor}"+++def _replace_location_links(result: dict, links: dict[int, str]) -> None:+ pending = [result]+ while pending:+ value = pending.pop()+ if isinstance(value, list):+ pending.extend(value)+ elif isinstance(value, dict):+ message = value.get("message")+ if isinstance(message, dict):++ def replace(match: re.Match) -> str:+ link = links.get(int(match.group(1)))+ return f"]({link})" if link else match.group(0)++ for field in ("text", "markdown"):+ if isinstance(message.get(field), str):+ message[field] = LOCATION_LINK.sub(+ replace, message[field]+ )+ if "arguments" in message:+ message["arguments"] = [+ LOCATION_LINK.sub(replace, argument)+ for argument in message["arguments"]+ ]+ pending.extend(+ child+ for key, child in value.items()+ if key not in ("message", "properties")+ )+++def _prepare_result(+ result: dict, templates: dict[str, set[str]], source_base_url: str | None+) -> None:+ locations = result.get("relatedLocations", [])+ if not isinstance(locations, list) or any(+ not isinstance(location, dict) for location in locations+ ):+ raise ValueError("invalid related locations")+ if len(locations) <= RELATED_LOCATION_LIMIT:+ return++ referenced = _referenced_locations(result, templates)+ if referenced is None:+ # Preserve reports whose indirect messages or relationships need+ # resolution before any related location can be considered unused.+ return++ seen_ids = set()+ required = set()+ for index, location in enumerate(locations):+ if "id" not in location:+ continue+ identifier = location["id"]+ if (+ not isinstance(identifier, int)+ or isinstance(identifier, bool)+ or identifier < 0+ or identifier in seen_ids+ ):+ raise ValueError("invalid or duplicate related-location ID")+ seen_ids.add(identifier)+ if identifier in referenced:+ required.add(index)++ if len(required) > RELATED_LOCATION_LIMIT:+ if not source_base_url:+ print("Preserving native locations: too many linked locations")+ return+ links = {}+ for index in sorted(required)[RELATED_LOCATION_LIMIT:]:+ location = locations[index]+ link = _source_link(location, source_base_url)+ if link is None:+ print("Preserving native locations: no source permalink")+ return+ links[location["id"]] = link+ candidate = copy.deepcopy(result)+ _replace_location_links(candidate, links)+ remaining = _referenced_locations(candidate, templates)+ if remaining is None or remaining.intersection(links):+ print("Preserving native locations: indirect overflow links")+ return+ result.clear()+ result.update(candidate)+ locations = result["relatedLocations"]+ required = {+ index for index in required if locations[index]["id"] not in links+ }+ retained = set(required)+ for index in range(len(locations)):+ if len(retained) == RELATED_LOCATION_LIMIT:+ break+ retained.add(index)+ result["relatedLocations"] = [+ location+ for index, location in enumerate(locations)+ if index in retained+ ]+++def prepare_report(+ report: object,+ *,+ preserve_locations: bool = False,+ source_base_url: str | None = None,+) -> dict:+ if source_base_url is not None:+ parsed = urlsplit(source_base_url)+ if (+ parsed.scheme != "https"+ or not parsed.netloc+ or parsed.username+ or parsed.password+ or parsed.query+ or parsed.fragment+ or not re.fullmatch(r"/[^/]+/[^/]+/blob/[0-9a-f]{40}", parsed.path)+ ):+ raise ValueError("expected a commit-pinned source base URL")+ if not isinstance(report, dict) or report.get("version") != "2.1.0":+ raise ValueError("expected a SARIF 2.1.0 report")+ runs = report.get("runs")+ if not isinstance(runs, list) or not runs:+ raise ValueError("missing CodeQL runs")+ prepared = copy.deepcopy(report)+ for run in prepared["runs"]:+ if not isinstance(run, dict):+ raise ValueError("invalid CodeQL run")+ tool = run.get("tool")+ driver = tool.get("driver") if isinstance(tool, dict) else None+ if not isinstance(driver, dict) or driver.get("name") not in (+ "CodeQL",+ "CodeQL command-line toolchain",+ ):+ raise ValueError("expected a CodeQL report")+ invocations = run.get("invocations", [])+ if not isinstance(invocations, list) or any(+ not isinstance(invocation, dict)+ or invocation.get("executionSuccessful") is not True+ for invocation in invocations+ ):+ raise ValueError("unsuccessful CodeQL invocation")+ results = run.get("results")+ if not isinstance(results, list) or any(+ not isinstance(result, dict) for result in results+ ):+ raise ValueError("missing or invalid CodeQL results")+ properties = run.get("properties", {})+ diff_informed = (+ isinstance(properties, dict)+ and properties.get("incrementalMode") == "diff-informed"+ )+ if not preserve_locations and not diff_informed:+ templates = _message_templates(run)+ for result in results:+ _prepare_result(result, templates, source_base_url)+ else:+ print("Preserving native locations: PR or diff-informed report")+ return prepared+++def prepare(+ source: Path,+ destination: Path,+ *,+ preserve_locations: bool = False,+ source_base_url: str | None = None,+) -> None:+ if source.resolve() == destination.resolve():+ raise ValueError("preserve the native CodeQL report")+ report = json.loads(+ source.read_text(encoding="utf-8"), parse_constant=_reject_constant+ )+ prepared = prepare_report(+ report,+ preserve_locations=preserve_locations,+ source_base_url=source_base_url,+ )+ destination.write_text(+ json.dumps(prepared, separators=(",", ":")) + "\n", encoding="utf-8"+ )+ before = sum(+ len(result.get("relatedLocations", []))+ for run in report["runs"]+ for result in run["results"]+ )+ after = sum(+ len(result.get("relatedLocations", []))+ for run in prepared["runs"]+ for result in run["results"]+ )+ print(f"CodeQL location metadata: {before} native, {after} prepared")+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("source", type=Path)+ parser.add_argument("destination", type=Path)+ parser.add_argument(+ "--preserve-locations",+ action="store_true",+ help="Preserve every location used by PR diff filtering",+ )+ parser.add_argument(+ "--source-base-url",+ help="Commit-pinned repository URL for overflow source links",+ )+ args = parser.parse_args()+ if args.source.resolve() == args.destination.resolve():+ parser.error("preserve the native CodeQL directory")+ reports = sorted(args.source.glob("*.sarif"))+ if not reports:+ parser.error("no native CodeQL reports found")+ args.destination.mkdir(parents=True, exist_ok=True)+ for report in reports:+ prepare(+ report,+ args.destination / report.name,+ preserve_locations=args.preserve_locations,+ source_base_url=args.source_base_url,+ )+++if __name__ == "__main__":+ main()diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.ymlindex bbb9b0ce54..18ccb00417 100644--- a/.github/workflows/codeql.yml+++ b/.github/workflows/codeql.yml@@ -72,6 +72,9 @@ jobs:with:persist-credentials: false+ - name: Test CodeQL report preparation+ run: python3 -m unittest discover -s tests/ci/standalone -p 'test_codeql_sarif.py' -v+# Add any setup steps before running the `github/codeql-action/init` action.# This includes steps like installing compilers or runtimes (`actions/setup-node`# or others). This is typically only required for manual builds.@@ -112,3 +115,24 @@ jobs:uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1with:category: "/language:${{matrix.language}}"+ upload: failure-only+ output: codeql-native++ - name: Prepare GitHub location metadata+ run: |+ report_args=()+ # PR diff filtering considers every related location, even those+ # not linked in the message. Keep its complete native input.+ if [ "$GITHUB_EVENT_NAME" = pull_request ]; then+ report_args+=(--preserve-locations)+ fi+ python3 .github/scripts/prepare_codeql_sarif.py codeql-native codeql-github \+ --source-base-url "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/blob/$GITHUB_SHA" \+ "${report_args[@]}"++ - name: Upload CodeQL results+ uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1+ with:+ sarif_file: codeql-github+ category: "/language:${{matrix.language}}"+ wait-for-processing: truediff --git a/tests/ci/standalone/test_codeql_sarif.py b/tests/ci/standalone/test_codeql_sarif.pynew file mode 100644index 0000000000..70a8ea0887--- /dev/null+++ b/tests/ci/standalone/test_codeql_sarif.py@@ -0,0 +1,497 @@+"""Preserve native CodeQL evidence while fitting optional location metadata.++# allow: no-sut-import — exercises the actual CI report adapter directly.+"""++import copy+import importlib.util+import json+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+++ROOT = Path(__file__).resolve().parents[3]+SCRIPT = ROOT / ".github/scripts/prepare_codeql_sarif.py"+SPEC = importlib.util.spec_from_file_location("prepare_codeql", SCRIPT)+PREPARE = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(PREPARE)+SOURCE_BASE = "https://example.test/example/project/blob/" + "a" * 40+++def sample_report(count=283):+ def link(label, identifier):+ return f"[{label}]({min(identifier, count)})" if count else label++ return {+ "version": "2.1.0",+ "runs": [+ {+ "tool": {+ "driver": {"name": "CodeQL", "rules": [{"id": "sample"}]}+ },+ "invocations": [{"executionSuccessful": True}],+ "results": [+ {+ "ruleId": "sample",+ "level": "warning",+ "message": {+ "text": f"Synthetic {link('first', 280)} and {link('second', 279)}.",+ "markdown": f"Synthetic {link('third', 281)}.",+ "arguments": [link("argument", 282)],+ },+ "locations": [+ {+ "physicalLocation": {+ "artifactLocation": {+ "uri": "src/example.py"+ },+ "region": {"startLine": 1},+ }+ }+ ],+ "partialFingerprints": {+ "primaryLocationLineHash": "sample:1"+ },+ "correlationGuid": "00000000-0000-4000-8000-000000000001",+ "properties": {"sample": "metadata"},+ "codeFlows": [+ {+ "threadFlows": [+ {+ "locations": [+ {+ "location": {+ "message": {+ "text": f"Flow {link('link', 283)}."+ },+ "physicalLocation": {+ "artifactLocation": {+ "uri": "src/example.py"+ },+ "region": {+ "startLine": 1+ },+ },+ }+ }+ ]+ }+ ]+ }+ ],+ "relatedLocations": [+ {+ "id": index,+ "physicalLocation": {+ "artifactLocation": {+ "uri": "src/example.py"+ },+ "region": {"startLine": index},+ },+ }+ for index in range(1, count + 1)+ ],+ }+ ],+ }+ ],+ }+++class CodeQLSarifTests(unittest.TestCase):+ def test_escaped_link_syntax_keeps_native_evidence(self):+ report = sample_report()+ report["runs"][0]["results"][0]["message"] = {+ "text": r"Literal source array\[0\](280)."+ }+ self.assertEqual(+ PREPARE.prepare_report(report, source_base_url=SOURCE_BASE), report+ )++ def test_linked_overflow_uses_source_permalinks_without_new_findings(self):+ report = sample_report()+ result = report["runs"][0]["results"][0]+ result["message"] = {+ "text": " ".join(+ f"[source {index}]({index})" for index in range(1, 284)+ ),+ "markdown": "See [source](280).",+ }+ original = copy.deepcopy(report)+ prepared = PREPARE.prepare_report(report, source_base_url=SOURCE_BASE)+ actual = prepared["runs"][0]["results"][0]+ self.assertEqual(len(actual["relatedLocations"]), 100)+ expected_text = " ".join(+ f"[source {index}]({index})"+ if index <= 100+ else f"[source {index}]({SOURCE_BASE}/src/example.py#L{index})"+ for index in range(1, 284)+ )+ self.assertEqual(actual["message"]["text"], expected_text)+ self.assertEqual(+ actual["message"]["markdown"],+ f"See [source]({SOURCE_BASE}/src/example.py#L280).",+ )+ self.assertEqual(len(prepared["runs"][0]["results"]), 1)+ for field in (+ "ruleId",+ "locations",+ "partialFingerprints",+ "correlationGuid",+ ):+ self.assertEqual(actual[field], result[field])+ flow_location = actual["codeFlows"][0]["threadFlows"][0]["locations"][+ 0+ ]["location"]+ self.assertEqual(+ flow_location["physicalLocation"],+ result["codeFlows"][0]["threadFlows"][0]["locations"][0][+ "location"+ ]["physicalLocation"],+ )+ self.assertEqual(+ flow_location["message"]["text"],+ f"Flow [link]({SOURCE_BASE}/src/example.py#L283).",+ )+ self.assertEqual(report, original)++ def test_source_permalinks_escape_paths_and_preserve_line_ranges(self):+ location = {+ "physicalLocation": {+ "artifactLocation": {+ "uri": "src/example%20%28%23%29.py",+ "uriBaseId": "%SRCROOT%",+ },+ "region": {"startLine": 10, "endLine": 12},+ }+ }+ self.assertEqual(+ PREPARE._source_link(location, SOURCE_BASE),+ f"{SOURCE_BASE}/src/example%20%28%23%29.py#L10-L12",+ )++ def test_unresolvable_overflow_source_locations_keep_the_native_report(+ self,+ ):+ mutations = (+ lambda loc: loc["physicalLocation"]["artifactLocation"].update(+ uri="../outside.py"+ ),+ lambda loc: loc["physicalLocation"]["artifactLocation"].update(+ uri="%2e%2e/outside.py"+ ),+ lambda loc: loc["physicalLocation"]["artifactLocation"].update(+ uri="file:///outside.py"+ ),+ lambda loc: loc["physicalLocation"]["artifactLocation"].update(+ uriBaseId="external"+ ),+ lambda loc: loc["physicalLocation"].update(region={}),+ )+ for mutate in mutations:+ with self.subTest(mutation=mutate):+ report = sample_report(150)+ result = report["runs"][0]["results"][0]+ result["message"] = {+ "text": " ".join(+ f"[source]({index})" for index in range(1, 151)+ )+ }+ mutate(result["relatedLocations"][149])+ self.assertEqual(+ PREPARE.prepare_report(report, source_base_url=SOURCE_BASE),+ report,+ )++ def test_indirect_overflow_links_are_preserved_without_rewriting_shared_templates(+ self,+ ):+ report = sample_report(150)+ run = report["runs"][0]+ run["tool"]["driver"]["globalMessageStrings"] = {+ "shared": {+ "text": " ".join(+ f"[source]({index})" for index in range(1, 151)+ )+ }+ }+ run["results"][0]["message"] = {"id": "shared"}+ self.assertEqual(+ PREPARE.prepare_report(report, source_base_url=SOURCE_BASE), report+ )++ def test_pr_and_diff_informed_reports_do_not_convert_overflow_links(self):+ report = sample_report(150)+ report["runs"][0]["results"][0]["message"] = {+ "text": " ".join(f"[source]({index})" for index in range(1, 151))+ }+ self.assertEqual(+ PREPARE.prepare_report(+ report, preserve_locations=True, source_base_url=SOURCE_BASE+ ),+ report,+ )+ report["runs"][0]["properties"] = {"incrementalMode": "diff-informed"}+ self.assertEqual(+ PREPARE.prepare_report(report, source_base_url=SOURCE_BASE), report+ )++ def test_source_base_must_be_a_commit_pinned_https_repository_url(self):+ invalid = (+ "https://example.test/example/project/blob/main",+ "http://example.test/example/project/blob/" + "a" * 40,+ SOURCE_BASE + "?query=example",+ SOURCE_BASE + "#fragment",+ SOURCE_BASE.replace("example.test", "[email protected]"),+ )+ for source_base in invalid:+ with self.subTest(source_base=source_base):+ with self.assertRaises(ValueError):+ PREPARE.prepare_report(+ sample_report(), source_base_url=source_base+ )++ def test_pr_preparation_preserves_all_locations_for_diff_filtering(self):+ report = sample_report()+ self.assertEqual(+ PREPARE.prepare_report(report, preserve_locations=True), report+ )++ def test_diff_informed_reports_keep_all_locations_without_a_caller_flag(+ self,+ ):+ report = sample_report()+ report["runs"][0]["properties"] = {"incrementalMode": "diff-informed"}+ self.assertEqual(PREPARE.prepare_report(report), report)++ def test_literal_braces_without_message_arguments_do_not_hide_links(self):+ report = sample_report()+ report["runs"][0]["results"][0]["message"] = {+ "text": "Literal {value} and [source](280)."+ }+ prepared = PREPARE.prepare_report(report)+ locations = prepared["runs"][0]["results"][0]["relatedLocations"]+ self.assertEqual(len(locations), 100)+ self.assertTrue(+ {280, 283}.issubset({location["id"] for location in locations})+ )++ def test_native_message_ids_and_formatted_arguments_keep_their_links(self):+ report = sample_report()+ run = report["runs"][0]+ run["tool"]["driver"]["globalMessageStrings"] = {+ "primary": {"text": "Synthetic [first]({0}) and {1}."},+ "flow": {"text": "Flow {0}."},+ "source": {"text": "Source location."},+ }+ result = run["results"][0]+ result["message"] = {+ "id": "primary",+ "arguments": ["280", "[second](279)"],+ }+ result["codeFlows"][0]["threadFlows"][0]["locations"][0]["location"][+ "message"+ ] = {"id": "flow", "arguments": ["[link](283)"]}+ for location in result["relatedLocations"]:+ location["message"] = {"id": "source"}+ original = copy.deepcopy(report)+ prepared = PREPARE.prepare_report(report)+ actual = prepared["runs"][0]["results"][0]+ self.assertEqual(len(actual["relatedLocations"]), 100)+ self.assertTrue(+ {279, 280, 283}.issubset(+ {loc["id"] for loc in actual["relatedLocations"]}+ )+ )+ self.assertEqual(actual["message"], result["message"])+ self.assertEqual(actual["codeFlows"], result["codeFlows"])+ self.assertEqual(+ actual["partialFingerprints"], result["partialFingerprints"]+ )+ self.assertEqual(report, original)++ def test_ambiguous_rule_message_ids_conservatively_keep_all_referenced_locations(+ self,+ ):+ report = sample_report()+ run = report["runs"][0]+ run["tool"]["driver"]["rules"] = [+ {"id": "one", "messageStrings": {"shared": {"text": "[one](200)"}}},+ {"id": "two", "messageStrings": {"shared": {"text": "[two](201)"}}},+ ]+ run["results"][0]["message"] = {"id": "shared"}+ prepared = PREPARE.prepare_report(report)+ locations = prepared["runs"][0]["results"][0]["relatedLocations"]+ self.assertEqual(len(locations), 100)+ self.assertTrue(+ {200, 201, 283}.issubset({location["id"] for location in locations})+ )++ def test_overflow_keeps_links_identities_findings_and_flow_data(self):+ report = sample_report()+ original = copy.deepcopy(report)+ prepared = PREPARE.prepare_report(report)+ result = prepared["runs"][0]["results"][0]+ retained = {location["id"] for location in result["relatedLocations"]}+ self.assertEqual(retained, set(range(1, 96)) | set(range(279, 284)))+ expected = copy.deepcopy(original)+ expected["runs"][0]["results"][0]["relatedLocations"] = [+ location+ for location in original["runs"][0]["results"][0][+ "relatedLocations"+ ]+ if location["id"] in retained+ ]+ self.assertEqual(prepared, expected)+ self.assertEqual(report, original)++ def test_valid_reports_below_the_limit_are_unchanged(self):+ for count in (0, 20, 100):+ with self.subTest(count=count):+ report = sample_report(count)+ report["runs"][0]["results"][0]["message"] = {+ "text": "Synthetic result."+ }+ self.assertEqual(PREPARE.prepare_report(report), report)++ def test_more_than_one_hundred_referenced_locations_are_not_removed(self):+ report = sample_report(150)+ report["runs"][0]["results"][0]["message"] = {+ "text": " ".join(f"[location]({index})" for index in range(1, 102))+ }+ self.assertEqual(PREPARE.prepare_report(report), report)++ def test_indirect_messages_relationships_and_markdown_references_are_preserved(+ self,+ ):+ mutations = (+ lambda result: result.update(message={"id": "sample-message"}),+ lambda result: result["relatedLocations"][0].update(+ relationships=[{"target": 200, "kinds": ["relevant"]}]+ ),+ lambda result: result["message"].update(+ markdown="[link][ref]\n[ref]: 200"+ ),+ )+ for mutate in mutations:+ with self.subTest(mutation=mutate):+ report = sample_report()+ mutate(report["runs"][0]["results"][0])+ self.assertEqual(PREPARE.prepare_report(report), report)++ def test_multiple_runs_and_results_are_preserved(self):+ report = sample_report()+ report["runs"].append(copy.deepcopy(report["runs"][0]))+ report["runs"][1]["results"].append(+ {"ruleId": "other", "message": {"text": "Other."}}+ )+ prepared = PREPARE.prepare_report(report)+ self.assertEqual(len(prepared["runs"]), 2)+ self.assertEqual(+ [len(run["results"]) for run in prepared["runs"]], [1, 2]+ )+ self.assertEqual(+ prepared["runs"][1]["results"][1], report["runs"][1]["results"][1]+ )++ def test_invalid_or_unsuccessful_native_reports_are_rejected(self):+ mutations = (+ lambda r: r.update(version="1.0.0"),+ lambda r: r.update(runs=[]),+ lambda r: r["runs"][0].update(tool="invalid"),+ lambda r: r["runs"][0]["tool"]["driver"].update(name="other"),+ lambda r: r["runs"][0].pop("results"),+ lambda r: r["runs"][0].update(results=None),+ lambda r: r["runs"][0].update(results=[None]),+ lambda r: r["runs"][0].update(+ invocations=[{"executionSuccessful": False}]+ ),+ lambda r: r["runs"][0].update(invocations=[{}]),+ lambda r: r["runs"][0]["results"][0].update(+ relatedLocations=[None] * 101+ ),+ lambda r: r["runs"][0]["results"][0]["relatedLocations"][1].update(+ id=1+ ),+ lambda r: r["runs"][0]["results"][0]["relatedLocations"][1].update(+ id=True+ ),+ )+ for mutate in mutations:+ with self.subTest(mutation=mutate):+ report = sample_report()+ mutate(report)+ with self.assertRaises(ValueError):+ PREPARE.prepare_report(report)++ def test_preparation_preserves_native_bytes_and_rejects_in_place_writes(+ self,+ ):+ with tempfile.TemporaryDirectory() as temporary:+ source = Path(temporary) / "native.sarif"+ destination = Path(temporary) / "upload.sarif"+ raw = json.dumps(sample_report())+ source.write_text(raw, encoding="utf-8")+ PREPARE.prepare(source, destination)+ self.assertEqual(source.read_text(encoding="utf-8"), raw)+ self.assertEqual(+ len(+ json.loads(destination.read_text(encoding="utf-8"))["runs"][+ 0+ ]["results"][0]["relatedLocations"]+ ),+ 100,+ )+ with self.assertRaises(ValueError):+ PREPARE.prepare(source, source)++ def test_cli_handles_the_native_output_directory(self):+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ source, destination = root / "native", root / "upload"+ source.mkdir()+ raw = json.dumps(sample_report())+ (source / "python.sarif").write_text(raw, encoding="utf-8")+ result = subprocess.run(+ [sys.executable, str(SCRIPT), str(source), str(destination)],+ capture_output=True,+ text=True,+ check=False,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertEqual(+ (source / "python.sarif").read_text(encoding="utf-8"), raw+ )+ prepared = json.loads(+ (destination / "python.sarif").read_text(encoding="utf-8")+ )+ self.assertEqual(+ len(prepared["runs"][0]["results"][0]["relatedLocations"]), 100+ )++ def test_nonstandard_json_and_missing_input_never_create_an_upload(self):+ with tempfile.TemporaryDirectory() as temporary:+ source, destination = (+ Path(temporary) / "native.sarif",+ Path(temporary) / "upload.sarif",+ )+ with self.assertRaises(FileNotFoundError):+ PREPARE.prepare(source, destination)+ for raw in (+ "{truncated",+ json.dumps(sample_report()).replace(+ '"version": "2.1.0"', '"version": NaN'+ ),+ ):+ with self.subTest(raw=raw[:20]):+ source.write_text(raw, encoding="utf-8")+ with self.assertRaises(ValueError):+ PREPARE.prepare(source, destination)+ self.assertFalse(destination.exists())+++if __name__ == "__main__":+ unittest.main()