Răsfoiți Sursa

fix: 2.20.0 - REGEX filters run on RE2 (security, out of cycle)

std::regex backtracks: a caller-supplied pattern such as (a+)+$ tied up a
server thread past the client's deadline on one long value. RE2 is linear,
UTF-8 aware and accepts (?i); a pattern is compiled once per thread instead
of once per row. An invalid pattern is refused with INVALID_ARGUMENT, reason
invalid_pattern, on find/count/similaritySearch/createView instead of
answering "no match". Backreferences and lookaround are now refused.
Capability re2_regex_filters.
fszontagh 1 lună în urmă
părinte
comite
72dea1e744

+ 18 - 0
CHANGELOG.md

@@ -12,7 +12,25 @@ consumer-facing usage is in `docs/integration-guide.md`.
 
 
 ## Unreleased
 ## Unreleased
 
 
+## 2.20.0 - 2026-10-16 (out of cycle: security)
+### Fixed
+- **[server]** REGEX filters ran on `std::regex`, which backtracks: a
+  caller-supplied pattern such as `(a+)+$` could tie up a server thread for
+  minutes against one long value (any key holder with a read grant). They now
+  run on RE2, in time linear in the value, compiled once per query instead of
+  once per row. Capability `re2_regex_filters`.
+- **[server]** A REGEX pattern that does not compile was answered as "no
+  match"; find, count, similaritySearch and createView now refuse it with
+  INVALID_ARGUMENT, reason `invalid_pattern` (reading the reason on a read call
+  needs a 2.17.0+ client).
+- **[server]** Character classes over non-ASCII letters matched bytes: `[áÁ]`
+  now matches one character, so `sz[áÁ]mfejt` matches and `[öÖ]` no longer
+  matches unrelated accented text. `(?i)` works as a case-insensitive flag.
 ### Changed
 ### Changed
+- **[server]** ⚠ Patterns with backreferences or lookaround are refused
+  (`invalid_pattern`): RE2 has neither. A view stored with such a pattern
+  matches nothing; recreate it.
+- **[client]** `Client::Capability::kRe2RegexFilters`.
 - Releases follow a weekly Tuesday cadence; hotfixes only for security, data
 - Releases follow a weekly Tuesday cadence; hotfixes only for security, data
   loss and regressions of the latest release. (process, no code change)
   loss and regressions of the latest release. (process, no code change)
 
 

Fișier diff suprimat deoarece este prea mare
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.19.0
+2.20.0

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

@@ -342,6 +342,12 @@ public:
         /// no capability: every server sends it, and this client attaches it
         /// no capability: every server sends it, and this client attaches it
         /// to get/find/export results when a document has an expiry.
         /// to get/find/export results when a document has an expiry.
         static constexpr const char* kDocumentExpiresAt = "document_expires_at";
         static constexpr const char* kDocumentExpiresAt = "document_expires_at";
