Repository navigation
[fix](inverted index) Keep the SNII array element gap when MATCH runs by rows - #71215
airborne12 wants to merge 4 commits into
Conversation
… by rows ### Background An inverted index on an ARRAY<STRING> column indexes the analyzed elements of a row as one document, and a phrase query (MATCH_PHRASE, MATCH_PHRASE_PREFIX, MATCH_PHRASE_EDGE) matches only adjacent positions. CLucene formats (V1/V2/V3) write the elements back to back, so a phrase can cross elements; SNII leaves one empty position after every element (`SniiIndexColumnWriter::add_array_values`), so it cannot. When a segment has no index for the column, BE evaluates MATCH by rows, and since apache#68661 that evaluation spaces elements like CLucene. ### What problem does this PR solve? Issue Number: None Related PR: apache#68661 (added the row-evaluation positions across array elements), apache#39062 (made FE reject a parser on ARRAY indexes), apache#70352 (branch-4.2 backport of apache#68661 where review found this) PR Type: Bugfix Problem Summary: For an analyzed SNII index on an ARRAY column, row evaluation and the index disagree on a phrase that crosses two elements: for `['hello', 'world']`, `MATCH_PHRASE 'hello world'` returns the row when the segment is read by rows but not on the SNII index (MATCH_PHRASE_PREFIX and MATCH_PHRASE_EDGE too). The answer then depends on whether each segment has its index. This PR makes row evaluation space the elements of SNII segments as SNII does; CLucene segments are unchanged. ### Details - **Change map:** 31 lines of production code in 4 files; 287 lines are the new BE unit test. - **Frequency:** Not observed; found by code review on apache#70352 and reproduced in a BE unit test with real SNII and V2 index files. Since apache#39062 FE rejects a parser, analyzer, or normalizer on ARRAY columns, and VARIANT array subcolumns inherit their index without one, so indexes created by current versions cannot trigger it. It triggers for an ARRAY index created with a parser before apache#39062 once its partitions are written in SNII through the partition storage format rollout (`partition_inverted_index_storage_format = "SNII"`). - **Root cause:** `match_phrase_data_tokens` in `match.cpp` moved the position base by the last token position of each element, as CLucene does. SNII moves it one position further per element, also for an element without tokens, so row evaluation made SNII's non-adjacent terms adjacent. - **Why existing tests missed it:** The array phrase cases in `function_match_test.cpp` (from apache#68661) check row evaluation with a context that does not know the storage format and expect CLucene spacing; `snii_golden_corpus_test.cpp` checks only the SNII index. No unit test compared the two. No regression suite can create an analyzed ARRAY index on current versions. - **Fix:** `VMatchPredicate::execute_column_impl` reads the storage format of the segment it evaluates (from the expression's `IndexExecContext`) and gives row evaluation an analyzer context whose new `array_element_position_gap` is 1 for SNII and 0 otherwise; `match_phrase_data_tokens` adds it after every analyzed element. The format is taken per segment rather than from FE because FE keeps the storage format per partition. The SNII writer is unchanged, so existing segments keep their meaning. - **Behavior change:** row evaluation on SNII segments no longer matches a phrase across two ARRAY elements; CLucene segments and every other MATCH function are unchanged. - **Other paths and branches:** - MATCH_PHRASE_PREFIX and MATCH_PHRASE_EDGE share the positions: fixed and tested. MATCH_ANY, MATCH_ALL and MATCH_REGEXP ignore positions. Keyword elements get no gap, as SNII writes them at consecutive positions. - MATCH_PHRASE with slop (`'hello world ~1'`): still to fix, separately. Row evaluation of analyzed columns does not parse the slop on any format and returns no row where the SNII and V2 indexes do. This predates this PR. - Row evaluation outside the storage layer (scanner-level conjuncts of AGG and merge-on-read tables, or MATCH above the scan) has no segment and keeps CLucene spacing; none of these can have an analyzed SNII ARRAY index. - Branches: master has the bug. branch-4.2 has SNII but not apache#68661; apache#70352 brings it, so pick this with it. branch-4.1 and branch-4.0 have no SNII. ### Testing - New BE UT `ArrayPhraseIndexParityTest` (`vmatch_predicate_test.cpp`) writes the same arrays (a phrase across elements, inside one element, and across an empty or NULL element) into an SNII and a V2 index, then runs `VMatchPredicate` by rows and on the index for MATCH_PHRASE, MATCH_PHRASE_PREFIX and MATCH_PHRASE_EDGE. Before the fix the SNII case fails for all three (rows `{1,1,1,1,1}`, index `{0,1,0,0,0}`) and the V2 case passes; after it both pass. - `run-be-ut.sh` with FunctionMatchTest, VMatchPredicateTest, ArrayPhraseIndexParityTest, Snii*, DorisSnii* and InvertedIndexArrayTest: 1561 tests passed (ASAN, local). - `./build.sh --be --fe` (ASAN), `clang-format.sh`, `check-build-hygiene.sh`: pass. `run-clang-tidy.sh`: no findings on changed lines, though the local clang-tidy could not fully analyze the files. - No regression case: FE rejects an analyzed ARRAY index on master, so a suite cannot reach this path. ### Release note On SNII partitions of an ARRAY column whose inverted index has a parser (only possible for indexes created before apache#39062), MATCH_PHRASE, MATCH_PHRASE_PREFIX and MATCH_PHRASE_EDGE without the index no longer match a phrase across two array elements, which agrees with the SNII index. ### Check List (For Author) - Behavior changed: Yes (see Details) - Does this need documentation: No - Pre-submission status: Partially verified: no end-to-end regression case, because current FE cannot create the analyzed ARRAY index that triggers it; covered by a BE unit test with real SNII and V2 index files. ### AI Disclosure - Tool: Claude Code (Claude Opus 5.5) - Generated: code, tests, this description - Human review: Pending author review Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
run buildall |
|
/review |
hello-stephen
left a comment
There was a problem hiding this comment.
I found one P2 correctness issue: selecting ARRAY phrase spacing from the presence of a segment context makes direct and nested MATCH projections disagree, even when inverted-index querying is disabled. Please make the positional policy consistent across those evaluation paths. The gap arithmetic itself matches the SNII writer.
No existing review comments were supplied, so there are no previously reported blocking findings to retain or resolve on this head.
Critical checkpoint conclusions
- Goal and proof: The change preserves SNII's extra position between analyzed ARRAY elements in segment row evaluation.
match.cpp:440-469matchesSniiIndexColumnWriter::add_array_values(snii_index_writer.cpp:300-328), including tokenless non-NULL elements and skipped NULL elements. The new parity tests support this scoped behavior, but the projection inconsistency below leaves the overall fix incomplete. - Small, clear and focused: The five changed files contain the position-gap field, context selection, shared phrase adjustment and tests. No unrelated product changes were found in the authoritative diff.
- Concurrency and locking: No new lock or thread is introduced.
SegmentIterator::_construct_compound_expr_contextclones contexts per segment;FunctionContext::clonegives each execution context separate thread-local state. The new assignment does not mutate the shared analyzer contexts after construction. - Lifecycle and static initialization: Both context variants retain the existing shared analyzer/provider ownership.
TextAnalyzeris immutable and eachBlockTokenizerowns its stream (text_analyzer.h,match.cpp). No new ownership cycle or cross-translation-unit initializer was found. The test fixture restores global cache pointers before destroying its caches. - Compatibility: No persisted format, Thrift/protobuf definition, FE–BE payload or configuration changes. The new format check reads the same segment schema used by
Segment::_open_index_file_reader(segment.cpp:417-422); legacy formats retain gap zero. Query-result compatibility is affected by the reported projection issue. - Functionally parallel paths: Phrase, phrase-prefix and phrase-edge share
match_phrase_data_tokens; empty token spans do not change ANY/ALL/REGEXP callbacks. However, direct MATCH projections are virtualized byPushDownMatchProjectionAsVirtualColumn, while nested MATCH remains in scanner/operator projections withoutIndexExecContext. This is the verified P2 finding. - Special conditions and comments: The new comments explain why SNII uses a gap and why empty analyzed elements must reach the callback. The
analyzedcondition preserves keyword behavior. The assumption that execution location can select the semantic policy is insufficient for wrapped projections (vmatch_predicate.cpp:254-263). - Test coverage:
ArrayPhraseIndexParityTestwrites real SNII/V2 indexes and evaluates rows before index results exist, covering all three phrase modes across five ARRAY shapes. It injects segment context directly, so it misses direct-versus-nested SQL projections and production fallback integration. Existingtest_match_projection_virtual_column.groovy, Test 12, confirms compound MATCH can remain above storage, but uses scalar strings. - Test results: The expected SNII vector
{false,true,false,false,false}and V2 vector{true,true,true,true,true}agree with the inspected writer/matcher rules. No regression output files changed. Test execution was not performed. - Observability: This change adds no distributed operation requiring a new metric. Existing MATCH debug logging and segment index statistics remain available (
FunctionMatchBase::execute_impl,SegmentIterator). No separate observability defect found. - Performance: Element traversal remains linear and token streams remain reused within a block. Context selection adds a shared-pointer assignment per fallback call and one context copy per predicate; source inspection found no material new hot-path allocation or repeated scan. No performance measurements were run.
- Other core invariants: The reported issue affects query correctness. Nullable/const materialization and error propagation remain unchanged (
FunctionMatchBase::execute_impl,VExprContext::execute). No new significant allocation, transaction visibility, version, delete-bitmap, persistence or data-write mechanism is introduced.
Requester focus
No additional focus was supplied.
Validation and coverage limits
Source coverage is complete for all five changed files and their relevant available Doris call chains. Two review rounds included the main risk scan, three delegated coverage areas, independent challenges of the finding, base/head attribution, deduplication and verification of the inline diff position.
- Builds, BE unit tests, SQL regressions, sanitizer checks, style/static gates and benchmarks were not run, as requested. The example result in the inline finding is derived from source execution paths, not an executed SQL reproduction.
- Runtime behavior of disabled/missing-index scans and direct/nested projections remains untested. The new fixture also omits absent context, NULL rows, const ARRAYs, stopword-only elements, custom analyzer gaps and slop. These are validation limits; their changed source paths were inspected.
- Third-party CLucene
invertFieldsource is not checked out. Its unchanged zero-gap behavior was assessed through the available Doris writer/bridge code and test expectations, without independently inspecting or running that third-party implementation.
No other unresolved source question remains. No product code was changed and nothing was published to GitHub.
Review converged after 2 round(s).
| index_context->segment()->tablet_schema()->get_inverted_index_storage_format() == | ||
| InvertedIndexStorageFormatPB::SNII; | ||
| fn_context->set_function_state(FunctionContext::FunctionStateScope::THREAD_LOCAL, | ||
| snii_segment ? _snii_analyzer_ctx : _analyzer_ctx); |
There was a problem hiding this comment.
[P2] Keep phrase spacing consistent above and inside the segment
With enable_match_without_inverted_index=true and enable_inverted_index_query=false, consider an SNII DUPLICATE KEY table with an English phrase index and a non-NULL arr=['hello','world']:
SELECT arr MATCH_PHRASE 'hello world' AS m,
NOT(arr MATCH_PHRASE 'hello world') AS n
FROM t;PushDownMatchProjectionAsVirtualColumn.unwrapMatch() virtualizes only the direct MATCH alias, leaving the nested MATCH in the ordinary projection. The resulting source-derived shape is:
Project[m=virtual_m, n=NOT(MATCH(arr, 'hello world'))]
OlapScan[virtual_m=MATCH(arr, 'hello world')]
The virtual expression has a segment context, so this selection gives it gap 1 and m=false. The nested MATCH executes in the scanner/operator projection without that context, gets gap 0 and returns true, making n=false too. Both run by rows because index querying is disabled; at the base both used gap 0 and returned (true,false). Physical CSE cannot reconcile them after the direct MATCH has become a virtual slot.
Please carry a consistent positional policy to every evaluation of the bound MATCH, including wrapped projections, and add a SQL regression for this case. The new fixture always injects a segment context and misses this path.
There was a problem hiding this comment.
Confirmed and fixed in 2639cd3.
On e3c8806 the two evaluations differ as you describe. The virtual column's context is cloned in SegmentIterator::_construct_compound_expr_context with an IndexExecContext that holds the segment, so it got the SNII gap. NOT(MATCH) stays in Scanner::_projections, which have no index context, so it got none. Scanner-level conjuncts (merge-on-read and AGG tables, or conjuncts re-cloned when a runtime filter arrives late) had the same gap problem. A BE UT that runs MATCH_PHRASE in an OlapScanner's conjunct and projection on an SNII tablet failed on e3c8806: ['hello','world'] matched.
The spacing now follows the index format of the tablet the rows come from. Whether a segment context exists no longer matters:
VExprContextcarries the inverted index storage format of the tablet whose rows it evaluates.SegmentIteratorsets it to the segment's format on the pushed-down and virtual-column contexts it clones.OlapScannersets it to its tablet's format on its conjuncts, projections and intermediate projections. It sets it again when a late runtime filter re-clones the conjuncts.VMatchPredicatereads only this value.
A tablet keeps the format it was created with: partition_inverted_index_storage_format applies only to new partitions. So both values agree for every row. In your example, m and n now come out (false, true) on SNII and (true, false) on CLucene, whether the index is used or not.
Not covered: an operator above the scan, such as a projection or filter after a join or aggregation, gets rows from several tablets, and those can be in different formats under the partition rollout. It has no single format to follow, so it keeps the CLucene spacing, as before this PR. A MATCH the optimizer leaves there can still disagree with one evaluated in the scan of an SNII tablet. The shapes PushDownMatchProjectionAsVirtualColumn produces (Project -> OlapScan and Project -> Filter -> OlapScan, wrapped or not) all evaluate in the scanner or the segment and are covered.
Tests:
ScannerLateArrivalRfTest.olap_scanner_match_follows_tablet_index_format(the reproduction above; it passes now).ScannerLateArrivalRfTest.late_arrival_conjuncts_keep_tablet_index_format.SegmentIteratorVirtualColumnTest.ExprContextsCarryTheSegmentIndexFormat.ArrayPhraseIndexParityTestnow also evaluates the rows in a context like the scanner's (format only, no index) and compares them with the real SNII and V2 index files.
No SQL regression: since #39062, FE rejects a parser on an ARRAY index (INVERTED index with parser: english is not supported for array column), so no suite can create the table in your example on current versions.
|
run cloud_p0 |
…x format in the scanner too MATCH by rows used the SNII array element gap only when its context had a segment. A MATCH projection pushed into the segment as a virtual column and NOT(MATCH) left in the scanner's projection could then disagree on the same row of an SNII tablet. VExprContext now carries the index format of the tablet whose rows it evaluates. The segment iterator sets it from the segment, OlapScanner from its tablet (again when a late runtime filter re-clones the conjuncts), and VMatchPredicate reads only that value. Rows above the scan keep the CLucene spacing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
run buildall |
|
/review |
hello-stephen
left a comment
There was a problem hiding this comment.
One new P2 correctness issue remains: short-circuit point queries omit the tablet format, so the same analyzed-array projection can return a different result when enable_short_circuit_query is toggled. The inline comment gives a source-derived example using a legal scalar English index and a computed ARRAY.
The earlier P2 comment 4750849256 is addressed for its scanner-versus-segment reproduction: both contexts now receive the same tablet format, including scanner projections and late-runtime-filter clones. The supplied history contains no P0/P1 comment to retain as blocking. The above-scan, potentially multi-tablet limitation already disclosed in reply 4763731171 remains outside that fix; I have not duplicated it.
Critical checkpoint conclusions
- Goal and correctness: Scan-local phrase positioning now follows the actual writer:
match_phrase_data_tokensinbe/src/exprs/function/match.cppadvances by the last position plus the selected gap, matchingSniiIndexColumnWriter::add_array_values.ArrayPhraseIndexParityTestasserts parity with real SNII/V2 files. The point-query path still needs the propagation described inline. - Scope and reuse: The changes are focused on one analyzer-context gap and tablet-format propagation through existing expression contexts. Exact, prefix and edge phrases share the corrected helper; no duplicate matching algorithm was added.
- Concurrency and locking: Scanner workers own cloned
VExprContext/FunctionContextinstances (vexpr_context.cpp:164,function_context.cpp:53), so their format and function-state updates are isolated. Point-queryReusablecontexts are shared throughLookupConnectionCache::get; overlapping prepared executions after a timeout can reuse them. Address the point-query omission with request-owned evaluation state rather than mutating a cached context's tablet binding. No lock-order changes were introduced. - Lifecycle and static initialization: The two analyzer contexts retain shared ownership of the same analyzer/provider; their configuration is initialized in
VMatchPredicate's constructor. Segment contexts are cloned before attaching segment-specific state inSegmentIterator::_construct_compound_expr_context. No new ownership cycle or cross-translation-unit initializer was found. - Configuration: No configuration item is added. Existing tablet format metadata selects the fallback policy; local/cloud rowset writers inherit that format from their owning tablet (
Tablet::_init_context_common_fields,CloudTablet::create_rowset_writer). - Compatibility: No persisted index bytes or reader implementation changes. SNII uses gap 1; CLucene retains gap 0. Scalar strings and unanalyzed arrays keep their previous results.
RowsetMeta::set_tablet_schemapreserves the persisted format during schema replacement. Mixed-version runtime behavior was not exercised. - Thrift/protobuf and FE–BE variables: No definitions or transmitted fields change; the optional format in
VExprContextis BE-local and uses the existing enum. - Parallel paths: Pushed-down expressions, virtual columns, scanner conjuncts, final/CSE projections and late-filter clones are covered. Point-query output evaluation is the verified omission (
Reusable::init,PointQueryExecutor::_output_data). Lambda bodies reuse their parent context;FunctionMultiMatch::execute_implexplicitly rejects row fallback. - Conditional checks and nullable handling: The unset-format branch accommodates non-OLAP scanners; format selection is documented in
VMatchPredicate. NULL array elements remain skipped, while tokenless non-NULL elements now consume the writer's gap. Default function NULL handling and input materialization inFunctionMatchBase::execute_implpreserve nullable/constant boundaries. - Test coverage: The three changed BE test files cover real-index exact/prefix/edge parity, SNII/V2 scanner conjunct/projection evaluation, late-filter re-cloning and both segment-context collections. They are registered by
be/test/CMakeLists.txt. They omit the point-query path. FE rejects analyzed ordinary ARRAY index DDL (InvertedIndexUtilparser/analyzer guards), but the computed-array example avoids that restriction and permits a SQL regression. - Changed test results: No regression result files change. The new English-fixture expectations agree with the writers: SNII prevents adjacent-element phrases, while V2 permits them, including across empty/NULL elements. These assertions were inspected, not executed.
- Memory, errors and performance: The extra analyzer-context copy occurs once per expression; fallback updates a shared pointer per block, with no new per-row context copy or index I/O. Existing task memory attachment and
RETURN_IF_ERRORpropagation remain in place. No material new allocation or complexity regression was established by source inspection. - Observability: This changes evaluation semantics without adding an operational stage or distributed request. Existing MATCH diagnostics remain available; no additional telemetry requirement was identified.
- Transactions, persistence and data writes: The supplied changes do not alter transaction visibility, version selection, delete bitmaps, metadata logging or write atomicity.
- Other issues: No additional independently reportable finding was established. Phrase-slop fallback limitations are present at the base; the previously disclosed above-scan limitation is not a new inline finding.
Requester focus
No additional focus was supplied.
Validation and coverage limits
Source coverage is complete for all 12 paths and all hunks in the supplied authoritative diff. All head-side hunk lines were checked against 2639cd3f78cff3d924d04b8fb7888ea2ce7e5c94; the inline anchor is verified. Review converged after three rounds with three review subagents. Scope follows the supplied diff, which excludes additional unrelated hunks in a raw pinned-base/head comparison.
No build, unit test, SQL query, sanitizer, or runtime/cloud rollout check was run, as requested. The new point-query example is source-derived and still needs runtime confirmation. The three BE test suites were not executed. Outer-NULL/all-constant nullable arrays, arbitrary custom-analyzer position streams, concurrent prepared-request behavior and mixed-format partition queries remain unvalidated at runtime; the fixtures do not establish those dimensions. No changed source area or separate source-reachability question remains uncovered.
Review converged after 3 round(s).
| // Above the scanner the tablet is unknown, and the rows keep the CLucene element spacing. | ||
| auto* fn_context = context->fn_context(_fn_context_index); | ||
| const bool snii_rows = | ||
| context->inverted_index_storage_format() == InvertedIndexStorageFormatPB::SNII; |
There was a problem hiding this comment.
[P2] Carry the tablet format through short-circuit point queries
PointQueryExecutor::_output_data() evaluates the output contexts created by Reusable::init(). That initializer receives the tablet schema but never sets this new format field. On an SNII UNIQUE KEY MOW table with store_row_column=true and light_schema_change=true, an English inverted index on scalar s STRING, and row (id=1, s='hello'), consider this query with enable_match_without_inverted_index=true:
SELECT NOT(array(s, 'world') MATCH_PHRASE 'hello world')
FROM t WHERE id = 1;ExpressionTranslator::visitMatch() binds the English analyzer through input slot s, so this needs no unsupported ARRAY index. The NOT wrapper also keeps the MATCH out of direct virtual-column extraction. The source-derived execution paths are:
normal scan: scanner projection, SNII format -> gap 1 -> NOT(false) = true
short circuit: point-query output, unset format -> gap 0 -> NOT(true) = false
At the base both paths used gap 0. Please carry the current request tablet's format into point-query output evaluation too, accounting for cached prepared contexts, and add a short-circuit-on/off SQL regression for this computed-array case.
There was a problem hiding this comment.
Confirmed and fixed in cf4ad92 (together with a null-tablet guard in OlapScanner's constructor for ScannerContextTest.test_init).
Reusable::initnow recordsschema.get_inverted_index_storage_format()and sets it on every context in_output_exprs_ctxs(whichVMysqlResultWriter::writeexecutes directly without cloning).PointQueryExecutor::initcheckscache_handle->inverted_index_storage_format()against the target tablet's format alongside timezone and locale, so prepared queries crossing V2 and SNII partitions rebuildReusable(and request query-context resend on lightweight prepared requests) without mutating any in-flightReusableinstance.
Tests:
ReusableTest.OutputExprsFollowTabletInvertedIndexFormatchecksNOT(array(s, 'world') MATCH_PHRASE 'hello world')throughReusable::initacrossSNIIandV2tablet schemas.PointQueryIndexFormatTest.PreparedLookupRebuildsReusableAcrossV2AndSniiTabletsdrivesPointQueryExecutor::initandlookup_up()on real V2 and SNII MOW row-store tablets under a shared prepared UUID (covering V2 cache seed, lightweight resend on SNII, full SNII rebuild without mutating the retained V2Reusable, and warm SNII cache hit). Fails before the fix and passes after.- No handwritten
.outregression was added without a local cluster in this worktree (AGENTS.mdforbids handwritten.outfiles).
…rray-phrase-fallback
… point queries ### Background `VExprContext` carries the `InvertedIndexStorageFormatPB` of the tablet whose rows it evaluates so row-evaluated `MATCH` predicates (such as `MATCH_PHRASE` over computed arrays) use the SNII array element gap on SNII tablets and CLucene spacing on V2 tablets. `SegmentIterator` and `OlapScanner` set this format on their expression contexts, whereas short-circuit point queries (`PointQueryExecutor` / `Reusable`) build and cache their own output `VExprContext` instances. ### What problem does this PR solve? Issue Number: None Related PR: apache#71215 (aligns row-evaluated MATCH array element gap with the tablet's inverted index format) PR Type: Bugfix Problem Summary: 1. `Reusable::init` created `_output_exprs_ctxs` without setting the tablet schema's `InvertedIndexStorageFormatPB`, and `PointQueryExecutor::init` reused cached `Reusable` entries across partitions with different inverted index storage formats, so short-circuit point queries such as `SELECT NOT(array(s, 'world') MATCH_PHRASE 'hello world') FROM t WHERE id = 1` disagreed with normal scans on SNII tablets. 2. `OlapScanner::OlapScanner` dereferenced `_tablet_reader_params.tablet` unconditionally, causing BE unit tests that construct `OlapScanner` without a tablet (`ScannerContextTest.test_init`) to crash with a null dereference. ### Details - **Frequency:** Always, when a short-circuit point query evaluates a `MATCH_PHRASE` expression over an array on an SNII UNIQUE KEY MOW table (or reuses a prepared `LookupConnectionCache` entry across V2 and SNII partitions), and whenever `OlapScanner` is constructed without a tablet in unit tests. Found by code review and BE unit tests on apache#71215. - **Root cause:** `Reusable::init` ignored `schema.get_inverted_index_storage_format()` when preparing `_output_exprs_ctxs`, `PointQueryExecutor::init` checked only timezone and locale on `LookupConnectionCache` hits, and `OlapScanner`'s constructor assumed `_tablet_reader_params.tablet` was non-null. - **Why existing tests missed it:** The tests added in `2639cd3f78c` covered `SegmentIterator` and `OlapScanner` contexts (`ScannerLateArrivalRfTest`, `SegmentIteratorVirtualColumnTest`, `ArrayPhraseIndexParityTest`), not `Reusable` / `PointQueryExecutor` or `ScannerContextTest.test_init`. - **Fix:** Record `schema.get_inverted_index_storage_format()` in `Reusable` and propagate it to every context in `_output_exprs_ctxs`; check `cache_handle->inverted_index_storage_format()` against the target tablet's format in `PointQueryExecutor::init` so format switches rebuild `Reusable` (and ask FE to resend query context on lightweight prepared requests) without mutating in-flight `Reusable` instances; guard `_tablet_reader_params.tablet != nullptr` in `OlapScanner::OlapScanner`. - **Other paths and branches:** `PointQueryExecutor` evaluates `VExprContext` only in `_output_data()` through `_reusable->output_exprs()`, and `VMysqlResultWriter::write` executes those contexts directly without cloning. Applies to apache#71215 targeting `master`. - **Behavior change:** Short-circuit point queries on SNII tablets now evaluate row-level `MATCH` array expressions with SNII's element gap, matching normal scans, and rebuild cached prepared `Reusable` contexts when crossing V2 and SNII partitions. ### Testing - `ReusableTest.OutputExprsFollowTabletInvertedIndexFormat`: verifies `Reusable::init` propagates `SNII` and `V2` formats to `_output_exprs_ctxs` and evaluates `NOT(array(s, 'world') MATCH_PHRASE 'hello world')` accordingly. - `PointQueryIndexFormatTest.PreparedLookupRebuildsReusableAcrossV2AndSniiTablets`: verifies prepared lookups across V2 and SNII tablets request query-context resend on lightweight misses, evaluate SNII gap after rebuild without mutating an in-flight V2 `Reusable`, and hit the updated SNII cache entry afterward. Fails before the fix and passes after. - `ScannerContextTest.test_init`, `LookupConnectionCacheTest.*`, `ScannerLateArrivalRfTest.*`, `ArrayPhraseIndexParityTest.*`, and `SegmentIteratorVirtualColumnTest.*` (23 tests total) passed locally under ASAN. ### Release note None ### Check List (For Author) - Behavior changed: Yes (see Details) - Does this need documentation: No - Pre-submission status: Partially verified: no cluster SQL run; verified via BE unit tests under ASAN ### AI Disclosure - Tool: T3 Code (Gemini) - Generated: code, tests, commit message - Human review: pending review
|
run buildall |
|
/review |
hello-stephen
left a comment
There was a problem hiding this comment.
I recommend changes before merging. The row matcher now follows the SNII writer’s element gap for the zero-slop indexed ARRAY cases, and the two previously reported propagation gaps are addressed in their described execution paths. The current implementation still makes MATCH on unindexed and computed ARRAYs depend on the tablet format, adds a race when prepared point-query output contexts are shared, and causes avoidable prepared-cache misses across formats.
- Previous scan-projection P2 (comment
4750849256) — fixed for the reported direct and wrapped scan projections.SegmentIterator::_construct_compound_expr_context()stamps pushed-down and virtual expressions, andScanner::init()stamps conjuncts, final projections, and intermediate projections. Late runtime-filter clones are stamped again. The known above-scan limitation remains, as noted in the earlier thread. - Previous point-query P2 (comment
4763827422) — fixed for serial short-circuit execution.Reusable::init()stamps the executed contexts, and a format mismatch takes the existing full-context resend path without overwriting the earlier request’sReusable. This does not prevent the new race on a same-format cache hit. - No previously reported P0 or P1 finding was present in the supplied review threads.
Critical checkpoint conclusions
- Goal, correctness, and proof —
SniiIndexColumnWriter::add_array_values()andmatch_phrase_data_tokens()now agree on the SNII gap after each non-null element, including tokenless elements.ArrayPhraseIndexParityTestcompares on-disk SNII/V2 results with scanner- and segment-style fallback for exact, prefix, and edge phrases. The new format selection is too broad for unindexed computed inputs. - Scope and clarity — The positional change reuses the existing streaming matcher and does not touch persisted index data. Carrying the format across the execution paths is clear, but
VMatchPredicate::execute_column_impl()selects by tablet alone where it needs to distinguish the indexed operand from one that only borrows its analyzer. - Concurrency and lock order — Scanner and segment contexts are cloned before they are stamped. Point-query RPCs can overlap on the same cached context after an FE timeout. The LRU protects lookup and ownership, and the block mutex protects the block pool, but neither protects the new
FunctionContextwrite. No new lock nesting was added. - Lifecycle and initialization —
VExprContext::clone()shares the expression tree and creates separate function contexts. The analyzer objects use shared ownership, and replacing aLookupConnectionCacheentry does not invalidate older holders. The patch adds no static-initialization dependency. The problem is executing against shared mutable state, not releasing the prior cache entry. - Configuration — No new configuration item. The computed-array and cache-switch examples use the existing cloud partition-format rollout in
OlapTableandCloudInternalCatalog. - Compatibility and rolling upgrades — No file layout, function registration, or lookup wire change.
PointQueryExecutor.javaalready handles the existing resend response. Old and new BEs can still differ in row-fallback results during a rolling upgrade because only the new BE inserts the gap. - Thrift and Protobuf IDs — No files under
gensrc/thriftorgensrc/protochanged. - Parallel execution paths — The normal and parallel OLAP scanners, segment pushdown and virtual columns, late-filter refresh, and point output all get a format. Generic projections above joins or aggregation still have no per-row format and keep the legacy spacing.
- Special conditions and error handling — The absent-tablet check in
OlapScannercovers the documented scanner-test construction path. The no-format branch inScannerleaves other scanner types unchanged. Existing expression and resend error paths remain in place. The SNII check itself needs to be narrowed as described above. - Test coverage — BE fixtures exercise the index files, scanner and segment context setup, late runtime filters, and sequential prepared cache seed, resend, rebuild, and hit. They do not exercise concurrent prepared output or SQL plans over unindexed or computed ARRAYs in mixed-format partitions.
- Expected results — The SNII/V2 phrase and serial point-query assertions follow the writer and matcher for the rows they construct. No SQL golden output changed. The computed-array assertions encode the physical-format dependency questioned in this review.
- Observability — Existing point-query profiles report
hit_lookup_cache, and the resend VLOG identifies the tablet. Those are sufficient to investigate the extra misses without adding logging to the MATCH hot path. - Transactions and persistence — No EditLog, transaction, publish, or storage-write change. The point-read version and delete-bitmap path are unchanged. The result issue is in expression evaluation, not row visibility.
- Data writes and atomicity — No product write path is changed. The only rowset writes added are in the point-query test fixture.
- FE/BE variables — No new field needs to be sent. The new context value is derived from BE tablet or segment metadata, and the FE continues to replay the same prepared context when requested.
- Performance — Row matching retains the streaming algorithm and no extra pass over a row. However, this patch allocates a second analyzer context for every
VMatchPredicate, writes a shared pointer on every slow-path evaluation, and rebuilds even format-independent prepared contexts following a format switch. - Other issues — The reader already handles analyzed phrase slop that the exact fallback matcher does not. That pre-existing difference is outside the zero-slop parity shown here.
Requester focus
No additional focus was supplied.
Validation and coverage limits
Source coverage is complete for all 15 changed paths. I traced the writer/reader, FE analyzer binding and projection placement, scanner and segment clones, and prepared lookup cache and resend paths. The text-only BE build-hygiene checks and git diff --check passed.
This was a source-only review. I did not build the BE, run the added unit tests, execute the SQL examples on a cluster, test rolling upgrades, or run a concurrent or sanitizer lookup test. The exact live plan, manifestation of the race, and cache-miss latency are therefore unmeasured. Full SQL parity for analyzed ARRAY indexes and MATCH above the scan remains untested. Normal local and cloud paths preserve the tablet format, but the source review did not establish parity for every legacy or restored rowset metadata combination. Current FE DDL rejects both parser and analyzer for ordinary ARRAY columns, but the unindexed and scalar-derived examples do not require that DDL.
Review converged after 2 round(s).
| analyzer_ctx && analyzer_ctx->requires_analysis() && analyzer_ctx->analyzer != nullptr; | ||
| // Positions follow the index this evaluation stands in for, including its gap between | ||
| // analyzed elements. | ||
| const int64_t element_gap = analyzed ? analyzer_ctx->array_element_position_gap : 0; |
There was a problem hiding this comment.
[P2] Keep unindexed ARRAY phrases independent of the tablet’s index format
Take a cloud duplicate-key table t(k DATE, a ARRAY<STRING>) with no inverted indexes. Use the partition rollout from test_partition_cloud_inverted_index_storage_format_rollout.groovy to keep one V2 partition and add an SNII partition. Insert a = ['hello', 'world'] in both and enable enable_match_without_inverted_index.
SELECT k, NOT(a MATCH_PHRASE 'hello world') AS n
FROM tAnalyzerSelector defaults to English when there is no index, so both rows use analyzed fallback in the scanner projection. The base returns n = false for both rows. The new gap leaves that result unchanged on V2 but makes it true on SNII, even though neither partition has an index. A computed array(v, 'world') that borrows the analyzer from a scalar index has the same problem. Apply the storage-specific gap only when the bound MATCH operand corresponds to an analyzed ARRAY index, and add a SQL regression for the unindexed case.
| auto* fn_context = context->fn_context(_fn_context_index); | ||
| const bool snii_rows = | ||
| context->inverted_index_storage_format() == InvertedIndexStorageFormatPB::SNII; | ||
| fn_context->set_function_state(FunctionContext::FunctionStateScope::THREAD_LOCAL, |
There was a problem hiding this comment.
[P2] Don’t mutate a cached MATCH context during point-query execution
PointQueryExecutor::_output_data() sends the cached Reusable’s output contexts directly to VMysqlResultWriter. If FE times out and re-executes the same prepared statement on the same BE, the earlier RPC can still run in _light_work_pool because the worker does not check cancellation. Both cache hits can therefore reach this assignment on the same FunctionContext. THREAD_LOCAL is an ordinary shared_ptr member of that object, not actual thread-local storage. Reassigning it here races with the other evaluation’s assignment or read even when both choose the same analyzer. Bind the analyzer before publishing a shared context, or keep execution state request-local. The new sequential V2/SNII cache test does not cover overlapping same-format requests.
| if (cache_handle != nullptr && | ||
| cache_handle->matches_timezone_and_locale(timezone, lc_time_names)) { | ||
| cache_handle->matches_timezone_and_locale(timezone, lc_time_names) && | ||
| cache_handle->inverted_index_storage_format() == |
There was a problem hiding this comment.
[P3] Preserve prepared cache hits for format-independent expressions
A prepared SELECT v FROM t WHERE k = ? on a row-store MoW table now misses whenever successive keys alternate between V2 and SNII partitions served by the same BE, even though it does not evaluate MATCH. The cache holds one Reusable per UUID, so every switch deserializes and reopens the context and replaces the previous entry. With lightweight lookup enabled, every switch also adds a resend RPC. Restrict format-based cache selection to contexts whose results depend on it, or supply the format in request-local state without rebuilding the cached plan.
Background
An inverted index on an ARRAY column indexes the analyzed elements of a row as one
document, and a phrase query (MATCH_PHRASE, MATCH_PHRASE_PREFIX, MATCH_PHRASE_EDGE) matches only
adjacent positions. CLucene formats (V1/V2/V3) write the elements back to back, so a phrase can
cross elements; SNII leaves one empty position after every element
(
SniiIndexColumnWriter::add_array_values), so it cannot. When a segment has no index for thecolumn, BE evaluates MATCH by rows, and since #68661 that evaluation spaces elements like CLucene.
What problem does this PR solve?
Issue Number: None
Related PR: #68661 (added the row-evaluation positions across array elements), #39062 (made FE reject a parser on ARRAY indexes), #70352 (branch-4.2 backport of #68661 where review found this)
PR Type: Bugfix
Problem Summary:
For an analyzed SNII index on an ARRAY column, row evaluation and the index disagree on a phrase
that crosses two elements: for
['hello', 'world'],MATCH_PHRASE 'hello world'returns the rowwhen the segment is read by rows but not on the SNII index (MATCH_PHRASE_PREFIX and
MATCH_PHRASE_EDGE too). The answer then depends on whether each segment has its index. This PR
makes row evaluation space the elements of rows from SNII tablets as SNII does, in the segment and
in the scanner alike; CLucene tablets are unchanged.
Details
partition_inverted_index_storage_format = "SNII").match_phrase_data_tokensinmatch.cppmoved the position base by the last token position of each element, as CLucene does. SNII moves it one position further per element, also for an element without tokens, so row evaluation made SNII's non-adjacent terms adjacent.function_match_test.cpp(from [fix](inverted index) Preserve tokens from all array elements in MATCH fallback #68661) check row evaluation with a context that does not know the storage format and expect CLucene spacing;snii_golden_corpus_test.cppchecks only the SNII index. No unit test compared the two. No regression suite can create an analyzed ARRAY index on current versions.VExprContextcarries the inverted index storage format of the tablet whose rows it evaluates.SegmentIteratorsets it to the segment's format on the pushed-down and virtual-column contexts it clones;OlapScannersets it to its tablet's format on its conjuncts, projections and intermediate projections, again when a late runtime filter re-clones the conjuncts.VMatchPredicate::execute_column_implreads only that value and gives row evaluation an analyzer context whose newarray_element_position_gapis 1 for SNII and 0 otherwise;match_phrase_data_tokensadds it after every analyzed element. A tablet keeps the format it was created with (partition_inverted_index_storage_formatapplies to new partitions only), so a MATCH that runs as a virtual column in the segment and one wrapped in the scanner's projection, such asNOT(arr MATCH_PHRASE ...), answer the same on every row. The format is taken in BE rather than from FE because FE keeps it per partition. The SNII writer is unchanged, so existing segments keep their meaning.'hello world ~1'): still to fix, separately. Row evaluation of analyzed columns does not parse the slop on any format and returns no row where the SNII and V2 indexes do. This predates this PR.PushDownMatchProjectionAsVirtualColumnproduces evaluate in the scanner or the segment and agree.Testing
ArrayPhraseIndexParityTest(vmatch_predicate_test.cpp) writes the same arrays (a phrase across elements, inside one element, and across an empty or NULL element) into an SNII and a V2 index, then runsVMatchPredicateby rows and on the index for MATCH_PHRASE, MATCH_PHRASE_PREFIX and MATCH_PHRASE_EDGE. Before the fix the SNII case fails for all three (rows{1,1,1,1,1}, index{0,1,0,0,0}) and the V2 case passes; after it both pass. It also evaluates the rows in a context like the scanner's (the format, no index), which must agree too.ScannerLateArrivalRfTest.olap_scanner_match_follows_tablet_index_formatbuilds anOlapScanneron an SNII and a V2 tablet and runs MATCH_PHRASE in its conjunct and projection by rows, the path ofNOT(arr MATCH_PHRASE ...)next to a MATCH virtual column. On e3c8806 (the first version of this PR) the SNII case failed:['hello', 'world']matched; it passes now.late_arrival_conjuncts_keep_tablet_index_formatandSegmentIteratorVirtualColumnTest.ExprContextsCarryTheSegmentIndexFormatcheck that conjuncts re-cloned for a late runtime filter and the segment iterator's contexts carry the format; the first fails when the re-clone is not tagged.run-be-ut.shwith ScannerLateArrivalRfTest, ScannerConjunctSortTest, ScannerProjectionTest, OlapScannerTest, SegmentIterator*, ArrayPhraseIndexParityTest, VMatchPredicateTest, FunctionMatchTest, Snii*, DorisSnii* and InvertedIndexArrayTest: 1689 tests passed (ASAN, local)../build.sh --be(ASAN),clang-format.sh,check-format.sh,check-build-hygiene.sh: pass. FE is unchanged;./build.sh --be --fepassed for the first version.run-clang-tidy.sh: the local clang-tidy could not fully analyze the files (missing system headers), so it gives no usable result; for the first version it reported no findings on changed lines.INVERTED index with parser: english is not supported for array column), so a suite cannot create the table this path needs.Release note
On SNII partitions of an ARRAY column whose inverted index has a parser (only possible for indexes created before #39062), MATCH_PHRASE, MATCH_PHRASE_PREFIX and MATCH_PHRASE_EDGE without the index no longer match a phrase across two array elements, which agrees with the SNII index.
Check List (For Author)
AI Disclosure
🤖 Generated with Claude Code