Ver Fonte

feat(search): report which path answered, and tell the FUNCTION too

Two approved items, in one change because they are the same response.

filter_mode on a search response - "server", "walk" or "none". It
exists because `scan_capped: false` means two different things: on the
database's pre-filter path it is false BY CONSTRUCTION, so sweeping a
filtered set is sound, while on the fallback walk it means only
"complete this time" and a sweep is not. The boolean cannot carry that.

A caller must not infer the path from /api/v1/version, which reports the
CLIENT library version while the path depends on the SERVER - a 2.14
client against a 2.13 server reads as the new path while running the old
capped one. That unsoundness is the whole reason this is per-response.
One filterModeName() definition, so the HTTP route and the runner cannot
drift into two spellings.

And a function now learns its search was truncated, instead of only the
run's console. A console line reaches neither the function's logic nor a
model downstream of it, and a function's result is routinely handed to
one - a consumer's own bug was precisely that: they had logged their
degraded-search fallback for the operator, and the gap was that the
ASSISTANT was never told, so it said "nothing in memory" with
confidence.

The return STAYS AN ARRAY. The flags ride on it as non-enumerable
properties, so indexing, length, iteration, spread and JSON.stringify
are all unchanged. Tests assert each of those individually, and that the
flags do NOT appear in JSON.stringify - a script that serialises its
results sends exactly what it sent before. The prelude also accepts a
host answering the old bare-array shape, so the two halves can deploy in
either order.

The console warning is kept rather than replaced: it is what an author
reading a run log sees, and the two serve different readers.

1248/1248 green.
fszontagh há 1 mês atrás
pai
commit
197a8b8184

+ 1 - 0
CLAUDE.md

@@ -149,6 +149,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **A FILTERED VECTOR SEARCH IS NOW ONE SERVER-SIDE CALL (database 2.14.0+), exact and UNCAPPED.** The filters select candidates BEFORE ranking, so the answer is the true top-K among matching rows rather than a filtered slice of the unfiltered top-K, and there is no walk, no 10000 cap and nothing to truncate. Measured by the database team on 12447 rows at dim 4096: a filter matching ~430 rows at `topK` 500 took **51 ms indexed** against **187 ms for the same search unfiltered** - the filter makes it CHEAPER, because only matching rows are scored. Our emulation took **3.21 s** for that shape on prod.
   - **`scan_capped` is emitted EXPLICITLY as `false` on this path, never omitted**, and `scanned` is 0 because no walk happened - which here is literally true rather than a sentinel. A consumer maps an absent `scan_capped` to "this server cannot report truncation, so completeness is unknown" and shows that to an operator; on this path that is both false and PERMANENT, and a warning that always fires is one people learn to skip. Absence is also already spoken for by the 0.8.3 agreement, where a missing field means "old server" and nothing else.
   - **Detection is the server's own `filters_applied` response field, not a version check we have to get right.** A pre-2.14.0 server would silently answer UNFILTERED, so the client throws `FailedPrecondition` / `filters_unsupported` instead - which is the only reason the new path can be tried optimistically. The refusal is LATCHED per process, so a deployment on an older database pays one refused round trip rather than one per search; one-way on purpose, since the emulation is correct and merely capped, and it clears on the restart a database upgrade involves anyway.
