This is an automated email from the ASF dual-hosted git repository.

yiguolei pushed a commit to branch branch-4.1
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/branch-4.1 by this push:
     new aa04393e7f5 branch-4.1: [fix](inverted index) Fix score() with MATCH 
on VARIANT paths missing from a segment #71022 (#71063)
aa04393e7f5 is described below

commit aa04393e7f5e63a945e36f5e76679473fd7b995d
Author: Jack <[email protected]>
AuthorDate: Fri Nov 27 13:56:13 2026 +0800

    branch-4.1: [fix](inverted index) Fix score() with MATCH on VARIANT paths 
missing from a segment #71022 (#71063)
    
    ### Background
    
    Pick of apache/doris#71022 to branch-4.1. `score()` needs every scored
    predicate answered by the inverted index, and an AND/OR/NOT with a
    scored branch fails when another branch has no index result (#69053, on
    this branch via #69160). A VARIANT column stores a path only in segments
    whose rows contain it, and SEARCH (#69347, on this branch via #69603)
    already proves such absence from segment metadata; MATCH did not.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #71022 (source, not merged yet when picked), #71060 (same
    pick for branch-4.2), #69160 (#69053 on branch-4.1), #69603 (#69347 on
    branch-4.1), #38908 (added the AND early exit fixed here)
    PR Type: Bugfix
    
    Problem Summary:
    
    On branch-4.1, `score()` over MATCH predicates combined with AND/OR/NOT
    on VARIANT paths fails with "Cannot score a compound predicate with
    incomplete index evaluation" when some segment does not store one of the
    paths, while `search()` works. Same fix as #71022: SEARCH's absence
    proof becomes one shared `IndexExecContext::is_variant_path_absent`,
    MATCH uses it to answer a provably absent path as no hits with every row
    NULL, the proof also finds dotted keys under the split path, and an
    index-evaluated AND no longer stops while NULL rows can still turn FALSE
    (which also fixes `NOT (a AND b)` on nullable indexed columns with
    `SIMPLIFY_NOT_EXPR` disabled).
    
    ### Details
    
    - **Source:** apache/doris#71022 head bd12065805b (commits 262a92cce17,
    ec87bb18603, bd12065805b), picked through the adapted branch-4.2 commits
    and squashed here. The source PR was still under review; recheck this
    pick against its merged commit.
    - **Adaptations for branch-4.1** (behavior unchanged):
    - `IndexExecContext::is_variant_path_absent` uses branch-4.1's own proof
    body moved from `vsearch.cpp` (column-ID mapping; root resolved by
    unique ID with `has_column_unique_id` and `get_column_reader`).
    Branch-4.1 has no escaped-key encoding, so the proof always also looks
    for a prefix under the split path, as `get_subcolumn_meta_by_path` on
    this branch always does.
    - `VMatchPredicate::evaluate_inverted_index` keeps this branch's form
    (no VARIANT values-index diagnostic, which came with #69761) and only
    adds the hook; the helper uses
    `get_inverted_index_iterator_by_column_id` and the column-ID mapping.
    - BE tests use this branch's `IndexExecContext` constructors and
    `Schema`; the V2 test sets the storage format on the schema before
    `init_tablet_from_current_schema`.
    - The regression case pins VARIANT storage with this branch's
    `default_variant_enable_doc_mode` and
    `default_variant_max_subcolumns_count`, and creates the dotted-path
    table without `variant_escape_dots_in_keys`, which this branch does not
    have (every segment stores keys unescaped).
    - **Frequency, root cause, other paths:** as in #71022.
    
    Hunk audit against #71022 (source hunks; the per-file comparison was
    redone against the source, not against the branch-4.2 pick):
    
    | File | Hunks | Status |
    | --- | --- | --- |
    | be/src/exprs/vcompound_pred.h | AND early exit | Ported (verbatim) |
    | be/src/exprs/vexpr_context.h | forward decl; `is_variant_path_absent`
    declaration | Ported (verbatim) |
    | be/src/exprs/vexpr_context.cpp | includes; `is_variant_path_absent` |
    Adapted: branch-4.1 root lookup and column-ID mapping; split-path prefix
    always checked (no `path_encoding()`); no `storage/iterators.h` |
    | be/src/exprs/vmatch_predicate.h | forward decl; helper declaration |
    Ported (verbatim) |
    | be/src/exprs/vmatch_predicate.cpp | includes; hook;
    `_evaluate_absent_variant_path` | Adapted: branch-4.1
    `evaluate_inverted_index` shape; branch APIs |
    | be/src/exprs/vsearch.cpp | includes; `verify_missing_variant_path` |
    Adapted: removes branch-4.1's own proof body |
    | be/src/storage/segment/variant/variant_column_reader.cpp | prefix
    lookup changed in ec87bb18603, restored in bd12065805b | Net zero, as in
    the source |
    | be/test/exprs/vcompound_pred_score_test.cpp | mock;
    `AndWithOnlyNullRowsLeftEvaluatesLaterBranches` | Adapted: branch
    constructor; appended after this branch's
    `NestedIncompleteScoringErrorSurvivesEmptyOrUnindexedSiblings` |
    | be/test/storage/variant/variant_column_writer_reader_test.cpp |
    includes; helper; three tests | Adapted: only the includes the tests
    need; `Schema` and `col_ids`; V2 through the schema |
    |
    regression-test/suites/search/test_search_score_boolean_branches.groovy
    | new VARIANT and nullable cases | Adapted: `default_variant_*`
    variables; no `variant_escape_dots_in_keys`; appended after this
    branch's WAND block |
    | regression-test/data/search/test_search_score_boolean_branches.out |
    new tags | Regenerated on branch-4.1 with `-forceGenOut`; byte-identical
    to the source .out |
    
    ### Testing
    
    Local, ASAN, single BE, on this commit:
    
    - BE UT `VariantColumnWriterReaderTest.*`, `VCompoundPredScoreTest.*`,
    `VSearch*`, `*VMatchPredicate*`, `*FunctionSearch*`,
    `*VariantColumnReader*`, `*HierarchicalData*`: 300 tests, 298 passed, 2
    skipped (NestedGroup not built); the four new tests and this branch's
    `NestedIncompleteScoringErrorSurvivesEmptyOrUnindexedSiblings` pass.
    With the split-path check removed,
    `test_match_reads_rows_for_legacy_dotted_variant_path` fails, so it
    covers this branch.
    - Regression `search/test_search_score_boolean_branches`: passes; the
    generated .out equals the source .out. The new queries return the same
    rows with `enable_inverted_index_query=false` (2,3 / 2,4,6 / 1 /
    1,3,5,9); `test_search_score_variant_dotted_path` was created with
    storage format V2.
    - `build-support/check-format.sh`: pass. This branch has no
    `check-build-hygiene.sh`.
    
    ### Release note
    
    Fixed the error "Cannot score a compound predicate with incomplete index
    evaluation" when `score()` ranks rows filtered by MATCH predicates on
    VARIANT paths combined with AND, OR, or NOT, and some data does not
    contain one of the paths. Also fixed missing rows for `NOT (a AND b)` on
    inverted-indexed columns when `a` is NULL and `b` is FALSE, with
    `SIMPLIFY_NOT_EXPR` disabled.
    
    ### Check List (For Author)
    
    - Behavior changed: Yes (see #71022: MATCH on a VARIANT path absent from
    a segment is answered by the index; same rows)
    - Does this need documentation: No
    - Pre-submission status: Partially verified: not run in cloud mode; the
    source PR is not merged yet
    
    ### AI Disclosure
    
    - Tool: Claude Code (Claude Opus 5.5)
    - Generated: the pick, its adaptations, and this description
    - Human review: not stated
    
    Backport-of: 262a92cce174c0ecc2929298034ba0598c5cf205
    Backport-of: ec87bb18603f866401dd2858829af87178471216
    Backport-of: bd12065805b77bed93f0b6d3158f0d201e48a65d
    Picked through the branch-4.2 adaptation of these commits and adapted
    again for branch-4.1.
