diff --git a/src/backend/embed.c b/src/backend/embed.c index 1d0f3c2..0952359 100644 --- a/src/backend/embed.c +++ b/src/backend/embed.c @@ -767,8 +767,24 @@ encode_remote(struct sp_embed_ctx *c, char *const *texts, size_t n, goto out; } for (j = 0; j < nj; j++) { - out[k][j] = mcp_arg_num(mcp_array_at(vec, j), - 0, 0.0); + /* + * 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); @@ -1350,6 +1366,26 @@ sp_embed_index_now(struct sp_embed_ctx *c, char *err, size_t errcap) 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 { @@ -1442,6 +1478,7 @@ sp_embed_search_full(struct sp_embed_ctx *c, const char *query, size_t limit, { double *q; struct hit *best; + struct sp_buf err; size_t i, n = 0, shown = 0; struct stat st; int caught_up; @@ -1452,6 +1489,8 @@ sp_embed_search_full(struct sp_embed_ctx *c, const char *query, size_t limit, 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 @@ -1477,23 +1516,38 @@ sp_embed_search_full(struct sp_embed_ctx *c, const char *query, size_t limit, 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; } - if (sp_embed_text(query, c->dims, q) != 0) { + /* + * 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); - pthread_mutex_unlock(&c->lock); - sp_buf_puts(out, "the query has no searchable words\n"); + 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) diff --git a/tests/test_embed.c b/tests/test_embed.c index 3003c81..029bfe3 100644 --- a/tests/test_embed.c +++ b/tests/test_embed.c @@ -14,7 +14,13 @@ #include #include #include +#include +#include +#include +#include #include +#include +#include #include "splinter.h" #include "config.h" @@ -358,6 +364,240 @@ test_compaction_recall(void) sp_embed_free(c); } +/* + * A remote index is only worth its network round trip when the vectors it + * stores are the ones the model returned. The reader used to call + * mcp_arg_num(collection_element, NULL, 0.0), which asks an object for a key + * and returns the default on an array - every stored vector was zeros, so an + * index built by embed = openai answered every search with nothing. + * + * The server here is a bag of words, not the local hash: text about the deploy + * machine and a question about its port land close, everything else far away. + */ +static const char *const fake_words[] = { + "deploy", "ssh", "key", "port", "index", "compaction", "service" +}; + +static void +fake_vector(const char *text, double *v, int dims) +{ + char low[2048]; + size_t i; + double norm = 0.0; + + snprintf(low, sizeof(low), "%.2047s", text); + for (i = 0; low[i] != '\0'; i++) + if (low[i] >= 'A' && low[i] <= 'Z') + low[i] = (char)(low[i] - 'A' + 'a'); + memset(v, 0, (size_t)dims * sizeof(*v)); + for (i = 0; i < sizeof(fake_words) / sizeof(fake_words[0]) && + (int)i < dims; i++) { + const char *p = low; + + while ((p = strstr(p, fake_words[i])) != NULL) { + v[i] += 1.0; + p += strlen(fake_words[i]); + } + } + if (dims > (int)sizeof(fake_words) / (int)sizeof(fake_words[0])) + v[dims - 1] = 0.25; + for (i = 0; i < (size_t)dims; i++) + norm += v[i] * v[i]; + if (norm > 0.0) { + /* Newton on x*x - norm: libm is not linked into the tests */ + double x = norm; + + for (i = 0; i < 60; i++) + x = 0.5 * (x + norm / x); + for (i = 0; i < (size_t)dims; i++) + v[i] /= x; + } +} + +static void +fake_embed_answer(int fd, const char *body, int dims) +{ + struct sp_buf out; + const char *p; + int first = 1; + + sp_buf_init(&out); + sp_buf_puts(&out, "{\"object\":\"list\",\"data\":["); + p = strstr(body, "\"input\":["); + p = p != NULL ? p + 9 : NULL; + while (p != NULL && *p == '"') { + char buf[1024], vec[1024]; + size_t n = 0, k, at = 0; + double v[512]; + + p++; + while (*p != '\0' && *p != '"' && n + 1 < sizeof(buf)) + buf[n++] = *p++; + buf[n] = '\0'; + if (*p == '"') + p++; + while (*p == ',' || *p == ' ') + p++; + fake_vector(buf, v, dims); + vec[0] = '\0'; + for (k = 0; k < (size_t)dims; k++) + at += (size_t)snprintf(vec + at, sizeof(vec) - at, + "%s%.6f", k != 0 ? "," : "", v[k]); + if (!first) + sp_buf_puts(&out, ","); + sp_buf_printf(&out, "{\"object\":\"embedding\",\"index\":0," + "\"embedding\":[%s]}", vec); + first = 0; + } + sp_buf_puts(&out, "],\"model\":\"fake\"}"); + { + char head[256]; + int hl; + + hl = snprintf(head, sizeof(head), + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" + "Content-Length: %zu\r\nConnection: close\r\n\r\n", + out.len); + (void)!write(fd, head, (size_t)hl); + (void)!write(fd, out.p != NULL ? out.p : "", out.len); + } + sp_buf_free(&out); +} + +/* A one-request HTTP server on a loopback port; returns the pid, sets *port. */ +static pid_t +start_embed_server(int *port) +{ + struct sockaddr_in a; + socklen_t alen = sizeof(a); + int ls, one = 1; + + ls = socket(AF_INET, SOCK_STREAM, 0); + if (ls < 0) + return -1; + (void)setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); + memset(&a, 0, sizeof(a)); + a.sin_family = AF_INET; + a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + a.sin_port = 0; + if (bind(ls, (struct sockaddr *)&a, sizeof(a)) != 0 || + listen(ls, 8) != 0 || + getsockname(ls, (struct sockaddr *)&a, &alen) != 0) { + close(ls); + return -1; + } + *port = (int)ntohs(a.sin_port); + { + pid_t pid = fork(); + + if (pid == 0) { + for (;;) { + char req[8192]; + ssize_t got; + int c = accept(ls, NULL, NULL); + + if (c < 0) + _exit(0); + got = read(c, req, sizeof(req) - 1); + if (got > 0) { + char *b; + + req[got] = '\0'; + b = strstr(req, "\r\n\r\n"); + fake_embed_answer(c, b != NULL ? b : "", + 64); + } + close(c); + } + } + close(ls); + return pid; + } +} + +static void +test_remote_vectors_are_the_models(void) +{ + char tmpl[] = "/tmp/splinter-embr-XXXXXX"; + char *dir = mkdtemp(tmpl); + char err[256], path[700], line[4096]; + const char *lines[] = { + "{\"role\":\"user\",\"text\":\"the deploy machine wants the " + "ssh key and port 2222\"}", + "{\"role\":\"assistant\",\"text\":\"the frontend build is green " + "and the service listens on 8080\"}" + }; + struct sp_embed_ctx *c; + struct sp_config conf; + struct sp_buf out; + FILE *f; + pid_t srv; + int port = 0, rc, saw = 0; + + if (dir == NULL) + return; + srv = start_embed_server(&port); + CHECK(srv > 0); + if (srv <= 0) + return; + + sp_config_init(&conf); + conf.embed = SP_EMBED_REMOTE; + snprintf(conf.embed_model, sizeof(conf.embed_model), "fake"); + snprintf(conf.embed_endpoint, sizeof(conf.embed_endpoint), + "http://127.0.0.1:%d/v1", port); + conf.embed_dims = 64; + write_session(dir, "r1", lines, 2); + + c = sp_embed_new(&conf); + CHECK(c != NULL); + if (c == NULL) { + kill(srv, SIGKILL); + (void)waitpid(srv, NULL, 0); + return; + } + sp_embed_bind(c, dir, "r1"); + rc = sp_embed_index_now(c, err, sizeof(err)); + CHECK(rc == 0); + if (rc != 0) + fprintf(stderr, " remote index: %s\n", err); + + /* + * The stored vector has to carry the model's numbers. All-zero is + * exactly the bug: the index looked built and could never match. + */ + snprintf(path, sizeof(path), "%s/emb/r1.emb", dir); + f = fopen(path, "r"); + CHECK(f != NULL); + if (f != NULL) { + while (fgets(line, sizeof(line), f) != NULL) { + const char *v = strstr(line, "\"v\":\""); + + if (v == NULL) + continue; + v += 5; + /* base64 of 64 zero floats is 'A' repeated */ + if (strspn(v, "A") < 40) + saw = 1; + } + fclose(f); + } + CHECK(saw); + + if (sp_buf_init(&out) == 0) { + rc = sp_embed_search(c, "which port does the deploy machine " + "use", 3, &out); + fprintf(stderr, " remote search: rc=%d %s", rc, + out.p != NULL ? out.p : ""); + CHECK(rc > 0); + CHECK(out.p != NULL && strstr(out.p, "port 2222") != NULL); + sp_buf_free(&out); + } + sp_embed_free(c); + kill(srv, SIGKILL); + (void)waitpid(srv, NULL, 0); +} + int main(void) { @@ -369,6 +609,8 @@ main(void) test_torn(); fprintf(stderr, "== refused batch\n"); test_failed_batch_frees_vectors(); + fprintf(stderr, "== remote vectors\n"); + test_remote_vectors_are_the_models(); fprintf(stderr, "== compaction recall\n"); test_compaction_recall(); if (failures != 0) {