Ver código fonte

feat: 2.18.0 - range filters compare number to number and string to string only

GT/GTE/LT/LTE used nlohmann's cross-type ordering (null < bool < number <
string): an explicit null or true matched year <= 2025, and the string
"1900" matched year >= 2025 - silent over-matching, found by a consumer's
access gate. A range now holds only when both sides are numbers or both are
strings; a null/boolean bound matches nothing. EQ/NE, EXISTS, absent-field
handling and sort order are unchanged. The index range plan declines a
null/boolean bound, because the ordered range plan trusts postings without
re-judging. Capability typed_range_filters. Tests: test_typed_ranges (30;
reverted: rule 17 fail, index gate 2).
fszontagh 1 mês atrás
pai
commit
ac108f7ce5

Diferenças do arquivo suprimidas por serem muito extensas
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.17.2
+2.18.0

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

@@ -333,6 +333,10 @@ public:
         static constexpr const char* kClientVersionHeader = "client_version_header";
         static constexpr const char* kCollectionSchema = "collection_schema";
         static constexpr const char* kEncryptionAtRest = "encryption_at_rest";
+        /// 2.18.0: range filters (GT/GTE/LT/LTE) match only number-to-number or
+        /// string-to-string; null, booleans and type mismatches never match.
+        /// Older servers compared across JSON types (null < bool < number < string).
+        static constexpr const char* kTypedRangeFilters = "typed_range_filters";
     };
 
     struct ServerInfo {

+ 9 - 2
docs/ROADMAP.md

@@ -1,6 +1,6 @@
 # Smartbotic Database - Status and Roadmap
 
-**Released version: 2.17.2** (see `VERSION`). Last reviewed: 2026-10-12.
+**Released version: 2.18.0** (see `VERSION`). Last reviewed: 2026-10-13.
 
 > 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,7 +56,7 @@ Consequences of that substitution, which trip up readers:
 
 ## Shipped
 
-Every item below is in the installed product as of 2.17.2. `CLAUDE.md` has the
+Every item below is in the installed product as of 2.18.0. `CLAUDE.md` has the
 detail and the failure modes.
 
 - JSON document store: collections, version history, field-level encryption, TTL
@@ -70,6 +70,8 @@ detail and the failure modes.
   `project:_name` refused, history pruned when `maxVersions` is lowered (2.17.1);
   per-file history locks, a reseal only where something was rewritten,
   vectors accepted in encrypted collections (2.17.2)
+- Typed range filters: GT/GTE/LT/LTE match number~number and string~string
+  only, scan and index alike (2.18.0)
 - Optional per-collection JSON Schema (enforce/audit, existing rows checked
   first, suggested from data) (2.16.0)
 - Independent client and server releases: `GetServerInfo` capability
@@ -386,6 +388,11 @@ joins; see 5c), which does not fit in 10 s. Run the container with
   cannot hold a start; switching to `deb-systemd-invoke` would let an
   operator stage an install without triggering a boot-time migration (today:
   mask the unit).
+- **Sort and filter disagree about an ABSENT field:** a sort places rows
+  without the field last ascending (first descending), while every filter but
+  `EXISTS false` excludes them. A paginated, sorted and filtered list view can
+  surface rows its filter would reject at the edges. Decide one rule for both
+  (e.g. absent sorts like null, first ascending) - a behaviour change.
 - Collection schemas cannot be declared in a migration file yet (the
   existing-row check lives in the SetCollectionSchema handler).
 - ~~**Bogus index declarations on a production instance (found 2026-10-09, predates 2.14.0):**~~ removed

+ 21 - 0
docs/integration-guide.md

@@ -1674,6 +1674,27 @@ auto docs = db.find("users", opts);
 | `FilterOp::REGEX`     | field matches the supplied regex pattern                       | string                      |
 | `FilterOp::SEARCH`    | full-text search across document ID and string fields          | string                      |
 
