diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc905cb1b..3205f2457 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 722483312..f74a2090e 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,10 @@ 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. `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 000000000..30f63a079 --- /dev/null +++ b/docs/d3d12-triage.md @@ -0,0 +1,90 @@ +# 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 + +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. + +## 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. +Risks: logger/schema drift may lose evidence (recognized malformed records warn), +and mixing runs can merge unrelated observations. Follow-ups: versioned structured +runtime events with run identity, then baseline comparisons once provenance is +available. 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 000000000..cb512880b --- /dev/null +++ b/scripts/test_triage_d3d12.py @@ -0,0 +1,130 @@ +"""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, 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) + + +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) + + @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 000000000..cb96e3095 --- /dev/null +++ b/scripts/triage_d3d12.py @@ -0,0 +1,165 @@ +"""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.") + out.append("Next: verify the caller and console layout before implementing a slot; IIDs may be optional probes.") + return "\n".join(out) + + +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") + args = parser.parse_args(argv) + warnings, report = [], None + try: + report = json.loads(args.report.read_text(encoding="utf-8-sig")) + if not isinstance(report, dict): + raise ValueError("report must be a JSON object") + 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)) + 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)) + return 0 + + +if __name__ == "__main__": + sys.exit(main())