Selaa lähdekoodia

feat(search): use the database's filtered similaritySearch (2.14.0)

A filtered vector search is now ONE server-side call instead of two to
four. The filters select candidates before ranking, so the answer is the
exact top-K among matching rows rather than a filtered slice of the
unfiltered top-K - there is no walk, no 10000-candidate cap, and nothing
that can be silently truncated.

The database team measured it on 12447 rows at dim 4096: a filter
matching ~430 rows at topK 500 takes 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 and never
omitted, and scanned is 0 because no walk happened. A consumer maps an
absent scan_capped to "this server cannot report truncation, so
completeness is unknown" and renders that to an operator; on this path
that sentence would be false AND permanent, and a warning that always
fires is one people learn to skip.

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 answer
UNFILTERED, so the client throws filters_unsupported instead, which is
the only reason the new path can be tried optimistically. The refusal is
latched per process so an older deployment pays one refused round trip
rather than one per search - one-way on purpose, because the emulation
is correct and merely capped, and it clears on the restart a database
upgrade involves anyway.

The emulation stays for any server older than 2.14.0.

The Depends floor moves to >= 2.14.0 and that is load-bearing. Verified
with nm on both shipped .so files rather than assumed: the 5-argument
symbol exists ONLY in 2.14.0, while 2.13.1 carries just the 4-argument
form. Every 2.x client shares one SONAME, so 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. DB_CLIENT_VERSION moves too, which means --rebuild-base.

Two integration tests, and the first one is written so it CANNOT pass on
the emulation: `scanned` is the discriminator, 0 on the server path and
at least 64 on the walk. Forcing the fallback makes it fail with
scanned: 64, which I checked - otherwise the suite would have passed
identically either way and I would have tested nothing. Both paths
returned identical ids, scores and order on the fixture, which is the
agreement the new path promises.

Also documents two database semantics that are unchanged but easy to
misread: min_score 0.0 drops rows whose cosine is negative, so "fewer
matches than topK returns all of them" means all scoring at or above
min_score; and from 2.14.0 equal scores are ordered by id, lowest first,
which applies to the unfiltered search too and is observable only on
duplicate vectors.

1242/1242 green against a real 2.14.0 server.
fszontagh 1 kuukausi sitten
vanhempi
sitoutus
2882f6d8c9

+ 8 - 2
CLAUDE.md

@@ -45,7 +45,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 ## Conventions
 
 - C++20, `nlohmann/json`, `spdlog`, cpp-httplib (FetchContent, OpenSSL on). Handlers `throw svapi::ApiError`; a global exception handler maps to `{error:{code,message}}` + HTTP status (`errors.hpp`: 400/401/403/404/422/503/500).
-- Filters: `field:op:value` (`op` ∈ eq/ne/gt/gte/lt/lte/in/contains/exists/regex/search). Used by `/documents` (`?filter=`, repeatable) **and** vector `/search` (`filters` body array) - both parse with `parseFilter()` and are evaluated by the DB, so semantics never diverge. `contains` is array membership; `search` is the substring op. Vector search intersects the DB's filter result with the similarity ranking (scores stay identical to an unfiltered query), scanning at most 10000 candidates.
+- Filters: `field:op:value` (`op` ∈ eq/ne/gt/gte/lt/lte/in/contains/exists/regex/search). Used by `/documents` (`?filter=`, repeatable) **and** vector `/search` (`filters` body array) - both parse with `parseFilter()` and are evaluated by the DB, so semantics never diverge. `contains` is array membership. **`search` IGNORES THE FIELD NAME**: it is a case-insensitive substring over the WHOLE document - the id, the keys, and every string and number in it - so `name:search:foo` matches a document with "foo" anywhere, not in `name`. Measured on prod with controls: `nosuchfield:search:webber` returns rows while `nosuchfield:eq:webber` returns none, and `departmentKey:search:szamla` returns rows while `departmentKey:eq:szamla` returns none. The field is syntactically required and semantically discarded, which this note previously described as "the substring op" in a `field:op:value` sentence - implying a scope it never had. **For a field-scoped substring use `regex` on that field.** This matters because a `search` filter written as a scoping or tenancy boundary admits rows the author believed it excluded, which is the same failure as a dropped filter and in the same direction. Vector search intersects the DB's filter result with the similarity ranking (scores stay identical to an unfiltered query), scanning at most 10000 candidates.
 - **Embedding config precedence:** collection `embedding_model` pin → project override → global default; endpoint + API key are the project override when set, else global. Resolved by the pure `resolveEmbedding()` (`project_settings.hpp`) - unit-test precedence there, not through the handlers.
 - **Every outbound request to an external provider goes through `applyOutboundDefaults()`** (`outbound_http.hpp`): `User-Agent: smartbotic-vectorapi/<version>` and nothing else, TLS verification on, redirects off. Never let cpp-httplib's default UA reach a provider.
 - **A PERMISSIVE TEST ASSERTION'S STRENGTH DEPENDS ON THE SERVER'S STRICTNESS, so tightening a contract can silently promote a sloppy test elsewhere into a blind spot.** A consumer found this while checking whether the `unknown_option` refusal would break them: a test asserting their outgoing body with `expect.objectContaining({...})` tolerated extra keys by construction, so it could only ever fail in the direction that was already safe - add a stray key and the test stays green while production starts refusing every search with 422. They tightened it to an exact match. The lesson for asking consumers about a breaking change: the question is not only "do you send an extra key" but **"would your tests notice if you started"**.
