Bladeren bron

feat: 2.14.0 - filtered similaritySearch, exact top-K among matching rows

similaritySearch(collection, vec, topK, minScore, filters): the filters
select candidates BEFORE ranking (find()'s grammar, planner and evaluator,
resolved in the same LMDB read transaction as the vectors), so the answer is
the true top-K among matching rows with scores bit-identical to an
unfiltered search and no candidate cap. Requested by smartbotic-vectorapi,
whose emulation took 3.2 s and could return a short answer.

- Ties ordered by id (lower first), filtered and unfiltered alike.
- A pre-2.14.0 server would ignore the filters and answer unfiltered: the
  response now says filters_applied and the client throws
  FailedPrecondition, reason filters_unsupported, instead.
- SimilaritySearch now applies the row predicate and column masks (and
  refuses filters on masked columns) like Find; before, it gated the
  collection and returned every row and column.

Tests: test_filtered_similarity (417, oracle = unfiltered full ranking
restricted to find()'s ids), test_policy_enforcement +6. Reverted alone:
post-filter 120 fail, no tie-break 34, no policy on the search 3.
fszontagh 1 maand geleden
bovenliggende
commit
a574fffacc

File diff suppressed because it is too large
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.13.1
+2.14.0

+ 23 - 0
client/include/smartbotic/database/client.hpp

@@ -898,6 +898,29 @@ public:
         uint32_t topK,
         float minScore = 0.0f);
 
