A 2.78-trillion-parameter Kimi K3 running inference on a single CPU in 8.24 GB of RAM. Portable C99: no BLAS, no framework, no GPU.
C avx2c99cpu-inferencedeep-learningfrom-scratchinference-enginekimi-k3linear-attentionllmllm-inferencemachine-learningmemory-efficientmixture-of-expertsmoemxfp4quantizationsimdsystems-programmingtransformerzero-dependencies
fix(security): harden safetensors, trunk, and JSON parsing against hostile input
Fareed Khan31444e618bc7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 709c7b3..6c9ca78 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -168,7 +168,7 @@ jobs:run: |make CC=clang CFLAGS="-O1 -g -std=gnu99 -Wall -Wextra -fsanitize=address,undefined -fno-omit-frame-pointer" \LDFLAGS="-lm -fsanitize=address,undefined -lpsapi -lwinpthread" ARCH= \- bin/test_ops bin/test_cfg bin/test_cache bin/test_st bin/k3_model+ bin/test_ops bin/test_cfg bin/test_cache bin/test_st bin/test_st_faults bin/k3_modelcp /clang64/bin/libclang_rt.asan_dynamic-x86_64.dll /clang64/bin/libwinpthread-1.dll /clang64/bin/libc++.dll bin/- name: Run under sanitizersenv:@@ -183,6 +183,7 @@ jobs:./bin/test_cache.exe tests/fixtures/cache./bin/test_st.exe tests/fixtures/st /tmp/idx.json \plain.f32.2d plain.bf16.1d tricky.f16.1d packed.u8.2d scalar.f32 second.shard.f32+ ./bin/test_st_faults.exe tests/fixtures/st /tmp/stfault./bin/k3_model.exe tests/fixtures# CMakeLists.txt documents itself as staying interchangeable with the Make build, but@@ -238,7 +239,7 @@ jobs:run: |make CFLAGS="-O1 -g -std=gnu99 -Wall -Wextra -fsanitize=address,undefined -fno-omit-frame-pointer" \LDFLAGS="-lm -fsanitize=address,undefined" ARCH= \- bin/test_ops bin/test_cfg bin/test_cache bin/test_st \+ bin/test_ops bin/test_cfg bin/test_cache bin/test_st bin/test_st_faults \bin/test_model_stream bin/k3_model \bin/bench_kernels \-j"$(nproc)"@@ -255,6 +256,7 @@ jobs:./bin/test_cache tests/fixtures/cache./bin/test_st tests/fixtures/st "$RUNNER_TEMP/idx.json" \plain.f32.2d plain.bf16.1d tricky.f16.1d packed.u8.2d scalar.f32 second.shard.f32+ ./bin/test_st_faults tests/fixtures/st "$RUNNER_TEMP/stfault"./bin/test_model_stream tests/fixtures/st./bin/k3_model tests/fixtures# The ms and GFLOP/s it prints are meaningless under -O1 with ASan interceptorsdiff --git a/.gitignore b/.gitignoreindex 2a1cc72..5c19cfa 100644--- a/.gitignore+++ b/.gitignore@@ -29,6 +29,7 @@ k3trunk/# credentialshf_token*+token.env*.pem*_key*_key.pubdiff --git a/CMakeLists.txt b/CMakeLists.txtindex 6768a1c..3a63e69 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -150,6 +150,7 @@ k3_add_test(test_model_stream tests/unit/test_model_stream.c)k3_add_test(test_cfg tests/unit/test_cfg.c)k3_add_test(test_tok tests/unit/test_tok.c)k3_add_test(test_chat tests/unit/test_chat.c)+k3_add_test(test_st_faults tests/unit/test_st_faults.c)target_link_libraries(test_chat PRIVATE k3_chat)k3_add_test(scale_test tests/unit/scale_test.c)k3_add_test(test_trunk tests/unit/test_trunk.c)@@ -186,6 +187,7 @@ add_test(NAME config_reject_bad_topkCOMMAND test_cfg reject ${FIX}/cfg/bad_topk.json)add_test(NAME safetensors COMMAND test_st ${FIX}/st ${CMAKE_CURRENT_BINARY_DIR}/idx.jsonplain.f32.2d plain.bf16.1d tricky.f16.1d packed.u8.2d scalar.f32 second.shard.f32)+add_test(NAME shard_faults COMMAND test_st_faults ${FIX}/st ${CMAKE_CURRENT_BINARY_DIR}/stfault)add_test(NAME model_stream COMMAND test_model_stream ${FIX}/st)add_test(NAME ultra_cli_contractCOMMAND ${CMAKE_COMMAND} -DCLI=$<TARGET_FILE:k3_cli>diff --git a/Makefile b/Makefileindex f602dff..ac0dc33 100644--- a/Makefile+++ b/Makefile@@ -156,7 +156,7 @@ CHAT_SRC := src/chat/k3_chat.c src/chat/k3_sampler.cCLI_BIN := $(BIN)/k3# Tests that need no checkpoint. These run in CI on every push.-UNIT_TESTS := test_ops test_cache test_st test_model_stream test_cfg test_tok test_chat scale_test k3_model test_trunk+UNIT_TESTS := test_ops test_cache test_st test_model_stream test_cfg test_tok test_chat scale_test k3_model test_trunk test_st_faults# Tests that need real shards. Built and run by `make test-all` with SHARD_DIR set;# see the weights-test target below.WEIGHT_TESTS := test_expert test_real_layer@@ -202,6 +202,9 @@ $(BIN)/test_model_stream: tests/unit/test_model_stream.c $(BUILD)/src/model/k3_b$(BUILD)/src/io/k3_st.o $(BUILD)/src/core/k3_ops.o | $(BIN)$(CC) $(CFLAGS) $(INCLUDES) $^ -o $@ $(LDFLAGS)+$(BIN)/test_st_faults: tests/unit/test_st_faults.c $(BUILD)/src/io/k3_st.o | $(BIN)+ $(CC) $(CFLAGS) $(INCLUDES) $^ -o $@ $(LDFLAGS)+# The tokenizer and config reader are portable C99 with no OpenMP and no platform calls,# so they build and are verifiable on any machine, including one with no checkpoint.$(BIN)/test_tok: tests/unit/test_tok.c | $(BIN)@@ -255,6 +258,7 @@ test: $(CLI_BIN) $(TEST_BINS)@echo "== safetensors =="; ./$(BIN)/test_st $(FIXTURES)/st $(BUILD)/st_index.json \plain.f32.2d plain.bf16.1d tricky.f16.1d packed.u8.2d scalar.f32 second.shard.f32@echo "== model streaming =="; ./$(BIN)/test_model_stream $(FIXTURES)/st+ @echo "== shard faults =="; ./$(BIN)/test_st_faults $(FIXTURES)/st $(BUILD)/stfault@echo "== config reader =="; ./$(BIN)/test_cfg fixture $(FIXTURES)/ref_k3.json@echo "== config refusals =="; \for f in no_layermap bad_layer_index bad_topk; do \diff --git a/include/k3/k3_cfg.h b/include/k3/k3_cfg.hindex 48e4cad..6410783 100644--- a/include/k3/k3_cfg.h+++ b/include/k3/k3_cfg.h@@ -247,9 +247,11 @@ static inline int k3_cfg_load(K3Cfg *c, int *fa, int fa_max, jval *root, const creturn 1;}-/* Convenience: read and parse a config file, then load it. The returned arena is left- * allocated because K3Cfg does not copy the strings it does not own; callers keep it- * for the process lifetime, which every caller here does. */+/* Convenience: read and parse a config file, then load it. k3_cfg_load copies+ * every value it keeps (numbers into K3Cfg, layer indices into fa), so the+ * parse tree is dead on return and freed here on ALL paths, success or+ * refusal. (Older revisions leaked the tree and called it process-lifetime;+ * a config parse is kilobytes, and leaks are how 700 KB disappear.) */static inline int k3_cfg_load_file(K3Cfg *c, int *fa, int fa_max, const char *path){FILE *f = fopen(path, "rb");@@ -270,7 +272,10 @@ static inline int k3_cfg_load_file(K3Cfg *c, int *fa, int fa_max, const char *pachar *arena = NULL;jval *root = json_parse(txt, &arena);if (!root) { fprintf(stderr, "%s: not valid JSON\n", path); free(txt); return 0; }- return k3_cfg_load(c, fa, fa_max, root, path);+ const int rc = k3_cfg_load(c, fa, fa_max, root, path);+ json_free_tree(root);+ free(txt);+ return rc;}#endif /* K3_CFG_H */diff --git a/src/io/k3_portable_io.h b/src/io/k3_portable_io.hindex 80159f8..1f3b0b4 100644--- a/src/io/k3_portable_io.h+++ b/src/io/k3_portable_io.h@@ -45,6 +45,10 @@* first failed on Windows. Windows gets MoveFileEx with* MOVEFILE_REPLACE_EXISTING, which has the POSIX semantics.*+ * mkdir POSIX takes a path and a permission mode; the CRT's _mkdir takes+ * only the path. Windows gets a wrapper that accepts and ignores the+ * mode, used by test fixtures that build a scratch directory tree.+ ** All four call sites fall back to buffered reads (or, for pread/posix_memalign, have* no fallback because the shim IS the implementation) when the direct path is* unavailable, so none of this changes what the engine computes, only how fast it@@ -263,6 +267,20 @@ static inline int k3_win_rename(const char *from, const char *to)}#define rename(from, to) k3_win_rename((from), (to))+/* mkdir(2) for MinGW. POSIX mkdir takes a path and a permission mode; the CRT's+ * _mkdir (declared in direct.h, not the fcntl.h/io.h this file already pulls in)+ * takes only the path, since Windows has no equivalent of the POSIX mode bits at+ * create time. The mode argument is accepted and ignored rather than dropped at+ * every call site, so test code written against the POSIX signature needs no+ * platform branch of its own. */+#include <direct.h>+static inline int k3_win_mkdir(const char *path, int mode)+{+ (void)mode;+ return _mkdir(path);+}+#define mkdir(path, mode) k3_win_mkdir((path), (mode))+/* madvise(MADV_HUGEPAGE) is a Linux transparent-hugepage hint; every caller already* treats it as advisory ("failure is not an error" -- k3_trunk.c), so a no-op is the* correct port here, not a functional gap. The alternative, VirtualAlloc withdiff --git a/src/io/k3_st.c b/src/io/k3_st.cindex 018f5a3..acbb562 100644--- a/src/io/k3_st.c+++ b/src/io/k3_st.c@@ -21,6 +21,7 @@#include <dirent.h>#include <fcntl.h>+#include <limits.h>#include <stdio.h>#include <stdlib.h>#include <string.h>@@ -43,8 +44,16 @@ int k3_st_elemsize(K3Dtype d)int64_t k3_st_numel(const K3Tensor *t){+ /* Saturate instead of wrap: a hostile shape near INT64_MAX used to wrap+ * n (signed overflow) and defeat the span check below with a small+ * matching `want`. Saturation keeps every downstream comparison honest;+ * no real tensor has 2^62 elements. */int64_t n = 1;- for (int i = 0; i < t->ndim; i++) n *= t->shape[i];+ for (int i = 0; i < t->ndim; i++) {+ if (t->shape[i] < 0) return (int64_t)INT64_MAX;+ if (n > (int64_t)INT64_MAX / (t->shape[i] > 0 ? t->shape[i] : 1)) return (int64_t)INT64_MAX;+ n *= t->shape[i];+ }return t->ndim ? n : 1;}@@ -124,8 +133,16 @@ static int i64_(Scan *s, int64_t *v)int neg = 0;if (s->p < s->end && (*s->p == '-' || *s->p == '+')) neg = (*s->p++ == '-');if (s->p >= s->end || *s->p < '0' || *s->p > '9') return 0;+ /* Saturate on overflow: hostile data_offsets/shape near INT64_MAX used+ * to wrap `a` small (signed overflow), defeating every check below. */int64_t a = 0;- while (s->p < s->end && *s->p >= '0' && *s->p <= '9') a = a * 10 + (*s->p++ - '0');+ while (s->p < s->end && *s->p >= '0' && *s->p <= '9') {+ int d = *s->p++ - '0';+ if (a > (INT64_MAX - d) / 10) { a = INT64_MAX; }+ else { a = a * 10 + d; }+ /* keep consuming digits so the scanner stays aligned */+ }+ if (neg && a == INT64_MAX) { *v = INT64_MIN; return 1; }*v = neg ? -a : a;return 1;}@@ -208,7 +225,12 @@ static int scan_shard(K3St *s, Build *b, int shard, const char *path)for (int i = 7; i >= 0; i--) hlen = (hlen << 8) | lenbuf[i]; /* little endian */off_t fsize = lseek(fd, 0, SEEK_END);- if (hlen == 0 || (uint64_t)fsize < 8 + hlen) {+ /* Subtraction, not addition: 8 + hlen wraps to small when hlen is near+ * 2^64 (a corrupt or hostile first 8 bytes), passing the check with a+ * malloc(0) followed by a giant pread -- a heap overflow that _FORTIFY_+ * turns into an abort. fsize >= 8 holds here (8 bytes were just read), so+ * fsize - 8 cannot underflow. Found by tests/unit/test_st_faults.c. */+ if (hlen == 0 || (uint64_t)(fsize - 8) < hlen) {fprintf(stderr, "k3_st: %s header length %llu is impossible (file %lld bytes)\n",path, (unsigned long long)hlen, (long long)fsize);close(fd); return -1;@@ -316,18 +338,32 @@ static int scan_shard(K3St *s, Build *b, int shard, const char *path)/* Consistency: the byte span must equal elements times element size. A mismatch* means the shape and the data disagree, and every later read of this tensor* would be silently misaligned. Refuse rather than load it. */+ /* Negative offsets used to pass through (only presence was+ * checked), and `base + o0` / `base + o1` could wrap int64, so a+ * hostile data_offsets pair defeated both the span check and the+ * EOF check. Order matters: bound o0/o1 BEFORE adding base.+ * (fsize - base cannot underflow: base <= fsize was verified at+ * the header check above.) */+ if (o0 < 0 || o1 < o0 || o1 > fsize - base) {+ fprintf(stderr, "k3_st: %s: %s has impossible data_offsets\n", path, name);+ goto bad;+ }t.off = base + o0;t.nbytes = o1 - o0;- const int64_t want = k3_st_numel(&t) * k3_st_elemsize(t.dtype);+ /* numel * esz can still wrap even with saturating numel (a hostile+ * shape times 4 bytes). Check before multiplying. */+ const int64_t numel = k3_st_numel(&t);+ const int64_t esz = k3_st_elemsize(t.dtype);+ if (esz <= 0 || numel > INT64_MAX / esz) {+ fprintf(stderr, "k3_st: %s: %s shape is impossibly large\n", path, name);+ goto bad;+ }+ const int64_t want = numel * esz;if (t.nbytes != want) {fprintf(stderr, "k3_st: %s: %s spans %lld bytes but shape implies %lld\n",path, name, (long long)t.nbytes, (long long)want);goto bad;}- if (base + o1 > fsize) {- fprintf(stderr, "k3_st: %s: %s ends past EOF\n", path, name);- goto bad;- }if (o1 > maxend) maxend = o1;if (push(b, s, name, nlen, &t) != 0) { fprintf(stderr, "k3_st: out of memory\n"); goto bad; }@@ -373,9 +409,25 @@ int k3_st_open(K3St *s, const char *dir)while ((e = readdir(d))) {size_t n = strlen(e->d_name);if (n < 12 || strcmp(e->d_name + n - 12, ".safetensors")) continue;- if (nf == cf) { cf = cf ? cf * 2 : 32; files = (char **)realloc(files, cf * sizeof *files); }+ if (nf == cf) {+ cf = cf ? cf * 2 : 32;+ char **nfiles = (char **)realloc(files, (size_t)cf * sizeof *files);+ if (!nfiles) {+ fprintf(stderr, "k3_st: OOM listing %s\n", dir);+ for (int k = 0; k < nf; k++) free(files[k]);+ free(files); closedir(d);+ return -1;+ }+ files = nfiles;+ }size_t len = strlen(dir) + 1 + n + 1;files[nf] = (char *)malloc(len);+ if (!files[nf]) {+ fprintf(stderr, "k3_st: OOM listing %s\n", dir);+ for (int k = 0; k < nf; k++) free(files[k]);+ free(files); closedir(d);+ return -1;+ }snprintf(files[nf], len, "%s/%s", dir, e->d_name);nf++;}diff --git a/src/io/k3_trunk.c b/src/io/k3_trunk.cindex d99df76..8af2a51 100644--- a/src/io/k3_trunk.c+++ b/src/io/k3_trunk.c@@ -151,6 +151,9 @@ int k3_trunk_open(K3Trunk *tr, const char *dir, const K3Cfg *c, int64_t budget_bjval *jl = json_get(root, "layers");if (!jl || jl->t != J_ARR) { fprintf(stderr, "k3_trunk: no layers array\n"); goto bad; }tr->n_layers = jl->len;+ /* An empty layers array used to reach the ring sizing below, which reads+ * lay[n_layers - 1] = lay[-1]. A trunk with no layers is not a trunk. */+ if (tr->n_layers <= 0) { fprintf(stderr, "k3_trunk: no layers\n"); goto bad; }tr->lay = (K3TrunkLayer *)calloc((size_t)tr->n_layers, sizeof(K3TrunkLayer));if (!tr->lay) goto bad;@@ -160,6 +163,13 @@ int k3_trunk_open(K3Trunk *tr, const char *dir, const K3Cfg *c, int64_t budget_bK3TrunkLayer *L = &tr->lay[i];if ((v = json_get(e, "file_off")) && v->t == J_NUM) L->file_off = (int64_t)v->num;if ((v = json_get(e, "nbytes")) && v->t == J_NUM) L->nbytes = (int64_t)v->num;+ /* A hostile trunk.json can carry negative geometry. Negative file_off+ * turns the pread offset backwards; negative nbytes skips the load+ * loop entirely and hands uninitialized heap to the kernels. */+ if (L->file_off < 0 || L->nbytes < 0) {+ fprintf(stderr, "k3_trunk: layer %d has negative geometry\n", i);+ goto bad;+ }jval *ts = json_get(e, "tensors");if (!ts || ts->t != J_OBJ) { fprintf(stderr, "k3_trunk: layer %d has no tensors\n", i); goto bad; }L->nt = ts->len;@@ -167,15 +177,31 @@ int k3_trunk_open(K3Trunk *tr, const char *dir, const K3Cfg *c, int64_t budget_bif (!L->t) goto bad;for (int k = 0; k < ts->len; k++) {K3TrunkTensor *t = &L->t[k];- /* keys live in the parser arena, which is kept for the process lifetime */- t->name = ts->keys[k];+ /* Names are strdup'd: the parse tree is freed below, and every+ * parser string is individually heap-owned (see json_free_tree),+ * so aliasing a tree string would dangle at the first verify. */+ t->name = ts->keys[k] ? strdup(ts->keys[k]) : NULL;+ if (ts->keys[k] && !t->name) goto bad;jval *o = ts->kids[k];if ((v = json_get(o, "off")) && v->t == J_NUM) t->off = (int64_t)v->num;if ((v = json_get(o, "nbytes")) && v->t == J_NUM) t->nbytes = (int64_t)v->num;if ((v = json_get(o, "dtype")) && v->t == J_STR) t->dtype = dt_of(v->str);+ /* The binder trusts these offsets into the layer run. A hostile+ * manifest can point a tensor at bytes outside the run (or wrap+ * off+nbytes around int64), handing kernels an arbitrary+ * heap-adjacent read. Refuse at parse time, overflow-safe. */+ if (t->off < 0 || t->nbytes < 0 || t->off > L->nbytes ||+ t->nbytes > L->nbytes - t->off) {+ fprintf(stderr, "k3_trunk: layer %d tensor '%s' escapes its run\n",+ i, t->name ? t->name : "?");+ goto bad;+ }}}- free(txt); /* arena holds the strings; txt itself is done */+ /* The trunk.json tree stays alive through the align lookup below; it is+ * freed right after. Offsets/counts are already copied out and every+ * tensor name was strdup'd above, so nothing retained dangles. */+ free(txt);snprintf(p, sizeof p, "%s/trunk.bin", dir);/* O_DIRECT, because the trunk is the one thing the page cache CANNOT help with.@@ -195,7 +221,11 @@ int k3_trunk_open(K3Trunk *tr, const char *dir, const K3Cfg *c, int64_t budget_btr->direct = 0;tr->fd = open(p, O_RDONLY);}- if (tr->fd < 0) { fprintf(stderr, "k3_trunk: cannot open %s\n", p); return -1; }+ if (tr->fd < 0) {+ fprintf(stderr, "k3_trunk: cannot open %s\n", p);+ json_free_tree(root);+ return -1;+ }{jval *a = json_get(root, "align");const int64_t want = (a && a->t == J_NUM) ? (int64_t)a->num : 0;@@ -208,9 +238,11 @@ int k3_trunk_open(K3Trunk *tr, const char *dir, const K3Cfg *c, int64_t budget_bclose(tr->fd);tr->direct = 0;tr->fd = open(p, O_RDONLY);- if (tr->fd < 0) return -1;+ if (tr->fd < 0) { json_free_tree(root); return -1; }}}+ /* Last use of the trunk.json tree was the align lookup above. */+ json_free_tree(root);const size_t widen = k3_bind_widen_bytes(c);int64_t total = 0;@@ -449,7 +481,23 @@ int k3_trunk_open(K3Trunk *tr, const char *dir, const K3Cfg *c, int64_t budget_b"a pinned SET is used instead)\n", 100.0 * npin / tr->n_layers);return 0;bad:+ /* Every open failure must leave nothing behind: partial layer tables and+ * their strdup'd names are freed here, so a corrupt trunk.json fails the+ * run without also failing a sanitizer. All pointers are NULL until+ * assigned (memset at open), so freeing unconditionally is safe. */free(txt);+ if (tr->lay) {+ for (int i = 0; i < tr->n_layers; i++) {+ for (int k = 0; k < tr->lay[i].nt; k++) free(tr->lay[i].t[k].name);+ free(tr->lay[i].t);+ }+ free(tr->lay);+ tr->lay = NULL;+ }+ free(tr->json_arena);+ tr->json_arena = NULL;+ memset(tr, 0, sizeof *tr);+ tr->fd = -1;return -1;}@@ -473,8 +521,14 @@ void k3_trunk_close(K3Trunk *tr)if (tr->pin) { for (int i = 0; i < tr->npin; i++) k3_aligned_free(tr->pin[i]); free(tr->pin); }k3_aligned_free(tr->arena); free(tr->layer_of); free(tr->slot_of); free(tr->pin_of);free(tr->reads_of);- if (tr->lay) { for (int i = 0; i < tr->n_layers; i++) free(tr->lay[i].t); free(tr->lay); }- free(tr->json_arena); /* every K3TrunkTensor.name points into this */+ if (tr->lay) {+ for (int i = 0; i < tr->n_layers; i++) {+ for (int k = 0; k < tr->lay[i].nt; k++) free(tr->lay[i].t[k].name);+ free(tr->lay[i].t);+ }+ free(tr->lay);+ }+ free(tr->json_arena); /* always NULL; the names above are owned individually */memset(tr, 0, sizeof *tr);tr->fd = -1; /* see k3_trunk_open: 0 is stdin, not "closed" */}@@ -523,7 +577,9 @@ static int k3_alloc_direct(void **out, size_t bytes)** Timing and byte counts come back through out-parameters rather than being added to* the K3Trunk here: two threads call this concurrently now, and += on a shared double is- * a data race whose symptom is a plausible-looking throughput figure. */+ * a data race whose symptom is a plausible-looking throughput figure. The reader thread+ * and the main thread both reach this function, so the fold-in has to happen under the+ * io mutex, not here; see the "Fold one completed read" step below. */static int load_run_to(K3Trunk *tr, int L, unsigned char *dst,double *secs, int64_t *bytes){diff --git a/src/tokenizer/k3_tok.h b/src/tokenizer/k3_tok.hindex ad4ad5f..f4a219d 100644--- a/src/tokenizer/k3_tok.h+++ b/src/tokenizer/k3_tok.h@@ -197,6 +197,13 @@ static inline void k3_tok_load(Tok *T, const char *files_dir)fprintf(stderr, "k3_tok: tokenizer_config.json has no added_tokens_decoder\n");exit(1);}+ /* json_get only guarantees non-NULL, not the type. An array here leaves+ * adt->keys NULL (arrays never set keys) and atoi(NULL) crashes two+ * lines below; a scalar silently yields zero specials. */+ if (adt->t != J_OBJ) {+ fprintf(stderr, "k3_tok: added_tokens_decoder is not an object\n");+ exit(1);+ }T->nsp = adt->len;T->sp = (Special *)calloc((size_t)(T->nsp ? T->nsp : 1), sizeof(Special));diff --git a/tests/unit/test_st_faults.c b/tests/unit/test_st_faults.cnew file mode 100644index 0000000..25167b7--- /dev/null+++ b/tests/unit/test_st_faults.c@@ -0,0 +1,256 @@+/* test_st_faults.c - partial and corrupt shards must fail loudly.+ *+ * WHY THIS FILE EXISTS+ * The download script warns that a partial checkpoint "does not fail loudly,+ * it produces wrong tokens". The reader is the last line of defense, and the+ * happy-path test (test_st.c) never feeds it a broken file. Each case below+ * builds a mutant of the real fixture shards and asserts the failure is+ * LOUD: open refuses, or a read comes back short. What is NOT asserted is+ * content corruption with intact structure, flipped data bytes, or lying+ * but in-range offsets: those read back full and silent, so this test+ * documents the boundary of what the reader itself can catch rather than+ * claiming to catch everything.+ *+ * usage: test_st_faults <fixture_st_dir> <work_dir>+ */+#define _POSIX_C_SOURCE 200809L++#include "k3_portable_io.h" /* mkdir() shim for MinGW; see the header for why */++#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include <dirent.h>++#include "k3_st.h"++static int g_fail = 0;++static void ck(int ok, const char *what, const char *detail)+{+ printf(" %s %-34s %s\n", ok ? "PASS" : "FAIL", what, detail ? detail : "");+ if (!ok) g_fail++;+}++static int endswith(const char *s, const char *suf)+{+ size_t a = strlen(s), b = strlen(suf);+ return a >= b && strcmp(s + a - b, suf) == 0;+}++static unsigned char *slurp(const char *path, size_t *n)+{+ FILE *f = fopen(path, "rb");+ if (!f) return NULL;+ fseek(f, 0, SEEK_END);+ long sz = ftell(f);+ fseek(f, 0, SEEK_SET);+ if (sz < 0) { fclose(f); return NULL; }+ unsigned char *b = (unsigned char *)malloc((size_t)sz ? (size_t)sz : 1);+ if (!b) { fclose(f); return NULL; }+ if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) {+ free(b); fclose(f); return NULL;+ }+ fclose(f);+ *n = (size_t)sz;+ return b;+}++static int writeall(const char *path, const unsigned char *b, size_t n)+{+ FILE *f = fopen(path, "wb");+ if (!f) return -1;+ const int ok = n == 0 || fwrite(b, 1, n, f) == n;+ fclose(f);+ return ok ? 0 : -1;+}++/* Copy every .safetensors from src to dst, then mutate file `which` with fn.+ * Mutations are small on purpose: each must break exactly one contract. */+static int make_case(const char *src, const char *dst, const char *mutname,+ size_t keep)+{+ /* mkdir, not system(): the path is ours and the shell adds nothing. */+ mkdir(dst, 0755);+ DIR *d = opendir(src);+ if (!d) return -1;+ struct dirent *e;+ int found = 0;+ while ((e = readdir(d)) != NULL) {+ if (!endswith(e->d_name, ".safetensors")) continue;+ char sp[1024], dp[1024];+ /* Checked, not just silenced: GCC cannot bound dst/src at compile time and+ * warns on that alone, but a genuinely truncated path here would make+ * writeall() below write the mutated shard under the wrong name, which+ * this file exists to catch elsewhere, not commit itself. */+ if (snprintf(sp, sizeof sp, "%s/%s", src, e->d_name) >= (int)sizeof sp ||+ snprintf(dp, sizeof dp, "%s/%s", dst, e->d_name) >= (int)sizeof dp) {+ closedir(d); return -1;+ }+ size_t n = 0;+ unsigned char *b = slurp(sp, &n);+ if (!b) { closedir(d); return -1; }+ if (mutname && strcmp(e->d_name, mutname) == 0) {+ if (keep < n) {+ unsigned char *t = (unsigned char *)malloc(keep ? keep : 1);+ if (!t) { free(b); closedir(d); return -1; }+ memcpy(t, b, keep);+ free(b);+ b = t;+ n = keep;+ }+ found = 1;+ }+ const int rc = writeall(dp, b, n);+ free(b);+ if (rc != 0) { closedir(d); return -1; }+ }+ closedir(d);+ return found || !mutname ? 0 : -1;+}++static uint64_t rdle64(const unsigned char *b)+{+ uint64_t v = 0;+ for (int i = 7; i >= 0; i--) v = (v << 8) | b[i];+ return v;+}++int main(int argc, char **argv)+{+ if (argc < 3) {+ fprintf(stderr, "usage: test_st_faults <fixture_st_dir> <work_dir>\n");+ return 2;+ }+ const char *fix = argv[1];+ const char *work = argv[2];+ mkdir(work, 0755); /* case dirs nest one level below; make_case makes those */++ char first[1024] = "";+ {+ /* First shard name, for targeted single-file mutations. */+ DIR *d = opendir(fix);+ if (!d) { fprintf(stderr, "cannot open %s\n", fix); return 2; }+ struct dirent *e;+ while ((e = readdir(d)) != NULL)+ if (endswith(e->d_name, ".safetensors")) {+ snprintf(first, sizeof first, "%s", e->d_name);+ break;+ }+ closedir(d);+ if (!first[0]) { fprintf(stderr, "no shards in %s\n", fix); return 2; }+ }++ /* Control: an unmutated copy opens. Without this, every refusal below+ * could be the harness failing instead of the reader refusing. */+ {+ char d[1024];+ snprintf(d, sizeof d, "%s/ctl", work);+ K3St s;+ int ok = make_case(fix, d, NULL, 0) == 0 && k3_st_open(&s, d) == 0 && s.nt > 0;+ ck(ok, "control unmutated copy opens", ok ? "" : "harness or reader broken");+ if (ok) k3_st_close(&s);+ }++ /* T1: file cut to 4 bytes (shorter than the 8-byte header length). */+ {+ char d[1024];+ snprintf(d, sizeof d, "%s/t1", work);+ K3St s;+ memset(&s, 0, sizeof s);+ const int built = make_case(fix, d, first, 4) == 0;+ const int rc = built ? k3_st_open(&s, d) : 0;+ ck(built && rc != 0, "4-byte file refused at open", "");+ if (rc == 0) k3_st_close(&s);+ }++ /* T2: header length overwritten with all-ones (impossible size). */+ {+ char d[1024], p[2048];+ snprintf(d, sizeof d, "%s/t2", work);+ K3St s;+ memset(&s, 0, sizeof s);+ int ok = make_case(fix, d, NULL, 0) == 0;+ snprintf(p, sizeof p, "%s/%s", d, first);+ FILE *f = ok ? fopen(p, "r+b") : NULL;+ if (f) {+ static const unsigned char ff[8] = {255, 255, 255, 255, 255, 255, 255, 255};+ ok = fwrite(ff, 1, 8, f) == 8;+ fclose(f);+ } else {+ ok = 0;+ }+ const int rc = ok ? k3_st_open(&s, d) : 0;+ ck(ok && rc != 0, "impossible header length refused", "");+ if (rc == 0 && ok) k3_st_close(&s);+ }++ /* T3: structural JSON byte flipped ('{' at offset 8 -> '['). */+ {+ char d[1024], p[2048];+ snprintf(d, sizeof d, "%s/t3", work);+ K3St s;+ memset(&s, 0, sizeof s);+ int ok = make_case(fix, d, NULL, 0) == 0;+ snprintf(p, sizeof p, "%s/%s", d, first);+ FILE *f = ok ? fopen(p, "r+b") : NULL;+ if (f) {+ fseek(f, 8, SEEK_SET);+ ok = fputc('[', f) == '[';+ fclose(f);+ } else {+ ok = 0;+ }+ const int rc = ok ? k3_st_open(&s, d) : 0;+ ck(ok && rc != 0, "corrupt header JSON refused", "");+ if (rc == 0 && ok) k3_st_close(&s);+ }++ /* T4: valid header, zero data bytes. Open may succeed (lazy index), but a+ * read must come back SHORT -- never full counts over missing bytes. */+ {+ char d[1024], p[2048];+ snprintf(d, sizeof d, "%s/t4", work);+ K3St s;+ memset(&s, 0, sizeof s);+ int ok = make_case(fix, d, NULL, 0) == 0;+ snprintf(p, sizeof p, "%s/%s", d, first);+ size_t n = 0;+ unsigned char *b = ok ? slurp(p, &n) : NULL;+ if (b && n >= 8) {+ const uint64_t hlen = rdle64(b);+ if (8 + hlen <= n && hlen > 0 && hlen < (1u << 20)) {+ ok = writeall(p, b, (size_t)(8 + hlen)) == 0;+ } else {+ ok = 0;+ }+ } else {+ ok = 0;+ }+ free(b);+ const int rc = ok ? k3_st_open(&s, d) : -99;+ int shortread = 0;+ if (ok && rc == 0 && s.nt > 0) {+ /* First tensor of the truncated shard: find any tensor whose+ * advertised extent is non-empty and read it. */+ for (int i = 0; i < s.nt; i++) {+ if (s.t[i].nbytes <= 0) continue;+ unsigned char *buf = (unsigned char *)malloc((size_t)s.t[i].nbytes);+ if (!buf) break;+ const int64_t got = k3_st_read(&s, &s.t[i], buf);+ free(buf);+ if (got != s.t[i].nbytes) shortread = 1;+ break;+ }+ k3_st_close(&s);+ }+ /* Either refusal at open or a short read: both are loud. Full counts+ * over a truncated file would be silent corruption. */+ ck(ok && (rc != 0 || shortread), "tail-truncated data surfaces loudly", "");+ }++ printf("\n%s\n", g_fail ? "ST-FAULT TESTS FAILED" : "ST-FAULT TESTS PASSED");+ return g_fail ? 1 : 0;+}diff --git a/third_party/json.h b/third_party/json.hindex 8b82894..b19dbfd 100644--- a/third_party/json.h+++ b/third_party/json.h@@ -36,6 +36,9 @@ typedef struct {int depth; /* current nesting depth: the bound that stops a hostile* JSON like [[[[...]]]] from overflowing this recursive-descent* parser's stack */+ int oom; /* latched on any allocation failure: parsing unwinds+ * and json_parse returns NULL instead of crashing+ * through a NULL pointer a few frames later */} jparser;/* Nesting ceiling. Safetensors headers and config files are shallow (depth ~3), so@@ -47,16 +50,17 @@ typedef struct {static char *j_dup(jparser *p, const char *b, int n) {/* Every string gets its own allocation. An arena that reallocs would move the* buffer and invalidate every pointer already handed out (use-after-free). */- (void)p;- char *d = (char *)malloc(n + 1);+ char *d = (char *)malloc((size_t)n + 1);+ if (!d) { p->oom = 1; return NULL; }memcpy(d, b, n); d[n] = 0;return d;}static void j_ws(jparser *p) { while (*p->s && isspace((unsigned char)*p->s)) p->s++; }-static jval *j_new(jtype t) {+static jval *j_new(jparser *p, jtype t) {jval *v = (jval *)calloc(1, sizeof(jval));+ if (!v) { p->oom = 1; return NULL; }v->t = t; return v;}@@ -70,9 +74,11 @@ static char *j_parse_str_raw(jparser *p) {* files, which corrupts values instead of reporting an error, and costs 64 KB of* stack on every call. */size_t cap = 64, n = 0; char *tmp = (char *)malloc(cap);- if (!tmp) { fprintf(stderr, "OOM parsing JSON string\n"); exit(1); }- #define J_PUT(ch) do{ if (n + 1 >= cap) { cap *= 2; tmp = (char *)realloc(tmp, cap); \- if (!tmp) { fprintf(stderr, "OOM parsing JSON string\n"); exit(1); } } tmp[n++] = (char)(ch); }while(0)+ if (!tmp) { p->oom = 1; return NULL; }+ /* A library must not exit(1) on OOM: the CLI distinguishes misuse (2)+ * from failure, and every json_parse caller already handles NULL. */+ #define J_PUT(ch) do{ if (n + 1 >= cap) { cap *= 2; char *nt = (char *)realloc(tmp, cap); \+ if (!nt) { free(tmp); p->oom = 1; return NULL; } tmp = nt; } tmp[n++] = (char)(ch); }while(0)while (*p->s && *p->s != '"') {char c = *p->s++;if (c == '\\' && *p->s) {@@ -105,63 +111,134 @@ static char *j_parse_str_raw(jparser *p) {#undef J_PUTif (*p->s == '"') p->s++;char *out = j_dup(p, tmp, (int)n); free(tmp);- return out;+ return out; /* NULL with oom latched on failure */}-static jval *j_parse_val(jparser *p) {+/* Grow helpers: realloc-or-latch, never assigning NULL over the live+ * pointer (the old code wrote realloc's result straight back, so one OOM+ * wrote through NULL two lines later). Objects grow keys[] and kids[] under+ * ONE cap update: doubling per array (8->16->32) while growing each once+ * overruns the first array past its allocation. */+static int j_grow(jparser *p, void **pp, int *cap, size_t elem) {+ int ncap = (*cap) * 2;+ void *np = realloc(*pp, (size_t)ncap * elem);+ if (!np) { p->oom = 1; return 0; }+ *pp = np; *cap = ncap;+ return 1;+}++static int j_grow2(jparser *p, void **a, size_t ae, void **b, size_t be,+ int *cap) {+ int ncap = (*cap) * 2;+ void *na = realloc(*a, (size_t)ncap * ae);+ if (!na) { p->oom = 1; return 0; }+ *a = na;+ void *nb = realloc(*b, (size_t)ncap * be);+ if (!nb) { p->oom = 1; return 0; } /* *a already grown; unwind frees it */+ *b = nb;+ *cap = ncap;+ return 1;+}++static jval *j_parse_val(jparser *p);+static void json_free_tree(jval *v);++static jval *j_parse_obj(jparser *p) {+ if (++p->depth > J_MAX_DEPTH) { p->depth--; return j_new(p, J_NULL); }+ p->s++; jval *v = j_new(p, J_OBJ);+ if (!v) { p->depth--; return NULL; }+ int cap = 8;+ v->keys = malloc((size_t)cap * sizeof(char*));+ v->kids = malloc((size_t)cap * sizeof(jval*));+ if (!v->keys || !v->kids) {+ free(v->keys); free(v->kids); free(v); p->oom = 1; p->depth--;+ return NULL;+ }j_ws(p);- char c = *p->s;- if (c == '"') { jval *v = j_new(J_STR); v->str = j_parse_str_raw(p); return v; }- if (c == '{') {- if (++p->depth > J_MAX_DEPTH) { p->depth--; return j_new(J_NULL); }- p->s++; jval *v = j_new(J_OBJ);- int cap = 8; v->keys = malloc(cap * sizeof(char*)); v->kids = malloc(cap * sizeof(jval*));+ if (*p->s == '}') { p->s++; p->depth--; return v; }+ for (;;) {j_ws(p);- if (*p->s == '}') { p->s++; p->depth--; return v; }- for (;;) {- j_ws(p);- char *key = j_parse_str_raw(p);- j_ws(p); if (*p->s == ':') p->s++;- jval *val = j_parse_val(p);- if (v->len == cap) { cap *= 2; v->keys = realloc(v->keys, cap*sizeof(char*)); v->kids = realloc(v->kids, cap*sizeof(jval*)); }- v->keys[v->len] = key; v->kids[v->len] = val; v->len++;- j_ws(p);- if (*p->s == ',') { p->s++; continue; }- if (*p->s == '}') { p->s++; break; }- break;+ char *key = j_parse_str_raw(p);+ j_ws(p); if (*p->s == ':') p->s++;+ jval *val = j_parse_val(p);+ /* Every allocated node is owned by exactly one frame's kids[], so+ * freeing this frame's partial v closes the whole failed subtree;+ * only the in-flight key/val need separate handling. */+ if (!key || !val || p->oom) {+ free(key); json_free_tree(val); json_free_tree(v);+ p->depth--;+ return NULL;}- p->depth--;- return v;- }- if (c == '[') {- if (++p->depth > J_MAX_DEPTH) { p->depth--; return j_new(J_NULL); }- p->s++; jval *v = j_new(J_ARR);- int cap = 8; v->kids = malloc(cap * sizeof(jval*));+ if (v->len == cap &&+ !j_grow2(p, (void **)&v->keys, sizeof(char*),+ (void **)&v->kids, sizeof(jval*), &cap)) {+ free(key); json_free_tree(val); json_free_tree(v);+ p->depth--;+ return NULL;+ }+ v->keys[v->len] = key; v->kids[v->len] = val; v->len++;j_ws(p);- if (*p->s == ']') { p->s++; p->depth--; return v; }- for (;;) {- jval *val = j_parse_val(p);- if (v->len == cap) { cap *= 2; v->kids = realloc(v->kids, cap*sizeof(jval*)); }- v->kids[v->len++] = val;- j_ws(p);- if (*p->s == ',') { p->s++; continue; }- if (*p->s == ']') { p->s++; break; }- break;+ if (*p->s == ',') { p->s++; continue; }+ if (*p->s == '}') { p->s++; break; }+ break;+ }+ p->depth--;+ return v;+}++static jval *j_parse_arr(jparser *p) {+ if (++p->depth > J_MAX_DEPTH) { p->depth--; return j_new(p, J_NULL); }+ p->s++; jval *v = j_new(p, J_ARR);+ if (!v) { p->depth--; return NULL; }+ int cap = 8;+ v->kids = malloc((size_t)cap * sizeof(jval*));+ if (!v->kids) { free(v); p->oom = 1; p->depth--; return NULL; }+ j_ws(p);+ if (*p->s == ']') { p->s++; p->depth--; return v; }+ for (;;) {+ jval *val = j_parse_val(p);+ if (!val || p->oom) { json_free_tree(val); json_free_tree(v); p->depth--; return NULL; }+ if (v->len == cap &&+ !j_grow(p, (void **)&v->kids, &cap, sizeof(jval*))) {+ json_free_tree(val); json_free_tree(v);+ p->depth--;+ return NULL;}- p->depth--;++ v->kids[v->len++] = val;+ j_ws(p);+ if (*p->s == ',') { p->s++; continue; }+ if (*p->s == ']') { p->s++; break; }+ break;+ }+ p->depth--;+ return v;+}++static jval *j_parse_val(jparser *p) {+ j_ws(p);+ char c = *p->s;+ if (c == '"') {+ jval *v = j_new(p, J_STR);+ if (!v) return NULL;+ v->str = j_parse_str_raw(p);+ if (!v->str) { free(v); return NULL; }return v;}- if (c == 't' && !strncmp(p->s, "true", 4)) { p->s += 4; jval *v = j_new(J_BOOL); v->boolean = 1; return v; }- if (c == 'f' && !strncmp(p->s, "false", 5)) { p->s += 5; jval *v = j_new(J_BOOL); v->boolean = 0; return v; }- if (c == 'n' && !strncmp(p->s, "null", 4)) { p->s += 4; return j_new(J_NULL); }+ if (c == '{') return j_parse_obj(p);+ if (c == '[') return j_parse_arr(p);+ if (c == 't' && !strncmp(p->s, "true", 4)) { p->s += 4; jval *v = j_new(p, J_BOOL); if (!v) return NULL; v->boolean = 1; return v; }+ if (c == 'f' && !strncmp(p->s, "false", 5)) { p->s += 5; jval *v = j_new(p, J_BOOL); if (!v) return NULL; v->boolean = 0; return v; }+ if (c == 'n' && !strncmp(p->s, "null", 4)) { p->s += 4; return j_new(p, J_NULL); }/* numero */- { char *end; double d = strtod(p->s, &end); p->s = end; jval *v = j_new(J_NUM); v->num = d; return v; }+ { char *end; double d = strtod(p->s, &end); p->s = end; jval *v = j_new(p, J_NUM); if (!v) return NULL; v->num = d; return v; }}/* API */static jval *json_parse(const char *text, char **arena_out) {- jparser p = { text, NULL, 0, 0, 0 };+ jparser p = { text, NULL, 0, 0, 0, 0 };jval *v = j_parse_val(&p);+ if (p.oom) { json_free_tree(v); v = NULL; }if (arena_out) *arena_out = p.arena; else free(p.arena);return v;}@@ -172,4 +249,29 @@ static jval *json_get(jval *o, const char *key) {return NULL;}+/* Free a parsed tree: nodes, key/value arrays, and every string. Every string+ * the parser hands out is individually heap-owned (see j_dup), including+ * object keys and J_STR values, so freeing after extraction leaks nothing.+ * The one exception a caller must respect: anything it ALIASED out of the+ * tree (k3_trunk.c tensor names, k3_tok.h special-token strings) must be+ * strdup'd first (trunk) or deliberately process-lifetime (tokenizer). */+static void json_free_tree(jval *v) {+ int i;+ if (!v) return;+ if (v->t == J_OBJ) {+ for (i = 0; i < v->len; i++) {+ free(v->keys[i]);+ json_free_tree(v->kids[i]);+ }+ free(v->keys);+ free(v->kids);+ } else if (v->t == J_ARR) {+ for (i = 0; i < v->len; i++) json_free_tree(v->kids[i]);+ free(v->kids);+ } else if (v->t == J_STR) {+ free(v->str);+ }+ free(v);+}+#endif