diff --git a/Makefile b/Makefile index 27bb4cd..67abd71 100644 --- a/Makefile +++ b/Makefile @@ -362,6 +362,12 @@ check: $(LIB) $(BIN) $(CLIENT) $(PLUGIN) $(TESTS) tests/test_junction check-asan: @sh tests/check_asan.sh +# The unit tests under ThreadSanitizer: the engine has a turn thread, a UI +# thread, widget threads and one thread per MCP server. Rebuilds the tree with +# -fsanitize=thread and back; run it when nothing else builds in this tree. +check-tsan: + @sh tests/check_tsan.sh + # the test binaries as a list, for check_asan.sh print-tests: @echo $(TESTS) diff --git a/README.md b/README.md index f774d16..9a22383 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,8 @@ Code: https://git.kropa.tech/hiddenbox/splinter make # libsplinter.so, the binaries, the plugins make check # the tests, no network, no model + make check-asan # the same under ASan/UBSan, leaks included + make check-tsan # the same under TSan: data races make install PREFIX=$HOME/.local # binaries, library, plugins splinter --init-config # writes ~/.splinter/splinter.conf @@ -1069,6 +1071,11 @@ ABI in `docs/PLUGINS.md`. - Plugins are not sandboxed. They run in the process with full rights; the authorization classes protect the harness from the *model*, not from code you chose to load. +- `make check` is single-threaded in what it asserts. The races that bit are + listed in `tests/check_tsan.sh`; run `make check-tsan` (a full rebuild under + ThreadSanitizer, then back) when you touched threads, a widget or a plugin's + process globals. It is not part of `make check` because a race is not + deterministic and the rebuild is slow. ## License diff --git a/plugins/foreign/foreign.c b/plugins/foreign/foreign.c index 070bc3f..c374c40 100644 --- a/plugins/foreign/foreign.c +++ b/plugins/foreign/foreign.c @@ -65,6 +65,7 @@ #include #include #include +#include #include #include #include @@ -101,6 +102,16 @@ static const char *const src_tag[] = { "fcl-", "fhm-", "foc-" }; /* ------------------------------------------------------------------ config */ +/* + * One initialisation guard for the paths below. The widget thread (foreign_tick) + * and the thread that runs a tool both call resolve_paths(); the flag used to be + * set *before* the paths it guards were filled, so the second thread returned at + * once and read empty paths - and the plain `int` read/write was a data race on + * top. The mutex serialises the init, the atomic publishes it. + */ +static pthread_mutex_t fr_init_mu = PTHREAD_MUTEX_INITIALIZER; +static int fr_ready; + static struct { struct sp_host *host; char claude[FR_PATH]; @@ -109,8 +120,7 @@ static struct { char opencode[FR_PATH]; size_t max_bytes; int limit; - int ready; -} fr = { NULL, "", { { "" } }, 0, "", FR_MAX_BYTES, 25, 0 }; +} fr = { NULL, "", { { "" } }, 0, "", FR_MAX_BYTES, 25 }; /* ~ at the front of a configured path; a trailing slash is dropped */ static int @@ -203,11 +213,31 @@ hermes_list(const char *val) free(copy); } +/* + * The host handle, read and written from the widget thread and from whichever + * thread runs a tool. Every writer passes the same handle today, so the race was + * harmless - but an unsynchronised word is still a race, and a build with two + * hosts in one process (dlopen shares this file's statics) would make it matter. + * Store release, load acquire: a thread that sees the handle sees its config. + */ +static void +set_host(struct sp_host *h) +{ + __atomic_store_n(&fr.host, h, __ATOMIC_RELEASE); +} + +static struct sp_host * +get_host(void) +{ + return __atomic_load_n(&fr.host, __ATOMIC_ACQUIRE); +} + static const char * conf(const char *key) { - return fr.host != NULL ? sp_host_plugin_config(fr.host, "foreign", key) : - NULL; + struct sp_host *h = get_host(); + + return h != NULL ? sp_host_plugin_config(h, "foreign", key) : NULL; } static void @@ -216,9 +246,13 @@ resolve_paths(void) const char *v; char home[FR_PATH]; - if (fr.ready) + if (__atomic_load_n(&fr_ready, __ATOMIC_ACQUIRE)) return; - fr.ready = 1; + pthread_mutex_lock(&fr_init_mu); + if (__atomic_load_n(&fr_ready, __ATOMIC_ACQUIRE)) { + pthread_mutex_unlock(&fr_init_mu); + return; + } snprintf(home, sizeof(home), "%s", getenv("HOME") != NULL ? getenv("HOME") : ""); @@ -283,6 +317,9 @@ resolve_paths(void) fr.limit = atoi(conf("limit")); if (fr.limit < 1 || fr.limit > 200) fr.limit = 25; + /* everything above is visible before the flag that says so */ + __atomic_store_n(&fr_ready, 1, __ATOMIC_RELEASE); + pthread_mutex_unlock(&fr_init_mu); } static enum fr_src @@ -2561,7 +2598,7 @@ import_any(struct sp_host *h, enum fr_src s, const char *foreign_id, resolve_paths(); if (!valid_id(foreign_id)) return sp_buf_puts(out, "error: 'id' is not a session id"); - fr.host = h; + set_host(h); if (load_any(s, foreign_id, &c, err, sizeof(err)) != 0) return sp_buf_printf(out, "error: %s", err); fconv_pair(&c); @@ -3122,7 +3159,7 @@ cmd_foreign(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx) int rc; (void)ctx; - fr.host = h; + set_host(h); resolve_paths(); args_split(args, sub, sizeof(sub), a1, sizeof(a1), a2, sizeof(a2)); @@ -3210,7 +3247,7 @@ foreign_tick(struct sp_host *h, const char *name, void *ctx) char text[128]; (void)ctx; - fr.host = h; + set_host(h); resolve_paths(); snprintf(text, sizeof(text), "claude %d hermes %d oc %d", count_claude(), count_hermes(), count_opencode()); @@ -3229,7 +3266,7 @@ foreign_init(struct sp_host *h) size_t i; memset(t, 0, sizeof(t)); - fr.host = h; + set_host(h); resolve_paths(); t[0].name = "foreign_list"; diff --git a/plugins/mcp/mcp.c b/plugins/mcp/mcp.c index e23003d..9dae04f 100644 --- a/plugins/mcp/mcp.c +++ b/plugins/mcp/mcp.c @@ -79,7 +79,27 @@ struct server { }; #define RETRY_S 10 -static volatile int stopping; +/* + * Written by the main thread in mcp_shutdown, read by every server thread in + * its loop. `volatile` was not enough: it stops the compiler from caching the + * value but gives no ordering, so a server thread could read 0 after the + * shutdown had already killed its child and keep using buffers that teardown + * frees. TSan reported the race as a write in mcp_shutdown against a read in + * server_thread_body; the accessors below make it visible and ordered. + */ +static int stopping; + +static int +is_stopping(void) +{ + return __atomic_load_n(&stopping, __ATOMIC_ACQUIRE); +} + +static void +set_stopping(int v) +{ + __atomic_store_n(&stopping, v, __ATOMIC_RELEASE); +} static struct server sv[MAX_SERVERS]; static size_t nsv; @@ -428,7 +448,7 @@ http_rpc(struct server *s, const char *method, const char *params, } hdrs[n] = NULL; - if (stopping) { + if (is_stopping()) { sp_buf_puts(err, "mcp: shutting down"); (void)unlink(body); (void)unlink(hdr); @@ -658,7 +678,7 @@ notify(struct server *s, const char *method) hdrs[n++] = sess; } hdrs[n] = NULL; - fd = stopping ? -1 : + fd = is_stopping() ? -1 : sp_curl_start(args, s->url, hdrs, 1, &pid, &err); if (fd >= 0) { @@ -1077,7 +1097,7 @@ nap(void) { int k; - for (k = 0; k < RETRY_S * 10 && !stopping; k++) { + for (k = 0; k < RETRY_S * 10 && !is_stopping(); k++) { struct timespec ts = { 0, 100000000L }; nanosleep(&ts, NULL); @@ -1113,7 +1133,7 @@ server_thread_body(void *arg) struct server *s = &sv[i]; int failed_said = 0, ever_up = 0; - while (!stopping) { + while (!is_stopping()) { struct sp_buf err; if (sp_buf_init(&err) != 0) @@ -1153,7 +1173,7 @@ server_thread_body(void *arg) char *r; nap(); - if (stopping) { + if (is_stopping()) { sp_buf_free(&err); break; } @@ -1198,7 +1218,7 @@ mcp_init(struct sp_host *h) host = h; nsv = 0; - stopping = 0; + set_stopping(0); conf = sp_host_config(h); if (conf != NULL) { @@ -1281,7 +1301,7 @@ mcp_shutdown(struct sp_host *h) int done; (void)h; - stopping = 1; + set_stopping(1); for (i = 0; i < nsv; i++) { /* a child is stopped without taking the lock a stuck call may hold */ if (!sv[i].http && sv[i].pid > 0) { diff --git a/src/backend/ack.c b/src/backend/ack.c index 102880f..1a2e0c6 100644 --- a/src/backend/ack.c +++ b/src/backend/ack.c @@ -37,7 +37,7 @@ #include "i18n.h" #include "ack.h" -static char ack_root[512]; +#define ACK_ROOT_MAX 512 static int ensure_dir(const char *path) @@ -65,14 +65,23 @@ sp_ack_dir(void) const char *env = getenv("SPLINTER_ACK_DIR"); const char *home = getenv("HOME"); + /* + * One buffer per thread. The path is a pure function of the environment, + * so a per-thread copy says the same thing everywhere - but a waiter in + * one thread and an answerer in another (the gateway does both) used to + * sprintf into the same static while the other read it. TSan found it; + * a garbled path here means an approval request that cannot be found. + */ + static __thread char root[ACK_ROOT_MAX]; + if (env != NULL && *env != '\0') { - snprintf(ack_root, sizeof(ack_root), "%s", env); - return ack_root; + snprintf(root, sizeof(root), "%s", env); + return root; } if (home == NULL || *home == '\0') return NULL; - snprintf(ack_root, sizeof(ack_root), "%s/.splinter/ack", home); - return ack_root; + snprintf(root, sizeof(root), "%s/.splinter/ack", home); + return root; } static int diff --git a/src/backend/agent.c b/src/backend/agent.c index 5b500b7..b2a2796 100644 --- a/src/backend/agent.c +++ b/src/backend/agent.c @@ -158,6 +158,14 @@ ack_approval(struct sp_agent *a, const struct sp_tool *t, const char *args) (void)write(stop[1], "x", 1); (void)pthread_join(th, NULL); } + /* + * pipe(2) fills both ends or neither, and nothing between here and the + * pipe() call can return, so one guard covers both. gcc's -fanalyzer + * reports stop[1] as leaked here anyway (checked 2026-11-22): the + * warning reproduces with a separate guard per fd too, so it is the + * analyzer losing track of the descriptor through the call to + * sp_ack_wait(), not a path that skips the close. + */ if (stop[0] >= 0) { close(stop[0]); close(stop[1]); diff --git a/src/backend/embed.c b/src/backend/embed.c index 0952359..aa31adb 100644 --- a/src/backend/embed.c +++ b/src/backend/embed.c @@ -309,6 +309,16 @@ struct sp_embed_ctx { char path[640]; /* the .jsonl */ char efile[700]; /* the .emb */ + /* + * Bumped by sp_embed_bind() whenever the session it points at changes. + * The index thread copies the paths and this number under the lock, works + * on its own copy, and drops the result if the number moved - otherwise a + * catch_up that started on the old session publishes the old file's byte + * offset into the new session's index, and everything up to that offset is + * never searched. + */ + unsigned long gen; + long offset; /* bytes of the session indexed */ struct erec *rec; size_t nrec; @@ -951,8 +961,10 @@ catch_up(struct sp_embed_ctx *c) double *vec[EMBED_BATCH]; FILE *f; char *line = NULL; + char path[sizeof(c->path)]; size_t linecap = 0, n, i; long pos; + unsigned long gen; int rc = 0; struct timespec t0, t1; @@ -960,11 +972,20 @@ catch_up(struct sp_embed_ctx *c) memset(vec, 0, sizeof(vec)); if (sp_buf_init(&err) != 0) return -1; - if (c->path[0] == '\0' || c->dir[0] == '\0') { + pthread_mutex_lock(&c->lock); + /* + * One snapshot of what to index. The paths are copied here so that the + * fopen() below does not read a buffer sp_embed_bind() may be rewriting, + * and the generation says whether that bind happened while this run was + * working - see the check before the offset is published. + */ + snprintf(path, sizeof(path), "%s", c->path); + gen = c->gen; + if (path[0] == '\0' || c->dir[0] == '\0') { + pthread_mutex_unlock(&c->lock); sp_buf_free(&err); return 0; } - pthread_mutex_lock(&c->lock); if (!c->loaded && load_index(c) != 0) { pthread_mutex_unlock(&c->lock); sp_buf_free(&err); @@ -973,7 +994,7 @@ catch_up(struct sp_embed_ctx *c) pos = c->offset; pthread_mutex_unlock(&c->lock); - f = fopen(c->path, "r"); + f = fopen(path, "r"); if (f == NULL) { /* nothing written yet is not a failure */ sp_buf_free(&err); @@ -1011,7 +1032,9 @@ catch_up(struct sp_embed_ctx *c) /* nothing embeddable left: the end, or one more line to skip */ if (eof) { pthread_mutex_lock(&c->lock); - c->offset = pos; + /* the session was swapped while this run read it */ + if (c->gen == gen) + c->offset = pos; pthread_mutex_unlock(&c->lock); break; } @@ -1055,6 +1078,17 @@ catch_up(struct sp_embed_ctx *c) rc = -1; break; } + /* + * Before commit, not after: commit appends to the index of the + * session bound *now*. Records read from the previous file must + * not land there - dropping the batch costs one re-index of the + * new session, which the bind already queued. + */ + if (c->gen != gen) { + pthread_mutex_unlock(&c->lock); + vecs_free(vec, n); + break; + } if (commit(c, p, vec, n) < 0) { pthread_mutex_unlock(&c->lock); vecs_free(vec, n); @@ -1230,6 +1264,14 @@ sp_embed_bind(struct sp_embed_ctx *c, const char *dir, const char *id) pthread_mutex_lock(&c->lock); changed = strcmp(c->id, id) != 0 || strcmp(c->dir, dir) != 0; if (changed) { + /* + * First, so a catch_up() that is already inside the old file + * fails its generation check instead of writing into this one. + * The bump and the reset below happen under the same lock, so a + * run that reads gen and offset together sees either both old or + * both new. + */ + c->gen++; snprintf(c->dir, sizeof(c->dir), "%s", dir); snprintf(c->id, sizeof(c->id), "%s", id); snprintf(c->path, sizeof(c->path), "%s/%s.jsonl", dir, id); @@ -1481,6 +1523,8 @@ sp_embed_search_full(struct sp_embed_ctx *c, const char *query, size_t limit, struct sp_buf err; size_t i, n = 0, shown = 0; struct stat st; + char path[sizeof(c->path)]; + long filled; int caught_up; if (c == NULL || query == NULL || out == NULL) @@ -1503,14 +1547,21 @@ sp_embed_search_full(struct sp_embed_ctx *c, const char *query, size_t limit, if (!c->loaded) (void)load_index(c); if (c->nrec == 0) { + /* + * The path and the offset go out of the lock with us: the turn + * thread may bind another session right after we unlock, and + * this answer is about the one that was bound here. + */ + snprintf(path, sizeof(path), "%s", c->path); + filled = c->offset; pthread_mutex_unlock(&c->lock); /* * Two very different situations, and the model acts on the * answer: an index that is still filling says "wait", a session * with nothing indexable says "there is nothing here". */ - if (!caught_up && c->path[0] != '\0' && - stat(c->path, &st) == 0 && (long)st.st_size > c->offset) + if (!caught_up && path[0] != '\0' && + stat(path, &st) == 0 && (long)st.st_size > filled) sp_buf_puts(out, "the index is still filling; ask " "again in a moment\n"); else diff --git a/tests/check_tsan.sh b/tests/check_tsan.sh new file mode 100755 index 0000000..0a410ea --- /dev/null +++ b/tests/check_tsan.sh @@ -0,0 +1,72 @@ +#!/bin/sh +# The unit tests under ThreadSanitizer. +# +# `make check` proves behaviour and `make check-asan` proves the memory it runs +# on; this proves the threads. Splinter has more of them than it looks: the turn +# thread, the UI thread, one widget thread per plugin that asks for one, and one +# thread per MCP server. Between them sit process globals that were written by +# whichever thread got there first. +# +# It found these real data races, all fixed: sp_ack_dir() returned one static +# buffer that a waiter and an answerer sprintf'd into each other, the MCP +# plugin's shutdown flag was a plain `volatile int` with no happens-before, the +# foreign plugin set its init flag before filling the paths it guards, and that +# plugin's host handle was written from two threads unsynchronised. The fifth +# was the expensive one: catch_up() read c->path, c->offset and c->id outside +# the lock, so a session switch mid-index published the old file's byte offset +# into the new session's index - everything below that offset was never +# searched again. A generation counter now makes that run drop its batch. +# +# A race is not deterministic, so this is not part of `make check`: it costs a +# full rebuild, and it needs a toolchain with TSan (Debian's gcc has it). Run it +# when the tree is idle - like check-asan, it rebuilds in place and back. +set -e +cd "$(dirname "$0")/.." + +TCF="-std=c99 -O1 -g -Wall -Wextra -fPIC -D_POSIX_C_SOURCE=200809L \ +-fsanitize=thread -fno-omit-frame-pointer \ +-Iinclude -Isrc/backend -Isrc/frontend -Ivendor/libmcp \ +-Ivendor/netbsd-curses/libcurses" + +TESTS=$(make -s print-tests) +[ -n "$TESTS" ] || { echo "no test binaries to run" >&2; exit 1; } + +make clean >/dev/null +if ! make -j"$(nproc)" CFLAGS="$TCF" all $TESTS > /tmp/check_tsan_build.log 2>&1; then + tail -20 /tmp/check_tsan_build.log >&2 + echo "tsan build failed" >&2 + exit 1 +fi + +failed=0 +races=0 +for t in $TESTS; do + if TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1 \ + LD_LIBRARY_PATH=. "./$t" > /tmp/check_tsan_one.log 2>&1; then + continue + fi + # A test can fail for its own reasons under TSan's slowdown; only a + # report counts here. Anything else is reported, not counted as a race. + if grep -q "WARNING: ThreadSanitizer" /tmp/check_tsan_one.log; then + echo "RACE $t" + grep -A 14 "WARNING: ThreadSanitizer" /tmp/check_tsan_one.log | + sed 's/^/ /' + races=$((races + 1)) + failed=1 + else + echo "FAIL $t (not a race report)" + tail -10 /tmp/check_tsan_one.log | sed 's/^/ /' + failed=1 + fi +done + +# leave the tree as it was found: a normal build +make clean >/dev/null +make -j"$(nproc)" >/dev/null + +if [ "$failed" -eq 0 ]; then + echo "check_tsan: all $(echo "$TESTS" | wc -w) test binaries free of data races" +else + echo "check_tsan: $races race report(s)" >&2 +fi +exit "$failed" diff --git a/tests/test_ack.c b/tests/test_ack.c index b69d27e..3fb2738 100644 --- a/tests/test_ack.c +++ b/tests/test_ack.c @@ -3,6 +3,7 @@ * may write it. Silence is not consent. */ #include +#include #include #include #include @@ -28,6 +29,29 @@ static int checks, fails; static int answer_id; static int answer_yes; +/* + * Two threads each ask sp_ack_dir() for the path and keep the pointer they got. + * A per-thread buffer gives two different addresses; one shared static gives the + * same address twice, which is the bug this guards. + */ +static struct { + const char *want; + unsigned long got; /* the address this thread was handed */ +} two_dirs[2]; + +static void * +dir_holder(void *arg) +{ + int idx = (int)(long)arg; + const char *p; + + p = sp_ack_dir(); + /* the address only: the thread's own buffer dies with the thread */ + if (p != NULL && strcmp(p, two_dirs[idx].want) == 0) + two_dirs[idx].got = (unsigned long)(uintptr_t)p; + return NULL; +} + static void * answerer(void *arg) { @@ -159,6 +183,29 @@ main(void) (void)unsetenv("SPLINTER_ACK_CHANNELS"); } + /* + * ---- the ack root is per thread ---- + * sp_ack_dir() used to return one static buffer, sprintf'd by whoever + * asked last, so a waiter in one thread and an answerer in another (the + * gateway does both) read each other's path. The contract is now one + * buffer per thread; two threads returning the same address means they + * share it again, and the value one of them reads can change under it. + */ + { + pthread_t ta, tb; + + two_dirs[0].want = dir; + two_dirs[1].want = dir; + (void)pthread_create(&ta, NULL, dir_holder, (void *)0L); + (void)pthread_create(&tb, NULL, dir_holder, (void *)1L); + (void)pthread_join(ta, NULL); + (void)pthread_join(tb, NULL); + CHECK(two_dirs[0].got != 0 && two_dirs[1].got != 0, + "both threads get an ack path"); + CHECK(two_dirs[0].got != two_dirs[1].got, + "the two threads do not share one buffer"); + } + /* ---- a directory others may write into is not trusted with a yes ---- */ CHECK(mkdtemp(open_dir) != NULL, "a directory for the permission test"); (void)chmod(open_dir, 0777); diff --git a/tests/test_embed.c b/tests/test_embed.c index 029bfe3..29b59c7 100644 --- a/tests/test_embed.c +++ b/tests/test_embed.c @@ -21,6 +21,7 @@ #include #include #include +#include #include "splinter.h" #include "config.h" @@ -515,6 +516,102 @@ start_embed_server(int *port) } } +/* + * A server that answers nothing until a file shows up. It exists for one + * reason: to hold a batch inside encode_remote() long enough for the test to + * move the context to another session underneath it. Without such a gate the + * window is microseconds wide and a test of the race proves nothing. + */ +static pid_t +start_gated_server(int *port, const char *gate_dir) +{ + struct sockaddr_in a; + socklen_t alen = sizeof(a); + int ls, one = 1; + + ls = socket(AF_INET, SOCK_STREAM, 0); + if (ls < 0) + return -1; + (void)setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); + memset(&a, 0, sizeof(a)); + a.sin_family = AF_INET; + a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + a.sin_port = 0; + if (bind(ls, (struct sockaddr *)&a, sizeof(a)) != 0 || + listen(ls, 8) != 0 || + getsockname(ls, (struct sockaddr *)&a, &alen) != 0) { + close(ls); + return -1; + } + *port = (int)ntohs(a.sin_port); + { + pid_t pid = fork(); + + if (pid == 0) { + for (;;) { + char req[8192], mark[800]; + ssize_t got; + int c = accept(ls, NULL, NULL); + int i; + + if (c < 0) + _exit(0); + got = read(c, req, sizeof(req) - 1); + req[got > 0 ? got : 0] = '\0'; + snprintf(mark, sizeof(mark), "%s/req", + gate_dir); + freopen(mark, "w", stderr); /* the flag */ + { + FILE *f = fopen(mark, "w"); + + if (f != NULL) + fclose(f); + } + snprintf(mark, sizeof(mark), "%s/go", + gate_dir); + for (i = 0; i < 2000; i++) { + if (access(mark, F_OK) == 0) + break; + { + struct timespec ts = { 0, 5000000L }; + + nanosleep(&ts, NULL); + } + } + if (i == 2000) + _exit(1); + { + char *b = strstr(req, "\r\n\r\n"); + + fake_embed_answer(c, b != NULL ? b : "", + 64); + } + close(c); + } + } + close(ls); + return pid; + } +} + +/* wait for a file to appear, up to ms */ +static int +wait_file(const char *path, long ms) +{ + long i; + + for (i = 0; i < ms / 5; i++) { + if (access(path, F_OK) == 0) + return 0; + { + struct timespec ts = { 0, 5000000L }; + + nanosleep(&ts, NULL); + } + } + return -1; +} + static void test_remote_vectors_are_the_models(void) { @@ -598,6 +695,152 @@ test_remote_vectors_are_the_models(void) (void)waitpid(srv, NULL, 0); } +/* + * Swapping the session while the indexer is between reading and publishing + * used to carry the old file's byte offset into the new session's index: a + * catch_up() that started on a long session and finished after sp_embed_bind() + * set the new offset to the old file's length, so everything in the new + * session before that many bytes was never indexed and never found. + * + * The generation counter closes it. This test asserts the outcome rather than + * the race: a short session bound after a long one is searchable from its + * first line. + */ +static void +test_bind_after_a_long_session(void) +{ + char tmpl[] = "/tmp/splinter-embg-XXXXXX"; + char *dir = mkdtemp(tmpl); + char status[512], mark[800]; + const char *longs[] = { + "{\"role\":\"user\",\"text\":\"der lange text ueber den " + "ersten dienst und seine konfiguration und den port\"}", + "{\"role\":\"assistant\",\"text\":\"die antwort dazu, mit " + "viel text, damit diese sitzung deutlich groesser wird als " + "die kurze, die danach kommt\"}" + }; + const char *shorty[] = { + "{\"role\":\"user\",\"text\":\"kurze frage zum stichwort " + "lindwurm\"}" + }; + struct sp_embed_ctx *c; + struct sp_config conf; + struct sp_buf out; + FILE *f; + pid_t srv; + int port = 0, n; + + if (dir == NULL) { + fprintf(stderr, "FAIL: no temp dir\n"); + failures++; + return; + } + srv = start_gated_server(&port, dir); + CHECK(srv > 0); + if (srv <= 0) + return; + + sp_config_init(&conf); + conf.embed = SP_EMBED_REMOTE; + snprintf(conf.embed_model, sizeof(conf.embed_model), "fake"); + snprintf(conf.embed_endpoint, sizeof(conf.embed_endpoint), + "http://127.0.0.1:%d/v1", port); + conf.embed_dims = 64; + write_session(dir, "long", longs, 2); + write_session(dir, "short", shorty, 1); + + c = sp_embed_new(&conf); + CHECK(c != NULL); + if (c == NULL) { + kill(srv, SIGKILL); + (void)waitpid(srv, NULL, 0); + return; + } + /* + * First, give "short" a real index on disk: header and one record. That + * matters - a leaked batch only stays visible if the file it lands in + * already exists. A file created by the leak itself has no header, so + * the next load_index() rebuilds it and the damage disappears. + */ + sp_embed_bind(c, dir, "short"); + snprintf(mark, sizeof(mark), "%s/req", dir); + CHECK(wait_file(mark, 15000) == 0); + snprintf(mark, sizeof(mark), "%s/go", dir); + { + FILE *go = fopen(mark, "w"); + + if (go != NULL) + fclose(go); + } + CHECK(sp_embed_flush(c, 15000) == 1); + snprintf(mark, sizeof(mark), "%s/go", dir); + (void)unlink(mark); /* re-arm the gate for the next request */ + snprintf(mark, sizeof(mark), "%s/req", dir); + (void)unlink(mark); + + /* + * Now switch to "long" and let its batch reach the encoder. The worker + * is inside encode_remote() when the session goes back to "short" - the + * records in flight belong to a session that is no longer bound, and + * committing them puts "long"'s lines into "short"'s index. + */ + sp_embed_bind(c, dir, "long"); + snprintf(mark, sizeof(mark), "%s/req", dir); + CHECK(wait_file(mark, 15000) == 0); + sp_embed_bind(c, dir, "short"); + snprintf(mark, sizeof(mark), "%s/go", dir); + { + FILE *go = fopen(mark, "w"); + + if (go != NULL) + fclose(go); + } + (void)sp_embed_flush(c, 15000); + + sp_embed_status(c, status, sizeof(status)); + fprintf(stderr, " after switch: %s\n", status); + CHECK(strstr(status, "1 messages") != NULL); + + if (sp_buf_init(&out) == 0) { + n = sp_embed_search(c, "lindwurm", 1, &out); + fprintf(stderr, " switch search: %d %s\n", n, + out.p != NULL ? out.p : ""); + CHECK(n == 1); + CHECK(out.p != NULL && strstr(out.p, "lindwurm") != NULL); + sp_buf_free(&out); + } + /* + * The index file is the truth, not the search: a batch in flight when + * the session changed must not have been written into the new session's + * index. "konfiguration" appears only in "long", so finding it in + * short.emb is the corruption. + */ + snprintf(mark, sizeof(mark), "%s/emb/short.emb", dir); + { + char line[4096]; + int leaked = 0, recs = 0; + + f = fopen(mark, "r"); + CHECK(f != NULL); + while (f != NULL && fgets(line, sizeof(line), f) != NULL) { + if (strstr(line, "\"v\":") == NULL) + continue; + recs++; + if (strstr(line, "konfiguration") != NULL) + leaked++; + } + if (f != NULL) + fclose(f); + fprintf(stderr, " short.emb: %d records, %d leaked\n", + recs, leaked); + CHECK(recs == 1); + CHECK(leaked == 0); + } + sp_embed_free(c); + kill(srv, SIGKILL); + (void)waitpid(srv, NULL, 0); +} + int main(void) { @@ -613,6 +856,8 @@ main(void) test_remote_vectors_are_the_models(); fprintf(stderr, "== compaction recall\n"); test_compaction_recall(); + fprintf(stderr, "== bind after a long session\n"); + test_bind_after_a_long_session(); if (failures != 0) { fprintf(stderr, "FAILED: %d\n", failures); return 1;