Browse Source

perf(search): widen the filtered walk by what it measured, not by four

The filtered walk re-runs the whole similarity search with a growing
limit, because the database client has no filtered similaritySearch. The
round trips are the cost.

Measured on prod with an explicit query_vector, so no embedding is in
the path, on 12447 rows at dim 4096:

    unfiltered, top_k 500        0.26 s   (one search)
    filtered,   top_k 5          0.41 s   (64, 256)
    filtered,   top_k 100        1.74 s   (400, 1600, 6400)
    filtered,   top_k 500        3.21 s   (2000, 8000, 10000)
    filter matching nothing      0.05 s   (no walk)

Time tracks rows fetched almost linearly at about 0.3 ms per candidate,
so neither the vector arithmetic nor the 1 MB response is the cost.

Two changes, both in pure functions with tests:

- firstScanDepth(): when the filter matches FEWER rows than topK the
  early exit can never fire, so every widening step before the cap is
  certain waste - start at the cap and spend one round trip.
- nextScanDepth(): widen by the hit rate the previous pass actually
  measured (scan * topK / matches, plus a quarter headroom) instead of
  quadrupling blindly.

`scan * 4` remains the FLOOR, which is what makes a mis-estimate safe:
this can only skip steps, never take smaller ones, so progress stays
guaranteed and nothing can get slower than the blind widening. The
RESULT is identical in every case, because each pass is a prefix of the
same ranking and the first topK matches within it are the same rows
whatever depth the walk stopped at.

Extracted and tested because vector_search.cpp had NO test at all, so
the previous version of this change altered the walk with zero coverage.
8 cases, including the x4 floor and progress guarantees over a matrix of
inputs, zero matches not dividing by zero, and scan * topK * 5 computed
in 64 bits - a 32-bit wrap there would produce a SMALLER next scan and
break the progress guarantee silently.

Corrects something I asserted earlier today and had wrong: I claimed
`departmentKey:eq:webber` matched ~426 rows against a top_k of 500, so
the walk could never terminate early and both smaller searches were pure
waste. The index says 553. So the early exit IS reachable for that
query, the consumer's 424 was a capped result and my 500 was a complete
one. The optimisation stands, but not for the reason I first gave.

The real fix is a server-side filtered similarity search, requested and
designed for database 2.14.0. This emulation has to keep working anyway
as the path for any older server.

1224/1224 green. The latency win is NOT yet measured - it is arithmetic
plus the round-trip timings above, and will be measured on prod at
deploy.
fszontagh 1 tháng trước cách đây
mục cha
commit
8b169108b1
5 tập tin đã thay đổi với 147 bổ sung và 2 xóa
  1. 1 0
      CLAUDE.md
  2. 3 2
      src/vector_search.cpp
  3. 50 0
      src/vector_search.hpp
  4. 5 0
      tests/CMakeLists.txt
  5. 88 0
      tests/test_vector_scan.cpp

+ 1 - 0
CLAUDE.md

@@ -141,6 +141,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **A REPRODUCIBLE vector-search baseline needs an explicit `query_vector`. Pinning `query_text` is NOT enough.** `query_text` is embedded server-side through the external provider on *every* call - there is no query-embedding cache (`emb.embed(cfg.model, text)` in `handlers/vectors.cpp`), so the same text can yield a different vector on a different day and every score and row count moves with it. Measured by a consumer across one deploy over a byte-identical collection (12447 rows unchanged): an unfiltered top score went 0.7221 to 0.7175 and a filtered count 424 to 426, while five consecutive calls agreed to six decimals - so it is drift in text→vector, not per-call noise. The isolating test: a fixed explicit `query_vector` returned bit-identical results three times, which proves the RANKING is deterministic given a vector. **So nothing in a release has to change for such a baseline to move, and it is therefore not evidence about the release either way.** Corollary worth stating because it bit us: `scan_capped` is query-dependent too and so is also a measurement, not a property of the collection - it is set only when the walk hit the cap *while still short of `top_k`*, so a query that fills `top_k` reports false where a query that falls short reports true. Read all three of the useful assertions (`scan_capped`/`scanned`/the nested error envelope) as "this query, this filter", never as facts about the data.
 - **A CACHE WOULD MAKE SEARCH LATENCY BIMODAL, so do not derive a timeout from a post-cache p50.** If query embeddings are ever cached, the same endpoint answers in ~3 s or ~12-15 s depending on state nothing outside can see, and a timeout or retry budget tuned against the hit path will fire on every miss. Same family as the startup loop that was bounded by an attempt COUNT: a budget encoding a duration as a count carries a hidden assumption about per-item cost. Note also that **caching would NOT make a search reproducible** - per-process plus a TTL means a restart or the TTL boundary clears it, so results would be stable across an afternoon and silently not across a deploy, which is stable long enough to be trusted and not long enough to be true. An explicit `query_vector` stays the only reproducible baseline.
 - **The embedding call IS essentially the whole vector-search latency.** Measured on prod with the ranking doing identical work both ways: a fixed `query_vector` search returned in 3.4 s against 12-15 s for the same filter and `top_k` via `query_text`. There is no query-embedding cache, so every repeated search pays the provider again.
