#!/usr/bin/env python3 """Unit tests for the GPU bring-up toolkit. Plain unittest: `python3 scripts/gpu-bringup/tests/test_gpu_bringup.py` (pytest also collects it). No GPU, nvcc or network is used; compile tests run scripts/gpu-bringup/fake-nvcc.""" import contextlib import hashlib import io import json import os import re import shutil import subprocess import sys import tempfile import unittest from pathlib import Path HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE.parent)) import bringup_lib as L # noqa: E402 import compile_assets as C # noqa: E402 import rustpins as R # noqa: E402 import seal_pins as S # noqa: E402 import smoke_inventory as SI # noqa: E402 REPO = L.REPO V = R.PinValues(raw_len=1234, ptx_sha256=hashlib.sha256(b"ptx").digest(), source_sha256=hashlib.sha256(b"cu").digest()) def sh(b: bytes) -> str: return hashlib.sha256(b).hexdigest() # --------------------------------------------------------------------------------------- plan parsing class PlanParsing(unittest.TestCase): def test_every_checked_in_plan_loads_and_cu_pins_are_current(self): assets, _ = L.load_all_assets(REPO, "precise") self.assertGreaterEqual(len(assets), 24) for a in assets: status, detail = L.check_cu_pin(REPO, a) self.assertIn(status, ("ok", "unpinned"), detail) def test_groups_cover_all_three_plan_formats_and_rope(self): assets, _ = L.load_all_assets(REPO, "preserve") groups = {a.group for a in assets} self.assertTrue({"additions", "experimental", "window", "rope", "kar"} <= groups) def test_window_new_sources_become_assets_with_pin_targets(self): assets, _ = L.load_all_assets(REPO, None) moe = next(a for a in assets if a.id == "original_verify_window_moe_experts") self.assertEqual(moe.pin_fields, {"original_verify_window_moe.rs": ["EXPERTS.sha"]}) self.assertIn("-Iengine/strata/include", [f"-I{d}" for d in moe.includes]) self.assertNotIn("-Iengine/strata/include", moe.flags) self.assertEqual(len(moe.entries), 16) self.assertEqual(moe.encoding, "include_bytes") gate = next(a for a in assets if a.id == "original_verify_window_qsa_gate") self.assertIn("--use_fast_math", gate.flags) self.assertNotIn("--ftz=false", gate.flags) def test_experimental_plan_is_raw_encoding_with_six_pin_slots(self): assets, _ = L.load_all_assets(REPO, None) exp = [a for a in assets if a.group == "experimental"] self.assertEqual(len(exp), 6) self.assertTrue(all(a.encoding == "concat_include_str" for a in exp)) self.assertEqual(sorted(f for a in exp for v in a.pin_fields.values() for f in v), sorted(f"PINS[{i}].{k}" for i in range(6) for k in ("source_sha256", "ptx_sha256"))) def test_unrecognised_plan_format_is_an_error(self): with tempfile.TemporaryDirectory() as d: p = Path(d) / "cuda-seal-plan-x.json" p.write_text(json.dumps({"schema": 1, "stuff": []})) with self.assertRaises(L.PlanError): L.load_plan_file(p) def test_duplicate_ids_across_plans_are_an_error(self): with tempfile.TemporaryDirectory() as d: root = Path(d) (root / "docs").mkdir() entry = {"cu": "a.cu", "ptx": "x/a.ptx", "flags": ["-ptx"]} for n in ("a", "b"): (root / "docs" / f"cuda-seal-plan-{n}.json").write_text(json.dumps({"assets": [entry]})) with self.assertRaises(L.PlanError): L.load_all_assets(root, None) def test_rope_list_and_abi_are_read_from_the_docs_not_hardcoded(self): flags, incs, sources = L.parse_rope_doc((REPO / L.ROPE_DOC).read_text()) self.assertEqual(sources, ["qsa_prompt_indexer", "qsa_prompt_postops", "qsa_decode_postops", "qsa_prompt_resolver"]) self.assertEqual(flags, ["--ptx", "-std=c++17", "-O3", "-arch=sm_120", "--fmad=true", "--ftz=false"]) self.assertEqual(incs, L.STANDARD_INCLUDES) abi = L.parse_abi_tuples((REPO / L.ABI_SOURCE).read_text()) self.assertEqual(abi["qsa_prompt_resolver.ptx"], {"leleka_qsa_stream_reset": (7, 2), "leleka_qsa_resolve": (10, 1)}) self.assertEqual(abi["qsa_prompt_indexer.ptx"]["qsa_append_blocks"], (13, 5)) def test_rope_variants_differ_only_for_the_two_fast_math_sources(self): precise = {a.id: a for a in L.rope_assets(REPO, "precise")} keep = {a.id: a for a in L.rope_assets(REPO, "preserve")} for name in precise: if name in L.ROPE_FASTMATH_SOURCES: self.assertIn("--use_fast_math", keep[name].flags) self.assertNotIn("--ftz=false", keep[name].flags) self.assertIn("--ftz=false", precise[name].flags) else: self.assertEqual(precise[name].flags, keep[name].flags) self.assertEqual(precise["qsa_prompt_indexer"].params["qsa_append_first"], 11) with self.assertRaises(L.PlanError): L.rope_assets(REPO, "bogus") def test_committed_rope_ptx_were_built_fast_math_for_the_two_sources(self): # evidence behind decision D1 in docs/gpu-bringup.md keep = {a.id: a for a in L.rope_assets(REPO, "preserve")} self.assertGreater(L.committed_fastmath_evidence(REPO, keep["qsa_prompt_indexer"]), 0) self.assertGreater(L.committed_fastmath_evidence(REPO, keep["qsa_decode_postops"]), 0) self.assertEqual(L.committed_fastmath_evidence(REPO, keep["qsa_prompt_resolver"]), 0) # ---------------------------------------------------------------------------------------- pin logic class CuPinLogic(unittest.TestCase): def setUp(self): self.d = tempfile.TemporaryDirectory() self.root = Path(self.d.name) (self.root / "k.cu").write_bytes(b"__global__ void k(){}\n") def tearDown(self): self.d.cleanup() def asset(self, pin): return L.Asset(id="k", cu="k.cu", ptx="k.ptx", flags=["-ptx"], cu_pin=pin) def test_ok_stale_bytes_unpinned_missing(self): data = (self.root / "k.cu").read_bytes() good = {"sha256": sh(data), "bytes": len(data)} self.assertEqual(L.check_cu_pin(self.root, self.asset(good))[0], "ok") self.assertEqual(L.check_cu_pin(self.root, self.asset({"sha256": "0" * 64, "bytes": len(data)}))[0], "stale") self.assertEqual(L.check_cu_pin(self.root, self.asset({"sha256": sh(data), "bytes": 1}))[0], "stale") self.assertEqual(L.check_cu_pin(self.root, self.asset(None))[0], "unpinned") a = self.asset(None) a.cu = "nope.cu" self.assertEqual(L.check_cu_pin(self.root, a)[0], "missing") def test_include_resolution(self): (self.root / "inc").mkdir() (self.root / "inc" / "h.hpp").write_text('#include "deep.hpp"\n') (self.root / "inc" / "deep.hpp").write_text("\n") (self.root / "k.cu").write_text('#include "h.hpp"\n#include "gone.hpp"\n#include \n') a = self.asset(None) a.includes = ["inc"] self.assertEqual(L.resolve_includes(self.root, a), ["gone.hpp (from k.cu)"]) class PolicyLint(unittest.TestCase): def mk(self, flags, policy): return L.Asset(id="x", cu="x.cu", ptx="x.ptx", flags=flags, policy=policy) def test_cases(self): self.assertEqual(L.policy_conflicts(self.mk(["--use_fast_math"], "Original native_qsa fastmath")), []) self.assertEqual(L.policy_conflicts(self.mk([], "Original device.cu; not in the CMake fast-math list")), []) self.assertEqual(L.policy_conflicts(self.mk([], "precise (not in CMake fast-math list)")), []) self.assertTrue(L.policy_conflicts(self.mk(["--use_fast_math"], "precise"))) self.assertTrue(L.policy_conflicts(self.mk([], "fast-math"))) self.assertTrue(L.policy_conflicts(self.mk(["--use_fast_math", "--ftz=false"], ""))) def test_checked_in_plans_have_no_conflicts(self): assets, _ = L.load_all_assets(REPO, "preserve") self.assertEqual([(a.id, L.policy_conflicts(a)) for a in assets if L.policy_conflicts(a)], []) class PtxValidation(unittest.TestCase): def ptx(self, entries=("k",), extra=""): body = ".version 8.7\n.target sm_120\n.address_size 64\n" for e in entries: body += f".visible .entry {e}(\n\t.param .u64 {e}_param_0,\n\t.param .u32 {e}_param_1\n)\n{{\n\tret;\n}}\n" return (body + extra).encode() def asset(self, **kw): return L.Asset(id="x", cu="x.cu", ptx="x.ptx", flags=[], entries=["k"], **kw) def test_accepts_good(self): self.assertEqual(L.validate_ptx(self.ptx(), self.asset()), []) def test_rejections(self): a = self.asset() self.assertTrue(L.validate_ptx(b"", a)) self.assertTrue(any("NUL" in m for m in L.validate_ptx(self.ptx() + b"\0", a))) self.assertTrue(any("ASCII" in m for m in L.validate_ptx(self.ptx() + "é".encode(), a))) self.assertTrue(any("sm_120" in m for m in L.validate_ptx(self.ptx().replace(b"sm_120", b"sm_90"), a))) self.assertTrue(any("UNSEALED" in m for m in L.validate_ptx(self.ptx(extra="// UNSEALED\n"), a))) self.assertTrue(any("missing" in m for m in L.validate_ptx(self.ptx(("other",)), a))) self.assertTrue(any("fake" in m for m in L.validate_ptx(self.ptx(extra="// FAKE-NVCC\n"), a))) self.assertEqual(L.validate_ptx(self.ptx(extra="// FAKE-NVCC\n"), a, allow_fake=True), []) def test_refuses_ptx_built_by_nvcc_13_2_0_or_13_2_1(self): a = self.asset() header = "// Cuda compilation tools, release 13.2, V{}" + chr(10) for build in ("13.2.0", "13.2.1", "13.2.51"): problems = L.validate_ptx(self.ptx(extra=header.format(build)), a) self.assertTrue(any(build in m and "miscompiles" in m for m in problems), (build, problems)) # the pinned and the older toolchains, and a header-less body (fake-nvcc output), stay acceptable for build in ("13.2.86", "13.2.2", "13.0.88", "12.8.93", "13.2.10", "13.2.100"): self.assertEqual(L.validate_ptx(self.ptx(extra=header.format(build)), a), [], build) self.assertEqual(L.validate_ptx(self.ptx(), a), []) def test_every_sealed_ptx_in_the_tree_names_a_good_nvcc(self): seen = 0 for path in sorted((REPO / "crates").rglob("*.ptx")): if "target" in path.parts: continue build = L.nvcc_build_of(path.read_bytes()[:4096].decode("latin-1")) seen += build is not None self.assertNotIn(build, L.BAD_NVCC_BUILDS, str(path)) self.assertGreater(seen, 100) def test_entry_regex_like_the_reference_seal_script(self): text = ".visible .entry a(\n)\n.weak .entry b(\n)\n .entry c(\n)\n// .entry d(\n" self.assertEqual(L.ptx_entries(text), ["a", "b", "c"]) def test_param_counts_and_prefix_counts(self): a = self.asset(params={"k": 2}) self.assertEqual(L.validate_ptx(self.ptx(), a), []) a.params = {"k": 3} self.assertTrue(any("params" in m for m in L.validate_ptx(self.ptx(), a))) b = L.Asset(id="m", cu="m.cu", ptx="m.ptx", flags=[], entry_prefix_counts={"_Z9mul": 2}) self.assertEqual(L.validate_ptx(self.ptx(("_Z9mul_a", "_Z9mul_b")), b), []) self.assertTrue(L.validate_ptx(self.ptx(("_Z9mul_a",)), b)) def test_encodings(self): self.assertEqual(L.stored_bytes(b"abc", "include_bytes"), b"abc\0") self.assertEqual(L.stored_bytes(b"abc", "concat_include_str"), b"abc") self.assertEqual(L.raw_from_stored(b"abc\0"), b"abc") self.assertEqual(L.raw_from_stored(b"abc"), b"abc") with self.assertRaises(L.PlanError): L.stored_bytes(b"x", "weird") def test_derive_entries_drops_macro_names(self): with tempfile.TemporaryDirectory() as d: root = Path(d) (root / "k.cu").write_text('extern "C" __global__ void NAME(int x){}\nextern "C" __global__ void real_k(int x){}\n' 'extern "C" __global__ __launch_bounds__(256) void other_k(int x){}\n') a = L.Asset(id="k", cu="k.cu", ptx="k.ptx", flags=[]) self.assertEqual(L.derive_entries(root, a), ["real_k", "other_k"]) # ------------------------------------------------------------------------------------ rust pin forms PINS_REPEAT = """\ /// doc pub const PINS: [PtxPin; 3] = [PtxPin { source_sha256: [0; 32], ptx_sha256: [0; 32], }; 3]; """ OTHER = "const A: usize = 0;\n" class RustPinForms(unittest.TestCase): def test_ptxpin_array_repeat_form_expands_and_reads_back(self): t = R.apply_field(PINS_REPEAT, "PINS[1].ptx_sha256", V) self.assertTrue(R.read_field(t, "PINS[1].ptx_sha256", V)) self.assertEqual(R.read_ptxpin(t, "PINS", 0, "ptx_sha256"), bytes(32)) self.assertEqual(R.read_ptxpin(t, "PINS", 2, "source_sha256"), bytes(32)) t = R.apply_field(t, "PINS[1].source_sha256", V) self.assertEqual(R.read_ptxpin(t, "PINS", 1, "source_sha256"), V.source_sha256) self.assertEqual(t.count("PtxPin {"), 3) with self.assertRaises(R.PinError): R.apply_field(t, "PINS[3].ptx_sha256", V) def test_ptxpin_single_struct(self): src = "pub const P: PtxPin = PtxPin {\n source_sha256: [0; 32],\n ptx_sha256: [0; 32],\n};\n" t = R.apply_field(R.apply_field(src, "P.source_sha256", V), "P.ptx_sha256", V) self.assertTrue(R.read_field(t, "P.source_sha256", V) and R.read_field(t, "P.ptx_sha256", V)) for line in t.splitlines(): self.assertLessEqual(len(line), 100) def test_asset_spec_sha(self): src = 'static E: AssetSpec = AssetSpec {\n name: "x.ptx",\n ptx: include_bytes!("x.ptx"),\n sha: [0; 32],\n entries: &[],\n};\n' t = R.apply_field(src, "E.sha", V) self.assertTrue(R.read_field(t, "E.sha", V)) self.assertEqual(t.count("sha:"), 1) self.assertIn('name: "x.ptx"', t) # already sealed with the unspaced style used in the window files keeps its style again = R.apply_field(t.replace(", ", ","), "E.sha", V) self.assertNotIn(", ", again.split("sha:")[1].split("]")[0]) def test_option_tuple_array_len_includes_the_nul(self): src = "const SEALED: [Option<(usize, [u8; 32])>; 3] = [None, None, None];\n" t = R.apply_field(src, "SEALED[2]", V) self.assertEqual(R.read_pin_array(t, "SEALED", 2), (V.raw_len + 1, V.ptx_sha256)) self.assertIsNone(R.read_pin_array(t, "SEALED", 0)) t = R.apply_field(t, "SEALED[0]", V) self.assertEqual(R.read_pin_array(t, "SEALED", 0)[0], 1235) def test_plain_const_types(self): for decl, spec, want in [ ("const L: usize = 0;", "L", 1234), ("const L: Option = None;", "L", 1234), ("const D: [u8; 32] = [0; 32];", "D", V.ptx_sha256), ("const D: Option<[u8; 32]> = None;", "D", V.ptx_sha256), ("const T: Option<(usize, [u8; 32])> = None;", "T", (1235, V.ptx_sha256)), ]: t = R.apply_field(decl + "\n", spec, V) self.assertEqual(R.read_plain(t, spec), want, decl) self.assertTrue(R.read_field(t, spec, V)) def test_option_slice_assets_are_refused_not_guessed(self): with self.assertRaises(R.PinError): R.apply_field("const ASSET: Option<&[u8]> = None;\n", "ASSET", V) def test_exactly_one_declaration_or_refuse(self): two = OTHER + "mod t {\n const A: usize = 0;\n}\n" with self.assertRaises(R.PinError): R.apply_field(two, "A", V) with self.assertRaises(R.PinError): R.apply_field(OTHER, "MISSING", V) with self.assertRaises(R.PinError): R.apply_field(OTHER, "A.bogus", V) def test_strings_and_comments_do_not_confuse_the_scanner(self): src = 'const X: usize = 0; // trailing; semicolon\nconst S: &str = "a;b";\nconst PINS: [PtxPin; 1] = [PtxPin { source_sha256: [0; 32], ptx_sha256: [0; 32] }; 1];\n' t = R.apply_field(src, "X", V) self.assertIn("const X: usize = 1234;", t) self.assertIn('"a;b"', t) def test_real_repo_declarations_patch_and_read_back(self): src = REPO / "crates/cuda-driver/src" cases = [ ("experimental.rs", [f"PINS[{i}].{k}" for i in range(6) for k in ("source_sha256", "ptx_sha256")]), ("kar_decode_levels.rs", ["KAR_DECODE_LEVELS_PIN.source_sha256", "KAR_DECODE_LEVELS_PIN.ptx_sha256"]), ("original_verify_window_moe.rs", ["EXPERTS.sha"]), ("original_verify_window_qsa.rs", ["GATE.sha"]), ("mmq_original_group.rs", ["SEALED[0]", "SEALED[1]", "SEALED[2]"]), ] for name, specs in cases: t = (src / name).read_text() for s in specs: t = R.apply_field(t, s, V) for s in specs: self.assertTrue(R.read_field(t, s, V), (name, s)) def test_already_sealed_consumers_are_recognised_as_resealable(self): t = (REPO / "crates/cuda-driver/src/gdn_fused_t1.rs").read_text() t2 = R.apply_field(R.apply_field(t, "FUSED_PTX_LEN", V), "FUSED_PTX_SHA256", V) self.assertEqual(R.read_plain(t2, "FUSED_PTX_LEN"), 1234) self.assertNotEqual(t, t2) def test_repin_decimal_inline_and_wrapped(self): old = hashlib.sha256(b"old").digest() new = V.ptx_sha256 inline = "x: [" + ",".join(map(str, old)) + "],\n" out, n = R.repin_decimal(inline, old, new) self.assertEqual(n, 1) self.assertEqual(out, "x: [" + ",".join(map(str, new)) + "],\n") wrapped = " sha: " + R.render_digest(old, " ", wrapped=True) + ",\n" out, n = R.repin_decimal(wrapped, old, new) self.assertEqual(n, 1) self.assertEqual(R.find_decimal_pins(out, new).__len__(), 1) self.assertEqual(R.repin_decimal("nothing", old, new), ("nothing", 0)) def test_placeholder_test_finder(self): t = '#[test]\nfn a_placeholder_check() {\n assert_eq!(P.sha, [0; 32]);\n}\n#[test]\nfn fine() {\n assert!(true);\n}\n' self.assertEqual(R.placeholder_tests(t), ["a_placeholder_check"]) # --------------------------------------------------------------- end-to-end on a miniature repository def mini_repo(root: Path, cu_pin=True): src = root / "crates/cuda-driver/src" src.mkdir(parents=True) (root / "docs").mkdir() (root / "deploy").mkdir() (root / "deploy/cuda-toolkit.lock.json").write_text(json.dumps({"components": [{"component": "cuda_nvcc", "version": "13.2.86"}]})) cu = 'extern "C" __global__ void leleka_a(int x){}\nextern "C" __global__ void leleka_b(int x){}\n' (src / "a.cu").write_text(cu) (src / "b.cu").write_text(cu.replace("leleka_a", "leleka_c").replace("leleka_b", "leleka_d")) (src / "a.ptx").write_text("// UNSEALED placeholder\n") (src / "b.ptx").write_text("// UNSEALED placeholder\n") pin_a = {"sha256": sh(cu.encode()), "bytes": len(cu)} if cu_pin else {"sha256": "0" * 64, "bytes": 1} plan = {"schema": 1, "assets": [ {"cu": "crates/cuda-driver/src/a.cu", "cu_pin": pin_a, "ptx": "crates/cuda-driver/src/a.ptx", "flags": ["-ptx", "-O3", "-arch=sm_120"], "policy": "precise", "entries": ["leleka_a", "leleka_b"], "encoding": "include_bytes", "rust_fields_to_fill": {"cons.rs": ["A_LEN", "A_SHA"]}}, {"cu": "crates/cuda-driver/src/b.cu", "ptx": "crates/cuda-driver/src/b.ptx", "flags": ["-ptx", "--use_fast_math"], "policy": "fastmath", "encoding": "concat_include_str", "rust_fields_to_fill": {"cons.rs": ["B_PIN.source_sha256", "B_PIN.ptx_sha256"]}}, ]} (root / "docs/cuda-seal-plan-mini.json").write_text(json.dumps(plan)) (src / "cons.rs").write_text( "const A_LEN: usize = 0;\nconst A_SHA: [u8; 32] = [0; 32];\n" "pub const B_PIN: PtxPin = PtxPin {\n source_sha256: [0; 32],\n ptx_sha256: [0; 32],\n};\n") def run_quiet(fn, *a): out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = fn(*a) return code, out.getvalue(), err.getvalue() class EndToEnd(unittest.TestCase): def setUp(self): self.d = tempfile.TemporaryDirectory() self.root = Path(self.d.name) / "repo" self.out = Path(self.d.name) / "ptx" mini_repo(self.root) def tearDown(self): self.d.cleanup() def compile(self, *extra): return run_quiet(C.main, ["--root", str(self.root), "--fake-nvcc", "--no-rope", "--out", str(self.out), *extra]) def test_dry_run_prints_commands_and_runs_nothing(self): code, out, _ = run_quiet(C.main, ["--root", str(self.root), "--dry-run", "--no-rope"]) self.assertEqual(code, 0) self.assertIn("nvcc -ptx -O3 -arch=sm_120 crates/cuda-driver/src/a.cu -o", out) self.assertIn("--use_fast_math crates/cuda-driver/src/b.cu", out) self.assertFalse(self.out.exists()) def test_rope_flags_are_mandatory_when_rope_is_selected(self): code, _, err = run_quiet(C.main, ["--root", str(REPO), "--dry-run"]) self.assertEqual(code, 2) self.assertIn("--rope-flags", err) def test_fake_compile_writes_ptx_and_manifest(self): code, _, _ = self.compile() self.assertEqual(code, 0) m = json.loads((self.out / "build-manifest.json").read_text()) self.assertTrue(m["fake"]) self.assertEqual([a["id"] for a in m["assets"]], ["a", "b"]) self.assertTrue(all(a["status"] == "ok" and a["cu_sha256"] for a in m["assets"])) text = (self.out / "a.ptx").read_text() self.assertIn(".entry leleka_a(", text) self.assertIn("FAKE-NVCC", text) self.assertEqual(code, 0) # a second run into the same directory is refused self.assertEqual(self.compile()[0], 2) def test_stale_cu_pin_is_refused_before_nvcc_runs(self): shutil.rmtree(self.root) mini_repo(self.root, cu_pin=False) code, out, _ = self.compile() self.assertEqual(code, 1) self.assertIn("refusing", out) m = json.loads((self.out / "build-manifest.json").read_text()) bad = next(a for a in m["assets"] if a["id"] == "a") self.assertEqual(bad["status"], "failed") self.assertNotIn("command", bad) self.assertEqual(next(a for a in m["assets"] if a["id"] == "b")["status"], "ok") self.assertFalse((self.out / "a.ptx").exists()) def test_missing_export_fails_validation_and_keeps_a_rejected_copy(self): import os os.environ["FAKE_NVCC_ENTRIES"] = "leleka_a" # the "compiler" forgets leleka_b try: code, out, _ = self.compile() finally: del os.environ["FAKE_NVCC_ENTRIES"] self.assertEqual(code, 1) self.assertIn("leleka_b", out) self.assertTrue((self.out / "a.ptx.rejected").exists()) def test_nvcc_failure_is_reported_and_other_assets_continue(self): import os os.environ["FAKE_NVCC_FAIL"] = "a.cu" try: code, out, _ = self.compile() finally: del os.environ["FAKE_NVCC_FAIL"] self.assertEqual(code, 1) self.assertIn("nvcc exit 2", out) self.assertTrue((self.out / "b.ptx").exists()) def test_seal_dry_run_then_write(self): self.assertEqual(self.compile()[0], 0) base = ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--rustfmt", "never"] code, out, _ = run_quiet(S.main, base) self.assertEqual(code, 0) man = json.loads(out) self.assertEqual(man["mode"], "dry-run") self.assertEqual((self.root / "crates/cuda-driver/src/a.ptx").read_text(), "// UNSEALED placeholder\n") code, out, _ = run_quiet(S.main, base + ["--write"]) self.assertEqual(code, 0) man = json.loads(out) a = next(x for x in man["assets"] if x["id"] == "a") b = next(x for x in man["assets"] if x["id"] == "b") ptx_a = (self.root / "crates/cuda-driver/src/a.ptx").read_bytes() ptx_b = (self.root / "crates/cuda-driver/src/b.ptx").read_bytes() self.assertTrue(ptx_a.endswith(b"\0") and ptx_a.count(b"\0") == 1) # include_bytes self.assertFalse(ptx_b.endswith(b"\0")) # concat_include_str self.assertEqual(a["raw_sha256"], sh(ptx_a[:-1])) self.assertEqual(b["raw_sha256"], sh(ptx_b)) cons = (self.root / "crates/cuda-driver/src/cons.rs").read_text() self.assertTrue(R.read_field(cons, "A_LEN", R.PinValues(len(ptx_a) - 1, hashlib.sha256(ptx_a[:-1]).digest(), b""))) self.assertEqual(R.read_plain(cons, "A_LEN"), len(ptx_a) - 1) self.assertEqual(R.read_ptxpin(cons, "B_PIN", None, "ptx_sha256"), hashlib.sha256(ptx_b).digest()) cu_b = (self.root / "crates/cuda-driver/src/b.cu").read_bytes() self.assertEqual(R.read_ptxpin(cons, "B_PIN", None, "source_sha256"), hashlib.sha256(cu_b).digest()) self.assertEqual(sorted(man["touched_files"]), ["crates/cuda-driver/src/a.ptx", "crates/cuda-driver/src/b.ptx", "crates/cuda-driver/src/cons.rs"]) self.assertEqual(man["unsealed_placeholders_remaining"], []) def test_fake_output_is_refused_in_the_real_checkout_and_without_the_flag(self): self.assertEqual(self.compile()[0], 0) code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root)]) self.assertEqual(code, 1) self.assertIn("fake-nvcc", err) code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--allow-fake"]) # root = this checkout self.assertEqual(code, 1) self.assertIn("scratch", err) def test_cu_changed_after_compile_is_refused(self): self.assertEqual(self.compile()[0], 0) (self.root / "crates/cuda-driver/src/b.cu").write_text('extern "C" __global__ void leleka_c(int x){} // edited\n') code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake"]) self.assertEqual(code, 1) self.assertIn("changed after it was compiled", err) def test_stale_plan_pin_at_seal_time_is_refused(self): self.assertEqual(self.compile()[0], 0) plan = json.loads((self.root / "docs/cuda-seal-plan-mini.json").read_text()) plan["assets"][0]["cu_pin"]["sha256"] = "1" * 64 (self.root / "docs/cuda-seal-plan-mini.json").write_text(json.dumps(plan)) code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake"]) self.assertEqual(code, 1) self.assertIn("stale source", err) def test_tampered_ptx_is_refused(self): self.assertEqual(self.compile()[0], 0) with open(self.out / "a.ptx", "a") as f: f.write("// tampered\n") code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake"]) self.assertEqual(code, 1) self.assertIn("does not match the manifest", err) def test_a_pin_field_that_matches_two_declarations_refuses_and_writes_nothing(self): self.assertEqual(self.compile()[0], 0) cons = self.root / "crates/cuda-driver/src/cons.rs" cons.write_text(cons.read_text() + "mod t {\n const A_LEN: usize = 0;\n}\n") before = cons.read_text() code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--write"]) self.assertEqual(code, 1) self.assertIn("exactly one declaration", err) self.assertEqual(cons.read_text(), before) self.assertEqual((self.root / "crates/cuda-driver/src/a.ptx").read_text(), "// UNSEALED placeholder\n") def test_idempotent_reseal_of_identical_output(self): self.assertEqual(self.compile()[0], 0) base = ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--rustfmt", "never", "--write"] self.assertEqual(run_quiet(S.main, base)[0], 0) snap = (self.root / "crates/cuda-driver/src/cons.rs").read_text() self.assertEqual(run_quiet(S.main, base)[0], 0) self.assertEqual((self.root / "crates/cuda-driver/src/cons.rs").read_text(), snap) def test_flag_override_is_recorded_and_checked_by_the_sealer(self): code, out, _ = self.compile("--flag-override", "b:-clearly-not-there") self.assertEqual(code, 2) shutil.rmtree(self.out, ignore_errors=True) code, out, err = self.compile("--flag-override", "a:+--use_fast_math") self.assertEqual(code, 0, out + err) m = json.loads((self.out / "build-manifest.json").read_text()) self.assertEqual(m["flag_overrides"], ["a:+--use_fast_math"]) rec = next(r for r in m["assets"] if r["id"] == "a") self.assertIn("--use_fast_math", rec["flags"]) self.assertEqual(rec["flag_overrides"], ["a:+--use_fast_math"]) base = ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--rustfmt", "never"] self.assertEqual(run_quiet(S.main, base)[0], 0) # the sealer re-applies the recorded overrides man = json.loads((self.out / "build-manifest.json").read_text()) man["flag_overrides"] = [] (self.out / "build-manifest.json").write_text(json.dumps(man)) code, _, err = run_quiet(S.main, base) self.assertEqual(code, 1) self.assertIn("compiled with flags", err) def test_contradictory_override_is_stopped_by_the_lint(self): code, out, _ = self.compile("--flag-override", "b:+--ftz=false") self.assertEqual(code, 1) self.assertIn("contradicts itself", out) def test_atomic_groups_must_move_together(self): plan = json.loads((self.root / "docs/cuda-seal-plan-mini.json").read_text()) for a in plan["assets"]: a["atomic_group"] = "g" (self.root / "docs/cuda-seal-plan-mini.json").write_text(json.dumps(plan)) self.assertEqual(self.compile()[0], 0) code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--only", "a"]) self.assertEqual(code, 1) self.assertIn("atomic group", err) class RealTreeFakeSeal(unittest.TestCase): """The whole checked-in plan set against a scratch copy: every field of every plan must patch and read back.""" def test_full_fake_pipeline_on_a_scratch_copy(self): with tempfile.TemporaryDirectory() as d: scratch = Path(d) / "tree" ignore = shutil.ignore_patterns(".git", "target", "*.gguf") for sub in ("crates", "docs", "deploy", "engine/strata/include", "engine/strata/third_party", "scripts/gpu-bringup"): shutil.copytree(REPO / sub, scratch / sub, ignore=ignore) out = Path(d) / "ptx" code, _, err = run_quiet(C.main, ["--root", str(scratch), "--fake-nvcc", "--out", str(out), "--rope-flags", "preserve", "--include-optional"]) self.assertEqual(code, 0, err) code, text, err = run_quiet(S.main, ["--ptx-dir", str(out), "--root", str(scratch), "--allow-fake", "--write", "--rustfmt", "never"]) self.assertEqual(code, 0, err) man = json.loads(text) self.assertEqual(len(man["assets"]), 33) self.assertEqual(man["min_driver_required"], "580.65.06") # the six fast-math reseals were re-pinned where the old digests lived, and the PLE length slot updated by = {a["id"]: a for a in man["assets"]} resealed = [a for a in man["assets"] if a["group"] == "reseal-fastmath"] self.assertEqual(len(resealed), 6) self.assertTrue(all("--use_fast_math" in a["flags"] and "--ftz=false" not in a["flags"] for a in resealed)) self.assertEqual(sum(r["replacements"] for a in resealed for r in a["repins"] if r.get("kind") == "decimal"), 7) ple = by["ple_native_batch"] queue = (scratch / "crates/cuda-driver/src/ple_batch_queue.rs").read_text() self.assertEqual(R.read_plain(queue, "PTX_BYTES"), ple["raw_bytes"]) self.assertEqual(R.read_plain(queue, "PTX_SHA256"), bytes.fromhex(ple["raw_sha256"])) gr = (scratch / "crates/cuda-driver/src/original_verify_window_gr.rs").read_text() self.assertEqual(len(R.find_decimal_pins(gr, bytes.fromhex(ple["raw_sha256"]))), 1) # idempotent on the second run of identical output code, _, err = run_quiet(S.main, ["--ptx-dir", str(out), "--root", str(scratch), "--allow-fake", "--write", "--rustfmt", "never"]) self.assertEqual(code, 0, err) abi = (scratch / L.ABI_SOURCE).read_text() self.assertIn("state == AbiState::Extended,", abi) # ---------------------------------------------------------------------------------- smoke inventory class SmokeInventory(unittest.TestCase): def test_every_real_ignore_attribute_is_found_and_comments_are_not(self): smokes = SI.scan(REPO) raw = 0 for p in (REPO / "crates").rglob("*.rs"): if "target" in p.parts: continue raw += len(re.findall(r"(?m)^[ \t]*#\[ignore", p.read_text(errors="replace"))) self.assertEqual(len(smokes), raw) self.assertGreaterEqual(len(smokes), 100) self.assertFalse([s for s in smokes if s.file.endswith(("experimental.rs", "kar_decode_levels.rs"))]) def test_gates_values_and_classes_on_known_tests(self): by = {s.name: s for s in SI.scan(REPO)} win = by["sealed_window_assets_load_on_the_device_and_export_every_named_entry"] self.assertEqual(win.gates, {"LELEKA_VERIFY_WINDOW_GPU": "yes"}) self.assertEqual(win.klass, "device") basic = by["installed_driver_fixed_kernels"] self.assertEqual(basic.gates, {"LELEKA_CUDA_REAL_GPU": "1"}) self.assertEqual(by["installed_driver_q5_numeric_refusals"].klass, "device") self.assertEqual(by["installed_driver_q5_native_parity"].klass, "assets") self.assertEqual(by["isolated_q5_protocol_matrix"].klass, "mock") self.assertEqual(by["pinned_artifact_two_tokens_finish_all_layers_and_commit_state"].klass if "pinned_artifact_two_tokens_finish_all_layers_and_commit_state" in by else "assets", "assets") self.assertEqual(by["actual_expert215_native_resident_gu_and_same_source_down_diagnostic"].klass, "assets") self.assertEqual(by["experimental_gpu_fwht256_matches_cpu"].gates, {}) def test_every_smoke_lands_in_a_declared_group_and_dependencies_precede(self): data = SI.load_groups() smokes = SI.scan(REPO) SI.assign(smokes, data) declared = {g["name"] for g in data["groups"]} | {data["asset_group"], data["mock_group"]} self.assertEqual({s.group for s in smokes} - declared, set()) self.assertEqual([s for s in smokes if s.group == data["fallback_group"]], [], "new smokes need a home in smoke-groups.json") self.assertEqual(SI.unique_filters(smokes), []) order = SI.select_order(data, None, [], False) for g in data["groups"]: for d in g["depends_on"]: self.assertLess(order.index(d), order.index(g["name"])) def test_selection_pulls_in_dependencies_and_guards_assets(self): data = SI.load_groups() self.assertEqual(SI.select_order(data, ["runtime-gr"], [], False), ["driver-basic", "transport", "gr", "runtime-gr"]) with self.assertRaises(SystemExit): SI.select_order(data, ["model-assets"], [], False) self.assertNotIn("model-assets", SI.select_order(data, None, [], False)) self.assertIn("model-assets", SI.select_order(data, None, [], True)) def test_doc_table_is_current(self): doc = REPO / "docs/gpu-bringup.md" if not doc.exists(): self.skipTest("docs/gpu-bringup.md not written yet") smokes = SI.scan(REPO) SI.assign(smokes, SI.load_groups()) text = doc.read_text() start, end = text.index(SI.TABLE_START) + len(SI.TABLE_START), text.index(SI.TABLE_END) self.assertEqual(text[start:end].strip("\n"), SI.emit_table(smokes, markdown=True), "run: python3 scripts/gpu-bringup/smoke_inventory.py --update-doc docs/gpu-bringup.md") def test_synthetic_tree(self): with tempfile.TemporaryDirectory() as d: src = Path(d) / "crates/cuda-driver/src" src.mkdir(parents=True) lines = [ 'const ENABLE: &str = "LELEKA_X_GPU";', '/// docs mention #[ignore] and "LELEKA_NOT_A_GATE"', '#[test]', '#[ignore = "Root-only"]', 'fn a_smoke() {', ' assert_eq!(std::env::var(ENABLE).as_deref(), Ok("yes"));', '}', '#[test]', '#[ignore]', 'fn a_smoke_longer() {', ' let _ = std::env::var("LELEKA_Y_SHARD0");', ' assert_eq!(std::env::var("LELEKA_Y_RUN_Z").as_deref(), Ok("1"));', '}', ] (src / "x_gpu.rs").write_text("\n".join(lines) + "\n") smokes = SI.scan(Path(d)) self.assertEqual([s.name for s in smokes], ["a_smoke", "a_smoke_longer"]) self.assertEqual(smokes[0].gates, {"LELEKA_X_GPU": "yes"}) self.assertEqual(smokes[1].gates, {"LELEKA_Y_RUN_Z": "1"}) self.assertEqual(smokes[1].klass, "assets") self.assertEqual(smokes[0].expected, 2) # the cargo filter "a_smoke" also matches a_smoke_longer STUB_CARGO = """#!/usr/bin/env bash name="${@: -1}" echo "running 1 test" if [[ ",${STUB_FAIL:-}," == *",$name,"* ]]; then echo "test $name ... FAILED"; echo "test result: FAILED. 0 passed; 1 failed; 0 ignored"; exit 101; fi if [[ ",${STUB_ZERO:-}," == *",$name,"* ]]; then echo "test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 90 filtered out"; exit 0; fi echo "test $name ... ok"; echo "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 90 filtered out" """ STUB_SMI = """#!/usr/bin/env bash case "$*" in *query-gpu=driver_version\\ *) echo "${STUB_DRIVER:-595.91.07}" ;; *query-compute-apps*) [[ -n "${STUB_BUSY:-}" ]] && echo "4242, strata, 1000 MiB" ;; *memory.free*) echo "${STUB_FREE:-32000}" ;; *query-gpu*) echo "2026/10/14 20:00:00.000, NVIDIA GeForce RTX 5090, 595.91, 100 MiB, 32607 MiB, 40, 30.0 W, 210 MHz, 405 MHz, 0 %" ;; *) echo "nvidia-smi -q (stub)" ;; esac """ class RunSmokesScript(unittest.TestCase): script = HERE.parent / "run_gpu_smokes.sh" def setUp(self): self.d = tempfile.TemporaryDirectory() self.bin = Path(self.d.name) / "bin" self.bin.mkdir() for name, body in (("cargo", STUB_CARGO), ("nvidia-smi", STUB_SMI)): (self.bin / name).write_text(body) (self.bin / name).chmod(0o755) self.run_dir = Path(self.d.name) / "run" def tearDown(self): self.d.cleanup() def run_script(self, *args, **env): e = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", SMOKES_ALLOW_NON_LINUX="1", **env) return subprocess.run([str(self.script), *args], capture_output=True, text=True, env=e, cwd=str(REPO)) def results(self): rows = [l.split("\t") for l in (self.run_dir / "results.tsv").read_text().splitlines()[1:]] return {r[2]: r[3] for r in rows} def status(self, g): return (self.run_dir / "status" / g).read_text().strip() def test_plan_mode_prints_commands_and_does_not_need_a_gpu(self): p = self.run_script("--plan", "--groups", "seal-loads") self.assertEqual(p.returncode, 0, p.stderr) self.assertIn("LELEKA_VERIFY_WINDOW_GPU=yes cargo test --locked -p leleka-cuda-driver --features cuda-driver --lib", p.stdout) self.assertIn("# dependency order: driver-basic seal-loads", p.stdout) def test_all_pass(self): p = self.run_script("--run", "--run-dir", str(self.run_dir)) self.assertEqual(p.returncode, 0, p.stdout + p.stderr) self.assertEqual(set(self.results().values()), {"PASS"}) self.assertTrue((self.run_dir / "nvidia-smi.before.txt").exists() and (self.run_dir / "nvidia-smi.after.txt").exists()) self.assertIn("# group gr start", (self.run_dir / "gpu-timeline.csv").read_text()) self.assertNotIn("model-assets", p.stdout) # never started by default def test_failure_stops_its_group_skips_dependents_and_continues_independent_groups(self): p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_FAIL="fixed_down_pack_matches_original_upload_and_refuses_before_copy") self.assertEqual(p.returncode, 1) r = self.results() self.assertTrue(r["fixed_down_pack_matches_original_upload_and_refuses_before_copy"].startswith("FAIL")) self.assertTrue(r["complete_selected_matrices_match_legacy_64_row_bits"].startswith("PASS")) # before it in the group self.assertTrue(r["prepared_routed_gate_up_reuses_exact_native_q8_and_refuses_invalid_owners"].startswith("NOT-RUN")) self.assertEqual(self.status("transport"), "FAIL") self.assertEqual(self.status("gr"), "SKIPPED-DEP") self.assertEqual(self.status("runtime-gr"), "SKIPPED-DEP") self.assertEqual(self.status("seal-loads"), "PASS") # independent of transport self.assertEqual(self.status("new-pins"), "PASS") def test_a_filter_that_matches_nothing_is_a_failure(self): p = self.run_script("--run", "--run-dir", str(self.run_dir), "--groups", "driver-basic", STUB_ZERO="installed_driver_fixed_kernels") self.assertEqual(p.returncode, 1) self.assertIn("filter matched nothing", self.results()["installed_driver_fixed_kernels"]) def test_first_group_failure_skips_everything_after(self): p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_FAIL="installed_driver_fixed_kernels") self.assertEqual(p.returncode, 1) self.assertEqual(self.status("driver-basic"), "FAIL") self.assertEqual({self.status(g) for g in ("seal-loads", "new-pins", "transport", "gr")}, {"SKIPPED-DEP"}) def test_old_driver_is_refused_because_the_tree_holds_ptx_isa_9_0(self): p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_DRIVER="575.28") self.assertEqual(p.returncode, 3) self.assertIn("ISA 9.0", p.stdout) self.assertIn("too old", p.stdout) self.assertFalse(self.run_dir.exists()) def test_busy_gpu_and_low_vram_are_refused_without_touching_anything(self): p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_BUSY="1") self.assertEqual(p.returncode, 3) self.assertIn("other processes hold the GPU", p.stderr) self.assertFalse(self.run_dir.exists()) p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_FREE="100") self.assertEqual(p.returncode, 3) def test_model_assets_need_the_flag_and_the_caller_supplied_env(self): p = self.run_script("--run", "--run-dir", str(self.run_dir), "--groups", "model-assets") self.assertNotEqual(p.returncode, 0) self.assertFalse(self.run_dir.exists()) p = self.run_script("--run", "--run-dir", str(self.run_dir), "--groups", "model-assets", "--allow-model-runs") self.assertEqual(p.returncode, 0, p.stdout + p.stderr) self.assertIn("skipped", p.stdout) self.assertTrue(all(v.startswith("SKIPPED") for v in self.results().values())) def test_existing_run_dir_is_never_reused(self): self.run_dir.mkdir() p = self.run_script("--run", "--run-dir", str(self.run_dir)) self.assertEqual(p.returncode, 2) STUB_SSH = """#!/usr/bin/env bash # records the remote command (and stdin size) instead of connecting anywhere shift_args=() for a in "$@"; do case "$a" in -o) skip=1 ;; *) if [[ "${skip:-}" == 1 ]]; then skip=0; else shift_args+=("$a"); fi ;; esac; done host="${shift_args[0]}"; remote="${shift_args[*]:1}" printf '%s\t%s\n' "$host" "$remote" >> "$STUB_LOG" case "$remote" in test\\ -e*SEALED-MANIFEST.json) [[ -n "${STUB_SEALED:-}" ]] ;; cat\\ *SEALED-MANIFEST.json) cat "$STUB_MANIFEST" ;; test\\ -d*) exit 1 ;; "bash -s") cat > "$STUB_LOG.script"; echo "BUILD OK" ;; cat\\ \\>*) cat > /dev/null ;; *) ;; esac """ STUB_RSYNC = """#!/usr/bin/env bash printf '%s\n' "$*" >> "$STUB_LOG.rsync" for a in "$@"; do case "$a" in --files-from=*) cp "${a#--files-from=}" "$STUB_LOG.filesfrom" ;; esac; done """ class DriverIsaChecks(unittest.TestCase): def test_table_and_checks(self): self.assertEqual(L.min_driver_for(["8.7", "9.0"]), ("9.0", "580.65.06")) self.assertEqual(L.driver_ok("595.91.07", ["8.7", "9.0"])[0], True) self.assertEqual(L.driver_ok("580.65.06", ["9.0"])[0], True) self.assertEqual(L.driver_ok("580.65.05", ["9.0"])[0], False) self.assertEqual(L.driver_ok("570.26", ["8.7"])[0], True) with self.assertRaises(L.PlanError): L.min_driver_for(["9.9"]) def test_the_tree_really_mixes_8_7_and_9_0(self): inv = L.isa_inventory(REPO) self.assertIn("8.7", inv) self.assertIn("9.0", inv) def test_cli_exit_codes(self): code, out, _ = run_quiet(C.main, ["--isa-inventory", "--driver-check", "--driver-version", "575.0"]) self.assertEqual(code, 1) self.assertIn("too old", out) self.assertEqual(run_quiet(C.main, ["--isa-inventory", "--driver-check", "--driver-version", "595.91.07"])[0], 0) class RemoteSyncScript(unittest.TestCase): """remote_sync.sh against stub ssh/rsync: argument construction and the safety refusals, no network.""" def setUp(self): self.d = tempfile.TemporaryDirectory() root = Path(self.d.name) self.repo = root / "repo" (self.repo / "scripts/gpu-bringup").mkdir(parents=True) shutil.copy(HERE.parent / "remote_sync.sh", self.repo / "scripts/gpu-bringup/remote_sync.sh") (self.repo / "tracked.txt").write_text("x\n") env = dict(os.environ, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@t", GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@t") for cmd in (["init", "-q"], ["add", "-A"], ["commit", "-q", "-m", "x"]): subprocess.run(["git", "-C", str(self.repo), *cmd], check=True, env=env, capture_output=True) self.bin = root / "bin" self.bin.mkdir() for name, body in (("ssh", STUB_SSH), ("rsync", STUB_RSYNC)): (self.bin / name).write_text(body) (self.bin / name).chmod(0o755) self.log = root / "stub.log" self.manifest = root / "manifest.json" self.manifest.write_text(json.dumps({"created_utc": "t", "mode": "write", "touched_files": ["crates/a.ptx", "docs/x.json"]})) def tearDown(self): self.d.cleanup() def run_sync(self, *args, **env): e = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", STUB_LOG=str(self.log), STUB_MANIFEST=str(self.manifest), **env) return subprocess.run([str(self.repo / "scripts/gpu-bringup/remote_sync.sh"), *args, "--host", "h", "--remote-dir", "~/work/x"], capture_output=True, text=True, env=e) def rsync_calls(self): p = Path(str(self.log) + ".rsync") return p.read_text().splitlines() if p.exists() else [] def test_dry_run_sync_uses_rsync_n_with_the_excludes_and_never_deletes(self): p = self.run_sync("sync", "--dry-run") self.assertEqual(p.returncode, 0, p.stderr) (call,) = self.rsync_calls() for needle in (" -n", "--exclude .git", "--exclude target", "--exclude *.gguf", "--max-size=200m", "h:~/work/x/"): self.assertIn(needle, call) self.assertNotIn("--delete", call) self.assertFalse((Path(str(self.log) + ".script")).exists()) def test_real_sync_records_the_head_and_creates_only_the_dedicated_dir(self): p = self.run_sync("sync") self.assertEqual(p.returncode, 0, p.stderr) log = self.log.read_text() self.assertIn("mkdir -p work/x", log) self.assertIn(".synced-from-head", log) def test_unpulled_sealed_files_block_a_second_sync(self): p = self.run_sync("sync", STUB_SEALED="1") self.assertEqual(p.returncode, 1) self.assertIn("pull-sealed", p.stderr) self.assertEqual(self.rsync_calls(), []) p = self.run_sync("sync", "--force-overwrite-sealed", STUB_SEALED="1") self.assertEqual(p.returncode, 0, p.stderr) def test_dirty_tracked_tree_is_refused_unless_allowed(self): (self.repo / "tracked.txt").write_text("changed\n") p = self.run_sync("sync", "--dry-run") self.assertEqual(p.returncode, 1) self.assertIn("commit first", p.stderr) self.assertEqual(self.run_sync("sync", "--dry-run", "--allow-dirty").returncode, 0) def test_remote_dir_must_be_a_dedicated_dir_below_home(self): for bad in ("/", "~", "~/", "/etc/x", "~/../x", "/home/para", "~/a b", "~/a;b", "~/$(x)"): e = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", STUB_LOG=str(self.log)) p = subprocess.run([str(self.repo / "scripts/gpu-bringup/remote_sync.sh"), "sync", "--dry-run", "--host", "h", "--remote-dir", bad], capture_output=True, text=True, env=e) self.assertEqual(p.returncode, 2, (bad, p.stderr)) def test_build_script_has_the_three_binaries_and_the_no_run_test_builds(self): p = self.run_sync("build", "--jobs", "4") self.assertEqual(p.returncode, 0, p.stderr) script = Path(str(self.log) + ".script").read_text() self.assertIn("cargo build --release --locked -j 4 -p strata-desktop-core --bin leleka-cli --bin leleka-daemon --bin leleka-inference", script) self.assertIn("cargo test --no-run --locked -j 4 -p leleka-cuda-driver --features cuda-driver", script) self.assertIn("-p leleka-runtime", script) self.assertIn("nice -n 10", script) self.assertIn("cargo fetch --locked", script) self.assertNotIn("cargo run", script) def test_pull_sealed_transfers_exactly_the_manifest_files(self): p = self.run_sync("pull-sealed") self.assertEqual(p.returncode, 0, p.stderr) self.assertEqual(Path(str(self.log) + ".filesfrom").read_text().split(), ["crates/a.ptx", "docs/x.json"]) self.manifest.write_text(json.dumps({"created_utc": "t", "touched_files": ["../../etc/passwd"]})) p = self.run_sync("pull-sealed") self.assertNotEqual(p.returncode, 0) self.assertIn("unsafe path", p.stderr) class FakeToolkitThroughTheRealPath(unittest.TestCase): """--toolkit: provenance must equal the lock; the version check runs; a mismatching nvcc is refused.""" def make_tk(self, root: Path, lock_override=None, version="13.2.86"): tk = root / "tk" (tk / "bin").mkdir(parents=True) nvcc = tk / "bin" / "nvcc" nvcc.write_text("#!/usr/bin/env bash\nif [[ \"$1\" == --version ]]; then echo 'Cuda compilation tools, release 13.0, V%s'; exit 0; fi\n" "exec %s \"$@\"\n" % (version, HERE.parent / "fake-nvcc")) nvcc.chmod(0o755) lock = json.loads((REPO / L.TOOLKIT_LOCK).read_text()) (tk / "TOOLKIT-PROVENANCE.json").write_text(json.dumps({"lock": lock_override or lock})) return tk def test_toolkit_path_with_matching_provenance_and_version(self): with tempfile.TemporaryDirectory() as d: tk = self.make_tk(Path(d)) code, out, err = run_quiet(C.main, ["--toolkit", str(tk), "--out", str(Path(d) / "o"), "--rope-flags", "preserve", "--only", "device_poison"]) self.assertEqual(code, 1, out + err) # real path: fake-nvcc output carries the FAKE marker and is rejected self.assertIn("fake-nvcc output", out) def test_wrong_provenance_and_wrong_version_are_refused(self): with tempfile.TemporaryDirectory() as d: tk = self.make_tk(Path(d), lock_override={"release": "other"}) with self.assertRaises(L.PlanError): C.locate_nvcc(type("A", (), {"fake_nvcc": False, "nvcc": None, "toolkit": str(tk), "allow_unprovenanced": False})(), REPO) with tempfile.TemporaryDirectory() as d: tk = self.make_tk(Path(d), version="13.2.2") code, _, err = run_quiet(C.main, ["--toolkit", str(tk), "--out", str(Path(d) / "o"), "--rope-flags", "preserve", "--only", "device_poison"]) self.assertEqual(code, 2) self.assertIn("13.2.2", err) self.assertIn("13.2.86", err) if __name__ == "__main__": unittest.main(verbosity=1)