Files
splinter/src/backend/embed.c
T
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

1732 lines
44 KiB
C

/*
* 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 <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <sys/wait.h>
#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 */
/*
* Bumped by sp_embed_bind() whenever the session it points at changes.
* The index thread copies the paths and this number under the lock, works
* on its own copy, and drops the result if the number moved - otherwise a
* catch_up that started on the old session publishes the old file's byte
* offset into the new session's index, and everything up to that offset is
* never searched.
*/
unsigned long gen;
long offset; /* bytes of the session indexed */
struct erec *rec;
size_t nrec;
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 <endpoint>/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++) {
/*
* mcp_arg_num() looks up a key in an
* object; a vector is a bare array, so the
* number has to be read from the node. It
* used to be mcp_arg_num(el, NULL, 0.0),
* which returns the default every time: a
* remote index of nothing but zeros, and a
* search that could never match.
*/
const mcp_json *el = mcp_array_at(vec, j);
if (el == NULL || el->t != MCP_NUM) {
sp_buf_printf(err, "embed: vector "
"%zu is not a number list", k);
mcp_json_free(v);
goto out;
}
out[k][j] = el->n;
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;
}
}
/*
* Free the vectors of a batch that did not hand them over: commit() nulls the
* ones it wrote, so everything still non-NULL here belongs to a batch that
* failed. Without this the retries of a failing remote encoder pile up until
* the worker parks.
*/
static void
vecs_free(double **vec, size_t n)
{
size_t i;
for (i = 0; i < n; i++) {
free(vec[i]);
vec[i] = 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;
char path[sizeof(c->path)];
size_t linecap = 0, n, i;
long pos;
unsigned long gen;
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;
pthread_mutex_lock(&c->lock);
/*
* One snapshot of what to index. The paths are copied here so that the
* fopen() below does not read a buffer sp_embed_bind() may be rewriting,
* and the generation says whether that bind happened while this run was
* working - see the check before the offset is published.
*/
snprintf(path, sizeof(path), "%s", c->path);
gen = c->gen;
if (path[0] == '\0' || c->dir[0] == '\0') {
pthread_mutex_unlock(&c->lock);
sp_buf_free(&err);
return 0;
}
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(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);
/* the session was swapped while this run read it */
if (c->gen == gen)
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");
vecs_free(vec, n);
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);
vecs_free(vec, n);
rc = -1;
break;
}
free(texts);
}
pthread_mutex_lock(&c->lock);
if (c->stop) {
pthread_mutex_unlock(&c->lock);
vecs_free(vec, n);
rc = -1;
break;
}
/*
* Before commit, not after: commit appends to the index of the
* session bound *now*. Records read from the previous file must
* not land there - dropping the batch costs one re-index of the
* new session, which the bind already queued.
*/
if (c->gen != gen) {
pthread_mutex_unlock(&c->lock);
vecs_free(vec, n);
break;
}
if (commit(c, p, vec, n) < 0) {
pthread_mutex_unlock(&c->lock);
vecs_free(vec, n);
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) {
/*
* First, so a catch_up() that is already inside the old file
* fails its generation check instead of writing into this one.
* The bump and the reset below happen under the same lock, so a
* run that reads gen and offset together sees either both old or
* both new.
*/
c->gen++;
snprintf(c->dir, sizeof(c->dir), "%s", dir);
snprintf(c->id, sizeof(c->id), "%s", id);
snprintf(c->path, sizeof(c->path), "%s/%s.jsonl", dir, id);
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;
}
/*
* The query has to land in the same vector space as the index. A remote index
* holds what the embedding model returned, so the question goes to the same
* model; hashing it locally instead compares two unrelated spaces and every
* search comes back empty. Returns 0 on success, -1 with err filled.
*/
static int
encode_query(struct sp_embed_ctx *c, const char *query, double *q,
struct sp_buf *err)
{
char *one[1];
double *vec[1];
if (c->cfg.kind != SP_EMBED_REMOTE)
return sp_embed_text(query, c->dims, q);
one[0] = (char *)query;
vec[0] = q;
return encode_remote(c, one, 1, vec, err);
}
/* ---------------------------------------------------------------- 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;
struct sp_buf err;
size_t i, n = 0, shown = 0;
struct stat st;
char path[sizeof(c->path)];
long filled;
int caught_up;
if (c == NULL || query == NULL || out == NULL)
return -1;
if (c->cfg.kind == SP_EMBED_OFF) {
sp_buf_puts(out, "embedding is off (core { embed = local })\n");
return 0;
}
if (sp_buf_init(&err) != 0)
return -1;
/*
* 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) {
/*
* The path and the offset go out of the lock with us: the turn
* thread may bind another session right after we unlock, and
* this answer is about the one that was bound here.
*/
snprintf(path, sizeof(path), "%s", c->path);
filled = c->offset;
pthread_mutex_unlock(&c->lock);
/*
* Two very different situations, and the model acts on the
* answer: an index that is still filling says "wait", a session
* with nothing indexable says "there is nothing here".
*/
if (!caught_up && path[0] != '\0' &&
stat(path, &st) == 0 && (long)st.st_size > filled)
sp_buf_puts(out, "the index is still filling; ask "
"again in a moment\n");
else
sp_buf_puts(out, "the index is empty: nothing in this "
"session has been indexed yet\n");
sp_buf_free(&err);
return 0;
}
q = calloc((size_t)c->dims, sizeof(double));
if (q == NULL) {
pthread_mutex_unlock(&c->lock);
sp_buf_free(&err);
return -1;
}
/*
* Encoded with the lock released: a remote encoder runs curl, and the
* index thread must not wait for that. The dims and the encoder are
* fixed once the context exists, so nothing here can change under us.
*/
pthread_mutex_unlock(&c->lock);
if (encode_query(c, query, q, &err) != 0) {
free(q);
if (c->cfg.kind == SP_EMBED_REMOTE)
sp_buf_printf(out, "the embedding endpoint refused the "
"query: %s\n", err.p != NULL ? err.p : "?");
else
sp_buf_puts(out, "the query has no searchable words\n");
sp_buf_free(&err);
return 0;
}
sp_buf_free(&err);
pthread_mutex_lock(&c->lock);
best = rank(c, q, &n);
free(q);
if (best == NULL) {
pthread_mutex_unlock(&c->lock);
sp_buf_free(&err);
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);
}