This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/branch-4.2 by this push:
new 1ae01a6f9c9 branch-4.2: [fix](search) Key the condition cache by the
SEARCH query #70886 (#70889)
1ae01a6f9c9 is described below
commit 1ae01a6f9c958842ae97aade695527ff83df2d7e
Author: Jack <[email protected]>
AuthorDate: Tue Nov 24 10:03:20 2026 +0800
branch-4.2: [fix](search) Key the condition cache by the SEARCH query
#70886 (#70889)
Backport #70886 to `branch-4.2` with `git cherry-pick -x` of its two
commits, `4c7fdbad5fe2d4a4176c5e14db565730c95d0fb3` (the fix) and
`6f55f4b960d` (pins VARIANT and MATCH session variables in the new
suite). #70886 is still open on master; this pick will follow any change
made there.
### Backport
- Conflicts: none.
- Hunk audit against the source diff (added and removed lines compared
per file, ignoring line offsets):
| File | Source hunks | Result |
|---|---|---|
| `be/src/exprs/vsearch.cpp` | `@@ -35,6 +35,8 @@`, `@@ -304,7 +306,25
@@ VSearchExpr::VSearchExpr` | Ported (verbatim) |
| `be/src/exprs/vsearch.h` | `@@ -41,6 +41,9 @@`, `@@ -50,6 +53,8 @@` |
Ported (verbatim) |
| `be/test/exprs/vsearch_expr_test.cpp` | `@@ -1625,4 +1625,76 @@` |
Ported (verbatim) |
| `regression-test/suites/search/test_search_condition_cache.groovy` |
`@@ -0,0 +1,128 @@` (new file) | Ported (verbatim) |
| same suite, second commit | `@@ -21,6 +21,10 @@` | Ported (verbatim);
the variable names match `branch-4.2` |
- Validation on this branch, run locally on RELEASE builds of this
head's tree:
- `./build.sh --fe --be` passed.
- `./run-be-ut.sh --run --filter='VSearchExprTest.*'`: 52 of 52 passed,
including the five `Digest*` cases this change adds.
- `search/test_search_condition_cache` passed against an isolated FE and
BE of this build (`doris-4.2.0-rc01`).
- The clang-format 16 preflight against `origin/branch-4.2` passed.
- These runs used the first commit; the second only adds three `SET`
statements and was not rerun locally.
---
### Background
`SEARCH(dsl, options)` runs a Lucene-style query against inverted
indexes. In the BE, `VSearchExpr` keeps the query text, the parsed
clause tree, the field bindings, and the options in a `TSearchParam`;
its children are only the bound columns. The condition cache
(`enable_condition_cache`, on by default) remembers, per segment, which
2048-row granules can hold rows that pass a scan's conjuncts. It keys
that result by rowset, segment, and a digest that each expression
computes with `get_digest()`.
### What problem does this PR solve?
Issue Number: None
Related PR: #55534 (added the condition cache, whose key misses the
SEARCH query), #56139 (added SEARCH)
PR Type: Bugfix
Problem Summary:
Two SEARCH predicates on the same column that differ only in their query
get the same condition cache key. The second query then reuses the
granules cached for the first and silently drops matching rows. This
happens when the scan also has a predicate the index cannot answer,
which keeps the cache in use. This PR adds the serialized `TSearchParam`
to the digest of `VSearchExpr`.
For example, on a table with rows `(1, 'alpha', 200)` and `(2, 'beta',
200)`, an inverted index on `s`, and none on `d`:
```sql
SET enable_condition_cache = true;
SELECT COUNT(*) FROM t WHERE abs(d) >= 100 AND SEARCH('nomatch*',
'{"default_field":"s","mode":"lucene"}');
SELECT COUNT(*) FROM t WHERE abs(d) >= 100 AND SEARCH('alpha*',
'{"default_field":"s","mode":"lucene"}');
```
| Query | Before the fix | With the fix | With the cache off |
|---|---|---|---|
| `nomatch*` | 0 | 0 | 0 |
| `alpha*` | 0 | 1 | 1 |
### Details
- **Frequency:** Always, when two SEARCH predicates with different
queries on the same column scan the same segment, the scan has a
predicate the inverted index cannot answer (such as `abs(d) >= 100` or a
cast of a VARIANT subcolumn), and the first query has filled the cache.
Rows are only lost, never added.
- **Root cause:** `VSearchExpr` does not override `get_digest()`, so it
inherits `VExpr::get_digest()`, which hashes only the children and the
node type. The children are the bound columns, and the query lives in
`TSearchParam`, so it never reaches the key. The FE seed of the digest
covers only session variables.
- **Why existing tests missed it:** Unit tests: `vsearch_expr_test.cpp`
never computes a digest, and `vliteral_digest_test.cpp` covers only
literals. Regression: `query_p0/cache/condition_cache.groovy` and
`condition_cache_eligibility.groovy` vary ordinary predicates and never
use SEARCH. The SEARCH suites, such as
`search/test_search_cache.groovy`, check the inverted index query cache
and never run two different queries with a residual predicate under the
condition cache. P0 also turns the condition cache on only for even PR
numbers.
- **Fix:** `VSearchExpr` serializes the whole `TSearchParam` once in its
constructor and mixes the bytes into `get_digest()` after the children.
Hashing the whole struct also covers fields added later. A failed
serialization returns 0, which disables the cache for that query.
`inverted_index_max_expansions` already reaches the key through the FE
seed.
- **Other paths and branches:** `VMatchPredicate` has a similar gap
found by code review: its analyzer settings are not in the digest, so
`MATCH ... USING ANALYZER a` and `USING ANALYZER b` on one column may
share a key. It is not fixed here. `branch-4.2` and `branch-4.1` have
the bug; `branch-4.0` has SEARCH but no condition cache.
### Testing
- New cases in `be/test/exprs/vsearch_expr_test.cpp`: on the code before
the fix, `DigestChangesWithSearchTerm` and
`DigestChangesWithSearchOptions` fail, with every query, operator,
`minimum_should_match`, and analyzer variant giving the same digest
`17354580315439948866`. With the fix, all 53 `VSearchExprTest` cases
pass. Run locally.
- New regression suite `search/test_search_condition_cache.groovy`
(group `p0`): passes locally on a build of this branch. Its queries run
on master without the fix return no rows for `alpha*` after `nomatch*`,
and no rows for `beta*` after `alpha*` when `beta` sits in another
granule.
- Manual check on the fixed build, from the BE `condition_cache`
metrics: a repeated identical SEARCH still hits the cache, and a SEARCH
with another query misses it and returns the right rows.
### Release note
Fix SEARCH queries that could miss matching rows when the condition
cache held the result of an earlier SEARCH with a different query on the
same column.
### Check List (For Author)
- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Ready
### AI Disclosure
- Tool: Claude Code (Claude Opus 5.5)
- Generated: the fix, the tests, and this description
- Human review: not stated
- Prompts: Asked the agent to check whether a bug report about SEARCH
losing rows duplicated earlier SEARCH issues, and if not, to reproduce
it and propose a fix; then to open this PR and backport it to the
release branches.
---------
Co-authored-by: Claude Opus 5.5 <[email protected]>
---
be/src/exprs/vsearch.cpp | 20 ++++
be/src/exprs/vsearch.h | 5 +
be/test/exprs/vsearch_expr_test.cpp | 72 +++++++++++
.../search/test_search_condition_cache.groovy | 132 +++++++++++++++++++++
4 files changed, 229 insertions(+)
diff --git a/be/src/exprs/vsearch.cpp b/be/src/exprs/vsearch.cpp
index dac696c1c5a..901e63fdda1 100644
--- a/be/src/exprs/vsearch.cpp
+++ b/be/src/exprs/vsearch.cpp
@@ -35,6 +35,8 @@
#include "storage/schema.h"
#include "storage/segment/segment.h"
#include "storage/segment/variant/variant_column_reader.h"
+#include "util/hash_util.hpp"
+#include "util/thrift_util.h"
namespace doris {
using namespace segment_v2;
@@ -332,7 +334,25 @@ VSearchExpr::VSearchExpr(const TExprNode& node) :
VExpr(node) {
if (node.__isset.search_param) {
_search_param = node.search_param;
_original_dsl = _search_param.original_dsl;
+ ThriftSerializer serializer(false, 1024);
+ Status st = serializer.serialize(&_search_param, &_search_param_key);
+ if (!st.ok()) {
+ LOG(WARNING) << "VSearchExpr: cannot serialize search param,
condition cache disabled: "
+ << st.to_string();
+ _search_param_key.clear();
+ }
+ }
+}
+
+uint64_t VSearchExpr::get_digest(uint64_t seed) const {
+ if (_search_param_key.empty()) {
+ return 0;
+ }
+ seed = VExpr::get_digest(seed);
+ if (seed == 0) {
+ return 0;
}
+ return HashUtil::hash64(_search_param_key.data(),
_search_param_key.size(), seed);
}
Status VSearchExpr::prepare(RuntimeState* state, const RowDescriptor& row_desc,
diff --git a/be/src/exprs/vsearch.h b/be/src/exprs/vsearch.h
index bb4f8170905..2406e037833 100644
--- a/be/src/exprs/vsearch.h
+++ b/be/src/exprs/vsearch.h
@@ -41,6 +41,9 @@ public:
bool can_push_down_to_index() const override { return true; }
+ // The condition cache key must cover the DSL, which lives in
_search_param, not in children.
+ uint64_t get_digest(uint64_t seed) const override;
+
const TSearchParam& get_search_param() const { return _search_param; }
bool enable_cache() const { return _enable_cache; }
@@ -50,6 +53,8 @@ public:
private:
TSearchParam _search_param;
std::string _original_dsl;
+ // Serialized _search_param, so every DSL field joins the digest. Empty
disables the cache.
+ std::string _search_param_key;
bool _enable_cache = true;
};
diff --git a/be/test/exprs/vsearch_expr_test.cpp
b/be/test/exprs/vsearch_expr_test.cpp
index 7d120066c33..6a8b259a0e2 100644
--- a/be/test/exprs/vsearch_expr_test.cpp
+++ b/be/test/exprs/vsearch_expr_test.cpp
@@ -1619,4 +1619,76 @@ TEST_F(VSearchExprTest,
EvaluateInvertedIndexRejectsSearchFallback) {
}
}
+namespace {
+
+constexpr uint64_t kDigestSeed = 42;
+
+uint64_t search_digest(const TExprNode& node, const std::string& column_name =
"title") {
+ auto expr = VSearchExpr::create_shared(node);
+ expr->add_child(create_slot_ref(0, column_name));
+ return expr->get_digest(kDigestSeed);
+}
+
+} // namespace
+
+// The condition cache keys segment results by this digest, so the same SEARCH
must keep hitting.
+TEST_F(VSearchExprTest, DigestIsStableForSameSearchParam) {
+ const uint64_t digest = search_digest(test_node);
+ EXPECT_NE(0, digest);
+ EXPECT_EQ(digest, search_digest(test_node));
+}
+
+// A result cached for one term must not be reused by another term on the same
column.
+TEST_F(VSearchExprTest, DigestChangesWithSearchTerm) {
+ TExprNode nomatch = test_node;
+ nomatch.search_param.original_dsl = "nomatch*";
+ nomatch.search_param.root.clause_type = "PREFIX";
+ nomatch.search_param.root.value = "nomatch";
+
+ TExprNode alpha = nomatch;
+ alpha.search_param.original_dsl = "alpha*";
+ alpha.search_param.root.value = "alpha";
+ EXPECT_NE(search_digest(nomatch), search_digest(alpha));
+
+ // The parsed clause decides the result even when the DSL text is the same.
+ TExprNode same_text = nomatch;
+ same_text.search_param.root.value = "alpha";
+ EXPECT_NE(search_digest(nomatch), search_digest(same_text));
+
+ TExprNode term = nomatch;
+ term.search_param.root.clause_type = "TERM";
+ EXPECT_NE(search_digest(nomatch), search_digest(term));
+}
+
+TEST_F(VSearchExprTest, DigestChangesWithSearchOptions) {
+ const uint64_t base = search_digest(test_node);
+
+ TExprNode and_operator = test_node;
+ and_operator.search_param.__set_default_operator("and");
+ TExprNode or_operator = test_node;
+ or_operator.search_param.__set_default_operator("or");
+ EXPECT_NE(search_digest(and_operator), search_digest(or_operator));
+
+ TExprNode min_should_match = test_node;
+ min_should_match.search_param.__set_minimum_should_match(2);
+ EXPECT_NE(base, search_digest(min_should_match));
+
+ TExprNode english = test_node;
+ english.search_param.field_bindings[0].__set_index_properties({{"parser",
"english"}});
+ TExprNode unicode = test_node;
+ unicode.search_param.field_bindings[0].__set_index_properties({{"parser",
"unicode"}});
+ EXPECT_NE(search_digest(english), search_digest(unicode));
+}
+
+TEST_F(VSearchExprTest, DigestStillDependsOnBoundColumn) {
+ EXPECT_NE(search_digest(test_node, "title"), search_digest(test_node,
"body"));
+}
+
+// Without a search param there is nothing to key on, so the condition cache
stays off.
+TEST_F(VSearchExprTest, DigestIsZeroWithoutSearchParam) {
+ TExprNode node = test_node;
+ node.__isset.search_param = false;
+ EXPECT_EQ(0, search_digest(node));
+}
+
} // namespace doris
diff --git a/regression-test/suites/search/test_search_condition_cache.groovy
b/regression-test/suites/search/test_search_condition_cache.groovy
new file mode 100644
index 00000000000..c15de4e5195
--- /dev/null
+++ b/regression-test/suites/search/test_search_condition_cache.groovy
@@ -0,0 +1,132 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// The BE condition cache must key SEARCH results by the DSL, not only by the
bound columns.
+// A residual predicate that the index cannot answer keeps the cache in use
for the segment.
+suite("test_search_condition_cache", "p0") {
+ sql "SET enable_sql_cache = false"
+ sql "SET enable_inverted_index_query_cache = false"
+ sql "SET enable_count_on_index_pushdown = false"
+ // Fuzzy session settings could otherwise store VARIANT paths without an
index iterator.
+ sql "SET enable_match_without_inverted_index = false"
+ sql "SET debug_variant_enable_typed_paths_to_sparse = false"
+ sql "SET debug_variant_enable_doc_mode = false"
+
+ def textTable = "search_condition_cache_text"
+ def variantTable = "search_condition_cache_variant"
+
+ def textIds = { String dsl ->
+ def rows = sql """
+ SELECT id FROM ${textTable}
+ WHERE abs(d) >= 100 AND SEARCH('${dsl}',
'{"default_field":"s","mode":"lucene","default_operator":"and"}')
+ ORDER BY id
+ """
+ return rows.collect { it[0] as long }
+ }
+ def variantCount = { String dsl ->
+ def rows = sql """
+ SELECT COUNT(*) FROM ${variantTable}
+ WHERE CAST(payload['datetime_7'] AS BIGINT) >= 100
+ AND SEARCH('${dsl}',
'{"default_field":"payload.string_8","mode":"lucene","default_operator":"and"}')
+ """
+ return rows[0][0] as long
+ }
+
+ def createTextTable = {
+ sql "DROP TABLE IF EXISTS ${textTable}"
+ sql """
+ CREATE TABLE ${textTable} (
+ id BIGINT NOT NULL,
+ s TEXT NULL,
+ d BIGINT NULL,
+ INDEX idx_s (s) USING INVERTED
+ ) DUPLICATE KEY(id)
+ DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES ("replication_num" = "1",
"inverted_index_storage_format" = "V2")
+ """
+ // Rows sit in key order, so `alpha` is in the first 2048-row granule
and `beta` in the second.
+ sql """
+ INSERT INTO ${textTable}
+ SELECT number,
+ CASE number WHEN 1 THEN 'alpha' WHEN 3000 THEN 'beta' ELSE
'filler' END,
+ 200
+ FROM numbers("number" = "4096")
+ """
+ sql "sync"
+ }
+ def createVariantTable = {
+ sql "DROP TABLE IF EXISTS ${variantTable}"
+ sql """
+ CREATE TABLE ${variantTable} (
+ id BIGINT NOT NULL,
+ payload VARIANT<'string_*':TEXT, 'datetime_*':BIGINT> NULL,
+ INDEX idx_string (payload) USING INVERTED
PROPERTIES("field_pattern" = "string_*"),
+ INDEX idx_datetime (payload) USING INVERTED
PROPERTIES("field_pattern" = "datetime_*")
+ ) DUPLICATE KEY(id)
+ DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES ("replication_num" = "1",
"inverted_index_storage_format" = "V2")
+ """
+ // The JSON cast stores objects; a bare string literal would be stored
as a string value.
+ sql """INSERT INTO ${variantTable} VALUES
+ (1, CAST('{"string_8":"alpha","datetime_7":200}' AS JSON)),
+ (2, CAST('{"string_8":"beta","datetime_7":200}' AS JSON))"""
+ sql "sync"
+ }
+
+ // An empty result cached for `nomatch*` must not prune rows for later
terms.
+ createTextTable()
+ sql "SET enable_condition_cache = true"
+ assertEquals([], textIds("nomatch*"))
+ assertEquals([1L], textIds("alpha*"))
+ assertEquals([3000L], textIds("s:beta"))
+ assertEquals([1L], textIds("s:alpha"))
+ assertEquals([1L], textIds("alpha*"))
+
+ // The granules cached for `alpha*` must not hide the granule that holds
`beta`.
+ createTextTable()
+ assertEquals([1L], textIds("alpha*"))
+ assertEquals([3000L], textIds("beta*"))
+ assertEquals([], textIds("nomatch*"))
+ assertEquals([1L], textIds("alpha*"))
+
+ sql "SET enable_condition_cache = false"
+ assertEquals([1L], textIds("alpha*"))
+ assertEquals([3000L], textIds("beta*"))
+
+ // A SEARCH without other predicates may cache the all-false result the
index proves.
+ createTextTable()
+ sql "SET enable_condition_cache = true"
+ def plainIds = { String dsl ->
+ def rows = sql """
+ SELECT id FROM ${textTable}
+ WHERE SEARCH('${dsl}',
'{"default_field":"s","mode":"lucene","default_operator":"and"}')
+ ORDER BY id
+ """
+ return rows.collect { it[0] as long }
+ }
+ assertEquals([], plainIds("nomatch*"))
+ assertEquals([1L], plainIds("alpha*"))
+ assertEquals([3000L], plainIds("beta*"))
+
+ // The same check on a VARIANT subcolumn with field-pattern indexes.
+ createVariantTable()
+ sql "SET enable_condition_cache = true"
+ assertEquals(0L, variantCount("nomatch*"))
+ assertEquals(1L, variantCount("alpha*"))
+ sql "SET enable_condition_cache = false"
+ assertEquals(1L, variantCount("alpha*"))
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]