Skip to content

[improvement](storage) Support empty ANN arrays and NULL vector distances - #70552

Open
yiguolei wants to merge 11 commits into
apache:masterfrom
yiguolei:improvement/ann-empty-array-opt-in
Open

yiguolei wants to merge 11 commits into
apache:masterfrom
yiguolei:improvement/ann-empty-array-opt-in

Conversation

@yiguolei

@yiguolei yiguolei commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Change map: Production changes cover sparse ANN row IDs and query handling, pre-acknowledgement Group Commit validation, nullable FE/BE distance results, and strict/inclusive range boundaries. Tests cover these paths through BE/FE units and five SQL suites. Most output lines record the same deterministic SQL across index types, metrics, cache states, reload and compaction.
  • Before and after: Empty arrays are rejected by default. With the option enabled, valid vectors retain their original data-file row IDs. Range complements exclude missing vectors; indexed TopN ranks only nonempty indexed vectors, regardless of NULLS FIRST/LAST. It does not pad results with missing vectors and can return fewer rows than LIMIT; all-empty indexed segments contribute no TopN rows. NULL or empty query vectors still use scalar evaluation.
  • Configs and defaults: 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.
  • Impact on existing users: Array distance/similarity results become nullable FLOAT. Whole-array NULL and empty arrays yield NULL; NULL coordinates and mismatched nonempty dimensions remain errors. Nonempty zero-vector behavior and the MAP overload of inner_product are unchanged. Nullable ANN columns remain unsupported.
  • Behavior change: The array overloads of l1_distance, l2_distance, inner_product, cosine_distance, cosine_similarity, l2_distance_approximate and inner_product_approximate adopt the missing-vector semantics. Indexed range comparisons also preserve strict versus inclusive boundaries in native searches and cache keys.
  • Index implementation: IVF stores explicit IDs natively; sparse HNSW uses IDMap. All-empty segments persist without training. Sparse complement domains are reconstructed lazily; dense IVF avoids full ID collection. FAISS versions and filenames are unchanged.
  • Compatibility: Mixed-version rolling query compatibility is not established. Upgrade FEs and BEs together before enabling empty-array writes. Downgrading persisted sparse ANN data to BEs without sparse support is unsupported.

Testing

Latest SIMD follow-up a7289fc99b50c9623b6fc4de39e6a276aa03124b:

  • Replace the per-vector memchr(..., 1, ...) null-map check with the existing simd::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.
  • Repository clang-format 16 fix/check, BE header hygiene and diff whitespace checks passed. Existing SIMD helper boundary tests were inspected, not executed. No performance gain is claimed without measurement.
  • Builds, BEUT and regression tests were not rerun for this follow-up, following the author's preference. Runtime results below apply to ea9c88689ac, before this helper substitution.

Current sparse-TopN validation on ea9c88689acfec9d6cef3397f7b40f612dfca076 (2026-11-26), with runner-generated outputs committed in 08ece8c0d1418f1cd3f3140db3b5b41adf8b4d4b:

  • ASAN BE and FE builds passed through build.sh in 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 -forceGenOut passed all 3 suites. A normal comparison including ann_const_expr_vector and cast_string_as_array passed all 5 suites; test_array_distance_functions also passed separately. No suites failed or were skipped.
  • The output-only follow-up copies the generated files unchanged. All 3,942 query-matrix blocks were inspected: 222 changed as expected for indexed TopN, including empty results for all-empty segments; unaffected blocks are unchanged. MoW output removes six NULL-distance rows. Group Commit output is unchanged.
  • run-be-ut.sh -j 16 --run --filter=AnnIndexLoadTest.SparseTopNRanksOnlyIndexedCandidates passed 1 test and exited 0 with default sanitizers, without suppression or an OpenMP workaround.
  • The combined focused ASAN BEUT run passed all 277 test assertions across 29 suites, but exited 134 because LeakSanitizer found 224 bytes in 2 allocations with an OpenMP ___kmp_allocate_align stack. This remains a failed sanitizer run.
  • clang-tidy exited 1: missing stddef.h prevented complete analysis of both changed translation units; the output also includes existing size/constness diagnostics. No clean clang-tidy result is claimed.
  • These results cover the indexed-only TopN change. Fallback segments still retain NULL-distance rows; mixed indexed/unindexed segments can therefore use inconsistent candidate sets under NULL ordering. The proposed unified fallback filtering has not been implemented or tested.