+        /// 2.20.0: REGEX filters use RE2 syntax (linear time, UTF-8 aware,
+        /// `(?i)` works; no backreferences or lookaround), and a pattern that
+        /// does not compile is refused with INVALID_ARGUMENT, reason
+        /// `invalid_pattern`. Older servers used std::regex (ECMAScript) and
+        /// answered an invalid pattern with an empty result.
+        static constexpr const char* kRe2RegexFilters = "re2_regex_filters";
     };
     };
 
 
     struct ServerInfo {
     struct ServerInfo {

+ 2 - 0
docs/ROADMAP.md

@@ -128,6 +128,8 @@ detail and the failure modes.
   values / min / max. A measured selectivity guard means declaring an index
   values / min / max. A measured selectivity guard means declaring an index
   cannot make a query slower. CLI: `indexes`, `index-create`, `index-drop`,
   cannot make a query slower. CLI: `indexes`, `index-create`, `index-drop`,
   `index-values`
   `index-values`
+- REGEX filters on RE2: linear time, UTF-8 character classes, `(?i)`, an
+  invalid pattern refused with `invalid_pattern` (2.20.0)
 
 
 ---
 ---
 
 

+ 35 - 1
docs/integration-guide.md

@@ -1744,7 +1744,7 @@ auto docs = db.find("users", opts);
 | `FilterOp::IN`        | field value appears in the supplied array                      | JSON array                  |
 | `FilterOp::IN`        | field value appears in the supplied array                      | JSON array                  |
 | `FilterOp::CONTAINS`  | field (array) contains the supplied value                      | any JSON                    |
 | `FilterOp::CONTAINS`  | field (array) contains the supplied value                      | any JSON                    |
 | `FilterOp::EXISTS`    | field presence check (`true` = must exist, `false` = must not) | bool                        |
 | `FilterOp::EXISTS`    | field presence check (`true` = must exist, `false` = must not) | bool                        |
-| `FilterOp::REGEX`     | field matches the supplied regex pattern                       | string                      |
+| `FilterOp::REGEX`     | field matches the supplied RE2 pattern (see below)             | string                      |
 | `FilterOp::SEARCH`    | full-text search across document ID and string fields          | string                      |
 | `FilterOp::SEARCH`    | full-text search across document ID and string fields          | string                      |
 
 
 **Comparison rules (2.18.0+, capability `typed_range_filters`):**
 **Comparison rules (2.18.0+, capability `typed_range_filters`):**
@@ -1768,6 +1768,40 @@ auto docs = db.find("users", opts);
   can change type with its content (`2026.1` is a number, `2026.1.3` a string),
   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.
   and a number never matches a string under these rules.
 
 
+**REGEX (2.20.0+, capability `re2_regex_filters`):**
+- **Patterns use RE2 syntax** (the same engine as a collection schema's
+  `pattern`). Matching is a SEARCH: the pattern may match anywhere unless you
+  anchor it with `^`/`$`. A value that is not a string never matches.
+- **Matching takes time linear in the value's length,** whatever the pattern.
+  Before 2.20.0 the server used `std::regex`, which backtracks: a
+  caller-supplied pattern such as `(a+)+$` against a long run of `a` could tie
+  up a server thread for minutes (measured: past a 20 s deadline on a
+  5,001-byte value, still running after the client had given up).
+- **UTF-8 aware:** `[áÁ]` matches one character and `.` matches `á`. Under
+  `std::regex` a character class matched single bytes, so `sz[áÁ]mfejt` never
+  matched `számfejt` and `[öÖ]` matched any text holding another accented
+  letter (they share a lead byte).
+- **`(?i)` makes a pattern case-insensitive**, non-ASCII letters included
+  (`(?i)BÉR` matches `bér`). There is no separate flag.
+- **A pattern that does not compile is refused** by find, count,
+  similaritySearch and createView: INVALID_ARGUMENT, reason `invalid_pattern`,
+  `fields` = the filter's field, and the message carries RE2's error. Before
+  2.20.0 it was silently treated as "no match", so a typo looked like an empty
+  result. To read the `reason` from a READ call (find, count,
+  similaritySearch) a consumer also needs a 2.17.0 or newer client library;
+  older clients see the InvalidArgument code without the detail.
+- **⚠ Breaking for patterns that used backreferences (`\1`) or lookaround
+  (`(?=...)`, `(?!...)`, `(?<=...)`):** RE2 has neither (that is what keeps it
+  linear), so they are now refused with `invalid_pattern`. Rewrite them, or
+  filter in your own code.
+- **A view or policy row predicate stored before 2.20.0** with a pattern RE2
+  cannot compile is NOT refused at read time (it was set by an administrator,
+  and refusing would break every read of the view): it matches nothing, as an
+  invalid pattern always did. Recreate such a view.
+- **To search for user input literally,** escape it before putting it in a
+  pattern (a backslash before each of `.^$|()[]{}*+?\`), and add `(?i)` for a
+  case-insensitive search box.
+
 Note: the old `_search` magic field name that auto-selected SEARCH is no
 Note: the old `_search` magic field name that auto-selected SEARCH is no
 longer special — use `FilterOp::SEARCH` explicitly instead.
 longer special — use `FilterOp::SEARCH` explicitly instead.
 
 

+ 34 - 0
service/src/database_grpc_impl.cpp

@@ -14,6 +14,7 @@
 #include "storage/document_store.hpp"
 #include "storage/document_store.hpp"
 #include "storage/document_store_lmdb.hpp"
 #include "storage/document_store_lmdb.hpp"
 #include "storage/project_store.hpp"
 #include "storage/project_store.hpp"
+#include "storage/regex_filter.hpp"
 #include "relations/relation_enforcement.hpp"
 #include "relations/relation_enforcement.hpp"
 #include "relations/relation_cascade.hpp"
 #include "relations/relation_cascade.hpp"
 #include "json_parse.hpp"
 #include "json_parse.hpp"
@@ -476,6 +477,32 @@ grpc::Status DatabaseGrpcImpl::refuseEncryptedFields(
                         "in a non-sensitive field.");
                         "in a non-sensitive field.");
 }
 }
 
 
+// v2.20.0 - see the header. Validated before any scan starts, on the
+// CALLER's filters only: a view's `where` and a policy row predicate were set
+// by an administrator, and a stored pattern that no longer compiles (one
+// written for std::regex before 2.20.0) fails closed at evaluation instead of
+// refusing every read of that view.
+grpc::Status DatabaseGrpcImpl::refuseInvalidPatterns(
+    grpc::ServerContext* context, const std::vector<Filter>& filters) {
+    std::vector<std::string> bad;
+    std::string firstError;
+    for (const auto& f : filters) {
+        if (f.op != FilterOp::REGEX) continue;
+        std::string err = f.value.is_string()
+            ? smartbotic::db::storage::regex_filter::validate(f.value.get<std::string>())
+            : std::string("the pattern must be a string");
+        if (err.empty()) continue;
+        if (firstError.empty()) firstError = f.field + ": " + err;
+        bad.push_back(f.field);
+    }
+    if (bad.empty()) return grpc::Status::OK;
+    attachErrorDetail(context, {{"reason", "invalid_pattern"}, {"fields", bad}});
+    return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+                        "invalid regex pattern (" + firstError +
+                        "). Patterns use RE2 syntax: no backreferences or lookaround; "
+                        "(?i) makes a match case-insensitive.");
+}
+
 grpc::Status DatabaseGrpcImpl::Insert(
 grpc::Status DatabaseGrpcImpl::Insert(
     grpc::ServerContext* context,
     grpc::ServerContext* context,
     const pb::InsertRequest* request,
     const pb::InsertRequest* request,
@@ -1612,6 +1639,7 @@ grpc::Status DatabaseGrpcImpl::Find(
     }
     }
 
 
     Query query = fromProtoQuery(*request);
     Query query = fromProtoQuery(*request);
+    if (auto st = refuseInvalidPatterns(context, query.filters); !st.ok()) return st;
 
 
     if (view) {
     if (view) {
         // AND-merge: append view's where filters to the caller's filters
         // AND-merge: append view's where filters to the caller's filters
@@ -1729,6 +1757,7 @@ grpc::Status DatabaseGrpcImpl::Count(
     }
     }
     // Append caller's filters (AND-merge; order doesn't matter for AND)
     // Append caller's filters (AND-merge; order doesn't matter for AND)
     auto callerFilters = fromProtoFilters(request->filters());
     auto callerFilters = fromProtoFilters(request->filters());
+    if (auto st = refuseInvalidPatterns(context, callerFilters); !st.ok()) return st;
     for (auto& f : callerFilters) {
     for (auto& f : callerFilters) {
         filters.push_back(std::move(f));
         filters.push_back(std::move(f));
     }
     }
@@ -1834,6 +1863,7 @@ grpc::Status DatabaseGrpcImpl::SimilaritySearch(
             return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
             return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
                                 std::string("Bad filter value: ") + e.what());
                                 std::string("Bad filter value: ") + e.what());
         }
         }
+        if (auto st = refuseInvalidPatterns(context, filters); !st.ok()) return st;
         if (auto st = rejectMaskedFilters(filters, dec.mask); !st.ok()) return st;
         if (auto st = rejectMaskedFilters(filters, dec.mask); !st.ok()) return st;
         if (auto st = refuseEncryptedFields(context, collection, filters, {}, "filter");
         if (auto st = refuseEncryptedFields(context, collection, filters, {}, "filter");
             !st.ok()) {
             !st.ok()) {
@@ -3693,6 +3723,10 @@ grpc::Status DatabaseGrpcImpl::CreateView(
             v.defaultSort = s;
             v.defaultSort = s;
         }
         }
 
 
+        // v2.20.0 - a view whose REGEX cannot compile would match nothing,
+        // forever; refuse it like a caller's filter.
+        if (auto st = refuseInvalidPatterns(context, v.where); !st.ok()) return st;
+
         std::string err;
         std::string err;
         bool ok = view_manager_.createView(v, err);
         bool ok = view_manager_.createView(v, err);
         response->set_success(ok);
         response->set_success(ok);

+ 6 - 0
service/src/database_grpc_impl.hpp

@@ -672,6 +672,12 @@ private:
                                        const std::vector<smartbotic::database::Filter>& filters,
                                        const std::vector<smartbotic::database::Filter>& filters,
                                        const std::vector<std::string>& fields,
                                        const std::vector<std::string>& fields,
                                        const std::string& what);
                                        const std::string& what);
+
+    // v2.20.0 - a REGEX filter whose pattern RE2 cannot compile is refused
+    // (INVALID_ARGUMENT, reason `invalid_pattern`, `fields` = the filter
+    // fields) instead of silently matching nothing.
+    grpc::Status refuseInvalidPatterns(grpc::ServerContext* context,
+                                       const std::vector<smartbotic::database::Filter>& filters);
     std::chrono::steady_clock::time_point startTime_ = std::chrono::steady_clock::now();
     std::chrono::steady_clock::time_point startTime_ = std::chrono::steady_clock::now();
 
 
     // v1.6.2 — per-RPC-type streaming concurrency limits (set by DatabaseService
     // v1.6.2 — per-RPC-type streaming concurrency limits (set by DatabaseService

+ 2 - 1
service/src/server_capabilities.hpp

@@ -18,7 +18,7 @@
 
 
 namespace smartbotic::database {
 namespace smartbotic::database {
 
 
-inline constexpr std::array<std::string_view, 25> kServerCapabilities = {
+inline constexpr std::array<std::string_view, 26> kServerCapabilities = {
     "projects",              // 2.3.0  <project>:<collection> namespaces
     "projects",              // 2.3.0  <project>:<collection> namespaces
     "access_policy",         // 2.7.0  row/column security
     "access_policy",         // 2.7.0  row/column security
     "query_projection",      // 2.7.1  FindRequest.projection
     "query_projection",      // 2.7.1  FindRequest.projection
@@ -44,6 +44,7 @@ inline constexpr std::array<std::string_view, 25> kServerCapabilities = {
     "encryption_at_rest",    // 2.17.0 encrypted collections encrypt, VerifyEncryption, encrypted_field
     "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
     "typed_range_filters",   // 2.18.0 GT/GTE/LT/LTE match number~number and string~string only
     "document_expires_at",   // 2.19.0 _expires_at filterable; reserved in write bodies
     "document_expires_at",   // 2.19.0 _expires_at filterable; reserved in write bodies
+    "re2_regex_filters",     // 2.20.0 REGEX filters use RE2 (UTF-8, linear); invalid_pattern refusals
 };
 };
 
 
 }  // namespace smartbotic::database
 }  // namespace smartbotic::database

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

@@ -19,7 +19,6 @@
 #include <cctype>
 #include <cctype>
 #include <functional>
 #include <functional>
 #include <optional>
 #include <optional>
-#include <regex>
 #include <sstream>
 #include <sstream>
 #include <string>
 #include <string>
 #include <vector>
 #include <vector>
@@ -27,6 +26,7 @@
 #include <nlohmann/json.hpp>
 #include <nlohmann/json.hpp>
 
 
 #include "document.hpp"
 #include "document.hpp"
+#include "storage/regex_filter.hpp"
 
 
 namespace smartbotic::db::storage::filter_eval {
 namespace smartbotic::db::storage::filter_eval {
 
 
@@ -214,12 +214,9 @@ inline bool matchesFiltersResolved(
             }
             }
             case FilterOp::REGEX:
             case FilterOp::REGEX:
                 if (!value || !value->is_string() || !filter.value.is_string()) return false;
                 if (!value || !value->is_string() || !filter.value.is_string()) return false;
-                try {
-                    std::regex re(filter.value.get<std::string>());
-                    if (!std::regex_search(value->get<std::string>(), re)) return false;
-                } catch (const std::regex_error&) {
-                    return false;
-                }
+                // v2.20.0 - RE2, compiled once per thread (regex_filter.hpp).
+                if (!regex_filter::search(filter.value.get<std::string>(),
+                                          value->get<std::string>())) return false;
                 break;
                 break;
             case FilterOp::SEARCH:
             case FilterOp::SEARCH:
                 // Unreachable through this entry point: a SEARCH filter needs the
                 // Unreachable through this entry point: a SEARCH filter needs the

+ 80 - 0
service/src/storage/regex_filter.hpp

@@ -0,0 +1,80 @@
+// v2.20.0 - the REGEX filter operator runs on RE2, not std::regex.
+//
+// A REGEX pattern is caller-supplied (any key holder with a read grant) and
+// runs against every row a scan visits, inside an LMDB read transaction.
+// std::regex backtracks: `(a+)+$` against a failing subject of 26 bytes took
+// 11 s in isolation and doubles per byte, and libstdc++'s executor recurses, so
+// a long subject can overflow the stack. RE2 matches in time linear in the
+// subject and never recurses - the reason the 2.16.0 schema `pattern` keyword
+// already chose it (schema/json_schema.hpp). One engine for both now, so a
+// pattern is accepted or refused the same way in either place.
+//
+// Also different from std::regex, on purpose:
+//   - UTF-8: a character class over non-ASCII letters (`[áÁ]`) matches one
+//     CHARACTER; std::regex matched one byte, so `sz[áÁ]mfejt` never matched
+//     and `[öÖ]` matched any text sharing the lead byte 0xC3.
+//   - `(?i)` (and the other RE2 flags) work; ECMAScript syntax rejected them.
+//   - No backreferences or lookaround - RE2 refuses them, which is what makes
+//     it linear.
+//   - A pattern that does not compile is REFUSED by the handlers
+//     (INVALID_ARGUMENT, reason `invalid_pattern`); before 2.20.0 it was
+//     swallowed and every row reported "no match".
+//
+// Header-only. Compiled patterns are cached per thread, so a scan compiles a
+// pattern once rather than once per row (std::regex was rebuilt per row).
+
+#pragma once
+
+#include <cstddef>
+#include <memory>
+#include <string>
+#include <unordered_map>
+
+#include <re2/re2.h>
+
+namespace smartbotic::db::storage::regex_filter {
+
+// Per-pattern memory budget for RE2's compiled program and lazy DFA. Past it
+// the DFA falls back to the NFA (still linear, slower), and a pattern whose
+// program alone exceeds it fails to compile (`invalid_pattern`). Kept below
+// RE2's 8 MB default because the cache below holds many per thread.
+inline constexpr int64_t kMaxMemBytes = 1 << 20;
+inline constexpr std::size_t kCacheEntriesPerThread = 64;
+
+struct Compiled {
+    std::shared_ptr<const re2::RE2> re;  // null when the pattern did not compile
+    std::string error;
+};
+
+inline Compiled compileUncached(const std::string& pattern) {
+    re2::RE2::Options opt;
+    opt.set_log_errors(false);
+    opt.set_max_mem(kMaxMemBytes);
+    auto re = std::make_shared<const re2::RE2>(pattern, opt);
+    if (!re->ok()) return {nullptr, re->error()};
+    return {std::move(re), {}};
+}
+
+// Compiled form of `pattern`, cached per thread (a failure is cached too, so a
+// bad pattern is not recompiled for every row before a handler refuses it).
+inline const Compiled& compile(const std::string& pattern) {
+    thread_local std::unordered_map<std::string, Compiled> cache;
+    if (auto it = cache.find(pattern); it != cache.end()) return it->second;
+    if (cache.size() >= kCacheEntriesPerThread) cache.clear();
+    return cache.emplace(pattern, compileUncached(pattern)).first->second;
+}
+
+// The compile error for `pattern`, or empty when it is valid.
+inline std::string validate(const std::string& pattern) {
+    return compile(pattern).error;
+}
+
+// True iff `pattern` matches anywhere in `subject` (search semantics, as
+// std::regex_search had). An invalid pattern matches nothing (fail closed; the
+// handlers refuse it before a scan starts).
+inline bool search(const std::string& pattern, const std::string& subject) {
+    const Compiled& c = compile(pattern);
+    return c.re && re2::RE2::PartialMatch(subject, *c.re);
+}
+
+}  // namespace smartbotic::db::storage::regex_filter

+ 13 - 0
tests/CMakeLists.txt

@@ -937,3 +937,16 @@ endif()
 target_link_libraries(test_history_audit_scan PRIVATE Threads::Threads ${yyjson_LIBRARIES})
 target_link_libraries(test_history_audit_scan PRIVATE Threads::Threads ${yyjson_LIBRARIES})
 target_compile_options(test_history_audit_scan PRIVATE -UNDEBUG)
 target_compile_options(test_history_audit_scan PRIVATE -UNDEBUG)
 add_test(NAME test_history_audit_scan COMMAND test_history_audit_scan)
 add_test(NAME test_history_audit_scan COMMAND test_history_audit_scan)
+
+# v2.20.0 - filter_eval.hpp (REGEX filters) uses RE2, and memory_store.cpp,
+# document_store_lmdb.cpp and relation_cascade.cpp include it, so every test
+# that compiles one of them needs RE2. Linked to every target here rather than
+# tracking which ones do.
+get_property(_sbdb_test_targets DIRECTORY PROPERTY BUILDSYSTEM_TARGETS)
+foreach(_t IN LISTS _sbdb_test_targets)
+    get_target_property(_type ${_t} TYPE)
+    if(_type STREQUAL "EXECUTABLE")
+        target_include_directories(${_t} PRIVATE ${TEST_RE2_INCLUDE_DIR})
+        target_link_libraries(${_t} PRIVATE ${TEST_RE2_LIBRARY})
+    endif()
+endforeach()

+ 135 - 0
tests/load_test/test_regex_filters.cpp

@@ -0,0 +1,135 @@
+// v2.20.0 - REGEX filters run on RE2. Reported by smartbotic-vectorapi from a
+// consumer's measurements: on std::regex (1) a pattern that did not compile
+// was swallowed and answered "no match", (2) `(?i)` was one such pattern,
+// (3) a character class over non-ASCII letters matched bytes, not characters
+// (`sz[áÁ]mfejt` never matched, `[öÖ]` matched text with neither), and
+// (4) a caller-supplied pattern backtracked exponentially per row of a scan.
+
+#include <smartbotic/database/client.hpp>
+
+#include <chrono>
+#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 + "}";
+}
+
+// Runs `call`, expecting INVALID_ARGUMENT with reason invalid_pattern naming `field`.
+template <typename Fn>
+static void refused(Fn call, const std::string& field, const std::string& what) {
+    try {
+        call();
+        ck(false, what + ": refused (it was answered)");
+    } catch (const Client::Error& e) {
+        ck(e.code() == Client::ErrorCode::InvalidArgument, what + ": InvalidArgument (" + e.what() + ")");
+        const auto* d = Client::errorDetail(e);
+        ck(d && d->reason == "invalid_pattern", what + ": reason invalid_pattern");
+        ck(d && d->fields == std::vector<std::string>{field}, what + ": fields names " + field);
+    }
+}
+
+static double seconds(std::chrono::steady_clock::time_point t0) {
+    return std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+}
+
+int main() {
+    Client::Config cfg;
+    cfg.address = "127.0.0.1:9036";
+    cfg.writeRetries = 0;
+    cfg.timeoutMs = 20000;
+    Client c(cfg);
+    ck(c.connect(), "connect");
+    ck(c.serverSupports(Client::Capability::kRe2RegexFilters), "server reports re2_regex_filters");
+
+    c.createCollection("t", 0, false, 0, 2);
+    c.insert("t", {{"text", "Dolgozói bérszámfejtés"}, {"_vector", std::vector<float>{1, 0}}}, "hu");
+    c.insert("t", {{"text", "öröm és bánat"}, {"_vector", std::vector<float>{0, 1}}}, "oe");
+    c.insert("t", {{"text", "plain ascii 2024"}, {"_vector", std::vector<float>{1, 1}}}, "ascii");
+    c.insert("t", {{"text", 42}, {"_vector", std::vector<float>{1, 0}}}, "num");
+    // The backtracking subject: many a's and a failing end.
+    c.insert("t", {{"text", std::string(5000, 'a') + "b"}, {"_vector", std::vector<float>{0, 1}}}, "redos");
+    // A long subject (a recursive engine can overflow the stack on it).
+    std::string longAb;
+    for (int i = 0; i < 200000; ++i) longAb += (i % 2 ? 'b' : 'a');
+    c.insert("t", {{"text", longAb}, {"_vector", std::vector<float>{1, 1}}}, "long");
+
+    // (1) an invalid pattern is refused, not answered with nothing - on every read that filters.
+    refused([&] { (void)ids(c, "t", {F::regex("text", "dolgoz(")}); }, "text", "find");
+    refused([&] { (void)c.count("t", {F::regex("text", "dolgoz(")}); }, "text", "count");
+    refused([&] { (void)c.similaritySearch("t", {1, 0}, 3, 0.0f, {F::regex("text", "[unclosed")}); },
+            "text", "similaritySearch");
+    refused([&] { (void)ids(c, "t", {F::eq("x", 1), F::regex("text", "(?=look)ahead")}); },
+            "text", "find, lookahead (RE2 has none)");
+    refused([&] { (void)ids(c, "t", {F::regex("text", "(a)\\1")}); }, "text", "find, backreference");
+    ck(!c.createView("badview", "t", {}, {}, {F::regex("text", "dolgoz(")}), "a view with an invalid pattern is refused");
+    ck(!c.getViewInfo("badview"), "the refused view does not exist");
+
+    // (2) (?i) is a flag now.
+    auto r = ids(c, "t", {F::regex("text", "(?i)dolgoz")});
+    ck(r == std::set<std::string>{"hu"}, "(?i)dolgoz matches Dolgozói (got " + show(r) + ")");
+    r = ids(c, "t", {F::regex("text", "dolgoz")});
+    ck(r.empty(), "without (?i) the match stays case-sensitive (got " + show(r) + ")");
+    r = ids(c, "t", {F::regex("text", "(?i)BÉRSZÁMFEJTÉS")});
+    ck(r == std::set<std::string>{"hu"}, "(?i) folds non-ASCII letters (got " + show(r) + ")");
+
+    // (3) a character class matches a character.
+    r = ids(c, "t", {F::regex("text", "sz[áÁ]mfejt")});
+    ck(r == std::set<std::string>{"hu"}, "sz[áÁ]mfejt matches számfejt (got " + show(r) + ")");
+    r = ids(c, "t", {F::regex("text", "[öÖ]")});
+    ck(r == std::set<std::string>{"oe"}, "[öÖ] matches only text containing ö (got " + show(r) + ")");
+    r = ids(c, "t", {F::regex("text", "^b.nat")});
+    ck(r.empty(), "anchored ^ still anchors at the start (got " + show(r) + ")");
+    r = ids(c, "t", {F::regex("text", "b.nat$")});
+    ck(r == std::set<std::string>{"oe"}, ". is one character, á included (got " + show(r) + ")");
+
+    // Unchanged: search semantics, anchors, classes, non-strings never match.
+    r = ids(c, "t", {F::regex("text", "\\d{4}$")});
+    ck(r == std::set<std::string>{"ascii"}, "\\d{4}$ (got " + show(r) + ")");
+    r = ids(c, "t", {F::regex("text", "^plain")});
+    ck(r == std::set<std::string>{"ascii"}, "^plain (got " + show(r) + ")");
+    r = ids(c, "t", {F::regex("text", "4")});
+    ck(r == std::set<std::string>{"ascii"}, "a number value never matches a regex (got " + show(r) + ")");
+    ck(c.count("t", {F::regex("text", "(?i)dolgoz")}) == 1, "count agrees with find");
+    const auto s = c.similaritySearch("t", {1, 0}, 5, -1.0f, {F::regex("text", "(?i)^dolgoz")});
+    ck(s.size() == 1 && s[0].id == "hu", "a filtered similarity search uses the same engine");
+    ck(c.createView("goodview", "t", {}, {}, {F::regex("text", "(?i)számfejt")}), "a view with a valid pattern");
+    r = ids(c, "goodview", {});
+    ck(r == std::set<std::string>{"hu"}, "the view's pattern applies (got " + show(r) + ")");
+
+    // (4) linear time: patterns that backtrack exponentially on std::regex.
+    auto t0 = std::chrono::steady_clock::now();
+    r = ids(c, "t", {F::regex("text", "(a+)+$")});
+    double el = seconds(t0);
+    ck(r.empty(), "(a+)+$ matches nothing here (got " + show(r) + ")");
+    ck(el < 2.0, "(a+)+$ over a 5001-byte failing subject is fast (" + std::to_string(el) + " s)");
+    t0 = std::chrono::steady_clock::now();
+    r = ids(c, "t", {F::regex("text", "^(a|b)*c$")});
+    el = seconds(t0);
+    ck(r.empty(), "^(a|b)*c$ matches nothing");
+    ck(el < 2.0, "^(a|b)*c$ over a 200000-byte subject is fast, no stack overflow (" + std::to_string(el) + " s)");
+    r = ids(c, "t", {F::regex("text", "^(ab)+$")});
+    ck(r == std::set<std::string>{"long"}, "^(ab)+$ matches the long row (got " + show(r) + ")");
+    ck(c.healthCheck(), "the server is still up");
+
+    std::cout << pass << " passed, " << fail << " failed\n";
+    return fail ? 1 : 0;
+}

+ 41 - 0
tests/load_test/test_regex_filters.sh

@@ -0,0 +1,41 @@
+#!/usr/bin/env bash
+# v2.20.0 e2e - REGEX filters run on RE2: invalid patterns refused, (?i), UTF-8
+# character classes, linear time.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-regex-filters
+PORT=9036
+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_regex_filters.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 - regex filters e2e passed" || { echo "FAILED"; tail -20 "$DIR/server.log"; }
+exit $rc

+ 1 - 1
tests/load_test/test_server_info.cpp

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

Unele fișiere nu au fost afișate deoarece prea multe fișiere au fost modificate în acest diff