@@ -146,7 +146,13 @@ 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 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.
+  - **`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".
+- **Two database semantics worth knowing, unchanged by 2.14.0 but easy to misread.** `minScore 0.0` DROPS rows whose cosine is negative, so "fewer matches than topK returns all of them" means all that score at or above `minScore` - pass a negative `minScore` to see genuinely every match. And from 2.14.0 rows with EQUAL scores are ordered by id, lower first, including when a tie straddles the cut; that applies to the unfiltered search too and was previously unspecified, so it is observable only on duplicate vectors.
+- **The filtered walk's EMULATION remains, for any server older than 2.14.0, and its cost is ROUND TRIPS.** 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 - 3
api/llms.txt

@@ -100,8 +100,8 @@ Supported ops: `eq`, `ne`, `lt`, `lte`, `gt`, `gte`, `in`, `contains`, `exists`,
 
 - `in` - value is a JSON array, e.g. `colour:in:["red","yellow"]`.
 - `contains` - **array membership**, not substring: it matches when the field is an array holding the value. `colour:contains:yellow` does NOT match the string `"yellow"`.
-- `search` - substring match on a string field, e.g. `colour:search:ell` matches `"yellow"`.
-- `regex` - regular-expression match.
+- `search` - **IGNORES THE FIELD NAME.** A case-insensitive substring over the WHOLE document: its id, its keys, and every string and number in it. So `colour:search:ell` matches `"yellow"` in `colour` AND a document whose `note` says "excellent", AND one whose id contains `ell`. The field is syntactically required and semantically discarded - `nosuchfield:search:ell` matches exactly what `colour:search:ell` does. **For a substring within ONE field, use `regex` on that field.** Worth care if a `search` filter is doing scoping work: it admits rows you may believe it excludes, and in the same direction as a filter that was dropped entirely.
+- `regex` - regular-expression match, and the field IS honoured. This is the field-scoped substring: `colour:regex:ell`.
 - `exists` - `field:exists:true` / `field:exists:false`.
 
 The value is parsed as JSON when it parses (numbers, booleans, arrays), otherwise it is taken as a string. Everything after the second `:` is the value, so a value may itself contain `:`. A malformed spec or unknown operator is rejected with **400** `bad_filter`.
@@ -137,7 +137,7 @@ Relation names are per-project and **unqualified**: requests and responses alway
 Requires a `kind=vector` collection. Vectors are stored with cosine-similarity indexing.
 
 - `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): a filtered search walks the ranking only `scan_cap` deep, so on a collection larger than that a filter whose matches lie deeper returns FEWER hits than match. `scan_capped: false` means the answer is complete - including the ordinary case of a filter matching fewer rows than `top_k`. **Check it before treating a filtered result set as exhaustive.** Inside a function the return stays an array and the warning goes to the run's console instead.
