Repository navigation
Conversation
### Background ANN data rows may contain empty arrays after opting in. Query vectors still need valid coordinates and dimensions. ### What problem does this PR solve? Issue Number: None Related PR: apache#70552 (follow-up) PR Type: Bugfix Problem Summary: Empty query vectors were incorrectly treated as NULL distances, and sparse TopN could skip dimension validation when falling back. Only empty data vectors should produce NULL. ### Details - **Frequency:** Queries with empty vectors or wrong dimensions on sparse segments. - **Root cause:** The empty-data semantics were also applied to query arguments, and metadata dimension validation happened after fallback decisions. - **Why existing tests missed it:** The initial tests explicitly accepted empty query vectors and did not cover metadata validation before sparse TopN fallback. - **Fix:** Restore nonempty query extraction, reject empty query arguments in scalar evaluation, and validate TopN dimensions before fallback. Preserve NULL results for empty data vectors and existing NULL-input rejection. - **Other paths and branches:** Cover scalar projection, range predicates, TopN, and a constant query in either argument position. No dependency or protocol change. ### Testing Repository clang-format v16 scripts, build hygiene and git diff checks passed. Targeted BE UT execution was attempted but stopped at the Java check; Java/JDK 17 is unavailable. Updated UT and differential regression coverage have not run. ### Release note Empty ANN data arrays produce NULL approximate distances. Empty, NULL, NULL-coordinate and dimension-mismatched query vectors are rejected. ### Check List (For Author) - Behavior changed: Yes (query validation described above). - Does this need documentation: Covered by the parent PR's documentation plan. - Pre-submission status: Not ready: parent PR remains draft pending builds and runtime verification. ### AI Disclosure - Tool: OpenAI Codex (GPT-6). - Generated: Code, tests and description. - Human review: Query validation semantics confirmed by the author; final implementation review pending.
50fae73 to
2dd7049
Compare
…nces ### Background ANN indexes identify vectors by their row IDs within a segment. Skipping empty arrays therefore requires preserving data-file row IDs and excluding those rows from range-search complements. Distance expressions also execute without an index, including when training is skipped or a query falls back to a scan. ### What problem does this PR solve? Issue Number: None Related PR: apache#70479 (related DELETE and Group Commit validation) PR Type: Enhancement Problem Summary: Allow empty arrays in ANN-indexed columns through a default-off BE option, preserving row IDs and SQL NULL semantics. Whole-array NULL and empty vectors produce NULL distances in both scalar evaluation and query-literal handling. Reject NULL coordinates such as `[1,NULL,3]` on every ANN write path, including Group Commit validation before asynchronous acknowledgement. The additional tests cover ingestion, partial updates, MoW, deletion, queries and index persistence. ### Details - **Change map:** 660 changed production lines and 1,773 changed test lines across 41 files; no generated files or documentation changes. Production code covers ANN storage and sparse row IDs, Group Commit validation, range/TopN handling, and FE/BE nullable distance results. Tests cover BE/FE units and SQL regressions. - **Before and after:** Empty arrays are rejected by default. With the option enabled they remain in the data file, while valid vectors are indexed under their original row IDs. Both directions of range comparisons exclude empty vectors. Sparse TopN and NULL/empty query vectors use scalar evaluation and normal SQL sorting to preserve filters, NULL ordering and LIMIT. - **Configs and defaults:** New mutable BE config `enable_ann_index_empty_array=false`. Enable it on all BEs before writing empty arrays and keep it enabled for subsequent writes, compaction, rebuilds and WAL replay. Readers do not consult this flag, and disabling it does not convert existing data. - **Impact on existing users:** NULL/empty distance semantics apply independently of the write flag. NULL coordinates are rejected on all ANN write paths, including rewrites of historical invalid vectors. This does not enable ANN indexes on nullable columns. Dense indexes retain their native representation; dense IVF complement searches avoid collecting every inverted-list ID. - **Behavior change:** Array overloads of `l1_distance`, `l2_distance`, `inner_product`, `cosine_distance`, `cosine_similarity`, `l2_distance_approximate` and `inner_product_approximate` return nullable FLOAT. Whole-array NULL or an empty array yields NULL, including `[]` versus `[]`. NULL elements in non-NULL arrays and mismatched nonempty dimensions remain errors. Nonempty zero-vector behavior and the MAP overload of `inner_product` are unchanged. - **Index implementation:** IVF stores explicit row IDs natively; sparse HNSW uses IDMap. All-empty segments persist an empty index without training. Sparse complement domains are reconstructed lazily from FAISS IDs, including IDs-only reads for IVF_ON_DISK. HNSW range queries translate selectors and result labels around the child index to preserve search parameters. FAISS versions and filenames are unchanged. - **Group Commit:** Validate dimensions and NULL coordinates before accepting a block into the background write path, even when ordinary row filtering is allowed. Require the dimension property from FE and use the same `stoi` parsing as the ANN writer. NULL-coordinate scans reuse existing SIMD helpers. - **Compatibility:** Requires a coordinated FE/BE upgrade and restart because distance-result nullability changes; mixed-version rolling query compatibility is not claimed. Enable empty-array writes only after the upgrade. Once empty arrays have been persisted, downgrade to BEs without sparse ANN support is unsupported, even if their FAISS reader can deserialize the file. ### Testing Passed locally on macOS arm64: - Repository clang-format v16 fix/check scripts on a scoped snapshot of all 25 changed C++ files; no additional formatting edits were needed. - `bash build-support/check-build-hygiene.sh`. - `git diff --cached --check`. - Checkstyle 9.3 with the repository configuration on all 11 changed Java files, using standalone JDK 21. This is a style check, not a JDK 17 build. - Groovy 4.0.15 syntax parsing of the three new ANN suites using standalone JDK 21. The regression framework uses Groovy 4.0.19; SQL and framework actions were not executed. Groovy regression coverage: - `ann_delete_group_commit`: HNSW/IVF/IVF_ON_DISK; off/sync/async modes; INSERT VALUES, INSERT SELECT and Stream Load; empty arrays with the flag on/off; whole-array NULL constraints/filtering; short/long vectors; NULL coordinates at different positions; multiple ANN columns; rejected mixed batches and post-publication data checks. - `ann_empty_array_mow`: SQL and Stream Load partial updates; omitted vector columns; valid/empty transitions; rejected updates preserving existing rows; missing-key policies; full-row MoW replacement; both light-delete settings; DELETE predicates and DELETE USING; compaction; delete-all and reinsertion. - `ann_empty_array_queries`: three index types and L2/IP; scalar/approximate comparisons; NULL/empty/invalid query arguments; constant expressions and FE/BE folding; TopN direction, NULL ordering and LIMIT boundaries; inclusive/exclusive range thresholds; cache reload, all-empty indexes, compaction, and mixed indexed/unindexed segments. These tests do not depend on Profiles or runtime counters. - Existing distance-function and cast regressions are updated. BE/FE unit tests cover writer validation before mutation, sparse labels and native reload, deleted-row filtering, all-empty result contracts, query extraction, and nullable expressions. Attempted on this revision but blocked before execution: - BE unit tests selected with `run-be-ut.sh --run --filter=...` and FE unit tests with `run-fe-ut.sh --run -Dtest=ArrayDistanceTest,InnerProductTest,ArrayArithmeticTest`: scripts exited during Java environment checks. - `run-regression-test.sh --run -d ann_index_p0 -s ann_empty_array_queries,ann_empty_array_mow,ann_delete_group_commit,cast_string_as_array -forceGenOut`: JDK 17 is missing. Compilation, unit tests and regressions remain unverified. Installed BE third-party dependencies and a compilation database are absent, so clang-tidy is also pending. **New/changed regression `.out` files must be generated and checked through the runner before this PR is ready; none were handwritten.** Runtime recovery/WAL replay and old/new binary compatibility remain unverified. Historical-data BUILD INDEX scenarios and generated-column DELETE behavior are outside this test batch. ### Notes for Reviewers | Self-review checkpoint | Conclusion | | --- | --- | | Scope and parallel paths | Writer and Group Commit reject invalid vectors; scalar expressions and ANN query preparation handle missing vectors consistently by design. Runtime verification is pending. | | Concurrency and ownership | Sparse row-domain initialization is mutex-protected and publishes only a completed bitmap; FAISS selectors and list borrows use RAII. | | Persistence and transactions | Native FAISS row IDs are preserved; validation precedes Group Commit acceptance. Thrift/Proto and transaction protocols are unchanged. | | Boundary conditions | All-empty indexes, missing queries, sparse range complements and TopN NULL ordering have dedicated tests. | | Performance | Dense IVF avoids full label collection; sparse first-use bitmaps and scalar TopN have additional cost. No benchmark claim. | | Validation | Static checks passed as listed above; this remains a Draft pending runtime tests and generated regression outputs. | ### Release note Add default-off `enable_ann_index_empty_array` support for ANN writes. Array distance and similarity functions return NULL for whole-array NULL or empty vectors, including query literals. ANN writes reject NULL coordinates, and Group Commit validates them before asynchronous acknowledgement. Upgrade and restart all FEs and BEs together; keep the write option enabled after storing empty arrays and do not downgrade those data files to a BE without sparse ANN support. ### Check List (For Author) - Behavior changed: Yes (see Details). - Does this need documentation: Yes; document the write option, NULL semantics, coordinated upgrade and downgrade restriction in the ANN and distance-function documentation. - Pre-submission status: Not ready: Draft pending compilation, runtime tests, generated regression outputs, and recovery/compatibility validation. ### AI Disclosure - Tool: OpenAI Codex (GPT-6). - Generated: Code, tests and this description. - Human review: The author reviewed selected implementation details and specified NULL/empty semantics, write validation and test scope. Final implementation review is pending.
…tests ### Background ANN range queries use FAISS hits or their complement to produce a bitmap, and cache that bitmap for repeated searches. Empty vectors are absent from the ANN index, so the sparse row-ID domain and nullable distance results must remain consistent across queries and loads. ### What problem does this PR solve? Issue Number: None Related PR: apache#70552 (verification and fixes on its exact head) PR Type: Bugfix Problem Summary: ANN range queries lose the distinction between strict and inclusive comparisons. In the MoW fixture, l2_distance <= 3 returns IDs 0,1,2,3 while its indexed equivalent omitted ID 3. Preserve boundary inclusion through runtime parameters, native search and cache keys. Repair the PR's test fixtures and generate five regression output files; most of this change is generated test data. ### Details - **Change map:** 55 changed lines in seven production files, 133 in nine test sources, and 3,837 in five generated output files. - **Frequency:** Always for the reproduced exact L2 boundary with an inclusive comparison; strict complement queries and inclusive inner-product searches share the missing distinction. - **Root cause:** Query preparation groups LE with LT and GE with GT, while FAISS applies strict comparisons. The cache key records only the comparison direction, so it also aliases strict and inclusive queries. - **Why existing tests missed it:** Native-FAISS comparison tests inherited the same strict bounds; complement tests did not state their intended GE semantics. The new empty-vector regression matrices expose exact boundaries, but compilation and Groovy fixture errors initially prevented them from completing. - **Fix:** Carry include_boundary through runtime copies and both search parameter layers, include it in cache keys, and move inclusive native bounds to the adjacent float. Reverse inclusiveness when complementing hits and retain the empty-vector domain restriction. Preserve negative L2 bound behavior. Repair nullable/constant fixtures, IVF reload flags and Stream Load setup. Fully connect tiny HNSW fixtures so recall does not obscure row-ID assertions. - **Behavior change:** Indexed comparisons now keep or exclude exact-threshold rows according to the SQL operator. - **Other paths and branches:** The shared wrapper covers L2 and inner product on HNSW, IVF and IVF_ON_DISK. The same strict-radius pattern predates this PR and is present in the inspected branch-4.2 commit 48b17e2; no backport was made. The introducing PR and branches 3.1, 4.0 and 4.1 were not established. ### Testing Build FE and ASAN BE on the development host using build.sh. The BE build passes the glibc 2.17 compatibility gate. Run 201 related unit tests through run-be-ut.sh: all assertions pass, but the combined process exits 134 after LeakSanitizer reports 224 bytes in two OpenMP allocations. This also occurred before the boundary fix and remains unresolved. Nine core tests and 70 vector tests excluding the concurrency stress case pass independently with ASAN exit 0; the concurrency case alone also exits 0. Generate outputs with run-regression-test.sh for ann_empty_array_queries, ann_empty_array_mow, ann_delete_group_commit, cast_string_as_array and test_array_distance_functions. All five suites pass the final comparison rerun, with zero failures, fatal scripts or skips (exit 0). The query matrix covers all four comparisons, both metrics, three index formats, cache reuse, index reload and compaction. The MoW suite covers partial updates, invalid loads and deletes. Clang-format 16 and build hygiene pass. The repository clang-tidy run and targeted reruns leave no diagnostics on changed lines after style fixes; raw targeted runs still report existing complexity at unchanged function declarations. Full unfiltered BE UT and CI were not run. ### Release note ANN range queries now preserve strict and inclusive boundary comparisons for L2 and inner-product searches, including sparse indexes with empty vectors. ### Check List (For Author) - Behavior changed: Yes (see Details) - Does this need documentation: No - Pre-submission status: Not ready: the combined ASAN run still reports an OpenMP allocation leak. ### AI Disclosure - Tool: OpenAI Codex - Generated: Production boundary fix, test fixture fixes, regression outputs, verification record and this description. - Human review: Not yet recorded.
### Background ANN empty-vector regression suites compare scalar and indexed results across query, load and update paths. Deterministic SQL results should also be checked against regression output files. ### What problem does this PR solve? Issue Number: None Related PR: apache#70552 (test follow-up) PR Type: Test Problem Summary: Replace live SQL-result equality assertions with golden-output checks in three ANN suites. Record exact and indexed paths separately, including cache reuse, reload, compaction and reads with empty-array writes disabled. Keep transport status, rejected-load and asynchronous publication checks. ### Details - **Scenarios:** Scalar and indexed query matrices, MoW range results, post-delete TopN, and TopN with the write option disabled. - **What existing tests miss:** Live equality can pass when both query paths return the same incorrect result; one final TopN query previously had no result assertion. - **Fails when broken:** The existing quickTest path rejects missing or differing output blocks. Runtime failure-detection verification remains pending because the development host is unreachable. ### Testing Groovy 4.0.15 syntax parsing with JDK 21 passed for all three changed suites. git diff --check passed. SSH to the development host timed out after VPN routing was confirmed, so this intermediate local commit has not regenerated outputs or rerun BE unit tests and regressions. Existing output files do not cover the new tags yet. Do not publish until runner-generated outputs are added and verification completes. ### Release note None ### Check List (For Author) - Behavior changed: No - Does this need documentation: No - Pre-submission status: Not ready: new output blocks and remote runtime verification are pending. ### AI Disclosure - Tool: OpenAI Codex - Generated: Groovy edits and this description. - Human review: Not yet recorded.
2dd7049 to
0c1d02e
Compare
…en results ### Background Distance constant folding only uses session variables, while ANN index fixtures change BE-wide writer settings and clear shared caches. ### What problem does this PR solve? Issue Number: None Related PR: apache#70552 (test coverage) PR Type: Test Problem Summary: Move connection-only constant-folding checks to the regular distance-function suite. Include the golden results generated and compared on the previous PR head, retaining serialization for suites that modify BE-wide state. ### Details - Scenarios: NULL and empty vectors, FE/BE constant folding, and ANN query, load and MoW paths across cache, reload and compaction phases. - What existing tests miss: Golden results for the full query matrix were not yet committed, and constant folding unnecessarily ran serially. - Fails when broken: Preserve all SQL, exception checks and output assertions. Relocate 28 generated constant-result blocks without changing their bytes. ### Testing Static diff and output provenance checks passed. All 3,822 generated query matrix blocks match their corresponding exact phase; projection rows match the fixture independently. On parent 0c1d02e, five regression suites passed output generation and comparison. No builds or runtime tests were rerun after moving the checks, following the author's preference. ### Notes for Reviewers Keep nonConcurrent on the three ANN suites: their setup and rebuilds require BE-wide settings, and reload coverage clears shared caches. The output files come from the regression runner; no expected result values are handwritten. ### Release note None ### Check List (For Author) - Behavior changed: No - Does this need documentation: No - Pre-submission status: Partially verified: relocated suite not rerun. ### AI Disclosure - Tool: OpenAI Codex. - Generated: Test relocation, output import and this description. - Human review: Author requested isolation improvements; final diff review pending.
|
run buildall |
### Background ANN empty-array writes now require an explicit opt-in. The index-builder UT still expects the older zero-dimension error for an all-empty read batch. ### What problem does this PR solve? Issue Number: None Related PR: apache#70552 (empty-array validation) PR Type: Test Problem Summary: Align the existing index-builder rejection test with the default-off empty-array contract, and make its configuration precondition independent of prior tests. ### Details - Failure: BuildAnnIndexRejectsAllEmptyBlock receives the opt-in diagnostic instead of the old dimension-mismatch diagnostic. - Cause: The ANN writer now validates empty-array opt-in before dimensions. - Stability evidence: Explicitly disable the flag for this test and restore its prior value with Defer. Preserve the complete empty batch, later valid rows, INVALID_ARGUMENT assertion and exact error-message comparison. ### Testing The author supplied the failing UT output. Source inspection confirms the writer's count-zero branch. Scoped repository clang-format 16 fix/check and git diff --check pass. No build or runtime test rerun, per author preference. ### Release note None ### Check List (For Author) - Behavior changed: No - Does this need documentation: No - Pre-submission status: Partially verified: updated UT not rerun. ### AI Disclosure - Tool: OpenAI Codex. - Generated: Test expectation, scoped config restoration and this message. - Human review: Author supplied the failure; updated diff review pending.
### Background Empty ANN query vectors now produce NULL distances and use scalar TopN evaluation. ### What problem does this PR solve? Issue Number: None Related PR: apache#70552 PR Type: Test Problem Summary: Update ann_const_expr_vector to check the NULL result instead of expecting the removed empty-query exception. ### Details - Failure: Test 6 expects an exception for array_repeat with a zero count. - Cause: The expectation predates the missing-vector distance semantics. - Stability evidence: Select only the distance to avoid an arbitrary row ID among tied NULL values; preserve ORDER BY and LIMIT. Keep the nonempty dimension mismatch error case unchanged. ### Testing Remote run-regression-test.sh --run -d ann_index_p0 -s ann_const_expr_vector -forceGenOut -parallel 1 succeeded. A subsequent run without -forceGenOut also succeeded, with one suite executed and no failures or skips. The generated output adds exactly one NULL result; existing output blocks are unchanged. Static diff inspection passed. No production code changes. ### Release note None ### Check List (For Author) - Behavior changed: No - Does this need documentation: No - Pre-submission status: Ready for this test-only follow-up; broader PR limitations remain. ### AI Disclosure - Tool: OpenAI Codex. - Generated: Test update and this description; expected output generated by the regression runner. - Human review: The author identified the stale assertion and requested this update.
|
run buildall |
|
/review |
There was a problem hiding this comment.
Request changes: three independently verified P1 findings cover failed-request atomicity, incorrect range comparisons, and rolling-upgrade query compatibility. Reviewed exact head d268047 across all 56 changed files. Existing review threads and additional user focus were empty. No existing blocking finding IDs apply.
Critical checkpoint conclusions (static inspection only):
- Goal and behavior: sparse ANN row IDs, missing-vector NULL semantics, coordinate rejection and boundary distinctions are substantially implemented. The three inline findings prevent the complete intended behavior; tests do not cover those failing scenarios.
- Scope and clarity: production changes follow the affected load/index/expression chain; most diff volume is repetitive generated output. No unrelated production change identified.
- Concurrency: shared loaded indexes remain immutable except the lazy indexed-row domain, whose mutex publishes only a complete domain. Build/load/reset happen before publication. One-time disk ID reads hold that initialization mutex; no lock inversion identified. Group Commit request/background separation is the atomicity finding.
- Lifecycle and initialization: native IDMap owns its HNSW child; directory/index-reader lifetime and writer success/error cleanup were traced, including both PODArray buffers and failed domain reads. No new cross-translation-unit static initialization dependency identified.
- Configuration: enable_ann_index_empty_array is mutable and defaults false; writer batches and Group Commit validation observe it. Readers deliberately do not consult it; disabling after sparse writes does not restore downgrade compatibility.
- Compatibility: new readers retain dense-file support, and sparse files use native FAISS labels/IDMap. Sparse-data downgrade is explicitly unsupported. Older FE/newer BE result metadata is a confirmed query regression even with the write option off (inline). No Thrift/protobuf definitions change.
- Parallel paths: direct load, Group Commit, rebuild/compaction, scalar/indexed range and TopN, HNSW/IVF/on-disk IVF, MAP inner_product and FE/BE constant execution were traced. Sparse and missing-query TopN correctly retain scalar fallback for NULL ordering/LIMIT. Existing rows and delete candidates remain aligned with physical IDs in inspected paths.
- Conditions and errors: new dimension/coordinate/empty checks describe concrete failure cases, validate each batch before changing writer state, and propagate Status failures. Const/nullable array shapes and outer-NULL payload handling are coherent in same-version execution. The per-block Group Commit check needs complete-request semantics.
- Test coverage: BE/FE units and SQL suites cover sparse labels, all-empty untrained persistence, deletes/MoW partial updates, compaction, caching/reload, NULL sorting/LIMIT, coordinate errors and wrapper shapes. Missing coverage includes rejected multi-block requests beyond 10,000 rows, nonrepresentable DOUBLE bounds, and older-FE/newer-BE queries. Quantized sparse runtime, recovery/WAL replay, repeated/concurrent regression execution and mixed-version execution were not established.
- Expected results: all 3,822 query-matrix blocks plus 120 ancillary blocks match an independently reconstructed fixture oracle; all 402 MoW output blocks match the mutation phases. Group Commit, distance-function, cast and constant-query expected outputs were also checked and are consistent with their small fixtures. This is data inspection, not execution of the Doris tests or independent proof of how outputs were generated.
- Observability: existing ANN fallback/load counters and contextual skipped-build logs cover these paths; no additional concrete observability defect identified.
- Persistence and transactions: no new FE EditLog or master-failover metadata is introduced. Rowset/version/delete-bitmap mechanisms are reused. Whole-request atomicity is not preserved by the new Group Commit failure path (inline); WAL replay was not executed.
- Data writes and failures: invalid writer batches leave counters/buffers unchanged, resources are released on build failure, and physical row IDs survive omitted arrays by inspection. A failed Group Commit request can nevertheless commit earlier queued rows (inline).
- FE/BE transport: no new transmitted variable is introduced; return-nullability agreement is correct for same-version code and fails for older FE plans as described inline.
- Performance and memory: dense indexes avoid full ID gathering, sparse complement domains are cached lazily, and writer buffers are released before save. Sparse TopN intentionally trades index speed for SQL NULL correctness. No further concrete performance/memory-safety defect identified statically.
- Other concerns and focus: no extra user focus was supplied. Preexisting FLOAT sqrt/squared-radius rounding was distinguished from the newly introduced DOUBLE-bound instance, and no duplicate finding was raised. No additional verified issue remained after the final review sweep.
Validation limits: no builds, Doris tests, benchmarks, ABI artifact checks or runtime experiments were run in this review environment, and source files were unchanged. Author-reported runs are not treated as independently executed validation. Static coverage is complete; runtime validation limits remain as stated. Convergence is determined by the recorded review rounds, independently of the request-changes verdict.
Review converged after 2 round(s).
| } | ||
| // Check retained rows before buffering/enqueueing: async success only guarantees WAL storage, | ||
| // and an invalid vector discovered by the segment writer cannot be repaired by WAL replay. | ||
| RETURN_IF_ERROR(_validate_ann_vectors(*block)); |
There was a problem hiding this comment.
[P1] Preserve request atomicity when a later ANN block is rejected
For a request whose valid prefix exceeds group_commit_memory_rows_for_max_filter_ratio (10,000 rows by default), _add_block() has already flushed earlier blocks to the shared queue, and async mode has written them to WAL. If a later block has the wrong vector dimension, this return fails only the submitting request. close() propagates the error and the local-state destructor merely calls remove_load_id(); that removes the dependency without retracting queued/WAL data. The separate background scan can therefore finish successfully and commit the valid prefix of a request reported as failed. Previously the malformed block reached the segment writer and failed that transaction. Validate/stage the whole request before exposing its blocks, or provide request-scoped rollback; cancelling the shared queue would also affect other accepted loads. The small validator/load tests miss the multi-block case beyond the flush threshold.
| search_param.get()); | ||
| float search_radius = radius > 0 ? radius * radius : 0.0F; | ||
| // Negative L2 bounds have no matching distances, including at zero. | ||
| if (include_boundary && radius >= 0) { |
There was a problem hiding this comment.
[P1] Preserve the original DOUBLE threshold when adjusting range bounds
With an L2 index and stored vector [1,0], the predicate CAST(l2_distance_approximate(vec,[0,0]) AS DOUBLE) <= CAST(0.99999999 AS DOUBLE) must reject the row: its distance is exactly 1. prepare_ann_range_search() accepts this cast/literal shape but narrows the bound to FLOAT 1. This new inclusive adjustment then searches squared distances below nextafter(1,+inf), so it incorrectly includes that row; the previous strict bound excluded it. VExprContext::evaluate_ann_range_search() installs the bitmap as the original comparison result, so the DOUBLE predicate is not rechecked. The symmetric IP strict/complement paths also change results near rounded bounds. Retain the original threshold and derive operator-aware bounds, or use scalar fallback when translation is inexact; cover DOUBLE thresholds immediately above/below representable distances as well as exact integer boundaries.
| } | ||
|
|
||
| block.replace_by_position(result, std::move(dst)); | ||
| block.replace_by_position(result, |
There was a problem hiding this comment.
[P1] Honor older FE result metadata during a rolling upgrade
An old FE declares these array-distance results as nonnullable FLOAT, including an ordinary nonconstant query such as SELECT l2_distance(vec,[0,0]) FROM t over valid, nonempty vectors. A newly upgraded BE now unconditionally constructs ColumnNullable(Float32). Function construction accepts the nested-type match, but VExpr::execute_column() checks the physical column against the FE-declared Float32 and returns return column type mismatch before result serialization. This affects existing queries even while enable_ann_index_empty_array=false; the default-off write option provides no compatibility protection. Add a result-metadata/execution-version compatibility path so old FE plans continue to receive the legacy physical type until the cluster can use the new nullable contract. Requiring a coordinated FE/BE upgrade in the description does not preserve rolling query compatibility.
### Background PR apache#70552 adds sparse ANN row IDs and NULL/empty-vector semantics. Master has since moved ANN persistence to AnnIndexSource/AnnIndexSink and added load-error propagation tests. ### What problem does this PR solve? Issue Number: None Related PR: apache#70552 (conflict resolution), apache#70270 (storage interface), apache#70271 (SNII storage), apache#70788 (load errors) PR Type: Build/CI/Chore Problem Summary: Merge master 141d321 into the empty-array branch. Resolve persistence conflicts using the current storage interface while retaining sparse labels and indexed-row cache invalidation. Adapt the affected tests to that interface and initialize the TopN load-error fixture's query vector. ### Details - Affected: ANN persistence and BE unit-test integration on supported BE platforms. - Developer and release impact: Removes merge conflicts and stale test API calls; no additional SQL, configuration or file-format change is intended. - License and third-party: None beyond the incoming master history. - Rollback: Revert this merge against its first parent to restore the previous PR head. ### Testing - Repository clang-format 16 fix/check scripts passed on a scoped copy of the three manually resolved/adapted C++ files; formatted copies match the checkout. - build-support/check-build-hygiene.sh passed. - Scoped diff whitespace checks and source/interface inspection passed. - Builds, unit tests, regression tests and clang-tidy were not run, following the author's preference. Earlier PR runtime results do not validate this merge. - A full first-parent whitespace check reports existing incoming-master golden output whitespace; those generated outputs are retained unchanged. ### Notes for Reviewers The manual integration is in faiss_ann_index.cpp, faiss_vector_index_test.cpp and ann_index_load_test.cpp. The latter fixture must model a prepared non-empty query to reach index loading after the new missing-vector check. ### Release note None ### Check List (For Author) - Behavior changed: No additional behavior change beyond the merged branches. - Does this need documentation: No additional documentation for conflict resolution. - Pre-submission status: Partially verified: merged code has not been built or tested; broader PR limitations recorded in apache#70552 are unchanged. ### AI Disclosure - Tool: OpenAI Codex. - Generated: Conflict resolution, test adaptation and this message. - Human review: The author requested conflict resolution; final diff review pending.
|
run buildall |
|
Some notes on the NULL / empty-vector semantics in this PR, plus a proposal for the sparse TopN path. 1. Semantics as implemented (please confirm this is the intent)
Two side effects of this that I think should be called out explicitly:
2. Sparse segments disable ANN TopN entirely
if (cast_set<size_t>(ann_index_reader->get_num_rows_in_index()) != rows_of_segment) {
_column_states[src_cid].need_read_data = true;
_opts.stats->ann_fall_back_brute_force_cnt += 1;
return Status::OK();
}
Range search is fine: NULL never satisfies a comparison, and the complement path already intersects with 3. Proposal: fill NULL rows instead of falling backNULL distances are mutually interchangeable, so the correct per-segment top-k is always a subset of: The global TopN above the scan is kept ( Sketch:
To keep approximate recall from turning into NULL pollution, use
Tests worth adding: NULLS FIRST/LAST, |
|
Follow-up review, based on the target semantics we would like Doris to provide. This supersedes the TopN part of my earlier comment: under these semantics, sparse segments no longer need either the brute-force fallback or the NULL-fill proposal. 0. Target semantics
Storage keeps the original value: 1. Write path
2. Storage / indexKeep the existing machinery, keyed on "missing vector" (
3. Query path (largest change)3.1 TopN: exclude missing vectors instead of falling back.
To make the result independent of the plan, I suggest:
The simpler alternative (exclude missing vectors only in the pushed-down path) makes results depend on the plan, so I would avoid it. Either way, "approximate-distance TopN implicitly drops NULL distances" is Doris-specific behavior and needs to be agreed on and documented. In a plain projection the functions still return NULL. 3.2 Range search. No change. A NULL comparison never matches, and the complement already excludes missing rows, so index and scalar paths agree. 3.3 NULL / 3.4 Nullable column on the query path. Audit BE code that 4. Distance functionsKeep the current change: the 7 array distance functions return nullable FLOAT, with NULL for NULL/ 5. FE
6. Suggest splitting outThese are independent of the semantics above and easier to review on their own:
7. Tests
8. Open decisions
Points 1.3 and 3.4 come from static reading and have not been checked at runtime. |
### What problem does this PR solve? Issue Number: None Related PR: apache#70552 Problem Summary: ANN TopN currently falls back to scalar evaluation whenever an index contains fewer vectors than its segment has physical rows. This also disables ANN for empty placeholder rows already excluded by delete bitmaps. Remove that fallback: indexed TopN ranks nonempty vectors only and does not pad LIMIT with empty-vector NULL distances for NULLS FIRST or NULLS LAST. A valid query against an all-empty index returns no rows. Missing query vectors, unsupported sort directions, missing indexes and other existing fallback rules keep their current behavior. Add a real save/load/search BE test through SegmentIterator for HNSW, IVF and IVF_ON_DISK with L2/IP, sparse/all-empty indexes, deletion masks and short/large limits. Update the regression matrix comments to distinguish indexed and scalar NULL behavior; its existing SQL already covers both NULL orders. ### Release note ANN TopN searches may now use indexes on segments containing empty vectors. Indexed searches omit empty-vector rows regardless of NULLS FIRST/LAST and may return fewer rows than LIMIT. Scalar fallback retains its existing NULL behavior. ### Check List (For Author) - Test: No runtime tests, per explicit author request. Repository clang-format 16 fix/check on both modified C++ files, BE header hygiene and git diff --check pass. Existing regression .out files remain unchanged and need runner regeneration and comparison before this follow-up is ready for CI. - Behavior changed: Yes, sparse ANN TopN ranks indexed candidates without NULL padding. - Does this need documentation: Yes, document indexed TopN empty-vector exclusion; documentation PR pending.
|
run buildall |
### What problem does this PR solve? Issue Number: None Related PR: apache#70552 Problem Summary: Sparse ANN TopN now ranks only indexed vectors, but the previous regression outputs still included missing-vector rows to satisfy NULL ordering and LIMIT. Regenerate the ANN query and MoW outputs with the regression runner on ea9c886. Check all 3,942 query output blocks: 222 changed as expected, including all-empty TopN results, while unaffected blocks remain unchanged. The MoW output removes six NULL-distance rows. Group Commit output is unchanged. ### Release note None ### Check List (For Author) - Test: ASAN BE and FE builds passed. Three ANN suites passed output generation; five ANN suites and one array-distance suite passed normal comparison with no failures or skips. SparseTopNRanksOnlyIndexedCandidates passed separately with default sanitizers (exit 0). The combined BEUT run passed all 277 test assertions but failed LeakSanitizer with a 224-byte OpenMP allocation leak (exit 134). clang-tidy could not complete due to missing stddef.h. - Behavior changed: No (generated expectations follow the preceding code change). - Does this need documentation: No (test-output update only).
### What problem does this PR solve? Issue Number: None Related PR: apache#70552 Problem Summary: Array distance validation used memchr to search for a literal 1 in each nonempty vector's null map. Reuse simd::contain_one, as the ANN writer already does, to detect nonzero NULL flags with the existing SIMD implementations. Preserve skipping outer NULL rows and empty arrays, and replace the unused cstring include with the SIMD helper header. No measured speedup is claimed. ### Release note None ### Check List (For Author) - Test: Repository clang-format 16 fix/check, BE header hygiene and diff whitespace checks passed. Existing BitsTest coverage was inspected. Builds and unit or regression tests were not run, following the user's preference for this edit. - Behavior changed: Canonical 0/1 null maps are unchanged; other nonzero flags are now treated as NULL consistently with the column's null-map semantics. - Does this need documentation: No.
|
Follow-up on the latest push ( Removing the sparse-segment fallback fixes the main issue from my first comment: sparse segments now use ANN TopN, including MoW segments whose The same SQL now returns different rows depending on the execution pathThe ANN path omits
The PR's own tests show this:
It also mixes within a single query, because the choice is made per segment:
In MoW, visible pgvector also omits NULL rows on its index path, but it picks one plan per query. It never mixes the two semantics across parts of the same table in one query. SuggestionMake "missing vectors are not recalled" independent of the plan:
Related: a NULL or Still open from earlier comments
Minor
|
### Background ANN TopN ranks indexed vectors only. Empty arrays remain data rows but have no ANN entry. ### What problem does this PR solve? Issue Number: None Related PR: apache#70552 (follow-up to review) PR Type: Build/CI/Chore Problem Summary: The empty-array configuration comment incorrectly claimed sparse segments fall back to scalar TopN to preserve NULL ordering and LIMIT. Update it to describe indexed-only TopN and the absence of empty-row padding. Runtime behavior is unchanged. ### Details - **Affected:** Two comment lines in be/src/common/config.cpp; no toolchain or workflow change. - **Developer and release impact:** Accurate configuration guidance; no runtime impact. - **License and third-party:** None. - **Rollback:** Revert this comment-only commit. ### Testing Verified the comment against SegmentIterator::_apply_ann_topn_predicate. Changed-line clang-format 16.0.6 and git diff --check passed. Static comparison confirms executable code is unchanged. No build or tests run: comment-only change and user preference. ### Release note None ### Check List (For Author) - Behavior changed: No - Does this need documentation: No - Pre-submission status: Ready (comment-only follow-up; existing compatibility issue is not fixed) ### AI Disclosure - Tool: Codex - Generated: Comment update and commit description. - Human review: Not yet confirmed for this follow-up.
|
run buildall |
|
Review completed for commit Conclusion: no remaining findings within the agreed review scope. This is a scoped review conclusion, not an unconditional approval of the entire PR. The following known issues were explicitly excluded at the author's request and are not considered fixed:
The stale configuration comment has been corrected: scalar distance evaluation returns NULL for empty arrays, while ANN TopN ranks indexed vectors only and does not pad LIMIT with empty-vector rows for NULLS FIRST/LAST. Coverage and validation:
AI-assisted review performed with Codex ( |
|
run buildall |
Background
ANN indexes identify vectors by their row IDs within a segment. Skipping empty arrays must preserve those IDs and exclude missing vectors from range-search complements. Distance expressions also execute without an index when training is skipped or a query falls back to a scan.
What problem does this PR solve?
Issue Number: None
Related PR: #70479 (related DELETE and Group Commit validation), #70270 and #70271 (ANN storage interface integrated from master), #70788 (ANN load-error handling integrated from master)
PR Type: Enhancement
Problem Summary:
Allow empty arrays in ANN-indexed columns through the mutable, default-off BE option
enable_ann_index_empty_array. Preserve row IDs and return NULL distances for whole-array NULL or empty vectors. Reject NULL coordinates on every ANN write path, including Group Commit before asynchronous acknowledgement. Most of the diff is tests and regression outputs; NULL/empty distance semantics apply even when the write option is off.Details
enable_ann_index_empty_array=false. Enable it on every BE before empty-array writes and retain it for compaction, rebuilds and WAL replay. Readers do not consult the flag; disabling it does not convert stored data.inner_productare unchanged. Nullable ANN columns remain unsupported.l1_distance,l2_distance,inner_product,cosine_distance,cosine_similarity,l2_distance_approximateandinner_product_approximateadopt the missing-vector semantics. Indexed range comparisons also preserve strict versus inclusive boundaries in native searches and cache keys.Testing
Latest SIMD follow-up
a7289fc99b50c9623b6fc4de39e6a276aa03124b:memchr(..., 1, ...)null-map check with the existingsimd::contain_one()helper, matching ANN writer validation. Outer NULL rows and empty arrays remain skipped; canonical 0/1 null maps behave unchanged, and all nonzero flags are treated as NULL.ea9c88689ac, before this helper substitution.Current sparse-TopN validation on
ea9c88689acfec9d6cef3397f7b40f612dfca076(2026-11-26), with runner-generated outputs committed in08ece8c0d1418f1cd3f3140db3b5b41adf8b4d4b:build.shin an isolated checkout. Runtime binary hashes were checked before regression execution.run-regression-test.sh --run -d ann_index_p0 -s ann_empty_array_queries,ann_empty_array_mow,ann_delete_group_commit -parallel 1 -forceGenOutpassed all 3 suites. A normal comparison includingann_const_expr_vectorandcast_string_as_arraypassed all 5 suites;test_array_distance_functionsalso passed separately. No suites failed or were skipped.run-be-ut.sh -j 16 --run --filter=AnnIndexLoadTest.SparseTopNRanksOnlyIndexedCandidatespassed 1 test and exited 0 with default sanitizers, without suppression or an OpenMP workaround.___kmp_allocate_alignstack. This remains a failed sanitizer run.stddef.hprevented complete analysis of both changed translation units; the output also includes existing size/constness diagnostics. No clean clang-tidy result is claimed.Previous merge update
14316491746710f3c2216b20bc2505588fb09231(2026-11-25):141d3212aaband resolve ANN persistence conflicts throughAnnIndexSource/AnnIndexSink, retaining sparse labels and indexed-row cache invalidation.Remote validation on
0c1d02e2330(the parent of the test-only follow-up):build.sh. FEUTArrayDistanceTest,InnerProductTest,ArrayArithmeticTestpassed all 8 tests..outgeneration and a subsequent normal comparison with-parallel 1:ann_empty_array_queries,ann_empty_array_mow,ann_delete_group_commit,cast_string_as_array, andtest_array_distance_functions. The generated results are now committed.libomp; this is a failed run. A standalone OpenMP program reproduced the same leak after nested parallel execution followed by shrinking the thread team from 4 to 2. A diagnostic rerun withKMP_HOT_TEAMS_MAX_LEVEL=0passed all 201 tests and exited 0 with leak detection enabled. No suppression or production configuration workaround is included.The earlier test-only follow-up moves connection-only constant-folding checks into the regular
test_array_distance_functionssuite. All SQL and error checks are retained, and 28 generated output blocks are relocated byte-for-byte. Static inspection confirmed that all 3,822 generated query-matrix blocks match the corresponding exact-query phase and that projection rows agree with the deterministic fixture. Production code is unchanged from the runtime-tested parent.Follow-up validation for
dc727716b4bplus the regression-only change committed asd268047102d:IndexBuilderTest.BuildAnnIndexRejectsAllEmptyBlocknow checks the default-off opt-in diagnostic and saves/restores the flag.run-be-ut.sh -j 24 --run --filter=IndexBuilderTest.BuildAnnIndexRejectsAllEmptyBlockpassed 1 test and exited 0 with ASAN defaults.ann_const_expr_vectornow checks the empty constant query vector through a generated.outNULL result, instead of expecting the removed exception.run-regression-test.sh --run -d ann_index_p0 -s ann_const_expr_vector -forceGenOut -parallel 1and a subsequent normal comparison both passed, each running 1 suite with no failures or skips. Only distance is selected to avoid an arbitrary row ID among tied NULL values. Existing output blocks are unchanged.FlussJniScannerPkTest, and 77 skips. This is a failed run.Repeated/concurrent regression stability, recovery/WAL replay and mixed-version compatibility remain unverified. The focused passes do not establish a passing full test suite.
Notes for Reviewers
The three ANN suites retain
nonConcurrentbecause their fixture writes/rebuilds modify BE-wide settings and query reload checks clear shared caches. Constant folding and unindexed distance checks run in the regular distance-function suite.nonConcurrentonly isolates suites within one regression process; these ANN fixtures still require a cluster not shared with another runner.The query-matrix HNSW fixture is fully connected to keep recall from obscuring row-ID assertions. The rebase preserves master's ANN build-resource cleanup and includes sparse row-ID buffers. Review writer validation and sparse IDs first, then query semantics and boundary handling. The large output diff contains runner-generated results, not handwritten expectations.
Release note
Add default-off empty-array ANN writes and NULL distances for whole-array NULL or empty vectors. Indexed TopN ranks only nonempty indexed vectors, irrespective of NULLS FIRST/LAST, and may return fewer rows than LIMIT. Reject NULL coordinates before Group Commit acknowledgement and preserve strict/inclusive ANN range boundaries. Upgrade FEs and BEs together before enabling empty-array writes; do not downgrade persisted sparse ANN data to older BEs.
Check List (For Author)
AI Disclosure