Files
lotherk 80f055711d races: five data races fixed, make check-tsan to keep them fixed
Found with ThreadSanitizer over the whole suite, not by reading:

- ack: sp_ack_dir() returned one static buffer. The waiter and the
  answerer (the gateway is both) sprintf'd into each other's path, so an
  approval request could be looked for in the wrong place. One buffer per
  thread now; test_ack asserts the two threads get different addresses.
- mcp: `stopping` was a plain volatile int with no happens-before, so a
  server thread could read 0 after shutdown killed its child and keep
  using buffers that teardown frees. Acquire/release accessors.
- foreign: fr.ready was set before the paths it guards were filled, so a
  second thread returned early and read empty paths; the flag and the host
  handle are now an atomic pair (publish) plus a mutex (the init itself).
- embed: catch_up() read c->path, c->offset and c->id outside the lock. 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 makes that run drop its batch, and the
  search path takes its snapshot under the same lock.

Proof, both directions:
- make check-tsan: 45/45 test binaries free of races (new target; the
  tree is rebuilt under TSan and back, like check-asan).
- test_embed's new gated test (a server that holds the batch until the
  session has been switched): without the generation check short.emb ends
  with 4 records, 1 of them leaked from the other session; with it, 1
  and 0. The test is deterministic, so it fails on a plain build too.
- test_ack: reverting to `static char root[]` fails
  "the two threads do not share one buffer".
- make check: all tests passed; make check-asan: 45/45 clean.
2026-11-23 08:30:29 +00:00

868 lines
23 KiB
C