Previous merge update 14316491746710f3c2216b20bc2505588fb09231 (2026-11-25):

  • Merge master 141d3212aab and resolve ANN persistence conflicts through AnnIndexSource/AnnIndexSink, retaining sparse labels and indexed-row cache invalidation.
  • Adapt four persistence tests to the current directory adapters and initialize the TopN load-error fixture with a non-empty query so it still reaches the load-error path.
  • Repository clang-format 16 fix/check scripts passed for the three manually adapted files; BE header hygiene and scoped diff whitespace checks passed.
  • Builds, unit tests, regression tests and clang-tidy were not rerun for this merge, following the author's preference. All runtime results below apply to earlier revisions, not this head.

Remote validation on 0c1d02e2330 (the parent of the test-only follow-up):

  • ASAN BE and FE builds passed through build.sh. FEUT ArrayDistanceTest,InnerProductTest,ArrayArithmeticTest passed all 8 tests.
  • Five Groovy suites passed automatic .out generation and a subsequent normal comparison with -parallel 1: ann_empty_array_queries, ann_empty_array_mow, ann_delete_group_commit, cast_string_as_array, and test_array_distance_functions. The generated results are now committed.
  • Default combined ASAN BEUT: 201 tests passed their assertions, but the process exited 134 with 224 bytes leaked in static 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 with KMP_HOT_TEAMS_MAX_LEVEL=0 passed 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_functions suite. 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 dc727716b4b plus the regression-only change committed as d268047102d:

  • IndexBuilderTest.BuildAnnIndexRejectsAllEmptyBlock now checks the default-off opt-in diagnostic and saves/restores the flag. run-be-ut.sh -j 24 --run --filter=IndexBuilderTest.BuildAnnIndexRejectsAllEmptyBlock passed 1 test and exited 0 with ASAN defaults.
  • ann_const_expr_vector now checks the empty constant query vector through a generated .out NULL result, instead of expecting the removed exception. run-regression-test.sh --run -d ann_index_p0 -s ann_const_expr_vector -forceGenOut -parallel 1 and 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.
  • The full BE UT run announced 17,075 tests; 7,245 completed successfully and 3 Iceberg tests failed on temporary-file permissions before a Lance multi-vector test looped on repeated read failures. The stuck process was terminated (exit 143); full BE coverage is incomplete.
  • The full FE UT command exited 1. Its reports contain 23,439 tests, 0 assertion failures, 6 errors in 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 nonConcurrent because 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. nonConcurrent only 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)

  • Behavior changed: Yes (see Details).
  • Does this need documentation: Yes; document the write option, NULL semantics and upgrade/downgrade restrictions in ANN and distance-function documentation.
  • Pre-submission status: Not ready: full BE coverage is incomplete, full FE UT reports 6 errors, and the earlier combined ASAN run reports a libomp leak. Local review also identified unresolved Group Commit atomicity and DOUBLE-to-FLOAT range-boundary concerns. The two stale-expectation fixes passed targeted validation on earlier revisions. The current sparse-TopN update has passing focused regression and standalone-test results with refreshed outputs, but its combined ASAN run still fails on the OpenMP leak, clang-tidy is incomplete, and mixed indexed/fallback NULL candidate consistency remains unresolved. Known review concerns remain open.

AI Disclosure

  • Tool: OpenAI Codex.
  • Generated: Code, tests, rebase/merge conflict resolution, test isolation changes 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.

