Kaynağa Gözat

fix(documents): refuse a vector row that no search could ever find

The vector_missing guard accepted a body carrying either `_vector` OR
`vector`. The documents route stores the body verbatim and a search
reads `_vector`. So a row written with `vector` was accepted with a 201
and was then findable by no search at all - the unsearchable junk row
the guard exists to prevent, admitted by the guard itself.

Measured before changing anything: two rows inserted into the same
collection from the same vector, one under each spelling, then searched
with that vector and min_score -1.0. Only the underscored row came back.

Refused rather than silently renamed. A caller who sent `vector` has
rows ALREADY stored and already unfindable; quietly fixing their next
write would leave those behind while making the problem look solved. The
message therefore names the field to use AND says to rewrite what is
already there.

Found by a consumer asking which field a RESTORE should write. The
question exposed it; no test did, and the guard's own comment describes
this exact failure two lines above the branch that caused it.

Also documents two things their restore test established:

- The export writes base64 and no insert route reads it.
  `vector_format=base64` emits `vector_b64`, while /documents wants
  `_vector` and /vectors wants `vector`, both as number arrays. So the
  one path a backup exists for does not round-trip without expanding
  first, and the 422 names what is missing rather than the good vector
  sitting in the field the exporter wrote. Whether to accept a base64
  write form is left open.

- A row count and an id set are structurally blind to the failure that
  matters when verifying a restore. They prove something was stored
  under the right names. A vector can be byte-perfect in the file,
  stored wrongly, read back flawlessly and rank nowhere. Their checks
  are the model: every restored row must be its own nearest neighbour at
  score 1.000000, and the same query_vector must score a row identically
  in the restored and original collections - they measured a delta of
  0.00e+00. Only retrieval by SIMILARITY exercises what a vector is for.

1243/1243 green.
fszontagh 1 ay önce
ebeveyn
işleme
a127e93e0e
4 değiştirilmiş dosya ile 88 ekleme ve 6 silme
  1. 3 0
      CLAUDE.md
  2. 2 0
      api/llms.txt
  3. 26 6
      src/handlers/documents.cpp
  4. 57 0
      tests/test_api_integration.cpp

+ 3 - 0
CLAUDE.md

@@ -156,6 +156,9 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **A filtered vector search can return FEWER hits than match, and the response now says so.** The walk goes only `kVectorFilterScanCap` (10000) deep into the ranking, so on a larger collection a filter whose matches lie deeper is silently short - measured at 455 returned of 553 true matches on 12448 rows. `VectorSearchResult::scanCapped` is set ONLY when the walk hit the cap while still short of `topK` and the ranking was not exhausted, so a filter that merely matches fewer rows than `top_k` is correctly reported as complete rather than crying wolf. The HTTP route adds `scan_capped`/`scanned`; `ctx...search()` keeps its ARRAY return and warns in the run console instead.
 - **Database failures keep their classification** (`db_errors.hpp`, client 2.11.4). `Client::Error::code()` on the throwing calls and the `Failure&` overloads on `update`/`patch`/`remove` feed one `translate()`: AlreadyExists → 409 `duplicate_values`, or `duplicate_id` when `reason` says so (database 2.12.1: a taken document id and a taken unique field value are the same code but different remedies), FailedPrecondition → 422 `relation_violation`, NotFound → 404, Unavailable/DeadlineExceeded/Unknown → 503, everything else → 500. **`ErrorCode::Ok` on a call that returned false means "did not apply", not an error** - map it to 404, or a plain missing document becomes a 500 with an empty message.
 - **`nlohmann::json` STORES invalid UTF-8 and throws only when you serialise it.** A binary `/fn` request body therefore reached the run request intact and blew up at `dump()` with `type_error.316`, which surfaced as a **500 with nothing pointing at the body** while the function never ran. `triggerBodyFields()` (`functions/trigger_body.hpp`, pure) now offers unserialisable bytes as base64 under their OWN keys - `body` stays `null`, `bodyBase64` carries them, `bodyEncoding` is `"base64"` - because base64 placed in `body` would hand an unprepared function a plausible-looking string that is not what was sent, and silent corruption is worse than a visible `null`. `bodyEncoding` is absent for a text body, so an existing function's trigger shape is unchanged. **`isValidUtf8()` (`utf8_text.hpp`) must agree with nlohmann's own decoder, not with a reading of RFC 3629** - a sequence it accepted and nlohmann rejected would only move the 500 - so it refuses overlongs, the surrogate range and anything past U+10FFFF, and the tests cross-check it against a real `dump()` over every single byte and all 65536 two-byte sequences rather than trusting either side alone.
