compile_assets.py reads docs/cuda-seal-plan*.json (assets and new_sources formats), an extra plan for assets no plan covers, and the four rope PTX list of docs/rope-and-memory-plan.md; verifies .cu pins, runs nvcc with the exact flags (fast-math policy lint, rope flag variants), validates exports and ABI parameter counts, and writes PTX + build-manifest.json outside the tree. seal_pins.py installs the PTX in the encoding each consumer expects and patches every pin form (PtxPin arrays/structs, AssetSpec.sha, Option tuple arrays, plain len/sha consts, re-pins of regenerated rope PTX, ptx_abi test) with exactly one replacement per field and a read-back check. fake-nvcc and a unittest suite exercise the pipeline on macOS; no GPU, no generated PTX. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
563 lines
29 KiB
Python
563 lines
29 KiB
Python
#!/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 shutil
|
|
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
|
|
|
|
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, 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 <cuda_runtime.h>\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_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<usize> = 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.0.88"}]}))
|
|
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_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"]), 21)
|
|
# 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)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main(verbosity=1)
|