yiguolei added a commit to yiguolei/incubator-doris that referenced this pull request Nov 13, 2026
### 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.
@yiguolei yiguolei changed the title [improvement](storage) Support opt-in empty arrays in ANN indexes [improvement](storage) Support empty ANN arrays and NULL vector distances Nov 13, 2026
@yiguolei
yiguolei force-pushed the improvement/ann-empty-array-opt-in branch from 50fae73 to 2dd7049 Compare November 17, 2026 10:29
yiguolei and others added 3 commits November 20, 2026 17:04
…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.
@yiguolei
yiguolei force-pushed the improvement/ann-empty-array-opt-in branch from 2dd7049 to 0c1d02e Compare November 20, 2026 09:05
…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.
@yiguolei

Copy link
Copy Markdown
Contributor Author

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.
@yiguolei yiguolei added usercase Important user case type label dev/4.1.x dev/4.2.x labels Nov 21, 2026
@yiguolei

Copy link
Copy Markdown
Contributor Author

run buildall

@yiguolei

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

  1. 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.
  2. Scope and clarity: production changes follow the affected load/index/expression chain; most diff volume is repetitive generated output. No unrelated production change identified.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. 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.
  11. Observability: existing ANN fallback/load counters and contextual skipped-build logs cover these paths; no additional concrete observability defect identified.
  12. 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.
  13. 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).
  14. 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.
  15. 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.
  16. 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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.
@yiguolei

Copy link
Copy Markdown
Contributor Author

run buildall

@RoanHeNaN

Copy link
Copy Markdown
Contributor

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)

  • Write side: only [] is newly accepted, and only with enable_ann_index_empty_array=true. A whole-array NULL is still impossible because ANN columns must be NOT NULL. [1, NULL, 3] is now rejected on every write path; previously the ANN writer did not check null_map and indexed the payload under the NULL.
  • Query side: the 7 array distance/similarity functions return NULL whenever either side is NULL or [], including [] vs []. NULL elements still raise an error, and the element check runs before the empty check, so l2_distance([1,NULL], []) still errors. FE constant folding (ArrayArithmetic.cosineSimilarity) behaves the same way.

Two side effects of this that I think should be called out explicitly:

  • l2_distance([1,2], []) used to fail with a dimension mismatch and now returns NULL. A dimension error involving [] is silently turned into a missing value.
  • The return type changes from FLOAT to Nullable(FLOAT). FunctionBuilderImpl::build (be/src/exprs/function/function.h) strictly compares FE and BE return types, nullability included. During a rolling upgrade, any query using these functions fails with "function return type check failed", whether or not the table has an ANN index. Given the dev/4.1.x / dev/4.2.x labels, I don't think this part should be backported as is.

2. Sparse segments disable ANN TopN entirely

segment_iterator.cpp (_apply_ann_topn_predicate):

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();
}
  • A single [] row makes the whole segment fall back to brute force. In practice empty vectors are scattered across loads, so almost every segment is sparse and ANN TopN is effectively never used.
  • The user cannot work around it. The check compares FAISS ntotal with the physical row count, so neither WHERE size(v) > 0 nor NULLS LAST avoids it.
  • The check runs after the index has already been loaded, so these segments pay for both the index load and the brute-force scan.
  • ORDER BY l2_distance_approximate(...) LIMIT k defaults to NULLS FIRST, so the empty rows come first. That is correct SQL, but users won't expect it.

Range search is fine: NULL never satisfies a comparison, and the complement path already intersects with _indexed_rows.

3. Proposal: fill NULL rows instead of falling back

NULL distances are mutually interchangeable, so the correct per-segment top-k is always a subset of:

FAISS top-k over non-empty vectors  ∪  any min(e, k) empty rows   (e = |_row_bitmap − indexed_rows|)

The global TopN above the scan is kept (PushDownVectorTopNIntoOlapScan returns topN.withChildren(...)), so it does the final NULLS FIRST/LAST ordering. A segment would emit at most 2k rows.

Sketch:

  1. Run evaluate_vector_ann_search as usual.
  2. If the segment is sparse, compute empty_rows = _row_bitmap − indexed_rows. Reusing _init_indexed_rows() keeps the delete bitmap and earlier index filters.
  3. Append the selected empty rows to _row_bitmap / row_ids, with NULL entries in the nullable distance column. VirtualColumnIterator::prepare_materialization already accepts unsorted labels. The result cache stays as is, since filling happens after the cached FAISS result.