+  - **`filter_mode` is on the response now, and a function's `.search()` carries it too.** `"server"`, `"walk"` or `"none"`, from the single `filterModeName()` so the HTTP route and the runner cannot spell it differently. On the function surface the return **stays an ARRAY** and the flags ride as NON-ENUMERABLE properties, so indexing, `length`, iteration, spread and `JSON.stringify` are byte-identical to before and a script written earlier is unaffected - tests assert each of those, and that the flags do NOT appear in `JSON.stringify`. The prelude also tolerates a host answering the old bare-array shape, so the two halves deploy in either order. The console warning STAYS: it is what an author reading a run log sees, and the structured flag is for the function's logic and for any model downstream of it - a consumer's own bug was exactly that their assistant was never told a search had degraded and said "nothing in memory" with confidence.
   - **`VectorSearchResult::serverFiltered` records which path answered**, because `scanCapped == false` means two different things: false BY CONSTRUCTION here (a sweep of a filtered set is sound) versus "complete this time" on the walk (it is not). A caller cannot infer it from `/api/v1/version`, which reports the CLIENT library version while the path depends on the SERVER - a 2.14 client against a 2.13 server reads as the new path while running the old capped one. Whether to expose it to callers is still open.
   - **The `Depends` floor had to move to `>= 2.14.0`, and that is load-bearing.** Verified rather than assumed, with `nm` on both shipped `.so` files: the 5-argument symbol exists only in 2.14.0, while 2.13.1 carries just the 4-argument form. Since every 2.x client shares one SONAME, leaving the old `>= 2.12.0` floor would have let apt install this binary against a client that cannot resolve the call - the failure that "installs fine and only breaks on the next restart".
 - **DATABASE 2.15.0 EXISTS AND IS NOT ADOPTED. Do not gate filtered search on a capability name.** 2.15.0 adds `GetServerInfo`, `serverInfo()`, `serverSupports(name)` and `Client::Capability` constants, and from it the client and server release independently (2.15.0 is the last lockstep release; the server no longer pins `libsmartbotic-db-client (= VERSION)`). Nothing in it changes our 2.14.0 alignment. **The trap, flagged by the database team: `serverSupports(Capability::kFilteredSimilarity)` is FALSE against a 2.14.0 server, which has no `GetServerInfo` but fully supports filters.** Capability names gate only features introduced in 2.15.0 or later, so a capability check there would silently drop us onto the emulation against the very server we just deployed. Keep what is built: call the filtered overload, and fall back only on `FailedPrecondition` with reason `filters_unsupported`. Adopting 2.15.0 would also make `serverInfo()` a cheaper answer than a `filter_mode` response field, because it finally exposes the SERVER version - which is the thing that decides support, and the gap that made version inference unsound. Note it costs one cached `GetServerInfo` per client per 60 s.

Diff do ficheiro suprimidas por serem muito extensas
+ 0 - 1
api/llms.txt


+ 1 - 41
api/openapi.json

