diff --git a/CHANGELOG.md b/CHANGELOG.md index 01c019c..b45be4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ 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 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..61282f5 --- /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 | `827b9ff` | test_cpu_inventory 5 OK; cpu-inventory compact | M2 runtime inventory | +| M2 Runtime intelligence | pending | — | — | — | +| 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..e70fff6 100644 --- a/scripts/qa/__main__.py +++ b/scripts/qa/__main__.py @@ -53,6 +53,11 @@ 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 .stale_branch import classify_sync, format_sync_reports from .verify import dumps_evidence, evidence_is_stale, load_evidence, run_profile @@ -117,10 +122,15 @@ 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/)") + 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 +330,20 @@ 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 == "verify": if args.check_stale: evidence = load_evidence(Path(args.check_stale).read_text(encoding="utf-8")) 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/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()