+- `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). **Against database 2.14.0 or newer a filtered search is a single server-side call: the filter selects candidates BEFORE ranking, so the answer is the exact top-K among matching rows, there is no scan cap, `scan_capped` is always `false` and `scanned` is `0`** - and it is FASTER than the same search unfiltered, because only matching rows are scored. Against an older server the service falls back to walking the ranking `scan_cap` deep, and there a filter whose matches lie deeper than the walk returns FEWER hits than match, which is what `scan_capped: true` reports. `scan_capped: false` always means the answer is complete; on 2.14.0+ it is complete by construction, on the fallback it means complete this time. **On the fallback, check it before treating a filtered result set as exhaustive.** Note `min_score` defaults to 0, which drops rows whose cosine is NEGATIVE - pass a negative `min_score` to see every match. Rows with equal scores are ordered by id, lowest first. Inside a function the return stays an array and a truncation warning goes to the run's console instead.
 
   Filtering is evaluated by the database, then intersected with the similarity ranking, so scores are identical with and without a filter and `min_score` means the same thing either way. The scan is bounded at 10000 candidates: within a collection of that size a filtered search returns exactly the true top-k, and beyond it a filter matching only very low-ranked vectors may return fewer.
 

+ 1 - 1
api/openapi.json

@@ -2627,7 +2627,7 @@
                     "items": {
                       "type": "string"
                     },
-                    "description": "Metadata filters in field:op:value grammar, ANDed (e.g. src:eq:n8n). Same operators as the documents endpoint (eq, ne, lt, lte, gt, gte, in, contains, exists, regex, search) and evaluated by the database, so a document scores the same with or without a filter. Metadata is stored at the document top level: metadata {\"colour\":\"red\"} is filtered as colour:eq:red. Note that contains is array membership - use search for substrings. A malformed spec or unknown operator returns 400 bad_filter. The filtered scan is bounded at 10000 candidates."
+                    "description": "Metadata filters in field:op:value grammar, ANDed (e.g. src:eq:n8n). Same operators as the documents endpoint (eq, ne, lt, lte, gt, gte, in, contains, exists, regex, search) and evaluated by the database, so a document scores the same with or without a filter. Metadata is stored at the document top level: metadata {\"colour\":\"red\"} is filtered as colour:eq:red. Note that contains is array membership. `search` IGNORES the field name - it is a case-insensitive substring over the whole document (id, keys and every string and number), so use `regex` on a field for a substring within that field. A malformed spec or unknown operator returns 400 bad_filter. The filtered scan is bounded at 10000 candidates."
                   }
                 }
               }

+ 1 - 1
packaging/Dockerfile.base

@@ -28,7 +28,7 @@ RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
 # only segfaults on the next service restart. Keep this equal to the client
 # version installed on the deploy target; when the target's DB moves, bump this
 # and ship both together.
-ARG DB_CLIENT_VERSION=2.13.1-1
+ARG DB_CLIENT_VERSION=2.14.0-1
 
 # Publishing a new client re-indexes the apt pool, so the pinned version is
 # often no longer installable from the repo. build.sh copies the matching .debs

+ 1 - 1
packaging/build.sh

@@ -21,7 +21,7 @@ BASE_IMAGE_NAME="smartbotic-vectorapi-build-base:debian13"
 # Client version the server deb is compiled against. Must equal the version
 # installed on the deploy target: every 2.x client shares one SONAME, so a
 # mismatch installs cleanly and only segfaults on the next service restart.
-DB_CLIENT_VERSION="${DB_CLIENT_VERSION:-2.13.1-1}"
+DB_CLIENT_VERSION="${DB_CLIENT_VERSION:-2.14.0-1}"
 BUILD_JOBS="${BUILD_JOBS:-$(nproc)}"
 DEB_REPO_DIR="${DEB_REPO_DIR:-/data/dev/smartbotics/smartbotics-deb-repo}"
 

+ 1 - 1
packaging/deb/templates/control.runner

@@ -12,7 +12,7 @@ Description: Smartbotic VectorAPI - server-side function runner
 Homepage: https://smartbotics.ai
 Section: contrib/utils
 Priority: optional
-Depends: libsmartbotic-db-client (>= 2.12.0), libssl3t64, libsystemd0, libspdlog1.15, tzdata, ca-certificates, libidn2-0
+Depends: libsmartbotic-db-client (>= 2.14.0), libssl3t64, libsystemd0, libspdlog1.15, tzdata, ca-certificates, libidn2-0
 Recommends: smartbotic-vectorapi (= {{VERSION}})
 Breaks: smartbotic-vectorapi (<< {{UPSTREAM_VERSION}})
 Installed-Size: {{INSTALLED_SIZE}}

+ 1 - 1
packaging/deb/templates/control.server

@@ -10,7 +10,7 @@ Description: Smartbotic VectorAPI — REST API for RAG vectors and JSON
 Homepage: https://smartbotics.ai
 Section: contrib/utils
 Priority: optional
-Depends: libsmartbotic-db-client (>= 2.12.0), libssl3t64, libsystemd0, libspdlog1.15, tzdata
+Depends: libsmartbotic-db-client (>= 2.14.0), libssl3t64, libsystemd0, libspdlog1.15, tzdata
 Recommends: smartbotic-vectorapi-webui (= {{VERSION}})
 Breaks: smartbotic-vectorapi-runner (<< {{UPSTREAM_VERSION}})
 Installed-Size: {{INSTALLED_SIZE}}

+ 72 - 0
src/vector_search.cpp

@@ -1,8 +1,31 @@
 #include "vector_search.hpp"
 #include <algorithm>
+#include <atomic>
 #include <unordered_set>
 
 namespace svapi {
+namespace {
+
+using Code = smartbotic::database::Client::ErrorCode;
+
+/// Whether this process has learned that the database predates 2.14.0.
+///
+/// A latch rather than a per-call probe: without it, a deployment on an older
+/// database pays one refused round trip for every filtered search. One-way on
+/// purpose - the emulation is correct and only capped, so remaining on it after
+/// a database upgrade is the safe direction, and it clears on the next restart,
+/// which such an upgrade involves anyway because the two ship together.
+std::atomic<bool> gServerFilteringUnsupported{false};
+
+bool serverFilteringUnsupported() {
+    return gServerFilteringUnsupported.load(std::memory_order_relaxed);
+}
+
+void markServerFilteringUnsupported() {
+    gServerFilteringUnsupported.store(true, std::memory_order_relaxed);
+}
+
+}  // namespace
 
 VectorSearchResult vectorSearch(
     smartbotic::database::Client& client, const std::string& coll,
@@ -14,6 +37,55 @@ VectorSearchResult vectorSearch(
         return out;   // no ranking walk, so nothing to cap
     }
 
+    // --- 2.14.0: ONE server-side filtered search, 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. No walk, no cap, and therefore no truncation to report. 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 on prod for the same shape.
+    //
+    // Against a pre-2.14.0 server the client throws rather than returning the
+    // unfiltered rows that server would have answered with - which is the only
+    // reason this can be tried optimistically at all. Note the detection is
+    // the SERVER's `filters_applied` response field, not a version number we
+    // have to read correctly, so there is no mixed client/server state in
+    // which this silently does the wrong thing.
+    if (!serverFilteringUnsupported()) {
+        try {
+            out.hits = client.similaritySearch(coll, query, topK, minScore, filters);
+            // EXPLICITLY false, never omitted. A consumer maps an absent
+            // `scan_capped` to "this server cannot report truncation, so
+            // completeness is unknown" and renders that to an operator - which
+            // on this path would be both false and permanent, and a warning
+            // that always fires is one people learn to skip. `false` says "I
+            // looked, there was no truncation"; absent says "I cannot speak to
+            // this". Only the first is true here.
+            out.scanCapped = false;
+            // 0 because no candidate walk HAPPENED, which on this path is
+            // literally true rather than a sentinel.
+            out.scanned = 0;
+            out.serverFiltered = true;
+            return out;
+        } catch (const smartbotic::database::Client::Error& e) {
+            const auto* detail = smartbotic::database::Client::errorDetail(e);
+            const bool unsupported = e.code() == Code::FailedPrecondition && detail != nullptr &&
+                                     detail->reason == "filters_unsupported";
+            if (!unsupported) throw;   // a real failure is NOT a reason to emulate
+            // Latched, so a deployment on an older database pays one refused
+            // round trip per PROCESS rather than one per search. One-way on
+            // purpose: the emulation is correct, only capped, so being stuck
+            // on it after a database upgrade is the safe direction - and it
+            // clears on the next restart, which a database upgrade involves
+            // anyway since the two ship together.
+            markServerFilteringUnsupported();
+        }
+    }
+
+    // --- the emulation, for any server older than 2.14.0 -------------------
+
     smartbotic::database::Client::QueryOptions opts;
     opts.filters = filters;
     opts.limit   = kVectorFilterScanCap;

+ 15 - 0
src/vector_search.hpp

@@ -91,6 +91,21 @@ 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;
+    /// True when the answer came from the database's own filtered search
+    /// (2.14.0+) rather than from the candidate walk.
+    ///
+    /// Worth distinguishing, because `scanCapped == false` means two different
+    /// things: on this path it is false BY CONSTRUCTION, since there is no cap
+    /// to reach, so a caller may safely sweep a filtered set; on the walk it
+    /// means "complete this time", and a sweep is still unsound. The boolean
+    /// alone cannot carry that, and a consumer cannot infer it from
+    /// `/api/v1/version` either - that reports the CLIENT library version,
+    /// while the path depends on the SERVER, so a 2.14 client against a 2.13
+    /// server would read as the new path while running the old capped one.
+    /// Whether to expose this to callers is a separate decision; it is
+    /// recorded here so the distinction is not lost.
+    bool serverFiltered = false;
+
     /// True when the walk stopped at the cap while STILL short of `topK` and
     /// the ranking was not exhausted - i.e. more matches may exist below.
     /// False whenever the answer is known to be complete, which includes the

+ 80 - 0
tests/test_api_integration.cpp

@@ -3387,3 +3387,83 @@ TEST_F(ApiFixture, IncrementNeedsTheUpdateGrant) {
     EXPECT_EQ(nlohmann::json::parse(allowed->body)["values"]["calls"], 2);
     db_->client().remove(keysColl_, writer.id);
 }
+
+// --- the 2.14.0 server-side filtered search ---------------------------------
+
+TEST_F(ApiFixture, AFilteredSearchUSESTheServerSidePathAndIsExact) {
+    // Proves the new path actually RAN rather than inferring it from the
+    // server's version. `scanned` is the discriminator: the candidate walk
+    // always reports at least its first pass (>= 64), while the server-side
+    // filtered search does no walk at all and reports 0. Without this the
+    // suite would pass identically on the emulation and I would have tested
+    // nothing about the new code.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(),
+                     nlohmann::json{{"name","vfilt"},{"kind","vector"},
+                                    {"vector_dimension",4}}.dump(),
+                     "application/json")->status, 201);
+    const std::string vecs = base + "/vfilt/vectors";
+    // Distinct vectors so the ranking is a strict order, and a filter that
+    // selects a minority - the shape where the emulation had to walk.
+    for (int i = 0; i < 12; ++i)
+        ASSERT_EQ(c.Post(vecs.c_str(),
+                         nlohmann::json{{"vector",{1.0 - i * 0.05, 0.1, 0.2, 0.3}},
+                                        {"metadata",{{"dept", i % 4 == 0 ? "webber" : "other"},
+                                                     {"n", i}}}}.dump(),
+                         "application/json")->status, 201);
+
+    auto r = c.Post((base + "/vfilt/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:webber"}}}.dump(), "application/json");
+    ASSERT_TRUE(r); ASSERT_EQ(r->status, 200) << r->body;
+    const auto j = nlohmann::json::parse(r->body);
+
+    // 0 = no walk happened, which on the server-side path is literally true
+    // rather than a sentinel. A non-zero value here means the emulation ran.
+    EXPECT_EQ(j.at("scanned"), 0) << "the candidate walk ran, so the 2.14.0 path did NOT: "
+                                  << j.dump();
+    // EXPLICITLY present and false, never omitted: a consumer renders an
+    // absent value as "completeness unknown", which would be false here.
+    ASSERT_TRUE(j.contains("scan_capped")) << j.dump();
+    EXPECT_FALSE(j.at("scan_capped").get<bool>()) << j.dump();
+
+    // And the answer is right: every hit matches the filter, and they are the
+    // three highest-scoring matching rows in descending order.
+    const auto& hits = j.at("results");
+    ASSERT_EQ(hits.size(), 3u) << j.dump();
+    double previous = 2.0;
+    for (const auto& h : hits) {
+        EXPECT_EQ(h.at("data").at("dept"), "webber") << "a non-matching row was returned: "
+                                                     << h.dump();
+        const double score = h.at("score").get<double>();
+        EXPECT_LE(score, previous) << "not in descending score order: " << hits.dump();
+        previous = score;
+    }
+    // The matching rows are n = 0, 4 and 8, and the query favours the lowest n.
+    EXPECT_EQ(hits.at(0).at("data").at("n"), 0) << hits.dump();
+}
+
+TEST_F(ApiFixture, AFilterMatchingNothingIsAnEmptyResultNotAnError) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(),
+                     nlohmann::json{{"name","vnone"},{"kind","vector"},
+                                    {"vector_dimension",4}}.dump(),
+                     "application/json")->status, 201);
+    ASSERT_EQ(c.Post((base + "/vnone/vectors").c_str(),
+                     nlohmann::json{{"vector",{1.0,0.0,0.0,0.0}},
+                                    {"metadata",{{"dept","other"}}}}.dump(),
+                     "application/json")->status, 201);
+    auto r = c.Post((base + "/vnone/search").c_str(),
+                    nlohmann::json{{"query_vector",{1.0,0.0,0.0,0.0}},
+                                   {"top_k",5},
+                                   {"filters",{"dept:eq:nosuchvalue"}}}.dump(),
+                    "application/json");
+    ASSERT_TRUE(r); ASSERT_EQ(r->status, 200) << r->body;
+    const auto j = nlohmann::json::parse(r->body);
+    EXPECT_TRUE(j.at("results").empty()) << j.dump();
+    EXPECT_FALSE(j.at("scan_capped").get<bool>()) << j.dump();
+}