+**Comparison rules (2.18.0+, capability `typed_range_filters`):**
+- **GT/GTE/LT/LTE match only number-to-number or string-to-string.** A field
+  holding null, a boolean, an object or an array, or a value of the other kind
+  than the bound, never satisfies a range; a null or boolean bound matches
+  nothing. `5` and `5.0` are both numbers. Strings compare byte-wise.
+- **Before 2.18.0** ranges compared ACROSS JSON types in the order
+  null < boolean < number < string, so an explicit `null` or `true` matched
+  `year <= 2025` and the string `"1900"` matched `year >= 2025`. A single bound
+  silently over-matched; anything that relied on that was already wrong.
+- **An absent field** never matches EQ, NE, a range, IN, CONTAINS or REGEX
+  (unchanged); only `EXISTS false` selects it. An explicit `null` is present:
+  `EXISTS true` matches it, and `EQ null` matches it.
+- **EQ/NE** keep JSON equality: NE matches values of another type.
+- **Sort order is unchanged and differs from filtering:** ascending puts null
+  first and rows WITHOUT the field last (descending the reverse). A list view
+  that sorts and filters on the same field should bound the filter on both
+  sides, so rows the sort would place at either end are excluded consistently.
+- **The value's JSON type is what you sent.** A filter value parsed from text
+  can change type with its content (`2026.1` is a number, `2026.1.3` a string),
+  and a number never matches a string under these rules.
+
 Note: the old `_search` magic field name that auto-selected SEARCH is no
 longer special — use `FilterOp::SEARCH` explicitly instead.
 

+ 2 - 1
service/src/server_capabilities.hpp

