Compare commits

..
Author SHA1 Message Date
Swastick Chowdhury c4d0b6c000 loader: stop the static probe panicking on truncated PE names (#270)
`probe_pe_bytes` panicked on a truncated PE instead of returning an error or
reporting the import as unreadable.

The cause was in `crates/loader/src/probe.rs`. `rva_to_offset` maps an RVA to
a file offset using the section header, so on a truncated file the computed
offset can point past the end of the buffer. The loop that finds the
terminating NUL then stopped at `bytes.len()`, leaving `no > end`, and the
slice `bytes[no..end]` panicked with "range start index 1632 out of range for
slice of length 1556".

Fix both name reads:

- `rva_to_offset` now returns `None` when the computed offset is at or past
  the end of the file, because such an offset is not readable. This applies to
  every caller, so the relocation, TLS, thunk and disassembly paths are
  covered by the same rule.
- A new `read_c_string` helper reads a NUL-terminated string and returns
  `None` when the string starts outside the buffer. It replaces the
  hand-written scan in the DLL-name read and in the symbol-name read, which
  also had an unchecked `ho + 2` for the two-byte import hint.

A name that cannot be read is reported as `UNKNOWN.dll` or `UNKNOWN_SYM`,
which is what the probe already did when the RVA did not resolve at all. The
probe stays read-only and still performs no guest execution.

Add a regression test that truncates the in-repo `fixtures/pe/trusted-runner.exe`
at every length from 1 to the file size and asserts that `probe_pe_bytes`
never panics. The reported range was 1,556 to 1,665 bytes; the sweep covers
the whole file, so it also covers the other name and thunk reads that the
report noted might share the pattern. The test fails against the unmodified
probe with the reported panic and passes with this change.

Closes #270

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:57:26 +05:30
8 changed files with 102 additions and 516 deletions

No files matched your search

-3
View File
@@ -9,9 +9,6 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Changed
- 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 Phase II infrastructure CLIs under `scripts/qa` and `scripts/release` (#277): read-only RDNA2 expansion planning over live inventories, unified verification profiles with stale-evidence detection, CPU/runtime coverage scans, benchmark regression comparisons that reject incompatible identities, git rename/delete scope collision reports, and release-readiness reports with SBOM/checksum/bundle checks. Covered by `tests/qa` and `tests/release`; advisory until reviewed.
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
+38 -18
View File
@@ -791,17 +791,42 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
});
}
// Map an RVA to a file offset.
//
// The offset is derived from the section header, so on a truncated file it
// can point past the end of the buffer. Such an offset is not readable, so
// it is reported as unmapped rather than returned and sliced later.
let rva_to_offset = |rva: u32| -> Option<usize> {
for sec in &sections {
let max_span = std::cmp::max(sec.virtual_size, sec.raw_data_size);
if rva >= sec.virtual_address && rva < sec.virtual_address.saturating_add(max_span) {
let off_in_sec = (rva - sec.virtual_address) as usize;
return Some(sec.raw_data_ptr as usize + off_in_sec);
let off = sec.raw_data_ptr as usize + off_in_sec;
if off >= bytes.len() {
return None;
}
return Some(off);
}
}
None
};
// Read a NUL-terminated string that starts at `start`.
//
// Returns `None` when the string starts outside the buffer or is not
// terminated, so a truncated file yields an unreadable name instead of a
// slice that panics.
let read_c_string = |start: usize| -> Option<String> {
if start >= bytes.len() {
return None;
}
let mut end = start;
while end < bytes.len() && bytes[end] != 0 {
end += 1;
}
Some(String::from_utf8_lossy(&bytes[start..end]).into_owned())
};
// 1. Relocations Census
let mut relocations = RelocationCensus {
total_entries: 0,
@@ -895,14 +920,11 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
}
desc_off += 20;
let dll_name = if let Some(no) = rva_to_offset(name_rva) {
let mut end = no;
while end < bytes.len() && bytes[end] != 0 {
end += 1;
}
String::from_utf8_lossy(&bytes[no..end]).into_owned()
} else {
"UNKNOWN.dll".to_string()
let dll_name = match rva_to_offset(name_rva).and_then(read_c_string) {
Some(name) => name,
// The name is outside the file or is not NUL-terminated
// within it, which a truncated file can cause.
None => "UNKNOWN.dll".to_string(),
};
let category = ProbeReport::categorize_dll(&dll_name);
@@ -925,15 +947,13 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
format!("Ordinal#{}", val & 0xFFFF)
} else {
let hint_rva = (val & 0x7FFF_FFFF) as u32;
if let Some(ho) = rva_to_offset(hint_rva) {
let str_start = ho + 2;
let mut str_end = str_start;
while str_end < bytes.len() && bytes[str_end] != 0 {
str_end += 1;
}
String::from_utf8_lossy(&bytes[str_start..str_end]).into_owned()
} else {
"UNKNOWN_SYM".to_string()
// The hint is two bytes, so the name starts after it.
match rva_to_offset(hint_rva)
.and_then(|ho| ho.checked_add(2))
.and_then(read_c_string)
{
Some(name) => name,
None => "UNKNOWN_SYM".to_string(),
}
};
+18
View File
@@ -0,0 +1,18 @@
use xenora_loader::probe::{ProbeConfig, probe_pe_bytes};
/// The static probe must never panic on a truncated PE.
///
/// The fixture is truncated across its whole length, which covers the range
/// where the import directory and the import names overlap the end of the
/// file, and every other range where a name or thunk read computed from the
/// section header can run past the buffer.
#[test]
fn probe_never_panics_on_truncated_input() {
let pe = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
for len in 1..=pe.len() {
let truncated = &pe[..len];
// The probe may reject the file or report it with unreadable
// imports, but it must not panic.
let _ = probe_pe_bytes(truncated, &ProbeConfig::default());
}
}
+4 -9
View File
@@ -29,13 +29,10 @@ PYTHONPATH=scripts python3 -m unittest discover -s tests/release
## Phase II CLIs
```sh
PYTHONPATH=scripts python3 -m qa rdna2 inventory --compact
PYTHONPATH=scripts python3 -m qa rdna2 candidates --family SOP2 --status reuse-primitives --limit 50
PYTHONPATH=scripts python3 -m qa rdna2 plan --limit 20 --compact
PYTHONPATH=scripts python3 -m qa rdna2 manifests --status reuse-primitives --limit 10 --claims claims.json
PYTHONPATH=scripts python3 -m qa rdna2 reconcile --compact
PYTHONPATH=scripts python3 -m qa rdna2 inventory
PYTHONPATH=scripts python3 -m qa rdna2 candidates --limit 50
PYTHONPATH=scripts python3 -m qa rdna2 plan
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 bench-compare --baseline b.json --current c.json
@@ -43,6 +40,4 @@ PYTHONPATH=scripts python3 -m release readiness --revision HEAD --live --binary
```
RDNA2 planning is read-only over the AMD snapshot, semantic registry, decoder tables and
`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.
`docs/status.toml`. Candidates are never counted as implemented forms.
+11 -101
View File
@@ -8,7 +8,6 @@ import shlex
import subprocess
import sys
from pathlib import Path
from typing import Any
from .bench_regress import IncompatibleComparison, compare_records, dumps_comparison, load_record
from .bench_stats import export_json, human_report, summarize
@@ -36,21 +35,14 @@ from .pr_validate import (
merge_reports,
)
from .rdna2_plan import (
build_manifests,
classify_unsupported,
compact_candidates,
compact_inventory,
compact_manifests,
coverage_diff,
discrepancies,
dumps_candidates,
dumps_inventory,
load_inventories,
parse_claims_file,
plan_batches,
reconcile_with_coverage_report,
summarize_inventory,
write_json,
)
from .coverage_history import historical_report, snapshot_inventory, write_snapshot
from .stale_branch import classify_sync, format_sync_reports
@@ -99,21 +91,8 @@ def main(argv: list[str] | None = None) -> int:
v.add_argument("--allowed", action="append", default=[])
r = sub.add_parser("rdna2", help="read-only RDNA2 expansion planning")
r.add_argument(
"action",
choices=("inventory", "candidates", "plan", "discrepancies", "diff", "manifests", "reconcile"),
)
r.add_argument("action", choices=("inventory", "candidates", "plan", "discrepancies", "diff"))
r.add_argument("--limit", type=int, default=0)
r.add_argument("--family", action="append", default=[], help="filter by encoding family")
r.add_argument(
"--status",
action="append",
default=[],
help="filter: reuse-primitives|needs-primitives|needs-operand-rules",
)
r.add_argument("--claims", default="", help="JSON claims file to exclude overlapping work")
r.add_argument("--compact", action="store_true", help="print compact summary to stdout")
r.add_argument("--out", default="", help="write full JSON under this path (prefer artifacts/)")
r.add_argument("--before", default="", help="JSON inventory for diff")
r.add_argument("--after", default="", help="JSON inventory for diff")
@@ -220,93 +199,24 @@ def main(argv: list[str] | None = None) -> int:
return Inventory(**{k: d[k] for k in (
"identified", "declared", "decoder_supported", "reference_verified",
"metal_verified", "unsupported", "by_family")})
payload = coverage_diff(inv(before), inv(after))
if args.out:
write_json(Path(args.out), payload)
if args.compact or args.out:
print(
f"declared_delta={payload['declared_delta']} "
f"unsupported_delta={payload['unsupported_delta']}"
)
else:
print(json.dumps(payload, indent=2, sort_keys=True))
print(json.dumps(coverage_diff(inv(before), inv(after)), indent=2, sort_keys=True))
return 0
data = load_inventories(root)
inv = summarize_inventory(data)
exclude_families: list[str] = []
claimed_paths: list[str] = []
if args.claims:
fams, paths = parse_claims_file(Path(args.claims))
exclude_families = sorted(fams)
claimed_paths = sorted(paths)
limit = args.limit or None
def emit(payload: Any, compact_text: str, full_text: str | None = None) -> int:
if args.out:
write_json(Path(args.out), payload)
if args.compact or args.out:
print(compact_text, end="")
elif full_text is not None:
print(full_text, end="")
else:
print(json.dumps(payload, indent=2, sort_keys=True) + "\n", end="")
return 0
if args.action == "inventory":
return emit(json.loads(dumps_inventory(inv)), compact_inventory(inv), dumps_inventory(inv))
print(dumps_inventory(inv), end="")
return 0
if args.action == "candidates":
cands = classify_unsupported(
data,
limit=limit,
families=args.family or None,
statuses=args.status or None,
exclude_families=exclude_families,
)
payload = json.loads(dumps_candidates(cands))
return emit(payload, compact_candidates(cands), dumps_candidates(cands))
limit = args.limit or None
print(dumps_candidates(classify_unsupported(data, limit=limit)), end="")
return 0
if args.action == "plan":
cands = classify_unsupported(
data,
limit=limit,
families=args.family or None,
statuses=args.status or None,
exclude_families=exclude_families,
)
payload = plan_batches(cands)
return emit(payload, compact_candidates(cands))
if args.action == "manifests":
cands = classify_unsupported(
data,
limit=None,
families=args.family or None,
statuses=args.status or ["reuse-primitives"],
exclude_families=exclude_families,
)
manifests = build_manifests(
cands,
exclude_families=exclude_families,
claimed_paths=claimed_paths,
limit=limit,
)
payload = {
"note": "Codex-ready planning manifests only; forms are not implemented.",
"count": len(manifests),
"manifests": manifests,
}
out = args.out or "artifacts/rdna2-manifests.json"
write_json(Path(out), payload)
print(compact_manifests(manifests), end="")
print(f"wrote {out}")
cands = classify_unsupported(data, limit=(args.limit or None))
print(json.dumps(plan_batches(cands), indent=2, sort_keys=True))
return 0
if args.action == "discrepancies":
payload = discrepancies(data)
return emit(payload, f"discrepancies={len(payload)}\n")
if args.action == "reconcile":
payload = reconcile_with_coverage_report(root, data)
return emit(
payload,
f"reconcile_ok={payload['ok']} mismatches={len(payload['mismatches'])}\n",
)
print(json.dumps(discrepancies(data), indent=2, sort_keys=True))
return 0
if args.command == "cpu-coverage":
report = build_cpu_report(root)
+28 -278
View File
@@ -9,13 +9,12 @@ implemented forms.
from __future__ import annotations
import json
import re
import runpy
import tomllib
from collections import defaultdict
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Iterable, Sequence
from typing import Any
def _load_coverage_module(root: Path):
@@ -47,8 +46,6 @@ class Candidate:
missing_effects: list[str] = field(default_factory=list)
spec_refs: list[dict[str, Any]] = field(default_factory=list)
priority_batch: str = "unclassified"
priority_rank: int = 99
status: str = "unsupported"
notes: list[str] = field(default_factory=list)
@@ -63,27 +60,6 @@ class Inventory:
by_family: dict[str, dict[str, int]]
# Conventional GPU semantic-expansion file set for Codex manifests only.
# Planning does not claim or edit these paths.
DEFAULT_PERMITTED_FILES = (
"crates/isa/semantics/rdna2.toml",
"crates/isa/src/semantics_gen.rs",
"crates/decoder/src/lib.rs",
"crates/shader/",
"crates/ref/",
"tests/validation/",
"docs/status.toml",
"CHANGELOG.md",
)
DEFAULT_ACCEPTANCE = (
"cargo test --locked -p xenora-ref",
"cargo test --locked -p xenora-semantic-review",
"scripts/test-gpu.sh",
"python3 scripts/audit/semantic_coverage.py --check",
)
def load_inventories(root: Path) -> dict[str, Any]:
sc = _load_coverage_module(root)
identified = sc["load_snapshot"](root)
@@ -170,65 +146,52 @@ def _declared_ops(registry: dict[str, Any]) -> set[str]:
return {form.get("operation") for form in registry.get("form", []) if form.get("operation")}
def _batch_for(family: str, family_rule_names: list[str], ops: set[str]) -> tuple[str, int, str]:
"""Return (batch_id, priority_rank, status). Lower rank is higher priority."""
if family_rule_names and ops:
return f"batch-{family.lower()}-reuse-primitives", 0, "reuse-primitives"
if family_rule_names:
return f"batch-{family.lower()}-needs-primitives", 1, "needs-primitives"
return f"batch-{family.lower()}-needs-operand-rules", 2, "needs-operand-rules"
def _declared_rules(registry: dict[str, Any]) -> set[str]:
return set(registry.get("operand_rules", {}))
def classify_unsupported(
data: dict[str, Any],
*,
limit: int | None = None,
families: Sequence[str] | None = None,
statuses: Sequence[str] | None = None,
exclude_families: Sequence[str] | None = None,
) -> list[Candidate]:
def classify_unsupported(data: dict[str, Any], *, limit: int | None = None) -> list[Candidate]:
"""Build candidates for identified forms that are not registry-declared.
Does not infer behaviour from the mnemonic. Width/type/layout are filled
only when already present on related declared forms in the same family, or
left null. Results are sorted by priority_rank then family/name.
left null.
"""
identified = data["identified"]
declared = data["declared"]
registry = data["registry"]
rules = data["rules"]
ops = _declared_ops(registry)
family_widths: dict[str, set[int]] = defaultdict(set)
family_types: dict[str, set[str]] = defaultdict(set)
rule_names = _declared_rules(registry)
family_rules = defaultdict(list)
family_widths = defaultdict(set)
family_types = defaultdict(set)
for form in registry.get("form", []):
family_rules[form["family"]].append(form.get("operands"))
if "width" in form:
family_widths[form["family"]].add(form["width"])
if "signedness" in form:
family_types[form["family"]].add(form["signedness"])
family_filter = {f.upper() for f in families} if families else None
status_filter = {s for s in statuses} if statuses else None
excluded = {f.upper() for f in (exclude_families or ())}
candidates: list[Candidate] = []
unsupported = sorted(set(identified) - set(declared))
if limit is not None:
unsupported = unsupported[:limit]
for family, name in unsupported:
if family_filter is not None and family.upper() not in family_filter:
continue
if family.upper() in excluded:
continue
opcode = identified[(family, name)]
reusable = sorted(op for op in ops if op)
family_rule_names = [n for n, (fam, _) in rules.items() if fam == family]
reusable = sorted(op for op in ops if op) # available primitives, not guessed mapping
missing_rules = []
# If the family has no operand rule yet, record that gap.
family_rule_names = [n for n, (fam, _) in rules.items() if fam == family]
if not family_rule_names:
missing_rules.append(f"no operand_rules for family {family}")
missing_effects = []
# Architectural effects are unknown until specified; flag absence.
missing_effects.append("scc/vcc/exec effects unspecified until registry declaration")
widths = sorted(family_widths.get(family, []))
types = sorted(family_types.get(family, []))
layout = family_rule_names[0] if len(family_rule_names) == 1 else None
batch, rank, status = _batch_for(family, family_rule_names, ops)
if status_filter is not None and status not in status_filter:
continue
batch = _batch_for(family, family_rule_names, ops)
candidates.append(Candidate(
family=family,
name=name,
@@ -238,22 +201,25 @@ def classify_unsupported(
operand_layout=layout,
reusable_primitives=reusable[:20],
missing_operand_rules=missing_rules,
missing_effects=["scc/vcc/exec effects unspecified until registry declaration"],
missing_effects=missing_effects,
spec_refs=[{"document": "xml", "note": "identity from pinned AMD snapshot only"}],
priority_batch=batch,
priority_rank=rank,
status=status,
notes=[
"behaviour must come from the public AMD guide, never the mnemonic",
"candidate is not implemented",
],
))
candidates.sort(key=lambda c: (c.priority_rank, c.family, c.name, c.opcode))
if limit is not None:
candidates = candidates[:limit]
return candidates
def _batch_for(family: str, family_rule_names: list[str], ops: set[str]) -> str:
if family_rule_names and ops:
return f"batch-{family.lower()}-reuse-primitives"
if family_rule_names:
return f"batch-{family.lower()}-needs-primitives"
return f"batch-{family.lower()}-needs-operand-rules"
def plan_batches(candidates: list[Candidate]) -> dict[str, list[dict[str, Any]]]:
batches: dict[str, list[dict[str, Any]]] = defaultdict(list)
for cand in candidates:
@@ -261,7 +227,6 @@ def plan_batches(candidates: list[Candidate]) -> dict[str, list[dict[str, Any]]]
"family": cand.family,
"name": cand.name,
"opcode": cand.opcode,
"status": cand.status,
"missing_operand_rules": cand.missing_operand_rules,
"reusable_primitives": cand.reusable_primitives[:5],
})
@@ -310,179 +275,6 @@ def discrepancies(data: dict[str, Any]) -> list[dict[str, str]]:
return issues
def reconcile_with_coverage_report(root: Path, data: dict[str, Any]) -> dict[str, Any]:
"""Compare planner inventory to canonical semantic_coverage collect_coverage.
Does not inflate planner counts. Reports per-family deltas only.
"""
sc = data["sc"]
identified = data["identified"]
registry = data["registry"]
decoder = data["decoder"]
status = data["status"]
counts, _rules = sc["collect_coverage"](identified, registry, decoder, status)
# collect_coverage tuple per family:
# Identified, Encoding-validated, Declared, Decoder-supported, IR, MSL,
# Reference-verified, Metal-verified, Unsupported operand variants
inv = summarize_inventory(data)
mismatches: list[dict[str, Any]] = []
for family, values in sorted(counts.items()):
canon_identified, _enc, canon_declared, canon_decoder, _ir, _msl, canon_ref, canon_metal, _u = values
bucket = inv.by_family.get(family, {})
pairs = (
("identified", canon_identified, bucket.get("identified", 0)),
("declared", canon_declared, bucket.get("declared", 0)),
("decoder", canon_decoder, bucket.get("decoder", 0)),
("reference", canon_ref, bucket.get("reference", 0)),
("metal", canon_metal, bucket.get("metal", 0)),
)
for field_name, canon, plan in pairs:
if canon != plan:
mismatches.append({
"family": family,
"field": field_name,
"canonical": canon,
"planner": plan,
"delta": plan - canon,
})
return {
"ok": not mismatches,
"canonical_totals": {
"identified": sum(v[0] for v in counts.values()),
"declared": sum(v[2] for v in counts.values()),
"decoder_supported": sum(v[3] for v in counts.values()),
"reference_verified": sum(v[6] for v in counts.values()),
"metal_verified": sum(v[7] for v in counts.values()),
},
"planner_totals": {
"identified": inv.identified,
"declared": inv.declared,
"decoder_supported": inv.decoder_supported,
"reference_verified": inv.reference_verified,
"metal_verified": inv.metal_verified,
},
"mismatches": mismatches,
"note": "Planner counts are not adjusted to match; mismatches must be investigated.",
}
@dataclass(frozen=True)
class ClaimScope:
"""One active claim. Families exclude those families; path-only claims
block candidates whose default permitted files overlap the claimed paths.
A claim that lists both families and paths excludes only the families —
the paths document the claim and do not blanket-block other families.
"""
families: frozenset[str] = frozenset()
paths: frozenset[str] = frozenset()
def parse_claims_file(path: Path) -> tuple[set[str], set[str]]:
"""Load excluded families and path-only claim prefixes.
Expected shape: {"claims":[{"families":["VOP2"], "paths":["crates/isa/**"]}, ...]}
or a bare list of such objects.
Returns (exclude_families, path_only_claimed_paths). Path prefixes from
claims that also name families are ignored for blocking so a SOP2+isa
claim does not suppress every other family's manifests.
"""
scopes = load_claim_scopes(path)
families: set[str] = set()
path_only: set[str] = set()
for scope in scopes:
families.update(scope.families)
if scope.families:
continue
path_only.update(scope.paths)
return families, path_only
def load_claim_scopes(path: Path) -> list[ClaimScope]:
raw = json.loads(path.read_text(encoding="utf-8"))
items = raw["claims"] if isinstance(raw, dict) and "claims" in raw else raw
if not isinstance(items, list):
raise ValueError("claims file must be a list or {\"claims\": [...]}")
scopes: list[ClaimScope] = []
for item in items:
fams = frozenset(str(f).upper() for f in (item.get("families") or []))
paths = frozenset(str(p) for p in (item.get("paths") or []))
if not fams and not paths:
continue
scopes.append(ClaimScope(families=fams, paths=paths))
return scopes
def claims_block_candidate(cand: Candidate, claimed_paths: set[str]) -> bool:
"""True if a path-only claim overlaps the default GPU expansion files."""
if not claimed_paths:
return False
for permitted in DEFAULT_PERMITTED_FILES:
for claimed in claimed_paths:
if _path_overlap(permitted, claimed):
return True
return False
def _path_overlap(a: str, b: str) -> bool:
a = a.rstrip("/")
b = b.rstrip("/")
if a.endswith("/**"):
a = a[:-3].rstrip("/")
if b.endswith("/**"):
b = b[:-3].rstrip("/")
return a == b or a.startswith(b + "/") or b.startswith(a + "/")
def build_manifests(
candidates: list[Candidate],
*,
exclude_families: Sequence[str] | None = None,
claimed_paths: Sequence[str] | None = None,
limit: int | None = None,
) -> list[dict[str, Any]]:
"""Deterministic Codex-ready implementation manifests.
Prioritises reuse-primitives, then needs-primitives, then needs-operand-rules.
Excludes active claim families and path-only claims. Does not invent semantics.
"""
excluded = {f.upper() for f in (exclude_families or ())}
claimed = set(claimed_paths or ())
manifests: list[dict[str, Any]] = []
for cand in candidates:
if cand.family.upper() in excluded:
continue
if claims_block_candidate(cand, claimed):
continue
deps: list[str] = []
if cand.status == "needs-operand-rules":
deps.append(f"define operand_rules for family {cand.family}")
if cand.status == "needs-primitives":
deps.append("add registry operation primitive before declaring this form")
if cand.status == "reuse-primitives":
deps.append("reuse existing registry primitives/operand rules; declare form from AMD guide")
deps.append("do not infer behaviour from the mnemonic")
manifest = {
"id": f"{cand.family}:{cand.name}",
"instruction": {
"family": cand.family,
"name": cand.name,
"opcode": cand.opcode,
},
"priority_rank": cand.priority_rank,
"status": cand.status,
"dependencies": deps,
"specification_references": cand.spec_refs,
"permitted_files": list(DEFAULT_PERMITTED_FILES),
"acceptance_tests": list(DEFAULT_ACCEPTANCE),
"notes": list(cand.notes),
}
manifests.append(manifest)
if limit is not None and len(manifests) >= limit:
break
return manifests
def coverage_diff(before: Inventory, after: Inventory) -> dict[str, Any]:
return {
"identified_delta": after.identified - before.identified,
@@ -507,45 +299,3 @@ def dumps_candidates(candidates: list[Candidate]) -> str:
def dumps_inventory(inv: Inventory) -> str:
return json.dumps(asdict(inv), indent=2, sort_keys=True) + "\n"
def compact_inventory(inv: Inventory) -> str:
lines = [
f"identified={inv.identified} declared={inv.declared} "
f"decoder={inv.decoder_supported} unsupported={inv.unsupported} "
f"ref={inv.reference_verified} metal={inv.metal_verified}",
]
for family, bucket in inv.by_family.items():
if bucket.get("unsupported", 0) == 0 and bucket.get("declared", 0) == 0:
continue
lines.append(
f" {family}: id={bucket['identified']} decl={bucket['declared']} "
f"dec={bucket['decoder']} unsup={bucket['unsupported']}"
)
return "\n".join(lines) + "\n"
def compact_candidates(candidates: Sequence[Candidate]) -> str:
lines = [f"candidates={len(candidates)}"]
for cand in candidates:
lines.append(
f" [{cand.priority_rank}:{cand.status}] {cand.family}:{cand.name} "
f"op=0x{cand.opcode:x} batch={cand.priority_batch}"
)
return "\n".join(lines) + "\n"
def compact_manifests(manifests: Sequence[dict[str, Any]]) -> str:
lines = [f"manifests={len(manifests)}"]
for item in manifests:
inst = item["instruction"]
lines.append(
f" [{item['priority_rank']}:{item['status']}] {inst['family']}:{inst['name']} "
f"deps={len(item['dependencies'])}"
)
return "\n".join(lines) + "\n"
def write_json(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
-21
View File
@@ -32,27 +32,6 @@ class CliSmoke(unittest.TestCase):
data = json.loads(inv.stdout)
self.assertGreater(data["identified"], data["declared"])
compact = run("qa", "rdna2", "candidates", "--status", "reuse-primitives", "--limit", "2", "--compact")
self.assertEqual(compact.returncode, 0, compact.stderr)
self.assertIn("candidates=2", compact.stdout)
recon = run("qa", "rdna2", "reconcile", "--compact")
self.assertEqual(recon.returncode, 0, recon.stderr)
self.assertIn("reconcile_ok=", recon.stdout)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "manifests.json"
man = run(
"qa", "rdna2", "manifests",
"--status", "reuse-primitives",
"--limit", "2",
"--out", str(out),
)
self.assertEqual(man.returncode, 0, man.stderr)
payload = json.loads(out.read_text(encoding="utf-8"))
self.assertEqual(payload["count"], 2)
self.assertIn("not implemented", payload["note"].lower())
def test_release_readiness_cli_negative(self):
r = run(
"release", "readiness",
+3 -86
View File
@@ -1,22 +1,16 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import tempfile
import unittest
from pathlib import Path
from qa.rdna2_plan import (
Inventory,
build_manifests,
classify_unsupported,
compact_candidates,
compact_inventory,
coverage_diff,
discrepancies,
dumps_candidates,
load_inventories,
parse_claims_file,
plan_batches,
reconcile_with_coverage_report,
summarize_inventory,
)
@@ -46,85 +40,9 @@ class Rdna2Plan(unittest.TestCase):
batches = plan_batches(cands)
self.assertTrue(batches)
def test_family_status_limit_and_priority(self):
reuse = classify_unsupported(
self.data, families=["SOP2"], statuses=["reuse-primitives"], limit=5
)
self.assertLessEqual(len(reuse), 5)
for cand in reuse:
self.assertEqual(cand.family, "SOP2")
self.assertEqual(cand.status, "reuse-primitives")
self.assertEqual(cand.priority_rank, 0)
needs_rules = classify_unsupported(
self.data, statuses=["needs-operand-rules"], limit=3
)
for cand in needs_rules:
self.assertEqual(cand.status, "needs-operand-rules")
self.assertEqual(cand.priority_rank, 2)
# Priority ordering: reuse before needs-operand-rules when unfiltered.
mixed = classify_unsupported(self.data, limit=20)
ranks = [c.priority_rank for c in mixed]
self.assertEqual(ranks, sorted(ranks))
def test_manifests_exclude_claims_and_stay_deterministic(self):
cands = classify_unsupported(self.data, statuses=["reuse-primitives"], limit=50)
with tempfile.TemporaryDirectory() as tmp:
claims = Path(tmp) / "claims.json"
claims.write_text(
json.dumps({"claims": [{"families": ["SOP2"], "paths": ["crates/isa/**"]}]}),
encoding="utf-8",
)
fams, paths = parse_claims_file(claims)
self.assertIn("SOP2", fams)
# Family+path claims must not path-block every other family.
self.assertEqual(paths, set())
manifests = build_manifests(
cands, exclude_families=sorted(fams), claimed_paths=sorted(paths), limit=5
)
self.assertGreater(len(manifests), 0)
for item in manifests:
self.assertNotEqual(item["instruction"]["family"], "SOP2")
self.assertIn("permitted_files", item)
self.assertIn("acceptance_tests", item)
self.assertIn("specification_references", item)
self.assertIn("dependencies", item)
again = build_manifests(
cands, exclude_families=sorted(fams), claimed_paths=sorted(paths), limit=5
)
self.assertEqual(manifests, again)
path_only = Path(tmp) / "path_only.json"
path_only.write_text(
json.dumps({"claims": [{"paths": ["crates/isa/**"]}]}),
encoding="utf-8",
)
_, path_claims = parse_claims_file(path_only)
self.assertIn("crates/isa/**", path_claims)
blocked = build_manifests(
cands, claimed_paths=sorted(path_claims), limit=5
)
self.assertEqual(blocked, [])
def test_reconcile_does_not_inflate_coverage(self):
report = reconcile_with_coverage_report(ROOT, self.data)
self.assertIn("mismatches", report)
self.assertEqual(
report["planner_totals"]["identified"],
report["canonical_totals"]["identified"],
)
# Declared/decoder may differ in representation but planner must not
# silently bump counts to hide mismatches.
before = self.inv.declared
_ = reconcile_with_coverage_report(ROOT, self.data)
after = summarize_inventory(self.data).declared
self.assertEqual(before, after)
self.assertTrue(report["ok"] or isinstance(report["mismatches"], list))
def test_compact_helpers_and_diff(self):
text = compact_inventory(self.inv)
self.assertIn("identified=", text)
cands = classify_unsupported(self.data, limit=2)
self.assertIn("candidates=2", compact_candidates(cands))
def test_discrepancies_and_diff(self):
issues = discrepancies(self.data)
self.assertIsInstance(issues, list)
before = Inventory(
identified=self.inv.identified,
declared=self.inv.declared - 1 if self.inv.declared else 0,
@@ -136,7 +54,6 @@ class Rdna2Plan(unittest.TestCase):
)
delta = coverage_diff(before, self.inv)
self.assertEqual(delta["declared_delta"], self.inv.declared - before.declared)
self.assertIsInstance(discrepancies(self.data), list)
if __name__ == "__main__":