+- **A VECTOR COLLECTION'S INSERT GUARD USED TO COMMIT THE EXACT BUG IT EXISTS TO PREVENT.** `vector_missing` accepted a body carrying either `_vector` OR `vector`, while the documents route stores the body verbatim and a search reads `_vector`. So a row written with `vector` got a 201 and was then findable by NO search - the unsearchable junk row the guard was written for, admitted by the guard. Measured with two rows inserted under the two spellings from the same vector: only the underscored one came back. Now refused, with a message that also says to REWRITE any row already stored that way, because a caller who hit this has unfindable rows behind them and silently fixing only their next write would leave those while looking solved. Found by a consumer asking which field a RESTORE should write - the question exposed it, not a test.
+- **The export writes base64 and no insert route reads it.** `vector_format=base64` emits `vector_b64`; `POST .../documents` wants `_vector` as a number array and `POST .../vectors` wants `vector` as a number array. So the one path a backup exists for does not round-trip without expanding the base64 first, and the 422 a caller gets names what is MISSING rather than the good vector sitting in the field the exporter wrote. Documented in `api/llms.txt`; whether to accept a base64 write form is open.
+- **VERIFYING A RESTORE: a row count and an id set cannot see the failure that matters.** They prove something was stored under the right names. A vector can be byte-perfect in the file, stored under the wrong field or in the wrong form, read back flawlessly and rank nowhere. A consumer's restore test is the model: every restored row must be **its own nearest neighbour at score 1.000000**, and the same `query_vector` must score a row **identically** in the restored and original collections (they measured a delta of 0.00e+00). Only retrieval BY SIMILARITY exercises what a vector is for - which is the same lesson as a digest that matched while the ordering was wrong.
 - **Document write bodies accept two shapes, via one reader.** `documentBody()` in `handlers/documents.cpp` is used by POST, PUT and PATCH: it unwraps `{"data":{...}}`, strips `id` (the document's identity, from the body on POST and from the URL on PUT/PATCH), and rejects `data` alongside any other top-level key with **422** `ambiguous_body`. Before 0.3.3 only POST unwrapped, so a `{"data":...}` PUT stored the wrapper as a literal field and a `data`-plus-siblings POST dropped the siblings silently. A literal top-level `data` field is still writable as `{"data":{"data":...}}`.
 - **QuickJS is pinned to an exact quickjs-ng tag** (`SVAPI_QUICKJS_TAG`, `runner/CMakeLists.txt`). QuickJS bytecode carries **no version stamp**, so a silent upgrade makes a cached blob *misread* rather than fail. quickjs-ng, not Bellard's tree: the module/promise/stack entry points the core needs (`JS_GetModuleNamespace`, `JS_PromiseState`, `JS_SetMaxStackSize`, `JS_IsJobPending`) are public API there. `JsBytecode` is an in-process cache only - never persist it without a QuickJS build fingerprint.
 - **QuickJS's job queue belongs to the `JSRuntime`, not the `JSContext`.** A fresh context per run is therefore *not* enough to isolate tenants: a run that times out mid-microtask leaves its jobs queued, and they would execute inside the next tenant's run. The core flushes them with the deadline forced into the past and marks the runtime `poisoned()` if anything survives; the pool destroys a poisoned runtime instead of leasing it out. An OOM poisons it too.

+ 2 - 0
api/llms.txt

@@ -136,6 +136,8 @@ Relation names are per-project and **unqualified**: requests and responses alway
 
 Requires a `kind=vector` collection. Vectors are stored with cosine-similarity indexing.
 
+- **RESTORING AN EXPORT: the export writes base64 and the insert routes do NOT read it.** `GET .../export` with `vector_format=base64` emits each row's vector as **`vector_b64`**, but there is no base64 WRITE form - `POST .../documents` wants **`_vector`** as a JSON array of numbers, and `POST .../vectors` wants **`vector`** as a JSON array. So an export cannot be fed straight back in: expand the base64 to float32 little-endian numbers first. The 422 you get otherwise says `vector_missing`, which is accurate and unhelpful - it names what is absent rather than the perfectly good vector sitting in the field the exporter put it in. **A document inserted with a field called `vector` (rather than `_vector`) is now REFUSED** for the same reason: it used to be accepted with a 201 and then found by no search at all, because the body is stored verbatim while a search reads `_vector`. If you have rows already stored that way they are unfindable and need rewriting.
+- **Verifying a restore: a row count and an id set are structurally blind to the failure that matters.** They prove you stored something under the right names. A vector can survive byte-perfect in a file, be stored under the wrong field or in the wrong form, read back flawlessly and rank nowhere. The checks that catch it: every restored row should be **its own nearest neighbour at score 1.000000**, and the same `query_vector` should score a row **identically** in the restored and original collections. Only asking the store to retrieve by SIMILARITY exercises the thing a vector is for.
 - `POST /api/v1/projects/{project}/collections/{name}/vectors` `{id?, text?, vector?, metadata?}` - Store a vector. Supply either `text` (the server embeds it, resolving the model as: the collection's `embedding_model` pin, else the project's embedding override, else the global default) or a pre-computed `vector` array. `vector` dimension must match the collection's `vector_dimension`. `metadata` is an arbitrary JSON object stored alongside the vector.
 - `POST /api/v1/projects/{project}/collections/{name}/search` `{query_text?, query_vector?, top_k?, min_score?, filters?}` - Cosine-similarity search. Supply either `query_text` or `query_vector`; neither is **422**. `top_k` caps the results, **default 5**. `min_score` (0-1) drops low-confidence matches, default 0. `filters` is an array of `field:op:value` strings applied to the vector's metadata, using the grammar and operators above - metadata is stored at the top level of the document, so a vector written with `metadata:{"colour":"red"}` is filtered as `colour:eq:red`. The response also carries **`scan_capped`** and `scanned` (plus `scan_cap` when capped). **UPGRADE NOTE: a filtered search may now return MORE rows than it did before, and that is the fix rather than a break.** On the old capped path a filter whose matches lay deeper than the walk returned fewer hits than matched - one collection measured 426 rows for a filter with ~553 true matches at `top_k: 500`. On 2.14.0 the same query returns the full 500. So `top_k` now bounds a COMPLETE set rather than a truncated one, and code that was tuned around the smaller number - a page size, a display limit, a loop termination, a count treated as a ceiling - will see the larger one. If you built against the capped behaviour, check those before concluding a filter stopped filtering.
 

+ 26 - 6
src/handlers/documents.cpp

@@ -112,12 +112,32 @@ void registerDocumentRoutes(ApiServer& s) {
         //
         // So the rule is simply: a vector collection takes a vector. Text goes
         // to `.../vectors`, which embeds it.
-        if (t.meta.kind == "vector" && !data.contains("_vector") && !data.contains("vector"))
-            throw ApiError(ErrCode::Unprocessable, "vector_missing",
-                           "a document inserted into a vector collection must carry '_vector', or "
-                           "it can never be found by a search. This route does not embed: POST "
-                           ".../vectors with 'text' to have it embedded for you, or use a json "
-                           "collection if this row is not meant to be searchable");
+        if (t.meta.kind == "vector" && !data.contains("_vector"))
+            throw ApiError(
+                ErrCode::Unprocessable, "vector_missing",
+                data.contains("vector")
+                    // `vector` USED TO SATISFY THIS GUARD, and that was the bug
+                    // the guard exists to prevent, committed by the guard
+                    // itself: the body is stored verbatim while a search reads
+                    // `_vector`, so the row was accepted with a 201 and was
+                    // then invisible to every search. Measured: two rows
+                    // inserted with the same vector under the two spellings,
+                    // and only the underscored one came back.
+                    //
+                    // Refused rather than silently renamed. A caller who sent
+                    // `vector` has rows ALREADY stored and already unfindable,
+                    // and quietly fixing their next write would leave those
+                    // behind while making the problem look solved. The message
+                    // therefore says to rewrite them.
+                    ? "this row carries 'vector', which is not the field a search reads - the "
+                      "stored field must be '_vector'. A row written with 'vector' is accepted by "
+                      "the database and then found by NO search, so rename it here and rewrite "
+                      "any row already stored that way. POST .../vectors instead takes 'vector' "
+                      "(or 'text', which it embeds) and stores it correctly for you"
+                    : "a document inserted into a vector collection must carry '_vector', or "
+                      "it can never be found by a search. This route does not embed: POST "
+                      ".../vectors with 'text' to have it embedded for you, or use a json "
+                      "collection if this row is not meant to be searchable");
 
         const uint32_t ttl = ttlParam(req).value_or(0);
         std::string newId;

+ 57 - 0
tests/test_api_integration.cpp

@@ -3467,3 +3467,60 @@ TEST_F(ApiFixture, AFilterMatchingNothingIsAnEmptyResultNotAnError) {
     EXPECT_TRUE(j.at("results").empty()) << j.dump();
     EXPECT_FALSE(j.at("scan_capped").get<bool>()) << j.dump();
 }
+
+TEST_F(ApiFixture, ADocumentInsertedWithAPlainVectorFieldMustBeFINDABLE) {
+    // The vector_missing guard accepts EITHER `_vector` or `vector`, but the
+    // documents route stores the body verbatim while a search reads `_vector`.
+    // So `vector` may satisfy a guard whose entire purpose is to prevent a row
+    // that "can never be found by a search" - which would be the exact junk
+    // row it was written to refuse, admitted by the guard itself.
+    //
+    // Raised by a consumer asking which field a RESTORE should write. This
+    // test answers it with the server rather than with the documentation,
+    // which has been wrong twice in this area.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(),
+                     nlohmann::json{{"name","vfield"},{"kind","vector"},
+                                    {"vector_dimension",4}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/vfield/documents";
+    const std::string search = base + "/vfield/search";
+    const nlohmann::json vec = {1.0, 0.0, 0.0, 0.0};
+
+    // a) the underscored spelling, which the message tells you to use
+    auto a = c.Post(docs.c_str(),
+                    nlohmann::json{{"_vector",vec},{"tag","underscored"}}.dump(),
+                    "application/json");
+    ASSERT_TRUE(a); ASSERT_EQ(a->status, 201) << a->body;
+
+    // b) the bare spelling must now be REFUSED. It used to be accepted with a
+    // 201 and then be findable by no search at all.
+    auto b = c.Post(docs.c_str(),
+                    nlohmann::json{{"vector",vec},{"tag","bare"}}.dump(),
+                    "application/json");
+    ASSERT_TRUE(b);
+    EXPECT_EQ(b->status, 422) << "a row that no search can find was accepted: " << b->body;
+    EXPECT_NE(b->body.find("vector_missing"), std::string::npos) << b->body;
+    // The message must name BOTH the fix and the rows already stored wrongly,
+    // because a caller who hit this has unfindable rows behind them.
+    EXPECT_NE(b->body.find("_vector"), std::string::npos) << b->body;
+    EXPECT_NE(b->body.find("rewrite"), std::string::npos) << b->body;
+
+    auto s = c.Post(search.c_str(),
+                    nlohmann::json{{"query_vector",vec},{"top_k",10},
+                                   {"min_score",-1.0}}.dump(), "application/json");
+    ASSERT_TRUE(s); ASSERT_EQ(s->status, 200) << s->body;
+    const auto j = nlohmann::json::parse(s->body);
+
+    std::set<std::string> found;
+    for (const auto& h : j.at("results"))
+        if (h.at("data").contains("tag")) found.insert(h.at("data").at("tag").get<std::string>());
+
+    EXPECT_TRUE(found.count("underscored"))
+        << "a row written with _vector was not findable: " << j.dump();
+    // And nothing unfindable was stored, because the refusal above stopped it
+    // being written at all.
+    EXPECT_FALSE(found.count("bare")) << j.dump();
+    EXPECT_EQ(found.size(), 1u) << j.dump();
+}