---
 be/src/exprs/vcompound_pred.h                      |   7 +-
 be/src/exprs/vexpr_context.cpp                     |  64 ++++++++
 be/src/exprs/vexpr_context.h                       |   8 +
 be/src/exprs/vmatch_predicate.cpp                  |  49 +++++-
 be/src/exprs/vmatch_predicate.h                    |   4 +
 be/src/exprs/vsearch.cpp                           |  53 +------
 be/test/exprs/vcompound_pred_score_test.cpp        |  66 +++++++++
 .../variant/variant_column_writer_reader_test.cpp  | 165 +++++++++++++++++++++
 .../search/test_search_score_boolean_branches.out  |  32 ++++
 .../test_search_score_boolean_branches.groovy      | 119 +++++++++++++++
 10 files changed, 517 insertions(+), 50 deletions(-)

diff --git a/be/src/exprs/vcompound_pred.h b/be/src/exprs/vcompound_pred.h
index bfe76d61496..5231d743768 100644
--- a/be/src/exprs/vcompound_pred.h
+++ b/be/src/exprs/vcompound_pred.h
@@ -344,8 +344,11 @@ public:
                         res &= *index_result;
                     }
 
-                    if (res.get_data_bitmap()->isEmpty()) {
-                        break; // Early exit if result is empty
+                    // Stop only once every row is FALSE. A NULL row can still 
become FALSE in a
+                    // later branch: NULL AND FALSE is FALSE, so NOT (NULL AND 
FALSE) keeps it.
+                    if (res.get_data_bitmap()->isEmpty() &&
+                        (res.get_null_bitmap() == nullptr || 
res.get_null_bitmap()->isEmpty())) {
+                        break;
                     }
                 } else {
                     all_pass = false;
diff --git a/be/src/exprs/vexpr_context.cpp b/be/src/exprs/vexpr_context.cpp
index b25d2daa112..a5f53c3a749 100644
--- a/be/src/exprs/vexpr_context.cpp
+++ b/be/src/exprs/vexpr_context.cpp
@@ -40,7 +40,11 @@
 #include "runtime/runtime_state.h"
 #include "runtime/thread_context.h"
 #include "storage/olap_common.h"
+#include "storage/schema.h"
 #include "storage/segment/column_reader.h"
+#include "storage/segment/segment.h"
+#include "storage/segment/variant/variant_column_reader.h"
+#include "util/json/path_in_data.h"
 #include "util/simd/bits.h"
 
 namespace doris {
@@ -50,6 +54,66 @@ class RowDescriptor;
 namespace doris {
 #include "common/compile_check_begin.h"
 
+Status IndexExecContext::is_variant_path_absent(int32_t read_ordinal,
+                                                const PathInData& 
relative_path,
+                                                bool* absent) const {
+    DORIS_CHECK(_segment != nullptr);
+    DORIS_CHECK_GE(read_ordinal, 0);
+    DORIS_CHECK_LT(static_cast<size_t>(read_ordinal), 
_read_schema->num_column_ids());
+    DORIS_CHECK(_column_iter_opts.stats != nullptr);
+    const auto& column = 
*_read_schema->column(_read_schema->column_id(read_ordinal));
+    const int32_t root_uid =
+            column.parent_unique_id() >= 0 ? column.parent_unique_id() : 
column.unique_id();
+    // DROP/ADD can leave an old segment without the current root UID. Do not 
open its
+    // historical same-named column or initialize readers for a root that is 
absent.
+    if (!_segment->tablet_schema()->has_column_unique_id(root_uid)) {
+        *absent = true;
+        return Status::OK();
+    }
+    std::shared_ptr<segment_v2::ColumnReader> column_reader;
+    Status st = _segment->get_column_reader(root_uid, &column_reader, 
_column_iter_opts.stats,
+                                            &_column_iter_opts.io_ctx);
+    if (st.is<ErrorCode::NOT_FOUND>()) {
+        // After DROP v(uid=1), ADD v(uid=2), an old segment cannot contain 
this scan's root.
+        // Resolve by the current uid so historical values of the same name 
cannot match.
+        *absent = true;
+        return Status::OK();
+    }
+    RETURN_IF_ERROR(st);
+    auto* reader = 
dynamic_cast<segment_v2::VariantColumnReader*>(column_reader.get());
+    DORIS_CHECK(reader != nullptr);
+    RETURN_IF_ERROR(
+            reader->load_external_meta_once(_column_iter_opts.stats, 
&_column_iter_opts.io_ctx));
+    const auto* stats = reader->get_stats();
+    // Doc statistics enumerate stored paths without the sparse statistics 
limit. For example,
+    // a segment containing only `string4` can prove `string5` absent even in 
doc mode.
+    // An opaque root/ancestor value may contain the requested path, so it 
remains unavailable.
+    bool in_doc = stats->existed_in_doc_value_column("") ||
+                  
stats->has_prefix_path_in_doc_value_column(relative_path.get_path() + ".");
+    std::string ancestor = relative_path.get_path();
+    while (!in_doc) {
+        in_doc = stats->existed_in_doc_value_column(ancestor);
+        const auto dot = ancestor.rfind('.');
+        if (dot == std::string::npos) {
+            break;
+        }
+        ancestor.resize(dot);
+    }
+    // Keys are not escaped, so the key `a.b` and the path a -> b are stored 
alike, and the read
+    // plan reads FE's component ['a.b'] through the split path. For example, 
a stored `a.b.c`
+    // gives `v['a.b']` the value {"c":...}, so the split path must count as a 
prefix too.
+    const bool has_prefix =
+            reader->has_prefix_path(relative_path, _column_iter_opts.stats,
+                                    &_column_iter_opts.io_ctx) ||
+            reader->has_prefix_path(PathInData(relative_path.get_path()), 
_column_iter_opts.stats,
+                                    &_column_iter_opts.io_ctx);
+    // Truncated sparse statistics cannot prove absence, nor can an existing 
unindexed path.
+    *absent = reader->get_subcolumn_meta_by_path(relative_path) == nullptr && 
!has_prefix &&
+              !reader->exist_in_sparse_column(relative_path) &&
+              !reader->is_exceeded_sparse_column_limit() && !in_doc && 
!stats->has_nested_group;
+    return Status::OK();
+}
+
 VExprContext::VExprContext(VExprSPtr expr) : _root(std::move(expr)) {}
 
 VExprContext::~VExprContext() {
diff --git a/be/src/exprs/vexpr_context.h b/be/src/exprs/vexpr_context.h
index f25f4b5adce..f40306ea4ba 100644
--- a/be/src/exprs/vexpr_context.h
+++ b/be/src/exprs/vexpr_context.h
@@ -44,6 +44,7 @@
 #include "storage/segment/column_reader.h"
 
 namespace doris {
+class PathInData;
 class Schema;
 class RowDescriptor;
 class RuntimeState;
@@ -124,6 +125,13 @@ public:
 
     const segment_v2::ColumnIteratorOptions& column_iter_opts() const { return 
_column_iter_opts; }
 
+    // Sets *absent to whether this segment proves that the VARIANT root read 
at `read_ordinal`
+    // stores nothing at `relative_path`, so every row of the segment reads 
NULL there. A missing
+    // index iterator proves nothing: `v.a` may live in the sparse or 
doc-value column, or in a
+    // segment written before its index existed. Requires a segment.
+    Status is_variant_path_absent(int32_t read_ordinal, const PathInData& 
relative_path,
+                                  bool* absent) const;
+
     bool has_index_result_for_expr(const VExpr* expr) const {
         return _index_result_bitmap.contains(expr);
     }
diff --git a/be/src/exprs/vmatch_predicate.cpp 
b/be/src/exprs/vmatch_predicate.cpp
index 6e5a3693b39..315b6149cfb 100644
--- a/be/src/exprs/vmatch_predicate.cpp
+++ b/be/src/exprs/vmatch_predicate.cpp
@@ -46,6 +46,8 @@
 #include "runtime/runtime_state.h"
 #include "storage/index/inverted/analyzer/analyzer.h"
 #include "storage/index/inverted/inverted_index_reader.h"
+#include "storage/schema.h"
+#include "util/json/path_in_data.h"
 
 namespace doris {
 class RowDescriptor;
@@ -174,7 +176,52 @@ Status 
VMatchPredicate::evaluate_inverted_index(VExprContext* context, uint32_t
     if (context != nullptr && context->get_index_context() != nullptr && 
_analyzer_ctx != nullptr) {
         context->get_index_context()->set_analyzer_ctx_for_expr(this, 
_analyzer_ctx);
     }
-    return _evaluate_inverted_index(context, _function, segment_num_rows);
+    auto status = _evaluate_inverted_index(context, _function, 
segment_num_rows);
+    if (status.ok() && context != nullptr && context->get_index_context() != 
nullptr &&
+        !context->get_index_context()->has_index_result_for_expr(this)) {
+        RETURN_IF_ERROR(
+                _evaluate_absent_variant_path(*context->get_index_context(), 
segment_num_rows));
+    }
+    return status;
+}
+
+// A MATCH on a VARIANT path that this segment does not store is NULL on every 
row, which the
+// index can answer exactly. Without that answer the MATCH falls back to row 
evaluation, and
+// score() then rejects an AND/OR whose other branches were scored. For 
example, in a segment
+// written from {"title":"apple archive"}, `v['content'] MATCH 'search'` is 
answered here, so
+// `v['title'] MATCH 'apple' OR v['content'] MATCH 'search'` can still score 
the title branch.
+Status VMatchPredicate::_evaluate_absent_variant_path(IndexExecContext& 
index_context,
+                                                      uint32_t 
segment_num_rows) {
+    // The planner reads `v['content']` as a path slot, usually under a cast 
to the MATCH type.
+    // Without a segment there is no VARIANT metadata to prove the path absent 
from.
+    const auto input = expr_without_cast(get_child(0));
+    if (!input->is_slot_ref() || index_context.segment() == nullptr) {
+        return Status::OK();
+    }
+    // A path with an index iterator has already been answered or declined by 
its index, and
+    // only an extracted VARIANT path can be absent from a segment.
+    const int column_id = assert_cast<const 
VSlotRef*>(input.get())->column_id();
+    const auto& read_schema = index_context.read_schema();
+    const auto& column = 
*read_schema->column(read_schema->column_id(column_id));
+    if (index_context.get_inverted_index_iterator_by_column_id(column_id) != 
nullptr ||
+        !column.is_extracted_column()) {
+        return Status::OK();
+    }
+    bool absent = false;
+    RETURN_IF_ERROR(index_context.is_variant_path_absent(
+            column_id, column.path_info_ptr()->copy_pop_front(), &absent));
+    // A path that is stored but has no index, such as one in the sparse 
column, still needs
+    // row evaluation.
+    if (!absent) {
+        return Status::OK();
+    }
+    auto null_rows = std::make_shared<roaring::Roaring>();
+    null_rows->addRange(0, segment_num_rows);
+    index_context.set_index_result_for_expr(
+            this,
+            InvertedIndexResultBitmap(std::make_shared<roaring::Roaring>(), 
std::move(null_rows)));
+    index_context.set_true_for_index_status(this, column_id);
+    return Status::OK();
 }
 
 const std::string& VMatchPredicate::get_analyzer_key() const {
diff --git a/be/src/exprs/vmatch_predicate.h b/be/src/exprs/vmatch_predicate.h
index 32fdf6fe7d6..f5c4a218dad 100644
--- a/be/src/exprs/vmatch_predicate.h
+++ b/be/src/exprs/vmatch_predicate.h
@@ -32,6 +32,7 @@ class Analyzer;
 }
 } // namespace lucene
 namespace doris {
+class IndexExecContext;
 class RowDescriptor;
 class RuntimeState;
 class TExprNode;
@@ -66,6 +67,9 @@ public:
     FunctionBasePtr function() { return _function; }
 
 private:
+    Status _evaluate_absent_variant_path(IndexExecContext& index_context,
+                                         uint32_t segment_num_rows);
+
     FunctionBasePtr _function;
     std::string _expr_name;
     std::string _function_name;
diff --git a/be/src/exprs/vsearch.cpp b/be/src/exprs/vsearch.cpp
index a2e94401961..ad12585f473 100644
--- a/be/src/exprs/vsearch.cpp
+++ b/be/src/exprs/vsearch.cpp
@@ -33,8 +33,7 @@
 #include "runtime/runtime_state.h"
 #include "storage/index/inverted/inverted_index_reader.h"
 #include "storage/schema.h"
-#include "storage/segment/segment.h"
-#include "storage/segment/variant/variant_column_reader.h"
+#include "util/json/path_in_data.h"
 
 namespace doris {
 using namespace segment_v2;
@@ -65,55 +64,15 @@ void add_search_binding_diagnostic(const IndexExecContext* 
index_context,
 // old rowsets may contain values without an executable SEARCH index.
 Status verify_missing_variant_path(const TSearchFieldBinding& binding, int 
column_index,
                                    IndexExecContext* index_context) {
-    auto* segment = index_context->segment();
-    if (segment == nullptr || !binding.__isset.parent_field_name ||
+    if (index_context->segment() == nullptr || 
!binding.__isset.parent_field_name ||
         !binding.__isset.subcolumn_path) {
         return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
                 "SEARCH cannot establish missing path '{}'", 
binding.field_name);
     }
-    const auto& read_schema = index_context->read_schema();
-    DORIS_CHECK_GE(column_index, 0);
-    DORIS_CHECK_LT(static_cast<size_t>(column_index), 
read_schema->num_column_ids());
-    const auto& column = 
*read_schema->column(read_schema->column_id(column_index));
-    const auto& opts = index_context->column_iter_opts();
-    DORIS_CHECK(opts.stats != nullptr);
-    const int32_t root_uid =
-            column.parent_unique_id() >= 0 ? column.parent_unique_id() : 
column.unique_id();
-    if (!segment->tablet_schema()->has_column_unique_id(root_uid)) {
-        return Status::OK();
-    }
-    std::shared_ptr<ColumnReader> column_reader;
-    Status st = segment->get_column_reader(root_uid, &column_reader, 
opts.stats, &opts.io_ctx);
-    if (st.is<ErrorCode::NOT_FOUND>()) {
-        // After DROP v(uid=1), ADD v(uid=2), an old segment cannot contain 
this scan's root.
-        // Resolve by the current uid so historical values of the same name 
cannot match.
-        return Status::OK();
-    }
-    RETURN_IF_ERROR(st);
-    auto* reader = dynamic_cast<VariantColumnReader*>(column_reader.get());
-    DORIS_CHECK(reader != nullptr);
-    RETURN_IF_ERROR(reader->load_external_meta_once(opts.stats, &opts.io_ctx));
-    const PathInData path(binding.subcolumn_path);
-    const auto* stats = reader->get_stats();
-    // Doc statistics enumerate stored paths without the sparse statistics 
limit. For example,
-    // a segment containing only `string4` can prove `string5` absent even in 
doc mode.
-    // An opaque root/ancestor value may contain the requested path, so it 
remains unavailable.
-    bool in_doc = stats->existed_in_doc_value_column("") ||
-                  stats->has_prefix_path_in_doc_value_column(path.get_path() + 
".");
-    std::string ancestor = path.get_path();
-    while (!in_doc) {
-        in_doc = stats->existed_in_doc_value_column(ancestor);
-        const auto dot = ancestor.rfind('.');
-        if (dot == std::string::npos) {
-            break;
-        }
-        ancestor.resize(dot);
-    }
-    // Truncated sparse statistics cannot prove absence, nor can an existing 
unindexed path.
-    if (reader->get_subcolumn_meta_by_path(path) != nullptr ||
-        reader->has_prefix_path(path, opts.stats, &opts.io_ctx) ||
-        reader->exist_in_sparse_column(path) || 
reader->is_exceeded_sparse_column_limit() ||
-        in_doc || stats->has_nested_group) {
+    bool absent = false;
+    RETURN_IF_ERROR(index_context->is_variant_path_absent(
+            column_index, PathInData(binding.subcolumn_path), &absent));
+    if (!absent) {
         return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
                 "SEARCH index unavailable for Variant field '{}'", 
binding.field_name);
     }
diff --git a/be/test/exprs/vcompound_pred_score_test.cpp 
b/be/test/exprs/vcompound_pred_score_test.cpp
index 35ee59dddf6..20dead97d0a 100644
--- a/be/test/exprs/vcompound_pred_score_test.cpp
+++ b/be/test/exprs/vcompound_pred_score_test.cpp
@@ -74,6 +74,45 @@ private:
     float _score;
 };
 
+// Publishes a fixed exact three-valued index result without scores.
+class ThreeValuedBitmapExpr final : public VExpr {
+public:
+    ThreeValuedBitmapExpr(std::initializer_list<uint32_t> true_rows,
+                          std::initializer_list<uint32_t> null_rows) {
+        set_node_type(TExprNodeType::MATCH_PRED);
+        for (uint32_t row : true_rows) {
+            _true_rows.add(row);
+        }
+        for (uint32_t row : null_rows) {
+            _null_rows.add(row);
+        }
+    }
+
+    const std::string& expr_name() const override {
+        static const std::string name = "ThreeValuedBitmapExpr";
+        return name;
+    }
+
+    Status execute(VExprContext*, Block*, int*) const override { return 
Status::OK(); }
+
+    Status execute_column_impl(VExprContext*, const Block*, const Selector*, 
size_t,
+                               ColumnPtr&) const override {
+        return Status::OK();
+    }
+
+    Status evaluate_inverted_index(VExprContext* context, uint32_t) override {
+        context->get_index_context()->set_index_result_for_expr(
+                this, segment_v2::InvertedIndexResultBitmap(
+                              std::make_shared<roaring::Roaring>(_true_rows),
+                              std::make_shared<roaring::Roaring>(_null_rows)));
+        return Status::OK();
+    }
+
+private:
+    roaring::Roaring _true_rows;
+    roaring::Roaring _null_rows;
+};
+
 class UnindexedExpr final : public VExpr {
 public:
     const std::string& expr_name() const override {
@@ -272,5 +311,32 @@ TEST(VCompoundPredScoreTest, 
NestedIncompleteScoringErrorSurvivesEmptyOrUnindexe
     }
 }
 
+TEST(VCompoundPredScoreTest, AndWithOnlyNullRowsLeftEvaluatesLaterBranches) {
+    // NOT (NULL AND FALSE) is TRUE on both rows. An AND that stopped after 
its first branch
+    // would keep both rows NULL, and NOT would then reject them.
+    auto conjunction = make_compound(
+            TExprOpcode::COMPOUND_AND,
+            
std::make_shared<ThreeValuedBitmapExpr>(std::initializer_list<uint32_t> {},
+                                                    
std::initializer_list<uint32_t> {0, 1}),
+            
std::make_shared<ThreeValuedBitmapExpr>(std::initializer_list<uint32_t> {},
+                                                    
std::initializer_list<uint32_t> {}));
+    auto root = make_not(conjunction);
+
+    std::vector<std::unique_ptr<segment_v2::IndexIterator>> iterators;
+    std::vector<IndexFieldNameAndTypePair> storage_types;
+    std::unordered_map<ColumnId, std::unordered_map<const VExpr*, bool>> 
status_map;
+    std::vector<ColumnId> col_ids;
+    auto index_context = std::make_shared<IndexExecContext>(col_ids, 
iterators, storage_types,
+                                                            status_map, 
nullptr);
+    auto expr_context = VExprContext::create_shared(root);
+    expr_context->set_index_context(index_context);
+
+    ASSERT_TRUE(root->evaluate_inverted_index(expr_context.get(), 2).ok());
+    const auto* result = index_context->get_index_result_for_expr(root.get());
+    ASSERT_NE(result, nullptr);
+    EXPECT_EQ(result->get_data_bitmap()->cardinality(), 2);
+    EXPECT_TRUE(result->get_null_bitmap()->isEmpty());
+}
+
 } // namespace
 } // namespace doris
diff --git a/be/test/storage/variant/variant_column_writer_reader_test.cpp 
b/be/test/storage/variant/variant_column_writer_reader_test.cpp
index c425fb7680a..165b8b8f978 100644
--- a/be/test/storage/variant/variant_column_writer_reader_test.cpp
+++ b/be/test/storage/variant/variant_column_writer_reader_test.cpp
@@ -46,6 +46,13 @@
 #include "core/value/variant/variant_batch_builder.h"
 #include "core/value/variant/variant_parquet_encoding.h"
 #include "exec/rowid_fetcher.h"
+#include "exprs/function/simple_function_factory.h"
+#include "exprs/vcast_expr.h"
+#include "exprs/vcompound_pred.h"
+#include "exprs/vexpr_context.h"
+#include "exprs/vliteral.h"
+#include "exprs/vmatch_predicate.h"
+#include "exprs/vslot_ref.h"
 #include "gtest/gtest.h"
 #include "runtime/descriptor_helper.h"
 #include "runtime/descriptors.h"
@@ -8641,6 +8648,164 @@ TEST_F(VariantColumnWriterReaderTest,
     EXPECT_NE(plan.regular_subcolumns[2].data_type->get_name().find("Array"), 
std::string::npos);
 }
 
+// Index evaluation of NOT(MATCH_ANY(CAST(v.<path> AS STRING), 'hit')), the 
form the planner sends
+// for `NOT v['<path>'] MATCH_ANY 'hit'`. It owns everything the index context 
refers to.
+struct NegatedMatchOnPath {
+    TabletColumnPtr leaf;
+    std::shared_ptr<VMatchPredicate> match;
+    VExprSPtr negation;
+    std::vector<ColumnId> col_ids {0};
+    std::vector<std::unique_ptr<segment_v2::IndexIterator>> no_indexes;
+    std::vector<IndexFieldNameAndTypePair> types;
+    std::unordered_map<ColumnId, std::unordered_map<const VExpr*, bool>> 
status_map;
+    OlapReaderStatistics stats;
+    std::shared_ptr<IndexExecContext> scan;
+    Status status;
+};
+
+static std::shared_ptr<VMatchPredicate> make_match_any_hit(const TabletColumn& 
leaf) {
+    const auto text_type = make_nullable(std::make_shared<DataTypeString>());
+    TMatchPredicate match;
+    match.__set_parser_type("english");
+    match.__set_parser_lowercase(true);
+    TFunctionName name;
+    name.__set_function_name("match_any");
+    TFunction fn;
+    fn.__set_name(name);
+    fn.__set_binary_type(TFunctionBinaryType::BUILTIN);
+    fn.__set_arg_types({create_type_desc(TYPE_STRING), 
create_type_desc(TYPE_STRING)});
+    fn.__set_ret_type(create_type_desc(TYPE_BOOLEAN));
+    TExprNode node;
+    node.__set_node_type(TExprNodeType::MATCH_PRED);
+    node.__set_type(create_type_desc(TYPE_BOOLEAN));
+    node.__set_is_nullable(true);
+    node.__set_num_children(2);
+    node.__set_fn(fn);
+    node.__set_match_predicate(match);
+    auto predicate = VMatchPredicate::create_shared(node);
+    TExprNode cast_node;
+    cast_node.__set_node_type(TExprNodeType::CAST_EXPR);
+    cast_node.__set_type(create_type_desc(TYPE_STRING));
+    cast_node.__set_is_nullable(true);
+    cast_node.__set_num_children(1);
+    auto cast = VCastExpr::create_shared(cast_node);
+    cast->_target_data_type = text_type;
+    auto slot = std::make_shared<VSlotRef>();
+    slot->set_node_type(TExprNodeType::SLOT_REF);
+    slot->set_column_id(0);
+    slot->_column_name = &leaf.name();
+    cast->add_child(slot);
+    predicate->add_child(cast);
+    TStringLiteral text;
+    text.__set_value("hit");
+    TExprNode literal;
+    literal.__set_node_type(TExprNodeType::STRING_LITERAL);
+    literal.__set_type(create_type_desc(TYPE_STRING));
+    literal.__set_string_literal(text);
+    predicate->add_child(VLiteral::create_shared(literal));
+    predicate->_function = SimpleFunctionFactory::instance().get_function(
+            "match_any",
+            {{nullptr, text_type, "v"}, {nullptr, 
std::make_shared<DataTypeString>(), "q"}},
+            make_nullable(std::make_shared<DataTypeUInt8>()));
+    DORIS_CHECK(predicate->_function != nullptr);
+    return predicate;
+}
+
+static std::unique_ptr<NegatedMatchOnPath> evaluate_negated_match_on_path(
+        segment_v2::Segment* segment, const std::string& path) {
+    auto run = std::make_unique<NegatedMatchOnPath>();
+    const auto& parent = segment->tablet_schema()->column(0);
+    auto leaf = std::make_shared<TabletColumn>();
+    leaf->set_name(parent.name() + "." + path);
+    leaf->set_type(FieldType::OLAP_FIELD_TYPE_STRING);
+    leaf->set_unique_id(-1);
+    leaf->set_parent_unique_id(parent.unique_id());
+    leaf->set_is_nullable(true);
+    // FE sends `v['a.b']` as the single path component `a.b`.
+    leaf->set_path_info(PathInData(parent.name(), std::vector<std::string> 
{path}));
+    run->leaf = leaf;
+    run->match = make_match_any_hit(*leaf);
+    TExprNode not_node;
+    not_node.__set_node_type(TExprNodeType::COMPOUND_PRED);
+    not_node.__set_opcode(TExprOpcode::COMPOUND_NOT);
+    not_node.__set_type(create_type_desc(TYPE_BOOLEAN));
+    not_node.__set_is_nullable(true);
+    not_node.__set_num_children(1);
+    run->negation = VCompoundPred::create_shared(not_node);
+    run->negation->add_child(run->match);
+
+    run->no_indexes.resize(1);
+    run->types = {{leaf->name(), std::make_shared<DataTypeString>()}};
+    run->status_map[0][run->match.get()] = false;
+    segment_v2::ColumnIteratorOptions opts;
+    opts.stats = &run->stats;
+    run->scan = std::make_shared<IndexExecContext>(
+            run->col_ids, run->no_indexes, run->types, run->status_map, 
nullptr, segment, opts,
+            std::make_shared<Schema>(std::vector<TabletColumnPtr> {leaf},
+                                     std::vector<ColumnId> {0}));
+    VExprContext context(run->negation);
+    context.set_index_context(run->scan);
+    run->status = run->negation->evaluate_inverted_index(&context, 2);
+    return run;
+}
+
+TEST_F(VariantColumnWriterReaderTest, 
test_match_returns_null_rows_for_absent_variant_path) {
+    init_variant_tablet(41006);
+    auto rowset = create_variant_rowset({{R"({"missing":"hit"})", R"({})"}}, 
1);
+    std::vector<segment_v2::SegmentSharedPtr> segments;
+    
ASSERT_TRUE(std::static_pointer_cast<BetaRowset>(rowset)->load_segments(&segments).ok());
+    ASSERT_EQ(1, segments.size());
+
+    // No row stores `absent`, so the MATCH is NULL on both rows, and so is 
its negation.
+    const auto run = evaluate_negated_match_on_path(segments.front().get(), 
"absent");
+    ASSERT_TRUE(run->status.ok()) << run->status;
+    for (const VExpr* expr :
+         std::initializer_list<const VExpr*> {run->match.get(), 
run->negation.get()}) {
+        const auto* result = run->scan->get_index_result_for_expr(expr);
+        ASSERT_NE(nullptr, result);
+        EXPECT_TRUE(result->get_data_bitmap()->isEmpty());
+        EXPECT_EQ(2, result->get_null_bitmap()->cardinality());
+    }
+    EXPECT_TRUE(run->status_map[0][run->match.get()]);
+}
+
+TEST_F(VariantColumnWriterReaderTest, 
test_match_reads_rows_for_unindexed_variant_path) {
+    init_variant_tablet(41007);
+    auto rowset = create_variant_rowset({{R"({"missing":"hit"})", R"({})"}}, 
1);
+    std::vector<segment_v2::SegmentSharedPtr> segments;
+    
ASSERT_TRUE(std::static_pointer_cast<BetaRowset>(rowset)->load_segments(&segments).ok());
+    ASSERT_EQ(1, segments.size());
+    const auto& parent = segments.front()->tablet_schema()->column(0);
+    
ASSERT_TRUE(segments.front()->tablet_schema()->inverted_indexs(parent.unique_id()).empty());
+
+    // Row 0 stores "hit" at `missing` without an index, so only row 
evaluation can answer it.
+    const auto run = evaluate_negated_match_on_path(segments.front().get(), 
"missing");
+    ASSERT_TRUE(run->status.ok()) << run->status;
+    EXPECT_FALSE(run->scan->has_index_result_for_expr(run->match.get()));
+    EXPECT_FALSE(run->scan->has_index_result_for_expr(run->negation.get()));
+    EXPECT_FALSE(run->status_map[0][run->match.get()]);
+}
+
+TEST_F(VariantColumnWriterReaderTest, 
test_match_reads_rows_for_legacy_dotted_variant_path) {
+    init_variant_tablet(41008);
+    // V2 keeps the path metadata inline, so no external meta store can answer 
the prefix `a.b.`.
+    
_tablet_schema->set_storage_format(TabletStorageFormatPB::TABLET_STORAGE_FORMAT_V2);
+    init_tablet_from_current_schema(41008);
+    auto rowset = create_variant_rowset({{R"({"a":{"b":{"c":"hit"}}})", 
R"({})"}}, 1);
+    std::vector<segment_v2::SegmentSharedPtr> segments;
+    
ASSERT_TRUE(std::static_pointer_cast<BetaRowset>(rowset)->load_segments(&segments).ok());
+    ASSERT_EQ(1, segments.size());
+
+    // Without escaped keys, the segment stores row 0 under a -> b -> c, and 
the read plan reads
+    // `v['a.b']` from there as {"c":"hit"}. The path is stored, so only row 
evaluation can
+    // answer the MATCH.
+    const auto run = evaluate_negated_match_on_path(segments.front().get(), 
"a.b");
+    ASSERT_TRUE(run->status.ok()) << run->status;
+    EXPECT_FALSE(run->scan->has_index_result_for_expr(run->match.get()));
+    EXPECT_FALSE(run->scan->has_index_result_for_expr(run->negation.get()));
+    EXPECT_FALSE(run->status_map[0][run->match.get()]);
+}
+
 TEST_F(VariantColumnWriterReaderTest,
        
test_streaming_compaction_writer_streams_regular_array_paths_across_batches) {
     if (!nested_group_write_path_available()) {
diff --git a/regression-test/data/search/test_search_score_boolean_branches.out 
b/regression-test/data/search/test_search_score_boolean_branches.out
index d68e69ed252..6c5a3a4c797 100644
--- a/regression-test/data/search/test_search_score_boolean_branches.out
+++ b/regression-test/data/search/test_search_score_boolean_branches.out
@@ -57,3 +57,35 @@
 7      0.4932
 8      0
 9      0.4932
+
+-- !variant_search --
+1      1.3164
+3      0.833
+5      0.833
+9      1.6659
+
+-- !variant_match_or --
+1      1.3164
+3      0.833
+5      0.833
+9      1.6659
+
+-- !variant_not_absent --
+1      0.6582
+2      0
+3      0.833
+6      0
+9      0.833
+
+-- !nullable_not_and --
+2
+3
+
+-- !variant_not_and_absent --
+2
+4
+6
+
+-- !variant_dotted_path --
+1
+
diff --git 
a/regression-test/suites/search/test_search_score_boolean_branches.groovy 
b/regression-test/suites/search/test_search_score_boolean_branches.groovy
index 39bd56cf107..1689a3b868a 100644
--- a/regression-test/suites/search/test_search_score_boolean_branches.groovy
+++ b/regression-test/suites/search/test_search_score_boolean_branches.groovy
@@ -130,4 +130,123 @@ suite("test_search_score_boolean_branches", "p0") {
             }
         }
     }
+
+    // Each INSERT writes its own segment, so some segments store only v.title 
or only v.content.
+    // Keep every path materialized and indexed; the fuzzy defaults may store 
paths in the sparse
+    // or doc-value column, where a segment cannot prove a path absent.
+    sql """ set default_variant_enable_doc_mode = false """
+    sql """ set default_variant_max_subcolumns_count = 0 """
+    sql "DROP TABLE IF EXISTS test_search_score_variant_absent_path"
+    sql """
+        CREATE TABLE test_search_score_variant_absent_path (
+            id INT NOT NULL,
+            v VARIANT NULL,
+            INDEX idx_v(v) USING INVERTED PROPERTIES("parser" = "english")
+        ) ENGINE=OLAP
+        DUPLICATE KEY(id)
+        DISTRIBUTED BY HASH(id) BUCKETS 1
+        PROPERTIES (
+            "replication_allocation" = "tag.location.default:1",
+            "disable_auto_compaction" = "true"
+        )
+    """
+    sql """
+        INSERT INTO test_search_score_variant_absent_path VALUES
+            (1, parse_to_variant('{"title":"apple search 
guide","content":"search database engine"}')),
+            (2, parse_to_variant('{"title":"banana guide","content":"analytics 
engine"}'))
+    """
+    sql """
+        INSERT INTO test_search_score_variant_absent_path VALUES
+            (3, parse_to_variant('{"title":"apple archive"}')),
+            (4, parse_to_variant('{"title":"database manual"}'))
+    """
+    sql """
+        INSERT INTO test_search_score_variant_absent_path VALUES
+            (5, parse_to_variant('{"content":"apple search"}')),
+            (6, parse_to_variant('{"content":"database analytics"}'))
+    """
+    sql """
+        INSERT INTO test_search_score_variant_absent_path VALUES
+            (7, parse_to_variant('{"category":"apple search metadata"}')),
+            (8, parse_to_variant('{}')),
+            (9, parse_to_variant('{"title":"apple database","content":"search 
analytics"}'))
+    """
+
+    order_qt_variant_search """
+        SELECT id, ROUND(score(), 4) AS bm25_score
+        FROM test_search_score_variant_absent_path
+        WHERE search('v.title:apple OR v.content:search')
+        ORDER BY score() DESC LIMIT 100
+    """
+
+    order_qt_variant_match_or """
+        SELECT id, ROUND(score(), 4) AS bm25_score
+        FROM test_search_score_variant_absent_path
+        WHERE v['title'] MATCH_ANY 'apple' OR v['content'] MATCH_ANY 'search'
+        ORDER BY score() DESC LIMIT 100
+    """
+
+    // An absent v.content is NULL, so NOT keeps a row only when v.title 
matches.
+    order_qt_variant_not_absent """
+        SELECT id, ROUND(score(), 4) AS bm25_score
+        FROM test_search_score_variant_absent_path
+        WHERE NOT (v['content'] MATCH_ANY 'search') OR v['title'] MATCH_ANY 
'apple'
+        ORDER BY score() DESC LIMIT 100
+    """
+
+    sql "DROP TABLE IF EXISTS test_search_score_nullable_not_and"
+    sql """
+        CREATE TABLE test_search_score_nullable_not_and (
+            id INT NOT NULL,
+            title STRING NULL,
+            content STRING NULL,
+            INDEX idx_title(title) USING INVERTED PROPERTIES("parser" = 
"english"),
+            INDEX idx_content(content) USING INVERTED PROPERTIES("parser" = 
"english")
+        ) ENGINE=OLAP
+        DUPLICATE KEY(id)
+        DISTRIBUTED BY HASH(id) BUCKETS 1
+        PROPERTIES ("replication_allocation" = "tag.location.default:1")
+    """
+    sql """
+        INSERT INTO test_search_score_nullable_not_and VALUES
+            (1, NULL, 'hit'), (2, NULL, 'miss'), (3, 'apple', 'miss')
+    """
+
+    // Keep NOT over AND. NULL AND FALSE is FALSE, so NOT keeps row 2 of the 
nullable table and
+    // row 4 of the VARIANT table, which has no v.content and a v.title 
without 'apple'.
+    sql """ set disable_nereids_expression_rules = 'SIMPLIFY_NOT_EXPR' """
+    order_qt_nullable_not_and """
+        SELECT id FROM test_search_score_nullable_not_and
+        WHERE NOT (title MATCH_ANY 'x' AND content MATCH_ANY 'hit')
+    """
+    order_qt_variant_not_and_absent """
+        SELECT id FROM test_search_score_variant_absent_path
+        WHERE NOT (v['content'] MATCH_ANY 'search' AND v['title'] MATCH_ANY 
'apple')
+    """
+    sql """ set disable_nereids_expression_rules = '' """
+
+    // Without escaped keys, the segment stores row 1 under a.b.c, and 
v['a.b'] reads
+    // {"c":"hit"} from there.
+    sql "DROP TABLE IF EXISTS test_search_score_variant_dotted_path"
+    sql """
+        CREATE TABLE test_search_score_variant_dotted_path (
+            id INT NOT NULL,
+            v VARIANT NULL,
+            INDEX idx_v(v) USING INVERTED PROPERTIES("parser" = "english")
+        ) ENGINE=OLAP
+        DUPLICATE KEY(id)
+        DISTRIBUTED BY HASH(id) BUCKETS 1
+        PROPERTIES (
+            "replication_allocation" = "tag.location.default:1",
+            "disable_auto_compaction" = "true"
+        )
+    """
+    sql """
+        INSERT INTO test_search_score_variant_dotted_path VALUES
+            (1, parse_to_variant('{"a":{"b":{"c":"hit"}}}')),
+            (2, parse_to_variant('{"a":{"x":"hit"}}'))
+    """
+    order_qt_variant_dotted_path """
+        SELECT id FROM test_search_score_variant_dotted_path WHERE v['a.b'] 
MATCH_ANY 'hit'
+    """
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to