diff --git a/.github/workflows/host-suites-2.yml b/.github/workflows/host-suites-2.yml index dd97a8152..53aba4d20 100644 --- a/.github/workflows/host-suites-2.yml +++ b/.github/workflows/host-suites-2.yml @@ -28,7 +28,8 @@ name: Host suites 2 # argus : test-argus-runtime test-machine-identity-argus # numeric2 : test-numeric-reduce-cpu test-divsqrt-host 6 s # tensor : test-tensor (M20 CPU tier, plain + ASan/UBSan + default-build -# no-test-hook nm check) test-m20-receipt test-tensor-mutations +# no-test-hook nm check) test-tensor-store test-m20-receipt +# test-tensor-mutations # Pinned dependencies are read from physics.lock, aienos.lock and argus.lock. # # Deliberately NOT here: @@ -146,7 +147,7 @@ jobs: sel runtime "$core|^src/(runtime|fabric)/|^tests/runtime/|^mk/fabric\.mk$|^tests/(r15_receipt_test\.sh|r16_[a-z_]+/)|^tools/(r15_|r16_|omegatool\.c)|^spec/r16-|^docs/r16-|^evidence/R15/|^(physics|aienos)\.lock$" sel argus "^src/runtime/|^tests/runtime/|^tests/bench_rx_argus\.c$|^mk/machine-identity\.mk$|^src/(sha256|omega_evidence)\.|^(physics|aienos|argus)\.lock$" sel numeric2 "^tests/(test_omega_reduce|test_omega_divsqrt_gb10)\.c$|^tests/numeric_oracle\.h$|^src/(omega_numeric|omega_blackwell_(encoder|codegen|matmul|qmd)|sha256)" - sel tensor "^tools/m20_receipt(_mutations)?\.sh$|^tests/test_m20_receipt\.sh$|^tests/fixtures/m20_receipt/|^src/tensor/|^tests/test_omega_tensor\.c$|^tools/tensor_mutations\.sh$|^mk/tensor\.mk$|^src/(omega_numeric|omega_blackwell_(encoder|codegen|matmul|qmd)|sha256)" + sel tensor "^tools/m20_receipt(_mutations)?\.sh$|^tests/test_m20_receipt\.sh$|^tests/fixtures/m20_receipt/|^src/tensor/|^tests/test_omega_tensor(_store)?\.c$|^tools/tensor_mutations\.sh$|^mk/tensor\.mk$|^src/(omega_numeric|omega_blackwell_(encoder|codegen|matmul|qmd)|sha256)" visor: needs: changes @@ -405,6 +406,8 @@ jobs: fetch-depth: 0 - name: M20 OMEGA_TENSOR CPU tier (plain + ASan/UBSan, test hook absent from default build; CPU only) run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-tensor + - name: M20 crash-safe storage lifetime (plain + ASan/UBSan; temp dirs only, CPU only) + run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-tensor-store - name: M20 receipt writer tests (fixtures only; shell + git + jq, no device) run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-m20-receipt - name: M20 OMEGA_TENSOR mutation sweep (each rule must turn the tests red) diff --git a/docs/tensor/M20_OMEGA_TENSOR.md b/docs/tensor/M20_OMEGA_TENSOR.md index 7515f93a3..49d70cea0 100644 --- a/docs/tensor/M20_OMEGA_TENSOR.md +++ b/docs/tensor/M20_OMEGA_TENSOR.md @@ -114,12 +114,16 @@ removed. Order and padding mutations are caught by the E1 WP-D suite. | CI | WIRED | `host-suites-2.yml` job `tensor`: `test-tensor` + `test-tensor-mutations` on the AArch64 hosted runner (not the Spark, not a qualification) | | GB10 parity | NOT_RUN | no GB10 realization table yet; no chip run in this work | | GB10 general matmul (Tensor Core beyond narrow K/tile) | MISSING_IMPLEMENTATION | | -| Crash-safe storage lifetime | MISSING_IMPLEMENTATION | storage is in-process memory only; no persistence or crash recovery | +| Crash-safe storage lifetime | PASS (CPU) | host PASS, forge log HIVE-M20-lifetime-light-182200 (`test-tensor-store` 314/0 plain + ASan/UBSan, 6/6 store mutants caught, hook absent from default build). `src/tensor/omega_tensor_store.{c,h}`: content-addressed payloads + checksummed journal, temp/fsync/rename/fsync-dir commit; recovery replays the journal, re-hashes every payload, refuses torn/short/corrupt records (typed errors), keeps generations monotonic; `test-tensor-store` (round trip, fork crash at all 8 commit phases, journal/payload truncated at every byte and bit-flipped, crafted journals) + 6 store mutants in `test-tensor-mutations` | | Reproducible receipt | PASS (CPU) | writer implemented and host-tested: `tools/m20_receipt.sh` writes `/.json` (0444, exclusive, never overwritten), QUALIFIED only with GB10 parity GB10 PASS + matching chip evidence; `test-m20-receipt` + 11 receipt mutants in `test-tensor-mutations`, forge log HIVE-M20-receipt-175835. No real M20 receipt has been written yet because the GB10 parity evidence does not exist. | | E1 numeric closure | PASS (on main) | E1 PASSED on main 4863803; receipt merged in omega#177 | -**M20 verdict: not qualified.** GB10 parity NOT_RUN; crash-safe storage -lifetime MISSING_IMPLEMENTATION; receipt writer host PASS, no M20 receipt written yet. +**M20 verdict: not qualified.** GB10 parity NOT_RUN; receipt writer host PASS, +no M20 receipt written yet. + +Known minor risks of the crash-safe store (neither ever returns wrong data): a +failed partial save can make a handle read as stale after reopen, and a +hand-deleted journal restarts the generation numbers. ## Open seams diff --git a/mk/tensor.mk b/mk/tensor.mk index 0d1f51b5e..a92e24ac7 100644 --- a/mk/tensor.mk +++ b/mk/tensor.mk @@ -16,9 +16,11 @@ # receipt writer tools/m20_receipt.sh (fixtures only) # test-tensor-e1-reduce alias of test-tensor (the reduction seam always # calls omega_reduce_cpu, E1 WP-D, omega #134) +# test-tensor-store crash-safe storage lifetime (omega_tensor_store): +# plain + ASan/UBSan, then test-tensor-no-hooks ifndef TENSOR_MK TENSOR_MK := 1 -.PHONY: test-tensor test-tensor-no-hooks test-tensor-mutations test-tensor-e1-reduce +.PHONY: test-tensor test-tensor-no-hooks test-tensor-mutations test-tensor-e1-reduce test-tensor-store TENSOR_CFLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -ffp-contract=off -Isrc -Isrc/tensor \ -DOMEGA_NUMERIC_CPU_ONLY TENSOR_SRCS = src/tensor/omega_tensor.c src/tensor/omega_tensor_cpu.c src/tensor/omega_tensor_reduce_seam.c \ @@ -28,7 +30,10 @@ TENSOR_DEPS = src/omega_numeric.c src/omega_numeric_provenance.c src/omega_black TENSOR_HDRS = src/tensor/omega_tensor.h src/tensor/omega_tensor_reduce_seam.h src/omega_numeric_reduce.h src/omega_numeric.h src/sha256.h src/omega_numeric_transc.h # Test builds only: compiles the test-only storage-generation hook. TENSOR_TEST_FLAGS = -DOMEGA_TENSOR_TEST_HOOKS -TENSOR_HOOK_SYMS = omega_tensor_test_set_storage_generation +TENSOR_HOOK_SYMS = omega_tensor_test_set_storage_generation omega_tensor_store_test_set_crash_step +# Crash-safe storage lifetime (omega_tensor_store); targets at the end of this file. +TENSOR_STORE_SRCS = src/tensor/omega_tensor_store.c +TENSOR_STORE_HDRS = src/tensor/omega_tensor_store.h $(OUT_DIR)/test_omega_tensor: tests/test_omega_tensor.c $(TENSOR_SRCS) $(TENSOR_DEPS) $(TENSOR_HDRS) @mkdir -p $(OUT_DIR) @@ -46,11 +51,15 @@ test-tensor: $(OUT_DIR)/test_omega_tensor $(OUT_DIR)/test_omega_tensor_asan # Default (library) build of the tensor sources: no OMEGA_TENSOR_TEST_HOOKS. # Fails if any test-only hook symbol is defined or referenced in the objects. -test-tensor-no-hooks: src/tensor/omega_tensor.c src/tensor/omega_tensor_cpu.c src/tensor/omega_tensor_reduce_seam.c $(TENSOR_HDRS) +test-tensor-no-hooks: src/tensor/omega_tensor.c src/tensor/omega_tensor_cpu.c src/tensor/omega_tensor_reduce_seam.c $(TENSOR_HDRS) \ + $(TENSOR_STORE_SRCS) $(TENSOR_STORE_HDRS) @mkdir -p $(OUT_DIR)/tensor-lib gcc $(TENSOR_CFLAGS) -O2 -c -o $(OUT_DIR)/tensor-lib/omega_tensor.o src/tensor/omega_tensor.c gcc $(TENSOR_CFLAGS) -O2 -c -o $(OUT_DIR)/tensor-lib/omega_tensor_cpu.o src/tensor/omega_tensor_cpu.c gcc $(TENSOR_CFLAGS) -O2 -c -o $(OUT_DIR)/tensor-lib/omega_tensor_reduce_seam.o src/tensor/omega_tensor_reduce_seam.c + gcc $(TENSOR_CFLAGS) -O2 -c -o $(OUT_DIR)/tensor-lib/omega_tensor_store.o src/tensor/omega_tensor_store.c + @if nm $(OUT_DIR)/tensor-lib/omega_tensor_store.o | grep -q "\b_exit\b"; then \ + echo "test-tensor-no-hooks: FAIL (crash hook _exit referenced by default omega_tensor_store.o)"; exit 1; fi @nm $(OUT_DIR)/tensor-lib/omega_tensor.o | grep -q " T omega_tensor_ctx_create\b" \ || { echo "test-tensor-no-hooks: FAIL (nm sanity: omega_tensor_ctx_create not found)"; exit 1; } @for s in $(TENSOR_HOOK_SYMS); do \ @@ -67,4 +76,26 @@ test-tensor-e1-reduce: test-tensor .PHONY: test-m20-receipt test-m20-receipt: tests/test_m20_receipt.sh + +# Crash-safe storage lifetime (src/tensor/omega_tensor_store.{c,h}): round +# trip, crash at every commit phase (fork + test-only hook), torn writes, +# crafted journals. Plain and ASan/UBSan, then test-tensor-no-hooks. Writes +# only under $TMPDIR (default /tmp). Its mutants run in test-tensor-mutations. + +$(OUT_DIR)/test_omega_tensor_store: tests/test_omega_tensor_store.c $(TENSOR_STORE_SRCS) $(TENSOR_SRCS) $(TENSOR_DEPS) \ + $(TENSOR_HDRS) $(TENSOR_STORE_HDRS) + @mkdir -p $(OUT_DIR) + gcc $(TENSOR_CFLAGS) $(TENSOR_TEST_FLAGS) -O2 -o $@ tests/test_omega_tensor_store.c $(TENSOR_STORE_SRCS) \ + $(TENSOR_SRCS) $(TENSOR_DEPS) + +$(OUT_DIR)/test_omega_tensor_store_asan: tests/test_omega_tensor_store.c $(TENSOR_STORE_SRCS) $(TENSOR_SRCS) \ + $(TENSOR_DEPS) $(TENSOR_HDRS) $(TENSOR_STORE_HDRS) + @mkdir -p $(OUT_DIR) + gcc $(TENSOR_CFLAGS) $(TENSOR_TEST_FLAGS) -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all \ + -o $@ tests/test_omega_tensor_store.c $(TENSOR_STORE_SRCS) $(TENSOR_SRCS) $(TENSOR_DEPS) + +test-tensor-store: $(OUT_DIR)/test_omega_tensor_store $(OUT_DIR)/test_omega_tensor_store_asan + ./$(OUT_DIR)/test_omega_tensor_store + ./$(OUT_DIR)/test_omega_tensor_store_asan + $(MAKE) --no-print-directory test-tensor-no-hooks endif diff --git a/src/tensor/omega_tensor_store.c b/src/tensor/omega_tensor_store.c new file mode 100644 index 000000000..0755ce8e4 --- /dev/null +++ b/src/tensor/omega_tensor_store.c @@ -0,0 +1,634 @@ +/* + * M20 OMEGA_TENSOR crash-safe storage lifetime. See omega_tensor_store.h. + * Commit pattern (temp write, fsync, rename, fsync directory; phased crash + * points behind a test-only hook that calls _exit) follows + * src/runtime/rx_generation.c; nothing from src/runtime is linked. + */ +#include "omega_tensor_store.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "sha256.h" + +#define JRN_MAGIC "OTSJRN1" /* 7 chars + NUL = 8 bytes */ +#define REC_MAGIC "OTSREC1" +#define JRN_VERSION 1u +#define HDR_BYTES 56u /* magic 8, version 4, capacity 4, count 8, sum 32 */ +#define HDR_SUM 24u +#define REC_BYTES 200u +#define REC_SUM 168u +#define REC_PUT 1u +#define REC_RELEASE 2u +#define PAYLOAD_TMP "payload.tmp" +#define JOURNAL_TMP "journal.tmp" +#define JOURNAL "journal" +#define PATH_MAX_LEN 600 + +typedef struct { + bool live; + uint64_t gen; + OmegaDType dtype; + uint32_t rank; + uint64_t shape[OMEGA_TENSOR_MAX_RANK]; + uint8_t value_id[32]; + uint8_t payload_sha[32]; +} StoreSlot; + +typedef struct { + uint32_t kind; + uint32_t slot; + uint64_t gen; + uint64_t seq; + uint32_t dtype; + uint32_t rank; + uint64_t shape[OMEGA_TENSOR_MAX_RANK]; + uint8_t value_id[32]; + uint8_t payload_sha[32]; +} Record; + +struct OmegaTensorStore { + char dir[PATH_MAX_LEN - 100]; + int lock_fd; + uint32_t cap; + StoreSlot *slots; + uint8_t *jbuf; /* journal file image: header + records */ + size_t jlen, jcap; + uint64_t count; /* records in jbuf */ + OmegaTensorCtx *vctx; /* private context used to recompute value ids */ + int crash_step; +}; + +/* ---- little-endian fields --------------------------------------------- */ + +static void put_u32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); } +static void put_u64(uint8_t *p, uint64_t v) { for (int i = 0; i < 8; i++) p[i] = (uint8_t)(v >> (8 * i)); } +static uint32_t get_u32(const uint8_t *p) { + uint32_t v = 0; + for (int i = 0; i < 4; i++) v |= (uint32_t)p[i] << (8 * i); + return v; +} +static uint64_t get_u64(const uint8_t *p) { + uint64_t v = 0; + for (int i = 0; i < 8; i++) v |= (uint64_t)p[i] << (8 * i); + return v; +} + +/* ---- crash points (test builds only) ---------------------------------- */ + +#ifdef OMEGA_TENSOR_TEST_HOOKS +#define CRASH_POINT(st, step) do { if ((st)->crash_step == (step)) _exit(86); } while (0) +int omega_tensor_store_test_set_crash_step(OmegaTensorStore *st, int step) { + if (!st || step < OMEGA_TSTORE_CRASH_NONE || step >= OMEGA_TSTORE_CRASH_COUNT) + return OMEGA_TENSOR_ERR_BAD_ARGS; + st->crash_step = step; + return OMEGA_TENSOR_OK; +} +#else +#define CRASH_POINT(st, step) ((void)(st), (void)(step)) +#endif + +/* ---- files ------------------------------------------------------------- */ + +static int path_join(char *out, size_t n, const char *a, const char *b) { + int w = snprintf(out, n, "%s/%s", a, b); + return (w < 0 || (size_t)w >= n) ? -1 : 0; +} + +static int write_full(int fd, const uint8_t *buf, size_t n) { + size_t off = 0; + while (off < n) { + ssize_t w = write(fd, buf + off, n - off); + if (w < 0) { + if (errno == EINTR) continue; + return -1; + } + off += (size_t)w; + } + return 0; +} + +static int fsync_path(const char *path) { + int fd = open(path, O_RDONLY); + if (fd < 0) return -1; + int rc = fsync(fd) == 0 ? 0 : -1; + close(fd); + return rc; +} + +/* Reads at most cap bytes of path into buf; *n = bytes read. A file longer + * than cap reads as cap bytes plus *longer = true. */ +static int read_upto(const char *path, uint8_t *buf, size_t cap, size_t *n, bool *longer) { + *n = 0; + *longer = false; + int fd = open(path, O_RDONLY); + if (fd < 0) return -1; + for (;;) { + uint8_t extra; + uint8_t *dst = *n < cap ? buf + *n : &extra; + size_t want = *n < cap ? cap - *n : 1; + ssize_t r = read(fd, dst, want); + if (r < 0) { + if (errno == EINTR) continue; + close(fd); + return -1; + } + if (r == 0) break; + if (*n >= cap) { *longer = true; break; } + *n += (size_t)r; + } + close(fd); + return 0; +} + +/* + * Durable replace of / with buf: write a temp file, fsync it, + * rename it over the final name, fsync the directory. step0 is the first of + * four crash points (PARTIAL, WRITTEN, RENAMED, SYNCED). + */ +static int commit_file(OmegaTensorStore *st, const char *tmp_name, const char *name, + const uint8_t *buf, size_t n, int step0) { + char tmp[PATH_MAX_LEN], final[PATH_MAX_LEN]; + if (path_join(tmp, sizeof tmp, st->dir, tmp_name) || path_join(final, sizeof final, st->dir, name)) + return OMEGA_TSTORE_ERR_IO; + const char *wpath = tmp; /* MUT:TSTORE_RENAME_BEFORE_WRITE (final name only after the bytes are durable) */ + int fd = open(wpath, O_CREAT | O_TRUNC | O_WRONLY, 0644); + if (fd < 0) return OMEGA_TSTORE_ERR_IO; +#ifdef OMEGA_TENSOR_TEST_HOOKS + if (st->crash_step == step0) { + size_t half = n / 2 ? n / 2 : (n ? 1 : 0); + if (write_full(fd, buf, half) == 0) (void)fsync(fd); + close(fd); + _exit(86); + } +#endif + if (write_full(fd, buf, n) != 0 || fsync(fd) != 0) { + close(fd); + return OMEGA_TSTORE_ERR_IO; + } + if (close(fd) != 0) return OMEGA_TSTORE_ERR_IO; + CRASH_POINT(st, step0 + 1); + if (rename(wpath, final) != 0) return OMEGA_TSTORE_ERR_IO; + CRASH_POINT(st, step0 + 2); + if (fsync_path(st->dir) != 0) return OMEGA_TSTORE_ERR_IO; + CRASH_POINT(st, step0 + 3); + return OMEGA_TENSOR_OK; +} + +static void hex_name(const uint8_t id[32], char out[69]) { + static const char hx[] = "0123456789abcdef"; + for (int i = 0; i < 32; i++) { + out[2 * i] = hx[id[i] >> 4]; + out[2 * i + 1] = hx[id[i] & 15]; + } + memcpy(out + 64, ".bin", 5); +} + +/* A payload file name: 64 lowercase hex digits + ".bin". */ +static bool is_payload_name(const char *s) { + if (strlen(s) != 68 || strcmp(s + 64, ".bin") != 0) return false; + for (int i = 0; i < 64; i++) + if (!((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f'))) return false; + return true; +} + +/* ---- shapes and payload bytes ----------------------------------------- */ + +/* Element count of a shape; 0 when the shape is invalid. */ +static uint64_t shape_elems(uint32_t dtype, uint32_t rank, const uint64_t *shape) { + if (omega_dtype_size((OmegaDType)dtype) == 0 || rank > OMEGA_TENSOR_MAX_RANK) return 0; + uint64_t e = 1; + for (uint32_t d = 0; d < rank; d++) { + if (shape[d] == 0 || shape[d] > OMEGA_TENSOR_MAX_ELEMS) return 0; + e *= shape[d]; + if (e > OMEGA_TENSOR_MAX_ELEMS) return 0; + } + return e; +} + +/* Every NaN becomes the canonical quiet NaN of its dtype (same rule as the + * value id), so a value id names exactly one payload byte string. */ +static void canonicalize(OmegaDType dt, uint8_t *buf, uint64_t elems) { + for (uint64_t e = 0; e < elems; e++) { + if (dt == OMEGA_DT_F32) { + uint8_t *p = buf + e * 4; + uint32_t u = get_u32(p); + if ((u & 0x7f800000U) == 0x7f800000U && (u & 0x007fffffU)) put_u32(p, 0x7fc00000U); + } else { + uint8_t *p = buf + e * 2; + uint16_t h = (uint16_t)(p[0] | (p[1] << 8)); + uint16_t c = h; + if (dt == OMEGA_DT_F16 && (h & 0x7c00U) == 0x7c00U && (h & 0x03ffU)) c = 0x7e00U; + if (dt == OMEGA_DT_BF16 && (h & 0x7f80U) == 0x7f80U && (h & 0x007fU)) c = 0x7fc0U; + p[0] = (uint8_t)c; + p[1] = (uint8_t)(c >> 8); + } + } +} + +/* Value id of a row-major payload, recomputed through the tensor layer. */ +static int payload_value_id(OmegaTensorStore *st, const StoreSlot *sl, const uint8_t *buf, + uint8_t vid[32]) { + OmegaTensor t; + int rc = omega_tensor_from_data(st->vctx, sl->dtype, sl->rank, sl->shape, buf, &t); + if (rc) return rc; + rc = omega_tensor_value_id(st->vctx, t, vid); + int rr = omega_tensor_release(st->vctx, t); + return rc ? rc : rr; +} + +/* + * Reads and verifies the payload of a live slot. On success *out (if not + * NULL) receives a malloc'd buffer of exactly the expected size. + */ +static int load_payload(OmegaTensorStore *st, const StoreSlot *sl, uint8_t **out) { + uint64_t elems = shape_elems((uint32_t)sl->dtype, sl->rank, sl->shape); + size_t expect = (size_t)elems * omega_dtype_size(sl->dtype); + if (elems == 0) return OMEGA_TSTORE_ERR_CORRUPT; + char name[69], path[PATH_MAX_LEN]; + hex_name(sl->value_id, name); + if (path_join(path, sizeof path, st->dir, name)) return OMEGA_TSTORE_ERR_IO; + uint8_t *buf = calloc(1, expect); + if (!buf) return OMEGA_TENSOR_ERR_CAPACITY; + size_t n; + bool longer; + if (read_upto(path, buf, expect, &n, &longer) != 0) { + int err = errno; + free(buf); + return err == ENOENT ? OMEGA_TSTORE_ERR_CORRUPT : OMEGA_TSTORE_ERR_IO; + } + /* The payload digest covers the bytes actually read; a short file keeps + * zeros past its end for the value id recomputation. */ + uint8_t dig[32], vid[32]; + sha256_hash(buf, n, dig); + int rc = payload_value_id(st, sl, buf, vid); + if (rc) { free(buf); return rc; } + if (longer || n != expect) { free(buf); return OMEGA_TSTORE_ERR_CORRUPT; } + if (memcmp(dig, sl->payload_sha, 32) != 0 || memcmp(vid, sl->value_id, 32) != 0) { /* MUT:TSTORE_HASH_VERIFY */ + free(buf); + return OMEGA_TSTORE_ERR_CORRUPT; + } + if (out) *out = buf; + else free(buf); + return OMEGA_TENSOR_OK; +} + +/* ---- journal encoding -------------------------------------------------- */ + +static void encode_header(uint32_t cap, uint64_t count, uint8_t out[HDR_BYTES]) { + memset(out, 0, HDR_BYTES); + memcpy(out, JRN_MAGIC, 8); + put_u32(out + 8, JRN_VERSION); + put_u32(out + 12, cap); + put_u64(out + 16, count); + sha256_hash(out, HDR_SUM, out + HDR_SUM); +} + +static void encode_record(const Record *r, uint8_t out[REC_BYTES]) { + memset(out, 0, REC_BYTES); + memcpy(out, REC_MAGIC, 8); + put_u32(out + 8, r->kind); + put_u32(out + 12, r->slot); + put_u64(out + 16, r->gen); + put_u64(out + 24, r->seq); + put_u32(out + 32, r->dtype); + put_u32(out + 36, r->rank); + for (uint32_t d = 0; d < OMEGA_TENSOR_MAX_RANK; d++) put_u64(out + 40 + 8 * d, r->shape[d]); + memcpy(out + 104, r->value_id, 32); + memcpy(out + 136, r->payload_sha, 32); + sha256_hash(out, REC_SUM, out + REC_SUM); +} + +static int decode_record(const uint8_t in[REC_BYTES], Record *r) { + uint8_t sum[32]; + if (memcmp(in, REC_MAGIC, 8) != 0) return OMEGA_TSTORE_ERR_TORN; + sha256_hash(in, REC_SUM, sum); + if (memcmp(sum, in + REC_SUM, 32) != 0) return OMEGA_TSTORE_ERR_TORN; /* MUT:TSTORE_RECORD_SUM */ + r->kind = get_u32(in + 8); + r->slot = get_u32(in + 12); + r->gen = get_u64(in + 16); + r->seq = get_u64(in + 24); + r->dtype = get_u32(in + 32); + r->rank = get_u32(in + 36); + for (uint32_t d = 0; d < OMEGA_TENSOR_MAX_RANK; d++) r->shape[d] = get_u64(in + 40 + 8 * d); + memcpy(r->value_id, in + 104, 32); + memcpy(r->payload_sha, in + 136, 32); + return OMEGA_TENSOR_OK; +} + +/* Applies one record to the slot table, refusing anything that does not + * follow from the state before it. Used by replay and by live commits. */ +static int apply_record(OmegaTensorStore *st, const Record *r, uint64_t expect_seq) { + if (r->seq != expect_seq || r->slot >= st->cap) return OMEGA_TSTORE_ERR_TORN; + StoreSlot *sl = &st->slots[r->slot]; + if (r->kind == REC_PUT) { + if (sl->live || sl->gen == UINT64_MAX || r->gen != sl->gen) return OMEGA_TSTORE_ERR_TORN; + if (shape_elems(r->dtype, r->rank, r->shape) == 0) return OMEGA_TSTORE_ERR_TORN; + for (uint32_t d = r->rank; d < OMEGA_TENSOR_MAX_RANK; d++) + if (r->shape[d] != 0) return OMEGA_TSTORE_ERR_TORN; + sl->live = true; + sl->dtype = (OmegaDType)r->dtype; + sl->rank = r->rank; + memcpy(sl->shape, r->shape, sizeof sl->shape); + memcpy(sl->value_id, r->value_id, 32); + memcpy(sl->payload_sha, r->payload_sha, 32); + return OMEGA_TENSOR_OK; + } + if (r->kind == REC_RELEASE) { + if (!sl->live || r->gen != sl->gen) return OMEGA_TSTORE_ERR_TORN; + sl->live = false; + sl->gen = r->gen + 1; /* MUT:TSTORE_GEN_RESET (released generation never returns) */ + return OMEGA_TENSOR_OK; + } + return OMEGA_TSTORE_ERR_TORN; +} + +static int jbuf_reserve(OmegaTensorStore *st, size_t need) { + if (need <= st->jcap) return 0; + size_t c = st->jcap ? st->jcap : 4096; + while (c < need) c *= 2; + uint8_t *p = realloc(st->jbuf, c); + if (!p) return -1; + st->jbuf = p; + st->jcap = c; + return 0; +} + +/* Appends r (seq = count) and commits the whole journal durably. On any + * failure the in-memory journal and slot table are unchanged. */ +static int commit_record(OmegaTensorStore *st, Record *r) { + if (r->slot >= st->cap) return OMEGA_TENSOR_ERR_BAD_ARGS; + r->seq = st->count; + StoreSlot saved = st->slots[r->slot]; + int rc = apply_record(st, r, st->count); + if (rc) return rc; + if (jbuf_reserve(st, st->jlen + REC_BYTES) != 0) { + st->slots[r->slot] = saved; + return OMEGA_TENSOR_ERR_CAPACITY; + } + size_t old_len = st->jlen; + encode_record(r, st->jbuf + st->jlen); + st->jlen += REC_BYTES; + encode_header(st->cap, st->count + 1, st->jbuf); + rc = commit_file(st, JOURNAL_TMP, JOURNAL, st->jbuf, st->jlen, OMEGA_TSTORE_CRASH_JOURNAL_PARTIAL); + if (rc) { + st->jlen = old_len; + encode_header(st->cap, st->count, st->jbuf); + st->slots[r->slot] = saved; + return rc; + } + st->count++; + return OMEGA_TENSOR_OK; +} + +/* ---- recovery ---------------------------------------------------------- */ + +static bool payload_referenced(const OmegaTensorStore *st, const char *name) { + char n[69]; + for (uint32_t i = 0; i < st->cap; i++) { + if (!st->slots[i].live) continue; + hex_name(st->slots[i].value_id, n); + if (strcmp(n, name) == 0) return true; + } + return false; +} + +/* Removes temp files and payloads no live slot refers to. When only_check is + * set, removes nothing and returns whether any payload file exists. */ +static int sweep_dir(OmegaTensorStore *st, bool only_check, bool *any_payload) { + DIR *d = opendir(st->dir); + if (!d) return OMEGA_TSTORE_ERR_IO; + struct dirent *e; + bool removed = false; + if (any_payload) *any_payload = false; + while ((e = readdir(d)) != NULL) { + bool is_tmp = strcmp(e->d_name, PAYLOAD_TMP) == 0 || strcmp(e->d_name, JOURNAL_TMP) == 0; + bool is_pay = is_payload_name(e->d_name); + if (is_pay && any_payload) *any_payload = true; + if (only_check) continue; + if (is_tmp || (is_pay && !payload_referenced(st, e->d_name))) { + char p[PATH_MAX_LEN]; + if (path_join(p, sizeof p, st->dir, e->d_name) == 0 && unlink(p) == 0) removed = true; + } + } + closedir(d); + if (removed && fsync_path(st->dir) != 0) return OMEGA_TSTORE_ERR_IO; + return OMEGA_TENSOR_OK; +} + +static int load_journal(OmegaTensorStore *st, const char *jpath, uint32_t capacity) { + struct stat sb; + int fd = open(jpath, O_RDONLY); + if (fd < 0) return OMEGA_TSTORE_ERR_IO; + if (fstat(fd, &sb) != 0 || sb.st_size < 0) { close(fd); return OMEGA_TSTORE_ERR_IO; } + size_t len = (size_t)sb.st_size; + if (jbuf_reserve(st, len + REC_BYTES) != 0) { close(fd); return OMEGA_TENSOR_ERR_CAPACITY; } + size_t got = 0; + while (got < len) { + ssize_t r = read(fd, st->jbuf + got, len - got); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) break; + got += (size_t)r; + } + close(fd); + len = got; + if (len < HDR_BYTES || memcmp(st->jbuf, JRN_MAGIC, 8) != 0) return OMEGA_TSTORE_ERR_TORN; + uint8_t sum[32]; + sha256_hash(st->jbuf, HDR_SUM, sum); + if (memcmp(sum, st->jbuf + HDR_SUM, 32) != 0) return OMEGA_TSTORE_ERR_TORN; /* MUT:TSTORE_HEADER_SUM */ + if (get_u32(st->jbuf + 8) != JRN_VERSION) return OMEGA_TSTORE_ERR_TORN; + if (get_u32(st->jbuf + 12) != capacity) return OMEGA_TENSOR_ERR_BAD_ARGS; + uint64_t count = get_u64(st->jbuf + 16); + if (count > (len - HDR_BYTES) / REC_BYTES + 1) count = (len - HDR_BYTES) / REC_BYTES + 1; + if (len != HDR_BYTES + count * REC_BYTES) return OMEGA_TSTORE_ERR_TORN; /* MUT:TSTORE_SHORT_RECORD */ + uint64_t i = 0; + for (; i < count && HDR_BYTES + (i + 1) * REC_BYTES <= len; i++) { + Record r; + int rc = decode_record(st->jbuf + HDR_BYTES + i * REC_BYTES, &r); + if (!rc) rc = apply_record(st, &r, i); + if (rc) return rc; + } + /* Keep exactly the records that were replayed (equal to the header count + * unless the length check above was bypassed). */ + st->count = i; + st->jlen = HDR_BYTES + i * REC_BYTES; + encode_header(st->cap, st->count, st->jbuf); + return OMEGA_TENSOR_OK; +} + +int omega_tensor_store_open(const char *dir, uint32_t capacity, OmegaTensorStore **out) { + if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; + *out = NULL; + if (!dir || capacity == 0 || capacity > OMEGA_TSTORE_MAX_CAPACITY || + strlen(dir) + 80 >= sizeof(((OmegaTensorStore *)0)->dir)) + return OMEGA_TENSOR_ERR_BAD_ARGS; + if (mkdir(dir, 0755) != 0 && errno != EEXIST) return OMEGA_TSTORE_ERR_IO; + OmegaTensorStore *st = calloc(1, sizeof(*st)); + if (!st) return OMEGA_TENSOR_ERR_CAPACITY; + snprintf(st->dir, sizeof st->dir, "%s", dir); + st->cap = capacity; + st->lock_fd = -1; + int rc = OMEGA_TENSOR_OK; + st->slots = calloc(capacity, sizeof(StoreSlot)); + if (!st->slots) { rc = OMEGA_TENSOR_ERR_CAPACITY; goto fail; } + for (uint32_t i = 0; i < capacity; i++) st->slots[i].gen = 1; + rc = omega_tensor_ctx_create(2, omega_tensor_cpu_realization(), &st->vctx); + if (rc) goto fail; + st->lock_fd = open(dir, O_RDONLY | O_DIRECTORY); + if (st->lock_fd < 0) { rc = OMEGA_TSTORE_ERR_IO; goto fail; } + if (flock(st->lock_fd, LOCK_EX | LOCK_NB) != 0) { + rc = errno == EWOULDBLOCK ? OMEGA_TSTORE_ERR_BUSY : OMEGA_TSTORE_ERR_IO; + goto fail; + } + char jpath[PATH_MAX_LEN]; + if (path_join(jpath, sizeof jpath, dir, JOURNAL)) { rc = OMEGA_TSTORE_ERR_IO; goto fail; } + if (access(jpath, F_OK) != 0) { + if (errno != ENOENT) { rc = OMEGA_TSTORE_ERR_IO; goto fail; } + /* No journal: a fresh store, unless payloads exist (a lost journal + * would silently reset every generation). */ + bool any = false; + rc = sweep_dir(st, true, &any); + if (rc) goto fail; + if (any) { rc = OMEGA_TSTORE_ERR_TORN; goto fail; } + if (jbuf_reserve(st, HDR_BYTES + REC_BYTES) != 0) { rc = OMEGA_TENSOR_ERR_CAPACITY; goto fail; } + encode_header(capacity, 0, st->jbuf); + st->jlen = HDR_BYTES; + rc = commit_file(st, JOURNAL_TMP, JOURNAL, st->jbuf, st->jlen, OMEGA_TSTORE_CRASH_COUNT); + if (rc) goto fail; + } else { + rc = load_journal(st, jpath, capacity); + if (rc) goto fail; + for (uint32_t i = 0; i < capacity; i++) { + if (!st->slots[i].live) continue; + rc = load_payload(st, &st->slots[i], NULL); + if (rc) goto fail; + } + } + rc = sweep_dir(st, false, NULL); + if (rc) goto fail; + *out = st; + return OMEGA_TENSOR_OK; +fail: + omega_tensor_store_close(st); + return rc; +} + +void omega_tensor_store_close(OmegaTensorStore *st) { + if (!st) return; + if (st->vctx) omega_tensor_ctx_destroy(st->vctx); + if (st->lock_fd >= 0) close(st->lock_fd); /* drops the flock */ + free(st->slots); + free(st->jbuf); + free(st); +} + +/* ---- live operations --------------------------------------------------- */ + +static StoreSlot *live_slot(const OmegaTensorStore *st, OmegaStorageHandle h) { + if (!st || h.slot >= st->cap) return NULL; + StoreSlot *sl = &st->slots[h.slot]; + if (!sl->live || sl->gen != h.generation) return NULL; + return sl; +} + +bool omega_tensor_store_valid(const OmegaTensorStore *st, OmegaStorageHandle h) { + return live_slot(st, h) != NULL; +} + +int omega_tensor_store_value_id(const OmegaTensorStore *st, OmegaStorageHandle h, uint8_t id[32]) { + if (!st || !id) return OMEGA_TENSOR_ERR_BAD_ARGS; + StoreSlot *sl = live_slot(st, h); + if (!sl) return OMEGA_TENSOR_ERR_STALE; + memcpy(id, sl->value_id, 32); + return OMEGA_TENSOR_OK; +} + +uint32_t omega_tensor_store_live_count(const OmegaTensorStore *st) { + uint32_t n = 0; + if (!st) return 0; + for (uint32_t i = 0; i < st->cap; i++) n += st->slots[i].live ? 1u : 0u; + return n; +} + +int omega_tensor_store_put(OmegaTensorStore *st, const OmegaTensorCtx *ctx, OmegaTensor t, + OmegaStorageHandle *out) { + if (!st || !ctx || !out) return OMEGA_TENSOR_ERR_BAD_ARGS; + OmegaTensorInfo info; + int rc = omega_tensor_info(ctx, t, &info); + if (rc) return rc; + uint32_t slot = st->cap; + for (uint32_t i = 0; i < st->cap; i++) + if (!st->slots[i].live && st->slots[i].gen != UINT64_MAX) { slot = i; break; } + if (slot == st->cap) return OMEGA_TENSOR_ERR_CAPACITY; + size_t es = omega_dtype_size(info.dtype); + size_t bytes = (size_t)info.elements * es; + uint8_t *buf = malloc(bytes); + if (!buf) return OMEGA_TENSOR_ERR_CAPACITY; + rc = omega_tensor_read(ctx, t, buf, bytes); + if (rc) { free(buf); return rc; } + canonicalize(info.dtype, buf, info.elements); + Record r; + memset(&r, 0, sizeof r); + r.kind = REC_PUT; + r.slot = slot; + r.gen = st->slots[slot].gen; + r.dtype = (uint32_t)info.dtype; + r.rank = info.rank; + for (uint32_t d = 0; d < info.rank; d++) r.shape[d] = info.shape[d]; + rc = omega_tensor_value_id(ctx, t, r.value_id); + if (rc) { free(buf); return rc; } + sha256_hash(buf, bytes, r.payload_sha); + char name[69]; + hex_name(r.value_id, name); + /* Payload first, journal second: the journal rename is the commit point. */ + rc = commit_file(st, PAYLOAD_TMP, name, buf, bytes, OMEGA_TSTORE_CRASH_PAYLOAD_PARTIAL); + free(buf); + if (rc) return rc; + rc = commit_record(st, &r); + if (rc) return rc; + out->slot = slot; + out->generation = r.gen; + return OMEGA_TENSOR_OK; +} + +int omega_tensor_store_get(OmegaTensorStore *st, OmegaStorageHandle h, OmegaTensorCtx *ctx, + OmegaTensor *out) { + if (!st || !ctx || !out) return OMEGA_TENSOR_ERR_BAD_ARGS; + StoreSlot *sl = live_slot(st, h); + if (!sl) return OMEGA_TENSOR_ERR_STALE; + uint8_t *buf = NULL; + int rc = load_payload(st, sl, &buf); + if (rc) return rc; + rc = omega_tensor_from_data(ctx, sl->dtype, sl->rank, sl->shape, buf, out); + free(buf); + return rc; +} + +int omega_tensor_store_release(OmegaTensorStore *st, OmegaStorageHandle h) { + if (!st) return OMEGA_TENSOR_ERR_BAD_ARGS; + StoreSlot *sl = live_slot(st, h); + if (!sl) return OMEGA_TENSOR_ERR_STALE; + uint8_t vid[32]; + memcpy(vid, sl->value_id, 32); + Record r; + memset(&r, 0, sizeof r); + r.kind = REC_RELEASE; + r.slot = h.slot; + r.gen = h.generation; + int rc = commit_record(st, &r); + if (rc) return rc; + /* Committed. Drop the payload if no other live slot shares it; a crash + * before this leaves an orphan that the next open removes. */ + char name[69], path[PATH_MAX_LEN]; + hex_name(vid, name); + if (!payload_referenced(st, name) && path_join(path, sizeof path, st->dir, name) == 0) + (void)unlink(path); + return OMEGA_TENSOR_OK; +} diff --git a/src/tensor/omega_tensor_store.h b/src/tensor/omega_tensor_store.h new file mode 100644 index 000000000..a0f46080a --- /dev/null +++ b/src/tensor/omega_tensor_store.h @@ -0,0 +1,107 @@ +#ifndef OMEGA_TENSOR_STORE_H +#define OMEGA_TENSOR_STORE_H + +/* + * M20 OMEGA_TENSOR crash-safe storage lifetime (docs/tensor/M20_OMEGA_TENSOR.md, + * row "Crash-safe storage lifetime"). Owned by src/tensor; does not link or + * call src/runtime (the commit pattern is copied from rx_generation.c). + * + * A store is a directory that keeps generation-checked tensor storage across + * process exits and crashes: + * /.bin content-addressed payload: the tensor's elements + * in logical row-major order, dtype width, + * little-endian, every NaN stored as the canonical + * quiet NaN (NaN payload is not semantic in M20, so + * a value id names exactly one byte string). + * /journal header + fixed-size records (PUT / RELEASE), + * each with slot, generation, sequence number, + * dtype, shape, value id and payload SHA-256, and + * its own SHA-256 checksum. + * + * Commit (put and release): the file is written to a temp name, fsynced, + * renamed over the final name, then the directory is fsynced. A put commits + * its payload first and its journal record second; the journal rename is the + * commit point. A crash anywhere leaves either the old or the new state. + * + * Recovery (open) replays the journal and refuses, with a typed error and + * without returning any data, when: + * - the journal is shorter or longer than its header says, a record or the + * header fails its checksum, or a record does not follow from the state + * before it (wrong sequence, wrong generation, release of a free slot, + * put on a live slot, slot or shape out of range): OMEGA_TSTORE_ERR_TORN; + * - a live record's payload is missing, short, long, or does not hash to + * the recorded payload SHA-256 and value id: OMEGA_TSTORE_ERR_CORRUPT; + * - the journal is missing while payload files exist (a lost journal would + * reset generations): OMEGA_TSTORE_ERR_TORN. + * Leftover temp files and payloads no live record refers to are removed. + * + * Generations: every slot starts at generation 1. A release bumps it, and the + * bump is journaled, so after any recovery a released handle stays released: + * its generation never comes back and it gets OMEGA_TENSOR_ERR_STALE. A slot + * whose generation reaches UINT64_MAX is retired, never wrapped. + * + * One opener at a time (flock on the directory; a second open gets + * OMEGA_TSTORE_ERR_BUSY). Not thread safe. The journal grows by one record + * per put/release and is rewritten whole on each commit (no compaction yet). + * Not covered: rollback of the whole directory to an older valid copy. + * + * Status codes: OMEGA_TENSOR_* from omega_tensor.h (OK, BAD_ARGS, STALE, + * CAPACITY, and any code of the tensor layer) plus the codes below. + */ + +#include +#include + +#include "omega_tensor.h" + +#define OMEGA_TSTORE_ERR_IO (-20) /* a file operation failed */ +#define OMEGA_TSTORE_ERR_TORN (-21) /* journal short/torn/inconsistent */ +#define OMEGA_TSTORE_ERR_CORRUPT (-22) /* payload missing or hash mismatch */ +#define OMEGA_TSTORE_ERR_BUSY (-23) /* store already open elsewhere */ + +#define OMEGA_TSTORE_MAX_CAPACITY (1u << 20) + +typedef struct OmegaTensorStore OmegaTensorStore; + +/* Opens (created if absent, with `capacity` slots), or recovers an + * existing store, whose recorded capacity must equal `capacity`. */ +int omega_tensor_store_open(const char *dir, uint32_t capacity, OmegaTensorStore **out); +void omega_tensor_store_close(OmegaTensorStore *st); + +/* Persists the value of t (any tensor or view of ctx) into a free slot and + * returns its handle once the commit is durable. */ +int omega_tensor_store_put(OmegaTensorStore *st, const OmegaTensorCtx *ctx, OmegaTensor t, + OmegaStorageHandle *out); +/* Loads the stored value into a new tensor of ctx. The payload hash and value + * id are checked again on every load. Stale handle: OMEGA_TENSOR_ERR_STALE. */ +int omega_tensor_store_get(OmegaTensorStore *st, OmegaStorageHandle h, OmegaTensorCtx *ctx, + OmegaTensor *out); +/* Releases the slot durably; every handle of it turns stale. Releasing twice, + * or through a stale handle, returns OMEGA_TENSOR_ERR_STALE and changes nothing. */ +int omega_tensor_store_release(OmegaTensorStore *st, OmegaStorageHandle h); +bool omega_tensor_store_valid(const OmegaTensorStore *st, OmegaStorageHandle h); +int omega_tensor_store_value_id(const OmegaTensorStore *st, OmegaStorageHandle h, uint8_t id[32]); +uint32_t omega_tensor_store_live_count(const OmegaTensorStore *st); + +/* Crash points, in commit order. A put passes 1..8, a release 5..8. */ +enum { + OMEGA_TSTORE_CRASH_NONE = 0, + OMEGA_TSTORE_CRASH_PAYLOAD_PARTIAL, /* half the payload temp written */ + OMEGA_TSTORE_CRASH_PAYLOAD_WRITTEN, /* payload temp fsynced, not renamed */ + OMEGA_TSTORE_CRASH_PAYLOAD_RENAMED, /* renamed, directory not fsynced */ + OMEGA_TSTORE_CRASH_PAYLOAD_SYNCED, /* payload durable, journal untouched */ + OMEGA_TSTORE_CRASH_JOURNAL_PARTIAL, /* half the journal temp written */ + OMEGA_TSTORE_CRASH_JOURNAL_WRITTEN, /* journal temp fsynced, not renamed */ + OMEGA_TSTORE_CRASH_JOURNAL_RENAMED, /* commit point passed */ + OMEGA_TSTORE_CRASH_JOURNAL_SYNCED, /* directory fsynced */ + OMEGA_TSTORE_CRASH_COUNT +}; + +#ifdef OMEGA_TENSOR_TEST_HOOKS +/* Test-only: the next commit that reaches `step` calls _exit(86) there. + * Compiled only with OMEGA_TENSOR_TEST_HOOKS; test-tensor-no-hooks checks with + * nm that the default build has neither this symbol nor a reference to _exit. */ +int omega_tensor_store_test_set_crash_step(OmegaTensorStore *st, int step); +#endif + +#endif /* OMEGA_TENSOR_STORE_H */ diff --git a/tests/test_omega_tensor_store.c b/tests/test_omega_tensor_store.c new file mode 100644 index 000000000..4c8dd4610 --- /dev/null +++ b/tests/test_omega_tensor_store.c @@ -0,0 +1,620 @@ +/* + * M20 OMEGA_TENSOR crash-safe storage lifetime tests + * (src/tensor/omega_tensor_store.h, docs/tensor/M20_OMEGA_TENSOR.md row + * "Crash-safe storage lifetime"). Host only, no device. + * + * round trip put/get/release across close and reopen, views, F16, + * rank 0, NaN canonical form, dedup, orphan sweep, busy + * lock, lost journal refused, generation monotonicity + * crash fork a child that crashes (_exit(86) via the test-only + * hook) at every commit phase of a put and of a release; + * the parent recovers and must see exactly the old state + * (before the journal rename) or the new state (after it) + * torn writes the journal truncated at every byte and with every byte + * flipped, the payload truncated at every byte, extended, + * and flipped: open must refuse with a typed error; a + * payload corrupted after open must be refused by get + * crafted journal an independent encoder of the documented format: the + * implementation's bytes match it, and records that do not + * follow from the state before them are refused + * Every refusal returns no data. Expected values come from the test's own + * tensors, never from the store. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef OMEGA_TENSOR_TEST_HOOKS +#error "test_omega_tensor_store.c needs -DOMEGA_TENSOR_TEST_HOOKS (set by mk/tensor.mk test build)" +#endif +#include "omega_numeric.h" +#include "omega_tensor.h" +#include "omega_tensor_store.h" +#include "sha256.h" + +static int g_pass, g_fail; +#define CHECK(cond, ...) do { if (cond) g_pass++; else { g_fail++; \ + printf("FAIL %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0) + +static OmegaTensorCtx *g; +static char g_root[256]; +static int g_ndir; + +/* ---- files ------------------------------------------------------------- */ + +static void new_dir(char *out, size_t n) { snprintf(out, n, "%s/s%d", g_root, g_ndir++); } + +static void rm_dir(const char *dir) { + DIR *d = opendir(dir); + if (!d) return; + struct dirent *e; + char p[1024]; + while ((e = readdir(d)) != NULL) { + if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue; + snprintf(p, sizeof p, "%s/%s", dir, e->d_name); + unlink(p); + } + closedir(d); + rmdir(dir); +} + +static int read_file(const char *path, uint8_t **buf, size_t *n) { + struct stat sb; + *buf = NULL; + *n = 0; + int fd = open(path, O_RDONLY); + if (fd < 0) return -1; + if (fstat(fd, &sb) != 0) { close(fd); return -1; } + *buf = malloc((size_t)sb.st_size + 1); + size_t got = 0; + while (*buf && got < (size_t)sb.st_size) { + ssize_t r = read(fd, *buf + got, (size_t)sb.st_size - got); + if (r <= 0) break; + got += (size_t)r; + } + close(fd); + *n = got; + return (*buf && got == (size_t)sb.st_size) ? 0 : -1; +} + +static int write_file(const char *path, const uint8_t *buf, size_t n) { + int fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0644); + if (fd < 0) return -1; + size_t off = 0; + while (off < n) { + ssize_t w = write(fd, buf + off, n - off); + if (w <= 0) { close(fd); return -1; } + off += (size_t)w; + } + close(fd); + return 0; +} + +static bool exists(const char *dir, const char *name) { + char p[1024]; + snprintf(p, sizeof p, "%s/%s", dir, name); + return access(p, F_OK) == 0; +} + +static void payload_name(const uint8_t id[32], char out[69]) { + for (int i = 0; i < 32; i++) snprintf(out + 2 * i, 3, "%02x", id[i]); + snprintf(out + 64, 5, ".bin"); +} + +/* ---- tensors ----------------------------------------------------------- */ + +static OmegaTensor mk_bits(uint32_t rank, const uint64_t *shape, const uint32_t *bits) { + uint64_t n = 1; + for (uint32_t d = 0; d < rank; d++) n *= shape[d]; + float *f = malloc(n * sizeof(float)); + memcpy(f, bits, n * sizeof(float)); + OmegaTensor t = {0, 0}; + int rc = omega_tensor_from_f32(g, rank, shape, f, &t); + CHECK(rc == OMEGA_TENSOR_OK, "setup: from_f32 rc %d", rc); + free(f); + return t; +} + +static OmegaTensor mk_vals(uint32_t rank, const uint64_t *shape, uint32_t seed) { + uint32_t bits[64]; + uint64_t n = 1; + for (uint32_t d = 0; d < rank; d++) n *= shape[d]; + for (uint64_t i = 0; i < n && i < 64; i++) bits[i] = 0x3f800000U + seed * 0x10000U + (uint32_t)i * 0x100U; + return mk_bits(rank, shape, bits); +} + +/* Loads h and compares with expect (value equality and exact bytes). */ +static bool got_equals(OmegaTensorStore *st, OmegaStorageHandle h, OmegaTensor expect) { + OmegaTensor t; + if (omega_tensor_store_get(st, h, g, &t) != OMEGA_TENSOR_OK) return false; + bool eq = false; + int rc = omega_tensor_value_equal(g, t, expect, &eq); + omega_tensor_release(g, t); + return rc == OMEGA_TENSOR_OK && eq; +} + +static void release_t(OmegaTensor t) { omega_tensor_release(g, t); } + +/* ---- round trip -------------------------------------------------------- */ + +static void test_round_trip(void) { + char dir[512]; + new_dir(dir, sizeof dir); + OmegaTensorStore *st = NULL, *st2 = NULL; + CHECK(omega_tensor_store_open(NULL, 4, &st) == OMEGA_TENSOR_ERR_BAD_ARGS, "open NULL dir refused"); + CHECK(omega_tensor_store_open(dir, 0, &st) == OMEGA_TENSOR_ERR_BAD_ARGS, "open capacity 0 refused"); + CHECK(omega_tensor_store_open(dir, 8, &st) == OMEGA_TENSOR_OK, "open fresh store"); + if (!st) return; + CHECK(omega_tensor_store_open(dir, 8, &st2) == OMEGA_TSTORE_ERR_BUSY && !st2, "second opener refused (busy)"); + + uint64_t s23[2] = {2, 3}, s5[1] = {5}; + uint32_t abits[6] = {0x3f800000U, 0x80000000U, 0x7fa00001U, 0xff800000U, 0x00000001U, 0x40490fdbU}; + OmegaTensor a = mk_bits(2, s23, abits); + uint16_t hbits[5] = {0x3c00U, 0x8000U, 0x7d01U, 0xfc00U, 0x0001U}; + OmegaTensor b; + CHECK(omega_tensor_from_data(g, OMEGA_DT_F16, 1, s5, hbits, &b) == OMEGA_TENSOR_OK, "F16 tensor"); + uint32_t cbits[1] = {0xc0000000U}; + OmegaTensor c = mk_bits(0, NULL, cbits); + OmegaTensor at; + CHECK(omega_tensor_transpose(g, a, &at) == OMEGA_TENSOR_OK, "transpose view"); + + OmegaStorageHandle ha, hb, hc, hat; + CHECK(omega_tensor_store_put(st, g, a, &ha) == OMEGA_TENSOR_OK, "put F32 [2,3]"); + CHECK(omega_tensor_store_put(st, g, b, &hb) == OMEGA_TENSOR_OK, "put F16 [5]"); + CHECK(omega_tensor_store_put(st, g, c, &hc) == OMEGA_TENSOR_OK, "put rank 0"); + CHECK(omega_tensor_store_put(st, g, at, &hat) == OMEGA_TENSOR_OK, "put transposed view"); + CHECK(ha.slot == 0 && ha.generation == 1 && hat.slot == 3 && hat.generation == 1, + "first handles are slot 0..3 at generation 1"); + CHECK(got_equals(st, ha, a) && got_equals(st, hb, b) && got_equals(st, hc, c) && got_equals(st, hat, at), + "every stored value reads back equal"); + + /* NaN payload is not semantic: stored as the canonical quiet NaN. */ + OmegaTensor ga; + float out[6]; + if (omega_tensor_store_get(st, ha, g, &ga) == OMEGA_TENSOR_OK) { + uint32_t ob[6]; + omega_tensor_read_f32(g, ga, out, 6); + memcpy(ob, out, sizeof ob); + CHECK(ob[2] == 0x7fc00000U && ob[1] == 0x80000000U && ob[4] == 0x00000001U, + "NaN canonical, -0 and subnormal kept (got %08x %08x %08x)", ob[2], ob[1], ob[4]); + release_t(ga); + } else CHECK(0, "get a"); + uint8_t vid[32], svid[32]; + omega_tensor_value_id(g, a, vid); + CHECK(omega_tensor_store_value_id(st, ha, svid) == OMEGA_TENSOR_OK && !memcmp(vid, svid, 32), + "store value id equals the tensor value id"); + char pname[69]; + payload_name(vid, pname); + CHECK(exists(dir, pname), "payload file is named by the value id"); + + omega_tensor_store_close(st); + st = NULL; + CHECK(omega_tensor_store_open(dir, 9, &st) == OMEGA_TENSOR_ERR_BAD_ARGS && !st, "reopen with other capacity refused"); + CHECK(omega_tensor_store_open(dir, 8, &st) == OMEGA_TENSOR_OK, "reopen"); + if (!st) return; + CHECK(omega_tensor_store_live_count(st) == 4, "4 live after reopen"); + CHECK(got_equals(st, ha, a) && got_equals(st, hb, b) && got_equals(st, hc, c) && got_equals(st, hat, at), + "every value reads back equal after reopen"); + + /* release: stale now and after recovery; generation never returns */ + CHECK(omega_tensor_store_release(st, ha) == OMEGA_TENSOR_OK, "release a"); + OmegaTensor tmp; + CHECK(omega_tensor_store_get(st, ha, g, &tmp) == OMEGA_TENSOR_ERR_STALE, "get after release: stale"); + CHECK(omega_tensor_store_release(st, ha) == OMEGA_TENSOR_ERR_STALE, "double release: stale"); + CHECK(!omega_tensor_store_valid(st, ha), "released handle invalid"); + CHECK(!exists(dir, pname), "unshared payload removed on release"); + OmegaStorageHandle wrong = hb; + wrong.generation++; + CHECK(omega_tensor_store_get(st, wrong, g, &tmp) == OMEGA_TENSOR_ERR_STALE, "wrong generation: stale"); + omega_tensor_store_close(st); + st = NULL; + CHECK(omega_tensor_store_open(dir, 8, &st) == OMEGA_TENSOR_OK, "reopen after release"); + if (!st) return; + CHECK(omega_tensor_store_get(st, ha, g, &tmp) == OMEGA_TENSOR_ERR_STALE, "released handle stale after recovery"); + OmegaTensor d = mk_vals(1, s5, 7); + OmegaStorageHandle hd; + CHECK(omega_tensor_store_put(st, g, d, &hd) == OMEGA_TENSOR_OK, "put d"); + CHECK(hd.slot == ha.slot && hd.generation == ha.generation + 1, + "slot reuse gets the next generation (slot %u gen %llu)", hd.slot, (unsigned long long)hd.generation); + CHECK(omega_tensor_store_get(st, ha, g, &tmp) == OMEGA_TENSOR_ERR_STALE, "old handle stale after slot reuse"); + CHECK(got_equals(st, hd, d), "d reads back"); + + /* dedup: two slots, one payload; releasing one keeps the other */ + OmegaStorageHandle hd2; + CHECK(omega_tensor_store_put(st, g, d, &hd2) == OMEGA_TENSOR_OK && hd2.slot != hd.slot, "put d twice"); + CHECK(omega_tensor_store_release(st, hd) == OMEGA_TENSOR_OK, "release first copy"); + CHECK(got_equals(st, hd2, d), "shared payload kept for the other copy"); + + /* capacity */ + OmegaStorageHandle hx; + int n = 0; + while (omega_tensor_store_put(st, g, d, &hx) == OMEGA_TENSOR_OK && n < 20) n++; + CHECK(n > 0 && omega_tensor_store_live_count(st) == 8, + "store fills to capacity then refuses"); + CHECK(omega_tensor_store_put(st, g, d, &hx) == OMEGA_TENSOR_ERR_CAPACITY, "full store: capacity"); + omega_tensor_store_close(st); + st = NULL; + + /* orphan sweep and leftover temp files */ + char orphan[69]; + uint8_t zid[32]; + memset(zid, 0xab, 32); + payload_name(zid, orphan); + char p[1024]; + snprintf(p, sizeof p, "%s/%s", dir, orphan); + write_file(p, (const uint8_t *)"x", 1); + snprintf(p, sizeof p, "%s/payload.tmp", dir); + write_file(p, (const uint8_t *)"junk", 4); + snprintf(p, sizeof p, "%s/journal.tmp", dir); + write_file(p, (const uint8_t *)"junk", 4); + CHECK(omega_tensor_store_open(dir, 8, &st) == OMEGA_TENSOR_OK, "open with leftovers"); + CHECK(!exists(dir, orphan) && !exists(dir, "payload.tmp") && !exists(dir, "journal.tmp"), + "orphan payload and temp files removed"); + CHECK(got_equals(st, hd2, d) && got_equals(st, hb, b), "values intact after sweep"); + omega_tensor_store_close(st); + st = NULL; + + /* lost journal: refused, never a silent fresh store */ + char jp[1024], jp2[1024]; + snprintf(jp, sizeof jp, "%s/journal", dir); + snprintf(jp2, sizeof jp2, "%s.moved", dir); + CHECK(rename(jp, jp2) == 0, "move journal away"); + CHECK(omega_tensor_store_open(dir, 8, &st) == OMEGA_TSTORE_ERR_TORN && !st, "missing journal with payloads refused"); + CHECK(rename(jp2, jp) == 0, "restore journal"); + CHECK(omega_tensor_store_open(dir, 8, &st) == OMEGA_TENSOR_OK, "open after restore"); + CHECK(omega_tensor_store_get(st, ha, g, &tmp) == OMEGA_TENSOR_ERR_STALE && got_equals(st, hd2, d), + "state intact after restore"); + omega_tensor_store_close(st); + release_t(at); + release_t(a); + release_t(b); + release_t(c); + release_t(d); + rm_dir(dir); +} + +/* ---- crash at every phase ---------------------------------------------- */ + +static int run_child_crash(const char *dir, int step, int release, OmegaStorageHandle h, OmegaTensor v) { + fflush(stdout); + pid_t pid = fork(); + if (pid < 0) return -1; + if (pid == 0) { + OmegaTensorStore *st = NULL; + if (omega_tensor_store_open(dir, 8, &st) != OMEGA_TENSOR_OK) _exit(3); + if (omega_tensor_store_test_set_crash_step(st, step) != OMEGA_TENSOR_OK) _exit(4); + OmegaStorageHandle out; + int rc = release ? omega_tensor_store_release(st, h) : omega_tensor_store_put(st, g, v, &out); + _exit(rc == OMEGA_TENSOR_OK ? 0 : 5); + } + int status = 0; + if (waitpid(pid, &status, 0) != pid) return -1; + return WIFEXITED(status) ? WEXITSTATUS(status) : -1; +} + +/* variant 0: put a new value; 1: put a value equal to a live one (shared + * payload); 2: release. */ +static void crash_case(int variant, int step) { + char dir[512]; + new_dir(dir, sizeof dir); + uint64_t s3[1] = {3}; + OmegaTensor a = mk_vals(1, s3, 1), b = mk_vals(1, s3, 2), c = mk_vals(1, s3, 3); + OmegaStorageHandle ha, hb; + OmegaTensorStore *st = NULL; + if (omega_tensor_store_open(dir, 8, &st) != OMEGA_TENSOR_OK) { CHECK(0, "crash setup open"); return; } + omega_tensor_store_put(st, g, a, &ha); + omega_tensor_store_put(st, g, b, &hb); + if (variant != 2) omega_tensor_store_release(st, ha); /* slot 0 free at generation 2 */ + omega_tensor_store_close(st); + st = NULL; + + OmegaTensor v = variant == 1 ? b : c; + int ex = run_child_crash(dir, step, variant == 2, ha, v); + CHECK(ex == 86, "variant %d step %d: child crashed at the hook (exit %d)", variant, step, ex); + int rc = omega_tensor_store_open(dir, 8, &st); + CHECK(rc == OMEGA_TENSOR_OK, "variant %d step %d: recovery opens (rc %d)", variant, step, rc); + if (!st) { release_t(a); release_t(b); release_t(c); rm_dir(dir); return; } + bool committed = step >= OMEGA_TSTORE_CRASH_JOURNAL_RENAMED; + CHECK(got_equals(st, hb, b), "variant %d step %d: untouched value intact", variant, step); + CHECK(!exists(dir, "payload.tmp") && !exists(dir, "journal.tmp"), "variant %d step %d: temp files swept", + variant, step); + OmegaTensor tmp; + if (variant == 2) { + if (committed) { + CHECK(omega_tensor_store_get(st, ha, g, &tmp) == OMEGA_TENSOR_ERR_STALE && + omega_tensor_store_live_count(st) == 1, "release step %d: committed, handle stale", step); + } else { + CHECK(got_equals(st, ha, a) && omega_tensor_store_live_count(st) == 2, + "release step %d: not committed, value intact", step); + } + } else { + OmegaStorageHandle hv = {0, 2}; + CHECK(omega_tensor_store_get(st, ha, g, &tmp) == OMEGA_TENSOR_ERR_STALE, "put step %d: released a stays stale", step); + if (committed) { + CHECK(got_equals(st, hv, v) && omega_tensor_store_live_count(st) == 2, + "put v%d step %d: committed, new value at slot 0 gen 2", variant, step); + } else { + CHECK(!omega_tensor_store_valid(st, hv) && omega_tensor_store_live_count(st) == 1, + "put v%d step %d: not committed, nothing new", variant, step); + } + } + /* the recovered store keeps working, and its next handle never reuses a + * released generation */ + OmegaStorageHandle hn; + CHECK(omega_tensor_store_put(st, g, c, &hn) == OMEGA_TENSOR_OK && got_equals(st, hn, c), + "variant %d step %d: put after recovery", variant, step); + CHECK(!(hn.slot == ha.slot && hn.generation <= ha.generation), "variant %d step %d: no generation reuse", + variant, step); + omega_tensor_store_close(st); + st = NULL; + CHECK(omega_tensor_store_open(dir, 8, &st) == OMEGA_TENSOR_OK && got_equals(st, hn, c) && got_equals(st, hb, b), + "variant %d step %d: second recovery stable", variant, step); + omega_tensor_store_close(st); + release_t(a); + release_t(b); + release_t(c); + rm_dir(dir); +} + +static void test_crash(void) { + for (int step = OMEGA_TSTORE_CRASH_PAYLOAD_PARTIAL; step < OMEGA_TSTORE_CRASH_COUNT; step++) { + crash_case(0, step); + crash_case(1, step); + } + for (int step = OMEGA_TSTORE_CRASH_JOURNAL_PARTIAL; step < OMEGA_TSTORE_CRASH_COUNT; step++) + crash_case(2, step); +} + +/* ---- torn writes ------------------------------------------------------- */ + +/* Store with history: put a, put b, release a. Returns the handles. */ +static void torn_setup(const char *dir, OmegaTensor a, OmegaTensor b, OmegaStorageHandle *ha, + OmegaStorageHandle *hb) { + OmegaTensorStore *st = NULL; + if (omega_tensor_store_open(dir, 8, &st) != OMEGA_TENSOR_OK) { CHECK(0, "torn setup"); return; } + omega_tensor_store_put(st, g, a, ha); + omega_tensor_store_put(st, g, b, hb); + omega_tensor_store_release(st, *ha); + omega_tensor_store_close(st); +} + +static void test_torn(void) { + char dir[512], jp[1024], pp[1024]; + new_dir(dir, sizeof dir); + uint64_t s3[1] = {3}; + OmegaTensor a = mk_vals(1, s3, 4), b = mk_vals(1, s3, 5); + OmegaStorageHandle ha = {0, 0}, hb = {0, 0}; + torn_setup(dir, a, b, &ha, &hb); + snprintf(jp, sizeof jp, "%s/journal", dir); + uint8_t vid[32]; + char pname[69]; + omega_tensor_value_id(g, b, vid); + payload_name(vid, pname); + snprintf(pp, sizeof pp, "%s/%s", dir, pname); + uint8_t *jr = NULL, *pr = NULL; + size_t jn = 0, pn = 0; + CHECK(read_file(jp, &jr, &jn) == 0 && jn == 56 + 3 * 200, "journal is header + 3 records (%zu bytes)", jn); + CHECK(read_file(pp, &pr, &pn) == 0 && pn == 12, "payload is 12 bytes (%zu)", pn); + if (!jr || !pr || jn != 656 || pn != 12) { free(jr); free(pr); return; } + OmegaTensorStore *st = NULL; + uint32_t lt0, ls0, lt1, ls1; + omega_tensor_live_counts(g, <0, &ls0); + + /* journal truncated at every byte boundary: refuse */ + int bad = 0; + for (size_t L = 0; L < jn; L++) { + write_file(jp, jr, L); + int rc = omega_tensor_store_open(dir, 8, &st); + if (rc != OMEGA_TSTORE_ERR_TORN || st) { + if (bad++ < 3) printf(" journal cut at %zu: rc %d\n", L, rc); + omega_tensor_store_close(st); + st = NULL; + } + } + CHECK(bad == 0, "journal truncated at all %zu lengths: all refused TORN (%d not)", jn, bad); + /* journal extended by one byte and by one full zero record: refuse */ + uint8_t *big = calloc(1, jn + 200); + memcpy(big, jr, jn); + write_file(jp, big, jn + 1); + CHECK(omega_tensor_store_open(dir, 8, &st) == OMEGA_TSTORE_ERR_TORN && !st, "journal + 1 byte refused"); + write_file(jp, big, jn + 200); + CHECK(omega_tensor_store_open(dir, 8, &st) == OMEGA_TSTORE_ERR_TORN && !st, "journal + zero record refused"); + free(big); + + /* every byte of the journal flipped: refuse */ + bad = 0; + for (size_t i = 0; i < jn; i++) { + jr[i] ^= (uint8_t)(1u << (i % 8)); + write_file(jp, jr, jn); + jr[i] ^= (uint8_t)(1u << (i % 8)); + int rc = omega_tensor_store_open(dir, 8, &st); + if ((rc != OMEGA_TSTORE_ERR_TORN && rc != OMEGA_TSTORE_ERR_CORRUPT) || st) { + if (bad++ < 3) printf(" journal byte %zu flipped: rc %d\n", i, rc); + omega_tensor_store_close(st); + st = NULL; + } + } + CHECK(bad == 0, "journal bit flip at each of %zu bytes: all refused (%d not)", jn, bad); + write_file(jp, jr, jn); + + /* payload truncated at every byte, extended, flipped: refuse */ + bad = 0; + for (size_t L = 0; L < pn; L++) { + write_file(pp, pr, L); + int rc = omega_tensor_store_open(dir, 8, &st); + if (rc != OMEGA_TSTORE_ERR_CORRUPT || st) { + if (bad++ < 3) printf(" payload cut at %zu: rc %d\n", L, rc); + omega_tensor_store_close(st); + st = NULL; + } + } + CHECK(bad == 0, "payload truncated at all %zu lengths: all refused CORRUPT (%d not)", pn, bad); + uint8_t ext[13]; + memcpy(ext, pr, 12); + ext[12] = 0; + write_file(pp, ext, 13); + CHECK(omega_tensor_store_open(dir, 8, &st) == OMEGA_TSTORE_ERR_CORRUPT && !st, "payload + 1 byte refused"); + bad = 0; + for (size_t i = 0; i < pn * 8; i++) { + pr[i / 8] ^= (uint8_t)(1u << (i % 8)); + write_file(pp, pr, pn); + pr[i / 8] ^= (uint8_t)(1u << (i % 8)); + int rc = omega_tensor_store_open(dir, 8, &st); + if (rc != OMEGA_TSTORE_ERR_CORRUPT || st) { + if (bad++ < 3) printf(" payload bit %zu flipped: rc %d\n", i, rc); + omega_tensor_store_close(st); + st = NULL; + } + } + CHECK(bad == 0, "payload: each of %zu bits flipped refused (%d not)", pn * 8, bad); + unlink(pp); + CHECK(omega_tensor_store_open(dir, 8, &st) == OMEGA_TSTORE_ERR_CORRUPT && !st, "missing payload refused"); + write_file(pp, pr, pn); + + /* restored files: the committed state comes back exactly */ + CHECK(omega_tensor_store_open(dir, 8, &st) == OMEGA_TENSOR_OK, "restored store opens"); + if (st) { + OmegaTensor tmp; + CHECK(omega_tensor_store_get(st, ha, g, &tmp) == OMEGA_TENSOR_ERR_STALE && got_equals(st, hb, b), + "restored: released stays stale, live value intact"); + /* corruption after open: get re-verifies and returns nothing */ + pr[5] ^= 0x10; + write_file(pp, pr, pn); + pr[5] ^= 0x10; + omega_tensor_live_counts(g, <1, &ls1); + tmp.slot = 0xffffffffU; + CHECK(omega_tensor_store_get(st, hb, g, &tmp) == OMEGA_TSTORE_ERR_CORRUPT, "payload corrupted after open: get refuses"); + uint32_t lt2, ls2; + omega_tensor_live_counts(g, <2, &ls2); + CHECK(lt2 == lt1 && ls2 == ls1 && tmp.slot == 0xffffffffU, "refused get created no tensor"); + omega_tensor_store_close(st); + } + omega_tensor_live_counts(g, <1, &ls1); + CHECK(lt1 == lt0 && ls1 == ls0, "torn checks leaked no tensors"); + free(jr); + free(pr); + release_t(a); + release_t(b); + rm_dir(dir); +} + +/* ---- crafted journals (independent encoder of the documented format) ---- */ + +static void le32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); } +static void le64(uint8_t *p, uint64_t v) { for (int i = 0; i < 8; i++) p[i] = (uint8_t)(v >> (8 * i)); } + +static void craft_header(uint8_t *h, uint32_t cap, uint64_t count) { + memset(h, 0, 56); + memcpy(h, "OTSJRN1", 8); + le32(h + 8, 1); + le32(h + 12, cap); + le64(h + 16, count); + sha256_hash(h, 24, h + 24); +} + +static void craft_record(uint8_t *r, uint32_t kind, uint32_t slot, uint64_t gen, uint64_t seq, + uint32_t dtype, uint32_t rank, const uint64_t *shape, const uint8_t *vid, + const uint8_t *psha) { + memset(r, 0, 200); + memcpy(r, "OTSREC1", 8); + le32(r + 8, kind); + le32(r + 12, slot); + le64(r + 16, gen); + le64(r + 24, seq); + le32(r + 32, dtype); + le32(r + 36, rank); + for (uint32_t d = 0; d < rank; d++) le64(r + 40 + 8 * d, shape[d]); + if (vid) memcpy(r + 104, vid, 32); + if (psha) memcpy(r + 136, psha, 32); + sha256_hash(r, 168, r + 168); +} + +static void test_crafted(void) { + char dir[512], jp[1024]; + new_dir(dir, sizeof dir); + snprintf(jp, sizeof jp, "%s/journal", dir); + uint64_t s3[1] = {3}; + uint32_t bits[3] = {0x3f800000U, 0x7fa00001U, 0x80000000U}; + OmegaTensor a = mk_bits(1, s3, bits); + OmegaStorageHandle ha; + OmegaTensorStore *st = NULL; + if (omega_tensor_store_open(dir, 4, &st) != OMEGA_TENSOR_OK) { CHECK(0, "crafted open"); return; } + CHECK(omega_tensor_store_put(st, g, a, &ha) == OMEGA_TENSOR_OK, "crafted put"); + omega_tensor_store_close(st); + st = NULL; + + /* expected bytes from the test's own encoder */ + uint8_t vid[32], psha[32], canon[12]; + omega_tensor_value_id(g, a, vid); + uint32_t cb[3] = {0x3f800000U, 0x7fc00000U, 0x80000000U}; + for (int i = 0; i < 3; i++) le32(canon + 4 * i, cb[i]); + sha256_hash(canon, 12, psha); + uint8_t want[56 + 200 * 2]; + craft_header(want, 4, 1); + craft_record(want + 56, 1, 0, 1, 0, OMEGA_DT_F32, 1, s3, vid, psha); + uint8_t *jr = NULL; + size_t jn = 0; + CHECK(read_file(jp, &jr, &jn) == 0 && jn == 256 && !memcmp(jr, want, 256), + "journal bytes match the documented format exactly"); + free(jr); + + struct { const char *what; uint32_t kind, slot; uint64_t gen, seq; int expect; } cases[] = { + {"release of a free slot", 2, 1, 1, 1, OMEGA_TSTORE_ERR_TORN}, + {"release with wrong generation", 2, 0, 2, 1, OMEGA_TSTORE_ERR_TORN}, + {"record out of sequence", 2, 0, 1, 5, OMEGA_TSTORE_ERR_TORN}, + {"put on a live slot", 1, 0, 1, 1, OMEGA_TSTORE_ERR_TORN}, + {"slot beyond capacity", 2, 4, 1, 1, OMEGA_TSTORE_ERR_TORN}, + {"unknown record kind", 3, 0, 1, 1, OMEGA_TSTORE_ERR_TORN}, + {"valid release (control)", 2, 0, 1, 1, OMEGA_TENSOR_OK}, + }; + for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) { + craft_header(want, 4, 2); + craft_record(want + 256, cases[i].kind, cases[i].slot, cases[i].gen, cases[i].seq, + OMEGA_DT_F32, 1, s3, vid, psha); + write_file(jp, want, sizeof want); + int rc = omega_tensor_store_open(dir, 4, &st); + CHECK(rc == cases[i].expect, "crafted %s: rc %d, want %d", cases[i].what, rc, cases[i].expect); + if (st) { + OmegaTensor tmp; + CHECK(omega_tensor_store_get(st, ha, g, &tmp) == OMEGA_TENSOR_ERR_STALE, "crafted release took effect"); + omega_tensor_store_close(st); + st = NULL; + } + } + /* a bad shape inside a correctly checksummed put record */ + uint64_t bad_shape[1] = {0}; + craft_header(want, 4, 1); + craft_record(want + 56, 1, 0, 1, 0, OMEGA_DT_F32, 1, bad_shape, vid, psha); + write_file(jp, want, 256); + CHECK(omega_tensor_store_open(dir, 4, &st) == OMEGA_TSTORE_ERR_TORN && !st, "crafted zero dimension refused"); + craft_record(want + 56, 1, 0, 1, 0, 9, 1, s3, vid, psha); + write_file(jp, want, 256); + CHECK(omega_tensor_store_open(dir, 4, &st) == OMEGA_TSTORE_ERR_TORN && !st, "crafted unknown dtype refused"); + release_t(a); + rm_dir(dir); +} + +int main(void) { + if (!omega_numeric_fpenv_ok()) { printf("FPCR not RNE/no-FTZ: refusing to run\n"); return 2; } + if (omega_tensor_ctx_create(256, omega_tensor_cpu_realization(), &g)) { printf("ctx\n"); return 2; } + snprintf(g_root, sizeof g_root, "%s/tensor-store.XXXXXX", getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp"); + if (!mkdtemp(g_root)) { printf("mkdtemp failed\n"); return 2; } + test_round_trip(); + test_crash(); + test_torn(); + test_crafted(); + uint32_t lt, ls; + omega_tensor_live_counts(g, <, &ls); + CHECK(lt == 0 && ls == 0, "no leaked tensors (%u) or storage (%u)", lt, ls); + omega_tensor_ctx_destroy(g); + rmdir(g_root); + printf("M20 OMEGA_TENSOR store tests: %d pass, %d fail\n", g_pass, g_fail); + printf("M20 verdict: NOT QUALIFIED (crash-safe storage lifetime host tier only)\n"); + return g_fail ? 1 : 0; +} diff --git a/tools/tensor_mutations.sh b/tools/tensor_mutations.sh index dbd85a573..180037a07 100755 --- a/tools/tensor_mutations.sh +++ b/tools/tensor_mutations.sh @@ -62,5 +62,49 @@ done IFS=$old_ifs # M20 receipt writer mutants (MUT: markers in tools/m20_receipt.sh), own sweep. tools/m20_receipt_mutations.sh || fail=1 + +# Crash-safe storage lifetime (omega_tensor_store.c): each mutant rebuilds +# tests/test_omega_tensor_store.c against the mutated copy and must FAIL it. +# (Skipping the fsync before rename is not observable without power loss, so +# it is not a mutant here.) +STORE_MUTATIONS='TSTORE_HASH_VERIFY|s/memcmp(dig, sl->payload_sha, 32) != 0 || memcmp(vid, sl->value_id, 32) != 0/0/ +TSTORE_SHORT_RECORD|s/len != HDR_BYTES + count \* REC_BYTES/0/ +TSTORE_GEN_RESET|s/sl->gen = r->gen + 1;/sl->gen = 1;/ +TSTORE_RENAME_BEFORE_WRITE|s/const char \*wpath = tmp;/const char *wpath = final;/ +TSTORE_RECORD_SUM|s/memcmp(sum, in + REC_SUM, 32) != 0/0/ +TSTORE_HEADER_SUM|s/memcmp(sum, st->jbuf + HDR_SUM, 32) != 0/0/' +STORE_SRCS="src/tensor/omega_tensor.c src/tensor/omega_tensor_cpu.c src/tensor/omega_tensor_reduce_seam.c" +if ! gcc $FLAGS -Isrc -Isrc/tensor -o "$SCRATCH/sbase" tests/test_omega_tensor_store.c \ + src/tensor/omega_tensor_store.c $STORE_SRCS $DEPS > "$SCRATCH/sbase.log" 2>&1 \ + || ! "$SCRATCH/sbase" > "$SCRATCH/sbase.run" 2>&1; then + head -5 "$SCRATCH/sbase.log" "$SCRATCH/sbase.run" 2>/dev/null + echo "MUTATION store baseline: unmutated store test does not pass"; fail=1 +else + IFS=' +' + for m in $STORE_MUTATIONS; do + IFS=$old_ifs + name=${m%%|*} + expr=${m#*|} + total=$((total + 1)) + cp src/tensor/omega_tensor_store.c "$SCRATCH/store.c" + sed -i "/MUT:$name/ $expr" "$SCRATCH/store.c" + if cmp -s src/tensor/omega_tensor_store.c "$SCRATCH/store.c"; then + echo "MUTATION $name: NOT APPLIED (marker or pattern missing)"; fail=1; continue + fi + if ! gcc $FLAGS -Isrc -Isrc/tensor -o "$SCRATCH/st" tests/test_omega_tensor_store.c \ + "$SCRATCH/store.c" $STORE_SRCS $DEPS > "$SCRATCH/sbuild.log" 2>&1; then + head -5 "$SCRATCH/sbuild.log" + echo "MUTATION $name: does not build (fix the sed expression)"; fail=1; continue + fi + if "$SCRATCH/st" > "$SCRATCH/srun.log" 2>&1; then + echo "MUTATION $name: NOT CAUGHT (tests still pass)"; fail=1 + else + echo "MUTATION $name: caught ($(grep -c '^FAIL' "$SCRATCH/srun.log") failing checks)" + fi + done + IFS=$old_ifs +fi + if [ "$fail" -ne 0 ]; then echo "tensor mutation sweep: FAIL"; exit 1; fi echo "tensor mutation sweep: PASS ($total of $total mutations caught)"