+    /**
+     * v2.14.0 - a similarity search over the rows matching EVERY filter.
+     *
+     * The filters select the candidates BEFORE ranking (same grammar and
+     * semantics as find()), so the answer is the exact top-K among matching
+     * rows, never a filtered slice of the unfiltered top-K. Scores are
+     * identical to an unfiltered search with the same vector. minScore trims
+     * after the filter. Fewer matches than topK returns all of them; no match
+     * returns empty. Rows with equal scores are ordered by id (lower first) -
+     * that holds for the unfiltered search too, from 2.14.0.
+     *
+     * Against a pre-2.14.0 server, which would ignore the filters and answer
+     * UNFILTERED, this throws Client::FailedPrecondition with reason
+     * `filters_unsupported` instead of returning those rows. An empty
+     * `filters` is the plain search and works against any server.
+     */
+    [[nodiscard]] std::vector<SimilarityResult> similaritySearch(
+        const std::string& collection,
+        const std::vector<float>& queryVector,
+        uint32_t topK,
+        float minScore,
+        const std::vector<Filter>& filters);
+
     // ===== Collection Management =====
 
     bool createCollection(const std::string& name, uint32_t defaultTtlSeconds = 0,

+ 26 - 1
client/src/client.cpp

@@ -1198,7 +1198,8 @@ public:
 
     std::vector<Client::SimilarityResult> similaritySearch(
         const std::string& collection, const std::vector<float>& queryVector,
-        uint32_t topK, float minScore) {
+        uint32_t topK, float minScore,
+        const std::vector<Client::Filter>& filters = {}) {
         smartbotic::databasepb::SimilaritySearchRequest request;
         request.set_collection(qualify(collection));
         for (float v : queryVector) {
@@ -1206,6 +1207,12 @@ public:
         }
         request.set_top_k(topK);
         request.set_min_score(minScore);
+        for (const auto& filter : filters) {
+            auto* pb = request.add_filters();
+            pb->set_field(filter.field);
+            pb->set_value(filter.value.dump());
+            pb->set_op(static_cast<smartbotic::databasepb::FilterOp>(filter.op));
+        }
 
         smartbotic::databasepb::SimilaritySearchResponse response;
         grpc::ClientContext context;
@@ -1216,6 +1223,18 @@ public:
             spdlog::error("Client::similaritySearch failed: {}", status.error_message());
             throwStatus(status, status.error_message());
         }
+        // v2.14.0 - a pre-2.14.0 server ignores the filters and ranks the
+        // whole collection. Those rows look exactly like a filtered answer, so
+        // they are refused rather than returned.
+        if (!filters.empty() && !response.filters_applied()) {
+            const std::string msg =
+                "similaritySearch: the server does not support filters (needs >= 2.14.0); "
+                "its answer would be unfiltered";
+            spdlog::error("Client::{}", msg);
+            throw DetailedFailedPrecondition(
+                msg, makeDetail(Client::ErrorCode::FailedPrecondition, msg,
+                                R"({"reason":"filters_unsupported"})"));
+        }
 
         std::vector<Client::SimilarityResult> results;
         results.reserve(response.results_size());
@@ -3182,6 +3201,12 @@ std::vector<Client::SimilarityResult> Client::similaritySearch(
     return impl_->similaritySearch(collection, queryVector, topK, minScore);
 }
 
+std::vector<Client::SimilarityResult> Client::similaritySearch(
+    const std::string& collection, const std::vector<float>& queryVector,
+    uint32_t topK, float minScore, const std::vector<Filter>& filters) {
+    return impl_->similaritySearch(collection, queryVector, topK, minScore, filters);
+}
+
 bool Client::createCollection(const std::string& name, uint32_t defaultTtlSeconds,
                               bool encrypted, uint32_t maxVersions, uint32_t vectorDimension) {
     return impl_->createCollection(name, defaultTtlSeconds, encrypted, maxVersions, vectorDimension);

+ 4 - 3
docs/ROADMAP.md

@@ -1,6 +1,6 @@
 # Smartbotic Database - Status and Roadmap
 
-**Released version: 2.13.1** (see `VERSION`). Last reviewed: 2026-10-08.
+**Released version: 2.14.0** (see `VERSION`). Last reviewed: 2026-10-09.
 
 > 2.11.5 was prepared but never released on its own: its work (event actors,
 > `removeAs()`) ships inside 2.12.0. There is no 2.11.5 package.
@@ -56,13 +56,14 @@ Consequences of that substitution, which trip up readers:
 
 ## Shipped
 
-Every item below is in the installed product as of 2.13.1. `CLAUDE.md` has the
+Every item below is in the installed product as of 2.14.0. `CLAUDE.md` has the
 detail and the failure modes.
 
 - JSON document store: collections, version history, field-level encryption, TTL
 - LMDB storage substrate, one env per project, dual-write mirror from MemoryStore
 - Multi-project namespaces (`<project>:<collection>`)
-- Vector storage with SIMD cosine similarity search
+- Vector storage with SIMD cosine similarity search; filtered search, exact
+  top-K among rows matching `find()`'s filters (2.14.0)
 - Views (read-only projections with baked-in filters)
 - Row- and column-level access policy, off by default per project
 - Project-scoped file storage with content-addressed, refcounted, deduplicated blobs

+ 47 - 1
docs/integration-guide.md

@@ -950,6 +950,10 @@ easy to forget:
   recomputes `total_count`, which would otherwise report how many files exist in
   types you have no grant for.
 - **Batch and set operations**, which are ordinary reads and writes.
+- **`SimilaritySearch`** (2.14.0+): row predicate, masks and the masked-filter
+  refusal exactly as `Find`. **Before 2.14.0 it checked the grant and then
+  returned every row and every column** - on a secured project a vector search
+  saw rows and fields `find()` refuses.
 
 Semantics worth knowing:
 
@@ -1496,9 +1500,51 @@ for (const auto& r : results) {
 ```
 
 Notes:
-- `_vector` is extracted and stored separately — not returned in `get()` or `find()` responses
+- `_vector` is extracted and stored separately; `get()`/`find()` return it only
+  when asked (`Client::WithVector`, 2.13.0+)
 - Dimension is validated on every insert — mismatches are rejected
 - SIMD-accelerated (AVX2/SSE4.1) brute-force cosine similarity
+- **`minScore` 0.0 drops rows whose cosine is NEGATIVE.** It is a threshold,
+  not "no threshold". To rank every row, pass `-1.0f`.
+- **Ties (2.14.0+):** rows with equal scores are ordered by id, lower first,
+  and when ties straddle the topK cut the lower ids are kept. Before 2.14.0 the
+  order of tied rows was unspecified.
+
+#### Filtered similarity search (2.14.0+)
+
+```cpp
+using F = smartbotic::database::Client::Filter;
+auto hits = db.similaritySearch("kb_chunks", queryVec, /*topK=*/500, /*minScore=*/0.0f,
+                                {F::eq("departmentKey", "webber")});
+```
+
+- **Exact:** the filters select candidate rows BEFORE ranking, so the answer is
+  the true top-K among matching rows - never a filtered slice of an unfiltered
+  top-K, and there is no candidate cap. Scores are bit-identical to an
+  unfiltered search with the same vector.
+- **Same grammar and evaluator as `find()`**: every operator, ANDed. A row
+  `find()` would return with those filters is exactly a row the search may rank.
+  An index on the filtered field is used the same way `find()` uses it.
+- `minScore` trims after the filter. Fewer matching rows than `topK` returns
+  all of them (that pass `minScore`); a filter matching nothing, or naming a
+  field no row carries, returns empty - neither is an error.
+- A matching row that has no stored vector is not returned.
+- **`SEARCH` ignores its field**, here as in `find()`: it is a case-insensitive
+  substring match over the whole document (id, keys, every string and number).
+  It also needs every document decoded, so it never runs at index speed.
+- Access policy applies as it does to `find()`: the row predicate is ANDed in,
+  masked columns are removed, a filter on a masked column is refused.
+- **⚠ Against a pre-2.14.0 server** the filters would be silently ignored and the
+  answer would be UNFILTERED. The client detects that (the response says whether
+  filters were applied) and throws `Client::FailedPrecondition`, reason
+  `filters_unsupported`, instead of returning those rows. An empty filter list
+  is the plain search and works against any server.
+
+Measured on 12,447 rows at dimension 4096 (best of 5, one host): unfiltered
+top 500 187 ms; a filter matching ~430 rows, top 500: 78 ms unindexed, 51 ms
+indexed; top 5 indexed: 13 ms; a filter matching 1/7 of rows: ~90 ms; a filter
+matching nothing: under 1 ms. A filtered search scores only matching rows, so it
+is cheaper than the unfiltered one, not dearer.
 
 ### Version History
 

+ 10 - 0
proto/database.proto

@@ -589,10 +589,20 @@ message SimilaritySearchRequest {
     repeated float query_vector = 2;
     uint32 top_k = 3;
     float min_score = 4;
+    // v2.14.0 - only rows matching EVERY filter are candidates (same grammar
+    // and semantics as FindRequest.filters). The answer is the exact top-K
+    // among matching rows; min_score then trims. A pre-2.14.0 server ignores
+    // this field and answers UNFILTERED, which is why the response says
+    // whether the filters were applied.
+    repeated Filter filters = 5;
 }
 
 message SimilaritySearchResponse {
     repeated SimilarityResult results = 1;
+    // v2.14.0 - true when the server applied `filters`. A pre-2.14.0 server
+    // never sets it, so a client that sent filters and reads false must NOT
+    // use the results: they are unfiltered.
+    bool filters_applied = 2;
 }
 
 message SimilarityResult {

+ 67 - 8
service/src/database_grpc_impl.cpp

@@ -16,6 +16,7 @@
 #include <nlohmann/json.hpp>
 
 #include <algorithm>
+#include <limits>
 #include <chrono>
 #include <fstream>
 #include <functional>
@@ -1697,6 +1698,23 @@ grpc::Status DatabaseGrpcImpl::SimilaritySearch(
         float minScore = request->min_score();
         const std::string& collection = request->collection();
 
+        // v2.14.0 - filters select the candidate rows BEFORE ranking, so the
+        // answer is the exact top-K among matching rows (a post-filter of an
+        // unfiltered top-K would be short whenever matches rank low). Same
+        // grammar and evaluator as Find. The access policy applies exactly as
+        // it does to Find - before 2.14.0 this handler gated but never applied
+        // the row predicate or the masks, so on a secured project a vector
+        // search returned rows and fields find() refuses.
+        std::vector<Filter> filters;
+        try {
+            filters = fromProtoFilters(request->filters());
+        } catch (const std::exception& e) {
+            return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+                                std::string("Bad filter value: ") + e.what());
+        }
+        if (auto st = rejectMaskedFilters(filters, dec.mask); !st.ok()) return st;
+        for (const auto& f : dec.row) filters.push_back(f);
+
         // v2.0 Stage 5 — LMDB-first SimilaritySearch. Same gate shape as
         // Exists/Get/Find: non-system collection + mirror healthy + zero
         // drift + doc_store_ available. We iterate the
@@ -1733,17 +1751,23 @@ grpc::Status DatabaseGrpcImpl::SimilaritySearch(
                         // MemoryStore behaviour which returns empty.
                         used_lmdb = true;
                     } else {
-                        // Min-heap of (score, id) keyed on score-ascending so
-                        // pop() evicts the weakest current top-K candidate.
+                        // Heap of the current top-K with the WEAKEST on top.
+                        // v2.14.0 - a tie on score is broken by id (lower id
+                        // ranks first), so which tied row makes the cut, and
+                        // the order of tied rows, no longer depends on the
+                        // order rows are visited - a filtered search visits
+                        // them differently from an unfiltered one, and both
+                        // must agree.
                         using Scored = std::pair<float, std::string>;
                         auto cmp = [](const Scored& a, const Scored& b) {
-                            return a.first > b.first;  // min-heap on score
+                            if (a.first != b.first) return a.first > b.first;
+                            return a.second < b.second;
                         };
                         std::priority_queue<Scored, std::vector<Scored>,
                                             decltype(cmp)> heap(cmp);
                         size_t expectedDim = queryVec.size();
 
-                        ds->scan_vectors(rc.collection,
+                        const auto score_row =
                             [&](std::string_view id, const float* data,
                                 size_t count) {
                                 if (count != expectedDim) {
@@ -1769,11 +1793,24 @@ grpc::Status DatabaseGrpcImpl::SimilaritySearch(
                                 if (score < minScore) return;
                                 if (heap.size() < topK) {
                                     heap.emplace(score, std::string(id));
-                                } else if (!heap.empty() && score > heap.top().first) {
+                                } else if (!heap.empty() &&
+                                           (score > heap.top().first ||
+                                            (score == heap.top().first &&
+                                             id < heap.top().second))) {
                                     heap.pop();
                                     heap.emplace(score, std::string(id));
                                 }
-                            });
+                            };
+                        // A store that cannot filter leaves `served` false and
+                        // the query goes to the MemoryStore path below - never
+                        // an unfiltered answer.
+                        bool served = true;
+                        if (filters.empty()) {
+                            ds->scan_vectors(rc.collection, score_row);
+                        } else {
+                            served = ds->scan_vectors_filtered(rc.collection, filters,
+                                                               score_row);
+                        }
 
                         if (dim_mismatch) {
                             return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
@@ -1800,13 +1837,20 @@ grpc::Status DatabaseGrpcImpl::SimilaritySearch(
                                 // also drops missing docs from results.
                                 continue;
                             }
+                            // The document is read after the ranking scan, so
+                            // a write in between can make it stop matching.
+                            // Re-judge: a row outside the filter (or outside
+                            // the caller's row predicate) is never returned.
+                            if (!filters.empty() && !store_.matchesFilters(*doc, filters)) {
+                                continue;
+                            }
                             MemoryStore::SimilarityResult r;
                             r.id = id;
                             r.score = score;
                             r.document = std::move(*doc);
                             results.push_back(std::move(r));
                         }
-                        used_lmdb = true;
+                        used_lmdb = served;
                     }
                 } catch (const std::invalid_argument&) {
                     // Argument-shape errors should propagate, not silently
@@ -1832,12 +1876,27 @@ grpc::Status DatabaseGrpcImpl::SimilaritySearch(
         }
 
         if (!used_lmdb) {
-            results = store_.similaritySearch(collection, queryVec, topK, minScore);
+            if (filters.empty()) {
+                results = store_.similaritySearch(collection, queryVec, topK, minScore);
+            } else {
+                // Degraded path (mirror unhealthy): rank everything, then keep
+                // the first topK that match - exact over what MemoryStore holds.
+                auto all = store_.similaritySearch(
+                    collection, queryVec, std::numeric_limits<uint32_t>::max(), minScore);
+                for (auto& r : all) {
+                    if (results.size() >= topK) break;
+                    if (store_.matchesFilters(r.document, filters)) {
+                        results.push_back(std::move(r));
+                    }
+                }
+            }
         }
+        response->set_filters_applied(true);
 
         for (auto& result : results) {
             // Decrypt sensitive fields before returning
             encryption_.decryptSensitiveFields(result.document);
+            applyMask(result.document, dec.mask);
 
             auto* protoResult = response->add_results();
             protoResult->set_id(result.id);

+ 16 - 0
service/src/storage/document_store.hpp

@@ -177,6 +177,22 @@ public:
                            const float* data,
                            size_t count)> /*callback*/) {}
 
+    // v2.14.0 - scan_vectors restricted to the rows whose DOCUMENT matches every
+    // filter (Find's grammar and semantics: the same index planner and the same
+    // evaluator decide it), in ONE read transaction with the vectors, so a row
+    // and its vector are judged in the same snapshot. Ids are offered in id
+    // order; the callback contract is scan_vectors'. A row matching the filters
+    // with no vector entry is simply not offered.
+    //
+    // Returns false when this store cannot evaluate filters (the default), so
+    // the caller must take another path - never an unfiltered answer.
+    virtual bool scan_vectors_filtered(
+        std::string_view /*collection*/,
+        const std::vector<smartbotic::database::Filter>& /*filters*/,
+        std::function<void(std::string_view id,
+                           const float* data,
+                           size_t count)> /*callback*/) { return false; }
+
     // v2.13.0 - ExportCollection. Walks one collection in id order inside ONE
     // read transaction, so a stream is an exact snapshot: no row is skipped or
     // repeated within it. Rows with an id <= `after_id` are skipped (resume).

+ 96 - 0
service/src/storage/document_store_lmdb.cpp

@@ -3064,6 +3064,102 @@ void LmdbDocumentStore::scan_vectors(
     }
 }
 
+std::vector<std::string> LmdbDocumentStore::matchingIdsTxn(
+    ReadTxn& rtxn, std::string_view collection,
+    const std::vector<smartbotic::database::Filter>& filters,
+    unsigned int coll_dbi) {
+    namespace fe = smartbotic::db::storage::filter_eval;
+    std::vector<std::string> ids;
+
+    // The row judge is scan()'s, both halves: the resolver path for ordinary
+    // predicates and a whole decoded document for SEARCH. A filtered vector
+    // search and a find() with the same filters must agree on which rows match;
+    // a second evaluator would drift silently.
+    const bool wholeDoc = fe::needsWholeDocument(filters);
+    const auto matches = [&](std::string_view bytes) -> bool {
+        if (wholeDoc) {
+            return fe::matchesFilters(decode_document(bytes), filters);
+        }
+        yyjson_doc* ydoc = yyjson_read(bytes.data(), bytes.size(), 0);
+        if (!ydoc) return false;   // unparseable row: scan() skips it too
+        yyjson_val* root = yyjson_doc_get_root(ydoc);
+        const bool ok = fe::matchesFiltersResolved(
+            [root](const std::string& f) { return resolve_from_yyjson(root, f); },
+            filters);
+        yyjson_doc_free(ydoc);
+        return ok;
+    };
+
+    std::optional<std::vector<std::string>> candidates;
+    if (!wholeDoc) {
+        smartbotic::database::Query q;
+        q.filters = filters;
+        candidates = planIndexCandidates(rtxn, collection, q, coll_dbi);
+    }
+    if (candidates) {
+        indexed_scans_.fetch_add(1, std::memory_order_relaxed);
+        // The index may name a superset (a scalar EQ on an array field, a
+        // posting ahead of its row): every candidate is still judged.
+        for (const auto& cid : *candidates) {
+            MDB_val ck = to_val(cid);
+            MDB_val cv{0, nullptr};
+            if (mdb_get(rtxn.raw(), coll_dbi, &ck, &cv) != MDB_SUCCESS) continue;
+            if (matches(to_sv(cv))) ids.push_back(cid);
+        }
+        std::sort(ids.begin(), ids.end());
+        ids.erase(std::unique(ids.begin(), ids.end()), ids.end());
+        return ids;
+    }
+
+    full_scans_.fetch_add(1, std::memory_order_relaxed);
+    MDB_cursor* cursor = nullptr;
+    mdb_check(mdb_cursor_open(rtxn.raw(), coll_dbi, &cursor), "cursor_open (match ids)");
+    struct CursorGuard {
+        MDB_cursor* c;
+        ~CursorGuard() { if (c) mdb_cursor_close(c); }
+    } guard{cursor};
+    MDB_val k{0, nullptr};
+    MDB_val v{0, nullptr};
+    int rc = mdb_cursor_get(cursor, &k, &v, MDB_FIRST);
+    while (rc == MDB_SUCCESS) {
+        if (!is_identity_key(to_sv(k)) && matches(to_sv(v))) {
+            ids.emplace_back(to_sv(k));   // cursor order is id order
+        }
+        rc = mdb_cursor_get(cursor, &k, &v, MDB_NEXT);
+    }
+    if (rc != MDB_NOTFOUND && rc != MDB_SUCCESS) {
+        throw_mdb(rc, "cursor_get (match ids)");
+    }
+    return ids;
+}
+
+bool LmdbDocumentStore::scan_vectors_filtered(
+    std::string_view collection,
+    const std::vector<smartbotic::database::Filter>& filters,
+    std::function<void(std::string_view, const float*, size_t)> callback) {
+    if (!callback) return true;
+    ReadTxn rtxn(env_);
+    auto coll_dbi = try_open_for_read(rtxn, collection);
+    if (!coll_dbi) return true;   // no collection: nothing matches
+    auto vec_dbi = try_open_for_read(rtxn, vector_subdb_name(collection));
+    if (!vec_dbi) return true;    // no vectors: nothing to rank
+
+    const auto ids = matchingIdsTxn(rtxn, collection, filters, *coll_dbi);
+    for (const auto& id : ids) {
+        MDB_val k = to_val(id);
+        MDB_val v{0, nullptr};
+        const int rc = mdb_get(rtxn.raw(), *vec_dbi, &k, &v);
+        if (rc == MDB_NOTFOUND) continue;   // a matching row without a vector
+        if (rc != MDB_SUCCESS) throw_mdb(rc, "get (filtered vectors)");
+        if (v.mv_size % sizeof(float) != 0) {
+            throw std::runtime_error(
+                "scan_vectors_filtered: stored bytes are not a multiple of sizeof(float)");
+        }
+        callback(id, static_cast<const float*>(v.mv_data), v.mv_size / sizeof(float));
+    }
+    return true;
+}
+
 bool LmdbDocumentStore::drop_collection(std::string_view collection) {
     // A collection's data spans two sub-dbs: the docs sub-db `<collection>`
     // and the parallel vectors sub-db `_vectors_<collection>`. Both must be

+ 14 - 0
service/src/storage/document_store_lmdb.hpp

@@ -495,6 +495,12 @@ public:
         std::function<void(std::string_view id,
                            const float* data,
                            size_t count)> callback) override;
+    bool scan_vectors_filtered(
+        std::string_view collection,
+        const std::vector<smartbotic::database::Filter>& filters,
+        std::function<void(std::string_view id,
+                           const float* data,
+                           size_t count)> callback) override;
 
     // v2.11.0 T12 — open a caller-owned WriteTxn spanning several
     // txn-accepting put()/del()/put_vector()/del_vector() calls across
@@ -715,6 +721,14 @@ private:
     lookupIndexAllTxn(class ReadTxn& rtxn, std::string_view collection,
                       const std::string& field, uint64_t budget);
 
+    // v2.14.0 - every id whose document matches `filters`, sorted, judged
+    // exactly as scan() judges a row (index candidates re-checked against every
+    // filter; SEARCH on the whole document).
+    std::vector<std::string>
+    matchingIdsTxn(class ReadTxn& rtxn, std::string_view collection,
+                   const std::vector<smartbotic::database::Filter>& filters,
+                   unsigned int coll_dbi);
+
     // Choose an index for a query, or nullopt to walk the whole collection.
     std::optional<std::vector<std::string>>
     planIndexCandidates(class ReadTxn& rtxn, std::string_view collection,

+ 345 - 0
tests/load_test/test_filtered_similarity.cpp

@@ -0,0 +1,345 @@
+// v2.14.0 client/server boundary test: similaritySearch with filters.
+//
+// Requested by smartbotic-vectorapi, which emulated a filtered vector search
+// by widening an unfiltered one and intersecting in its own process: 3.2 s for
+// a 0.26 s search, and past its 10000-candidate cap the answer could be short.
+//
+// THE ORACLE: an unfiltered search with topK = every row is the full ranking.
+// Restricted to the ids find() returns for the same filters, its first topK is
+// what a filtered search must return - same ids, same order, BIT-identical
+// scores, same bodies. That pins exactness (the true top-K among matching
+// rows, not a filtered slice of the unfiltered top-K) and that find() and a
+// filtered search agree on which rows match, for every operator.
+//
+// Phases, run by test_filtered_similarity.sh:
+//   write  - seed the collections.
+//   check  - every operator and a conjunction against the oracle, several
+//            queries and topK values; fewer matches than topK; no match; a
+//            field no row carries; minScore after the filter; ties ordered by
+//            id; vector-less matching rows; the same answers once an index
+//            serves the filter.
+//   old <addr> - against a pre-2.14.0 server: filters are refused with
+//            `filters_unsupported`, never answered unfiltered; no filters
+//            still works.
+
+#include <smartbotic/database/client.hpp>
+
+#include <cstring>
+#include <iostream>
+#include <random>
+#include <set>
+#include <string>
+#include <vector>
+
+using namespace smartbotic::database;
+using F = Client::Filter;
+using SR = Client::SimilarityResult;
+static int pass = 0, fail = 0;
+static void ck(bool c, const std::string& m) {
+    if (c) { ++pass; } else { ++fail; std::cerr << "FAIL: " << m << "\n"; }
+}
+
+static std::string gAddr = "127.0.0.1:9024";
+static const uint32_t kDim = 8;
+static const int kRows = 300;
+static const int kNoVecFrom = 290;   // rows 290..299 are written WITHOUT a vector
+
+static std::vector<float> randVec(uint32_t seed) {
+    std::mt19937 rng(seed);
+    std::normal_distribution<float> nd(0.f, 1.f);
+    std::vector<float> v(kDim);
+    for (auto& x : v) x = nd(rng);
+    return v;
+}
+static std::string rid(int i) {
+    char b[16];
+    std::snprintf(b, sizeof b, "r%03d", i);
+    return b;
+}
+static std::string deptOf(int i) {
+    if (i % 25 == 0) return "rare";   // 12 rows with a vector: 0, 25, ..., 275
+    static const char* d[] = {"a", "b", "c"};
+    return d[i % 3];
+}
+
+static Client::Config cfg() {
+    Client::Config c;
+    c.address = gAddr;
+    c.project = "fs";
+    return c;
+}
+
+static int write() {
+    Client c(cfg());
+    c.connect();
+    ck(c.createCollection("kb", 0, false, 0, kDim), "create kb (dim 8)");
+    for (int i = 0; i < kRows; ++i) {
+        nlohmann::json d = {
+            {"dept", deptOf(i)},
+            {"n", i},
+            {"tags", nlohmann::json::array({"t" + std::to_string(i % 5), "all"})},
+            {"title", "Doc " + std::to_string(i) + " body"},
+            {"meta", {{"note", i % 7 == 0 ? "Gamma ray" : "plain"}}},
+        };
+        if (i % 2 == 0) d["opt"] = true;
+        // The last rows match filters but have no vector: never offered.
+        if (i >= kNoVecFrom) d["dept"] = "rare";
+        else d["_vector"] = randVec(100 + i);
+        c.insert("kb", d, rid(i));
+    }
+    // Ties: three rows with the SAME vector, inserted out of id order.
+    const auto tv = randVec(7);
+    for (const char* id : {"tie_b", "tie_c", "tie_a"}) {
+        c.insert("kb", {{"dept", "tie"}, {"n", -1}, {"_vector", tv}}, id);
+    }
+    ck(c.createCollection("plain"), "create plain (no dimension)");
+    c.insert("plain", {{"dept", "a"}}, "p1");
+    return 0;
+}
+
+static std::set<std::string> findIds(Client& c, const std::vector<F>& filters) {
+    Client::QueryOptions o;
+    o.filters = filters;
+    o.limit = 100000;
+    std::set<std::string> ids;
+    for (const auto& d : c.find("kb", o, {"_id"})) ids.insert(d.value("_id", ""));
+    return ids;
+}
+
+static std::vector<SR> oracle(Client& c, const std::vector<float>& q,
+                              const std::vector<F>& filters, uint32_t topK, float minScore) {
+    const auto all = c.similaritySearch("kb", q, 100000, minScore);
+    const auto ids = findIds(c, filters);
+    std::vector<SR> out;
+    for (const auto& r : all) {
+        if (out.size() >= topK) break;
+        if (ids.count(r.id)) out.push_back(r);
+    }
+    return out;
+}
+
+static bool sameBits(float a, float b) { return std::memcmp(&a, &b, sizeof a) == 0; }
+
+static void ordered(const std::vector<SR>& r, const std::string& what) {
+    bool ok = true;
+    for (size_t i = 1; i < r.size(); ++i) {
+        if (r[i - 1].score < r[i].score) ok = false;
+        if (r[i - 1].score == r[i].score && !(r[i - 1].id < r[i].id)) ok = false;
+    }
+    ck(ok, what + ": strictly descending, ties by id");
+}
+
+// Returns the filtered result so a caller can assert more about it.
+static std::vector<SR> against(Client& c, const std::string& what, const std::vector<float>& q,
+                               const std::vector<F>& filters, uint32_t topK,
+                               float minScore = 0.0f) {
+    const auto got = c.similaritySearch("kb", q, topK, minScore, filters);
+    const auto want = oracle(c, q, filters, topK, minScore);
+    bool same = got.size() == want.size();
+    for (size_t i = 0; same && i < got.size(); ++i) {
+        same = got[i].id == want[i].id && sameBits(got[i].score, want[i].score) &&
+               got[i].data == want[i].data;
+    }
+    ck(same, what + " k=" + std::to_string(topK) + ": equals the oracle (" +
+                 std::to_string(got.size()) + " vs " + std::to_string(want.size()) + ")");
+    ordered(got, what);
+    return got;
+}
+
+static int check() {
+    Client c(cfg());
+    c.connect();
+
+    struct Case {
+        std::string name;
+        std::vector<F> filters;
+    };
+    const std::vector<Case> cases = {
+        {"eq", {F::eq("dept", "b")}},
+        {"ne", {F::ne("dept", "a")}},
+        {"gt", {F::gt("n", 150)}},
+        {"gte", {F::gte("n", 150)}},
+        {"lt", {F::lt("n", 40)}},
+        {"lte", {F::lte("n", 40)}},
+        {"in", {F::in("dept", nlohmann::json::array({"b", "rare"}))}},
+        {"contains", {F::contains("tags", "t3")}},
+        {"exists", {F::exists("opt", true)}},
+        {"not-exists", {F::exists("opt", false)}},
+        {"regex", {F::regex("title", "^Doc 1[0-9] ")}},
+        {"search", {F::search("", "gamma")}},
+        {"and", {F::eq("dept", "b"), F::gt("n", 100)}},
+        {"and-contains", {F::contains("tags", "all"), F::lt("n", 60)}},
+    };
+    const std::vector<uint32_t> ks = {1, 5, 50, 500};
+    for (uint32_t qs = 0; qs < 3; ++qs) {
+        const auto q = randVec(9000 + qs);
+        for (const auto& cs : cases) {
+            for (uint32_t k : ks) against(c, cs.name + " q" + std::to_string(qs), q, cs.filters, k);
+        }
+    }
+
+    // Sanity that the oracle is not vacuous: each case matches something,
+    // and "search" really searches nested values case-insensitively.
+    for (const auto& cs : cases) ck(!findIds(c, cs.filters).empty(), cs.name + " matches rows");
+
+    const auto q = randVec(4242);
+
+    // 1. Fewer matches than topK: all of them, and only those with a vector.
+    // minScore -1 admits every cosine; at the usual 0.0 a row scoring below
+    // zero is trimmed (minScore applies after the filter, as unfiltered).
+    {
+        const auto r = against(c, "rare", q, {F::eq("dept", "rare")}, 500, -1.0f);
+        ck(r.size() == 12, "rare: the 12 rows with a vector, not the 10 without (got " +
+                               std::to_string(r.size()) + ")");
+        bool noVecLeak = true;
+        for (const auto& x : r) if (x.id >= rid(kNoVecFrom)) noVecLeak = false;
+        ck(noVecLeak, "rare: rows without a vector are never offered");
+        const auto z = against(c, "rare minScore 0", q, {F::eq("dept", "rare")}, 500);
+        size_t nonneg = 0;
+        for (const auto& x : r) if (x.score >= 0.0f) ++nonneg;
+        ck(z.size() == nonneg && nonneg < r.size(),
+           "rare at minScore 0: exactly the non-negative scores (" + std::to_string(z.size()) +
+               " of " + std::to_string(r.size()) + ")");
+    }
+    // Exactness is not trivially satisfied: the filtered top-12 reaches rows
+    // that an unfiltered top-12 does not contain.
+    {
+        const auto f = c.similaritySearch("kb", q, 12, 0.0f, {F::eq("dept", "rare")});
+        const auto u = c.similaritySearch("kb", q, 12);
+        std::set<std::string> uids;
+        for (const auto& x : u) uids.insert(x.id);
+        size_t outside = 0;
+        for (const auto& x : f) if (!uids.count(x.id)) ++outside;
+        ck(outside > 0, "filtered top-K reaches past the unfiltered top-K (" +
+                            std::to_string(outside) + " rows)");
+    }
+    // 2. Scores bit-identical to the unfiltered search, row by row.
+    {
+        const auto f = c.similaritySearch("kb", q, 500, 0.0f, {F::eq("dept", "c")});
+        const auto all = c.similaritySearch("kb", q, 100000);
+        bool ok = !f.empty();
+        for (const auto& x : f) {
+            bool found = false;
+            for (const auto& y : all) {
+                if (y.id == x.id) { found = sameBits(x.score, y.score); break; }
+            }
+            ok = ok && found;
+        }
+        ck(ok, "scores bit-identical to the unfiltered search");
+    }
+    // 3. A filter matching nothing: empty, not an error.
+    {
+        bool threw = false;
+        std::vector<SR> r;
+        try { r = c.similaritySearch("kb", q, 500, 0.0f, {F::eq("dept", "zzz")}); }
+        catch (...) { threw = true; }
+        ck(!threw && r.empty(), "no match: empty, no throw");
+    }
+    // 5. A field no row carries: empty, never everything.
+    {
+        const auto r = c.similaritySearch("kb", q, 500, 0.0f, {F::eq("nosuchfield", "x")});
+        ck(r.empty(), "absent field: empty");
+    }
+    // minScore trims AFTER the filter.
+    {
+        const auto r = against(c, "minScore", q, {F::eq("dept", "b")}, 500, 0.3f);
+        bool ok = !r.empty();
+        for (const auto& x : r) ok = ok && x.score >= 0.3f;
+        ck(ok, "minScore: every returned score >= 0.3");
+    }
+    // 4. Ties: same vector, ordered by id, and the cut keeps the lower ids -
+    // filtered AND unfiltered.
+    {
+        const auto tq = randVec(7);
+        const auto f = c.similaritySearch("kb", tq, 2, 0.0f, {F::eq("dept", "tie")});
+        ck(f.size() == 2 && f[0].id == "tie_a" && f[1].id == "tie_b",
+           "ties (filtered): tie_a, tie_b");
+        const auto u = c.similaritySearch("kb", tq, 2);
+        ck(u.size() == 2 && u[0].id == "tie_a" && u[1].id == "tie_b",
+           "ties (unfiltered): tie_a, tie_b");
+        ck(f.size() == 2 && sameBits(f[0].score, f[1].score), "ties really tie");
+    }
+    // An explicitly project-qualified name means the same collection.
+    {
+        const auto a = c.similaritySearch("kb", q, 20, 0.0f, {F::eq("dept", "b")});
+        const auto b = c.similaritySearch("fs:kb", q, 20, 0.0f, {F::eq("dept", "b")});
+        bool same = a.size() == b.size() && !a.empty();
+        for (size_t i = 0; same && i < a.size(); ++i) same = a[i].id == b[i].id;
+        ck(same, "qualified name: same answer");
+    }
+    // Empty filters through the new overload is the plain search.
+    {
+        const auto a = c.similaritySearch("kb", q, 30, 0.0f, std::vector<F>{});
+        const auto b = c.similaritySearch("kb", q, 30);
+        bool same = a.size() == b.size() && a.size() == 30;
+        for (size_t i = 0; same && i < a.size(); ++i) {
+            same = a[i].id == b[i].id && sameBits(a[i].score, b[i].score);
+        }
+        ck(same, "empty filters: same as the plain search");
+    }
+    // A collection without a vector dimension: empty, not an error.
+    {
+        bool threw = false;
+        std::vector<SR> r;
+        try { r = c.similaritySearch("plain", q, 5, 0.0f, {F::eq("dept", "a")}); }
+        catch (...) { threw = true; }
+        ck(!threw && r.empty(), "no-vector collection: empty, no throw");
+    }
+
+    // The same answers once an index serves the filter.
+    ck(c.createIndex("kb", "dept"), "create index on dept");
+    ck(c.createIndex("kb", "tags"), "create index on tags");
+    for (uint32_t qs = 0; qs < 3; ++qs) {
+        const auto iq = randVec(9100 + qs);
+        against(c, "indexed rare", iq, {F::eq("dept", "rare")}, 500);
+        against(c, "indexed eq", iq, {F::eq("dept", "b")}, 7);
+        against(c, "indexed in", iq, {F::in("dept", nlohmann::json::array({"rare", "tie"}))}, 50);
+        against(c, "indexed contains", iq, {F::contains("tags", "t1")}, 5);
+        against(c, "indexed and", iq, {F::eq("dept", "rare"), F::gt("n", 100)}, 500);
+        against(c, "indexed miss", iq, {F::eq("dept", "zzz")}, 5);
+        // EQ with a scalar on an array field: the index names every row whose
+        // array CONTAINS it, but EQ compares the whole array, so nothing
+        // matches - only re-judging each candidate gets this right.
+        const auto arr = against(c, "indexed eq-on-array", iq, {F::eq("tags", "t1")}, 50);
+        ck(arr.empty(), "indexed eq-on-array: index candidates are re-judged (empty)");
+    }
+    return 0;
+}
+
+// Against a pre-2.14.0 server.
+static int old() {
+    Client c(cfg());
+    if (!c.connect()) { ck(false, "old: connect"); return 0; }
+    c.createCollection("kb", 0, false, 0, kDim);
+    for (int i = 0; i < 20; ++i) {
+        c.upsert("kb", {{"dept", deptOf(i)}, {"_vector", randVec(100 + i)}}, rid(i));
+    }
+    const auto q = randVec(1);
+    bool refused = false;
+    std::string reason;
+    try {
+        (void)c.similaritySearch("kb", q, 5, 0.0f, {F::eq("dept", "rare")});
+    } catch (const Client::FailedPrecondition& e) {
+        refused = true;
+        if (const auto* d = Client::errorDetail(e)) reason = d->reason;
+    } catch (...) {
+    }
+    ck(refused, "old server: filtered search refused, not answered unfiltered");
+    ck(reason == "filters_unsupported", "old server: reason filters_unsupported (got '" +
+                                            reason + "')");
+    ck(c.similaritySearch("kb", q, 5).size() == 5, "old server: plain search still works");
+    ck(c.similaritySearch("kb", q, 5, 0.0f, std::vector<F>{}).size() == 5,
+       "old server: empty filters still work");
+    return 0;
+}
+
+int main(int argc, char** argv) {
+    const std::string phase = argc > 1 ? argv[1] : "";
+    if (argc > 2) gAddr = argv[2];
+    if (phase == "write") write();
+    else if (phase == "check") check();
+    else if (phase == "old") old();
+    else { std::cerr << "usage: write|check|old [addr]\n"; return 2; }
+    std::cout << phase << ": " << pass << " passed, " << fail << " failed\n";
+    return fail == 0 ? 0 : 1;
+}

+ 70 - 0
tests/load_test/test_filtered_similarity.sh

@@ -0,0 +1,70 @@
+#!/usr/bin/env bash
+# v2.14.0 client/server boundary e2e - similaritySearch with filters must be
+# the exact top-K among matching rows. See test_filtered_similarity.cpp.
+# The pre-2.14.0 refusal needs an old server: run the binary's `old <addr>`
+# phase against one by hand.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-filtered-similarity
+PORT=9024
+
+rm -rf "$DIR"
+mkdir -p "$DIR/data"
+
+cat > "$DIR/config.json" <<CFG
+{
+  "storage": {
+    "data_directory": "$DIR/data",
+    "bind_address": "127.0.0.1",
+    "rpc_port": $PORT,
+    "encryption": { "enabled": false },
+    "migrations": { "enabled": false },
+    "replication": { "enabled": false }
+  }
+}
+CFG
+
+echo "=== building test binary ==="
+g++ -std=c++20 -O1 -o "$DIR/t" test_filtered_similarity.cpp \
+    -I"$ROOT/client/include" -I"$ROOT/build/client" \
+    -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt -pthread
+
+SERVER_PID=""
+stop() {
+    [[ -n "$SERVER_PID" ]] || return 0
+    kill -CONT "$SERVER_PID" 2>/dev/null || true
+    kill "$SERVER_PID" 2>/dev/null || true
+    wait "$SERVER_PID" 2>/dev/null || true
+    SERVER_PID=""
+}
+trap stop EXIT
+
+"$ROOT/build/service/smartbotic-database" --config "$DIR/config.json" > "$DIR/server.log" 2>&1 &
+SERVER_PID=$!
+for _ in $(seq 1 60); do
+    grep -q "Notified systemd: READY" "$DIR/server.log" && break
+    sleep 0.5
+done
+grep -q "Notified systemd: READY" "$DIR/server.log" || { tail -30 "$DIR/server.log"; exit 1; }
+
+run() {
+    set +e
+    LD_LIBRARY_PATH="$ROOT/build/client" "$DIR/t" "$1" 2>&1 | grep -v '\[error\]' | tee "$DIR/out-$1.txt"
+    local rc=${PIPESTATUS[0]}
+    set -e
+    [[ $rc -eq 0 ]] || { echo "FAILED in phase $1"; exit $rc; }
+}
+
+echo "=== write ==="
+run write
+
+echo "=== check ==="
+run check
+
+echo ""
+echo "OK - filtered similarity e2e passed"

+ 31 - 3
tests/load_test/test_policy_enforcement.cpp

@@ -62,11 +62,16 @@ int main(int argc, char** argv) {
     Client stranger(mk(strange_key, "secured"));
     ops.connect(); reader.connect(); stranger.connect();
 
-    // Seed data as admin.
+    // Seed data as admin. v2.14.0 - `docs` carries vectors so similaritySearch
+    // can be checked against the same rules (phase 5b).
+    ck(ops.createCollection("docs", 0, false, 0, 4), "admin creates docs (dim 4)");
+    const std::vector<float> v1 = {1.f, 0.f, 0.f, 0.f};
+    const std::vector<float> v2 = {0.9f, 0.1f, 0.f, 0.f};   // ranks next to v1
     auto d1 = ops.insert("docs", nlohmann::json{
-        {"tenant", "acme"}, {"ssn", "111-22-3333"}, {"note", "visible"}});
+        {"tenant", "acme"}, {"ssn", "111-22-3333"}, {"note", "visible"}, {"_vector", v1}});
     auto d2 = ops.insert("docs", nlohmann::json{
-        {"tenant", "other"}, {"ssn", "999-88-7777"}, {"note", "hidden by row rule"}});
+        {"tenant", "other"}, {"ssn", "999-88-7777"}, {"note", "hidden by row rule"},
+        {"_vector", v2}});
     ck(!d1.empty() && !d2.empty(), "admin can write in a secured project");
 
     // ---- Phase 3: deny-by-default -----------------------------------------
@@ -102,6 +107,29 @@ int main(int argc, char** argv) {
     }
     ck(!saw_other, "row predicate filters Find results");
 
+    // ---- Phase 5b: similaritySearch obeys the same rules (v2.14.0) --------
+    // Before 2.14.0 it gated the collection and then returned every row and
+    // every column, so a vector search saw what find() refuses.
+    {
+        auto all = ops.similaritySearch("docs", v1, 10);
+        ck(all.size() == 2, "admin's vector search sees both rows");
+        auto r = reader.similaritySearch("docs", v1, 10);
+        ck(r.size() == 1 && r[0].id == d1, "row predicate filters similaritySearch");
+        bool masked = true;
+        for (const auto& x : r) if (x.data.contains("ssn")) masked = false;
+        ck(masked, "masked column is absent from similaritySearch results");
+        auto f = reader.similaritySearch("docs", v1, 10, -1.f,
+                                         {Client::Filter::eq("tenant", "other")});
+        ck(f.empty(), "a filter cannot widen past the row predicate");
+        ck(denied([&]{
+            (void)reader.similaritySearch("docs", v1, 10, -1.f,
+                                          {Client::Filter::eq("ssn", "111-22-3333")});
+           }),
+           "a similaritySearch filter on a masked column is refused");
+        ck(denied([&]{ (void)stranger.similaritySearch("docs", v1, 10); }),
+           "stranger is denied on similaritySearch");
+    }
+
     // ---- Phase 6: mask is not an inference channel ------------------------
     ck(denied([&]{
         reader.find("docs", Client::QueryOptions{

Some files were not shown because too many files changed in this diff