Explorar o código

fix(documents): an export's vector_b64 must not read as data loss

Feeding an export taken with vector_format=base64 straight back into the
documents route answered "a document inserted into a vector collection
must carry '_vector'". Accurate, and the worst possible message for the
situation it occurs in.

A consumer named the misreading after restoring a 294 MB export:
somebody doing this at 3am reads it as "my backup has no vectors",
which is indistinguishable from real data loss and will be believed.
The error named what was absent while the caller held a perfectly good
vector in the field our own exporter had put it in.

The message now names `vector_b64`, says YOUR BACKUP IS FINE, and gives
the conversion - decode to float32 little-endian and send a JSON array
under `_vector`.

A test asserts the ordinary missing-vector case does NOT mention a
backup, so the reassurance cannot be offered where it would be false.

The general rule, recorded: when an error can be read as "your data is
gone", say explicitly that it is not. An error's worst reading is the
one it gets under pressure.

This does not close the underlying asymmetry - the export writes base64
and no insert route reads it - which stays open as a decision about
whether to accept a base64 write form. If that is ever added, this
message becomes unnecessary rather than wrong.
fszontagh hai 1 mes
pai
achega
d43c0f07de
Modificáronse 3 ficheiros con 50 adicións e 1 borrados
  1. 1 0
      CLAUDE.md
  2. 16 1
      src/handlers/documents.cpp
  3. 33 0
      tests/test_api_integration.cpp

+ 1 - 0
CLAUDE.md

@@ -158,6 +158,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **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.
+- **AN ERROR'S WORST READING IS THE ONE IT WILL GET UNDER PRESSURE.** Feeding an export's `vector_b64` back into the documents route used to answer "a document must carry `_vector`" - accurate, and read by someone restoring a 294 MB file at 3am as **"my backup has no vectors"**, which is indistinguishable from real data loss and will be believed. A consumer named that misreading after doing the restore. The message now names the export's own field, states that the backup is FINE, and says to expand the base64 - and a test asserts the ORDINARY missing-vector case does NOT mention a backup, so the reassurance cannot be given where it would be a lie. The general rule: when an error can be read as "your data is gone", say explicitly that it is not.
 - **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":...}}`.

+ 16 - 1
src/handlers/documents.cpp

@@ -115,7 +115,22 @@ void registerDocumentRoutes(ApiServer& s) {
         if (t.meta.kind == "vector" && !data.contains("_vector"))
             throw ApiError(
                 ErrCode::Unprocessable, "vector_missing",
-                data.contains("vector")
+                // The EXPORT spelling, and the most dangerous misreading of
+                // this error. An export taken with `vector_format=base64`
+                // emits `vector_b64`, and feeding it straight back here used
+                // to answer "a document must carry '_vector'" - which someone
+                // restoring a large file under pressure reads as "my backup
+                // has no vectors". That is indistinguishable from real data
+                // loss and it will be believed. So when the row carries the
+                // export's own field, say that the backup is fine and what to
+                // do, rather than naming what is absent.
+                (data.contains("vector_b64") || data.contains("_vector_b64"))
+                    ? "this row carries 'vector_b64', which is the EXPORT format and not a "
+                      "writable field - there is no base64 write form. YOUR BACKUP IS FINE: "
+                      "decode the base64 to float32 little-endian numbers and send them as a "
+                      "JSON array under '_vector'. The vector count in your export is not the "
+                      "problem and no data is 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

+ 33 - 0
tests/test_api_integration.cpp

@@ -3524,3 +3524,36 @@ TEST_F(ApiFixture, ADocumentInsertedWithAPlainVectorFieldMustBeFINDABLE) {
     EXPECT_FALSE(found.count("bare")) << j.dump();
     EXPECT_EQ(found.size(), 1u) << j.dump();
 }
+
+TEST_F(ApiFixture, TheExportsBase64FieldGetsAnErrorThatDoesNotREADAsDataLoss) {
+    // The 3am restore case, raised by a consumer who had just restored a
+    // 294 MB export. `vector_b64` is what the exporter writes; feeding it back
+    // used to answer "a document must carry '_vector'", which reads as "my
+    // backup has no vectors" - indistinguishable from real data loss, and it
+    // will be believed. The message must say the backup is FINE and what to do.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(),
+                     nlohmann::json{{"name","vb64"},{"kind","vector"},
+                                    {"vector_dimension",4}}.dump(),
+                     "application/json")->status, 201);
+    auto r = c.Post((base + "/vb64/documents").c_str(),
+                    nlohmann::json{{"vector_b64","AACAPwAAAAAAAAAAAAAAAA=="},
+                                   {"tag","from-export"}}.dump(), "application/json");
+    ASSERT_TRUE(r);
+    EXPECT_EQ(r->status, 422) << r->body;
+    // It must name the export's own field, so the reader knows we SAW it.
+    EXPECT_NE(r->body.find("vector_b64"), std::string::npos) << r->body;
+    // It must say the backup is fine - this is the whole point.
+    EXPECT_NE(r->body.find("BACKUP IS FINE"), std::string::npos) << r->body;
+    // And it must say what to do instead.
+    EXPECT_NE(r->body.find("_vector"), std::string::npos) << r->body;
+    // The plain `_vector` case must keep its own, different message, or this
+    // branch has swallowed the ordinary one.
+    auto plain = c.Post((base + "/vb64/documents").c_str(),
+                        nlohmann::json{{"tag","no-vector-at-all"}}.dump(), "application/json");
+    ASSERT_TRUE(plain);
+    EXPECT_EQ(plain->status, 422) << plain->body;
+    EXPECT_EQ(plain->body.find("BACKUP IS FINE"), std::string::npos)
+        << "the ordinary missing-vector case must not claim a backup is involved: " << plain->body;
+}