Ver código fonte

fix: the documents route checks a vector's WIDTH, not only its presence

POST .../documents guarded that `_vector` was PRESENT and never that it was
the collection's width, while both sibling write paths guarded both. Two
distinct faults got through, measured through the built binary rather than
argued:

  _vector length 3 into a dim-4 collection  ->  500 `internal`
  _vector as the STRING "AAAA"              ->  201, stored, unsearchable

The first is the classification defect: the database does refuse it, but as a
bare ErrorCode::Internal with no `reason`, so apiErrorFor can only map it to
500 - telling a caller that their own permanent, correctable mistake is our
outage, on the one class of fault no retry can ever fix. The same fault on
POST .../vectors answers 422 `dimension_mismatch`.

The second is worse and was not expected: a non-array `_vector` is not a
vector at all, the database stores the body verbatim, and the row reads back
perfectly while being findable by NO search. That is exactly the junk row the
presence guard beside it was written for, admitted through the gap in the
same guard - the shape this repo has now recorded three times.

Fixed on our side rather than in the error mapping: we hold the pin, so the
width is answerable before the call, and the only other way to classify the
database's refusal would be to match on its message text, which is forbidden
here. Routed to the database owners separately - a dimension mismatch should
carry a `reason` so any client can classify it.

A non-array takes the SAME slug as a wrong length: the remedy is identical and
two codes would send a caller looking for two fixes.

The test carries the falsifiability pairing, without which its refusal
assertions would pass equally against a route that refused every vector: the
correct width is still accepted AND still findable by a similarity search, not
merely counted. Deliberately falsified by removing the guard - the refusal
arms go red reporting 500, the string case reveals itself by storing a second
row, and the pairing stays green.

Found while answering novitax before they write 26186 rows into two freshly
pinned collections, where vector_dimension is write-once and the refusal is
the only thing standing between a wrong model card and a permanent mistake.
fszontagh 3 semanas atrás
pai
commit
515fc13c89
2 arquivos alterados com 111 adições e 0 exclusões
  1. 34 0
      src/handlers/documents.cpp
  2. 77 0
      tests/test_api_integration.cpp

+ 34 - 0
src/handlers/documents.cpp

@@ -180,6 +180,40 @@ void registerDocumentRoutes(ApiServer& s) {
                       ".../vectors with 'text' to have it embedded for you, or use a json "
                       "collection if this row is not meant to be searchable");
 