+- **The filtered walk's cost is ROUND TRIPS, and the widening is now measured rather than blind.** The client has no filtered `similaritySearch`, so a filtered search fetches the filter's ids with `find()` and then re-runs the WHOLE similarity search with a growing limit, intersecting in our process. Measured on prod with an explicit `query_vector` (no embedding in the path), on 12447 rows at dim 4096: unfiltered `top_k` 500 is **0.26 s**, filtered `top_k` 500 is **3.21 s** having issued three searches (2000, 8000, 10000), and a filter matching nothing is 0.05 s. Time tracks rows fetched almost linearly, ~0.3 ms per candidate - neither the vector arithmetic nor the 1 MB response is the cost. `firstScanDepth()`/`nextScanDepth()` (`vector_search.hpp`, pure, 8 tests) therefore go straight to the cap when the filter matches fewer rows than `topK` (the early exit can never fire, so every step before the cap is certain waste) and otherwise widen by the hit rate the previous pass actually measured. **`scan * 4` stays the FLOOR**, so a mis-estimate can only skip steps and never shrink one - progress stays guaranteed and nothing can get slower. The RESULT is unchanged in every case: each pass is a prefix of the same ranking, so the first `topK` matches within it are the same rows whatever depth the walk stopped at. The real fix is a server-side filtered similarity search, requested and designed for database 2.14.0; this emulation must keep working regardless, as the path for any older server.
 - **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.

+ 3 - 2
src/vector_search.cpp