/*
* splinter -- the embedding index tests.
*
* Three things have to hold for this to be worth having:
*
* 1. the local encoder puts similar text near each other and unrelated text
* far apart, without a model, a key or the network;
* 2. indexing is incremental: a second run reads only the new lines, and the
* result equals an index built in one go;
* 3. a compaction makes the messages searchable again, and the search finds
* the right one - that is the whole point of the module.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include "splinter.h"
#include "config.h"
#include "embed.h"
static int failures;
#define CHECK(cond) do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
failures++; \
} \
} while (0)
/* ------------------------------------------------------------- encoder */
static void
test_encoder(void)
{
double a[256], b[256], c[256], v[256];
int i, nz = 0;
CHECK(sp_embed_text("the compaction throws the front away and keeps the "
"tail of the conversation", 256, a) == 0);
CHECK(sp_embed_text("compaction throws the front away and keeps the tail "
"of a conversation", 256, b) == 0);
CHECK(sp_embed_text("a pool fails over to the member with room left, and "
"the turn continues there", 256, c) == 0);
/* unit length: the cosine is the dot product, nothing else */
for (i = 0; i < 256; i++) {
CHECK(a[i] >= -1.0000001 && a[i] <= 1.0000001);
if (a[i] != 0.0)
nz++;
}
CHECK(nz > 4);
/*
* A paraphrase has to score clearly above an unrelated sentence. The
* numbers are printed so a change in the weights is visible in the log.
*/
fprintf(stderr, " encoder: paraphrase %.3f, unrelated %.3f\n",
sp_embed_dot(a, b, 256), sp_embed_dot(a, c, 256));
CHECK(sp_embed_dot(a, b, 256) > 0.55);
CHECK(sp_embed_dot(a, c, 256) < sp_embed_dot(a, b, 256));
CHECK(sp_embed_dot(a, a, 256) > 0.999);
/* a word inside a longer word: the 4-grams carry it */
CHECK(sp_embed_text("kompaktierung", 256, a) == 0);
CHECK(sp_embed_text("kompaktierung der sitzung", 256, b) == 0);
fprintf(stderr, " encoder: compound %.3f\n", sp_embed_dot(a, b, 256));
CHECK(sp_embed_dot(a, b, 256) > 0.4);
/* nothing to say: no direction, and the call says so */
CHECK(sp_embed_text("the and of to", 256, v) == -1);
CHECK(sp_embed_text("", 256, v) == -1);
CHECK(sp_embed_text(NULL, 256, v) == -1);
CHECK(sp_embed_text("x", 0, v) == -1);
}
/* --------------------------------------------------------------- index */
static void
write_session(const char *dir, const char *id, const char *const *lines,
size_t n)
{
char path[700];
FILE *f;
size_t i;
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, id);
f = fopen(path, "a");
if (f == NULL) {
perror(path);
return;
}
for (i = 0; i < n; i++)
fprintf(f, "%s\n", lines[i]);
fclose(f);
}
static long
file_size(const char *path)
{
struct stat st;
if (stat(path, &st) != 0)
return -1;
return (long)st.st_size;
}
static void
test_index(void)
{
char tmpl[] = "/tmp/splinter-emb-XXXXXX";
char *dir = mkdtemp(tmpl);
char err[256], status[256], efile[800];
const char *first[] = {
"{\"role\":\"user\",\"text\":\"die kompaktierung wirft den "
"anfang der sitzung weg\"}",
"{\"role\":\"assistant\",\"text\":\"der tail bleibt, und der "
"rest steht im session-log\"}",
"{\"role\":\"user\",\"text\":\"welche ports hoert der dienst?\"}",
"{\"role\":\"assistant\",\"text\":\"der dienst hoert auf 8080 "
"und spricht http\"}"
};
const char *more[] = {
"{\"role\":\"user\",\"text\":\"und wie wird der index "
"nachgezogen?\"}"
};
struct sp_embed_ctx *c;
struct sp_config conf;
struct sp_buf out;
struct stat st;
int n;
if (dir == NULL) {
fprintf(stderr, "FAIL: no temp dir\n");
failures++;
return;
}
sp_config_init(&conf);
conf.embed = SP_EMBED_LOCAL;
conf.embed_dims = 256;
write_session(dir, "s1", first, 4);
c = sp_embed_new(&conf);
CHECK(c != NULL);
if (c == NULL)
return;
sp_embed_bind(c, dir, "s1");
/* the caller's thread does the work, so the test is deterministic */
CHECK(sp_embed_index_now(c, err, sizeof(err)) == 0);
if (err[0] != '\0')
fprintf(stderr, " index: %s\n", err);
snprintf(efile, sizeof(efile), "%s/emb/s1.emb", dir);
CHECK(file_size(efile) > 0);
CHECK(stat(efile, &st) == 0 && (st.st_mode & 07700) == 0600 &&
"the index file is private like the session");
sp_embed_status(c, status, sizeof(status));
fprintf(stderr, " status: %s\n", status);
CHECK(strstr(status, "4 messages") != NULL);
CHECK(strstr(status, "current") != NULL);
/* the file grew by one line: the next run adds one record, not five */
{
long before = file_size(efile);
write_session(dir, "s1", more, 1);
CHECK(sp_embed_index_now(c, err, sizeof(err)) == 0);
fprintf(stderr, " incremental: %ld -> %ld bytes\n", before,
file_size(efile));
CHECK(file_size(efile) > before);
sp_embed_status(c, status, sizeof(status));
CHECK(strstr(status, "5 messages") != NULL);
}
/* and the search finds by meaning, not by substring */
if (sp_buf_init(&out) != 0)
return;
n = sp_embed_search(c, "was passiert mit dem anfang bei der "
"kompaktierung", 3, &out);
fprintf(stderr, " search: %d hits\n%s", n, out.p != NULL ? out.p : "");
CHECK(n > 0);
CHECK(out.p != NULL && strstr(out.p, "kompaktierung") != NULL);
CHECK(out.p != NULL && strstr(out.p, "8080") == NULL);
/* the whole message comes back when asked for */
sp_buf_clear(&out);
n = sp_embed_search_full(c, "kompaktierung anfang", 1, 1, 4096, &out);
CHECK(n == 1);
CHECK(out.p != NULL && strstr(out.p, "die kompaktierung wirft den "
"anfang der sitzung weg") != NULL);
/* a query with no content words says so instead of ranking noise */
sp_buf_clear(&out);
CHECK(sp_embed_search(c, "the and of", 3, &out) == 0);
CHECK(out.p != NULL && strstr(out.p, "no searchable words") != NULL);
sp_buf_free(&out);
/* reopening the same session must not duplicate the index */
sp_embed_free(c);
c = sp_embed_new(&conf);
CHECK(c != NULL);
if (c != NULL) {
sp_embed_bind(c, dir, "s1");
CHECK(sp_embed_index_now(c, err, sizeof(err)) == 0);
sp_embed_status(c, status, sizeof(status));
fprintf(stderr, " after reopen: %s\n", status);
CHECK(strstr(status, "5 messages") != NULL);
sp_embed_free(c);
}
/* off is off, and it says why */
conf.embed = SP_EMBED_OFF;
c = sp_embed_new(&conf);
CHECK(c != NULL);
if (c != NULL) {
CHECK(sp_embed_index_now(c, err, sizeof(err)) == -1);
CHECK(strstr(err, "off") != NULL);
sp_embed_status(c, status, sizeof(status));
CHECK(strcmp(status, "off") == 0);
sp_embed_free(c);
}
}
/* a torn tail must not stop the index, and must not be counted either */
static void
test_torn(void)
{
char tmpl[] = "/tmp/splinter-embt-XXXXXX";
char *dir = mkdtemp(tmpl);
char err[256], status[256], path[800];
const char *lines[] = {
"{\"role\":\"user\",\"text\":\"erste nachricht\"}",
"{\"role\":\"assistant\",\"text\":\"zweite nachricht\"}"
};
struct sp_embed_ctx *c;
struct sp_config conf;
FILE *f;
if (dir == NULL)
return;
sp_config_init(&conf);
conf.embed = SP_EMBED_LOCAL;
write_session(dir, "s2", lines, 2);
/* a crash in the middle of a write */
snprintf(path, sizeof(path), "%s/s2.jsonl", dir);
f = fopen(path, "a");
if (f != NULL) {
fputs("{\"role\":\"user\",\"text\":\"abgeschnit", f);
fclose(f);
}
c = sp_embed_new(&conf);
CHECK(c != NULL);
if (c == NULL)
return;
sp_embed_bind(c, dir, "s2");
CHECK(sp_embed_index_now(c, err, sizeof(err)) == 0);
sp_embed_status(c, status, sizeof(status));
fprintf(stderr, " torn: %s\n", status);
CHECK(strstr(status, "2 messages") != NULL);
sp_embed_free(c);
}
/*
* A batch that never reaches the index must not leak the vectors it built.
* The remote encoder is the easy way to make one fail: with no endpoint it
* refuses before anything is written, and every retry rebuilt the whole batch.
*/
static void
test_failed_batch_frees_vectors(void)
{
char tmpl[] = "/tmp/splinter-embf-XXXXXX";
char *dir = mkdtemp(tmpl);
char err[256];
const char *lines[] = {
"{\"role\":\"user\",\"text\":\"erste nachricht ueber den dienst\"}",
"{\"role\":\"assistant\",\"text\":\"zweite nachricht ueber die ports\"}"
};
struct sp_embed_ctx *c;
struct sp_config conf;
if (dir == NULL)
return;
sp_config_init(&conf);
conf.embed = SP_EMBED_REMOTE;
snprintf(conf.embed_model, sizeof(conf.embed_model), "m");
conf.embed_dims = 16;
/* no embed_endpoint: the batch is refused, nothing is written */
write_session(dir, "s4", lines, 2);
c = sp_embed_new(&conf);
CHECK(c != NULL);
if (c == NULL)
return;
sp_embed_bind(c, dir, "s4");
CHECK(sp_embed_index_now(c, err, sizeof(err)) == -1);
fprintf(stderr, " refused batch: %s\n", err);
sp_embed_free(c);
}
/*
* The end-to-end shape: a session with a lot of history, one compaction, and
* the question that a compaction always makes unanswerable from the context.
*/
static void
test_compaction_recall(void)
{
char tmpl[] = "/tmp/splinter-embs-XXXXXX";
char *dir = mkdtemp(tmpl);
char err[256], big[512];
const char *lines[64];
struct sp_embed_ctx *c;
struct sp_config conf;
struct sp_buf out;
size_t i, n = 0, base;
int rc;
if (dir == NULL)
return;
sp_config_init(&conf);
conf.embed = SP_EMBED_LOCAL;
/*
* A real session: the interesting sentence is at the top and the rest is
* chatter, exactly the shape that compaction cuts away first.
*/
lines[n++] = "{\"role\":\"user\",\"text\":\"der deploy geht nur ueber "
"den rechner mit dem alten ssh-schluessel, port 2222\"}";
base = n;
for (i = 0; i < 40; i++) {
snprintf(big, sizeof(big), "{\"role\":\"%s\",\"text\":\"schritt "
"%zu: die datei wird gelesen und geprueft, danach geht es "
"weiter\"}", (i % 2) ? "assistant" : "user", i);
lines[n++] = strdup(big);
}
lines[n++] = "{\"role\":\"user\",\"text\":\"und noch etwas ganz "
"anderes: wie viele ports hat der dienst?\"}";
write_session(dir, "s3", lines, n);
/* the generated lines were strdup'd; the literals are not ours to free */
for (i = base; i < base + 40; i++)
free((char *)lines[i]);
c = sp_embed_new(&conf);
CHECK(c != NULL);
if (c == NULL)
return;
sp_embed_bind(c, dir, "s3");
CHECK(sp_embed_index_now(c, err, sizeof(err)) == 0);
if (sp_buf_init(&out) != 0)
return;
rc = sp_embed_search(c, "welchen port nimmt der deploy-rechner",
3, &out);
fprintf(stderr, " recall: %d hits\n%s", rc,
out.p != NULL ? out.p : "");
CHECK(rc > 0);
CHECK(out.p != NULL && strstr(out.p, "2222") != NULL);
sp_buf_free(&out);
sp_embed_free(c);
}
/*
* A remote index is only worth its network round trip when the vectors it
* stores are the ones the model returned. The reader used to call
* mcp_arg_num(collection_element, NULL, 0.0), which asks an object for a key
* and returns the default on an array - every stored vector was zeros, so an
* index built by embed = openai answered every search with nothing.
*
* The server here is a bag of words, not the local hash: text about the deploy
* machine and a question about its port land close, everything else far away.
*/
static const char *const fake_words[] = {
"deploy", "ssh", "key", "port", "index", "compaction", "service"
};
static void
fake_vector(const char *text, double *v, int dims)
{
char low[2048];
size_t i;
double norm = 0.0;
snprintf(low, sizeof(low), "%.2047s", text);
for (i = 0; low[i] != '\0'; i++)
if (low[i] >= 'A' && low[i] <= 'Z')
low[i] = (char)(low[i] - 'A' + 'a');
memset(v, 0, (size_t)dims * sizeof(*v));
for (i = 0; i < sizeof(fake_words) / sizeof(fake_words[0]) &&
(int)i < dims; i++) {
const char *p = low;
while ((p = strstr(p, fake_words[i])) != NULL) {
v[i] += 1.0;
p += strlen(fake_words[i]);
}
}
if (dims > (int)sizeof(fake_words) / (int)sizeof(fake_words[0]))
v[dims - 1] = 0.25;
for (i = 0; i < (size_t)dims; i++)
norm += v[i] * v[i];
if (norm > 0.0) {
/* Newton on x*x - norm: libm is not linked into the tests */
double x = norm;
for (i = 0; i < 60; i++)
x = 0.5 * (x + norm / x);
for (i = 0; i < (size_t)dims; i++)
v[i] /= x;
}
}
static void
fake_embed_answer(int fd, const char *body, int dims)
{
struct sp_buf out;
const char *p;
int first = 1;
sp_buf_init(&out);
sp_buf_puts(&out, "{\"object\":\"list\",\"data\":[");
p = strstr(body, "\"input\":[");
p = p != NULL ? p + 9 : NULL;
while (p != NULL && *p == '"') {
char buf[1024], vec[1024];
size_t n = 0, k, at = 0;
double v[512];
p++;
while (*p != '\0' && *p != '"' && n + 1 < sizeof(buf))
buf[n++] = *p++;
buf[n] = '\0';
if (*p == '"')
p++;
while (*p == ',' || *p == ' ')
p++;
fake_vector(buf, v, dims);
vec[0] = '\0';
for (k = 0; k < (size_t)dims; k++)
at += (size_t)snprintf(vec + at, sizeof(vec) - at,
"%s%.6f", k != 0 ? "," : "", v[k]);
if (!first)
sp_buf_puts(&out, ",");
sp_buf_printf(&out, "{\"object\":\"embedding\",\"index\":0,"
"\"embedding\":[%s]}", vec);
first = 0;
}
sp_buf_puts(&out, "],\"model\":\"fake\"}");
{
char head[256];
int hl;
hl = snprintf(head, sizeof(head),
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
"Content-Length: %zu\r\nConnection: close\r\n\r\n",
out.len);
(void)!write(fd, head, (size_t)hl);
(void)!write(fd, out.p != NULL ? out.p : "", out.len);
}
sp_buf_free(&out);
}
/* A one-request HTTP server on a loopback port; returns the pid, sets *port. */
static pid_t
start_embed_server(int *port)
{
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];
ssize_t got;
int c = accept(ls, NULL, NULL);
if (c < 0)
_exit(0);
got = read(c, req, sizeof(req) - 1);
if (got > 0) {
char *b;
req[got] = '\0';
b = strstr(req, "\r\n\r\n");
fake_embed_answer(c, b != NULL ? b : "",
64);
}
close(c);
}
}
close(ls);
return pid;
}
}
/*
* 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)
{
char tmpl[] = "/tmp/splinter-embr-XXXXXX";
char *dir = mkdtemp(tmpl);
char err[256], path[700], line[4096];
const char *lines[] = {
"{\"role\":\"user\",\"text\":\"the deploy machine wants the "
"ssh key and port 2222\"}",
"{\"role\":\"assistant\",\"text\":\"the frontend build is green "
"and the service listens on 8080\"}"
};
struct sp_embed_ctx *c;
struct sp_config conf;
struct sp_buf out;
FILE *f;
pid_t srv;
int port = 0, rc, saw = 0;
if (dir == NULL)
return;
srv = start_embed_server(&port);
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, "r1", lines, 2);
c = sp_embed_new(&conf);
CHECK(c != NULL);
if (c == NULL) {
kill(srv, SIGKILL);
(void)waitpid(srv, NULL, 0);
return;
}
sp_embed_bind(c, dir, "r1");
rc = sp_embed_index_now(c, err, sizeof(err));
CHECK(rc == 0);
if (rc != 0)
fprintf(stderr, " remote index: %s\n", err);
/*
* The stored vector has to carry the model's numbers. All-zero is
* exactly the bug: the index looked built and could never match.
*/
snprintf(path, sizeof(path), "%s/emb/r1.emb", dir);
f = fopen(path, "r");
CHECK(f != NULL);
if (f != NULL) {
while (fgets(line, sizeof(line), f) != NULL) {
const char *v = strstr(line, "\"v\":\"");
if (v == NULL)
continue;
v += 5;
/* base64 of 64 zero floats is 'A' repeated */
if (strspn(v, "A") < 40)
saw = 1;
}
fclose(f);
}
CHECK(saw);
if (sp_buf_init(&out) == 0) {
rc = sp_embed_search(c, "which port does the deploy machine "
"use", 3, &out);
fprintf(stderr, " remote search: rc=%d %s", rc,
out.p != NULL ? out.p : "");
CHECK(rc > 0);
CHECK(out.p != NULL && strstr(out.p, "port 2222") != NULL);
sp_buf_free(&out);
}
sp_embed_free(c);
kill(srv, SIGKILL);
(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)
{
fprintf(stderr, "== encoder\n");
test_encoder();
fprintf(stderr, "== index\n");
test_index();
fprintf(stderr, "== torn tail\n");
test_torn();
fprintf(stderr, "== refused batch\n");
test_failed_batch_frees_vectors();
fprintf(stderr, "== remote vectors\n");
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;
}
fprintf(stderr, "ok\n");
return 0;
}