@@ -18,7 +18,7 @@
 
 namespace smartbotic::database {
 
-inline constexpr std::array<std::string_view, 23> kServerCapabilities = {
+inline constexpr std::array<std::string_view, 24> kServerCapabilities = {
     "projects",              // 2.3.0  <project>:<collection> namespaces
     "access_policy",         // 2.7.0  row/column security
     "query_projection",      // 2.7.1  FindRequest.projection
@@ -42,6 +42,7 @@ inline constexpr std::array<std::string_view, 23> kServerCapabilities = {
     "client_version_header", // 2.15.0 the server reads sbdb-client-version
     "collection_schema",     // 2.16.0 Set/Get/SuggestCollectionSchema, schema_violation
     "encryption_at_rest",    // 2.17.0 encrypted collections encrypt, VerifyEncryption, encrypted_field
+    "typed_range_filters",   // 2.18.0 GT/GTE/LT/LTE match number~number and string~string only
 };
 
 }  // namespace smartbotic::database

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

@@ -1233,6 +1233,12 @@ LmdbDocumentStore::lookupIndexRangeTxn(ReadTxn& rtxn,
     if (op != Op::GT && op != Op::GTE && op != Op::LT && op != Op::LTE) {
         return std::nullopt;
     }
+    // v2.18.0 - a range compare holds only number-to-number or
+    // string-to-string (filter_eval::comparableForRange). A null or boolean
+    // bound matches nothing, so the index must not serve it: the ordered
+    // range plan (rangeOrderedFromIndex) trusts these postings without
+    // re-judging them.
+    if (!value.is_number() && !value.is_string()) return std::nullopt;
     const auto bound = encode_index_key(value);
     if (!bound) return std::nullopt;
 

+ 16 - 4
service/src/storage/filter_eval.hpp

@@ -47,6 +47,18 @@ getJsonPath(const nlohmann::json& obj, const std::string& path) {
     return std::optional<nlohmann::json>(*current);
 }
 
+// v2.18.0 - a RANGE comparison (GT/GTE/LT/LTE) holds only between two
+// numbers or two strings, as in SQL where NULL and a type mismatch never
+// satisfy a comparison. Before 2.18.0 these used nlohmann's operators, which
+// order ACROSS types (null < boolean < number < string), so an explicit null
+// or `true` matched `year <= 2025` and the string "1900" matched
+// `year >= 2025` - silent over-matching, found by a consumer whose access gate
+// used a single bound. EQ/NE keep JSON equality (5 == 5.0; NE matches a
+// different type).
+inline bool comparableForRange(const nlohmann::json& a, const nlohmann::json& b) {
+    return (a.is_number() && b.is_number()) || (a.is_string() && b.is_string());
+}
+
 // Compare two JSON values under one of the relational operators. Returns
 // false for non-relational ops (the caller must dispatch those separately).
 inline bool compareJson(const nlohmann::json& a,
@@ -56,10 +68,10 @@ inline bool compareJson(const nlohmann::json& a,
     switch (op) {
         case FilterOp::EQ:  return a == b;
         case FilterOp::NE:  return a != b;
-        case FilterOp::GT:  return a > b;
-        case FilterOp::GTE: return a >= b;
-        case FilterOp::LT:  return a < b;
-        case FilterOp::LTE: return a <= b;
+        case FilterOp::GT:  return comparableForRange(a, b) && a > b;
+        case FilterOp::GTE: return comparableForRange(a, b) && a >= b;
+        case FilterOp::LT:  return comparableForRange(a, b) && a < b;
+        case FilterOp::LTE: return comparableForRange(a, b) && a <= b;
         default:            return false;
     }
 }

+ 1 - 0
tests/load_test/test_server_info.cpp

@@ -43,6 +43,7 @@ static const std::vector<const char*> kAllCaps = {
     Cap::kCompositeUnique, Cap::kBatchDeleteIds, Cap::kEventActor, Cap::kVectorReadback,
     Cap::kExportCollection, Cap::kWriteSizeGuard, Cap::kFilteredSimilarity, Cap::kServerInfo,
     Cap::kClientVersionHeader, Cap::kCollectionSchema, Cap::kEncryptionAtRest,
+    Cap::kTypedRangeFilters,
 };
 
 // Ordinary calls a client of any version makes; they must work across versions.

+ 124 - 0
tests/load_test/test_typed_ranges.cpp

@@ -0,0 +1,124 @@
+// v2.18.0 - range filters (GT/GTE/LT/LTE) match only number-to-number or
+// string-to-string. Before 2.18.0 they compared ACROSS JSON types (null <
+// boolean < number < string): an explicit null or `true` matched
+// `year <= 2025`, and the string "1900" matched `year >= 2025` - silent
+// over-matching, found by a consumer whose access gate used a single bound.
+// EQ/NE and sort order are unchanged. Every case runs twice: on a collection
+// without an index (scan) and with one (the index plans must agree).
+
+#include <smartbotic/database/client.hpp>
+
+#include <algorithm>
+#include <iostream>
+#include <set>
+#include <string>
+
+using namespace smartbotic::database;
+using F = Client::Filter;
+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::set<std::string> ids(Client& c, const std::string& coll, std::vector<F> f) {
+    Client::QueryOptions o;
+    o.filters = std::move(f);
+    std::set<std::string> out;
+    for (auto& d : c.find(coll, o)) out.insert(d["_id"].get<std::string>());
+    return out;
+}
+
+static std::string show(const std::set<std::string>& s) {
+    std::string r;
+    for (const auto& x : s) r += (r.empty() ? "" : " ") + x;
+    return "{" + r + "}";
+}
+
+int main() {
+    Client::Config cfg;
+    cfg.address = "127.0.0.1:9034";
+    cfg.writeRetries = 0;
+    Client c(cfg);
+    c.connect();
+    ck(c.serverSupports(Client::Capability::kTypedRangeFilters), "server reports typed_range_filters");
+    for (std::string coll : {"scan", "idx", "bools"}) {
+        if (coll == "bools") continue;
+        c.insert(coll, {{"year", nullptr}}, "null");
+        c.insert(coll, {{"other", 1}}, "absent");
+        c.insert(coll, {{"year", 2024}}, "n2024");
+        c.insert(coll, {{"year", 2030.5}}, "n2030");
+        c.insert(coll, {{"year", "1900"}}, "s1900");
+        c.insert(coll, {{"year", "2100"}}, "s2100");
+        c.insert(coll, {{"year", true}}, "bool");
+    }
+    ck(c.createIndex("idx", "year"), "index declared");
+
+    for (std::string coll : {"scan", "idx"}) {
+        const std::string t = coll + ": ";
+        auto r = ids(c, coll, {F::lte("year", 2025)});
+        ck(r == std::set<std::string>{"n2024"}, t + "lte 2025 matches only the number below (got " + show(r) + ")");
+        r = ids(c, coll, {F::lte("year", 1900)});
+        ck(r.empty(), t + "lte 1900 matches nothing - not null, not true (got " + show(r) + ")");
+        r = ids(c, coll, {F::gte("year", 2025)});
+        ck(r == std::set<std::string>{"n2030"}, t + "gte 2025 does not match the string \"1900\" (got " + show(r) + ")");
+        r = ids(c, coll, {F::gt("year", 0), F::lt("year", 3000)});
+        ck(r == std::set<std::string>{"n2024", "n2030"}, t + "a numeric pair of bounds (got " + show(r) + ")");
+        r = ids(c, coll, {F::gte("year", "2000")});
+        ck(r == std::set<std::string>{"s2100"}, t + "a string bound compares strings only (got " + show(r) + ")");
+        r = ids(c, coll, {F::lt("year", "2000")});
+        ck(r == std::set<std::string>{"s1900"}, t + "string lt (got " + show(r) + ")");
+        r = ids(c, coll, {F::lte("year", nullptr)});
+        ck(r.empty(), t + "a null bound matches nothing (got " + show(r) + ")");
+        r = ids(c, coll, {F::gte("year", false)});
+        ck(r.empty(), t + "a boolean bound matches nothing (got " + show(r) + ")");
+        // Unchanged: equality, NE, EXISTS.
+        r = ids(c, coll, {F::eq("year", nullptr)});
+        ck(r == std::set<std::string>{"null"}, t + "EQ null still matches the explicit null (got " + show(r) + ")");
+        r = ids(c, coll, {F::ne("year", 2024)});
+        ck(r == std::set<std::string>{"null", "n2030", "s1900", "s2100", "bool"},
+           t + "NE keeps JSON inequality, absent excluded (got " + show(r) + ")");
+        ck(c.count(coll, {F::lte("year", 2025)}) == 1, t + "count agrees with find");
+        // Unchanged: sort order (null lowest, absent last ascending).
+        Client::QueryOptions o;
+        o.sortField = "year";
+        std::string order;
+        for (auto& d : c.find(coll, o)) order += d["_id"].get<std::string>() + " ";
+        ck(order == "null bool n2024 n2030 s1900 s2100 absent ",
+           t + "sort order is unchanged (got " + order + ")");
+        // The ordered range plan (range + sort on the same field).
+        Client::QueryOptions ro;
+        ro.filters = {F::gte("year", 2000)};
+        ro.sortField = "year";
+        order.clear();
+        for (auto& d : c.find(coll, ro)) order += d["_id"].get<std::string>() + " ";
+        ck(order == "n2024 n2030 ", t + "range + sort returns the numbers only, in order (got " + order + ")");
+    }
+
+    // Single-type indexes with a matching null / boolean bound: the index range
+    // plan would serve them, and its ordered variant (range + sort on the same
+    // field) trusts postings WITHOUT re-judging. (true and false carry different
+    // index tags, so the index must hold only one of them to be single-type.)
+    c.insert("trues", {{"flag", true}}, "t1");
+    c.insert("trues", {{"flag", true}}, "t2");
+    c.createIndex("trues", "flag");
+    c.insert("nulls", {{"v", nullptr}}, "n1");
+    c.insert("nulls", {{"v", nullptr}}, "n2");
+    c.createIndex("nulls", "v");
+    {
+        Client::QueryOptions o;
+        o.filters = {F::gte("flag", true)};
+        o.sortField = "flag";
+        auto r = c.find("trues", o);
+        ck(r.empty(), "an all-true index with a boolean bound + sort returns nothing (got " +
+                          std::to_string(r.size()) + ")");
+        Client::QueryOptions n;
+        n.filters = {F::lte("v", nullptr)};
+        n.sortField = "v";
+        auto rn = c.find("nulls", n);
+        ck(rn.empty(), "an all-null index with a null bound + sort returns nothing (got " +
+                           std::to_string(rn.size()) + ")");
+    }
+
+    std::cout << "typed ranges: " << pass << " passed, " << fail << " failed\n";
+    return fail == 0 ? 0 : 1;
+}

+ 42 - 0
tests/load_test/test_typed_ranges.sh

@@ -0,0 +1,42 @@
+#!/usr/bin/env bash
+# v2.18.0 e2e - range filters compare number-to-number and string-to-string
+# only; null, booleans and type mismatches never satisfy a range. Scan and
+# index plans must agree.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-typed-ranges
+PORT=9034
+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_typed_ranges.cpp \
+    -I"$ROOT/client/include" -I"$ROOT/build/client" \
+    -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt -pthread
+
+"$ROOT/build/service/smartbotic-database" --config "$DIR/config.json" > "$DIR/server.log" 2>&1 &
+SERVER_PID=$!
+trap 'kill $SERVER_PID 2>/dev/null || true; wait $SERVER_PID 2>/dev/null || true' EXIT
+for _ in $(seq 1 120); do grep -q "Notified systemd: READY" "$DIR/server.log" && break; sleep 0.5; done
+
+LD_LIBRARY_PATH="$ROOT/build/client" "$DIR/t" 2>&1 | grep -v '\[error\]\|\[info\]'
+rc=${PIPESTATUS[0]}
+[[ $rc -eq 0 ]] && echo "OK - typed ranges e2e passed" || { echo "FAILED"; tail -20 "$DIR/server.log"; }
+exit $rc

Alguns arquivos não foram mostrados porque muitos arquivos mudaram nesse diff