@@ -2636,47 +2636,7 @@
         },
         "responses": {
           "200": {
-            "description": "Search results",
-            "content": {
-              "application/json": {
-                "schema": {
-                  "type": "object",
-                  "properties": {
-                    "results": {
-                      "type": "array",
-                      "items": {
-                        "type": "object",
-                        "properties": {
-                          "id": {
-                            "type": "string"
-                          },
-                          "score": {
-                            "type": "number"
-                          },
-                          "data": {
-                            "type": "object",
-                            "additionalProperties": true,
-                            "description": "The stored document. Named `data`, not `metadata`. The stored vector is NOT included - no read returns it."
-                          }
-                        }
-                      }
-                    },
-                    "scan_capped": {
-                      "type": "boolean",
-                      "description": "True when the filtered walk stopped at the candidate scan cap while still short of top_k, so MORE rows may match than were returned. False means the answer is complete, including a filter that simply matches fewer rows than top_k. Check it before treating a filtered result set as exhaustive."
-                    },
-                    "scanned": {
-                      "type": "integer",
-                      "description": "How deep into the ranking the walk went. Absent for an unfiltered search."
-                    },
-                    "scan_cap": {
-                      "type": "integer",
-                      "description": "The cap that was hit. Present only when scan_capped is true."
-                    }
-                  }
-                }
-              }
-            }
+            "description": "Hits plus completeness metadata: `results`, `scan_capped`, `scanned`, `filter_mode` (\"server\" = the database filtered before ranking, uncapped, so a sweep of a filtered set is sound; \"walk\" = the fallback emulation, where scan_capped:false means only \"complete this time\"; \"none\" = unfiltered), and `scan_cap` when capped. Do not infer the path from /api/v1/version: that reports the client library version while the path depends on the server."
           },
           "401": {
             "description": "Unauthorized"

+ 20 - 9
runner/src/host_context.cpp

@@ -2021,22 +2021,33 @@ struct HostContext::Impl {
         // thing here as it does on the HTTP route, scan cap included.
         const VectorSearchResult found = vectorSearch(db.client(), c, q, topK, minScore, filters);
 
-        // An incomplete answer is said out loud in the run's console rather
-        // than added to the return value: the return stays an ARRAY, which is
-        // what the design's example reads and what every existing script
-        // indexes into. A field would mean changing that shape for everyone to
-        // carry a flag almost no run needs - at the top_k of 5-10 a function
-        // actually uses, the cap is never reached.
+        // The console warning STAYS - it is what an author reading a run log
+        // sees. But it is no longer the only signal, because a console line
+        // reaches neither the function's logic nor an LLM downstream of it,
+        // and a function's result is routinely handed to a model. A consumer
+        // hit exactly this shape in their own code: they had logged their
+        // degraded-search fallback for the operator, and the gap was that the
+        // ASSISTANT was never told, so it stated "nothing in memory" with
+        // confidence. The structured signal is added below, next to the hits.
         if (found.scanCapped)
             addLog("[warn] search on '" + collection + "' stopped at the " +
                    std::to_string(kVectorFilterScanCap) +
                    "-candidate scan cap while still short of top_k " +
                    std::to_string(topK) + ": more rows may match than were returned");
 
-        nlohmann::json out = nlohmann::json::array();
+        // The RETURN SHAPE IS STILL AN ARRAY to the script - see the prelude,
+        // which unwraps this and attaches the two flags as PROPERTIES on the
+        // array it hands back. A JS array carries properties without affecting
+        // indexing, `length`, iteration, spread or `JSON.stringify`, so every
+        // existing script behaves identically and one that wants the flags
+        // reads them. Returning an object here and an array there is the only
+        // way to have both.
+        nlohmann::json hits = nlohmann::json::array();
         for (const auto& r : found.hits)
-            out.push_back({{"id", r.id}, {"score", r.score}, {"data", r.data}});
-        return out;
+            hits.push_back({{"id", r.id}, {"score", r.score}, {"data", r.data}});
+        return nlohmann::json{{"hits", std::move(hits)},
+                              {"scan_capped", found.scanCapped},
+                              {"filter_mode", filterModeName(found.mode)}};
     }
 
     nlohmann::json store(const std::string& collection, const nlohmann::json& payload) {

+ 27 - 1
runner/src/host_prelude.js

@@ -206,7 +206,18 @@
         const extra = options.filters === undefined || options.filters === null
                       ? [] : options.filters;
         need(Array.isArray(extra), '.search() filters must be an array of strings');
-        return __hostDb(name, 'search', {
+        // The host answers {hits, scan_capped, filter_mode}; the script gets an
+        // ARRAY, with the two flags as properties on it. A JS array carries
+        // properties without affecting indexing, length, iteration, spread or
+        // JSON.stringify, so a script written before this behaves identically
+        // and one that wants to know reads `result.scan_capped`.
+        //
+        // The flags exist because a truncated search used to be a console
+        // warning only, which reaches neither the function's logic nor a model
+        // downstream of it - and a function's result is routinely given to one.
+        // `scan_capped: false` on filter_mode 'server' is false BY
+        // CONSTRUCTION; on 'walk' it means complete this time.
+        const answer = __hostDb(name, 'search', {
           query_text: options.query_text,
           query_vector: options.query_vector,
           top_k: options.top_k,
@@ -220,6 +231,21 @@
           embedTimeoutMs: options.embedTimeoutMs,
           filters: query.filters.concat(extra)
         });
+        // Tolerate a host that answered the old bare-array shape, so the two
+        // halves can be deployed in either order.
+        if (Array.isArray(answer)) return answer;
+        const hits = answer && Array.isArray(answer.hits) ? answer.hits : [];
+        try {
+          Object.defineProperty(hits, 'scan_capped',
+                                { value: !!(answer && answer.scan_capped), enumerable: false });
+          Object.defineProperty(hits, 'filter_mode',
+                                { value: (answer && answer.filter_mode) || 'none',
+                                  enumerable: false });
+        } catch (e) {
+          // A frozen array would be the only way this fails; the hits matter
+          // more than the flags, so never let attaching them break a search.
+        }
+        return hits;
       },
       store: function (options) {
         need(options !== null && typeof options === 'object', '.store() takes an options object');

+ 52 - 0
runner/tests/host_prelude_test.cpp

@@ -811,3 +811,55 @@ TEST(HostPrelude, TheChainedFilterStillMergesWithAnExplicitFiltersArray) {
     EXPECT_EQ(sent.at(0), "x:eq:1") << sent.dump();
     EXPECT_EQ(sent.at(1), "y:eq:2") << sent.dump();
 }
+
+// --- #60: a truncated search must reach the FUNCTION, not just the console --
+//
+// A console warning reaches neither the function's logic nor a model
+// downstream of it, and a function's result is routinely handed to one. A
+// consumer hit this exact shape: they logged their degraded-search fallback
+// for the operator, and the gap was that the ASSISTANT was never told, so it
+// stated "nothing in memory" with confidence.
+//
+// The return must stay an ARRAY, so the flags ride as properties on it.
+
+TEST(HostPrelude, SearchStillReturnsAnARRAYThatBehavesLikeOne) {
+    // The compatibility guarantee: indexing, length, iteration, spread and
+    // JSON.stringify must all be exactly as before. If any of these changed,
+    // every existing script breaks.
+    const nlohmann::json out = runPrelude(
+        "const r = ctx.collections('c').search({ query_text: 'x' });"
+        "return { isArray: Array.isArray(r), len: r.length,"
+        "         viaIndex: r.length > 0 ? typeof r[0] : 'n/a',"
+        "         viaSpread: [...r].length,"
+        "         viaFor: (function(){ let n = 0; for (const h of r) n++; return n; })(),"
+        "         json: JSON.stringify(r) };");
+    const nlohmann::json& v = out.at("value");
+    EXPECT_EQ(v.at("isArray"), true) << v.dump();
+    EXPECT_EQ(v.at("viaSpread"), v.at("len")) << v.dump();
+    EXPECT_EQ(v.at("viaFor"), v.at("len")) << v.dump();
+    // The flags must NOT appear in JSON.stringify - they are non-enumerable,
+    // so a script that serialises its results sends what it always sent.
+    const std::string json = v.at("json").get<std::string>();
+    EXPECT_EQ(json.find("scan_capped"), std::string::npos) << json;
+    EXPECT_EQ(json.find("filter_mode"), std::string::npos) << json;
+    EXPECT_EQ(json.front(), '[') << json;
+}
+
+TEST(HostPrelude, TheFlagsAreREADABLEOnTheReturnedArray) {
+    const nlohmann::json out = runPrelude(
+        "const r = ctx.collections('c').search({ query_text: 'x' });"
+        "return { capped: r.scan_capped, mode: r.filter_mode,"
+        "         cappedType: typeof r.scan_capped, modeType: typeof r.filter_mode };");
+    const nlohmann::json& v = out.at("value");
+    EXPECT_EQ(v.at("cappedType"), "boolean") << v.dump();
+    EXPECT_EQ(v.at("modeType"), "string") << v.dump();
+}
+
+TEST(HostPrelude, ABareArrayFromAnOlderHostIsStillAccepted) {
+    // The two halves can deploy in either order, so the prelude must tolerate
+    // a host that answers the old shape rather than throwing on it.
+    const nlohmann::json out = runPrelude(
+        "const r = ctx.collections('c').search({ query_text: 'x' });"
+        "return Array.isArray(r);");
+    EXPECT_EQ(out.at("value"), true) << out.dump();
+}

+ 11 - 1
src/handlers/vectors.cpp

@@ -146,9 +146,19 @@ void registerVectorRoutes(ApiServer& s) {
         // absence mean exactly one thing: too old. A consumer found it by
         // measuring an unfiltered search and getting scan_capped=false with
         // scanned undefined.
+        // `filter_mode` exists because `scan_capped: false` means two
+        // different things. "server" is false BY CONSTRUCTION - nothing
+        // truncates, so sweeping a filtered set is sound. "walk" means
+        // complete THIS TIME, and a sweep is not. "none" is an unfiltered
+        // search, which has no cap either. A caller cannot get this from
+        // /api/v1/version, which reports the CLIENT library version while the
+        // path depends on the SERVER - a 2.14 client against a 2.13 server
+        // would read as the new path while running the old capped one. So it
+        // is per-request or it is useless.
         nlohmann::json out = {{"results", arr},
                               {"scan_capped", found.scanCapped},
-                              {"scanned", found.scanned}};
+                              {"scanned", found.scanned},
+                              {"filter_mode", filterModeName(found.mode)}};
         // Conditional on purpose, and the condition is the one a caller needs:
         // whenever `scan_capped` is true this is present, so "if capped, read
         // the cap" is safe and nobody has to hardcode the number.

+ 3 - 0
src/vector_search.cpp

@@ -34,6 +34,7 @@ VectorSearchResult vectorSearch(
     VectorSearchResult out;
     if (filters.empty()) {
         out.hits = client.similaritySearch(coll, query, topK, minScore);
+        out.mode = VectorSearchResult::Mode::NoFilter;
         return out;   // no ranking walk, so nothing to cap
     }
 
@@ -68,6 +69,7 @@ VectorSearchResult vectorSearch(
             // literally true rather than a sentinel.
             out.scanned = 0;
             out.serverFiltered = true;
+            out.mode = VectorSearchResult::Mode::ServerFiltered;
             return out;
         } catch (const smartbotic::database::Client::Error& e) {
             const auto* detail = smartbotic::database::Client::errorDetail(e);
@@ -129,6 +131,7 @@ VectorSearchResult vectorSearch(
         scan = nextScanDepth(scan, topK, results.size());
     }
     out.hits = std::move(results);
+    out.mode = VectorSearchResult::Mode::Walk;
     return out;
 }
 

+ 29 - 0
src/vector_search.hpp

@@ -91,6 +91,23 @@ struct VectorSearchResult {
     /// How deep into the ranking the last pass went. 0 for an unfiltered
     /// search, which does not walk the ranking at all.
     uint32_t scanned = 0;
+    /// Which path produced the answer, for callers rather than for us.
+    ///
+    /// `scanCapped == false` means two different things and the boolean cannot
+    /// carry the difference: on `ServerFiltered` it is false BY CONSTRUCTION,
+    /// since nothing truncates, so a caller may sweep a filtered set; on `Walk`
+    /// it means "complete this time", and a sweep is still unsound. `NoFilter`
+    /// is the third case, where there is no filter to apply and therefore no
+    /// cap either.
+    ///
+    /// A caller CANNOT infer this from `/api/v1/version`: that reports the
+    /// CLIENT library version while the path depends on the SERVER, so a 2.14
+    /// client against a 2.13 server reads as the new path while running the old
+    /// capped one. It is per-request truth or it is nothing, which is why it
+    /// travels on the response.
+    enum class Mode { NoFilter, ServerFiltered, Walk };
+    Mode mode = Mode::NoFilter;
+
     /// True when the answer came from the database's own filtered search
     /// (2.14.0+) rather than from the candidate walk.
     ///
@@ -113,6 +130,18 @@ struct VectorSearchResult {
     bool scanCapped = false;
 };
 
+/// The wire spelling of a search's filter mode. ONE definition, because the
+/// HTTP route and the runner both report it and a second spelling is how the
+/// two drift.
+constexpr const char* filterModeName(VectorSearchResult::Mode m) {
+    switch (m) {
+        case VectorSearchResult::Mode::ServerFiltered: return "server";
+        case VectorSearchResult::Mode::Walk:           return "walk";
+        case VectorSearchResult::Mode::NoFilter:       break;
+    }
+    return "none";
+}
+
 VectorSearchResult vectorSearch(
     smartbotic::database::Client& client, const std::string& qualifiedCollection,
     const std::vector<float>& query, uint32_t topK, float minScore,

+ 40 - 0
tests/test_api_integration.cpp

@@ -3557,3 +3557,43 @@ TEST_F(ApiFixture, TheExportsBase64FieldGetsAnErrorThatDoesNotREADAsDataLoss) {
     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;
 }
+
+TEST_F(ApiFixture, AFilteredSearchREPORTSWhichPathAnsweredIt) {
+    // filter_mode exists because `scan_capped: false` means two different
+    // things: false BY CONSTRUCTION on the server path (a sweep is sound) and
+    // "complete this time" on the walk (it is not). A caller cannot get this
+    // from /api/v1/version, which reports the CLIENT library version while the
+    // path depends on the SERVER.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(),
+                     nlohmann::json{{"name","vmode"},{"kind","vector"},
+                                    {"vector_dimension",4}}.dump(),
+                     "application/json")->status, 201);
+    for (int i = 0; i < 6; ++i)
+        ASSERT_EQ(c.Post((base + "/vmode/vectors").c_str(),
+                         nlohmann::json{{"vector",{1.0 - i * 0.1, 0.1, 0.2, 0.3}},
+                                        {"metadata",{{"dept", i % 2 ? "a" : "b"}}}}.dump(),
+                         "application/json")->status, 201);
+    const std::string search = base + "/vmode/search";
+
+    // Unfiltered: there is no filter and therefore no cap either.
+    auto u = c.Post(search.c_str(),
+                    nlohmann::json{{"query_vector",{1.0,0.1,0.2,0.3}},{"top_k",3},
+                                   {"min_score",-1.0}}.dump(), "application/json");
+    ASSERT_TRUE(u); ASSERT_EQ(u->status, 200) << u->body;
+    EXPECT_EQ(nlohmann::json::parse(u->body).at("filter_mode"), "none") << u->body;
+
+    // Filtered against a 2.14.0 server: the pre-filter path.
+    auto f = c.Post(search.c_str(),
+                    nlohmann::json{{"query_vector",{1.0,0.1,0.2,0.3}},{"top_k",3},
+                                   {"min_score",-1.0},
+                                   {"filters",{"dept:eq:b"}}}.dump(), "application/json");
+    ASSERT_TRUE(f); ASSERT_EQ(f->status, 200) << f->body;
+    const auto j = nlohmann::json::parse(f->body);
+    EXPECT_EQ(j.at("filter_mode"), "server") << j.dump();
+    // And the two agree with each other: "server" must never be reported
+    // alongside a capped answer, since that path cannot cap.
+    EXPECT_FALSE(j.at("scan_capped").get<bool>()) << j.dump();
+    EXPECT_EQ(j.at("scanned"), 0) << j.dump();
+}

Alguns ficheiros não foram mostrados porque muitos ficheiros mudaram neste diff