/* * 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 #include #include #include #include #include #include #include #include #include #include #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; } } 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); } 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(); if (failures != 0) { fprintf(stderr, "FAILED: %d\n", failures); return 1; } fprintf(stderr, "ok\n"); return 0; }