From 87f5987a46f432ef2494c95f9519b3acecab8fa1 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sat, 21 Nov 2026 21:26:22 +0000 Subject: [PATCH] embed: a session is searchable by meaning, with no model and no key Compaction drops most of a session out of the window, and the only way back to it was a substring search. That answers "where does this word stand", not "what did we say about this". history_search is the second question: every message the session ever wrote gets a vector, and the model asks by meaning. Three rules shaped it. It works with no model. The default is a local encoder - the hashing trick over words, word bigrams and character 4-grams, 256 dimensions, pure CPU - so remembering does not stop when an API key expires. `embed = openai` points it at a real embedding model instead. The index records which one built it: a vector from one space compared against another is noise that looks like a result. It never costs the turn. Embedding runs on its own thread; the turn only says "this session grew" (sp_embed_note_compaction, called from the compaction event) and goes on. An index that lags is reported as lagging. It indexes the session file, not the conversation. The conversation is what is left after the last compaction; the file is everything that was said. "Before compaction" is not a snapshot to take, it is the file - and the index stores the byte offset it reached, so the update is incremental for free. It is derived data, append-only at /emb/.emb, and losing it costs a rebuild, never history. /status gains a row for it (index: N messages, lags by M). --- share/locale/de.msg | 1 + share/locale/en.msg | 1 + share/locale/pt_BR.msg | 1 + src/backend/config.c | 56 ++ src/backend/config.h | 11 + src/backend/embed.c | 1605 ++++++++++++++++++++++++++++++++++++++++ src/backend/embed.h | 128 ++++ tests/test_embed.c | 342 +++++++++ 8 files changed, 2145 insertions(+) create mode 100644 src/backend/embed.c create mode 100644 src/backend/embed.h create mode 100644 tests/test_embed.c diff --git a/share/locale/de.msg b/share/locale/de.msg index b345ae4..d911bb0 100644 --- a/share/locale/de.msg +++ b/share/locale/de.msg @@ -245,6 +245,7 @@ status.cost = Kosten status.cost_value = %.4f USD status.compact = Kompaktierung status.compact_value = %zu angewandt, %zu fehlgeschlagen, %zu Runden (Agent %zu) +status.embed = Index status.limits = Limits status.limits_value = max_bytes %zu, max_steps %zu%s status.autonomous = , autonom diff --git a/share/locale/en.msg b/share/locale/en.msg index f320e80..6a326ba 100644 --- a/share/locale/en.msg +++ b/share/locale/en.msg @@ -244,6 +244,7 @@ status.cost = cost status.cost_value = %.4f USD status.compact = compact status.compact_value = %zu applied, %zu failed, %zu turns (agent %zu) +status.embed = index status.limits = limits status.limits_value = max_bytes %zu, max_steps %zu%s status.autonomous = , autonomous diff --git a/share/locale/pt_BR.msg b/share/locale/pt_BR.msg index 09c7d41..2a770e4 100644 --- a/share/locale/pt_BR.msg +++ b/share/locale/pt_BR.msg @@ -248,6 +248,7 @@ status.cost = custo status.cost_value = %.4f USD status.compact = compactacao status.compact_value = %zu aplicadas, %zu falharam, %zu turnos (agente %zu) +status.embed = indice status.limits = limites status.limits_value = max_bytes %zu, max_steps %zu%s status.autonomous = , autonomo diff --git a/src/backend/config.c b/src/backend/config.c index a55ed5f..608e7f8 100644 --- a/src/backend/config.c +++ b/src/backend/config.c @@ -15,6 +15,7 @@ #include #include "config.h" +#include "embed.h" #include "usage.h" #include "confblock.h" @@ -23,6 +24,13 @@ sp_config_init(struct sp_config *c) { memset(c, 0, sizeof(*c)); c->autonomous = -1; + /* + * The index is on by default and it is the local encoder: the whole + * point is that a session becomes searchable without a model, a key or + * a network. `embed = off` turns it off; `embed = openai` swaps in a + * trained encoder. + */ + c->embed = SP_EMBED_LOCAL; snprintf(c->key_env, sizeof(c->key_env), "SPLINTER_API_KEY"); } @@ -761,6 +769,45 @@ load_stream(struct sp_config *c, FILE *f, const char *path, c->compact_threshold = (size_t)strtoul(val, NULL, 10); else if (!strcmp(key, "compact_target")) c->compact_target = (size_t)strtoul(val, NULL, 10); + /* + * The embedding index. `embed = local` is the built-in CPU + * encoder (no model, no key), `openai` posts to + * /embeddings, `off` disables it. + */ + else if (!strcmp(key, "embed")) { + if (!strcmp(val, "local") || !strcmp(val, "1") || + !strcmp(val, "true")) + c->embed = SP_EMBED_LOCAL; + else if (!strcmp(val, "openai") || + !strcmp(val, "remote")) + c->embed = SP_EMBED_REMOTE; + else if (!strcmp(val, "off") || !strcmp(val, "0") || + !strcmp(val, "false") || !strcmp(val, "none")) + c->embed = SP_EMBED_OFF; + else { + sp_buf_printf(err, "config: %s:%u: embed is " + "local, openai or off", path, lineno); + return -1; + } + } + else if (!strcmp(key, "embed_dims")) { + long d = strtol(val, NULL, 10); + + if (d < 8 || d > 4096) { + sp_buf_printf(err, "config: %s:%u: embed_dims " + "wants 8..4096", path, lineno); + return -1; + } + c->embed_dims = (int)d; + } + else if (!strcmp(key, "embed_model")) + set_str(c->embed_model, sizeof(c->embed_model), val); + else if (!strcmp(key, "embed_endpoint")) + set_str(c->embed_endpoint, sizeof(c->embed_endpoint), val); + else if (!strcmp(key, "embed_key_env")) + set_str(c->embed_key_env, sizeof(c->embed_key_env), val); + else if (!strcmp(key, "embed_timeout")) + c->embed_timeout = strtol(val, NULL, 10); else if (!strcmp(key, "http_timeout") || !strcmp(key, "request_timeout")) c->http_timeout = strtol(val, NULL, 10); @@ -920,6 +967,15 @@ sp_config_write_example(const char *path, struct sp_buf *err) " # A usage limit is waited out: splinter finds the reset and goes on.\n" " #on_limit = wait # or fail\n" " #max_wait = 12h\n" + "\n" + " # The session index behind history_search. `local` is built in and\n" + " # needs no model: feature hashing on the CPU, in a background\n" + " # thread, slower to build but never a request. `openai` sends to\n" + " # embed_endpoint, `off` keeps the tool away.\n" + " #embed = local\n" + " #embed_dims = 256 # vector size for `local`\n" + " #embed_endpoint = http://127.0.0.1:8080/v1\n" + " #embed_model = nomic-embed-text\n" "}\n" "\n" "# One block per plugin; what is in it is that plugin's own setting.\n" diff --git a/src/backend/config.h b/src/backend/config.h index 4857c88..35d5a53 100644 --- a/src/backend/config.h +++ b/src/backend/config.h @@ -173,6 +173,17 @@ struct sp_config { * and there is already an explicit cli delegate for the same program. */ int env_delegates; + /* + * The embedding index (see embed.h). On by default with the local + * encoder: a harness that needs an API key before it can remember + * anything stops remembering the day the key expires. + */ + int embed; /* SP_EMBED_OFF | _LOCAL | _REMOTE */ + int embed_dims; + char embed_model[256]; + char embed_endpoint[512]; + char embed_key_env[64]; + long embed_timeout; }; void sp_config_init(struct sp_config *); diff --git a/src/backend/embed.c b/src/backend/embed.c new file mode 100644 index 0000000..fa1a052 --- /dev/null +++ b/src/backend/embed.c @@ -0,0 +1,1605 @@ +/* + * splinter -- the embedding index of a session. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * See embed.h for why this exists. What follows is how. + * + * The encoder is the hashing trick: a text becomes a bag of features -- words, + * word bigrams, character 4-grams -- each feature is hashed to one of 'dims' + * buckets with a sign taken from another hash bit, weighted, and the whole + * vector is scaled to unit length. Two properties make it the right default + * here: it needs no model, no network and no training, and a near-identical + * text lands on a near-identical vector, which is all a recall tool needs. + * + * Its honest limit: it is lexical. "compaction" and "Kompaktierung" are two + * different features and their cosine is near zero. A real encoder fixes that; + * `embed = openai` asks for one. What does NOT happen is a silent mix of the + * two: the index file's first line names the encoder that built it, and a + * mismatch rebuilds instead of comparing two spaces. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "splinter.h" +#include "config.h" +#include "embed.h" +#include "b64.h" +#include "curl.h" +#include "log.h" +#include "mcp.h" + +#define EMBED_HEAD 240 /* bytes of a message kept for the hit list */ +#define EMBED_TEXT 8000 /* bytes of a message that are embedded */ +#define EMBED_SLOTS 4096 /* feature table per text */ +#define EMBED_BATCH 24 /* records per commit */ +/* How long a search waits for the index thread before answering anyway. */ +#define EMBED_SEARCH_WAIT_MS 20000 +/* + * On exit, wait this long for what is left. A short `-p` run used to leave a + * header-only index behind because nothing ever asked the worker to finish: + * the index stayed empty until some later run happened to look at the file. + * The bound is deliberate - leaving the process is not the place to wait for a + * 900 KB backlog. + */ +#define EMBED_EXIT_WAIT_MS 3000 + +#define EMBED_WAKE_MS 20000 /* how often the idle worker looks again */ +#define EMBED_FAIL_MAX 3 /* consecutive failures before it parks */ + +/* ------------------------------------------------------------------- bits */ + +/* No libm in this project's link line, and none is needed: one Newton loop. */ +static double +d_sqrt(double x) +{ + double g; + int i; + + if (x <= 0.0) + return 0.0; + g = x > 1.0 ? x : 1.0; + for (i = 0; i < 64; i++) { + double n = 0.5 * (g + x / g); + + if (n == g) + break; + g = n; + } + return g; +} + +static uint64_t +fnv(const char *s, size_t n) +{ + uint64_t h = 1469598103934665603ULL; + size_t i; + + for (i = 0; i < n; i++) { + h ^= (unsigned char)s[i]; + h *= 1099511628211ULL; + } + return h; +} + +/* ASCII lowercasing; bytes >= 0x80 pass through (UTF-8 is case-blind here) */ +static char +lower_byte(char c) +{ + return (c >= 'A' && c <= 'Z') ? (char)(c - 'A' + 'a') : c; +} + +static int +is_word(unsigned char c) +{ + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || c == '_' || c >= 0x80; +} + +/* + * The words that carry no meaning and would otherwise dominate every vector. + * Short on purpose: a stoplist is a blunt instrument, and the count weighting + * below already keeps a repeated word from running away. + */ +static int +is_stop(const char *w, size_t n) +{ + static const char *const stop[] = { + "the", "a", "an", "and", "or", "of", "to", "in", "is", "it", + "that", "this", "for", "on", "with", "as", "at", "be", "by", + "from", "was", "are", "were", "not", "but", "have", "has", + "had", "i", "you", "we", "they", "he", "she", "do", "does", + "did", "so", "if", "then", "than", "there", "their", "its", + "der", "die", "das", "den", "dem", "des", "ein", "eine", + "einer", "eines", "und", "oder", "aber", "ist", "sind", "war", + "waren", "nicht", "mit", "von", "zu", "zum", "zur", "im", + "am", "auf", "fuer", "aus", "bei", "nach", "wie", "was", + "wer", "wo", "wenn", "dann", "auch", "noch", "nur", "schon", + "sich", "man", "dass", "ich", "du", "er", "sie", "es", "wir", + "ihr", NULL + }; + size_t i; + + for (i = 0; stop[i] != NULL; i++) + if (strlen(stop[i]) == n && memcmp(stop[i], w, n) == 0) + return 1; + return 0; +} + +/* one feature: its hash, how often it was seen, and which kind it is */ +struct feat { + uint64_t key; + unsigned count; + unsigned char kind; /* 0 word, 1 bigram, 2 char 4-gram */ +}; + +static void +feat_add(struct feat *t, size_t cap, uint64_t h, unsigned char kind) +{ + size_t i; + + if (h == 0) + h = 1; + for (i = 0; i < cap; i++) { + size_t k = (size_t)(h % cap + i) % cap; + + if (t[k].key == 0) { + t[k].key = h; + t[k].count = 1; + t[k].kind = kind; + return; + } + if (t[k].key == h) { + if (t[k].count < 255) + t[k].count++; + return; + } + } + /* full: the feature is dropped, which costs a little recall, not safety */ +} + +static double +feat_weight(unsigned char kind) +{ + switch (kind) { + case 0: return 1.0; + case 1: return 0.6; + default: return 0.35; + } +} + +int +sp_embed_text(const char *text, int dims, double *v) +{ + struct feat *t; + char prev[64], cur[64]; + size_t n, i, plen = 0, clen = 0; + double norm = 0.0; + int any = 0; + + if (text == NULL || v == NULL || dims <= 0) + return -1; + for (i = 0; i < (size_t)dims; i++) + v[i] = 0.0; + t = calloc(EMBED_SLOTS, sizeof(*t)); + if (t == NULL) + return -1; + + n = strlen(text); + if (n > EMBED_TEXT) + n = EMBED_TEXT; + for (i = 0; i <= n; i++) { + unsigned char c = i < n ? (unsigned char)text[i] : ' '; + + if (is_word(c)) { + if (clen + 1 < sizeof(cur)) + cur[clen++] = lower_byte((char)c); + continue; + } + if (clen == 0) + continue; + cur[clen] = '\0'; + if (!is_stop(cur, clen)) { + feat_add(t, EMBED_SLOTS, fnv(cur, clen), 0); + any = 1; + if (plen > 0) { + char pair[132]; + size_t pn = plen + 1 + clen; + + if (pn < sizeof(pair)) { + memcpy(pair, prev, plen); + pair[plen] = ' '; + memcpy(pair + plen + 1, cur, clen); + feat_add(t, EMBED_SLOTS, fnv(pair, pn), 1); + } + } + /* + * Character 4-grams are what makes "kompaktier" meet + * "kompaktierung" and a typo meet its word. Only for + * words long enough to have any, and capped: a 300 + * byte token would otherwise own the vector. + */ + if (clen >= 5) { + size_t g, grams = clen - 3; + + if (grams > 24) + grams = 24; + for (g = 0; g < grams; g++) + feat_add(t, EMBED_SLOTS, + fnv(cur + g, 4), 2); + } + } + memcpy(prev, cur, clen); + plen = clen; + clen = 0; + } + if (!any) { + free(t); + return -1; /* nothing but stopwords: no direction */ + } + for (i = 0; i < EMBED_SLOTS; i++) { + double w; + + if (t[i].key == 0) + continue; + w = feat_weight(t[i].kind) * d_sqrt((double)t[i].count); + /* the sign comes from the same hash: no second table */ + v[(size_t)(t[i].key % (uint64_t)dims)] += + ((t[i].key >> 62) & 1u) ? -w : w; + } + free(t); + for (i = 0; i < (size_t)dims; i++) + norm += v[i] * v[i]; + norm = d_sqrt(norm); + if (norm <= 0.0) + return -1; + for (i = 0; i < (size_t)dims; i++) + v[i] /= norm; + return 0; +} + +double +sp_embed_dot(const double *a, const double *b, int dims) +{ + double s = 0.0; + int i; + + if (a == NULL || b == NULL || dims <= 0) + return 0.0; + for (i = 0; i < dims; i++) + s += a[i] * b[i]; + return s; +} + +/* -------------------------------------------------------------- the index */ + +struct erec { + double *v; + long off; /* where the line starts in the session file */ + long next; /* where the line after it starts */ + char role[12]; + char head[EMBED_HEAD]; +}; + +struct sp_embed_ctx { + struct sp_embed_cfg cfg; + int dims; /* of the vectors in memory and on disk */ + + pthread_mutex_t lock; + pthread_cond_t cond; + pthread_t th; + int have_thread; + int stop; + int pending; /* the session grew, or was bound */ + int busy; /* somebody is inside catch_up */ + int loaded; /* the file was read into rec */ + + char dir[512]; + char id[64]; + char path[640]; /* the .jsonl */ + char efile[700]; /* the .emb */ + + long offset; /* bytes of the session indexed */ + struct erec *rec; + size_t nrec; + size_t cap; + + unsigned runs, fails, fail_streak; + int parked; /* too many failures: wait for a nudge */ + long last_ms; + char err[200]; +}; + +static void +cfg_defaults(struct sp_embed_cfg *c) +{ + if (c->kind != SP_EMBED_OFF && c->kind != SP_EMBED_REMOTE) + c->kind = SP_EMBED_LOCAL; + /* only the local encoder has a width it can pick for itself */ + if (c->dims <= 0 && c->kind == SP_EMBED_LOCAL) + c->dims = 256; + if (c->dims > 4096) + c->dims = 4096; + if (c->timeout_s <= 0) + c->timeout_s = 60; + if (c->key_env[0] == '\0') + snprintf(c->key_env, sizeof(c->key_env), "SPLINTER_API_KEY"); +} + +void +sp_embed_cfg_from_config(const struct sp_config *conf, struct sp_embed_cfg *out) +{ + memset(out, 0, sizeof(*out)); + if (conf == NULL) { + cfg_defaults(out); + return; + } + out->kind = (enum sp_embed_kind)conf->embed; + out->dims = conf->embed_dims; + out->timeout_s = conf->embed_timeout; + snprintf(out->model, sizeof(out->model), "%s", conf->embed_model); + snprintf(out->endpoint, sizeof(out->endpoint), "%s", + conf->embed_endpoint); + snprintf(out->key_env, sizeof(out->key_env), "%s", conf->embed_key_env); + cfg_defaults(out); +} + +/* ---------------------------------------------------------------- records */ + +static void +recs_free(struct erec *v, size_t n) +{ + size_t i; + + if (v == NULL) + return; + for (i = 0; i < n; i++) + free(v[i].v); + free(v); +} + +static void +head_of(const char *text, char *out, size_t cap) +{ + size_t i, n = 0; + + if (cap == 0) + return; + for (i = 0; text[i] != '\0' && n + 1 < cap; i++) { + unsigned char c = (unsigned char)text[i]; + + if (c == '\n' || c == '\r' || c == '\t') + c = ' '; + else if (c < 0x20 || c == 0x7f) + continue; + out[n++] = (char)c; + } + out[n] = '\0'; +} + +/* float32, little-endian on disk: an index may travel between machines */ +static int +put_float32(struct sp_buf *b, float f) +{ + union { float f; uint32_t u; } v; + unsigned char raw[4]; + + v.f = f; + raw[0] = (unsigned char)(v.u & 0xff); + raw[1] = (unsigned char)((v.u >> 8) & 0xff); + raw[2] = (unsigned char)((v.u >> 16) & 0xff); + raw[3] = (unsigned char)((v.u >> 24) & 0xff); + return sp_buf_add(b, (const char *)raw, sizeof(raw)); +} + +static float +get_float32(const char *p) +{ + union { float f; uint32_t u; } v; + + v.u = (uint32_t)(unsigned char)p[0] | + ((uint32_t)(unsigned char)p[1] << 8) | + ((uint32_t)(unsigned char)p[2] << 16) | + ((uint32_t)(unsigned char)p[3] << 24); + return v.f; +} + +/* one index line: {"o":offset,"r":role,"h":head,"v":"base64 floats"} */ +static int +rec_line(struct sp_buf *line, const struct erec *r, int dims) +{ + struct sp_buf vec, b64; + int i, rc = -1; + + if (sp_buf_init(line) != 0 || sp_buf_init(&vec) != 0 || + sp_buf_init(&b64) != 0) { + sp_buf_free(line); + return -1; + } + for (i = 0; i < dims; i++) + if (put_float32(&vec, (float)r->v[i]) != 0) + goto out; + if (sp_b64_encode(vec.p != NULL ? vec.p : "", vec.len, &b64) != 0) + goto out; + if (sp_buf_printf(line, "{\"o\":%ld,\"n\":%ld,\"r\":\"", r->off, + r->next) != 0 || + sp_json_escape(line, r->role) != 0 || + sp_buf_puts(line, "\",\"h\":\"") != 0 || + sp_json_escape(line, r->head) != 0 || + sp_buf_puts(line, "\",\"v\":\"") != 0 || + sp_buf_add(line, b64.p != NULL ? b64.p : "", b64.len) != 0 || + sp_buf_puts(line, "\"}\n") != 0) + goto out; + rc = 0; +out: + sp_buf_free(&vec); + sp_buf_free(&b64); + if (rc != 0) + sp_buf_free(line); + return rc; +} + +/* -------------------------------------------------------------- the file */ + +/* the first line names the encoder; a different one means rebuild */ +static int +header_line(struct sp_buf *b, const struct sp_embed_cfg *cfg, int dims, + const char *id) +{ + const char *kind = cfg->kind == SP_EMBED_REMOTE ? "remote" : "local"; + + if (sp_buf_init(b) != 0) + return -1; + return sp_buf_printf(b, + "{\"sp_embed\":1,\"kind\":\"%s\",\"dims\":%d,\"model\":\"%s\"," + "\"session\":\"%s\"}\n", kind, dims, cfg->model, id); +} + +static int +header_matches(const char *line, const struct sp_embed_cfg *cfg, int dims) +{ + const char *kind = cfg->kind == SP_EMBED_REMOTE ? "remote" : "local"; + mcp_json *v = mcp_parse(line); + const char *gk, *gm; + int ok = 0; + + if (v == NULL) + return 0; + gk = mcp_arg_string(v, "kind"); + gm = mcp_arg_string(v, "model"); + ok = mcp_arg_num(v, "sp_embed", 0) == 1 && gk != NULL && gm != NULL && + strcmp(gk, kind) == 0 && strcmp(gm, cfg->model) == 0 && + (int)mcp_arg_num(v, "dims", 0) == dims; + mcp_json_free(v); + return ok; +} + +static int +start_file(struct sp_embed_ctx *c) +{ + struct sp_buf hdr; + FILE *w; + int rc; + + if (header_line(&hdr, &c->cfg, c->dims, c->id) != 0) + return -1; + w = fopen(c->efile, "w"); + if (w == NULL) { + snprintf(c->err, sizeof(c->err), "cannot write %.120s: %s", + c->efile, strerror(errno)); + sp_buf_free(&hdr); + return -1; + } + rc = fwrite(hdr.p, 1, hdr.len, w) == hdr.len ? 0 : -1; + sp_buf_free(&hdr); + if (fclose(w) != 0) + rc = -1; + if (rc != 0) + snprintf(c->err, sizeof(c->err), "cannot write %.120s", + c->efile); + return rc; +} + +/* + * Read the index file into memory. A torn tail is dropped, never repaired: it + * is derived data, and the next run re-reads those lines from the session. + * Lock held. + */ +static int +load_index(struct sp_embed_ctx *c) +{ + char *line = NULL; + size_t linecap = 0; + ssize_t len; + FILE *f; + struct stat st; + + c->loaded = 1; + f = fopen(c->efile, "r"); + if (f == NULL) + return start_file(c); + len = getline(&line, &linecap, f); + if (len <= 0 || !header_matches(line, &c->cfg, c->dims)) { + free(line); + (void)fclose(f); + sp_logf("embed", "%.80s: encoder changed, rebuilding", c->efile); + recs_free(c->rec, c->nrec); + c->rec = NULL; + c->nrec = 0; + c->cap = 0; + c->offset = 0; + return start_file(c); + } + while ((len = getline(&line, &linecap, f)) > 0) { + mcp_json *v; + const char *b64; + struct sp_buf raw; + struct erec r; + size_t i; + + if (line[len - 1] != '\n' || line[0] != '{') + continue; /* the torn tail of a crash */ + v = mcp_parse(line); + if (v == NULL) + continue; + b64 = mcp_arg_string(v, "v"); + memset(&r, 0, sizeof(r)); + if (b64 == NULL) { + mcp_json_free(v); + continue; + } + if (sp_buf_init(&raw) != 0) { + mcp_json_free(v); + continue; + } + if (sp_b64_decode(b64, strlen(b64), &raw) != 0 || + raw.len != (size_t)c->dims * 4) { + sp_buf_free(&raw); + mcp_json_free(v); + continue; + } + r.v = calloc((size_t)c->dims, sizeof(double)); + if (r.v != NULL) + for (i = 0; i < (size_t)c->dims; i++) + r.v[i] = (double)get_float32(raw.p + i * 4); + sp_buf_free(&raw); + if (r.v == NULL) { + mcp_json_free(v); + continue; + } + r.off = (long)mcp_arg_num(v, "o", 0); + r.next = (long)mcp_arg_num(v, "n", 0); + snprintf(r.role, sizeof(r.role), "%s", + mcp_arg_string(v, "r") != NULL ? + mcp_arg_string(v, "r") : "?"); + snprintf(r.head, sizeof(r.head), "%s", + mcp_arg_string(v, "h") != NULL ? + mcp_arg_string(v, "h") : ""); + if (c->nrec == c->cap) { + size_t nc = c->cap != 0 ? c->cap * 2 : 64; + struct erec *nv = realloc(c->rec, + nc * sizeof(*c->rec)); + + if (nv == NULL) { + free(r.v); + mcp_json_free(v); + break; + } + c->rec = nv; + c->cap = nc; + } + c->rec[c->nrec++] = r; + mcp_json_free(v); + } + free(line); + (void)fclose(f); + /* + * The index reaches as far as its last record: the next append starts + * there. Anything after it in the session file was never indexed and is + * picked up by the read below. + */ + if (c->nrec > 0) { + c->offset = c->rec[c->nrec - 1].next; + if (stat(c->path, &st) == 0 && c->offset > (long)st.st_size) + c->offset = 0; /* the session was replaced under us */ + } + return 0; +} + +/* ------------------------------------------------------------- encoding */ + +/* + * One text -> one vector, on the caller's thread. A message that is nothing + * but stopwords still gets a record, so the count stays honest; its vector + * points nowhere and it will simply never rank. + */ +static void +encode_one(struct sp_embed_ctx *c, const char *text, double *v) +{ + if (sp_embed_text(text, c->dims, v) == 0) + return; + memset(v, 0, (size_t)c->dims * sizeof(*v)); + v[0] = 1.0; +} + +/* POST /embeddings for a batch; fills out[i] with dims doubles each */ +static int +encode_remote(struct sp_embed_ctx *c, char *const *texts, size_t n, + double **out, struct sp_buf *err) +{ + struct sp_buf body, resp; + char path[520], data[560], url[600], auth[600], tmo[32]; + const char *args[16]; + const char *hdrs[2] = { NULL, NULL }; + const char *key; + char chunk[4096], *nl; + pid_t pid = -1; + FILE *f; + int fd, i, status = 0, rc = -1; + size_t got, k; + long http = 0; + + if (c->cfg.endpoint[0] == '\0') { + sp_buf_puts(err, "embed: embed = openai needs embed_endpoint"); + return -1; + } + if (sp_buf_init(&body) != 0 || sp_buf_init(&resp) != 0) + return -1; + if (sp_buf_printf(&body, "{\"model\":\"%s\",\"input\":[", c->cfg.model) + != 0) + goto out; + for (i = 0; i < (int)n; i++) { + if (i > 0 && sp_buf_puts(&body, ",") != 0) + goto out; + if (sp_buf_puts(&body, "\"") != 0 || + sp_json_escape(&body, texts[i]) != 0 || + sp_buf_puts(&body, "\"") != 0) + goto out; + } + if (sp_buf_puts(&body, "]}") != 0) + goto out; + + snprintf(path, sizeof(path), "%s/splinter-embed-XXXXXX", + getenv("TMPDIR") != NULL ? getenv("TMPDIR") : "/var/tmp"); + fd = mkstemp(path); + if (fd < 0) { + sp_buf_printf(err, "embed: mkstemp: %s", strerror(errno)); + goto out; + } + if (write(fd, body.p, body.len) != (ssize_t)body.len) { + close(fd); + (void)unlink(path); + sp_buf_puts(err, "embed: short write"); + goto out; + } + close(fd); + /* the body holds the message text, not a secret, but it still goes */ + snprintf(data, sizeof(data), "@%s", path); + snprintf(url, sizeof(url), "%s/embeddings", c->cfg.endpoint); + snprintf(tmo, sizeof(tmo), "%ld", c->cfg.timeout_s); + args[0] = "-sS"; + args[1] = "-m"; + args[2] = tmo; + args[3] = "-X"; + args[4] = "POST"; + args[5] = "-H"; + args[6] = "Content-Type: application/json"; + args[7] = "--data-binary"; + args[8] = data; + args[9] = "-w"; + args[10] = "\n%{http_code}"; + args[11] = NULL; + key = getenv(c->cfg.key_env); + if (key != NULL && *key != '\0') { + snprintf(auth, sizeof(auth), "Authorization: Bearer %s", key); + hdrs[0] = auth; + } + fd = sp_curl_start(args, url, hdrs, 1, &pid, err); + memset(auth, 0, sizeof(auth)); + if (fd < 0) { + (void)unlink(path); + goto out; + } + f = fdopen(fd, "r"); + if (f == NULL) { + close(fd); + (void)kill(pid, SIGKILL); + (void)waitpid(pid, NULL, 0); + (void)unlink(path); + sp_buf_puts(err, "embed: fdopen"); + goto out; + } + while ((got = fread(chunk, 1, sizeof(chunk), f)) > 0) + (void)sp_buf_add(&resp, chunk, got); + fclose(f); + (void)waitpid(pid, &status, 0); + (void)unlink(path); + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { + sp_buf_puts(err, "embed: curl failed"); + goto out; + } + nl = resp.p != NULL ? strrchr(resp.p, '\n') : NULL; + if (nl != NULL) { + http = strtol(nl + 1, NULL, 10); + *nl = '\0'; + } + if (http < 200 || http > 299) { + sp_buf_printf(err, "embed: endpoint answered %ld", http); + goto out; + } + { + mcp_json *v = mcp_parse(resp.p); + const mcp_json *arr; + size_t nd; + + if (v == NULL) { + sp_buf_puts(err, "embed: the answer is not JSON"); + goto out; + } + arr = mcp_arg(v, "data"); + nd = mcp_array_len(arr); + if (nd != n) { + sp_buf_printf(err, "embed: %zu vectors for %zu texts", + nd, n); + mcp_json_free(v); + goto out; + } + for (k = 0; k < nd; k++) { + const mcp_json *vec = mcp_arg(mcp_array_at(arr, k), + "embedding"); + size_t j, nj = mcp_array_len(vec); + double norm = 0.0; + + if (nj != (size_t)c->dims) { + sp_buf_printf(err, "embed: the model returns " + "%zu dims, embed_dims says %d", nj, c->dims); + mcp_json_free(v); + goto out; + } + for (j = 0; j < nj; j++) { + out[k][j] = mcp_arg_num(mcp_array_at(vec, j), + 0, 0.0); + norm += out[k][j] * out[k][j]; + } + norm = d_sqrt(norm); + if (norm > 0.0) + for (j = 0; j < nj; j++) + out[k][j] /= norm; + } + mcp_json_free(v); + } + rc = 0; +out: + sp_buf_free(&body); + sp_buf_free(&resp); + return rc; +} + +/* ------------------------------------------------------------- catch up */ + +struct pend { + char *text; + long off; + long next; + char role[12]; + char head[EMBED_HEAD]; +}; + +static void +pends_free(struct pend *p, size_t n) +{ + size_t i; + + for (i = 0; i < n; i++) { + free(p[i].text); + p[i].text = NULL; + } +} + +/* + * Read one session record into p. 1 = read, 0 = end of file, 2 = a line that + * holds nothing to embed (skipped), -1 = out of memory. 'pos' is the byte + * offset of the line and moves past it either way. + */ +static int +next_rec(FILE *f, char **line, size_t *cap, long *pos, struct pend *p) +{ + ssize_t len; + mcp_json *v; + const char *role, *text; + long start = *pos; + size_t n; + + len = getline(line, cap, f); + if (len < 0) + return 0; + *pos += (long)len; + if ((*line)[0] != '{' || (*line)[len - 1] != '\n') + return 2; /* a torn or foreign line */ + v = mcp_parse(*line); + if (v == NULL) + return 2; + role = mcp_arg_string(v, "role"); + text = mcp_arg_string(v, "text"); + if (role == NULL || text == NULL || text[0] == '\0') { + mcp_json_free(v); + return 2; + } + n = strlen(text); + p->text = malloc(n + 1); + if (p->text != NULL) + memcpy(p->text, text, n + 1); + p->off = start; + p->next = *pos; + snprintf(p->role, sizeof(p->role), "%s", role); + head_of(text, p->head, sizeof(p->head)); + mcp_json_free(v); + return p->text != NULL ? 1 : -1; +} + +/* + * Append one batch to the index file and to memory. Lock held. Takes ownership + * of vec[i] on success and sets it to NULL there; the caller frees the rest. + * Returns the number of records added, or -1. + */ +static int +commit(struct sp_embed_ctx *c, struct pend *p, double **vec, size_t n) +{ + FILE *f; + size_t i; + int added = 0; + + f = fopen(c->efile, "a"); + if (f == NULL) { + snprintf(c->err, sizeof(c->err), "cannot append %.120s: %s", + c->efile, strerror(errno)); + return -1; + } + for (i = 0; i < n && vec[i] != NULL; i++) { + struct erec r; + struct sp_buf line; + + memset(&r, 0, sizeof(r)); + memset(&line, 0, sizeof(line)); + r.v = vec[i]; + r.off = p[i].off; + r.next = p[i].next; + snprintf(r.role, sizeof(r.role), "%s", p[i].role); + snprintf(r.head, sizeof(r.head), "%s", p[i].head); + if (rec_line(&line, &r, c->dims) != 0 || + fwrite(line.p, 1, line.len, f) != line.len) { + sp_buf_free(&line); + snprintf(c->err, sizeof(c->err), "short write to %.120s", + c->efile); + break; + } + sp_buf_free(&line); + if (c->nrec == c->cap) { + size_t nc = c->cap != 0 ? c->cap * 2 : 64; + struct erec *nv = realloc(c->rec, + nc * sizeof(*c->rec)); + + if (nv == NULL) + break; + c->rec = nv; + c->cap = nc; + } + c->rec[c->nrec++] = r; + vec[i] = NULL; + added++; + } + if (fclose(f) != 0 && added >= 0) { + snprintf(c->err, sizeof(c->err), "cannot close %.120s", + c->efile); + added = added > 0 ? added : -1; + } + return added; +} + +/* + * Bring the index up to the end of the session file. Runs on the index thread, + * or on the caller's thread for sp_embed_index_now; 'busy' keeps them apart. + */ +static int +catch_up(struct sp_embed_ctx *c) +{ + struct sp_buf err; + struct pend p[EMBED_BATCH]; + double *vec[EMBED_BATCH]; + FILE *f; + char *line = NULL; + size_t linecap = 0, n, i; + long pos; + int rc = 0; + struct timespec t0, t1; + + memset(p, 0, sizeof(p)); + memset(vec, 0, sizeof(vec)); + if (sp_buf_init(&err) != 0) + return -1; + if (c->path[0] == '\0' || c->dir[0] == '\0') { + 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); + return -1; + } + pos = c->offset; + pthread_mutex_unlock(&c->lock); + + f = fopen(c->path, "r"); + if (f == NULL) { + /* nothing written yet is not a failure */ + sp_buf_free(&err); + return 0; + } + if (fseek(f, pos, SEEK_SET) != 0) { + pos = 0; + (void)fseek(f, 0, SEEK_SET); + } + clock_gettime(CLOCK_MONOTONIC, &t0); + for (;;) { + int eof = 0, bad = 0; + + n = 0; + while (n < EMBED_BATCH) { + int r = next_rec(f, &line, &linecap, &pos, &p[n]); + + if (r == 1) { + n++; + continue; + } + if (r == 0) + eof = 1; + else if (r < 0) + bad = 1; + /* r == 2: a torn or foreign line, skipped */ + break; + } + if (bad) { + sp_buf_puts(&err, "out of memory"); + rc = -1; + break; + } + if (n == 0) { + /* nothing embeddable left: the end, or one more line to skip */ + if (eof) { + pthread_mutex_lock(&c->lock); + c->offset = pos; + pthread_mutex_unlock(&c->lock); + break; + } + continue; + } + for (i = 0; i < n; i++) { + vec[i] = calloc((size_t)c->dims, sizeof(double)); + if (vec[i] == NULL) + break; + if (c->cfg.kind != SP_EMBED_REMOTE) + encode_one(c, p[i].text, vec[i]); + } + if (i < n) { + sp_buf_puts(&err, "out of memory"); + rc = -1; + break; + } + if (c->cfg.kind == SP_EMBED_REMOTE) { + char **texts = calloc(n, sizeof(*texts)); + + if (texts == NULL) { + sp_buf_puts(&err, "out of memory"); + rc = -1; + break; + } + for (i = 0; i < n; i++) + texts[i] = p[i].text; + if (encode_remote(c, texts, n, vec, &err) != 0) { + free(texts); + rc = -1; + break; + } + free(texts); + } + pthread_mutex_lock(&c->lock); + if (c->stop) { + pthread_mutex_unlock(&c->lock); + rc = -1; + break; + } + if (commit(c, p, vec, n) < 0) { + pthread_mutex_unlock(&c->lock); + rc = -1; + break; + } + c->offset = pos; + c->runs++; + clock_gettime(CLOCK_MONOTONIC, &t1); + c->last_ms = (t1.tv_sec - t0.tv_sec) * 1000 + + (t1.tv_nsec - t0.tv_nsec) / 1000000; + c->fail_streak = 0; + memset(c->err, 0, sizeof(c->err)); + pthread_cond_broadcast(&c->cond); + pthread_mutex_unlock(&c->lock); + pends_free(p, n); + if (eof) + break; + } + pends_free(p, n); + (void)fclose(f); + free(line); + if (rc != 0) { + pthread_mutex_lock(&c->lock); + snprintf(c->err, sizeof(c->err), "%s", + err.p != NULL ? err.p : "indexing failed"); + pthread_mutex_unlock(&c->lock); + } + sp_buf_free(&err); + return rc; +} + +/* ------------------------------------------------------------------- api */ + +static void * +embed_thread(void *arg) +{ + struct sp_embed_ctx *c = arg; + + for (;;) { + struct timespec until; + struct stat st; + int go = 0; + + clock_gettime(CLOCK_REALTIME, &until); + until.tv_sec += EMBED_WAKE_MS / 1000; + until.tv_nsec += (long)(EMBED_WAKE_MS % 1000) * 1000000L; + if (until.tv_nsec >= 1000000000L) { + until.tv_sec++; + until.tv_nsec -= 1000000000L; + } + pthread_mutex_lock(&c->lock); + while (!c->stop && !c->pending) { + if (pthread_cond_timedwait(&c->cond, &c->lock, &until) + != ETIMEDOUT) + continue; + /* + * The nudge is the compaction, but a session that never + * compacts must still become searchable. Look at the + * file now and then, and cost nothing when it did not + * grow. + */ + if (!c->parked && c->path[0] != '\0' && + stat(c->path, &st) == 0 && + (long)st.st_size > c->offset) + go = 1; + break; + } + if (c->stop) { + pthread_mutex_unlock(&c->lock); + break; + } + if (c->pending) { + c->pending = 0; + go = 1; + } + if (go && !c->busy) + c->busy = 1; + else + go = 0; + pthread_mutex_unlock(&c->lock); + if (!go) + continue; + { + int rc = catch_up(c); + + pthread_mutex_lock(&c->lock); + if (rc != 0) { + c->fails++; + c->fail_streak++; + if (c->fail_streak >= EMBED_FAIL_MAX && + !c->parked) { + c->parked = 1; + sp_logf("embed", "parked after %u " + "failures: %s", c->fail_streak, + c->err); + } + } + c->busy = 0; + pthread_cond_broadcast(&c->cond); + pthread_mutex_unlock(&c->lock); + } + } + return NULL; +} + +struct sp_embed_ctx * +sp_embed_new(const struct sp_config *conf) +{ + struct sp_embed_ctx *c = calloc(1, sizeof(*c)); + + if (c == NULL) + return NULL; + sp_embed_cfg_from_config(conf, &c->cfg); + c->dims = c->cfg.dims; + pthread_mutex_init(&c->lock, NULL); + pthread_cond_init(&c->cond, NULL); + if (c->cfg.kind == SP_EMBED_OFF) { + snprintf(c->err, sizeof(c->err), "off"); + return c; + } + if (c->cfg.kind == SP_EMBED_REMOTE && + (c->dims <= 0 || c->cfg.model[0] == '\0')) { + snprintf(c->err, sizeof(c->err), + "embed = openai needs embed_model and embed_dims"); + sp_logf("embed", "%s", c->err); + c->cfg.kind = SP_EMBED_OFF; + return c; + } + if (pthread_create(&c->th, NULL, embed_thread, c) != 0) { + snprintf(c->err, sizeof(c->err), "cannot start the thread"); + c->cfg.kind = SP_EMBED_OFF; + return c; + } + c->have_thread = 1; + return c; +} + +void +sp_embed_free(struct sp_embed_ctx *c) +{ + if (c == NULL) + return; + if (c->have_thread) { + /* + * Let the worker finish what is already on disk. Without this + * the process can end between "session line written" and "line + * indexed", and the index of that run stays empty. + */ + (void)sp_embed_flush(c, EMBED_EXIT_WAIT_MS); + pthread_mutex_lock(&c->lock); + c->stop = 1; + pthread_cond_broadcast(&c->cond); + pthread_mutex_unlock(&c->lock); + (void)pthread_join(c->th, NULL); + c->have_thread = 0; + } + recs_free(c->rec, c->nrec); + pthread_cond_destroy(&c->cond); + pthread_mutex_destroy(&c->lock); + free(c); +} + +void +sp_embed_bind(struct sp_embed_ctx *c, const char *dir, const char *id) +{ + int changed, queue = 0; + + if (c == NULL || dir == NULL || id == NULL || *id == '\0') + return; + if (c->cfg.kind == SP_EMBED_OFF) + return; + pthread_mutex_lock(&c->lock); + changed = strcmp(c->id, id) != 0 || strcmp(c->dir, dir) != 0; + if (changed) { + 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); + snprintf(c->efile, sizeof(c->efile), "%s/emb/%s.emb", dir, id); + { + char mk[600]; + + snprintf(mk, sizeof(mk), "%s/emb", dir); + (void)mkdir(mk, 0755); + } + recs_free(c->rec, c->nrec); + c->rec = NULL; + c->nrec = 0; + c->cap = 0; + c->offset = 0; + c->loaded = 0; + c->parked = 0; + c->fail_streak = 0; + memset(c->err, 0, sizeof(c->err)); + queue = 1; + } + /* + * The first bind of a session queues the whole file: a resumed + * conversation is searchable before anything is compacted, and /new + * starts the new one's index. A later bind of the same session costs + * nothing. + */ + if (queue) { + c->pending = 1; + pthread_cond_broadcast(&c->cond); + } + pthread_mutex_unlock(&c->lock); +} + +void +sp_embed_note_compaction(struct sp_embed_ctx *c) +{ + if (c == NULL || c->cfg.kind == SP_EMBED_OFF) + return; + pthread_mutex_lock(&c->lock); + if (!c->parked) { + c->pending = 1; + pthread_cond_broadcast(&c->cond); + } + pthread_mutex_unlock(&c->lock); +} + +int +sp_embed_flush(struct sp_embed_ctx *c, long timeout_ms) +{ + struct timespec until; + int idle; + + if (c == NULL || c->cfg.kind == SP_EMBED_OFF || !c->have_thread) + return 1; + clock_gettime(CLOCK_REALTIME, &until); + until.tv_sec += timeout_ms / 1000; + until.tv_nsec += (timeout_ms % 1000) * 1000000L; + if (until.tv_nsec >= 1000000000L) { + until.tv_sec++; + until.tv_nsec -= 1000000000L; + } + pthread_mutex_lock(&c->lock); + /* + * "Idle" has to mean "nothing left to index", not "the thread happens + * to be asleep". The worker only re-checks the file every + * EMBED_WAKE_MS, so a caller that arrives right after a user message + * was appended would otherwise be told there is nothing to do while the + * file is already longer than the offset. Nudge it here and wait for + * real. + */ + if (!c->parked && c->path[0] != '\0') { + struct stat st; + + if (stat(c->path, &st) == 0 && (long)st.st_size > c->offset && + !c->busy) { + c->pending = 1; + pthread_cond_broadcast(&c->cond); + } + } + while (c->pending || c->busy) + if (pthread_cond_timedwait(&c->cond, &c->lock, &until) == + ETIMEDOUT) + break; + idle = !c->pending && !c->busy; + pthread_mutex_unlock(&c->lock); + return idle; +} + +int +sp_embed_index_now(struct sp_embed_ctx *c, char *err, size_t errcap) +{ + int rc; + + if (err != NULL && errcap > 0) + err[0] = '\0'; + if (c == NULL) { + if (err != NULL && errcap > 0) + snprintf(err, errcap, "no index"); + return -1; + } + if (c->cfg.kind == SP_EMBED_OFF) { + if (err != NULL && errcap > 0) + snprintf(err, errcap, "%s", + c->err[0] != '\0' ? c->err : "embedding is off"); + return -1; + } + pthread_mutex_lock(&c->lock); + if (c->busy) { + pthread_mutex_unlock(&c->lock); + if (sp_embed_flush(c, 60000) == 0) { + if (err != NULL && errcap > 0) + snprintf(err, errcap, "still indexing"); + return -1; + } + pthread_mutex_lock(&c->lock); + } + c->busy = 1; + c->parked = 0; + c->fail_streak = 0; + c->pending = 0; + pthread_mutex_unlock(&c->lock); + rc = catch_up(c); + pthread_mutex_lock(&c->lock); + c->busy = 0; + if (rc != 0) { + c->fails++; + if (err != NULL && errcap > 0) + snprintf(err, errcap, "%s", c->err[0] != '\0' ? c->err : + "indexing failed"); + } + pthread_cond_broadcast(&c->cond); + pthread_mutex_unlock(&c->lock); + return rc; +} + +/* ---------------------------------------------------------------- search */ + +struct hit { + double score; + size_t idx; +}; + +static int +hit_cmp(const void *a, const void *b) +{ + const struct hit *x = a, *y = b; + + if (x->score != y->score) + return x->score < y->score ? 1 : -1; + return x->idx < y->idx ? -1 : (x->idx > y->idx); +} + +/* + * The hits, closest first. Lock held by the caller; q is the query's vector. + * Returns a malloc'd array the caller frees, or NULL. + */ +static struct hit * +rank(struct sp_embed_ctx *c, const double *q, size_t *n) +{ + struct hit *best; + size_t i; + + best = calloc(c->nrec > 0 ? c->nrec : 1, sizeof(*best)); + if (best == NULL) + return NULL; + for (i = 0; i < c->nrec; i++) { + best[i].score = sp_embed_dot(q, c->rec[i].v, c->dims); + best[i].idx = i; + } + qsort(best, c->nrec, sizeof(*best), hit_cmp); + *n = c->nrec; + return best; +} + +/* the whole message, read back from the session at the offset it was indexed */ +static int +print_at(struct sp_buf *out, const char *path, long off, size_t cap) +{ + FILE *f; + char *line = NULL; + size_t linecap = 0; + ssize_t len; + mcp_json *v; + const char *text; + size_t i, n; + + f = fopen(path, "r"); + if (f == NULL || fseek(f, off, SEEK_SET) != 0) { + if (f != NULL) + (void)fclose(f); + return sp_buf_puts(out, " (the message is gone from the " + "session file)\n"); + } + len = getline(&line, &linecap, f); + (void)fclose(f); + v = len > 0 ? mcp_parse(line) : NULL; + free(line); + if (v == NULL) + return sp_buf_puts(out, " (the message is gone from the " + "session file)\n"); + text = mcp_arg_string(v, "text"); + n = text != NULL ? strlen(text) : 0; + if (n > cap) + n = cap; + for (i = 0; i < n; i++) + if (sp_buf_add(out, &text[i], 1) != 0) + break; + if (text != NULL && strlen(text) > n) + sp_buf_puts(out, "\n [...]"); + sp_buf_puts(out, "\n"); + mcp_json_free(v); + return 0; +} + +int +sp_embed_search(struct sp_embed_ctx *c, const char *query, size_t limit, + struct sp_buf *out) +{ + return sp_embed_search_full(c, query, limit, 0, 4096, out); +} + +int +sp_embed_search_full(struct sp_embed_ctx *c, const char *query, size_t limit, + int full, size_t cap, struct sp_buf *out) +{ + double *q; + struct hit *best; + size_t i, n = 0, shown = 0; + struct stat st; + int caught_up; + + if (c == NULL || query == NULL || out == NULL) + return -1; + if (c->cfg.kind == SP_EMBED_OFF) { + sp_buf_puts(out, "embedding is off (core { embed = local })\n"); + return 0; + } + /* + * A search must not race the indexer. The thread reads the session file + * from the beginning and a question can arrive while it is still at line + * three, so the tool waits for it here. The wait is bounded: an indexer + * that is stuck (a failing remote endpoint) must not hang the turn, and + * a partial answer beats none. + */ + caught_up = sp_embed_flush(c, EMBED_SEARCH_WAIT_MS); + pthread_mutex_lock(&c->lock); + if (!c->loaded) + (void)load_index(c); + if (c->nrec == 0) { + 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) + sp_buf_puts(out, "the index is still filling; ask " + "again in a moment\n"); + else + sp_buf_puts(out, "the index is empty: nothing in this " + "session has been indexed yet\n"); + return 0; + } + q = calloc((size_t)c->dims, sizeof(double)); + if (q == NULL) { + pthread_mutex_unlock(&c->lock); + return -1; + } + if (sp_embed_text(query, c->dims, q) != 0) { + free(q); + pthread_mutex_unlock(&c->lock); + sp_buf_puts(out, "the query has no searchable words\n"); + return 0; + } + best = rank(c, q, &n); + free(q); + if (best == NULL) { + pthread_mutex_unlock(&c->lock); + return -1; + } + if (limit == 0 || limit > n) + limit = n; + { + double floor = 3.0 / d_sqrt((double)c->dims); + + for (i = 0; i < n && shown < limit; i++) { + const struct erec *r = &c->rec[best[i].idx]; + + /* + * A hashing index gives every pair a small positive + * score, so a query that matches nothing still + * "ranks" something. Measured: unrelated texts land + * around 0 with a spread of about 1/sqrt(dims), so + * three spreads is where a hit stops being + * distinguishable from a collision. Below it nothing + * is reported: an empty answer is honest, a ranked + * coincidence is not. + */ + if (best[i].score < floor) + break; + sp_buf_printf(out, "%2zu. %.3f %-9s %s\n", + shown + 1, best[i].score, r->role, r->head); + if (full) + (void)print_at(out, c->path, r->off, cap); + shown++; + } + } + free(best); + pthread_mutex_unlock(&c->lock); + if (shown == 0) + sp_buf_puts(out, "nothing in this session is close to that\n"); + return (int)shown; +} + +/* The tool: the model asks by meaning, not by substring. */ +static int +tool_history_search(const char *args, struct sp_buf *out, void *ctx) +{ + struct sp_embed_ctx *c = ctx; + char query[1000] = ""; + int limit = 8, full = 0; + size_t cap = 4096; + + if (args != NULL && args[0] == '{') { + mcp_json *v = mcp_parse(args); + const char *q; + + if (v != NULL) { + q = mcp_arg_string(v, "query"); + if (q != NULL) + snprintf(query, sizeof(query), "%s", q); + limit = (int)mcp_arg_num(v, "limit", 8); + full = (int)mcp_arg_num(v, "full", 0); + if (full) { + double want = mcp_arg_num(v, "bytes", 4096); + + if (want >= 200 && want <= 40000) + cap = (size_t)want; + } + mcp_json_free(v); + } + } + if (query[0] == '\0') + return sp_buf_puts(out, "error: query is required"); + if (limit <= 0 || limit > 50) + limit = 8; + return sp_embed_search_full(c, query, (size_t)limit, full, cap, + out) < 0 ? -1 : 0; +} + +int +sp_embed_register(struct sp_registry *r, struct sp_embed_ctx *c) +{ + struct sp_tool t; + + if (r == NULL || c == NULL) + return -1; + memset(&t, 0, sizeof(t)); + t.name = "history_search"; + t.description = "Search everything this session ever said, ranked by " + "meaning - including what compaction threw out of the context. Ask " + "with the words of the thing you are looking for; full=1 also " + "prints the message."; + t.params = "{\"type\":\"object\",\"properties\":{\"query\":" + "{\"type\":\"string\",\"description\":\"what to look for\"}," + "\"limit\":{\"type\":\"number\",\"description\":\"how many hits, " + "default 8\"},\"full\":{\"type\":\"number\",\"description\":\"1 " + "prints the whole message\"},\"bytes\":{\"type\":\"number\"," + "\"description\":\"bytes per printed message, default 4096\"}}," + "\"required\":[\"query\"]}"; + t.auth = SP_AUTH_READ; + t.run = tool_history_search; + t.ctx = c; + return sp_registry_add(r, &t); +} + +void +sp_embed_status(struct sp_embed_ctx *c, char *buf, size_t cap) +{ + const char *kind; + struct stat st; + long behind = 0; + + if (buf == NULL || cap == 0) + return; + if (c == NULL || c->cfg.kind == SP_EMBED_OFF) { + snprintf(buf, cap, "%s", c != NULL && c->err[0] != '\0' ? + c->err : "off"); + return; + } + kind = c->cfg.kind == SP_EMBED_REMOTE ? "remote" : "local"; + pthread_mutex_lock(&c->lock); + if (c->path[0] != '\0' && stat(c->path, &st) == 0) { + behind = (long)st.st_size - c->offset; + if (behind < 0) + behind = 0; + } + if (c->parked) + snprintf(buf, cap, "%s %dd, %zu messages, paused (%s)", kind, + c->dims, c->nrec, c->err[0] != '\0' ? c->err : "failed"); + else if (behind > 0) + snprintf(buf, cap, "%s %dd, %zu messages, %ld bytes behind", + kind, c->dims, c->nrec, behind); + else + snprintf(buf, cap, "%s %dd, %zu messages, current", kind, + c->dims, c->nrec); + pthread_mutex_unlock(&c->lock); +} diff --git a/src/backend/embed.h b/src/backend/embed.h new file mode 100644 index 0000000..6fa3cbe --- /dev/null +++ b/src/backend/embed.h @@ -0,0 +1,128 @@ +/* + * splinter -- the embedding index of a session. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * Compaction throws most of a session out of the context window. Until now the + * only way back to it was a substring search (lcm's recall, the session + * plugin's session_search), which answers "where does this word stand" and not + * "what did we say about this". The index here is the second question: every + * message a session ever wrote, with a vector, so the model can ask by meaning. + * + * Three rules shape it, and each one was paid for elsewhere in this tree. + * + * 1. It must work with no model at all. A harness that needs an embedding API + * before it can remember anything is a harness that stops remembering the + * day the key expires. So the default is local: the hashing trick over + * words, word bigrams and character 4-grams, a few hundred dimensions, + * pure CPU, microseconds per message. It is weaker than a trained encoder + * and it is honest about being a lexical measure -- it will not match + * "Kompaktierung" with "compaction", and its job does not require it to. + * kind = openai points it at a real embedding model instead; the index + * records which one built it, because a vector from one space compared to a + * vector from another is noise that looks like a result. + * + * 2. It must never cost the turn. Embedding runs on a thread of its own; the + * turn only says "this session grew" and goes on. Nothing waits for the + * index, and an index that lags is reported as lagging instead of pretending + * the newest messages are in it. + * + * 3. It indexes the session file, not the conversation. The conversation is + * what is left after the last compaction; the file is everything that was + * ever said. "Before compaction" is not a snapshot to take, it is the file. + * That also makes the update incremental for free: the index stores the byte + * offset it reached, so the next run reads only the new lines. + * + * The index is derived data. Losing it costs a rebuild, never history, so it + * lives next to the session and is written append-only: + * + * /emb/.emb + * + * one JSON object per line, the vector as base64 float32. + */ +#ifndef SPLINTER_EMBED_H +#define SPLINTER_EMBED_H + +#include + +#include "splinter.h" + +struct sp_config; +struct sp_registry; +struct sp_embed_ctx; + +enum sp_embed_kind { + SP_EMBED_OFF = 0, /* kind = off */ + SP_EMBED_LOCAL, /* the built-in hashing encoder, CPU */ + SP_EMBED_REMOTE /* POST /embeddings somewhere */ +}; + +struct sp_embed_cfg { + enum sp_embed_kind kind; + int dims; /* local: the hash width */ + char model[256]; + char endpoint[512]; + char key_env[64]; + long timeout_s; +}; + +/* the config file's embed settings, with the defaults applied */ +void sp_embed_cfg_from_config(const struct sp_config *, struct sp_embed_cfg *); + +/* + * One index per engine. ALWAYS returns a context, even with kind = off: the + * call sites must not each decide what "off" means. + */ +struct sp_embed_ctx *sp_embed_new(const struct sp_config *); +void sp_embed_free(struct sp_embed_ctx *); + +/* The session the index belongs to. A changed id starts the new one's index; + * the first bind of a session also queues the whole file, so a resume is + * searchable before anything is compacted. */ +void sp_embed_bind(struct sp_embed_ctx *, const char *dir, const char *id); + +/* A compaction just threw history out of the context. Cheap: a flag and a + * signal, no I/O and no work on the caller's thread. */ +void sp_embed_note_compaction(struct sp_embed_ctx *); + +/* + * Wait until the worker has caught up: 1 when it is idle, 0 on timeout. + * Tests need it; a shutdown may not. + */ +int sp_embed_flush(struct sp_embed_ctx *, long timeout_ms); + +/* Register the history_search tool. ctx is the index, owned by the engine. */ +int sp_embed_register(struct sp_registry *, struct sp_embed_ctx *); + +/* One line for /status or a widget: kind, records, how far behind. */ +void sp_embed_status(struct sp_embed_ctx *, char *buf, size_t cap); + +/* + * The pieces, exposed for tests and for the tool. None of these touch the + * thread. + */ + +/* Local encoder: 'v' must hold dims doubles. Returns 0, or -1 for an empty + * text (a vector of zeros has no direction). */ +int sp_embed_text(const char *text, int dims, double *v); + +/* Cosine of two L2-normalised vectors, which is their dot product. */ +double sp_embed_dot(const double *a, const double *b, int dims); + +/* + * Run the indexer for one session now, on the caller's thread. 'err' gets a + * message on failure and stays empty on success. Returns the number of records + * added, or -1. + */ +int sp_embed_index_now(struct sp_embed_ctx *, char *err, size_t errcap); + +/* Search the index: the 'limit' closest messages, written to out. */ +int sp_embed_search(struct sp_embed_ctx *, const char *query, size_t limit, + struct sp_buf *out); +/* The same, and with full != 0 each hit is followed by 'cap' bytes of the + * message itself, read back from the session log. */ +int sp_embed_search_full(struct sp_embed_ctx *, const char *query, + size_t limit, int full, size_t cap, struct sp_buf *out); + +#endif /* SPLINTER_EMBED_H */ diff --git a/tests/test_embed.c b/tests/test_embed.c new file mode 100644 index 0000000..d7715d9 --- /dev/null +++ b/tests/test_embed.c @@ -0,0 +1,342 @@ +/* + * 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 "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); +} + +/* + * 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); +} + +int +main(void) +{ + fprintf(stderr, "== encoder\n"); + test_encoder(); + fprintf(stderr, "== index\n"); + test_index(); + fprintf(stderr, "== torn tail\n"); + test_torn(); + 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; +}