To keep approximate recall from turning into NULL pollution, use ann_sort_info.nulls_first. TSortInfo field 3 is already sent, but olap_scan_operator.cpp only reads is_asc_order:

Order Empty rows to add Skip FAISS?
NULLS FIRST min(e, k) yes, when e >= k
NULLS LAST k − n only when n = |_row_bitmap ∩ indexed_rows| < k (based on the candidate count, not on how many rows FAISS returned) no

Tests worth adding: NULLS FIRST/LAST, e < k and e >= k, with a delete bitmap / pre-filter, and HNSW + IVF.

@RoanHeNaN

Copy link
Copy Markdown
Contributor

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

  • ANN indexes may be built on Nullable ARRAY<FLOAT>.
  • [] and NULL are both accepted on write, with no BE config.
  • Vectors containing NULL elements are rejected.
  • [] and NULL are "missing vectors": they are stored as written but never recalled by vector search.
Value Write In ANN index Scalar distance Range dist < r TopN ORDER BY dist LIMIT k
valid vector ✅ ✅ value by distance recalled
[] ✅ (no config) ❌ NULL never matches not recalled
NULL (nullable column) ✅ ❌ NULL never matches not recalled
[1, NULL, 3] ❌ error — error — —
non-empty, wrong dim ❌ error — error — —

Storage keeps the original value: SELECT vec still returns [] or NULL. Only the index treats both as missing.

1. Write path

  1. Remove enable_ann_index_empty_array and every check or message that depends on it.
  2. AnnIndexColumnWriter::add_array_values: always skip count == 0 rows. Keep the dimension and NULL-element checks for non-empty rows.
  3. Outer NULL rows. add_nulls / add_array_nulls currently return "Ann index should not be used on nullable column". They must instead treat those rows as missing vectors.
    • The catch: feed_array_index (array_index_input.cpp) calls add_array_values before add_array_nulls, and the payload under a NULL row is not guaranteed to be empty (e.g. if(cond, NULL, arr)).
    • So the writer has to know the outer null map while it handles add_array_values. Otherwise it may index garbage, or reject a NULL row on the dimension check.
    • Suggest passing the outer null map into add_array_values, or reordering the two calls. The BUILD INDEX path (index_builder.cpp) needs the same fix.
  4. Group Commit:
    • Drop the "[] requires config" check. Keep the dimension and NULL-element checks, but skip rows whose outer value is NULL. _validate_ann_vectors currently applies remove_nullable and would misjudge them.
    • Consider moving this validation into OlapTableBlockConvertor so regular loads and Group Commit share one implementation.
  5. MoW partial update needs nothing extra. Omitted vectors are filled with NULL (nullable column) or [] (NOT NULL column), and both are accepted by (2) and (3).

2. Storage / index

Keep the existing machinery, keyed on "missing vector" ([] or NULL) instead of "empty array":

  • sparse row IDs: IVF add_with_ids, HNSW wrapped in IndexIDMap, the writer's row-ID buffer;
  • all-missing segments;
  • complement range search intersecting with _indexed_rows.

3. Query path (largest change)

3.1 TopN: exclude missing vectors instead of falling back.

  • The ANN path already satisfies "not recalled", because FAISS only returns indexed rows. So the sparse-segment fallback in SegmentIterator::_apply_ann_topn_predicate (ntotal != rows_of_segment) can be deleted, and sparse segments use ANN normally.
  • Every brute-force path must give the same result: segments without an index, segments below ann_index_build_min_segment_rows, and filters or common exprs that force fallback. With ASC defaulting to NULLS FIRST, missing vectors would otherwise be sorted to the top.

