Run frontier MoE models on hardware you already own β pure C, zero deps, experts streamed from disk. Tiny engine, immense model. π¦
C
refactor(windows): add HIP runtime binding foundations
Kenneth-Javier Ortigozac5f5922d3ccc
diff --git a/c/backend_loader.c b/c/backend_loader.cindex 698e23c1..9c4adf1f 100644--- a/c/backend_loader.c+++ b/c/backend_loader.c@@ -26,6 +26,7 @@#include <string.h>#include <wchar.h>#include <windows.h>+#include <tlhelp32.h>#include "backend_cuda.h"@@ -399,6 +400,565 @@ static void coli_win_error_phrase(DWORD code, char *buf, size_t n){else snprintf(buf, n, "Windows loader error %lu", (unsigned long)code);}+/* ===================== Windows runtime identity and inventory =============+ *+ * Foundation for deterministic HIP runtime binding. NOTHING HERE IS CALLED BY+ * THE LOADER YET: this slice adds the machinery and proves it, and a later one+ * wires it in. Keeping the two apart means the change that alters what the+ * process loads can be reviewed β and reverted β on its own.+ *+ * Three measured Windows facts shape all of it:+ *+ * 1. Two modules with the same base name, loaded from different absolute+ * paths, really do coexist in one process, with distinct HMODULEs.+ * 2. GetModuleHandleExW asked for a BASE NAME returns only the first of them+ * and silently hides the rest, so it cannot answer "what is loaded".+ * 3. Two different path strings can name one physical file (hard links, dot+ * segments, case), and one path string can be re-pointed at a different+ * file by a rename even while the old one is mapped.+ *+ * So: enumerate every match rather than ask for one, and decide equality on+ * physical file identity rather than on path text. Paths are kept only to tell+ * a human which file we meant.+ *+ * These functions have external linkage but appear in no header, are never+ * exported, and live in backend_loader.o, which links into the host executable+ * only β coli_hip.dll and coli_cuda.dll are built from backend_cuda.cu and+ * never see this file. External linkage rather than `static` is deliberate:+ * unused static functions would warn, and the warning would be noise rather+ * than a finding while the wiring is still a slice away. */++#define COLI_W32_RUNTIME_BASENAME L"amdhip64_7.dll"+#define COLI_W32_PATH_START 512u /* wchar_t; grows, never a correctness bound */+#define COLI_W32_PATH_ROUNDS 8 /* 512 -> 65536 wchar_t before giving up */++int coli_win32_loader_is_sep(wchar_t c){ return c == L'\\' || c == L'/'; }++/* --- physical file identity ------------------------------------------+ *+ * Two representations, because the newer one is not always obtainable.+ * FILE_ID_INFO carries a 128-bit ID that stays unique on ReFS;+ * BY_HANDLE_FILE_INFORMATION carries the classic 64-bit index. Both are+ * captured when available so a later comparison can pick a format the two+ * sides genuinely share β see coli_win32_loader_identity_equal. */+typedef struct {+ int have_id_info;+ int have_by_handle;+ DWORD error; /* why nothing could be captured */+ ULONGLONG idi_volume;+ FILE_ID_128 idi_id;+ DWORD bh_volume;+ DWORD bh_index_high;+ DWORD bh_index_low;+} ColiW32FileId;++int coli_win32_loader_identity_valid(const ColiW32FileId *id){+ return id && (id->have_id_info || id->have_by_handle);+}++/* 1 = the same physical file, 0 = different files, -1 = cannot be determined.+ *+ * The fallback is SYMMETRIC: if either side is missing FILE_ID_INFO, BOTH+ * sides drop to the by-handle index. A 128-bit ID is never compared against a+ * 64-bit index, because they are different namespaces and a coincidental match+ * would be indistinguishable from a real one. When no shared format exists the+ * answer is "unknown" β never a text comparison, which would reject hard links+ * to the very file that was configured. */+int coli_win32_loader_identity_equal(const ColiW32FileId *a, const ColiW32FileId *b){+ if(!a || !b) return -1;+ if(a->have_id_info && b->have_id_info)+ return (a->idi_volume == b->idi_volume &&+ memcmp(&a->idi_id, &b->idi_id, sizeof a->idi_id) == 0) ? 1 : 0;+ if(a->have_by_handle && b->have_by_handle)+ return (a->bh_volume == b->bh_volume &&+ a->bh_index_high == b->bh_index_high &&+ a->bh_index_low == b->bh_index_low) ? 1 : 0;+ return -1;+}++/* --- growing-buffer Unicode paths ------------------------------------+ *+ * Every one of these returns a malloc'd, NUL-terminated wide string the caller+ * frees, or NULL with *err set. None of them treats MAX_PATH as a limit. */++static int coli_w32_grow_ok(size_t cap){+ return cap <= ((size_t)-1) / sizeof(wchar_t) / 2;+}++/* Path of a loaded module, or of the running executable when mod is NULL.+ * GetModuleFileNameW signals truncation by returning the buffer size AND+ * setting ERROR_INSUFFICIENT_BUFFER; the length alone cannot be trusted,+ * which is why the error code is cleared first and then consulted. */+wchar_t *coli_win32_loader_module_path(HMODULE mod, DWORD *err){+ size_t cap = COLI_W32_PATH_START;+ int round;+ if(err) *err = 0;+ for(round = 0; round < COLI_W32_PATH_ROUNDS; round++){+ wchar_t *buf;+ DWORD n;+ if(!coli_w32_grow_ok(cap)){ if(err) *err = ERROR_ARITHMETIC_OVERFLOW; return NULL; }+ buf = (wchar_t *)malloc(cap * sizeof(wchar_t));+ if(!buf){ if(err) *err = ERROR_NOT_ENOUGH_MEMORY; return NULL; }+ SetLastError(ERROR_SUCCESS);+ n = GetModuleFileNameW(mod, buf, (DWORD)cap);+ if(n == 0){+ DWORD e = GetLastError();+ free(buf);+ if(err) *err = e;+ return NULL;+ }+ if((size_t)n < cap && GetLastError() != ERROR_INSUFFICIENT_BUFFER){+ buf[n] = L'\0';+ return buf;+ }+ free(buf);+ cap *= 2;+ }+ if(err) *err = ERROR_INSUFFICIENT_BUFFER;+ return NULL;+}++wchar_t *coli_win32_loader_exe_path(DWORD *err){+ return coli_win32_loader_module_path(NULL, err);+}++/* Canonical path behind an open handle, for DIAGNOSTICS ONLY. It resolves+ * case, dot segments, symlinks and junctions β but NOT hard links, which keep+ * their own names. That is exactly why equality is decided on file identity+ * and this string is only ever shown to a human. The VOLUME_NAME_DOS form is+ * returned as Windows gives it, including any \\?\ prefix: stripping that+ * prefix can change how a path is interpreted, so it is left intact. */+wchar_t *coli_win32_loader_final_path(HANDLE handle, DWORD *err){+ size_t cap = COLI_W32_PATH_START;+ int round;+ if(err) *err = 0;+ for(round = 0; round < COLI_W32_PATH_ROUNDS; round++){+ wchar_t *buf;+ DWORD n;+ if(!coli_w32_grow_ok(cap)){ if(err) *err = ERROR_ARITHMETIC_OVERFLOW; return NULL; }+ buf = (wchar_t *)malloc(cap * sizeof(wchar_t));+ if(!buf){ if(err) *err = ERROR_NOT_ENOUGH_MEMORY; return NULL; }+ SetLastError(ERROR_SUCCESS);+ n = GetFinalPathNameByHandleW(handle, buf, (DWORD)cap,+ FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);+ if(n == 0){+ DWORD e = GetLastError();+ free(buf);+ if(err) *err = e;+ return NULL;+ }+ if((size_t)n < cap){ buf[n] = L'\0'; return buf; }+ free(buf);+ /* n is the required size INCLUDING the terminator when it did not fit. */+ cap = (size_t)n + 1;+ }+ if(err) *err = ERROR_INSUFFICIENT_BUFFER;+ return NULL;+}++/* <dir> + one separator + <child>. Purely textual: nothing is resolved,+ * expanded or searched for. A value already ending in a separator does not+ * gain a second one, because "C:\x\\y" reads as a UNC root. */+wchar_t *coli_win32_loader_join(const wchar_t *dir, const wchar_t *child, DWORD *err){+ size_t dl, cl, need;+ int sep;+ wchar_t *out;+ if(err) *err = 0;+ if(!dir || !child || !dir[0]){ if(err) *err = ERROR_INVALID_PARAMETER; return NULL; }+ dl = wcslen(dir);+ cl = wcslen(child);+ sep = !coli_win32_loader_is_sep(dir[dl - 1]);+ if(cl > ((size_t)-1) - dl - 2){ if(err) *err = ERROR_ARITHMETIC_OVERFLOW; return NULL; }+ need = dl + (size_t)(sep ? 1 : 0) + cl + 1;+ if(need > ((size_t)-1) / sizeof(wchar_t)){ if(err) *err = ERROR_ARITHMETIC_OVERFLOW; return NULL; }+ out = (wchar_t *)malloc(need * sizeof(wchar_t));+ if(!out){ if(err) *err = ERROR_NOT_ENOUGH_MEMORY; return NULL; }+ wcscpy(out, dir);+ if(sep) wcscat(out, L"\\");+ wcscat(out, child);+ return out;+}++/* One open, both answers. Zero requested access means "query metadata": it+ * needs no read permission and cannot disturb a mapped module. Full sharing+ * means the probe never blocks anyone else, and FILE_FLAG_BACKUP_SEMANTICS+ * lets the same call work if the target turns out to be a directory. */+int coli_win32_loader_probe(const wchar_t *path, ColiW32FileId *id,+ wchar_t **final_path, DWORD *err){+ HANDLE h;+ FILE_ID_INFO fii;+ BY_HANDLE_FILE_INFORMATION bhi;+ if(final_path) *final_path = NULL;+ if(err) *err = 0;+ if(!id) return 0;+ memset(id, 0, sizeof *id);+ if(!path){ id->error = ERROR_INVALID_PARAMETER; if(err) *err = id->error; return 0; }++ h = CreateFileW(path, 0,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+ NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);+ if(h == INVALID_HANDLE_VALUE){+ id->error = GetLastError();+ if(err) *err = id->error;+ return 0;+ }+ if(GetFileInformationByHandleEx(h, FileIdInfo, &fii, (DWORD)sizeof fii)){+ id->have_id_info = 1;+ id->idi_volume = fii.VolumeSerialNumber;+ id->idi_id = fii.FileId;+ }+ if(GetFileInformationByHandle(h, &bhi)){+ id->have_by_handle = 1;+ id->bh_volume = bhi.dwVolumeSerialNumber;+ id->bh_index_high = bhi.nFileIndexHigh;+ id->bh_index_low = bhi.nFileIndexLow;+ }+ if(!coli_win32_loader_identity_valid(id)){+ id->error = GetLastError();+ if(err) *err = id->error;+ CloseHandle(h);+ return 0;+ }+ if(final_path) *final_path = coli_win32_loader_final_path(h, NULL);+ CloseHandle(h);+ return 1;+}++/* --- inventory of every loaded module with a given base name ---------- */++enum {+ COLI_W32_INV_OK = 0,+ COLI_W32_INV_SNAPSHOT_FAILED,+ COLI_W32_INV_ENUM_FAILED,+ COLI_W32_INV_ALLOC_FAILED,+ COLI_W32_INV_PATH_FAILED,+ COLI_W32_INV_IDENTITY_FAILED+};++typedef struct {+ HMODULE module;+ wchar_t *path; /* authoritative, from GetModuleFileNameW */+ wchar_t *final_path; /* canonical, diagnostics only, may be NULL */+ wchar_t *entry_path; /* MODULEENTRY32W.szExePath, MAX_PATH, fallback */+ ColiW32FileId id;+} ColiW32Module;++typedef struct {+ int status;+ DWORD error;+ size_t count;+ ColiW32Module *items;+} ColiW32Inventory;++void coli_win32_loader_inventory_free(ColiW32Inventory *inv){+ size_t i;+ if(!inv) return;+ for(i = 0; i < inv->count; i++){+ free(inv->items[i].path);+ free(inv->items[i].final_path);+ free(inv->items[i].entry_path);+ }+ free(inv->items);+ inv->items = NULL;+ inv->count = 0;+}++static wchar_t *coli_w32_wdup(const wchar_t *s){+ size_t n;+ wchar_t *o;+ if(!s) return NULL;+ n = wcslen(s) + 1;+ o = (wchar_t *)malloc(n * sizeof(wchar_t));+ if(o) memcpy(o, s, n * sizeof(wchar_t));+ return o;+}++/* Enumerate, do not ask. A failed or partial enumeration is reported as such:+ * it must never be mistaken for "nothing is loaded", because the two lead to+ * opposite decisions. Reference counts are untouched β the HMODULEs recorded+ * here are observations, not owned references. */+int coli_win32_loader_inventory(const wchar_t *basename, ColiW32Inventory *out){+ int attempt;+ if(!out) return COLI_W32_INV_ALLOC_FAILED;+ memset(out, 0, sizeof *out);+ if(!basename){ out->status = COLI_W32_INV_ENUM_FAILED; out->error = ERROR_INVALID_PARAMETER; return out->status; }++ for(attempt = 0; attempt < 8; attempt++){+ HANDLE snap;+ MODULEENTRY32W entry;+ BOOL more;++ snap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32,+ GetCurrentProcessId());+ if(snap == INVALID_HANDLE_VALUE){+ DWORD e = GetLastError();+ /* The module list changed underneath the snapshot; that is normal+ * and transient, so retry rather than report a failure. */+ if(e == ERROR_BAD_LENGTH) continue;+ out->status = COLI_W32_INV_SNAPSHOT_FAILED;+ out->error = e;+ return out->status;+ }++ memset(&entry, 0, sizeof entry);+ entry.dwSize = sizeof entry;+ more = Module32FirstW(snap, &entry);+ if(!more){+ DWORD e = GetLastError();+ CloseHandle(snap);+ if(e == ERROR_BAD_LENGTH) continue;+ out->status = COLI_W32_INV_ENUM_FAILED;+ out->error = e;+ return out->status;+ }+ do {+ ColiW32Module *grown, item;+ DWORD err = 0;+ if(_wcsicmp(entry.szModule, basename) != 0) continue;++ memset(&item, 0, sizeof item);+ item.module = entry.hModule;+ item.entry_path = coli_w32_wdup(entry.szExePath);+ item.path = coli_win32_loader_module_path(entry.hModule, &err);+ if(!item.path){+ free(item.entry_path);+ CloseHandle(snap);+ coli_win32_loader_inventory_free(out);+ out->status = COLI_W32_INV_PATH_FAILED;+ out->error = err;+ return out->status;+ }+ if(!coli_win32_loader_probe(item.path, &item.id, &item.final_path, &err)){+ free(item.entry_path);+ free(item.path);+ CloseHandle(snap);+ coli_win32_loader_inventory_free(out);+ out->status = COLI_W32_INV_IDENTITY_FAILED;+ out->error = err;+ return out->status;+ }+ grown = (ColiW32Module *)realloc(out->items,+ (out->count + 1) * sizeof *out->items);+ if(!grown){+ free(item.entry_path);+ free(item.path);+ free(item.final_path);+ CloseHandle(snap);+ coli_win32_loader_inventory_free(out);+ out->status = COLI_W32_INV_ALLOC_FAILED;+ out->error = ERROR_NOT_ENOUGH_MEMORY;+ return out->status;+ }+ out->items = grown;+ out->items[out->count++] = item;+ } while(Module32NextW(snap, &entry));++ CloseHandle(snap);+ out->status = COLI_W32_INV_OK;+ out->error = 0;+ return out->status;+ }+ out->status = COLI_W32_INV_SNAPSHOT_FAILED;+ out->error = ERROR_BAD_LENGTH;+ return out->status;+}++/* --- the decision ----------------------------------------------------+ *+ * Deliberately pure: no Windows call, no allocation, no global state, nothing+ * loaded. It takes the comparison results rather than the identities so that+ * every branch β including the ones the filesystem will not produce on demand+ * β can be driven directly from a test. */+enum {+ COLI_BIND_NEED_EXACT_LOAD = 0,+ COLI_BIND_REUSE_EXACT_MATCH,+ COLI_BIND_REJECT_WRONG_RUNTIME,+ COLI_BIND_REJECT_MULTIPLE_RUNTIMES,+ COLI_BIND_REJECT_UNVERIFIABLE+};++int coli_win32_loader_decide(int configured_valid, int inventory_status,+ size_t count, const int *match_equality){+ if(!configured_valid) return COLI_BIND_REJECT_UNVERIFIABLE;+ if(inventory_status != COLI_W32_INV_OK) return COLI_BIND_REJECT_UNVERIFIABLE;+ if(count == 0) return COLI_BIND_NEED_EXACT_LOAD;+ /* More than one same-basename runtime is refused even when one of them is+ * the configured file: which one an import binds to is decided by load+ * order, not by us, so the situation is not something to pick a winner in. */+ if(count > 1) return COLI_BIND_REJECT_MULTIPLE_RUNTIMES;+ if(!match_equality) return COLI_BIND_REJECT_UNVERIFIABLE;+ if(match_equality[0] == 1) return COLI_BIND_REUSE_EXACT_MATCH;+ if(match_equality[0] == 0) return COLI_BIND_REJECT_WRONG_RUNTIME;+ return COLI_BIND_REJECT_UNVERIFIABLE; /* identity unknown -> refuse */+}++/* --- the configured runtime, as a short-lived fact -------------------+ *+ * Only what this slice can honestly establish: where the runtime is, what file+ * that is, and how to name it in a message. No module handle, no ownership+ * flag, no verification state β those become real when something is actually+ * loaded, and inventing them now would mean carrying fields that no code can+ * yet set correctly. */+typedef struct {+ wchar_t *path;+ wchar_t *final_path;+ ColiW32FileId id;+ int valid;+ DWORD error;+} ColiW32ConfiguredRuntime;++/* Idempotent, and safe on a zero-initialised object. */+void coli_win32_loader_configured_free(ColiW32ConfiguredRuntime *cr){+ if(!cr) return;+ free(cr->path);+ free(cr->final_path);+ cr->path = NULL;+ cr->final_path = NULL;+ cr->valid = 0;+}++int coli_win32_loader_configured(const wchar_t *dir, ColiW32ConfiguredRuntime *out){+ DWORD err = 0;+ if(!out) return 0;+ memset(out, 0, sizeof *out);+ out->path = coli_win32_loader_join(dir, COLI_W32_RUNTIME_BASENAME, &err);+ if(!out->path){ out->error = err; return 0; }+ if(!coli_win32_loader_probe(out->path, &out->id, &out->final_path, &err)){+ out->error = err;+ return 0; /* path retained for diagnostics; free() is the caller's */+ }+ out->valid = 1;+ return 1;+}++#ifdef COLI_LOADER_TEST_API+/* ---- Test-only surface (never compiled into the shipped host) --------+ *+ * The loader tests run the REAL functions above by compiling this file into a+ * native harness with COLI_LOADER_TEST_API defined. Only that build has these+ * symbols; the normal host build contains none of them.+ *+ * Everything is passed by value or through caller-owned buffers on purpose:+ * no internal pointer, no struct layout and no mutable global escapes, so the+ * test surface cannot become a back door into loader state. */++static int coli_w32_test_utf8(const wchar_t *w, char *out, size_t cap){+ if(!out || cap == 0) return 0;+ out[0] = '\0';+ if(!w) return 0;+ return WideCharToMultiByte(CP_UTF8, 0, w, -1, out, (int)cap, NULL, NULL) > 0;+}++/* 1 same file, 0 different, -1 undeterminable β the production contract. */+int coli_loader_test_same_file(const wchar_t *a, const wchar_t *b){+ ColiW32FileId ia, ib;+ coli_win32_loader_probe(a, &ia, NULL, NULL);+ coli_win32_loader_probe(b, &ib, NULL, NULL);+ return coli_win32_loader_identity_equal(&ia, &ib);+}++/* Drives the symmetric fallback directly: the caller says which+ * representations each side has, so the mixed case can be exercised without+ * needing a filesystem on which one API fails. */+int coli_loader_test_identity_equal_synthetic(int a_idi, int a_bh, int b_idi, int b_bh,+ int same_idi, int same_bh){+ ColiW32FileId a, b;+ memset(&a, 0, sizeof a);+ memset(&b, 0, sizeof b);+ a.have_id_info = a_idi; a.have_by_handle = a_bh;+ b.have_id_info = b_idi; b.have_by_handle = b_bh;+ a.idi_volume = 1; b.idi_volume = same_idi ? 1 : 2;+ a.bh_volume = 1; b.bh_volume = same_bh ? 1 : 2;+ return coli_win32_loader_identity_equal(&a, &b);+}++int coli_loader_test_final_path(const wchar_t *path, char *out, size_t cap){+ ColiW32FileId id;+ wchar_t *final_path = NULL;+ int ok;+ if(!coli_win32_loader_probe(path, &id, &final_path, NULL)) return 0;+ ok = coli_w32_test_utf8(final_path, out, cap);+ free(final_path);+ return ok;+}++int coli_loader_test_join(const wchar_t *dir, const wchar_t *child, char *out, size_t cap){+ DWORD err = 0;+ wchar_t *joined = coli_win32_loader_join(dir, child, &err);+ int ok;+ if(!joined) return 0;+ ok = coli_w32_test_utf8(joined, out, cap);+ free(joined);+ return ok;+}++int coli_loader_test_exe_path(char *out, size_t cap){+ DWORD err = 0;+ wchar_t *p = coli_win32_loader_exe_path(&err);+ int ok;+ if(!p) return 0;+ ok = coli_w32_test_utf8(p, out, cap);+ free(p);+ return ok;+}++int coli_loader_test_decide(int configured_valid, int inventory_status,+ int count, const int *match_equality){+ return coli_win32_loader_decide(configured_valid, inventory_status,+ (size_t)count, match_equality);+}++int coli_loader_test_configured(const wchar_t *dir, char *path_out, size_t path_cap,+ char *final_out, size_t final_cap, unsigned long *error){+ ColiW32ConfiguredRuntime cr;+ int valid;+ int ok = coli_win32_loader_configured(dir, &cr);+ coli_w32_test_utf8(cr.path, path_out, path_cap);+ coli_w32_test_utf8(cr.final_path, final_out, final_cap);+ if(error) *error = cr.error;+ valid = cr.valid;+ coli_win32_loader_configured_free(&cr);+ coli_win32_loader_configured_free(&cr); /* proves the free is idempotent */+ (void)ok;+ return valid;+}++/* One inventory pass, flattened into caller-owned slots. *count is the true+ * match count even when it exceeds max_items, so a test can never mistake a+ * truncated report for a smaller inventory. */+int coli_loader_test_inventory(const wchar_t *configured_path,+ int *status, unsigned long *error, int *count,+ int max_items, int slot,+ char *paths, char *finals,+ unsigned long long *modules, int *equal_to_configured){+ ColiW32Inventory inv;+ ColiW32FileId configured;+ int have_configured = 0;+ size_t i;++ memset(&configured, 0, sizeof configured);+ if(configured_path)+ have_configured = coli_win32_loader_probe(configured_path, &configured, NULL, NULL);++ coli_win32_loader_inventory(COLI_W32_RUNTIME_BASENAME, &inv);+ if(status) *status = inv.status;+ if(error) *error = inv.error;+ if(count) *count = (int)inv.count;++ for(i = 0; i < inv.count && (int)i < max_items; i++){+ if(paths) coli_w32_test_utf8(inv.items[i].path, paths + (size_t)slot * i, (size_t)slot);+ if(finals) coli_w32_test_utf8(inv.items[i].final_path, finals + (size_t)slot * i, (size_t)slot);+ if(modules) modules[i] = (unsigned long long)(uintptr_t)inv.items[i].module;+ if(equal_to_configured)+ equal_to_configured[i] = have_configured+ ? coli_win32_loader_identity_equal(&configured, &inv.items[i].id)+ : -1;+ }+ coli_win32_loader_inventory_free(&inv);+ return inv.status;+}+#endif /* COLI_LOADER_TEST_API */+/* Resolve the DLL and all 11 symbols. Returns 1 on success, 0 otherwise.* Idempotent: the first call (success or fail) sticks; later calls are no-ops* that return the cached result. The engine treats a 0 return as "CUDAdiff --git a/c/tests/test_backend_loader.py b/c/tests/test_backend_loader.pyindex df9366c5..dc8bb62f 100644--- a/c/tests/test_backend_loader.py+++ b/c/tests/test_backend_loader.py@@ -171,8 +171,11 @@ class _StubFixture:self.harness_src = self.src_dir / "harness.c"self.harness_exe = self.harness_dir / "test_loader_harness.exe"self.cuda_harness_exe = self.harness_dir / "test_loader_harness_cuda.exe"+ self.helper_src = self.src_dir / "helpers.c"+ self.helper_exe = self.harness_dir / "test_loader_helpers.exe"self.harness_cmd = []self.cuda_harness_cmd = []+ self.helper_cmd = []self.runtime_a = self.runtime_a_dir / _RUNTIME_BASENAMEself.runtime_b = self.runtime_b_dir / _RUNTIME_BASENAMEself.backend = self.backend_dir / "coli_hip.dll"@@ -338,6 +341,181 @@ int main(int argc, char **argv)runtime_inventory("runtime_after_backend");return 0;}+'''++ HELPER_SOURCE = r'''+/* Native exerciser for the loader's internal Windows helpers (generated).+ *+ * Compiled together with the repository's real c/backend_loader.c and+ * -DCOLI_LOADER_TEST_API, so the functions under test are production's own.+ * The normal host build never defines that macro and therefore never contains+ * the coli_loader_test_* wrappers this file calls.+ *+ * Loads nothing except the controlled stub runtimes it is explicitly told to+ * preload, by absolute path. No PATH change, no System32, no real ROCm.+ *+ * usage: test_loader_helpers.exe <mode> [args...]+ */+#include <windows.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <wchar.h>++#define SLOT 4096+#define MAXI 8++int coli_loader_test_same_file(const wchar_t *a, const wchar_t *b);+int coli_loader_test_identity_equal_synthetic(int, int, int, int, int, int);+int coli_loader_test_final_path(const wchar_t *path, char *out, size_t cap);+int coli_loader_test_join(const wchar_t *dir, const wchar_t *child, char *out, size_t cap);+int coli_loader_test_exe_path(char *out, size_t cap);+int coli_loader_test_decide(int configured_valid, int inventory_status,+ int count, const int *match_equality);+int coli_loader_test_configured(const wchar_t *dir, char *path_out, size_t path_cap,+ char *final_out, size_t final_cap, unsigned long *error);+int coli_loader_test_inventory(const wchar_t *configured_path,+ int *status, unsigned long *error, int *count,+ int max_items, int slot,+ char *paths, char *finals,+ unsigned long long *modules, int *equal_to_configured);++/* "@N" means: take the real value from COLI_TEST_ARGN with+ * GetEnvironmentVariableW. Narrow argv is converted by Windows to the console+ * codepage before this program ever sees it, which destroys any character that+ * codepage lacks -- so a Unicode path cannot be passed positionally. The+ * environment is the same Unicode source production reads from, so routing+ * those arguments through it tests the helpers rather than argv. */+static wchar_t *wide(const char *s)+{+ static wchar_t bufs[8][SLOT];+ static int turn = 0;+ wchar_t *w = bufs[turn++ % 8];+ if (s[0] == '@' && s[1] >= '0' && s[1] <= '9' && s[2] == '\0') {+ wchar_t name[] = L"COLI_TEST_ARG0";+ name[13] = (wchar_t)s[1];+ w[0] = L'\0';+ GetEnvironmentVariableW(name, w, SLOT);+ return w;+ }+ MultiByteToWideChar(CP_UTF8, 0, s, -1, w, SLOT);+ return w;+}++/* The prefix keeps the before- and after-preload dumps apart; identical keys+ * would silently overwrite each other in the caller's parsed output. */+static void dump_inventory(const char *prefix, const wchar_t *configured)+{+ char paths[MAXI][SLOT], finals[MAXI][SLOT];+ unsigned long long mods[MAXI];+ int eq[MAXI], status = -1, count = -1, i;+ unsigned long err = 0;+ memset(paths, 0, sizeof paths);+ memset(finals, 0, sizeof finals);+ coli_loader_test_inventory(configured, &status, &err, &count,+ MAXI, SLOT, &paths[0][0], &finals[0][0], mods, eq);+ printf("%s_status=%d\n", prefix, status);+ printf("%s_error=%lu\n", prefix, err);+ printf("%s_count=%d\n", prefix, count);+ for (i = 0; i < count && i < MAXI; i++) {+ printf("%s_%d_path=%s\n", prefix, i, paths[i]);+ printf("%s_%d_final=%s\n", prefix, i, finals[i]);+ printf("%s_%d_module=%llu\n", prefix, i, mods[i]);+ printf("%s_%d_equal=%d\n", prefix, i, eq[i]);+ }+}++int main(int argc, char **argv)+{+ const char *mode = (argc > 1) ? argv[1] : "";+ char buf[SLOT], buf2[SLOT];++ /* The enum values themselves, so a rename in production cannot leave the+ * tests quietly asserting stale numbers. */+ if (!strcmp(mode, "enums")) {+ int eq1 = 1;+ printf("need_exact_load=%d\n", coli_loader_test_decide(1, 0, 0, NULL));+ printf("reuse_exact_match=%d\n", coli_loader_test_decide(1, 0, 1, &eq1));+ { int e0 = 0; printf("reject_wrong_runtime=%d\n", coli_loader_test_decide(1, 0, 1, &e0)); }+ { int two[2] = {1, 1}; printf("reject_multiple_runtimes=%d\n", coli_loader_test_decide(1, 0, 2, two)); }+ printf("reject_unverifiable=%d\n", coli_loader_test_decide(0, 0, 0, NULL));+ return 0;+ }++ /* decide <configured_valid> <inventory_status> <count> [equality ...] */+ if (!strcmp(mode, "decide")) {+ int eq[MAXI], n = argc - 5, i;+ if (n < 0) n = 0;+ if (n > MAXI) n = MAXI;+ for (i = 0; i < n; i++) eq[i] = atoi(argv[5 + i]);+ printf("decision=%d\n", coli_loader_test_decide(+ atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), n ? eq : NULL));+ return 0;+ }++ if (!strcmp(mode, "identity")) {+ printf("same=%d\n", coli_loader_test_same_file(wide(argv[2]), wide(argv[3])));+ return 0;+ }++ /* a_idi a_bh b_idi b_bh same_idi same_bh -> the symmetric fallback, driven+ * directly instead of hoping the filesystem makes one API fail. */+ if (!strcmp(mode, "synthetic")) {+ printf("same=%d\n", coli_loader_test_identity_equal_synthetic(+ atoi(argv[2]), atoi(argv[3]), atoi(argv[4]),+ atoi(argv[5]), atoi(argv[6]), atoi(argv[7])));+ return 0;+ }++ if (!strcmp(mode, "join")) {+ printf("ok=%d\n", coli_loader_test_join(wide(argv[2]), wide(argv[3]), buf, sizeof buf));+ printf("join=%s\n", buf);+ return 0;+ }++ if (!strcmp(mode, "exepath")) {+ printf("ok=%d\n", coli_loader_test_exe_path(buf, sizeof buf));+ printf("exe=%s\n", buf);+ return 0;+ }++ if (!strcmp(mode, "final")) {+ printf("ok=%d\n", coli_loader_test_final_path(wide(argv[2]), buf, sizeof buf));+ printf("final=%s\n", buf);+ return 0;+ }++ if (!strcmp(mode, "configured")) {+ unsigned long err = 0;+ printf("valid=%d\n", coli_loader_test_configured(wide(argv[2]), buf, sizeof buf,+ buf2, sizeof buf2, &err));+ printf("cfg_path=%s\n", buf);+ printf("cfg_final=%s\n", buf2);+ printf("cfg_error=%lu\n", err);+ return 0;+ }++ /* inventory <configured-or-NONE> [absolute preload ...] */+ if (!strcmp(mode, "inventory")) {+ const wchar_t *configured = strcmp(argv[2], "NONE") ? wide(argv[2]) : NULL;+ int i;+ dump_inventory("before", configured);+ for (i = 3; i < argc; i++) {+ HMODULE h = LoadLibraryExW(wide(argv[i]), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);+ int (*marker)(void);+ printf("preload_%d_ok=%d\n", i - 3, h != NULL);+ if (!h) { printf("preload_%d_error=%lu\n", i - 3, GetLastError()); continue; }+ printf("preload_%d_module=%llu\n", i - 3, (unsigned long long)(UINT_PTR)h);+ marker = (int (*)(void))(void *)GetProcAddress(h, "coli_test_runtime_marker");+ if (marker) printf("preload_%d_marker=%d\n", i - 3, marker());+ }+ dump_inventory("after", configured);+ return 0;+ }++ printf("unknown_mode=%s\n", mode);+ return 2;+}'''def _gcc(self, args, what):@@ -483,6 +661,17 @@ int main(int argc, char **argv)self._gcc(self.cuda_harness_cmd,"building the native loader harness (CUDA mode)")+ # The helper exerciser is the only build that defines+ # COLI_LOADER_TEST_API; the two harnesses above and the shipped host+ # do not, so the test wrappers exist nowhere else.+ self.helper_src.write_text(self.HELPER_SOURCE, encoding="ascii")+ self.helper_cmd = [+ "-O0", "-DCOLI_CUDA", "-DCOLI_HIP_DLL", "-DCOLI_LOADER_TEST_API",+ "-I" + str(HERE), str(self.helper_src), str(HERE / "backend_loader.c"),+ "-o", str(self.helper_exe),+ ]+ self._gcc(self.helper_cmd, "building the loader helper exerciser")+# --- inspection (objdump only; nothing is ever loaded) -------------@staticmethod@@ -528,7 +717,47 @@ int main(int argc, char **argv)self.runtime_b_dir / "libamdhip64_7.a",self.dep_full, self.dep_lean, self.dep_full_src,self.dep_lean_src, self.backend_dep_src, self.backend_dep,- self.bad_pe, self.dep_full_dir / "libcoli_test_dep.a"]+ self.bad_pe, self.dep_full_dir / "libcoli_test_dep.a",+ self.helper_src, self.helper_exe]++ def run_helper(self, *args, cwd=None):+ """Run the helper exerciser in its own process and parse key=value output.++ No DLL is ever loaded into the Python interpreter: every LoadLibraryExW+ happens inside this short-lived subprocess, which has exited before the+ caller inspects the result.++ Any argument containing non-ASCII is hoisted into COLI_TEST_ARG<n> and+ replaced by the token ``@n``. Windows converts a narrow argv through the+ console codepage, which silently mangles characters that codepage+ cannot represent; the environment carries them intact, and it is what+ the production loader reads anyway.+ """+ env = {k: v for k, v in os.environ.items()+ if not k.startswith("COLI_TEST_ARG")}+ argv = []+ for arg in args:+ text = str(arg)+ if not text.isascii():+ slot = len(env.keys() & {"COLI_TEST_ARG%d" % i for i in range(10)})+ env["COLI_TEST_ARG%d" % slot] = text+ text = "@%d" % slot+ argv.append(text)+ # encoding="utf-8": the helper converts every path with+ # WideCharToMultiByte(CP_UTF8, ...), so its output is UTF-8 by+ # construction. Decoding it as the locale codepage instead would mangle+ # exactly the non-ASCII paths these tests exist to check.+ proc = subprocess.run(+ [str(self.helper_exe)] + argv, env=env,+ cwd=str(cwd) if cwd else str(self.harness_dir),+ text=True, encoding="utf-8", errors="replace",+ capture_output=True, timeout=120)+ fields = {}+ for line in (proc.stdout or "").splitlines():+ if "=" in line:+ key, _, value = line.partition("=")+ fields[key.strip()] = value.strip()+ return proc, fieldsdef run_harness(self, case_dir, preload, env=None, vendor="hip",with_backend=True, backend_override=None, extra_files=()):@@ -1127,6 +1356,350 @@ class LoaderRuntimeDirContractTest(unittest.TestCase):os.path.normcase(os.path.normpath(str(f.runtime_b))), detail)+class _HelperTestBase(unittest.TestCase):+ """Shared fixture for the W1-B2d1 helper exercisers."""++ fixture = None++ @classmethod+ def setUpClass(cls):+ reason = _fixture_toolchain_skip()+ if reason:+ raise unittest.SkipTest(reason)+ cls.fixture = _StubFixture()++ @classmethod+ def tearDownClass(cls):+ if cls.fixture is not None:+ cls.fixture.cleanup()+ cls.fixture = None++ def setUp(self):+ self.cases = tempfile.TemporaryDirectory(prefix="coli helper ")+ self.addCleanup(self.cases.cleanup)+++class LoaderFileIdentityTest(_HelperTestBase):+ """Does the loader decide "same file" on physical identity, not path text?++ This is the property that decides whether a correctly configured runtime+ reached by a hard link, a dot segment or a different case is accepted or+ wrongly refused. Every case runs the production comparison through the real+ c/backend_loader.c; nothing here loads a DLL.+ """++ def _same(self, a, b):+ proc, out = self.fixture.run_helper("identity", a, b)+ self.assertEqual(proc.returncode, 0, proc.stderr)+ return int(out["same"])++ def test_a_file_is_the_same_file_as_itself(self):+ self.assertEqual(self._same(self.fixture.runtime_a, self.fixture.runtime_a), 1)++ def test_two_distinct_runtimes_differ(self):+ self.assertEqual(self._same(self.fixture.runtime_a, self.fixture.runtime_b), 0)++ def test_hardlink_alias_is_the_same_physical_file(self):+ """Different name, different final path β same file, so: equal.++ A textual comparison fails this, which is precisely why the production+ code does not use one.+ """+ alias = Path(self.cases.name) / "aliased runtime.dll"+ try:+ os.link(self.fixture.runtime_a, alias)+ except (OSError, NotImplementedError, AttributeError) as exc:+ self.skipTest("hard links unavailable here: %s" % exc)+ self.assertEqual(self._same(self.fixture.runtime_a, alias), 1)+ # ...and the diagnostic paths really do disagree, so the test is not+ # accidentally comparing one string with itself.+ _, out_a = self.fixture.run_helper("final", self.fixture.runtime_a)+ _, out_b = self.fixture.run_helper("final", alias)+ self.assertEqual(out_a.get("ok"), "1")+ self.assertEqual(out_b.get("ok"), "1")+ self.assertNotEqual(out_a["final"], out_b["final"])++ def test_dot_dot_alias_is_the_same_physical_file(self):+ f = self.fixture+ dotted = f.runtime_a.parent / "sub" / ".." / f.runtime_a.name+ (f.runtime_a.parent / "sub").mkdir(exist_ok=True)+ self.assertEqual(self._same(f.runtime_a, dotted), 1)++ def test_case_variant_is_the_same_physical_file(self):+ f = self.fixture+ upper = Path(str(f.runtime_a.parent).upper()) / f.runtime_a.name.upper()+ self.assertEqual(self._same(f.runtime_a, upper), 1)++ def test_missing_file_is_unavailable_not_unequal(self):+ """Absent or unreadable must never be reported as "a different file"."""+ gone = Path(self.cases.name) / "no such runtime.dll"+ self.assertEqual(self._same(self.fixture.runtime_a, gone), -1)+ self.assertEqual(self._same(gone, gone), -1)++ def test_identity_representations_are_never_mixed(self):+ """The FILE_ID_INFO / by-handle fallback is symmetric.++ Driven through the pure comparison rather than by hoping some+ filesystem makes one API fail: whenever either side lacks the 128-bit+ ID, *both* sides drop to the 64-bit index, and when no representation+ is shared the answer is "unknown".+ """+ f = self.fixture++ def synth(a_idi, a_bh, b_idi, b_bh, same_idi, same_bh):+ _, out = f.run_helper("synthetic", a_idi, a_bh, b_idi, b_bh,+ same_idi, same_bh)+ return int(out["same"])++ # Both have the 128-bit ID: it decides, even when the 64-bit indices+ # would have said otherwise.+ self.assertEqual(synth(1, 1, 1, 1, 1, 0), 1)+ self.assertEqual(synth(1, 1, 1, 1, 0, 1), 0)+ # One side lacks it: both fall back to the by-handle index...+ self.assertEqual(synth(1, 1, 0, 1, 0, 1), 1)+ self.assertEqual(synth(0, 1, 1, 1, 1, 0), 0)+ # ...and a matching 128-bit ID on one side is never used against a+ # 64-bit index on the other.+ self.assertEqual(synth(1, 0, 0, 1, 1, 1), -1)+ self.assertEqual(synth(0, 1, 1, 0, 1, 1), -1)+ # Nothing on either side.+ self.assertEqual(synth(0, 0, 0, 0, 1, 1), -1)+++class LoaderPathHelperTest(_HelperTestBase):+ """Unicode path construction with no MAX_PATH anywhere in the contract."""++ def _join(self, dir_, child):+ proc, out = self.fixture.run_helper("join", dir_, child)+ self.assertEqual(proc.returncode, 0, proc.stderr)+ self.assertEqual(out.get("ok"), "1", proc.stdout)+ return out["join"]++ def test_join_inserts_exactly_one_separator(self):+ self.assertEqual(self._join(r"C:\rocm\bin", "amdhip64_7.dll"),+ r"C:\rocm\bin\amdhip64_7.dll")++ def test_join_does_not_double_an_existing_separator(self):+ for tail in ("\\", "/"):+ with self.subTest(tail=tail):+ joined = self._join(r"C:\rocm\bin" + tail, "amdhip64_7.dll")+ self.assertTrue(joined.endswith("amdhip64_7.dll"), joined)+ self.assertNotIn("\\\\", joined[2:])+ self.assertNotIn("//", joined)++ def test_join_preserves_spaces_and_unicode(self):+ joined = self._join("C:\\Program Files\\kΓΆrtid Ο", "amdhip64_7.dll")+ self.assertEqual(joined, "C:\\Program Files\\kΓΆrtid Ο\\amdhip64_7.dll")++ def test_join_handles_a_path_far_beyond_max_path(self):+ """MAX_PATH is not a correctness bound anywhere in the helper."""+ deep = "C:\\" + "\\".join("segment%03d" % i for i in range(80))+ self.assertGreater(len(deep), 260)+ joined = self._join(deep, "amdhip64_7.dll")+ self.assertEqual(joined, deep + "\\amdhip64_7.dll")++ def test_exe_path_is_the_running_helper(self):+ """The growing GetModuleFileNameW buffer returns a usable full path."""+ proc, out = self.fixture.run_helper("exepath")+ self.assertEqual(out.get("ok"), "1", proc.stdout)+ self.assertTrue(out["exe"].lower().endswith("test_loader_helpers.exe"),+ out["exe"])+ self.assertTrue(Path(out["exe"]).is_file(), out["exe"])++ def test_final_path_is_canonical_and_keeps_its_prefix(self):+ """Documented representation: VOLUME_NAME_DOS, \\\\?\\ prefix left intact.++ Stripping the prefix can change how a path is interpreted, so the+ helper does not, and this pins that decision down.+ """+ f = self.fixture+ _, out = f.run_helper("final", f.runtime_a)+ self.assertEqual(out.get("ok"), "1")+ final = out["final"]+ self.assertTrue(final.startswith("\\\\?\\"), final)+ self.assertTrue(final.lower().endswith(_RUNTIME_BASENAME), final)+ # Canonical: a dot-dot alias of the same file yields the same text.+ (f.runtime_a.parent / "sub").mkdir(exist_ok=True)+ _, dotted = f.run_helper("final", f.runtime_a.parent / "sub" / ".." / f.runtime_a.name)+ self.assertEqual(dotted.get("final"), final)++ def test_configured_runtime_foundation(self):+ """Directory in, absolute runtime path plus identity out."""+ f = self.fixture+ proc, out = f.run_helper("configured", f.runtime_a_dir)+ self.assertEqual(out.get("valid"), "1", proc.stdout)+ self.assertEqual(out["cfg_path"],+ str(f.runtime_a_dir / _RUNTIME_BASENAME))+ self.assertTrue(out["cfg_final"].lower().endswith(_RUNTIME_BASENAME))+ self.assertEqual(out.get("cfg_error"), "0")++ def test_configured_runtime_reports_a_missing_runtime(self):+ missing = Path(self.cases.name) / "empty dir"+ missing.mkdir()+ proc, out = self.fixture.run_helper("configured", missing)+ self.assertEqual(out.get("valid"), "0", proc.stdout)+ # The path is still built, so a diagnostic can name it.+ self.assertEqual(out["cfg_path"], str(missing / _RUNTIME_BASENAME))+ self.assertNotEqual(out.get("cfg_error"), "0")+++class LoaderInventoryTest(_HelperTestBase):+ """What does the process actually have loaded under that base name?++ Every module is loaded inside the helper subprocess, by absolute path, from+ the controlled stub fixtures. No real runtime, no PATH, no System32.+ """++ def _inventory(self, name, configured, *preloads):+ case = Path(self.cases.name) / name+ case.mkdir(parents=True, exist_ok=True)+ proc, out = self.fixture.run_helper(+ "inventory", configured, *preloads, cwd=case)+ self.assertEqual(proc.returncode, 0,+ "helper crashed\n%s\n%s" % (proc.stdout, proc.stderr))+ self.assertEqual(out.get("before_status"), "0", proc.stdout)+ self.assertEqual(out.get("after_status"), "0", proc.stdout)+ return out++ @staticmethod+ def _same_path(a, b):+ return os.path.normcase(os.path.normpath(a)) == \+ os.path.normcase(os.path.normpath(b))++ def test_nothing_preloaded_is_a_successful_empty_inventory(self):+ """Zero matches, reported as success β not as a failure."""+ f = self.fixture+ out = self._inventory("none", f.runtime_a)+ self.assertEqual(out["before_count"], "0")+ self.assertEqual(out["after_count"], "0")+ self.assertEqual(out["before_error"], "0")++ def test_runtime_a_preloaded_is_seen_once_and_identified(self):+ f = self.fixture+ out = self._inventory("a", f.runtime_a, f.runtime_a)+ self.assertEqual(out["preload_0_marker"], str(_RUNTIME_MARKER_A))+ self.assertEqual(out["after_count"], "1")+ self.assertTrue(self._same_path(out["after_0_path"], str(f.runtime_a)))+ self.assertEqual(out["after_0_equal"], "1")+ self.assertTrue(out["after_0_final"].lower().endswith(_RUNTIME_BASENAME))++ def test_runtime_b_preloaded_is_identified_as_not_the_configured_file(self):+ f = self.fixture+ out = self._inventory("b", f.runtime_a, f.runtime_b)+ self.assertEqual(out["preload_0_marker"], str(_RUNTIME_MARKER_B))+ self.assertEqual(out["after_count"], "1")+ self.assertTrue(self._same_path(out["after_0_path"], str(f.runtime_b)))+ self.assertEqual(out["after_0_equal"], "0")++ def test_two_runtimes_are_both_seen_as_distinct_modules(self):+ """The case a base-name lookup cannot report at all.++ Both are mapped, both are callable, both have their own HMODULE and+ identity β and exactly one of them is the configured file.+ """+ f = self.fixture+ out = self._inventory("ab", f.runtime_a, f.runtime_a, f.runtime_b)+ self.assertEqual(out["preload_0_marker"], str(_RUNTIME_MARKER_A))+ self.assertEqual(out["preload_1_marker"], str(_RUNTIME_MARKER_B))+ self.assertEqual(out["after_count"], "2")+ self.assertNotEqual(out["after_0_module"], out["after_1_module"])+ paths = {out["after_0_path"].lower(), out["after_1_path"].lower()}+ self.assertEqual(len(paths), 2, paths)+ self.assertTrue(out["after_0_final"] and out["after_1_final"])+ self.assertEqual({out["after_0_equal"], out["after_1_equal"]}, {"1", "0"})++ def test_repeated_load_of_one_runtime_is_still_one_module(self):+ """References are not modules: three loads, one inventory entry."""+ f = self.fixture+ out = self._inventory("refs", f.runtime_a,+ f.runtime_a, f.runtime_a, f.runtime_a)+ for i in range(3):+ self.assertEqual(out["preload_%d_ok" % i], "1")+ self.assertEqual(out["preload_%d_marker" % i], str(_RUNTIME_MARKER_A))+ self.assertEqual(out["after_count"], "1")+ self.assertEqual(out["preload_0_module"], out["preload_2_module"])++ def test_runtime_loaded_through_a_hardlink_still_matches_the_configured_file(self):+ """Configured by one path, loaded through another: physically equal.++ The alias keeps the production base name but lives in a different+ directory, because the inventory matches on base name β a runtime+ loaded under some *other* file name is a different module as far as the+ loaded-module list is concerned, which is a separate question from file+ identity. Here the path text differs and the physical file does not, so+ the comparison must say "same", which a textual test could not.+ """+ f = self.fixture+ alias_dir = Path(self.cases.name) / "alias dir"+ alias_dir.mkdir(exist_ok=True)+ alias = alias_dir / _RUNTIME_BASENAME+ try:+ if not alias.exists():+ os.link(f.runtime_a, alias)+ except (OSError, NotImplementedError, AttributeError) as exc:+ self.skipTest("hard links unavailable here: %s" % exc)+ out = self._inventory("hardlink", f.runtime_a, alias)+ self.assertEqual(out["after_count"], "1")+ self.assertNotEqual(os.path.normcase(out["after_0_path"]),+ os.path.normcase(str(f.runtime_a)))+ self.assertEqual(out["after_0_equal"], "1",+ "identity comparison rejected a hard link")+++class LoaderBindingDecisionTest(_HelperTestBase):+ """The pure decision: inventory plus configured identity in, one verdict out.++ The helper reads the enum values back out of production rather than+ restating them, so renaming or reordering the enum cannot leave these+ assertions quietly checking stale numbers.+ """++ def setUp(self):+ super().setUp()+ _, self.e = self.fixture.run_helper("enums")++ def test_enum_values_are_distinct(self):+ """Five outcomes must be five values, or the matrix below proves nothing."""+ values = [self.e[k] for k in ("need_exact_load", "reuse_exact_match",+ "reject_wrong_runtime",+ "reject_multiple_runtimes",+ "reject_unverifiable")]+ self.assertEqual(len(set(values)), 5, values)++ def test_decision_matrix(self):+ """Every branch, with exact result assertions."""+ f = self.fixture+ cases = [+ # (label, configured_valid, inv_status, count, equality, expected)+ ("zero matches", 1, 0, 0, [], "need_exact_load"),+ ("one identical", 1, 0, 1, [1], "reuse_exact_match"),+ ("one different", 1, 0, 1, [0], "reject_wrong_runtime"),+ ("one undeterminable", 1, 0, 1, [-1], "reject_unverifiable"),+ ("two different", 1, 0, 2, [1, 0], "reject_multiple_runtimes"),+ ("two identical", 1, 0, 2, [1, 1], "reject_multiple_runtimes"),+ ("configured unavailable", 0, 0, 0, [], "reject_unverifiable"),+ ("snapshot failure", 1, 1, 0, [], "reject_unverifiable"),+ ("enumeration failure", 1, 2, 0, [], "reject_unverifiable"),+ ("allocation failure", 1, 3, 0, [], "reject_unverifiable"),+ ("module-path failure", 1, 4, 0, [], "reject_unverifiable"),+ ("module-identity failure", 1, 5, 0, [], "reject_unverifiable"),+ ]+ for label, valid, status, count, eq, expected in cases:+ with self.subTest(case=label):+ _, out = f.run_helper("decide", valid, status, count, *eq)+ self.assertEqual(out.get("decision"), self.e[expected],+ "%s -> %s" % (label, out))++ def test_a_failed_inventory_never_looks_like_zero_matches(self):+ """The distinction the whole status model exists for."""+ f = self.fixture+ _, ok = f.run_helper("decide", 1, 0, 0)+ _, bad = f.run_helper("decide", 1, 1, 0)+ self.assertEqual(ok["decision"], self.e["need_exact_load"])+ self.assertEqual(bad["decision"], self.e["reject_unverifiable"])+ self.assertNotEqual(ok["decision"], bad["decision"])++class LoaderFailureDiagnosticTest(unittest.TestCase):"""When the backend will not load, does the message say what really happened?