Skip to content

Run frontier MoE models on hardware you already own β€” pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

feat(xdna): add optional helper runtime binding

Kenneth-Javier Ortigozacef87a9f1c80
diff --git a/GPU_BACKENDS.md b/GPU_BACKENDS.md
index 93a141be..ca5f1633 100644
--- a/GPU_BACKENDS.md
+++ b/GPU_BACKENDS.md
@@ -185,3 +185,72 @@ on real hardware is for (matrix below).
`PIN=auto` + `PIN_FILL` + `CUDA_RELEASE_HOST`, which achieve the same
capacity extension with deeper engine integration; this branch's safety
and validation work now targets that mechanism.
+
+## Optional XDNA2 (Ryzen AI NPU) lane
+
+Status: **binding foundation only.** There is no NPU compute path yet.
+
+XDNA2 is an *optional compute lane*, not an engine and not a GPU. Colibri keeps
+model semantics, routing, expert identity, weight ownership, scheduling and
+fallback; the lane would only ever execute one already-selected, already
+qualified operation. Nothing about it is required to build or run Colibri.
+
+### What is optional, and how
+
+| concern | answer |
+|---|---|
+| does ordinary Colibri need XRT? | **no** β€” no header, no import library, no DLL import |
+| does the default build need an XDNA SDK? | **no** |
+| does a machine need an NPU? | **no** β€” absence is a normal machine, not an error |
+| where does XRT live? | only inside an optional native helper, `coli_xdna.dll` |
+| how is the helper reached? | resolved at runtime, exactly like `coli_cuda.dll` / `coli_hip.dll` in `backend_loader.c` |
+
+`c/backend_xdna.h` and `c/backend_xdna.c` are the host-side owners. They never
+include or link XRT. `colibri` does not link them yet either: there is no caller
+until an operation seam lands, so the default binary is byte-for-byte what it
+was. `make xdna-obj` compiles the host side on its own.
+
+### What this slice implements
+
+- a versioned C ABI boundary (`COLI_XDNA_ABI_VERSION`) to an optional helper
+- runtime discovery and binding of `coli_xdna.dll`, looked up by absolute path
+ beside the executable β€” no PATH search, no current-directory search
+- **all-or-nothing binding**: a helper is usable only when it loads, reports the
+ expected ABI generation, and exports every entry point this host requires. Any
+ failure leaves nothing callable behind
+- a sticky verdict, so a machine without a helper pays one lookup, not one per
+ operation
+- safe shutdown: before probing, after a failed probe, after a good bind, and
+ repeatedly
+
+A successful bind means `HELPER_ABI_AVAILABLE` and nothing more.
+
+### What this slice does NOT implement
+
+Device discovery, XRT initialization, artifact registry, `.xclbin` loading,
+weight preparation, buffer wrapping, dispatch, matmul interception, scheduling
+policy, and any user-facing switch. There is deliberately no `--xdna` flag and
+no `COLI_XDNA*` environment variable: the lane has no operation to offer yet, so
+advertising a control would be premature.
+
+**No real XRT-linked helper is built by this slice.** The XRT-owning helper
+source is not compiled here, because binding is fully qualified without it (see
+below) and dead XRT-linked code would contaminate the build for no gain.
+
+### Validation (no NPU, no XRT, no hardware)
+
+The whole binding contract is qualified against *synthetic* helper DLLs built by
+the tests with the same MinGW gcc the loader tests already require. Those
+fixtures contain no XRT and do no accelerator work; the contract under test is
+the loader's verdict, which is reached long before any real runtime would be.
+
+```
+python -m unittest test_backend_loader.XdnaLoaderOwnerTest \
+ test_backend_loader.XdnaOptionalBindingTest \
+ test_backend_loader.XdnaDefaultBuildIndependenceTest
+```
+
+Covered: helper absent, good helper, wrong ABI generation, missing required
+entry point, present-but-unloadable helper (a deleted dependency), repeated
+probes, the three shutdown orders, and a dependency inspection asserting the
+ordinary `colibri` binary imports neither XRT nor the helper.
diff --git a/c/Makefile b/c/Makefile
index 290b75dc..552b4b20 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -713,6 +713,18 @@ shaders/%.spv: shaders/%.comp
backend_loader.o: backend_loader.c backend_cuda.h compat.h .build-config
$(CC) $(CFLAGS) -c backend_loader.c -o $@
+# Optional XDNA2 (Ryzen AI NPU) lane, host side only. This object resolves an
+# optional coli_xdna.dll at runtime and links nothing: it needs no XRT header,
+# no XRT import library and no NPU, exactly like backend_loader.o needs no CUDA
+# SDK. colibri$(EXE) does NOT link it yet -- there is no caller until the
+# operation seam lands -- so the default build stays byte-for-byte what it was.
+# The rule exists so an ordinary `make xdna-obj` (and the loader tests, which
+# compile the same source in place) catch a break in the C side early.
+.PHONY: xdna-obj
+xdna-obj: backend_xdna.o
+backend_xdna.o: backend_xdna.c backend_xdna.h .build-config
+ $(CC) $(CFLAGS) -c backend_xdna.c -o $@
+
# Windows CUDA DLL: compile backend_cuda.cu with nvcc (+MSVC cl.exe as host
# compiler, required by nvcc on Windows) into coli_cuda.dll. Run this from a
# shell that has the MSVC environment set (e.g. after vcvars64.bat, or from a
diff --git a/c/backend_xdna.c b/c/backend_xdna.c
new file mode 100644
index 00000000..0f3f65ff
--- /dev/null
+++ b/c/backend_xdna.c
@@ -0,0 +1,208 @@
+/* Optional AMD XDNA2 helper binding -- the C side, which never touches XRT.
+ *
+ * The split mirrors backend_loader.c: the host resolves an optional native DLL
+ * at runtime and links none of its dependencies, so an ordinary Colibri build
+ * has no XRT headers, no XRT import library and no XRT DLL import. Everything
+ * that needs XRT lives in coli_xdna.dll, which this file loads and may refuse.
+ *
+ * Refusal is the normal case. A machine with no NPU, no XRT or no helper is
+ * ordinary, and every rejection path here ends the same way: the lane is
+ * unavailable and the caller keeps doing exactly what it does today.
+ *
+ * W2-N7-I1 implements the binding only. There is deliberately no device open,
+ * no artifact, no weight preparation and no dispatch here yet; the entry-point
+ * set is the smallest one that makes the boundary versioned and testable, so
+ * later slices extend it rather than inheriting speculative signatures.
+ */
+
+#include "backend_xdna.h"
+
+#include <stdio.h>
+#include <string.h>
+
+#ifdef _WIN32
+#include <windows.h>
+#endif
+
+/* Entry points required of a helper at this ABI generation. Kept minimal on
+ * purpose: a version handshake, and the release call this file's own lifetime
+ * contract needs. Later slices add device/artifact/execute entry points and
+ * bump COLI_XDNA_ABI_VERSION with them. */
+typedef unsigned int (*coli_xdna_fn_abi_version)(void);
+typedef void (*coli_xdna_fn_shutdown)(void);
+
+static struct {
+ ColiXdnaBinding state;
+ int load_attempts;
+ char path[512]; /* test override; empty = default lookup */
+#ifdef _WIN32
+ HMODULE dll;
+#endif
+ coli_xdna_fn_abi_version abi_version;
+ coli_xdna_fn_shutdown shutdown;
+} g_xdna = { COLI_XDNA_UNPROBED, 0, {0},
+#ifdef _WIN32
+ NULL,
+#endif
+ NULL, NULL };
+
+/* Drop every callable pointer. Always runs BEFORE the module is released, so a
+ * rejected or shut-down helper can never leave a pointer into an unmapped
+ * module behind -- the all-or-nothing half of the binding contract. */
+static void coli_xdna_clear_entry_points(void){
+ g_xdna.abi_version = NULL;
+ g_xdna.shutdown = NULL;
+}
+
+const char *coli_xdna_binding_text(ColiXdnaBinding state){
+ switch(state){
+ case COLI_XDNA_UNPROBED: return "UNPROBED";
+ case COLI_XDNA_AVAILABLE: return "AVAILABLE";
+ case COLI_XDNA_ABSENT: return "ABSENT";
+ case COLI_XDNA_LOAD_FAILED: return "LOAD_FAILED";
+ case COLI_XDNA_ABI_INCOMPATIBLE: return "ABI_INCOMPATIBLE";
+ case COLI_XDNA_SYMBOL_INCOMPLETE: return "SYMBOL_INCOMPLETE";
+ }
+ return "UNKNOWN";
+}
+
+#ifdef _WIN32
+
+/* Where the helper is looked for when no test override is set: beside the
+ * running executable, by absolute path. Deliberately NOT a search: no PATH, no
+ * current directory, no application-directory fallback. W1 established that an
+ * already-loaded module with the same basename wins over a later absolute-path
+ * load, so a search order here would be both unsafe and unpredictable. A helper
+ * that is not where we look is simply ABSENT. */
+static int coli_xdna_default_helper_path(char *out, size_t cap){
+ char exe[512];
+ DWORD n = GetModuleFileNameA(NULL, exe, (DWORD)sizeof exe);
+ if(n == 0 || n >= sizeof exe) return 0;
+ char *slash = strrchr(exe, '\\');
+ char *fwd = strrchr(exe, '/');
+ if(fwd && (!slash || fwd > slash)) slash = fwd;
+ if(!slash) return 0;
+ *slash = '\0';
+ int written = snprintf(out, cap, "%s\\%s", exe, COLI_XDNA_HELPER_DLL);
+ return written > 0 && (size_t)written < cap;
+}
+
+static void coli_xdna_probe(void){
+ char resolved[512];
+ const char *path = g_xdna.path[0] ? g_xdna.path : NULL;
+
+ if(!path){
+ if(!coli_xdna_default_helper_path(resolved, sizeof resolved)){
+ g_xdna.state = COLI_XDNA_ABSENT;
+ return;
+ }
+ path = resolved;
+ }
+
+ /* Absence is not a load failure, and the difference is worth keeping: one
+ * means "this build simply has no optional lane here", the other means "a
+ * helper is installed but something about it is wrong". */
+ if(GetFileAttributesA(path) == INVALID_FILE_ATTRIBUTES){
+ g_xdna.state = COLI_XDNA_ABSENT;
+ return;
+ }
+
+ g_xdna.load_attempts++;
+ /* LOAD_WITH_ALTERED_SEARCH_PATH lets the helper's own directory satisfy the
+ * helper's dependencies (it will eventually need the XRT runtime beside it)
+ * without widening the search for the helper itself, which we located by
+ * absolute path above. */
+ HMODULE dll = LoadLibraryExA(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
+ if(!dll){
+ g_xdna.state = COLI_XDNA_LOAD_FAILED;
+ return;
+ }
+
+ /* Resolve into locals: nothing becomes callable until the whole set has
+ * validated and the ABI generation matches. */
+#if defined(__GNUC__)
+ /* GetProcAddress returns FARPROC; casting to the exact exported signature
+ * is the standard LoadLibrary idiom, same as backend_loader.c's RESOLVE. */
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wcast-function-type"
+#endif
+ coli_xdna_fn_abi_version abi_version =
+ (coli_xdna_fn_abi_version)GetProcAddress(dll, "coli_xdna_helper_abi_version");
+ coli_xdna_fn_shutdown shutdown =
+ (coli_xdna_fn_shutdown)GetProcAddress(dll, "coli_xdna_helper_shutdown");
+#if defined(__GNUC__)
+ #pragma GCC diagnostic pop
+#endif
+
+ /* The version handshake comes first: a helper from a different generation
+ * may well export a symbol of the same name with a different meaning, so
+ * the missing-symbol check below is only meaningful once generations agree.
+ * A helper that cannot even report its generation is incompatible, not
+ * incomplete -- there is no version to compare. */
+ if(!abi_version || abi_version() != COLI_XDNA_ABI_VERSION){
+ FreeLibrary(dll);
+ g_xdna.state = COLI_XDNA_ABI_INCOMPATIBLE;
+ return;
+ }
+ if(!shutdown){
+ FreeLibrary(dll);
+ g_xdna.state = COLI_XDNA_SYMBOL_INCOMPLETE;
+ return;
+ }
+
+ g_xdna.dll = dll;
+ g_xdna.abi_version = abi_version;
+ g_xdna.shutdown = shutdown;
+ g_xdna.state = COLI_XDNA_AVAILABLE;
+}
+
+void coli_xdna_shutdown(void){
+ if(g_xdna.shutdown) g_xdna.shutdown();
+ coli_xdna_clear_entry_points();
+ if(g_xdna.dll){
+ FreeLibrary(g_xdna.dll);
+ g_xdna.dll = NULL; /* released exactly once; repeat calls are no-ops */
+ }
+ /* The verdict is deliberately NOT reset to UNPROBED: shutting the lane down
+ * is not a reason to re-probe it later in the same process. */
+}
+
+#else /* !_WIN32 */
+
+/* The qualified XDNA lane is Windows/XDNA2-specific (see the N6 architecture
+ * freeze). Elsewhere the loader compiles and answers ABSENT, so the rest of the
+ * engine needs no platform branches and the contract stays uniform. */
+static void coli_xdna_probe(void){
+ g_xdna.state = COLI_XDNA_ABSENT;
+}
+
+void coli_xdna_shutdown(void){
+ coli_xdna_clear_entry_points();
+}
+
+#endif /* _WIN32 */
+
+ColiXdnaBinding coli_xdna_binding(void){
+ /* Sticky: probe at most once per path. Everything after the first call is a
+ * branch, which is what keeps a machine with no helper from paying a module
+ * load on every candidate operation. */
+ if(g_xdna.state == COLI_XDNA_UNPROBED) coli_xdna_probe();
+ return g_xdna.state;
+}
+
+void coli_xdna_test_set_helper_path(const char *path){
+ coli_xdna_shutdown();
+ g_xdna.state = COLI_XDNA_UNPROBED;
+ g_xdna.load_attempts = 0;
+ if(path && *path){
+ snprintf(g_xdna.path, sizeof g_xdna.path, "%s", path);
+ } else {
+ g_xdna.path[0] = '\0';
+ }
+}
+
+ColiXdnaBinding coli_xdna_test_state(void){ return g_xdna.state; }
+int coli_xdna_test_load_attempts(void){ return g_xdna.load_attempts; }
+int coli_xdna_test_entry_points_bound(void){
+ return g_xdna.abi_version != NULL && g_xdna.shutdown != NULL;
+}
diff --git a/c/backend_xdna.h b/c/backend_xdna.h
new file mode 100644
index 00000000..7e69918f
--- /dev/null
+++ b/c/backend_xdna.h
@@ -0,0 +1,93 @@
+#ifndef COLIBRI_BACKEND_XDNA_H
+#define COLIBRI_BACKEND_XDNA_H
+
+/* Optional AMD XDNA2 (Ryzen AI NPU) compute lane -- host-side binding only.
+ *
+ * XDNA is an OPTIONAL lane, never an engine. Colibri keeps model semantics,
+ * routing, expert identity, weight ownership, scheduling and fallback; the
+ * helper only ever executes one already-selected, already-qualified operation.
+ *
+ * This header and backend_xdna.c are the C-side owners and they NEVER include
+ * or link XRT. XRT lives exclusively behind an optional native helper DLL
+ * (coli_xdna.dll), resolved at runtime the way backend_loader.c resolves the
+ * GPU backend. An ordinary Colibri build has no XRT dependency at all, and a
+ * machine with no helper, no XRT and no NPU is a normal machine, not a broken
+ * one.
+ *
+ * Scope of THIS slice (W2-N7-I1): binding only. Nothing here opens a device,
+ * reads an artifact, prepares a weight or executes anything -- see the state
+ * comment on ColiXdnaBinding.
+ */
+
+#include <stddef.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Host-side ABI generation. A helper reporting a different value is refused
+ * outright: there is no partial acceptance and no speculative forward
+ * compatibility, because neither could be tested here. Bump this when the
+ * required entry-point set or any signature changes. */
+#define COLI_XDNA_ABI_VERSION 1u
+
+/* Symbols the helper must export, all prefixed coli_xdna_helper_ so they can
+ * never collide with the host-side coli_xdna_ names in this header. */
+#define COLI_XDNA_HELPER_DLL "coli_xdna.dll"
+
+/* Loader verdict. This describes the HELPER BINDING and nothing else.
+ *
+ * COLI_XDNA_AVAILABLE means HELPER_ABI_AVAILABLE: a compatible helper is loaded
+ * and every entry point this host requires resolved. It does NOT mean a device
+ * is present, an artifact is usable, or any operation is eligible -- those are
+ * separate concerns owned by later slices, deliberately not conflated here. */
+typedef enum {
+ COLI_XDNA_UNPROBED = 0, /* no probe attempted yet */
+ COLI_XDNA_AVAILABLE, /* compatible helper bound (ABI only) */
+ COLI_XDNA_ABSENT, /* no helper file where we looked */
+ COLI_XDNA_LOAD_FAILED, /* file present, but it would not load */
+ COLI_XDNA_ABI_INCOMPATIBLE, /* loaded, reported a different ABI generation */
+ COLI_XDNA_SYMBOL_INCOMPLETE /* loaded and compatible, but an entry point is missing */
+} ColiXdnaBinding;
+
+/* Probe once, then answer from the cached verdict. The probe is LAZY: an
+ * ordinary run that never asks pays nothing, and a run that asks pays one
+ * LoadLibrary at most. Every outcome other than COLI_XDNA_AVAILABLE simply
+ * means the lane is unavailable; none of them is an error the caller must
+ * handle beyond continuing on its current path. */
+ColiXdnaBinding coli_xdna_binding(void);
+
+/* Stable, allocation-free label for diagnostics and tests. */
+const char *coli_xdna_binding_text(ColiXdnaBinding state);
+
+/* Release the helper. Safe when never probed, safe after a failed probe, and
+ * safe to call repeatedly. Callable pointers are cleared before the module is
+ * released, so no entry point can outlive the module that provided it. */
+void coli_xdna_shutdown(void);
+
+/* -- test seams -----------------------------------------------------------
+ * Mirrors the coli_loader_test_* convention in backend_loader.c: exercised by
+ * c/tests/test_backend_loader.py against synthetic helpers that contain no
+ * XRT, so the whole binding contract is qualified without an NPU. */
+
+/* Point the loader at a specific helper file instead of the default lookup.
+ * Resets any cached verdict so the next query re-probes. */
+void coli_xdna_test_set_helper_path(const char *path);
+
+/* Cached verdict WITHOUT triggering a probe. */
+ColiXdnaBinding coli_xdna_test_state(void);
+
+/* How many times a module load has actually been attempted. The sticky verdict
+ * contract is that this never exceeds 1 for a given path. */
+int coli_xdna_test_load_attempts(void);
+
+/* 1 only when a complete, compatible entry-point set is currently callable. A
+ * rejected helper must leave this 0 -- binding is all-or-nothing. */
+int coli_xdna_test_entry_points_bound(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* COLIBRI_BACKEND_XDNA_H */
diff --git a/c/tests/test_backend_loader.py b/c/tests/test_backend_loader.py
index 60ef934a..435c12b7 100644
--- a/c/tests/test_backend_loader.py
+++ b/c/tests/test_backend_loader.py
@@ -2415,5 +2415,350 @@ class LoaderBackendSelectionTest(unittest.TestCase):
self.assertEqual(result.returncode, 2)
+
+
+# ---------------------------------------------------------------------------
+# W2-N7-I1: the optional XDNA helper binding contract.
+#
+# c/backend_xdna.c is the C-side loader for an OPTIONAL native helper DLL. It
+# must never require XRT: the helper owns XRT, the host owns only the binding.
+# These tests compile the production loader in place from c/ (never a copy) and
+# drive it against synthetic helpers built with the same MinGW gcc the loader
+# tests already require. Nothing here needs XRT, an NPU, or coli_xdna.dll.
+#
+# The contract under test is the BINDING, not the device: a successful bind
+# means HELPER_ABI_AVAILABLE and nothing more.
+# ---------------------------------------------------------------------------
+
+_XDNA_HELPER_BASENAME = "coli_xdna.dll"
+
+# Synthetic helper. Never links XRT; -D switches select the defect under test.
+_XDNA_FAKE_HELPER_C = r'''
+#include <windows.h>
+
+#ifndef FAKE_ABI_VERSION
+#define FAKE_ABI_VERSION 1u
+#endif
+
+__declspec(dllexport) unsigned int coli_xdna_helper_abi_version(void){
+ return (unsigned int)FAKE_ABI_VERSION;
+}
+
+#ifndef FAKE_OMIT_SHUTDOWN
+__declspec(dllexport) void coli_xdna_helper_shutdown(void){ }
+#endif
+
+#ifdef FAKE_NEEDS_MISSING_DEP
+/* Pulls in a dependency the test deletes, so LoadLibrary fails with 126
+ * (ERROR_MOD_NOT_FOUND) instead of the file being absent outright. */
+__declspec(dllimport) int coli_xdna_fake_dep_probe(void);
+__declspec(dllexport) int coli_xdna_helper_touch_dep(void){
+ return coli_xdna_fake_dep_probe();
+}
+#endif
+
+BOOL WINAPI DllMain(HINSTANCE h, DWORD reason, LPVOID reserved){
+ (void)h; (void)reason; (void)reserved; return TRUE;
+}
+'''
+
+_XDNA_FAKE_DEP_C = r'''
+#include <windows.h>
+__declspec(dllexport) int coli_xdna_fake_dep_probe(void){ return 7; }
+BOOL WINAPI DllMain(HINSTANCE h, DWORD reason, LPVOID reserved){
+ (void)h; (void)reason; (void)reserved; return TRUE;
+}
+'''
+
+# Harness: compiles the REAL c/backend_xdna.c and drives its test seams.
+_XDNA_HARNESS_C = r'''
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include "backend_xdna.c"
+
+static void report(const char *tag){
+ ColiXdnaBinding s = coli_xdna_binding();
+ printf("%s=%s attempts=%d\n", tag, coli_xdna_binding_text(s),
+ coli_xdna_test_load_attempts());
+}
+
+int main(int argc, char **argv){
+ const char *mode = argc > 1 ? argv[1] : "";
+ const char *path = argc > 2 ? argv[2] : NULL;
+
+ if(path && *path) coli_xdna_test_set_helper_path(path);
+
+ if(!strcmp(mode, "probe")){
+ report("state");
+ return 0;
+ }
+ if(!strcmp(mode, "repeat")){
+ int n = argc > 3 ? atoi(argv[3]) : 5;
+ for(int i = 0; i < n; i++) (void)coli_xdna_binding();
+ report("state");
+ return 0;
+ }
+ if(!strcmp(mode, "shutdown_after_probe")){
+ report("before");
+ coli_xdna_shutdown();
+ printf("shutdown_ok=1\n");
+ coli_xdna_shutdown(); /* repeated shutdown must be safe */
+ printf("second_shutdown_ok=1\n");
+ return 0;
+ }
+ if(!strcmp(mode, "shutdown_without_probe")){
+ coli_xdna_shutdown();
+ printf("shutdown_ok=1\n");
+ printf("state=%s\n", coli_xdna_binding_text(coli_xdna_test_state()));
+ return 0;
+ }
+ if(!strcmp(mode, "callable")){
+ /* A rejected helper must leave NO callable entry point behind. */
+ report("state");
+ printf("callable=%d\n", coli_xdna_test_entry_points_bound());
+ return 0;
+ }
+ fprintf(stderr, "unknown_mode=%s\n", mode);
+ return 2;
+}
+'''
+
+
+class XdnaLoaderOwnerTest(unittest.TestCase):
+ """The optional XDNA loader must exist and declare its binding contract.
+
+ This owner needs no toolchain: it is the contract that c/backend_xdna.{c,h}
+ are the C-side owners of the optional helper boundary, and that the boundary
+ is versioned and all-or-nothing.
+ """
+
+ def test_loader_owner_files_exist(self):
+ for name in ("backend_xdna.h", "backend_xdna.c"):
+ with self.subTest(source=name):
+ self.assertTrue((HERE / name).is_file(),
+ "c/%s is the C-side XDNA owner and must exist" % name)
+
+ def test_header_declares_the_binding_contract(self):
+ hdr = (HERE / "backend_xdna.h").read_text(encoding="utf-8", errors="replace")
+ for token in ("COLI_XDNA_ABI_VERSION", "ColiXdnaBinding",
+ "COLI_XDNA_UNPROBED", "COLI_XDNA_AVAILABLE",
+ "COLI_XDNA_ABSENT", "COLI_XDNA_LOAD_FAILED",
+ "COLI_XDNA_ABI_INCOMPATIBLE", "COLI_XDNA_SYMBOL_INCOMPLETE",
+ "coli_xdna_binding", "coli_xdna_shutdown"):
+ with self.subTest(token=token):
+ self.assertIn(token, hdr)
+
+
+class XdnaOptionalBindingTest(unittest.TestCase):
+ """Does the optional XDNA helper bind all-or-nothing, and stay optional?
+
+ Every case runs the production c/backend_xdna.c. The helper under test is a
+ synthetic DLL with no XRT in it; the point is the loader's verdict, which is
+ reached long before any real runtime would be.
+ """
+
+ tmp = None
+
+ @classmethod
+ def setUpClass(cls):
+ reason = _fixture_toolchain_skip()
+ if reason:
+ raise unittest.SkipTest(reason)
+ cls.tmp = tempfile.TemporaryDirectory(prefix="coli xdna bind ")
+ root = Path(cls.tmp.name)
+ cls.root = root
+
+ def gcc(args, what):
+ cmd = ["gcc"] + args
+ proc = subprocess.run(cmd, text=True, errors="replace",
+ capture_output=True, timeout=300)
+ if proc.returncode != 0:
+ raise FixtureBuildError(
+ "%s failed (rc=%d)\ncommand: %s\nstdout:\n%s\nstderr:\n%s"
+ % (what, proc.returncode, " ".join(cmd), proc.stdout, proc.stderr))
+ return proc
+
+ cls._gcc = staticmethod(gcc)
+
+ helper_src = root / "fake_helper.c"
+ helper_src.write_text(_XDNA_FAKE_HELPER_C, encoding="ascii")
+ dep_src = root / "fake_dep.c"
+ dep_src.write_text(_XDNA_FAKE_DEP_C, encoding="ascii")
+ harness_src = root / "xdna_harness.c"
+ harness_src.write_text(_XDNA_HARNESS_C, encoding="ascii")
+
+ # Good helper: current ABI, complete entry points.
+ cls.good = root / "good" / _XDNA_HELPER_BASENAME
+ cls.good.parent.mkdir(parents=True, exist_ok=True)
+ gcc(["-O0", "-shared", str(helper_src), "-o", str(cls.good)],
+ "building the good synthetic helper")
+
+ # Wrong ABI version.
+ cls.bad_abi = root / "bad_abi" / _XDNA_HELPER_BASENAME
+ cls.bad_abi.parent.mkdir(parents=True, exist_ok=True)
+ gcc(["-O0", "-shared", "-DFAKE_ABI_VERSION=999u", str(helper_src),
+ "-o", str(cls.bad_abi)], "building the wrong-ABI synthetic helper")
+
+ # Missing a required entry point.
+ cls.incomplete = root / "incomplete" / _XDNA_HELPER_BASENAME
+ cls.incomplete.parent.mkdir(parents=True, exist_ok=True)
+ gcc(["-O0", "-shared", "-DFAKE_OMIT_SHUTDOWN", str(helper_src),
+ "-o", str(cls.incomplete)], "building the incomplete synthetic helper")
+
+ # Present but unloadable: imports a dependency that is then deleted.
+ cls.unloadable = root / "unloadable" / _XDNA_HELPER_BASENAME
+ cls.unloadable.parent.mkdir(parents=True, exist_ok=True)
+ dep_dll = cls.unloadable.parent / "coli_xdna_fake_dep.dll"
+ gcc(["-O0", "-shared", str(dep_src), "-o", str(dep_dll)],
+ "building the synthetic helper dependency")
+ gcc(["-O0", "-shared", "-DFAKE_NEEDS_MISSING_DEP", str(helper_src),
+ "-o", str(cls.unloadable), str(dep_dll)],
+ "building the dependency-bound synthetic helper")
+ dep_dll.unlink() # now the helper cannot load
+
+ cls.absent = root / "empty" / _XDNA_HELPER_BASENAME # never created
+ cls.absent.parent.mkdir(parents=True, exist_ok=True)
+
+ cls.harness = root / "xdna_harness.exe"
+ gcc(["-O0", "-I", str(HERE), str(harness_src), "-o", str(cls.harness)],
+ "building the XDNA loader harness")
+
+ @classmethod
+ def tearDownClass(cls):
+ if cls.tmp is not None:
+ cls.tmp.cleanup()
+ cls.tmp = None
+
+ def _run(self, mode, path, *extra):
+ cmd = [str(self.harness), mode, str(path)] + [str(a) for a in extra]
+ proc = subprocess.run(cmd, text=True, errors="replace",
+ capture_output=True, timeout=120)
+ self.assertEqual(proc.returncode, 0,
+ "harness failed: %s\n%s\n%s"
+ % (" ".join(cmd), proc.stdout, proc.stderr))
+ return proc.stdout
+
+ def _state(self, out, key="state"):
+ for line in out.splitlines():
+ if line.startswith(key + "="):
+ return line.split("=", 1)[1].split(" ")[0]
+ self.fail("no %s= line in harness output:\n%s" % (key, out))
+
+ # -- the load-bearing case: absence is not a failure --------------------
+ def test_absent_helper_is_not_fatal(self):
+ out = self._run("probe", self.absent)
+ self.assertEqual(self._state(out), "ABSENT")
+
+ def test_good_helper_binds(self):
+ out = self._run("probe", self.good)
+ self.assertEqual(self._state(out), "AVAILABLE")
+
+ def test_wrong_abi_is_rejected(self):
+ out = self._run("probe", self.bad_abi)
+ self.assertEqual(self._state(out), "ABI_INCOMPATIBLE")
+
+ def test_missing_required_entry_point_is_rejected(self):
+ out = self._run("probe", self.incomplete)
+ self.assertEqual(self._state(out), "SYMBOL_INCOMPLETE")
+
+ def test_unloadable_helper_is_rejected_not_fatal(self):
+ out = self._run("probe", self.unloadable)
+ self.assertEqual(self._state(out), "LOAD_FAILED")
+
+ # -- all-or-nothing ----------------------------------------------------
+ def test_rejected_helper_leaves_nothing_callable(self):
+ for name, path in (("bad_abi", self.bad_abi),
+ ("incomplete", self.incomplete),
+ ("unloadable", self.unloadable),
+ ("absent", self.absent)):
+ with self.subTest(helper=name):
+ out = self._run("callable", path)
+ self.assertEqual(self._state(out, "callable"), "0")
+
+ def test_bound_helper_reports_its_entry_points(self):
+ out = self._run("callable", self.good)
+ self.assertEqual(self._state(out, "callable"), "1")
+
+ # -- sticky verdict ----------------------------------------------------
+ def test_repeated_probe_loads_at_most_once(self):
+ for name, path in (("good", self.good), ("absent", self.absent),
+ ("bad_abi", self.bad_abi)):
+ with self.subTest(helper=name):
+ out = self._run("repeat", path, 8)
+ # attempts is reported on the same line as state=
+ line = [l for l in out.splitlines() if l.startswith("state=")][0]
+ attempts = int(line.split("attempts=")[1])
+ self.assertLessEqual(attempts, 1,
+ "loader re-probed %d times: %s" % (attempts, out))
+
+ # -- lifetime ----------------------------------------------------------
+ def test_shutdown_after_bind_is_safe_and_repeatable(self):
+ out = self._run("shutdown_after_probe", self.good)
+ self.assertEqual(self._state(out, "before"), "AVAILABLE")
+ self.assertIn("shutdown_ok=1", out)
+ self.assertIn("second_shutdown_ok=1", out)
+
+ def test_shutdown_without_probe_is_safe(self):
+ out = self._run("shutdown_without_probe", self.absent)
+ self.assertIn("shutdown_ok=1", out)
+ self.assertEqual(self._state(out), "UNPROBED")
+
+ def test_shutdown_after_failed_bind_is_safe(self):
+ out = self._run("shutdown_after_probe", self.bad_abi)
+ self.assertEqual(self._state(out, "before"), "ABI_INCOMPATIBLE")
+ self.assertIn("second_shutdown_ok=1", out)
+
+
+class XdnaDefaultBuildIndependenceTest(unittest.TestCase):
+ """Does the ordinary host stay free of XRT and of the helper?
+
+ c/backend_xdna.c is the only C-side XDNA owner and it must compile with no
+ XRT header available. The default host must import neither XRT nor the
+ optional helper.
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ reason = _fixture_toolchain_skip()
+ if reason:
+ raise unittest.SkipTest(reason)
+
+ def test_loader_source_names_no_xrt_header(self):
+ src = (HERE / "backend_xdna.c").read_text(encoding="utf-8", errors="replace")
+ hdr = (HERE / "backend_xdna.h").read_text(encoding="utf-8", errors="replace")
+ for name, text in (("backend_xdna.c", src), ("backend_xdna.h", hdr)):
+ with self.subTest(source=name):
+ self.assertNotIn("xrt/", text,
+ "%s must not include any XRT header" % name)
+ self.assertNotIn("xrt_", text.replace("coli_xdna_", ""),
+ "%s must not name an XRT symbol" % name)
+
+ def test_loader_compiles_without_any_xrt_include_path(self):
+ with tempfile.TemporaryDirectory(prefix="coli xdna nodep ") as tmp:
+ obj = Path(tmp) / "backend_xdna.o"
+ cmd = ["gcc", "-O0", "-c", str(HERE / "backend_xdna.c"), "-o", str(obj)]
+ proc = subprocess.run(cmd, text=True, errors="replace",
+ capture_output=True, timeout=300)
+ self.assertEqual(proc.returncode, 0,
+ "the C-side loader must compile with no XRT present:\n%s\n%s"
+ % (proc.stdout, proc.stderr))
+ self.assertTrue(obj.is_file())
+
+ def test_default_host_imports_neither_xrt_nor_helper(self):
+ exe = HERE / "colibri.exe"
+ if not exe.is_file():
+ raise unittest.SkipTest("c/colibri.exe not built here")
+ proc = subprocess.run(["objdump", "-p", str(exe)], text=True,
+ errors="replace", capture_output=True, timeout=300)
+ self.assertEqual(proc.returncode, 0, proc.stderr)
+ imports = [l.split()[-1].lower() for l in proc.stdout.splitlines()
+ if "DLL Name:" in l]
+ for bad in ("xrt_coreutil.dll", "xrt_core.dll", "xrt_coreutil_static.dll",
+ _XDNA_HELPER_BASENAME):
+ self.assertNotIn(bad, imports,
+ "default host must not import %s (imports: %s)"
+ % (bad, imports))
+
if __name__ == "__main__":
unittest.main()