To make the result independent of the plan, I suggest:

  • FE: for TopN ordered by l2_distance_approximate / inner_product_approximate, add an implicit dist IS NOT NULL filter before PushDownVectorTopNIntoOlapScan, so the semantics hold whether or not the TopN is pushed down.
  • BE: once pushed down, recognize IS NOT NULL on the ANN virtual column as implied by ANN results and skip it on the ANN path. Otherwise it counts as a common expr and forces fallback. On fallback it is evaluated normally.

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 / [] query vector. Every distance is NULL, so TopN and range search should return an empty result directly instead of the current has_missing_query_vector() brute-force fallback. With 3.1 in place the fallback would also return empty; this is only an optimization.

3.4 Nullable column on the query path. Audit BE code that assert_casts the indexed column to ColumnArray assuming NOT NULL: brute-force reads, virtual column materialization, and the code around extract_query_vector.

4. Distance functions

Keep the current change: the 7 array distance functions return nullable FLOAT, with NULL for NULL/[] input; FE constant folding matches; the MAP overload of inner_product is unchanged. NULL is now a legal stored value, so this is required.

5. FE

  • Remove the "ANN index must be built on a column that is not nullable" check in IndexDefinition.checkColumn (both overloads), for CREATE TABLE, CREATE INDEX and ALTER.
  • Add the implicit TopN filter from 3.1.
  • Confirm PushDownVectorTopNIntoOlapScan pushes down nullable slots. It already strips the MV Nullable wrapper.
  • Docs: the semantics table above, plus the implicit TopN filter.

6. Suggest splitting out

These are independent of the semantics above and easier to review on their own:

  1. Range-search <=/< boundary fix plus the cache-key change. Resolve the open DOUBLE-to-FLOAT threshold issue there.
  2. Rejecting NULL elements in the ANN writer. This is a standalone bug fix and can be backported.
  3. Group Commit partial-acknowledgement atomicity (the open P1).

7. Tests

  • Remove: setBeConfigTemporary([enable_ann_index_empty_array: true]) and the config-off rejection cases, e.g. IndexBuilderTest.BuildAnnIndexRejectsAllEmptyBlock.
  • Add:
    • nullable ANN column with mixed NULL / [] / valid rows, for HNSW, IVF and IVF_ON_DISK;
    • NULL rows whose array payload is non-empty, e.g. INSERT ... SELECT if(cond, NULL, arr); such rows must not be indexed;
    • TopN never returns missing vectors on all three paths: ANN, brute-force fallback (a segment below the min-rows threshold), and not pushed down (e.g. with a join);
    • a profile check that sparse segments use ANN (ann_fall_back_brute_force_cnt == 0);
    • range search including the complement direction (>, >=);
    • MoW partial update: NULL fill (nullable column), [] fill (NOT NULL column), sequence-column losers, partial update of a deleted key, flexible partial update;
    • results before and after cumulative compaction;
    • Group Commit with NULL rows, [] and NULL elements.
  • Regenerate the .out files. Rows that used to sort first under NULLS FIRST must no longer appear in TopN results.

8. Open decisions

  1. Implicit TopN filter in FE (plan-independent, recommended) versus pushed-down path only.
  2. How to change the add_array_values interface: an extra outer-null-map parameter, or reordering it with add_array_nulls. This also affects the inverted-index writers.

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.
@shuke987

Copy link
Copy Markdown
Contributor

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.
@RoanHeNaN

Copy link
Copy Markdown
Contributor

Follow-up on the latest push (ea9c88689a, 08ece8c0d1, a7289fc99b).

Removing the sparse-segment fallback fixes the main issue from my first comment: sparse segments now use ANN TopN, including MoW segments whose [] rows are already masked by the delete bitmap (sequence losers, rows overwritten by a delete). The new SparseTopNRanksOnlyIndexedCandidates test is good coverage. simd::contain_one is fine.

The same SQL now returns different rows depending on the execution path

The ANN path omits [] rows. Every brute-force path still returns them with NULL distances. Brute force is used when:

  • the segment has no index, or is below ann_index_build_min_segment_rows;
  • the candidate ratio is below ann_index_candidate_rows_percent_threshold (default 0.3);
  • there is a filter or common expr, including the implicit MoW __DORIS_DELETE_SIGN__ = 0 on segments that contain tombstones;
  • the sort direction is unsupported (DESC for L2, ASC for IP), or the metric does not match.

