Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
build(xdna): define optional sidecar release process
Kenneth-Javier Ortigoza528e1f54dae1
diff --git a/c/tests/test_xdna_package.py b/c/tests/test_xdna_package.pynew file mode 100644index 00000000..d4a3a733--- /dev/null+++ b/c/tests/test_xdna_package.py@@ -0,0 +1,213 @@+"""Owner for the optional XDNA sidecar release process.++tools/build_xdna_package.py is the only thing that decides what the optional+Windows XDNA download contains and whether it may be published. These tests+pin the parts a release depends on: the asset set, the naming that keeps the+sidecar distinguishable from the core archive, mechanical manifest generation,+and -- most of all -- that a wrong version, a wrong archive checksum or a+digest that disagrees with the compiled registry is refused BEFORE the upload+step rather than after.++The qualified helper and artifact bytes are not available on a build machine,+so every fixture here is synthetic: the tests drive the tool's own registry+parsing, so the expected names and hashes come from c/backend_xdna.c exactly as+they do in production.+"""+import hashlib+import importlib.util+import os+import shutil+import subprocess+import sys+import tempfile+import unittest+import zipfile++HERE = os.path.dirname(os.path.abspath(__file__))+TOOL = os.path.normpath(os.path.join(HERE, "..", "tools", "build_xdna_package.py"))+++def load_tool():+ spec = importlib.util.spec_from_file_location("build_xdna_package", TOOL)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++class TestSidecarReleaseProcess(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.tool = load_tool()++ # ---- asset set -------------------------------------------------------++ def test_expected_asset_count_is_five(self):+ """One helper plus four qualified artifacts -- nothing else ships."""+ need = self.tool.required_files()+ self.assertEqual(len(need), 4, "expected four qualified artifacts")+ self.assertTrue(self.tool.helper_name().endswith(".dll"))+ # 4 artifacts + 1 helper+ self.assertEqual(len(need) + 1, 5)++ def test_registry_hashes_are_read_from_the_engine_source(self):+ """The packager must not carry its own copy of the expected hashes."""+ with open(self.tool.REGISTRY_SRC, encoding="utf-8", errors="replace") as fh:+ src = fh.read()+ for name, digest in self.tool.required_files():+ self.assertIn(name, src)+ self.assertIn(digest, src)++ # ---- naming ----------------------------------------------------------++ def test_asset_name_is_distinguishable_from_the_core_archive(self):+ stem = self.tool.asset_stem("v1.2.3")+ self.assertEqual(stem, "colibri-v1.2.3-windows-x86_64-xdna")+ # the core archive for the same tag/platform must not collide+ self.assertNotEqual(stem, "colibri-v1.2.3-windows-x86_64")+ # and it still matches the release job's own `sha256sum colibri-*`+ self.assertTrue(stem.startswith("colibri-"))++ def test_version_is_derived_not_duplicated(self):+ """The tag must come from version.py, not a second hand-edited string."""+ v = self.tool.release_version()+ src = os.path.normpath(os.path.join(HERE, "..", "version.py"))+ with open(src, encoding="utf-8") as fh:+ self.assertIn('"%s"' % v, fh.read())++ # ---- manifest + rejection --------------------------------------------++ def _fake_release(self, tmp, tag="v0.0.0-test", break_what=None):+ """Build a synthetic sidecar release and return (archive, manifest)."""+ tool = self.tool+ adir, hname = tool.artifact_dir_name(), tool.helper_name()+ root = os.path.join(tmp, "pkg")+ os.makedirs(os.path.join(root, adir), exist_ok=True)+ with open(os.path.join(root, hname), "wb") as f:+ f.write(b"synthetic-helper")+ for name, _ in tool.required_files():+ with open(os.path.join(root, adir, name), "wb") as f:+ f.write(b"synthetic-artifact-" + name.encode())++ dist = os.path.join(tmp, "dist")+ os.makedirs(dist, exist_ok=True)+ stem = tool.asset_stem(tag)+ archive = os.path.join(dist, stem + ".zip")+ with zipfile.ZipFile(archive, "w") as z:+ z.write(os.path.join(root, hname), hname)+ for name, _ in tool.required_files():+ z.write(os.path.join(root, adir, name), "%s/%s" % (adir, name))++ # a manifest that claims the REAL registry digests, so the only thing+ # under test is the checking, not the synthetic bytes+ lines = [+ "# synthetic",+ "release_version\t%s" % tag,+ "platform\t%s" % tool.PLATFORM,+ "archive\t%s" % os.path.basename(archive),+ "archive_sha256\t%s" % tool.sha256(archive),+ "archive_bytes\t%d" % os.path.getsize(archive),+ "",+ "%s\t%d\t%s\t%s\tn/a" % (hname, 1, "0" * 64, "OPTIONAL_XDNA_HELPER"),+ ]+ for name, digest in tool.required_files():+ if break_what == "hash" and name.endswith(".xclbin"):+ digest = "0" * 64+ break_what = "done"+ lines.append("%s/%s\t%d\t%s\t%s\tYES" % (adir, name, 1, digest,+ "QUALIFIED_XDNA_ARTIFACT"))+ manifest = os.path.join(dist, stem + ".manifest.txt")+ with open(manifest, "w", encoding="utf-8", newline="\n") as f:+ f.write("\n".join(lines) + "\n")+ return archive, manifest++ def test_clean_release_verifies(self):+ with tempfile.TemporaryDirectory() as tmp:+ archive, _ = self._fake_release(tmp)+ self.assertEqual(self.tool.verify_release(archive), [])++ def test_wrong_archive_checksum_is_refused(self):+ with tempfile.TemporaryDirectory() as tmp:+ archive, _ = self._fake_release(tmp)+ with open(archive, "ab") as f:+ f.write(b"\x00")+ problems = self.tool.verify_release(archive)+ self.assertTrue(any("sha256 does not match" in p for p in problems), problems)++ def test_wrong_release_version_is_refused(self):+ with tempfile.TemporaryDirectory() as tmp:+ archive, manifest = self._fake_release(tmp)+ with open(manifest, encoding="utf-8") as fh:+ body = fh.read()+ body = body.replace("v0.0.0-test", "v9.9.9", 1)+ with open(manifest, "w", encoding="utf-8", newline="\n") as fh:+ fh.write(body)+ problems = self.tool.verify_release(archive)+ self.assertTrue(any("version" in p for p in problems), problems)++ def test_requested_tag_mismatch_is_refused(self):+ with tempfile.TemporaryDirectory() as tmp:+ archive, _ = self._fake_release(tmp)+ problems = self.tool.verify_release(archive, tag_expected="v1.2.3")+ self.assertTrue(any("release version mismatch" in p for p in problems), problems)++ def test_digest_disagreeing_with_the_registry_is_refused(self):+ with tempfile.TemporaryDirectory() as tmp:+ archive, _ = self._fake_release(tmp, break_what="hash")+ problems = self.tool.verify_release(archive)+ self.assertTrue(any("compiled registry" in p for p in problems), problems)++ def test_missing_manifest_is_refused(self):+ with tempfile.TemporaryDirectory() as tmp:+ archive, manifest = self._fake_release(tmp)+ os.remove(manifest)+ problems = self.tool.verify_release(archive)+ self.assertTrue(any("manifest missing" in p for p in problems), problems)++ def test_missing_artifact_row_is_refused(self):+ with tempfile.TemporaryDirectory() as tmp:+ archive, manifest = self._fake_release(tmp)+ with open(manifest, encoding="utf-8") as fh:+ keep = [l for l in fh if "wa_F3_M256" not in l]+ with open(manifest, "w", encoding="utf-8", newline="\n") as fh:+ fh.writelines(keep)+ problems = self.tool.verify_release(archive)+ self.assertTrue(any("missing" in p for p in problems), problems)++ # ---- archive shape ---------------------------------------------------++ def test_archive_contains_exactly_the_asset_set(self):+ with tempfile.TemporaryDirectory() as tmp:+ archive, _ = self._fake_release(tmp)+ with zipfile.ZipFile(archive) as z:+ members = sorted(z.namelist())+ adir = self.tool.artifact_dir_name()+ expected = sorted(+ [self.tool.helper_name()]+ + ["%s/%s" % (adir, n) for n, _ in self.tool.required_files()])+ self.assertEqual(members, expected)+ self.assertFalse([m for m in members if m.endswith(".pyc")])+ self.assertFalse([m for m in members if "__pycache__" in m])+ self.assertFalse([m for m in members if m.startswith("/") or ":" in m])++ def test_no_external_runtime_is_bundled(self):+ """XRT and the MSVC runtime stay external -- never inside the sidecar."""+ with tempfile.TemporaryDirectory() as tmp:+ archive, _ = self._fake_release(tmp)+ with zipfile.ZipFile(archive) as z:+ members = [m.lower() for m in z.namelist()]+ for forbidden in ("xrt_core.dll", "xrt_coreutil.dll", "msvcp140.dll",+ "vcruntime140.dll", "vcruntime140_1.dll"):+ self.assertFalse([m for m in members if m.endswith(forbidden)],+ "%s must not be bundled" % forbidden)++ # ---- CLI contract ----------------------------------------------------++ def test_cli_exposes_the_release_owner(self):+ out = subprocess.run([sys.executable, TOOL, "--help"],+ capture_output=True, text=True, timeout=60).stdout+ for flag in ("--release", "--dist", "--verify-release", "--verify"):+ self.assertIn(flag, out)+++if __name__ == "__main__":+ unittest.main()diff --git a/c/tools/build_xdna_package.py b/c/tools/build_xdna_package.pyindex c1a036d9..04b46181 100644--- a/c/tools/build_xdna_package.py+++ b/c/tools/build_xdna_package.py@@ -50,7 +50,8 @@ HEADER_SRC = os.path.normpath(os.path.join(HERE, "..", "backend_xdna.h"))def artifact_dir_name():"""The relative directory the engine appends to the executable directory."""- src = open(HEADER_SRC, encoding="utf-8").read()+ with open(HEADER_SRC, encoding="utf-8") as fh:+ src = fh.read()m = re.search(r'#define\s+COLI_XDNA_ARTIFACT_DIR\s+"([^"]+)"', src)if not m:sys.exit("could not find COLI_XDNA_ARTIFACT_DIR in backend_xdna.h")@@ -58,7 +59,8 @@ def artifact_dir_name():def helper_name():- src = open(HEADER_SRC, encoding="utf-8").read()+ with open(HEADER_SRC, encoding="utf-8") as fh:+ src = fh.read()m = re.search(r'#define\s+COLI_XDNA_HELPER_DLL\s+"([^"]+)"', src)if not m:sys.exit("could not find COLI_XDNA_HELPER_DLL in backend_xdna.h")@@ -71,7 +73,8 @@ def required_files():Parsed from the production registry table so the package can never disagreewith the binary that will verify it."""- src = open(REGISTRY_SRC, encoding="utf-8").read()+ with open(REGISTRY_SRC, encoding="utf-8") as fh:+ src = fh.read()m = re.search(r"g_xdna_production_rows\[\]\s*=\s*\{(.*?)\n\};", src, re.S)if not m:sys.exit("could not find g_xdna_production_rows[] in backend_xdna.c")@@ -121,6 +124,118 @@ def verify_tree(root, adir, hname, need_helper=True):return problems+PLATFORM = "windows-x86_64" # matches the release workflow matrix name+++def release_version():+ """The single source of truth the rest of the release already uses."""+ src = os.path.normpath(os.path.join(HERE, "..", "version.py"))+ with open(src, encoding="utf-8") as fh:+ m = re.search(r'__version__\s*=\s*"([^"]+)"', fh.read())+ if not m:+ sys.exit("cannot read __version__ from %s" % src)+ return m.group(1)+++def asset_stem(tag):+ """colibri-<tag>-windows-x86_64-xdna++ The core archive is colibri-<tag>-<platform>.zip (release.yml, Package+ step). The sidecar keeps that stem and adds -xdna, so it sorts beside the+ core asset, is matched by the release job's own "sha256sum colibri-*", and+ can never be mistaken for the core download.+ """+ return "colibri-%s-%s-xdna" % (tag, PLATFORM)+++def manifest_text(tag, root, adir, hname, need, archive_path):+ """Generated mechanically. Nothing here is transcribed by hand."""+ L = []+ L.append("# colibri optional XDNA sidecar -- release manifest")+ L.append("# generated by tools/build_xdna_package.py; do not edit by hand")+ L.append("release_version\t%s" % tag)+ L.append("platform\t%s" % PLATFORM)+ L.append("archive\t%s" % os.path.basename(archive_path))+ L.append("archive_sha256\t%s" % sha256(archive_path))+ L.append("archive_bytes\t%d" % os.path.getsize(archive_path))+ L.append("")+ L.append("# relative_path\tbytes\tsha256\trole\tregistry_match")+ hp = os.path.join(root, hname)+ L.append("%s\t%d\t%s\t%s\t%s"+ % (hname, os.path.getsize(hp), sha256(hp), "OPTIONAL_XDNA_HELPER", "n/a"))+ for name, want in need:+ q = os.path.join(root, adir, name)+ got = sha256(q)+ L.append("%s/%s\t%d\t%s\t%s\t%s"+ % (adir, name, os.path.getsize(q), got,+ "QUALIFIED_XDNA_ARTIFACT", "YES" if got == want else "NO"))+ L.append("")+ L.append("# external runtime prerequisites -- NOT shipped by colibri")+ L.append("# xrt_coreutil.dll, xrt_core.dll AMD XRT / Ryzen AI install")+ L.append("# MSVCP140.dll, VCRUNTIME140.dll, VCRUNTIME140_1.dll MS VC++ redistributable")+ return "\n".join(L) + "\n"+++def read_manifest(path):+ fields, files = {}, []+ with open(path, encoding="utf-8") as fh:+ for line in fh:+ line = line.rstrip("\n")+ if not line or line.startswith("#"):+ continue+ parts = line.split("\t")+ if len(parts) == 2:+ fields[parts[0]] = parts[1]+ elif len(parts) == 5:+ files.append(parts)+ return fields, files++def verify_release(archive, tag_expected=None):+ """Fail closed before anything is uploaded."""+ manifest = os.path.splitext(archive)[0] + ".manifest.txt"+ problems = []+ if not os.path.isfile(archive):+ problems.append("archive missing: %s" % archive)+ if not os.path.isfile(manifest):+ problems.append("manifest missing: %s" % manifest)+ if problems:+ return problems+ fields, files = read_manifest(manifest)+ got = sha256(archive)+ if fields.get("archive_sha256") != got:+ problems.append("archive sha256 does not match its manifest\n"+ " manifest %s\n actual %s"+ % (fields.get("archive_sha256"), got))+ if fields.get("archive") != os.path.basename(archive):+ problems.append("manifest names a different archive: %s" % fields.get("archive"))+ want_stem = asset_stem(fields.get("release_version", ""))+ if os.path.splitext(os.path.basename(archive))[0] != want_stem:+ problems.append("archive name does not match its manifest version: expected %s.zip"+ % want_stem)+ if tag_expected is not None and fields.get("release_version") != tag_expected:+ problems.append("release version mismatch: manifest %s, requested %s"+ % (fields.get("release_version"), tag_expected))+ reg = dict(required_files())+ seen = set()+ for rel, _b, digest, role, match in files:+ if role != "QUALIFIED_XDNA_ARTIFACT":+ continue+ base = rel.split("/")[-1]+ seen.add(base)+ if base not in reg:+ problems.append("manifest lists an unknown artifact: %s" % rel)+ elif reg[base] != digest:+ problems.append("artifact does not match the compiled registry: %s\n"+ " registry %s\n manifest %s" % (rel, reg[base], digest))+ if match != "YES":+ problems.append("manifest records a failed registry match: %s" % rel)+ missing = set(reg) - seen+ if missing:+ problems.append("manifest is missing %d qualified artifact(s): %s"+ % (len(missing), ", ".join(sorted(missing))))+ return problems++def main():ap = argparse.ArgumentParser(description=__doc__,formatter_class=argparse.RawDescriptionHelpFormatter)@@ -129,11 +244,28 @@ def main():ap.add_argument("--out", help="package root to create")ap.add_argument("--zip", help="also write this zip of the package root")ap.add_argument("--verify", help="verify an existing package root and exit")+ ap.add_argument("--release", nargs="?", const="", metavar="TAG",+ help="produce release assets (archive + manifest + checksum) "+ "into --dist; TAG defaults to v<version.py>")+ ap.add_argument("--dist", default="dist", help="directory for --release output")+ ap.add_argument("--verify-release", metavar="ARCHIVE",+ help="verify a release archive against its manifest and the "+ "compiled registry, then exit")a = ap.parse_args()adir, hname = artifact_dir_name(), helper_name()need = required_files()+ if a.verify_release:+ problems = verify_release(a.verify_release)+ for q in problems:+ print("FAIL " + q)+ if problems:+ sys.exit("release assets INVALID: %d problem(s)" % len(problems))+ print("release assets OK: %s" % os.path.basename(a.verify_release))+ print(" archive, manifest and the compiled registry all agree")+ return+if a.verify:problems = verify_tree(a.verify, adir, hname)for p in problems:@@ -189,6 +321,44 @@ def main():z.write(os.path.join(a.out, adir, name), "%s/%s" % (adir, name))print("zip written: %s (%d bytes)" % (a.zip, os.path.getsize(a.zip)))+ if a.release is not None:+ tag = a.release or ("v" + release_version())+ os.makedirs(a.dist, exist_ok=True)+ stem = asset_stem(tag)+ archive = os.path.join(a.dist, stem + ".zip")+ with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as z:+ z.write(os.path.join(a.out, hname), hname)+ for name, _ in need:+ z.write(os.path.join(a.out, adir, name), "%s/%s" % (adir, name))+ manifest = os.path.join(a.dist, stem + ".manifest.txt")+ with open(manifest, "w", encoding="utf-8", newline="\n") as f:+ f.write(manifest_text(tag, a.out, adir, hname, need, archive))+ # sha256sum format, so it reads exactly like the release job's own+ # SHA256SUMS.txt and can simply be appended to it.+ checksum = os.path.join(a.dist, stem + ".sha256")+ with open(checksum, "w", encoding="utf-8", newline="\n") as f:+ f.write("%s %s\n" % (sha256(archive), os.path.basename(archive)))++ problems = verify_release(archive, tag_expected=tag)+ if problems:+ for q in problems:+ print("FAIL " + q)+ sys.exit("refusing to publish: %d problem(s)" % len(problems))++ print("")+ print("release assets for %s" % tag)+ print(" %s (%d bytes)" % (os.path.basename(archive), os.path.getsize(archive)))+ print(" %s" % os.path.basename(manifest))+ print(" %s" % os.path.basename(checksum))+ print("")+ print("verified: archive, manifest and compiled registry agree")+ print("")+ print("attach with the release owner's own command:")+ print(" gh release upload %s \\" % tag)+ print(" %s \\" % archive)+ print(" %s \\" % manifest)+ print(" %s --clobber" % checksum)+if __name__ == "__main__":main()diff --git a/docs/xdna.md b/docs/xdna.mdindex 0aba9bed..d1b0b2e8 100644--- a/docs/xdna.md+++ b/docs/xdna.md@@ -124,6 +124,59 @@ When everything is in place you get the activation notice instead, once:All of this goes to stderr, so it never mixes into machine-readable output.++## Producing the optional package (maintainers)++CI cannot build this package. The helper needs the XRT SDK and the artifacts+need the AIE toolchain, and the release runners have neither — which is why the+Windows job builds an XDNA-capable host and stops there. The sidecar is produced+on a qualified machine and attached to the same release.++Everything below is owned by `c/tools/build_xdna_package.py`. It reads the+expected artifact names and hashes out of `c/backend_xdna.c`, so the package can+never drift from what the engine will accept at runtime.++```bash+python tools/build_xdna_package.py \+ --helper <path to the built coli_xdna.dll> \+ --artifacts <directory holding the four qualified artifacts> \+ --out dist/xdna-pkg \+ --release --dist dist+```++That verifies every input against the compiled registry *before* writing+anything, then produces three files named from `version.py`:++```+colibri-<tag>-windows-x86_64-xdna.zip the sidecar+colibri-<tag>-windows-x86_64-xdna.manifest.txt sizes, hashes, roles, version+colibri-<tag>-windows-x86_64-xdna.sha256 sha256sum format+```++The name keeps the core archive's stem and adds `-xdna`, so it sits beside+`colibri-<tag>-windows-x86_64.zip`, is matched by the release job's own+`sha256sum colibri-*`, and cannot be mistaken for the core download.++Before publishing, re-verify the built assets:++```bash+python tools/build_xdna_package.py --verify-release dist/colibri-<tag>-windows-x86_64-xdna.zip+```++This refuses to pass if the archive does not match its manifest, if the manifest+names a different release version than the file does, or if any artifact digest+disagrees with the compiled registry. Attach only after it prints `release+assets OK` — the command to do so is printed by `--release`, and uses the same+`gh release upload ... --clobber` the release workflow itself uses.++**Never bundle** `xrt_core.dll`, `xrt_coreutil.dll`, the MSVC redistributable, the+AIE toolchain or any SDK header. Those are the user's to install; the sidecar is+only colibrì's own helper and artifacts.++To confirm the ordinary download is unaffected, install the core archive on its+own and run normally: no helper is loaded, no device is opened, and nothing+about the default path changes.+## What this backend does not do- It is not enabled by having the hardware, the helper, or the package.