+        // AND THE VECTOR HAS TO BE THE RIGHT SHAPE, which this route checked
+        // nowhere while its two siblings both did. `POST .../vectors` and the
+        // runner's `.store()` each compare the resolved vector against the
+        // collection's pin and answer 422 `dimension_mismatch`; here the body
+        // went straight to the database, which refuses it as a bare
+        // `ErrorCode::Internal` carrying no `reason` - so `apiErrorFor` maps it
+        // to **500 `internal`**, telling a caller their own permanent,
+        // correctable mistake is our outage. Measured through the shipped debs:
+        // a length-3 vector into a dim-4 collection answered 500
+        // `internal` here and 422 `dimension_mismatch` on `.../vectors`, for
+        // the same fault in the same collection.
+        //
+        // The fix belongs on OUR side rather than in the error mapping: we hold
+        // the pin, so the length is answerable before the call, and the only
+        // other way to classify the database's refusal would be to match on its
+        // message text. The guard is the same CLASS as the presence check
+        // directly above it - a vector collection takes a vector, and it takes
+        // one of its own width - which is why it goes here and not behind a
+        // database round trip.
+        //
+        // A non-array `_vector` is the same refusal rather than its own: the
+        // caller's remedy is identical, and two slugs would send them looking
+        // for two fixes.
+        if (t.meta.kind == "vector") {
+            const auto& v = data.at("_vector");
+            if (!v.is_array() || v.size() != t.meta.vectorDimension)
+                throw ApiError(ErrCode::Unprocessable, "dimension_mismatch",
+                               "'_vector' must be an array of " +
+                                   std::to_string(t.meta.vectorDimension) +
+                                   " numbers, which is this collection's pinned dimension; got " +
+                                   (v.is_array() ? std::to_string(v.size()) + " elements"
+                                                 : std::string("a ") + v.type_name()));
+        }
+
         const uint32_t ttl = ttlParam(req).value_or(0);
         std::string newId;
         try {

+ 77 - 0
tests/test_api_integration.cpp

@@ -3056,6 +3056,83 @@ TEST_F(ApiFixture, InsertingAVectorlessDocumentIntoAVectorCollectionIsRefused) {
     ASSERT_TRUE(del);
 }
 
+TEST_F(ApiFixture, AWrongWidthVectorOnTheDocumentsRouteIsRefusedAsDimensionMismatch) {
+    // The documents route guarded the PRESENCE of `_vector` and never its
+    // WIDTH, while both sibling write paths guarded both. The database does
+    // refuse it - nothing lands silently - but it refuses as a bare
+    // `ErrorCode::Internal` with no `reason`, so `apiErrorFor` could only map
+    // it to 500 `internal`: a caller's permanent, correctable mistake reported
+    // as our outage, on the one class of fault where no retry can ever help.
+    //
+    // Found while answering a consumer about to write 26186 vectors into two
+    // freshly pinned collections, where a wrong width is baked in permanently
+    // and the refusal is the only thing that stops it.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    const std::string ct = "application/json";
+    ASSERT_EQ(c.Post(base.c_str(),
+                     nlohmann::json{{"name","vwide"},{"kind","vector"},
+                                    {"vector_dimension",4}}.dump(), ct)->status, 201);
+
+    auto count = [&]() {
+        auto r = c.Get((base + "/vwide/documents").c_str());
+        if (!r || r->status != 200) return std::size_t{0};
+        return nlohmann::json::parse(r->body)["documents"].size();
+    };
+
+    // Too short, and too long: both are the same mistake and the same slug.
+    for (const auto& v : {nlohmann::json{1.0, 0.0, 0.0},
+                          nlohmann::json{1.0, 0.0, 0.0, 0.5, 0.25}}) {
+        auto bad = c.Post((base + "/vwide/documents").c_str(),
+                          nlohmann::json{{"_vector", v}, {"tag", "bad"}}.dump(), ct);
+        ASSERT_TRUE(bad);
+        EXPECT_EQ(bad->status, 422) << bad->body;
+        EXPECT_NE(bad->body.find("dimension_mismatch"), std::string::npos) << bad->body;
+        // The message must name the collection's own width, because the caller
+        // cannot see the pin and "wrong dimension" alone does not say what to
+        // send instead.
+        EXPECT_NE(bad->body.find("4"), std::string::npos) << bad->body;
+        EXPECT_EQ(count(), 0u) << "a refused insert must store nothing";
+    }
+
+    // A `_vector` that is not an array at all takes the SAME slug rather than
+    // its own - the remedy is identical, and two codes would send a caller
+    // looking for two fixes.
+    auto notArray = c.Post((base + "/vwide/documents").c_str(),
+                           nlohmann::json{{"_vector", "AAAA"}}.dump(), ct);
+    ASSERT_TRUE(notArray);
+    EXPECT_EQ(notArray->status, 422) << notArray->body;
+    EXPECT_NE(notArray->body.find("dimension_mismatch"), std::string::npos) << notArray->body;
+
+    // THE PAIRING, without which the three assertions above would pass just as
+    // well against a route that refused EVERY vector: the correct width is
+    // still accepted, and is still findable by a SEARCH rather than merely
+    // stored. A guard that admits a row while leaving it unsearchable is the
+    // defect this whole family exists to prevent.
+    auto good = c.Post((base + "/vwide/documents").c_str(),
+                       nlohmann::json{{"_vector",{1.0,0.0,0.0,0.5}},{"tag","good"}}.dump(), ct);
+    ASSERT_TRUE(good);
+    ASSERT_EQ(good->status, 201) << good->body;
+    EXPECT_EQ(count(), 1u);
+    auto found = c.Post((base + "/vwide/search").c_str(),
+                        nlohmann::json{{"query_vector",{1.0,0.0,0.0,0.5}},{"top_k",10}}.dump(), ct);
+    ASSERT_TRUE(found);
+    ASSERT_EQ(found->status, 200) << found->body;
+    EXPECT_EQ(nlohmann::json::parse(found->body)["results"].size(), 1u)
+        << "the accepted row must be retrievable by similarity, not just by a count";
+
+    // And the sibling route still answers the SAME slug for the same fault, so
+    // the two cannot drift apart again.
+    auto viaVectors = c.Post((base + "/vwide/vectors").c_str(),
+                             nlohmann::json{{"vector",{1.0,0.0,0.0}}}.dump(), ct);
+    ASSERT_TRUE(viaVectors);
+    EXPECT_EQ(viaVectors->status, 422) << viaVectors->body;
+    EXPECT_NE(viaVectors->body.find("dimension_mismatch"), std::string::npos) << viaVectors->body;
+
+    auto del = c.Delete((base + "/vwide").c_str());
+    ASSERT_TRUE(del);
+}
+
 TEST_F(ApiFixture, ReplacingADocumentInAVectorCollectionIsRefused) {
     auto c = admin();
     const std::string base = "/api/v1/projects/" + project_ + "/collections";