The PR's own tests show this:

  • ann_empty_array_mow.groovy qt_mow_topn runs ORDER BY d ASC NULLS LAST LIMIT 10 with only one visible non-empty row. The suite sets ann_index_build_min_segment_rows and both candidate thresholds to 0, which forces ANN, so 08ece8c0d1 drops 100 \N from the output. With default settings this small table falls back and row 100 comes back.
  • ann_empty_array_queries.groovy keeps separate expected outputs for the scalar_fallback phase and the ANN phases, for the same queries.

It also mixes within a single query, because the choice is made per segment:

  • A freshly loaded small segment below the build threshold falls back and sends its [] rows with NULL distances to the global TopN.
  • Large indexed segments omit theirs.
  • With the default ASC NULLS FIRST, those rows from the small segment come first.
  • Once compaction merges that segment into an indexed one, they disappear. The data hasn't changed, but the result has.

In MoW, visible [] rows come from partial updates on a deleted key, flexible partial updates with an in-load delete, and DEFAULT '[]' fills for new keys. They show up mostly in recent, small segments, so this is the common case rather than an edge case.

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.

Suggestion

Make "missing vectors are not recalled" independent of the plan:

  • Preferred: FE adds an implicit dist IS NOT NULL filter for TopN on l2_distance_approximate / inner_product_approximate. BE drops that filter on the ANN path, where it is implied, and evaluates it on fallback. Details in section 3.1 of my previous comment.
  • Or: BE filters NULL-distance rows on every brute-force TopN path for these two functions.
  • At minimum: the release note should say explicitly that results depend on the execution path and on compaction state. "Scalar fallback retains its existing NULL behavior" doesn't make that clear.

Related: a NULL or [] query vector still falls back and returns k NULL-distance rows. That is also inconsistent with "not recalled" on the ANN path. Returning an empty result would match it.

Still open from earlier comments

  • enable_ann_index_empty_array is still a BE config, default false.
  • Nullable ANN columns are still rejected (IndexDefinition.java "not nullable" checks).
  • The Group Commit validation location and the partial-acknowledgement atomicity (P1) are unchanged.
  • The range-boundary fix and the NULL-element rejection are not split out.

Minor

  • The commit message of 08ece8c0d1 reports that the combined BE UT run failed LeakSanitizer (a 224-byte OpenMP allocation, exit 134). Please confirm whether the new tests introduced the leak or it existed before.
  • The new UT writes many private members of SegmentIterator and AnnTopNRuntime directly. A small test helper would make it less fragile.

### 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.
@yiguolei

Copy link
Copy Markdown
Contributor Author

run buildall

@yiguolei

Copy link
Copy Markdown
Contributor Author

Review completed for commit 8ccf0612a0ae4262f9054af595a8ae6ff121c89a.

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:

  • Group Commit can publish earlier blocks before a later block fails validation.
  • DOUBLE precision in ANN range-bound handling.
  • Old FE / new BE compatibility when the FE declares a non-nullable FLOAT result but the BE returns a nullable distance result. The reviewed path returns a query error; it is not a demonstrated BE process crash.

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:

  • All 57 changed files were covered by the preceding code review. For this follow-up, 56 files were confirmed byte-identical to the previously reviewed commit a7289fc99b50c9623b6fc4de39e6a276aa03124b; the only delta is the two-line configuration comment correction, which was independently rechecked.
  • Previous static checks of the ANN and MoW expected-result files were reused; they were not new test executions.
  • No builds or tests were run during this review.

AI-assisted review performed with Codex (gpt-6-astra, xhigh). No machine-readable whole-PR PASS receipt is issued because it would not represent the exclusions above.

@yiguolei yiguolei closed this Nov 28, 2026
@yiguolei yiguolei reopened this Nov 28, 2026
@yiguolei

Copy link
Copy Markdown
Contributor Author

run buildall

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants