diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc905cb1bc..3205f24578 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,6 +33,9 @@ jobs: steps: - uses: actions/checkout@v4 + - name: D3D12.X triage regressions (synthetic reports and logs) + run: python -B -m unittest discover -s scripts -p test_triage_d3d12.py -v + - name: Rust (stable, MSVC) run: | rustup toolchain install stable --profile minimal diff --git a/README.md b/README.md index 722483312f..f121e5f708 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,12 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder those on which the GPU completed at least one operation. - Every run writes `report.json` (called stubs, unknown D3D12.X slots and interfaces, XGameRuntime classes asked for, shader statistics, audio formats, crash). + For unknown slots/IIDs, run `python scripts/triage_d3d12.py --log ` + using files from the same run (`--json` for machine-readable output). It also recovers + first-call evidence from the log if the report is missing or truncated. See + [D3D12.X triage](docs/d3d12-triage.md) for limits and synthetic tests. + Add `--baseline --fail-on-new` to flag newly observed + slot/IID identities; incomplete evidence returns an error instead of a clean verdict. `d3d12.presents` counts presentations, not visible content. With `XCL_FRAME_DUMP=N` (`N > 1`), the existing optional frame dumps also set `d3d12.last_frame_dump`: the latest sampled frame's zero-based index, source dimensions, DXGI format, sample step, sample count and `non_dark_samples` diff --git a/docs/d3d12-triage.md b/docs/d3d12-triage.md new file mode 100644 index 0000000000..aac7c0f593 --- /dev/null +++ b/docs/d3d12-triage.md @@ -0,0 +1,122 @@ +# D3D12.X crash-report triage + +## Design + +Chosen blocker: **6, crash-report triage for unknown D3D12.X slots/interfaces**. +The runtime already records called slot stubs in `report.json.called_stubs` and +unknown QueryInterface GUIDs in `d3d12.unknown_iids`. `stubs::record_call` logs the +first call, including its caller. Queue stubs include the older/newer layout in +their name. Today these observations must be extracted manually, and a missing +or truncated final JSON report makes its evidence harder to recover. + +This is the highest-leverage bounded increment available without proprietary +data: it covers every title's unknown interface paths, needs no GPU assumptions, +and can be tested in CI. Wave64 and mesh already have substantial synthetic +coverage; full MSAA conversion requires broader layout and upload work. Runtime +report-persistence work is already proposed in upstream PR #240; this tool is +independent of it. + +Add a dependency-free Python CLI that reads an existing report and optionally its +matching log. Group slot observations by DLL, interface, slot and layout suffix; +preserve distinct callers and source provenance. Unknown IIDs remain separate +observations: their appearance does not establish which interface or slot failed. +Use report counts when available; log first-call lines are evidence, not extra +calls. Sort output deterministically and support JSON for automated comparisons. + +If the report cannot be read or decoded, warn and use the explicitly supplied +log. Reject an invocation with no usable input. Warn about malformed relevant +records rather than treating them as a clean run. Do not infer method signatures, +return values, crash causality or gameplay success. Never change runtime dispatch +or pretend an unknown slot succeeded. No executable, shader or game asset is read. + +Expected impact: better preservation and grouping of unknown-slot evidence +reduces diagnosis time and the chance that a recurring boot blocker is overlooked. +It does not itself make an unsupported method execute. Synthetic tests will cover +both slot spellings, duplicate report/log evidence, IID normalization, deterministic +output and damaged-report fallback. Retail progression and future title-specific +interfaces remain unvalidated; a report can identify a candidate, not prove that +implementing it reaches gameplay. + +## Reproduce and test + +### Baseline comparison design (follow-up) + +Compare exact slot identities (DLL, interface, number, variant) and canonical +IIDs against an explicitly supplied raw report. Preserve all current evidence; +report only newly observed identities. Count/caller changes and disappearance +of an observation say nothing about a newly missing or newly supported method. +Reject incomplete baselines. An opt-in CI gate returns 2 for incomplete current +evidence, 1 for new observations, and 0 otherwise. The caller must select +comparable title/version/backend runs; this is an evidence comparison, not proof +of a regression or matching run identity. Keep this increment separate from the +initial triage PR, with synthetic tests and no runtime changes. + +From the repository root, with Python 3 (standard library only): + +```powershell +python scripts/triage_d3d12.py path\report.json --log path\xcl.log +python scripts/triage_d3d12.py path\report.json --log path\xcl.log --json +python -B -m unittest discover -s scripts -p test_triage_d3d12.py -v +.\scripts\test.ps1 +``` + +Use the report and log from **one run**; the tool cannot establish their identity. +`--log` is optional. Supply it explicitly to recover evidence when the report +path is missing or its JSON is damaged. Input files are read only; nothing is +uploaded. Output includes caller module names/offsets: review before sharing. + +JSON schema version 1 has `slots`, `unknown_iids` and `warnings`. Slot `calls` +sums counts from report records, which may be an earlier snapshot; `null` means +log-only evidence with no known total. `first_callers` and `sources` are deduplicated. +`variant` preserves bare/null-backend, `not on PC`, older/newer layout and future +suffixes independently. Ordinary named stubs and other DLLs are excluded. IIDs +have no inferred call count, caller or slot association. Warnings also go to +stderr. Exit 0 means inputs were processed (even with warnings/findings), 2 means +no usable input or invalid CLI arguments. An empty result never proves support. + +For a comparable earlier raw `report.json`, add `--baseline baseline.json`. +The optional `comparison` object lists `new_slots` and `new_iids` while keeping +all current evidence. `complete` means no recognized input/parser warnings; +it does not establish that either report is final or all title paths ran. +Disappeared observations are not called fixed. A malformed/incomplete baseline +produces exit 2 and a warning, retaining current evidence without a comparison. + +```powershell +python scripts/triage_d3d12.py current.json --baseline baseline.json --json --fail-on-new +``` + +`--fail-on-new` requires `--baseline`. Its exit codes are 0 for no new identities, +1 for newly observed identities, and 2 for incomplete evidence or input errors. +Incomplete evidence takes precedence even if new identities were found. Without +the gate, a valid comparison returns 0 regardless of findings. Choose comparable +title versions, workloads, backends and adapters: different host interface +versions can change slot identities, and the tool cannot verify provenance. + +## Validation and limits + +On base `508a0c7` plus this scripts/docs/CI change: Windows 11 Home build 26300, +i9-14900K, RTX 4080 SUPER driver 32.0.16.2114, Rust 1.93.0, DXC 1.9.2609.5, +Python 3.13, debug build. No runtime source changed. + +- New regression command above: **15 passed, 0 failed, 0 skipped**. Before the + implementation, discovery failed because the triage module did not exist. +- Existing `scripts/test.ps1`: **680 passed, 0 failed, 41 ignored**. Within the + passing count, two native-wave64 cases and two missing-debug-layer cases skipped; + 32 sample-gated tests returned without data (guard count, not an emitted total). + All `XCL_SAMPLE_*` were unset. The synthetic console-title e2e test ran and passed. +- Streaming 100,000 identical synthetic first-call lines: **0.164 s**, one unique + slot, unknown call total; 325-byte compact JSON. This is a local microbenchmark, + not a runtime or gameplay speedup. + +Regression coverage includes distinct interfaces/layouts, duplicate guarded +records, report/log overlap, IID normalization, malformed records/logs, stable +ordering, Unicode callers, missing/truncated/non-object reports, missing logs, +deeply nested JSON, and CLI/text-output behavior. Windows CI runs these without a GPU or game files. +The baseline follow-up adds 9 regressions (24 total), including exact identity +matching, count/caller independence, incomplete inputs, evidence retention and +all three gate exit codes. Risks: logger/schema drift may lose evidence +(recognized malformed records warn), and mixing runs can merge unrelated +observations. Follow-up: versioned structured runtime events with run identity. +No AMD/Intel GPU or retail run was performed. Future title interfaces, +shader behavior and boot-to-gameplay progression cannot be validated without an +authorized executable; none was requested or used here. diff --git a/scripts/test_triage_d3d12.py b/scripts/test_triage_d3d12.py new file mode 100644 index 0000000000..f1901c6452 --- /dev/null +++ b/scripts/test_triage_d3d12.py @@ -0,0 +1,205 @@ +"""Synthetic report/log regressions; no game files, GPU, or third-party packages.""" +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from triage_d3d12 import analyze, compare, render + + +IID = "12345678-1234-5678-9abc-123456789abc" +LOG = ("[12:34:56 WARN] [STUB] d3d12_xs.dll!ID3D12Device::#200 (not on PC) " + "first called from synthetic.exe+0x10 → returning 0x0") + + +def stub(calls=1, caller="synthetic.exe+0x10", variant="not on PC", dll="d3d12_xs.dll"): + suffix = f" ({variant})" if variant else "" + return dict(dll=dll, function=f"ID3D12Device::#200{suffix}", calls=calls, first_caller=caller) + + +def report(stubs=(), iids=()): + return {"called_stubs": list(stubs), "d3d12": {"unknown_iids": list(iids)}} + + +class TriageTests(unittest.TestCase): + def test_guard_duplicates_sum_report_counts_and_keep_callers(self): + result = analyze({"called_stubs": [stub(2), stub(3, "synthetic.exe+0x20")]}) + self.assertEqual(result["schema_version"], 1) + self.assertEqual(len(result["slots"]), 1) + self.assertEqual(result["slots"][0]["calls"], 5) + self.assertEqual(result["slots"][0]["first_callers"], ["synthetic.exe+0x10", "synthetic.exe+0x20"]) + + def test_log_duplicates_do_not_inflate_report_count(self): + slot = analyze({"called_stubs": [stub(4)]}, [LOG, LOG])["slots"][0] + self.assertEqual(slot["calls"], 4) + self.assertEqual(slot["sources"], ["log", "report"]) + + def test_log_only_has_unknown_count_and_unicode_caller(self): + result = analyze(None, [LOG.replace("synthetic.exe", "合成.exe")]) + self.assertIsNone(result["slots"][0]["calls"]) + self.assertEqual(result["slots"][0]["first_callers"], ["合成.exe+0x10"]) + self.assertTrue(result["warnings"]) + + def test_variants_and_null_backend_are_distinct(self): + rows = [stub(variant=v) for v in ("", "not on PC", "older layout", "newer layout")] + slots = analyze({"called_stubs": rows})["slots"] + self.assertEqual([s["variant"] for s in slots], ["", "newer layout", "not on PC", "older layout"]) + + def test_dll_normalization_and_unrelated_stubs(self): + rows = [stub(dll="D3D12_XS.DLL"), stub(dll="kernelx.dll"), + dict(stub(), function="ID3D12Device::CreateHeap")] + slots = analyze({"called_stubs": rows})["slots"] + self.assertEqual(len(slots), 1) + self.assertEqual(slots[0]["dll"], "d3d12_xs.dll") + + def test_slot_numbers_are_scoped_to_the_interface(self): + rows = [stub(), dict(stub(), function="ID3D12CommandQueue::#200 (not on PC)")] + slots = analyze({"called_stubs": rows})["slots"] + self.assertEqual([s["interface"] for s in slots], ["ID3D12CommandQueue", "ID3D12Device"]) + + def test_bad_count_warns_and_preserves_valid_records(self): + result = analyze({"called_stubs": [stub(-1), stub(True), stub("2"), stub(0), stub(2**64), stub(7)]}) + self.assertTrue(any("call count" in warning for warning in result["warnings"])) + self.assertEqual(result["slots"][0]["calls"], 7) + + def test_iids_normalize_deduplicate_and_merge_sources(self): + log = f"D3D12.X: QueryInterface({IID}) – interface unknown on the PC (console-only?)" + result = analyze({"d3d12": {"unknown_iids": [IID.upper(), IID]}}, [log, log]) + self.assertEqual(result["unknown_iids"], [{"iid": IID, "sources": ["log", "report"]}]) + + def test_missing_optional_fields_and_malformed_entries(self): + self.assertEqual(analyze({})["slots"], []) + result = analyze({"called_stubs": [None, stub()], "d3d12": {"unknown_iids": [None, "invalid", IID]}}) + self.assertEqual(len(result["slots"]), 1) + self.assertEqual(len(result["unknown_iids"]), 1) + self.assertTrue(result["warnings"]) + + def test_input_order_does_not_change_findings(self): + rows = [stub(2, "b.exe+0x20"), stub(3, "a.exe+0x10"), stub(variant="older layout")] + self.assertEqual(analyze({"called_stubs": rows}, [LOG]), + analyze({"called_stubs": rows[::-1]}, [LOG])) + + def test_cli_falls_back_from_missing_truncated_and_non_object_reports(self): + with tempfile.TemporaryDirectory() as directory: + report, log = Path(directory) / "report.json", Path(directory) / "xcl.log" + log.write_text(LOG + "\n", encoding="utf-8") + for content in (None, '{"called_stubs":', "[]", "[" * 10000 + "0" + "]" * 10000): + with self.subTest(content=content): + if content is not None: + report.write_text(content, encoding="utf-8") + proc = self.run_cli(report, "--log", log, "--json") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIsNone(json.loads(proc.stdout)["slots"][0]["calls"]) + self.assertTrue(proc.stderr.strip()) + + def test_cli_missing_inputs_fail_clearly(self): + with tempfile.TemporaryDirectory() as directory: + proc = self.run_cli(Path(directory) / "missing.json", "--log", Path(directory) / "missing.log", "--json") + self.assertEqual(proc.returncode, 2) + self.assertTrue(proc.stderr.strip()) + self.assertNotIn("Traceback", proc.stderr) + + def test_bad_log_lines_warn_without_hiding_valid_evidence(self): + result = analyze(None, [LOG, LOG.split(" first called")[0], + "D3D12.X: QueryInterface(new format) interface unknown", "\ufffd"]) + self.assertEqual(len(result["slots"]), 1) + self.assertEqual(len(result["warnings"]), 4) + + def test_cli_report_survives_missing_optional_log(self): + with tempfile.TemporaryDirectory() as directory: + report = Path(directory) / "report.json" + report.write_text(json.dumps({"called_stubs": [stub(9)], "d3d12": {"unknown_iids": []}}), + encoding="utf-8-sig") + proc = self.run_cli(report, "--log", Path(directory) / "absent.log", "--json") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(json.loads(proc.stdout)["slots"][0]["calls"], 9) + self.assertIn("Cannot use log", proc.stderr) + + def test_text_output_does_not_claim_support_or_causation(self): + self.assertIn("does not establish interface support", render(analyze({}))) + text = render(analyze(None, [LOG])) + self.assertIn("not proven crash causes", text) + self.assertIn("calls=unknown", text) + self.assertIn("first caller:", text) + + def test_comparison_preserves_full_new_slot_and_iid_evidence(self): + current = analyze(report([stub(7)], [IID])) + self.assertEqual(compare(current, analyze(report())), + dict(complete=True, new_slots=current["slots"], new_iids=current["unknown_iids"])) + + def test_comparison_ignores_counts_callers_and_iid_spelling(self): + baseline = analyze(report([stub(2), stub(3)], [IID.upper()])) + current = analyze(report([stub(11, "different.exe+0x90")], ["{" + IID + "}"])) + self.assertEqual(compare(current, baseline), dict(complete=True, new_slots=[], new_iids=[])) + + def test_comparison_keeps_dll_interface_and_layout_identities(self): + rows = [stub(), stub(variant="older layout"), stub(dll="d3d12_x.dll"), + dict(stub(), function="ID3D12CommandQueue::#200 (not on PC)")] + current = analyze(report(rows)) + delta = compare(current, analyze(report([stub()]))) + self.assertEqual(delta["new_slots"], [s for s in current["slots"] + if (s["dll"], s["interface"], s["variant"]) != ("d3d12_xs.dll", "ID3D12Device", "not on PC")]) + + def test_comparison_rejects_incomplete_baseline(self): + for baseline in (analyze({}), analyze(report([stub(-1)])), analyze(report(iids=["invalid"]))): + with self.subTest(baseline=baseline), self.assertRaises(ValueError): + compare(analyze(report()), baseline) + + def test_comparison_marks_log_only_current_incomplete(self): + current = analyze(None, [LOG]) + delta = compare(current, analyze(report())) + self.assertFalse(delta["complete"]) + self.assertEqual(delta["new_slots"], current["slots"]) + + def test_disappearing_observations_are_not_reported_as_fixed(self): + current = analyze(report()) + current["comparison"] = compare(current, analyze(report([stub()], [IID]))) + self.assertEqual(current["comparison"], dict(complete=True, new_slots=[], new_iids=[])) + self.assertNotRegex(render(current).lower(), r"\b(fixed|resolved|supported)\b") + + def test_cli_baseline_gate_codes_and_full_current_output(self): + with tempfile.TemporaryDirectory() as directory: + baseline, path = Path(directory) / "baseline.json", Path(directory) / "current.json" + baseline.write_text(json.dumps(report()), encoding="utf-8") + for data, code in ((report(), 0), (report([stub()], [IID]), 1), ({"called_stubs": [stub()]}, 2)): + with self.subTest(code=code): + path.write_text(json.dumps(data), encoding="utf-8") + proc = self.run_cli(path, "--baseline", baseline, "--fail-on-new", "--json") + self.assertEqual(proc.returncode, code, proc.stderr) + result = json.loads(proc.stdout) + self.assertEqual(result["slots"], analyze(data)["slots"]) + self.assertEqual(result["comparison"]["complete"], code != 2) + self.assertEqual(self.run_cli(path, "--baseline", baseline, "--json").returncode, 0) + + def test_cli_rejects_missing_corrupt_and_incomplete_baselines(self): + with tempfile.TemporaryDirectory() as directory: + baseline, path = Path(directory) / "baseline.json", Path(directory) / "current.json" + path.write_text(json.dumps(report([stub()])), encoding="utf-8") + for content in (None, "{", "[]", "{}", json.dumps(report([stub(-1)]))): + with self.subTest(content=content): + if content is not None: + baseline.write_text(content, encoding="utf-8") + proc = self.run_cli(path, "--baseline", baseline, "--json") + self.assertEqual(proc.returncode, 2) + self.assertIn("baseline", proc.stderr.lower()) + self.assertNotIn("Traceback", proc.stderr) + result = json.loads(proc.stdout) + self.assertEqual(result["slots"][0]["slot"], 200) + self.assertNotIn("comparison", result) + + def test_cli_gate_requires_baseline(self): + proc = self.run_cli("unused.json", "--fail-on-new") + self.assertEqual(proc.returncode, 2) + self.assertIn("baseline", proc.stderr.lower()) + self.assertNotIn("Traceback", proc.stderr) + + @staticmethod + def run_cli(*args): + return subprocess.run([sys.executable, str(Path(__file__).with_name("triage_d3d12.py")), + *map(str, args)], capture_output=True, text=True, encoding="utf-8") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/triage_d3d12.py b/scripts/triage_d3d12.py new file mode 100644 index 0000000000..dd89053f9f --- /dev/null +++ b/scripts/triage_d3d12.py @@ -0,0 +1,209 @@ +"""Summarize observed D3D12.X slot stubs and unknown IIDs, without running a title. + +python scripts/triage_d3d12.py report.json [--log xcl.log] [--json] +Supply files from the same run. First-call log lines never increase report counts. +""" +import argparse +import json +from pathlib import Path +import re +import sys +import uuid + + +DLLS = {"d3d12_xs.dll", "d3d12_x.dll"} +SLOT = re.compile(r"(I[A-Za-z0-9_]+)::#([0-9]{1,10})(?: \(([^()\r\n]+)\))?") +STUB_LOG = re.compile(r"\[STUB\] ([^!\s]+)!(.*?) first called from (.*?) (?:→|->) returning 0x[0-9a-fA-F]+\s*$") +IID_LOG = re.compile(r"D3D12\.X: QueryInterface\(([^)]+)\) (?:–|-) interface unknown on the PC \(console-only\?\)\s*$") + + +def analyze(report, lines=()): + """Return deterministic evidence, not a diagnosis or a compatibility verdict.""" + slots, iids, warnings = {}, {}, set() + + def slot(dll, function, calls, caller, source): + if not isinstance(dll, str): + warnings.add("Invalid called_stubs DLL; evidence may be incomplete.") + return + dll = dll.lower() + if dll not in DLLS: + return + if not isinstance(function, str): + warnings.add("Invalid D3D12.X stub name; evidence may be incomplete.") + return + match = SLOT.fullmatch(function) + if not match: + if "::#" in function: + warnings.add("Unrecognized D3D12.X slot name; evidence may be incomplete.") + return + if source == "report" and (type(calls) is not int or not 0 <= calls <= 2**64 - 1): + warnings.add("Invalid D3D12.X slot call count; evidence may be incomplete.") + return + if source == "report" and calls == 0: + return + if not isinstance(caller, str): + warnings.add("Invalid D3D12.X first caller; retaining slot without caller.") + caller = "" + interface, number, variant = match.groups() + key = (dll, interface, int(number), variant or "") + entry = slots.setdefault(key, dict(dll=dll, interface=interface, slot=int(number), + variant=variant or "", calls=None, first_callers=set(), sources=set())) + if source == "report": + entry["calls"] = (entry["calls"] or 0) + calls + if caller: + entry["first_callers"].add(caller) + entry["sources"].add(source) + + def iid(value, source): + try: + if not isinstance(value, str): + raise ValueError() + canonical = str(uuid.UUID(value)) + except ValueError: + warnings.add("Invalid unknown IID; evidence may be incomplete.") + return + iids.setdefault(canonical, set()).add(source) + + if report is None: + warnings.add("No usable report; only first-call log evidence is available and call totals are unknown.") + else: + if not isinstance(report, dict): + raise ValueError("report must be a JSON object") + records = report.get("called_stubs") + if not isinstance(records, list): + warnings.add("Missing or invalid called_stubs; slot evidence may be incomplete.") + else: + for record in records: + if not isinstance(record, dict): + warnings.add("Invalid called_stubs entry; evidence may be incomplete.") + continue + slot(record.get("dll"), record.get("function"), record.get("calls"), + record.get("first_caller", ""), "report") + d3d12 = report.get("d3d12") + unknown = d3d12.get("unknown_iids") if isinstance(d3d12, dict) else None + if not isinstance(unknown, list): + warnings.add("Missing or invalid d3d12.unknown_iids; IID evidence may be incomplete.") + else: + for value in unknown: + iid(value, "report") + + for line in lines: + if "\ufffd" in line: + warnings.add("Log contains replacement characters; evidence may be incomplete.") + match = STUB_LOG.search(line) + if match: + dll, function, caller = match.groups() + slot(dll, function, None, caller, "log") + elif "[STUB]" in line and any(dll in line.lower() for dll in DLLS) and "::#" in line: + warnings.add("Unrecognized D3D12.X slot log entry; evidence may be incomplete.") + match = IID_LOG.search(line) + if match: + iid(match[1], "log") + elif "D3D12.X: QueryInterface(" in line and "interface unknown" in line: + warnings.add("Unrecognized unknown-IID log entry; evidence may be incomplete.") + + for entry in slots.values(): + entry["sources"] = sorted(entry["sources"]) + entry["first_callers"] = sorted(entry["first_callers"]) + return dict(schema_version=1, slots=[slots[key] for key in sorted(slots)], + unknown_iids=[dict(iid=key, sources=sorted(iids[key])) for key in sorted(iids)], + warnings=sorted(warnings)) + + +def render(result): + out = ["D3D12.X observations (not proven crash causes)"] + for entry in result["slots"]: + count = str(entry["calls"]) if entry["calls"] is not None else "unknown" + variant = f" ({entry['variant']})" if entry["variant"] else "" + out.append(f"{entry['dll']}!{entry['interface']}::#{entry['slot']}{variant}: " + f"calls={count}; sources={','.join(entry['sources'])}") + out.extend(f" first caller: {json.dumps(caller, ensure_ascii=True)}" for caller in entry["first_callers"]) + out.extend(f"unknown IID {entry['iid']}; sources={','.join(entry['sources'])}" + for entry in result["unknown_iids"]) + if not result["slots"] and not result["unknown_iids"]: + out.append("No matching observations found; this does not establish interface support.") + if "comparison" in result: + comparison = result["comparison"] + out.append(f"Newly observed against baseline: {len(comparison['new_slots'])} slots, " + f"{len(comparison['new_iids'])} IIDs; evidence complete={comparison['complete']}") + for entry in comparison["new_slots"]: + out.append(f" new slot: {entry['dll']}!{entry['interface']}::#{entry['slot']} " + f"{json.dumps(entry['variant'], ensure_ascii=True)}") + out.extend(f" new IID: {entry['iid']}" for entry in comparison["new_iids"]) + out.append("Next: verify the caller and console layout before implementing a slot; IIDs may be optional probes.") + return "\n".join(out) + + +def compare(current, baseline): + """Compare observed identities only; missing observations do not imply a fix.""" + if baseline["warnings"]: + raise ValueError("baseline has incomplete evidence: " + "; ".join(baseline["warnings"])) + def key(entry): + return (entry["dll"], entry["interface"], entry["slot"], entry["variant"]) + slots = {key(entry) for entry in baseline["slots"]} + iids = {entry["iid"] for entry in baseline["unknown_iids"]} + return dict(complete=not current["warnings"], + new_slots=[entry for entry in current["slots"] if key(entry) not in slots], + new_iids=[entry for entry in current["unknown_iids"] if entry["iid"] not in iids]) + + +def read_report(path): + report = json.loads(path.read_text(encoding="utf-8-sig")) + if not isinstance(report, dict): + raise ValueError("report must be a JSON object") + return report + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("report", type=Path) + parser.add_argument("--log", type=Path, help="matching run's UTF-8 log, also used if the report is unusable") + parser.add_argument("--json", action="store_true", help="machine-readable evidence on stdout") + parser.add_argument("--baseline", type=Path, help="complete raw report from a comparable run") + parser.add_argument("--fail-on-new", action="store_true", help="with --baseline: exit 1 on new identities, 2 on incomplete evidence") + args = parser.parse_args(argv) + if args.fail_on_new and args.baseline is None: + parser.error("--fail-on-new requires --baseline") + warnings, report = [], None + try: + report = read_report(args.report) + except (OSError, UnicodeError, ValueError, RecursionError) as error: + warnings.append(f"Cannot use report: {error}") + report = None + result = None + if args.log: + try: + with args.log.open(encoding="utf-8-sig", errors="replace") as lines: + result = analyze(report, lines) + except OSError as error: + warnings.append(f"Cannot use log: {error}") + if result is None: + if report is None: + for warning in warnings: + print(f"warning: {warning}", file=sys.stderr) + print("error: no usable report or log", file=sys.stderr) + return 2 + result = analyze(report) + result["warnings"] = sorted(set(result["warnings"] + warnings)) + comparison_failed = False + if args.baseline: + try: + result["comparison"] = compare(result, analyze(read_report(args.baseline))) + except (OSError, UnicodeError, ValueError, RecursionError) as error: + result["warnings"].append(f"Cannot compare baseline: {error}") + comparison_failed = True + for warning in result["warnings"]: + print(f"warning: {warning}", file=sys.stderr) + print(json.dumps(result, indent=2, ensure_ascii=True) if args.json else render(result)) + if comparison_failed: + return 2 + if args.fail_on_new: + comparison = result["comparison"] + if not comparison["complete"]: + return 2 + return int(bool(comparison["new_slots"] or comparison["new_iids"])) + return 0 + + +if __name__ == "__main__": + sys.exit(main())