@@ -31,7 +31,7 @@ VectorSearchResult vectorSearch(
     // the ranking is exhausted. Because the scan is in descending score order,
     // stopping as soon as topK matches are collected still yields the true
     // topK: anything unseen scores lower than everything already kept.
-    uint32_t scan = std::max<uint32_t>(topK * 4, 64);
+    uint32_t scan = firstScanDepth(topK, allowed.size());
     while (true) {
         const std::vector<smartbotic::database::Client::SimilarityResult> page =
             client.similaritySearch(coll, query, scan, minScore);
@@ -53,7 +53,8 @@ VectorSearchResult vectorSearch(
             out.scanCapped = true;
             break;
         }
-        scan = std::min(scan * 4, kVectorFilterScanCap);
+        // The decision itself is pure and tested in vector_search.hpp.
+        scan = nextScanDepth(scan, topK, results.size());
     }
     out.hits = std::move(results);
     return out;

+ 50 - 0
src/vector_search.hpp

@@ -1,6 +1,7 @@
 #pragma once
 #include "db_gateway.hpp"
 #include <smartbotic/database/client.hpp>
+#include <cstddef>
 #include <string>
 #include <vector>
 
@@ -11,6 +12,55 @@ namespace svapi {
 /// returns fewer than top_k rather than walking the whole collection.
 constexpr uint32_t kVectorFilterScanCap = 10000;
 
+/// The depth of the FIRST pass of a filtered walk.
+///
+/// `allowedCount` is how many rows the filter matched. When that is fewer than
+/// `topK` the early exit can never fire, so every widening step before the cap
+/// is certain waste and the first pass goes straight to the deepest scan
+/// allowed. Strictly `<`: with exactly `topK` matches the exit is still
+/// reachable, so that keeps the ordinary start.
+constexpr uint32_t firstScanDepth(uint32_t topK, std::size_t allowedCount,
+                                  uint32_t cap = kVectorFilterScanCap) {
+    if (allowedCount < topK) return cap;
+    const uint32_t start = topK > (cap / 4) ? cap : topK * 4;
+    return start < 64 ? 64 : start;
+}
+
+/// The depth of the NEXT pass, given what this one measured.
+///
+/// Widen by what was actually observed rather than by a blind factor: having
+/// seen `matches` of `scan` ranked rows pass the filter, the depth needed for
+/// `topK` matches is about `scan * topK / matches`. Jumping there costs one
+/// round trip where quadrupling costs several, and the round trips ARE the
+/// cost - measured on prod, a filtered `topK` 500 issued three similarity
+/// searches (2000, 8000, 10000) and took 3.21 s against 0.26 s for the same
+/// query unfiltered, with the time tracking rows fetched almost linearly.
+///
+/// `scan * 4` is the FLOOR, so this can only skip steps and never take smaller
+/// ones. That guarantees progress and means a mis-estimate can never be slower
+/// than the blind widening it replaces: overshooting costs rows that were not
+/// needed, undershooting simply widens again. The RESULT is unaffected either
+/// way, because every pass is a prefix of the same ranking and the first
+/// `topK` matches within it are the same rows whatever depth the walk stopped
+/// at.
+///
+/// A quarter of headroom on the estimate, because it assumes matches are
+/// spread evenly through the ranking while a filter correlated with the query
+/// clusters them near the top.
+constexpr uint32_t nextScanDepth(uint32_t scan, uint32_t topK, std::size_t matches,
+                                 uint32_t cap = kVectorFilterScanCap) {
+    const uint64_t floorNext = static_cast<uint64_t>(scan) * 4;
+    uint64_t next = floorNext;
+    if (matches > 0) {
+        // scan * topK / matches * 1.25, in integers: (scan * topK * 5) / (matches * 4)
+        const uint64_t needed = (static_cast<uint64_t>(scan) * topK * 5) /
+                                (static_cast<uint64_t>(matches) * 4);
+        if (needed > next) next = needed;
+    }
+    if (next > cap) next = cap;
+    return static_cast<uint32_t>(next);
+}
+
 /// Vector similarity search with optional database-evaluated filters.
 ///
 /// ONE implementation on purpose. This is reached from the HTTP route

+ 5 - 0
tests/CMakeLists.txt

@@ -253,6 +253,11 @@ target_include_directories(test_header_fields PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_header_fields PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_header_fields)
 
+add_executable(test_vector_scan test_vector_scan.cpp)
+target_include_directories(test_vector_scan PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_vector_scan PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_vector_scan)
+
 add_executable(test_imap_reader test_imap_reader.cpp)
 target_include_directories(test_imap_reader PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_imap_reader PRIVATE GTest::gtest_main)

+ 88 - 0
tests/test_vector_scan.cpp

@@ -0,0 +1,88 @@
+#include <gtest/gtest.h>
+
+#include "vector_search.hpp"
+
+using svapi::firstScanDepth;
+using svapi::kVectorFilterScanCap;
+using svapi::nextScanDepth;
+
+// The filtered walk re-runs the whole similarity search with a growing limit,
+// because the database client has no filtered similarity search. The round
+// trips ARE the cost: measured on prod, a filtered top_k 500 issued three
+// searches (2000, 8000, 10000) at 3.21 s against 0.26 s for the same query
+// unfiltered. These pin the depth decisions so the emulation can be tuned
+// without a database and a 12000-row collection.
+
+TEST(VectorScan, TheFirstPassStartsAtFourTimesTopKWithAFloorOf64) {
+    EXPECT_EQ(firstScanDepth(500, 100000), 2000u);
+    EXPECT_EQ(firstScanDepth(100, 100000), 400u);
+    // The floor matters: 4 x 5 would be a pointlessly small round trip.
+    EXPECT_EQ(firstScanDepth(5, 100000), 64u);
+    EXPECT_EQ(firstScanDepth(1, 100000), 64u);
+}
+
+TEST(VectorScan, AFilterMatchingFEWERRowsThanTopKGoesStraightToTheCap) {
+    // The early exit needs topK matches, so with fewer than topK matching rows
+    // it can never fire and every step before the cap is certain waste.
+    EXPECT_EQ(firstScanDepth(500, 300), kVectorFilterScanCap);
+    EXPECT_EQ(firstScanDepth(500, 0), kVectorFilterScanCap);
+    // Strictly fewer. With EXACTLY topK matches the exit is still reachable,
+    // so that case keeps the ordinary start rather than paying for the cap.
+    EXPECT_EQ(firstScanDepth(500, 500), 2000u);
+    EXPECT_EQ(firstScanDepth(500, 553), 2000u);
+}
+
+TEST(VectorScan, TheFirstPassNeverExceedsTheCap) {
+    // topK x 4 would overshoot for a large topK; the cap is the ceiling.
+    EXPECT_LE(firstScanDepth(5000, 100000), kVectorFilterScanCap);
+    EXPECT_LE(firstScanDepth(1000000, 100000), kVectorFilterScanCap);
+}
+
+TEST(VectorScan, WideningUsesTheOBSERVEDHitRateRatherThanABlindFactor) {
+    // The prod shape: 553 matching rows of 12447, so a scan of 2000 finds
+    // about 89. To reach 500 matches needs roughly 2000 x 500 / 89 = 11200,
+    // which is past the cap - so ONE jump instead of 2000 -> 8000 -> 10000.
+    EXPECT_EQ(nextScanDepth(2000, 500, 89), kVectorFilterScanCap);
+    // A denser filter needs less: 400 matches in 2000 means a rate of 20%, so
+    // 500 matches needs about 2500, plus the 25% headroom = 3125. But the
+    // x4 floor is 8000, which is larger, so the floor wins.
+    EXPECT_EQ(nextScanDepth(2000, 500, 400), 8000u);
+}
+
+TEST(VectorScan, TheFourTimesStepIsAFLOORSoThisCanOnlySKIPStepsNeverShrink) {
+    // The guarantee that makes a mis-estimate safe: whatever the estimate
+    // says, the next pass is never smaller than the old blind widening would
+    // have made it, so progress is certain and nothing gets slower.
+    for (uint32_t scan : {64u, 256u, 400u, 1000u, 2000u}) {
+        for (std::size_t m : {std::size_t(1), std::size_t(10), std::size_t(1000)}) {
+            const uint32_t next = nextScanDepth(scan, 500, m);
+            EXPECT_GE(next, std::min(scan * 4, kVectorFilterScanCap))
+                << "scan=" << scan << " matches=" << m;
+            EXPECT_GT(next, scan) << "must make progress: scan=" << scan;
+        }
+    }
+}
+
+TEST(VectorScan, ZeroMatchesFallsBackToTheFloorRatherThanDividingByZero) {
+    // No matches in this pass says nothing about the rate, so there is nothing
+    // to estimate from - and it must not be an arithmetic fault.
+    EXPECT_EQ(nextScanDepth(64, 500, 0), 256u);
+    EXPECT_EQ(nextScanDepth(2000, 500, 0), 8000u);
+}
+
+TEST(VectorScan, NothingEverExceedsTheCap) {
+    // The cap is the whole reason the walk is bounded; an estimate must not be
+    // able to step over it.
+    EXPECT_EQ(nextScanDepth(9999, 500, 1), kVectorFilterScanCap);
+    EXPECT_EQ(nextScanDepth(5000, 500, 1), kVectorFilterScanCap);
+    EXPECT_LE(nextScanDepth(2500, 500, 1), kVectorFilterScanCap);
+}
+
+TEST(VectorScan, ALargeScanTimesTopKDoesNotOVERFLOW) {
+    // scan * topK * 5 is computed in 64 bits precisely because 32 would wrap:
+    // 10000 * 500 * 5 is 25 million, fine, but a caller-supplied topK is not
+    // bounded here and a wrap would produce a SMALLER next scan, which would
+    // break the progress guarantee silently.
+    EXPECT_LE(nextScanDepth(kVectorFilterScanCap, 4000000000u, 1), kVectorFilterScanCap);
+    EXPECT_GT(nextScanDepth(1000, 4000000000u, 1), 1000u);
+}