Files

379 lines
18 KiB
Python
Executable File

#!/usr/bin/env python3
"""Install compiled PTX into the tree and patch the Rust pins that guard it.
Input is the directory written by compile_assets.py (PTX + build-manifest.json). For every asset the tool
1. refuses a stale .cu (plan pin) or a .cu that changed after compile (manifest sha),
2. re-validates the PTX and checks its sha against the manifest,
3. patches each `rust_fields_to_fill` field (exactly one declaration per field, round-trip verified),
4. re-pins the digests of already-sealed PTX that are being regenerated (rope assets),
5. writes the PTX in the encoding its consumer expects,
and prints a sealed-manifest JSON. Without --write nothing on disk changes (dry run).
seal_pins.py --ptx-dir /path/to/ptx-out # dry run against this checkout
seal_pins.py --ptx-dir /path/to/ptx-out --write # install + patch
seal_pins.py --ptx-dir DIR --root /tmp/scratch --allow-fake --write # test with fake-nvcc output
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Dict, List, Optional, Tuple
sys.path.insert(0, str(Path(__file__).resolve().parent))
import bringup_lib as L # noqa: E402
import rustpins as R # noqa: E402
class SealError(RuntimeError):
pass
# ------------------------------------------------------------------------------------------ helpers
def find_consumer(root: Path, name: str) -> Path:
"""Consumer files live next to the PTX (crates/cuda-driver/src); a name with '/' is repo-relative."""
if "/" in name:
hits = [root / name] if (root / name).is_file() else []
else:
near = root / "crates/cuda-driver/src" / name
if near.is_file():
return near
hits = [p for p in (root / "crates").rglob(name) if p.is_file() and "target" not in p.parts]
if len(hits) != 1:
raise SealError(f"consumer {name}: expected exactly one file, found {len(hits)}")
return hits[0]
def rustfmt_text(text: str) -> Optional[str]:
exe = shutil.which("rustfmt")
if not exe:
return None
p = subprocess.run([exe, "--edition", "2024"], input=text, capture_output=True, text=True, timeout=120)
return p.stdout if p.returncode == 0 else None
class Workspace:
"""In-memory edits keyed by repo-relative path; nothing touches disk until commit()."""
def __init__(self, root: Path):
self.root = root
self.text: Dict[str, str] = {}
self.orig: Dict[str, str] = {}
self.blobs: Dict[str, bytes] = {}
def read(self, rel: str) -> str:
if rel not in self.text:
t = (self.root / rel).read_text(encoding="utf-8")
self.text[rel] = t
self.orig[rel] = t
return self.text[rel]
def write(self, rel: str, text: str) -> None:
self.read(rel)
self.text[rel] = text
def touched(self) -> List[str]:
a = [r for r, t in self.text.items() if t != self.orig[r]]
return sorted(a + [r for r in self.blobs])
def commit(self) -> None:
for rel, t in self.text.items():
if t != self.orig[rel]:
_atomic(self.root / rel, t.encode("utf-8"))
for rel, b in self.blobs.items():
_atomic(self.root / rel, b)
def _atomic(path: Path, data: bytes) -> None:
tmp = path.with_name("." + path.name + ".seal-tmp")
tmp.write_bytes(data)
os.replace(tmp, path)
# -------------------------------------------------------------------------------------------- plan
def load_manifest(ptx_dir: Path) -> dict:
p = ptx_dir / "build-manifest.json"
if not p.is_file():
raise SealError(f"{p} not found (run compile_assets.py first)")
m = json.loads(p.read_text(encoding="utf-8"))
if m.get("schema") != 1:
raise SealError("unsupported build-manifest schema")
return m
def resolve_assets(root: Path, manifest: dict) -> Dict[str, L.Asset]:
has_rope = any(r.get("group") == "rope" for r in manifest["assets"])
if has_rope and manifest.get("rope_flags") not in L.ROPE_VARIANTS:
raise SealError("manifest holds rope assets but no valid rope_flags")
assets, _ = L.load_all_assets(root, manifest["rope_flags"] if has_rope else None)
L.apply_flag_overrides(assets, manifest.get("flag_overrides", []))
return {a.id: a for a in assets}
# ------------------------------------------------------------------------------------------- sealing
def seal(root: Path, ptx_dir: Path, *, allow_fake: bool, only: Optional[set], rustfmt: str,
update_abi_test: bool) -> Tuple[dict, Workspace]:
manifest = load_manifest(ptx_dir)
if manifest.get("fake") and not allow_fake:
raise SealError("build-manifest.json is from fake-nvcc; refusing (use --allow-fake with a scratch --root)")
if manifest.get("fake") and root.resolve() == L.REPO.resolve():
raise SealError("fake-nvcc output may not be sealed into the checkout that holds this script; use a scratch --root")
plan = resolve_assets(root, manifest)
ws = Workspace(root)
sealed: List[dict] = []
todo = [r for r in manifest["assets"] if r["status"] == "ok" and (not only or r["id"] in only)]
failed = [r["id"] for r in manifest["assets"] if r["status"] != "ok" and (not only or r["id"] in only)]
if failed:
raise SealError(f"the compile manifest has failed assets: {', '.join(failed)}; fix or --only the good ones")
if not todo:
raise SealError("nothing to seal")
ids = {r["id"] for r in todo}
# atomic groups: rope (ABI) and mmq_group must move together
for a in plan.values():
if a.atomic_group and a.id in ids:
missing = [b.id for b in plan.values() if b.atomic_group == a.atomic_group and b.id not in ids]
if missing:
raise SealError(f"{a.id} belongs to atomic group {a.atomic_group!r}; also need: {', '.join(missing)}")
placeholders_before = set(L.scan_placeholders(root))
for rec in sorted(todo, key=lambda r: r["id"]):
asset = plan.get(rec["id"])
if asset is None:
raise SealError(f"{rec['id']}: not in any plan any more")
L.fill_derived_entries(root, asset)
want_flags = asset.flags + [f"-I{d}" for d in asset.includes]
if rec["flags"] != want_flags:
raise SealError(f"{asset.id}: compiled with flags {rec['flags']} but the plan now says {want_flags}")
status, detail = L.check_cu_pin(root, asset)
if status in ("stale", "missing"):
raise SealError(f"{asset.id}: stale source: {detail}")
cu_bytes = (root / asset.cu).read_bytes()
if L.sha256_hex(cu_bytes) != rec["cu_sha256"]:
raise SealError(f"{asset.id}: {asset.cu} changed after it was compiled (sha256 differs from the manifest)")
raw = (ptx_dir / rec["ptx_file"]).read_bytes()
if L.sha256_hex(raw) != rec["raw_sha256"]:
raise SealError(f"{asset.id}: PTX in {ptx_dir} does not match the manifest")
problems = L.validate_ptx(raw, asset, allow_fake=allow_fake and bool(manifest.get("fake")))
if problems:
raise SealError(f"{asset.id}: {'; '.join(problems)}")
stored = L.stored_bytes(raw, asset.encoding)
values = R.PinValues(raw_len=len(raw), ptx_sha256=L.sha256_digest(raw), source_sha256=L.sha256_digest(cu_bytes))
out = {"id": asset.id, "group": asset.group, "cu": asset.cu, "cu_sha256": rec["cu_sha256"],
"ptx": asset.ptx, "encoding": asset.encoding, "flags": rec["flags"],
"raw_bytes": len(raw), "raw_sha256": rec["raw_sha256"],
"stored_bytes": len(stored), "stored_sha256": L.sha256_hex(stored),
"patches": [], "repins": [], "followup_tests": {}}
# --- re-pin digests of the PTX being replaced (only if it was a real, sealed PTX)
old_path = root / asset.ptx
if old_path.is_file():
old_stored = old_path.read_bytes()
head = old_stored[:4096].decode("latin-1")
if "UNSEALED" not in head and "PLACEHOLDER" not in head and len(old_stored) > 1:
old_raw = L.raw_from_stored(old_stored)
_repin(root, ws, asset, old_raw, raw, out)
# --- rust_fields_to_fill
for consumer, specs in sorted(asset.pin_fields.items()):
path = find_consumer(root, consumer)
rel = str(path.relative_to(root))
ws.read(rel)
for spec in specs:
text = ws.read(rel)
try:
new = R.apply_field(text, spec, values)
if not R.read_field(new, spec, values):
raise SealError(f"{consumer} {spec}: value does not read back after patching")
except R.PinError as error:
raise SealError(f"{asset.id}: {consumer} {spec}: {error}") from error
ws.write(rel, new)
out["patches"].append({"file": rel, "field": spec, "replacements": 1, "changed": new != text})
if rel not in out["followup_tests"]:
out["followup_tests"][rel] = R.placeholder_tests(ws.orig[rel])
if asset.seal_fields:
_fill_plan_seal_fields(root, ws, asset, raw, out)
ws.blobs[asset.ptx] = stored
sealed.append(out)
# --- rope ABI test: require the extended argument lists
if update_abi_test and any(s["group"] == "rope" for s in sealed):
rel = L.ABI_SOURCE
text = ws.read(rel)
old = "matches!(state, AbiState::Frozen | AbiState::Extended),"
new = "state == AbiState::Extended,"
already = text.count(old) == 0 and text.count(new) == 1
if text.count(old) != 1 and not already:
raise SealError(f"{rel}: expected exactly one `{old}` (or the already-patched form)")
ws.write(rel, text if already else text.replace(old, new))
for s in sealed:
if s["group"] == "rope":
s["patches"].append({"file": rel, "field": "committed_ptx_has_the_frozen_argument_lists: require Extended",
"replacements": 0 if already else 1, "changed": not already})
break
# --- keep rustfmt-clean files rustfmt-clean
fmt_notes = []
for rel in sorted(r for r in ws.text if r.endswith(".rs") and ws.text[r] != ws.orig[r]):
fm = rustfmt_text(ws.orig[rel]) if rustfmt != "never" else None
clean = fm is not None and fm == ws.orig[rel]
if clean:
formatted = rustfmt_text(ws.text[rel])
if formatted is None:
fmt_notes.append(f"{rel}: rustfmt failed on the patched text; run cargo fmt")
else:
ws.text[rel] = formatted
else:
fmt_notes.append(f"{rel}: was not rustfmt-clean before (or rustfmt missing); left as patched")
# --- final read-back of every pin after formatting
for s in sealed:
asset = plan[s["id"]]
raw = (ptx_dir / manifest_file(manifest, asset.id)).read_bytes()
cu_bytes = (root / asset.cu).read_bytes()
v = R.PinValues(len(raw), L.sha256_digest(raw), L.sha256_digest(cu_bytes))
for consumer, specs in asset.pin_fields.items():
rel = str(find_consumer(root, consumer).relative_to(root))
for spec in specs:
if not R.read_field(ws.text[rel], spec, v):
raise SealError(f"{rel} {spec}: pin does not read back after formatting")
placeholders_after = sorted(placeholders_before - {s["ptx"] for s in sealed})
# ISA inventory of the tree AFTER this seal: the driver on the GPU host must support the highest version
isa: Dict[str, List[str]] = {k: list(v) for k, v in L.isa_inventory(root).items()}
for s_ in sealed:
v = L.ptx_isa_version((ptx_dir / manifest_file(manifest, s_["id"])).read_bytes())
name = Path(s_["ptx"]).name
for k in isa:
if name in isa[k]:
isa[k].remove(name)
if v:
isa.setdefault(v, []).append(name)
isa = {k: sorted(v) for k, v in isa.items() if v}
top_isa, min_driver = L.min_driver_for(isa)
result = {
"schema": 1,
"tool": "scripts/gpu-bringup/seal_pins.py",
"created_utc": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
"root": str(root),
"source_manifest": {"dir": str(ptx_dir), "sha256": L.sha256_hex((ptx_dir / "build-manifest.json").read_bytes()),
"nvcc": manifest.get("nvcc"), "fake": bool(manifest.get("fake")),
"repo_head": manifest.get("repo_head"), "rope_flags": manifest.get("rope_flags")},
"assets": sealed,
"touched_files": ws.touched(),
"unsealed_placeholders_remaining": placeholders_after,
"ptx_isa_inventory": {k: len(v) for k, v in sorted(isa.items())},
"highest_ptx_isa": top_isa,
"min_driver_required": min_driver,
"format_notes": fmt_notes,
"after_sealing": [
"These tests assert the placeholder state and WILL fail until updated (listed per file in followup_tests).",
"Files in format_notes were not rustfmt-clean before; they are left as patched (do not run cargo fmt over the crate).",
"Sealing is not qualification: run the GPU smokes (spec node gpu-bringup.md step e) before trusting any pin.",
],
}
return result, ws
def manifest_file(manifest: dict, asset_id: str) -> str:
for r in manifest["assets"]:
if r["id"] == asset_id:
return r["ptx_file"]
raise SealError(asset_id)
def _fill_plan_seal_fields(root: Path, ws: Workspace, asset: L.Asset, raw: bytes, out: dict) -> None:
"""Record the seal in the plan JSON itself (seal_sha256 / seal_length of the asset's entry), text-level so the
file's formatting is untouched. Assets without a Rust pin have no other in-tree record of their digest."""
rel = f"{L.SEAL_PLAN_DIR}/{asset.plan}"
if not (root / rel).is_file():
return
text = ws.read(rel)
pat = re.compile(r'("ptx"\s*:\s*"' + re.escape(asset.ptx) + r'"(?:(?!"cu"\s*:).)*?"seal_sha256"\s*:\s*)(null|"[0-9a-f]{64}")'
r'(\s*,\s*"seal_length"\s*:\s*)(null|\d+)', re.S)
ms = list(pat.finditer(text))
if len(ms) != 1:
raise SealError(f"{rel}: expected one seal_sha256/seal_length slot for {asset.ptx}, found {len(ms)}")
m = ms[0]
new = text[: m.start(2)] + f'"{L.sha256_hex(raw)}"' + m.group(3) + str(len(raw)) + text[m.end(4):]
ws.write(rel, new)
out["patches"].append({"file": rel, "field": f"seal_sha256/seal_length of {asset.id}", "replacements": 1, "changed": new != text})
def _repin(root: Path, ws: Workspace, asset: L.Asset, old_raw: bytes, new_raw: bytes, out: dict) -> None:
old_d, new_d = L.sha256_digest(old_raw), L.sha256_digest(new_raw)
if old_d == new_d:
out["repins"].append({"note": "regenerated PTX is byte-identical to the committed one"})
return
found: Dict[str, int] = {}
for p in sorted((root / "crates").rglob("*.rs")):
if "target" in p.parts:
continue
rel = str(p.relative_to(root))
n = len(R.find_decimal_pins(ws.read(rel) if rel in ws.text else p.read_text(encoding="utf-8", errors="replace"), old_d))
if n:
found[rel] = n
expected = asset.repin_expect
if found != expected:
raise SealError(f"{asset.id}: digest of the committed PTX is pinned at {found or 'nowhere'}, expected {expected or 'nowhere'}; "
"investigate before sealing (another consumer pins the old bytes)")
for rel, n in found.items():
new_text, count = R.repin_decimal(ws.read(rel), old_d, new_d)
if count != n:
raise SealError(f"{rel}: re-pin replaced {count}, expected {n}")
ws.write(rel, new_text)
out["repins"].append({"file": rel, "kind": "decimal", "replacements": count})
doc = root / L.ROPE_HEX_DOC
if doc.is_file():
want = 1 if any(i["ptx"].endswith("/" + asset.ptx_name) and i["sha256"] == old_d.hex() for i in L.window_sealed_bound(root)) else 0
text = ws.read(L.ROPE_HEX_DOC)
new_text, n = R.replace_hex(text, old_d.hex(), new_d.hex())
if n != want:
raise SealError(f"{L.ROPE_HEX_DOC}: old digest of {asset.ptx_name} appears {n} times, expected {want}")
if n:
ws.write(L.ROPE_HEX_DOC, new_text)
out["repins"].append({"file": L.ROPE_HEX_DOC, "kind": "hex", "replacements": n})
# ------------------------------------------------------------------------------------------- main
def main(argv: Optional[List[str]] = None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--ptx-dir", required=True, type=Path, help="compile_assets.py --out directory")
ap.add_argument("--root", type=Path, default=L.REPO, help="tree to patch (default: this checkout)")
ap.add_argument("--write", action="store_true", help="install PTX and patch Rust; default is a dry run")
ap.add_argument("--only", help="comma list of asset ids to seal (default: all ok assets in the manifest)")
ap.add_argument("--allow-fake", action="store_true", help="accept fake-nvcc output (scratch --root only)")
ap.add_argument("--rustfmt", choices=("auto", "never"), default="auto")
ap.add_argument("--no-abi-test-update", action="store_true", help="leave crates/context ptx_abi.rs alone")
ap.add_argument("--manifest-out", type=Path, help="also write the sealed manifest here")
args = ap.parse_args(argv)
root = args.root.resolve()
only = set(filter(None, (args.only or "").split(","))) or None
try:
result, ws = seal(root, args.ptx_dir.resolve(), allow_fake=args.allow_fake, only=only,
rustfmt=args.rustfmt, update_abi_test=not args.no_abi_test_update)
except (SealError, L.PlanError, R.PinError) as error:
print(f"REFUSED: {error}", file=sys.stderr)
return 1
result["mode"] = "write" if args.write else "dry-run"
if args.write:
ws.commit()
result["written"] = True
text = json.dumps(result, indent=2, sort_keys=True) + "\n"
if args.manifest_out:
args.manifest_out.write_text(text, encoding="utf-8")
sys.stdout.write(text)
if not args.write:
print("DRY RUN: nothing was written. Re-run with --write.", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())