diff --git a/CHANGELOG.md b/CHANGELOG.md index 01c019c..acc1736 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,9 @@ remains unsupported. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. ### Added +- Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`. +- Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`. + - Added a typed runtime service registry (`crates/loader/runtime/services.txt`) and `xenora-runtime-gen`, which generates Win64 argument and result adapters, static metadata and a coverage report. It covers 20 services: 16 existing kernel32 services moved to typed handlers, and `sqrt`, `sqrtf`, `fabs` and `fabsf` with arguments and results in XMM registers. Conflicting keys, unlisted API sets, unsupported types and behaviour without an existing test are rejected. See `docs/runtime/registry.md`. - Added SSE and SSE2 floating point in scalar and packed, binary32 and binary64 forms: add, subtract, multiply, divide, minimum, maximum, square root, compares, COMI/UCOMI and the conversions between formats and integers (parts of #127 and #128; awaiting independent review). `crates/loader/src/softfloat.rs` computes every result exactly and rounds once, with MXCSR rounding modes, sticky flags, denormals-are-zero, flush-to-zero, tininess after rounding and x86 NaN rules; host floating point is not used because ARM64 differs. An unmasked exception exits with `SimdException` and leaves everything but MXCSR unchanged. RCP, RSQRT and MMX conversions are rejected, and no floating-point form is translated to NEON yet. - Added 6,824 floating-point vectors computed with exact fractions by `tests/x86/float_reference.py`, run through both engines from registers and memory and through the packed forms, and more than two million round-to-nearest results compared with the host's IEEE 754 hardware. diff --git a/docs/testing/infrastructure/README.md b/docs/testing/infrastructure/README.md index b9c9661..b4128a9 100644 --- a/docs/testing/infrastructure/README.md +++ b/docs/testing/infrastructure/README.md @@ -38,6 +38,7 @@ PYTHONPATH=scripts python3 -m qa rdna2 discrepancies PYTHONPATH=scripts python3 -m qa rdna2 diff --before before.json --after after.json --compact PYTHONPATH=scripts python3 -m qa verify quick PYTHONPATH=scripts python3 -m qa cpu-coverage --blockers +PYTHONPATH=scripts python3 -m qa cpu-inventory --compact PYTHONPATH=scripts python3 -m qa bench-compare --baseline b.json --current c.json PYTHONPATH=scripts python3 -m release readiness --revision HEAD --live --binary path --app path.app ``` @@ -46,3 +47,12 @@ RDNA2 planning is read-only over the AMD snapshot, semantic registry, decoder ta `docs/status.toml`. Candidates and manifests are never counted as implemented forms. Family claims exclude those families; path-only claims block candidates whose default permitted files overlap. Reconcile reports mismatches without adjusting planner counts. + +## Phase III — compatibility intelligence + +Checkpoint ledger: [phase3-compat-ledger.md](phase3-compat-ledger.md). + +`cpu-inventory` consumes the x86 instruction registry (not heuristic opcode scans). +Declared forms are decodable only; native vs shared-semantic partitions come from +read-only `dbt.rs` analysis. Unsupported intentional rejections stay in a separate catalog. + diff --git a/docs/testing/infrastructure/phase3-compat-ledger.md b/docs/testing/infrastructure/phase3-compat-ledger.md new file mode 100644 index 0000000..87a7b2c --- /dev/null +++ b/docs/testing/infrastructure/phase3-compat-ledger.md @@ -0,0 +1,20 @@ +# Phase III compatibility-intelligence checkpoint ledger + +Branch: `feat/infra-phase3-compat`. Issue #277. +Approved paths only. No push without separate authorization. + +| Milestone | Status | Commit | Tests | Next | +| --- | --- | --- | --- | --- | +| M1 CPU inventory | done | `b2a36e9` | test_cpu_inventory 5 OK; cpu-inventory compact | M2 runtime inventory | +| M2 Runtime intelligence | done | `da92995` | test_runtime_inventory 2 OK; runtime-inventory compact | M3 compat gaps | +| M3 Compat gaps | pending | — | — | — | +| M4 Performance intel | pending | — | — | — | +| M5 Regression detection | pending | — | — | — | +| M6 Task planning | pending | — | — | — | +| M7 Unified diagnostics | pending | — | — | — | +| M8 Verify profiles | pending | — | — | — | + +## Notes + +- Do not inflate coverage. Declared ≠ implemented. +- Prefer focused `tests/qa` unit tests between milestones. diff --git a/scripts/qa/__main__.py b/scripts/qa/__main__.py index ea6df74..8e90182 100644 --- a/scripts/qa/__main__.py +++ b/scripts/qa/__main__.py @@ -53,6 +53,17 @@ from .rdna2_plan import ( write_json, ) from .coverage_history import historical_report, snapshot_inventory, write_snapshot +from .cpu_inventory import ( + build_inventory as build_cpu_inventory, + compact_inventory as compact_cpu_inventory, + dumps_inventory as dumps_cpu_inventory, +) +from .runtime_inventory import ( + build_runtime_inventory, + compact_runtime, + dumps_runtime, +) +from .compat_gaps import analyze_gaps, compact_gaps, dumps_gaps, load_dependency_report from .stale_branch import classify_sync, format_sync_reports from .verify import dumps_evidence, evidence_is_stale, load_evidence, run_profile @@ -117,10 +128,24 @@ def main(argv: list[str] | None = None) -> int: r.add_argument("--before", default="", help="JSON inventory for diff") r.add_argument("--after", default="", help="JSON inventory for diff") - cpu = sub.add_parser("cpu-coverage", help="read-only CPU/runtime coverage scan") + cpu = sub.add_parser("cpu-coverage", help="legacy heuristic CPU/runtime coverage scan") cpu.add_argument("--blockers", action="store_true") cpu.add_argument("--compare", default="", help="previous JSON report path") + cinv = sub.add_parser("cpu-inventory", help="authoritative x86 inventory from instructions.toml") + cinv.add_argument("--compact", action="store_true") + cinv.add_argument("--forms", action="store_true", help="include expanded form records in JSON") + cinv.add_argument("--out", default="", help="write JSON (prefer artifacts/)") + + rinv = sub.add_parser("runtime-inventory", help="typed runtime services from services.txt") + rinv.add_argument("--compact", action="store_true") + rinv.add_argument("--out", default="") + + gaps = sub.add_parser("compat-gaps", help="read-only dependency gap analysis (no binary exec)") + gaps.add_argument("--deps", required=True, help="JSON dependency report path") + gaps.add_argument("--compact", action="store_true") + gaps.add_argument("--out", default="") + ver = sub.add_parser("verify", help="run a verification profile") ver.add_argument("profile", choices=("quick", "cpu", "gpu", "app", "full", "release")) ver.add_argument("--revision", default="") @@ -320,6 +345,46 @@ def main(argv: list[str] | None = None) -> int: print(dumps_cpu(report), end="") return 0 + if args.command == "cpu-inventory": + inv = build_cpu_inventory(root) + payload = inv.to_dict() + if not args.forms: + payload.pop("forms", None) + if args.out: + Path(args.out).parent.mkdir(parents=True, exist_ok=True) + Path(args.out).write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") + if args.compact or args.out: + print(compact_cpu_inventory(inv), end="") + else: + print(dumps_cpu_inventory(inv, include_forms=args.forms), end="") + return 0 + + if args.command == "runtime-inventory": + inv = build_runtime_inventory(root) + payload = inv.to_dict() + if args.out: + Path(args.out).parent.mkdir(parents=True, exist_ok=True) + Path(args.out).write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") + if args.compact or args.out: + print(compact_runtime(inv), end="") + else: + print(dumps_runtime(inv), end="") + return 0 + + if args.command == "compat-gaps": + deps = load_dependency_report(Path(args.deps)) + rt = build_runtime_inventory(root) + report = analyze_gaps(deps, implemented=rt.implemented, partial=rt.partial) + payload = report.to_dict() + if args.out: + Path(args.out).parent.mkdir(parents=True, exist_ok=True) + Path(args.out).write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") + if args.compact or args.out: + print(compact_gaps(report), end="") + else: + print(dumps_gaps(report), end="") + return 0 + if args.command == "verify": if args.check_stale: evidence = load_evidence(Path(args.check_stale).read_text(encoding="utf-8")) diff --git a/scripts/qa/compat_gaps.py b/scripts/qa/compat_gaps.py new file mode 100644 index 0000000..7ad8a73 --- /dev/null +++ b/scripts/qa/compat_gaps.py @@ -0,0 +1,141 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Compatibility gap analysis over read-only dependency reports. + +Consumes JSON describing imports required by authorized workloads. Never +executes input binaries. Groups missing symbols by reusable subsystem. +""" +from __future__ import annotations + +import json +from collections import defaultdict +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any, Iterable + + +# Heuristic subsystem buckets for missing Win64/CRT symbols (planning only). +SUBSYSTEM_RULES: tuple[tuple[str, tuple[str, ...]], ...] = ( + ("memory", ("VirtualAlloc", "VirtualFree", "HeapAlloc", "HeapFree", "LocalAlloc", "GlobalAlloc")), + ("threading", ("CreateThread", "OpenThread", "WaitFor", "Sleep", "Tls", "CriticalSection")), + ("process", ("GetCurrentProcess", "GetProcess", "TerminateProcess", "ExitProcess", "CreateProcess")), + ("error", ("GetLastError", "SetLastError", "FormatMessage")), + ("time", ("GetSystemTime", "QueryPerformance", "GetTickCount", "Sleep")), + ("crt-math", ("sqrt", "fabs", "sin", "cos", "pow", "exp", "log", "floor", "ceil")), + ("crt-string", ("strlen", "strcmp", "strcpy", "memcpy", "memmove", "memset", "sprintf", "snprintf")), + ("file-io", ("CreateFile", "ReadFile", "WriteFile", "CloseHandle", "GetFileSize")), + ("sync", ("WaitForSingleObject", "WaitForMultipleObjects", "CreateEvent", "CreateMutex", "ReleaseMutex")), +) + + +@dataclass +class GapItem: + module: str + symbol: str + subsystem: str + status: str # missing | partial | present + note: str = "" + + +@dataclass +class GapReport: + workload: str + total_imports: int + missing: list[dict[str, Any]] = field(default_factory=list) + partial: list[dict[str, Any]] = field(default_factory=list) + present: list[dict[str, Any]] = field(default_factory=list) + by_subsystem: dict[str, list[str]] = field(default_factory=dict) + shared_primitives: list[str] = field(default_factory=list) + notes: list[str] = field(default_factory=list) + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +def classify_subsystem(symbol: str) -> str: + for name, needles in SUBSYSTEM_RULES: + for needle in needles: + if needle.lower() in symbol.lower(): + return name + return "other" + + +def _normalize_imports(payload: dict[str, Any]) -> list[tuple[str, str]]: + """Accept {workload, imports:[{module,symbol}| "mod!sym"]} or flat list.""" + items = payload.get("imports", payload if isinstance(payload, list) else []) + out: list[tuple[str, str]] = [] + for item in items: + if isinstance(item, str): + if "!" in item: + mod, sym = item.split("!", 1) + else: + mod, sym = "unknown", item + out.append((mod, sym)) + elif isinstance(item, dict): + mod = str(item.get("module") or item.get("dll") or "unknown") + sym = str(item.get("symbol") or item.get("name") or "") + if sym: + out.append((mod, sym)) + return out + + +def analyze_gaps( + dependency_report: dict[str, Any], + *, + implemented: Iterable[str], + partial: Iterable[str], +) -> GapReport: + """Compare required imports to runtime inventory keys (`dll!symbol`).""" + impl = {k.lower() for k in implemented} + part = {k.lower() for k in partial} + workload = str(dependency_report.get("workload", "unspecified")) + imports = _normalize_imports(dependency_report) + missing: list[GapItem] = [] + partial_hits: list[GapItem] = [] + present: list[GapItem] = [] + for module, symbol in imports: + key = f"{module}!{symbol}".lower() + # Also try basename match on symbol alone against inventory keys. + symbol_keys = {k for k in impl | part if k.endswith("!" + symbol.lower())} + if key in impl or any(k in impl for k in symbol_keys): + present.append(GapItem(module, symbol, classify_subsystem(symbol), "present")) + elif key in part or any(k in part for k in symbol_keys): + partial_hits.append(GapItem(module, symbol, classify_subsystem(symbol), "partial", + "registry status is partial")) + else: + missing.append(GapItem(module, symbol, classify_subsystem(symbol), "missing")) + + by_sub: dict[str, list[str]] = defaultdict(list) + for item in missing + partial_hits: + by_sub[item.subsystem].append(f"{item.module}!{item.symbol}") + # Shared primitives: subsystems with more than one missing/partial entry. + shared = sorted(sub for sub, items in by_sub.items() if len(items) > 1 and sub != "other") + return GapReport( + workload=workload, + total_imports=len(imports), + missing=[asdict(i) for i in missing], + partial=[asdict(i) for i in partial_hits], + present=[asdict(i) for i in present], + by_subsystem={k: sorted(v) for k, v in sorted(by_sub.items())}, + shared_primitives=shared, + notes=[ + "Read-only analysis of a dependency JSON report; binaries are not executed.", + "Subsystem grouping is advisory for prioritising shared primitives.", + "Does not claim Xbox or commercial workload compatibility.", + ], + ) + + +def load_dependency_report(path: Path) -> dict[str, Any]: + return json.loads(path.read_text(encoding="utf-8")) + + +def compact_gaps(report: GapReport) -> str: + return ( + f"workload={report.workload} imports={report.total_imports} " + f"missing={len(report.missing)} partial={len(report.partial)} " + f"present={len(report.present)} shared_subsystems={len(report.shared_primitives)}\n" + ) + + +def dumps_gaps(report: GapReport) -> str: + return json.dumps(report.to_dict(), indent=2, sort_keys=True) + "\n" diff --git a/scripts/qa/cpu_inventory.py b/scripts/qa/cpu_inventory.py new file mode 100644 index 0000000..56a47e1 --- /dev/null +++ b/scripts/qa/cpu_inventory.py @@ -0,0 +1,258 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Authoritative x86-64 inventory from the instruction registry. + +Consumes `crates/loader/x86/instructions.toml` via `generate_x86.load`. +Classifies native lowering from read-only `is_native`/`neon_operation` arms in +`dbt.rs`. Does not modify CPU crates or invent support percentages. +""" +from __future__ import annotations + +import json +import re +import runpy +import sys +from collections import defaultdict +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any + + +REGISTRY_REL = Path("crates/loader/x86/instructions.toml") +GENERATOR_REL = Path("crates/loader/generate_x86.py") +DBT_REL = Path("crates/loader/src/dbt.rs") +FIXTURE_RELS = ( + Path("crates/loader/tests/x86/integer.txt"), + Path("crates/loader/tests/x86/vector.txt"), + Path("crates/loader/tests/x86/float.txt"), +) + +# Documented intentional rejections (docs/cpu/instruction-registry.md). +# Not registry forms; tracked separately so they are never counted as declared. +UNSUPPORTED_CATALOG = ( + "LOCK", + "F2/F3-as-rep (except PAUSE / declared forms)", + "F2+F3 combined", + "address-size override", + "ignored segment after FS/GS", + "16-bit stack/branch", + "16-bit BSWAP/MOVSXD", + "BT memory by register index", + "RCL/RCR/SHLD/SHRD", + "string instructions", + "MMX", + "RCP/RSQRT approximations", + "SSE3+", + "VEX", + "atomics/fences", + "raw SYSCALL in DBT", +) + + +@dataclass(frozen=True) +class FormRecord: + op: str + map: str + prefix: str + opcode: int + digit: int | None + enc: str + size: str + imm: str + src: str + expanded_from_count: bool = False + + +@dataclass +class CpuInventory: + schema: int + architecture: str + form_count: int + operation_count: int + by_map: dict[str, int] = field(default_factory=dict) + by_prefix: dict[str, int] = field(default_factory=dict) + by_size: dict[str, int] = field(default_factory=dict) + by_enc: dict[str, int] = field(default_factory=dict) + operations: list[str] = field(default_factory=list) + native_ops: list[str] = field(default_factory=list) + shared_semantic_ops: list[str] = field(default_factory=list) + fixture_mnemonics: list[str] = field(default_factory=list) + ops_missing_fixture_evidence: list[str] = field(default_factory=list) + unsupported_catalog: list[str] = field(default_factory=list) + forms: list[dict[str, Any]] = field(default_factory=list) + notes: list[str] = field(default_factory=list) + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +def _load_generator(root: Path): + path = root / GENERATOR_REL + if not path.is_file(): + raise FileNotFoundError(f"missing generator {path}") + # Keep generate_x86 importable without installing the package. + sys.path.insert(0, str(path.parent)) + try: + return runpy.run_path(str(path)) + finally: + if sys.path and sys.path[0] == str(path.parent): + sys.path.pop(0) + + +def expand_forms(raw_forms: list[dict[str, Any]]) -> list[FormRecord]: + """Expand count>1 encodings into per-opcode records (matches generator slots).""" + out: list[FormRecord] = [] + for form in raw_forms: + count = int(form.get("count", 1)) + base = int(form["opcode"]) + for offset in range(count): + out.append( + FormRecord( + op=str(form["op"]), + map=str(form.get("map", "1")), + prefix=str(form.get("prefix", "") or ""), + opcode=base + offset, + digit=form.get("digit"), + enc=str(form["enc"]), + size=str(form["size"]), + imm=str(form.get("imm", "") or ""), + src=str(form.get("src", "") or ""), + expanded_from_count=count > 1, + ) + ) + return out + + +def parse_native_ops(dbt_text: str) -> set[str]: + """Collect Op::* names that appear as unconditional native arms or NEON table keys. + + Conditional native (wide-only, encoding-gated) still counts the op as having + a native lowering path; shared-semantic remains available for other widths. + """ + native: set[str] = set() + # Arms of is_native before the final `_ => false` + fn = re.search(r"pub fn is_native\(.*?\{(.*?)\n\}", dbt_text, re.S) + body = fn.group(1) if fn else dbt_text + for match in re.finditer(r"Op::([A-Za-z0-9_]+)", body): + # Stop once we hit neon_operation definition if we grabbed too much. + native.add(_rust_op_to_registry(match.group(1))) + neon = re.search(r"fn neon_operation\(.*?\{(.*?)\n\}", dbt_text, re.S) + if neon: + for match in re.finditer(r"Op::([A-Za-z0-9_]+)", neon.group(1)): + native.add(_rust_op_to_registry(match.group(1))) + native.discard("syscall") # is_translatable rejects; not a native lower + return native + + +def _rust_op_to_registry(name: str) -> str: + # Op::Movsxd -> movsxd, Op::Add -> add + out = [] + for i, ch in enumerate(name): + if ch.isupper() and i: + out.append("_") + out.append(ch.lower()) + return "".join(out).replace("__", "_") + + +def parse_fixture_mnemonics(texts: list[str]) -> set[str]: + """First token after `|` in `hex | asm` fixture lines.""" + found: set[str] = set() + for text in texts: + for line in text.splitlines(): + if " | " not in line: + continue + asm = line.split(" | ", 1)[1].strip() + if not asm: + continue + token = asm.split()[0].lower() + # strip width suffixes used in intel syntax occasionally + found.add(token) + return found + + +def mnemonic_covers_op(mnemonic: str, op: str) -> bool: + if mnemonic == op: + return True + # Common aliases: jcc conditions, cmovcc, setcc, imul2 -> imul + if op == "jcc" and mnemonic.startswith("j") and mnemonic not in {"jmp", "jecxz", "jrcxz"}: + return True + if op == "cmov" and mnemonic.startswith("cmov"): + return True + if op == "setcc" and mnemonic.startswith("set"): + return True + if op == "imul2" and mnemonic == "imul": + return True + if op in {"cwde", "cdq"} and mnemonic in {"cwde", "cdqe", "cdq", "cqo", "cbw", "cwd"}: + return True + return False + + +def build_inventory(root: Path) -> CpuInventory: + gen = _load_generator(root) + text = (root / REGISTRY_REL).read_text(encoding="utf-8") + operations, forms = gen["load"](text) + records = expand_forms(forms) + by_map: dict[str, int] = defaultdict(int) + by_prefix: dict[str, int] = defaultdict(int) + by_size: dict[str, int] = defaultdict(int) + by_enc: dict[str, int] = defaultdict(int) + for rec in records: + by_map[rec.map] += 1 + by_prefix[rec.prefix or "none"] += 1 + by_size[rec.size] += 1 + by_enc[rec.enc] += 1 + + dbt = (root / DBT_REL).read_text(encoding="utf-8") if (root / DBT_REL).is_file() else "" + native_ops = sorted(parse_native_ops(dbt) & set(operations)) + shared = sorted(set(operations) - set(native_ops)) + + fixture_texts = [] + for rel in FIXTURE_RELS: + path = root / rel + if path.is_file(): + fixture_texts.append(path.read_text(encoding="utf-8")) + mnemonics = parse_fixture_mnemonics(fixture_texts) + missing = sorted( + op for op in operations + if not any(mnemonic_covers_op(m, op) for m in mnemonics) + and op not in {"ldmxcsr", "stmxcsr", "jcc", "jmp", "call", "ret", "hlt", "syscall"} + ) + + notes = [ + "Declared forms are decodable; support requires semantics + fixtures (docs/cpu/instruction-registry.md).", + "Native ops are read from dbt.rs is_native/neon_operation; conditional width/encoding gates still use shared semantics for other cases.", + "Unsupported catalog is documentation of intentional rejections, not missing registry rows.", + "Does not inflate coverage: fixture evidence is mnemonic-level, not form-index proof.", + ] + return CpuInventory( + schema=1, + architecture="x86-64", + form_count=len(records), + operation_count=len(operations), + by_map=dict(sorted(by_map.items())), + by_prefix=dict(sorted(by_prefix.items())), + by_size=dict(sorted(by_size.items())), + by_enc=dict(sorted(by_enc.items())), + operations=sorted(operations), + native_ops=native_ops, + shared_semantic_ops=shared, + fixture_mnemonics=sorted(mnemonics), + ops_missing_fixture_evidence=missing, + unsupported_catalog=list(UNSUPPORTED_CATALOG), + forms=[asdict(r) for r in records], + notes=notes, + ) + + +def compact_inventory(inv: CpuInventory) -> str: + return ( + f"forms={inv.form_count} ops={inv.operation_count} " + f"native={len(inv.native_ops)} shared={len(inv.shared_semantic_ops)} " + f"maps={inv.by_map} unsupported_catalog={len(inv.unsupported_catalog)}\n" + ) + + +def dumps_inventory(inv: CpuInventory, *, include_forms: bool = False) -> str: + data = inv.to_dict() + if not include_forms: + data.pop("forms", None) + return json.dumps(data, indent=2, sort_keys=True) + "\n" diff --git a/scripts/qa/runtime_inventory.py b/scripts/qa/runtime_inventory.py new file mode 100644 index 0000000..b3da3f7 --- /dev/null +++ b/scripts/qa/runtime_inventory.py @@ -0,0 +1,163 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Typed runtime service inventory from crates/loader/runtime/services.txt. + +Separates canonical services from API-set aliases. Does not execute guests or +modify runtime crates. +""" +from __future__ import annotations + +import json +import re +from collections import defaultdict +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any + + +SERVICES_REL = Path("crates/loader/runtime/services.txt") +STATUS_VALUES = frozenset({"implemented", "partial", "stub"}) + + +@dataclass +class ServiceRecord: + library: str + symbol: str + signature: str + handler: str + status: str + aliases: list[str] = field(default_factory=list) + fails: str = "" + ref: str = "" + tests: list[str] = field(default_factory=list) + + @property + def key(self) -> str: + return f"{self.library}!{self.symbol}" + + +@dataclass +class RuntimeInventory: + service_count: int + by_status: dict[str, int] + implemented: list[str] + partial: list[str] + stub: list[str] + independently_verified: list[str] + aliases: list[dict[str, str]] + alias_count: int + libraries: dict[str, int] + services: list[dict[str, Any]] + notes: list[str] + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +_SERVICE_HEAD = re.compile( + r"^service\s+(\S+)\s+(\S+)\((.*)\)\s*->\s*(\S+)\s*$" +) + + +def parse_services_text(text: str) -> list[ServiceRecord]: + services: list[ServiceRecord] = [] + current: ServiceRecord | None = None + for raw in text.splitlines(): + line = raw.strip() + if not line or line.startswith("#"): + continue + if line.startswith("service "): + match = _SERVICE_HEAD.match(line) + if not match: + raise ValueError(f"bad service header: {line}") + library, symbol, params, result = match.groups() + current = ServiceRecord( + library=library, + symbol=symbol, + signature=f"({params}) -> {result}", + handler="", + status="", + ) + services.append(current) + continue + if current is None: + raise ValueError(f"field outside service: {line}") + if " " not in line: + raise ValueError(f"missing field value: {line}") + key, value = line.split(None, 1) + if key == "handler": + current.handler = value + elif key == "status": + if value not in STATUS_VALUES: + raise ValueError(f"unknown status {value!r}") + current.status = value + elif key == "alias": + current.aliases.append(value) + elif key == "fails": + current.fails = value + elif key == "ref": + current.ref = value + elif key == "test": + current.tests.append(value) + else: + raise ValueError(f"unknown field {key!r}") + for svc in services: + if not svc.handler or not svc.status: + raise ValueError(f"incomplete service {svc.key}") + return services + + +def build_runtime_inventory(root: Path) -> RuntimeInventory: + path = root / SERVICES_REL + services = parse_services_text(path.read_text(encoding="utf-8")) + by_status: dict[str, int] = defaultdict(int) + libraries: dict[str, int] = defaultdict(int) + aliases: list[dict[str, str]] = [] + for svc in services: + by_status[svc.status] += 1 + libraries[svc.library] += 1 + for alias in svc.aliases: + aliases.append({ + "alias": alias, + "canonical": svc.key, + "symbol": svc.symbol, + }) + # Independently verified: registry documents zero acceptance unless a future + # field appears; do not invent. Track explicit empty list. + independently_verified: list[str] = [] + notes = [ + "Status values are registry contracts for synthetic guests, not Xbox compatibility.", + "API-set aliases are counted separately from canonical services.", + "Independently verified remains empty until an acceptance process records it; not inferred.", + "docs/runtime/services.md counts are generated; this tool re-parses services.txt.", + ] + return RuntimeInventory( + service_count=len(services), + by_status=dict(sorted(by_status.items())), + implemented=sorted(s.key for s in services if s.status == "implemented"), + partial=sorted(s.key for s in services if s.status == "partial"), + stub=sorted(s.key for s in services if s.status == "stub"), + independently_verified=independently_verified, + aliases=sorted(aliases, key=lambda a: (a["alias"], a["canonical"])), + alias_count=len(aliases), + libraries=dict(sorted(libraries.items())), + services=[asdict(s) for s in services], + notes=notes, + ) + + +def compact_runtime(inv: RuntimeInventory) -> str: + return ( + f"services={inv.service_count} " + f"implemented={inv.by_status.get('implemented', 0)} " + f"partial={inv.by_status.get('partial', 0)} " + f"stub={inv.by_status.get('stub', 0)} " + f"aliases={inv.alias_count} " + f"verified={len(inv.independently_verified)}\n" + ) + + +def dumps_runtime(inv: RuntimeInventory, *, include_services: bool = True) -> str: + data = inv.to_dict() + if not include_services: + data.pop("services", None) + return json.dumps(data, indent=2, sort_keys=True) + "\n" diff --git a/tests/qa/test_compat_gaps.py b/tests/qa/test_compat_gaps.py new file mode 100644 index 0000000..6d40add --- /dev/null +++ b/tests/qa/test_compat_gaps.py @@ -0,0 +1,39 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +import unittest + +from qa.compat_gaps import analyze_gaps, classify_subsystem, compact_gaps + + +class CompatGaps(unittest.TestCase): + def test_groups_missing_by_subsystem(self): + report = analyze_gaps( + { + "workload": "synthetic-a", + "imports": [ + {"module": "kernel32.dll", "symbol": "VirtualAlloc"}, + {"module": "kernel32.dll", "symbol": "VirtualFree"}, + {"module": "kernel32.dll", "symbol": "GetCurrentProcess"}, + {"module": "ucrtbase.dll", "symbol": "sqrt"}, + {"module": "kernel32.dll", "symbol": "CreateFileW"}, + ], + }, + implemented=["kernel32.dll!GetCurrentProcess"], + partial=["kernel32.dll!VirtualAlloc", "ucrtbase.dll!sqrt"], + ) + self.assertEqual(report.workload, "synthetic-a") + self.assertEqual(len(report.present), 1) + self.assertEqual(len(report.partial), 2) + self.assertEqual(len(report.missing), 2) # VirtualFree, CreateFileW + self.assertIn("memory", report.by_subsystem) + self.assertIn("memory", report.shared_primitives) + self.assertIn("binaries are not executed", " ".join(report.notes).lower()) + self.assertIn("missing=2", compact_gaps(report)) + + def test_subsystem_rules(self): + self.assertEqual(classify_subsystem("VirtualAlloc"), "memory") + self.assertEqual(classify_subsystem("sqrtf"), "crt-math") + self.assertEqual(classify_subsystem("NoSuchThing"), "other") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/qa/test_cpu_inventory.py b/tests/qa/test_cpu_inventory.py new file mode 100644 index 0000000..6937353 --- /dev/null +++ b/tests/qa/test_cpu_inventory.py @@ -0,0 +1,71 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +import unittest +from pathlib import Path + +from qa.cpu_inventory import ( + build_inventory, + compact_inventory, + expand_forms, + mnemonic_covers_op, + parse_fixture_mnemonics, + parse_native_ops, +) + +ROOT = Path(__file__).resolve().parents[2] + + +class CpuInventory(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.inv = build_inventory(ROOT) + + def test_registry_forms_not_heuristic(self): + self.assertEqual(self.inv.schema, 1) + self.assertEqual(self.inv.architecture, "x86-64") + self.assertGreater(self.inv.form_count, 200) + self.assertGreater(self.inv.operation_count, 100) + self.assertIn("1", self.inv.by_map) + self.assertIn("0f", self.inv.by_map) + self.assertEqual( + self.inv.form_count, + sum(self.inv.by_map.values()), + ) + + def test_native_and_shared_partition(self): + native = set(self.inv.native_ops) + shared = set(self.inv.shared_semantic_ops) + ops = set(self.inv.operations) + self.assertTrue(native) + self.assertTrue(shared) + self.assertTrue(native.issubset(ops)) + self.assertTrue(shared.issubset(ops)) + self.assertEqual(native | shared, ops) + self.assertEqual(native & shared, set()) + + def test_unsupported_catalog_separate(self): + self.assertIn("MMX", self.inv.unsupported_catalog) + for name in self.inv.unsupported_catalog: + self.assertNotIn(name.lower(), self.inv.operations) + + def test_expand_count_and_fixtures(self): + expanded = expand_forms( + [{"op": "push", "opcode": 0x50, "count": 8, "enc": "op_reg", "size": "q"}] + ) + self.assertEqual(len(expanded), 8) + self.assertEqual(expanded[0].opcode, 0x50) + self.assertEqual(expanded[7].opcode, 0x57) + mnems = parse_fixture_mnemonics(["00 cb | add bl, cl\n66 01 cb | add bx, cx\n"]) + self.assertEqual(mnems, {"add"}) + self.assertTrue(mnemonic_covers_op("je", "jcc")) + self.assertTrue(mnemonic_covers_op("imul", "imul2")) + + def test_compact_and_no_coverage_inflation(self): + text = compact_inventory(self.inv) + self.assertIn(f"forms={self.inv.form_count}", text) + # Notes must deny inflation. + joined = " ".join(self.inv.notes).lower() + self.assertIn("does not inflate", joined) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/qa/test_runtime_inventory.py b/tests/qa/test_runtime_inventory.py new file mode 100644 index 0000000..4c7ef76 --- /dev/null +++ b/tests/qa/test_runtime_inventory.py @@ -0,0 +1,56 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +import unittest +from pathlib import Path + +from qa.runtime_inventory import build_runtime_inventory, compact_runtime, parse_services_text + +ROOT = Path(__file__).resolve().parents[2] + +SAMPLE = """ +# comment +service kernel32.dll GetCurrentProcess() -> handle + handler get_current_process + status implemented + alias api-ms-win-core-processthreads-l1-1-0.dll + fails never + ref processthreadsapi.h GetCurrentProcess + test identity_services_return_documented_pseudo_handles_and_ids + +service ucrtbase.dll sqrt(x: f64) -> f64 + handler crt_sqrt + status partial + fails NaN for a negative argument + ref math.h sqrt + test crt_math_guest_dispatch +""" + + +class RuntimeInventory(unittest.TestCase): + def test_parse_separates_aliases(self): + services = parse_services_text(SAMPLE) + self.assertEqual(len(services), 2) + self.assertEqual(services[0].status, "implemented") + self.assertEqual(services[0].aliases, ["api-ms-win-core-processthreads-l1-1-0.dll"]) + self.assertEqual(services[1].library, "ucrtbase.dll") + + def test_live_registry(self): + inv = build_runtime_inventory(ROOT) + self.assertGreaterEqual(inv.service_count, 20) + self.assertEqual( + inv.service_count, + inv.by_status.get("implemented", 0) + + inv.by_status.get("partial", 0) + + inv.by_status.get("stub", 0), + ) + self.assertEqual(inv.independently_verified, []) + self.assertGreater(inv.alias_count, 0) + # Aliases are separate records pointing at canonical services. + self.assertTrue(all("canonical" in a and "alias" in a for a in inv.aliases)) + self.assertTrue(all("!" in a["canonical"] for a in inv.aliases)) + text = compact_runtime(inv) + self.assertIn(f"services={inv.service_count}", text) + self.assertIn("verified=0", text) + + +if __name__ == "__main__": + unittest.main()