Skip to content

fix(ivfflat): preserve sparse batches and distance semantics - #29535

Merged
XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-29381-ivf-empty-entry-compaction
Oct 1, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-29381-ivf-empty-entry-compaction

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Fixes #29381

Fixes #29038

Fixes #29536

What this PR does / why we need it:

Three corrections to existing IVFFLAT distance-filter responsibilities:

  • Storage Top-K intentionally omits the embedding after scoring. Partial exact filtering previously shrank that empty vector and caused a recovered query panic. Reuse the relation reader's row-selection helper for loaded columns, preserve the empty embedding slot, and reject malformed scalar/distance alignment through the existing result cleanup owner.
  • A cached index retained the first request's distance function. Resolve L2/squared-L2 units once from the current request at the common search entry, using only by-value configuration copies. The shared cached object stays immutable; legacy calls without a runtime function use the table-config fallback.
  • Lossy entry encoding can clip or round distinct source distances to the same score. For example, INT8 training clips source 2.5 to an index distance of 1, so peeling 1.5 < distance < 3 incorrectly drops it. Derive lossiness from already decoded catalog metadata and retain these predicates on the existing source-row residual-filter path. FLOAT32-on-FLOAT32 and other identity encodings retain their current range pushdown. Replace an unused planner context field; add no second validator or execution path.

The search retains existing ANN ordering, probe lists and bounded candidate budgets/overfetch. Lossy range predicates now evaluate the original source vectors, which requires the existing source-row fetch/filter and prevents index-only execution for these queries. Candidate budgets do not bound all base/membership-scan work; these correctness checks make no scale-performance claim. Projected distances and ordering remain approximate index scores; this does not change ANN into an exact full-recall search. No storage-format change, cache-key split, shared mutable state, worker or embedding reload in storage Top-K. Production increment: +59/-52 lines. Tests extend existing UT/BVT fixtures; no permanent embedded-cluster fixture is added.

The copied PRE membership producer also retains these distance predicates before candidate Top-K. Its previous cleanup removed every vector-column predicate, so 60 nearer nonmatches could fill the 50-candidate budget for K=10 and hide ten qualifying rows. Reuse the existing direct IS NOT NULL cleanup only for synchronous candidates, preserve async predicates, and account for all retained columns during regular-index planning. This follow-up also deletes the now-uncalled recursive column-reference helper, reducing production code by 32 lines. It changes neither retries nor candidate budgets.

Validation

  • Both persisted sparse-batch panic and clipped INT8 range failure reproduced through real MySQL on baseline production source, with persisted-object presence asserted.
  • Full pkg/sql/plan and pkg/vectorindex/ivfflat tests passed. The final extended planner regression covers 10 encoding controls plus PRE/INCLUDE and async PRE, semantic OFFSET/candidate limits, original and copied membership predicates with rebound tags, synchronous non-null elision/async retention, and safe range pushdown. Sparse-batch coverage includes all/none/partial selection, nullable INCLUDE alignment, malformed scalar rejection and delayed vector loading.
  • Previously recorded 210 real SQL checks passed for INT8, UINT8, BF16, Float16 and F64→F32: in-memory/persisted entries, lower/upper/both bounds against scalar references, ordinary-predicate equivalence, function switching, prepared NULL/rebinding and cleanup. Fixtures retain every candidate to independently verify predicate truth.
  • The 70-row BF16 counterexample failed on the pre-fix PR head 85e39d559: all eight PRE/INCLUDE × L2/squared-L2 × memory/persisted combinations returned no rows instead of ten. The corrected copied-scan unit regression also failed before the patch. All eight public cases now return the complete ten-row set. Another 112 indexed checks passed with real regular secondary indexes, NULL vectors, wrapped vector expressions, prepared NULL/strict-bound/rebinding, and unquantized/BF16/INT8/UINT8 controls.
  • The previous 48 SQL cache-unit checks passed again, including both first-function orders, repeated switching, nullable INCLUDE, concurrent cold requests to one cached index and both functions in one CTE statement.
  • Ordinary mo-tester comparison passed twice on the same isolated instance: 170/170 each (75 prepared-distance statements + 95 quantization statements), zero failures/ignored/abnormal statements and zero database residue. Existing quantization fixture now covers a clipped row, false-positive rejection, inclusive boundaries and prepared NULL/rebinding, plus the single-list 70-row PRE/INCLUDE counterexample before and after entries flush.
  • CPU service build and go vet for both owning packages passed on Darwin arm64 / Go 1.26.4. Existing unchanged search/cache code previously passed owning-package race validation and 100 repetitions of the cache-generation regression. The new planner property adds no concurrency ownership.
  • Independent complete commit review: explicit Codex CLI gpt-6.1-sol / reasoning xhigh, APPROVE for final 302c2fbb3260ccafc928655b925ce861e02941d3 versus 0d3687004d712e0878d63f2e848f69c5df5d1c0f. Complete 12-file review and final dead-code reconciliation exclude the previously invalid PRE-producer conclusion (threads 01a0f35f-9b5e-7e11-8c85-6447c4d3a3d0, 01a0f373-b5be-7ea2-9a12-f0c85dee97ca).

CI is not a completion gate for this task; local validation is recorded above.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner September 30, 2026 16:26
@XuPeng-SH XuPeng-SH changed the title fix(ivfflat): preserve sparse batches and query distance units fix(ivfflat): preserve sparse batches and distance semantics Sep 30, 2026

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Deep review of 302c2fbb3260ccafc928655b925ce861e02941d3 against base/merge-base 0d3687004d712e0878d63f2e848f69c5df5d1c0f: no blocking findings. Code-review recommendation: accept. This is submitted as COMMENT because the authenticated reviewer account is also the PR author; it is not a GitHub approval from a different reviewer.

Read all changed hunks in all 12 files, traced the owning storage reader, shared cache, original source scan, copied membership producer, regular-index rewrite and terminal cleanup. This is a focused bug correction, exempt from a new feature-design document. The design reuses existing responsibilities:

Contract Review result
Sparse storage Top-K batches Only the deliberately omitted embedding is excluded from selection. Scalar, distance and nullable INCLUDE columns stay aligned. The existing reader row-selection helper is reused; malformed alignment returns through the existing batch/result/reader cleanup owners. No embedding reload or second cleanup mechanism.
Request distance units Search resolves the current function in by-value runtime/table configurations. Cached configuration remains immutable. Explicit request wins; the legacy empty-runtime fallback is consistent for range filtering and returned scores. Reindex/cache generations do not retain another request's units.
Lossy distance predicates Original source vectors own SQL predicate truth; encoded index scores retain ANN ordering. Lossiness is derived from already decoded metadata and the existing quantizer mapping. Identity encodings retain pushdown. Source predicates cannot be classified as covered INCLUDE filters and therefore prevent unsafe index-only execution.
PRE/INCLUDE and regular indexes The copied membership producer retains distance and wrapped-vector predicates before bounded Top-K. Only a direct synchronous vector IS NOT NULL is implied by candidates; async predicates stay. Rebound tags, retained-column accounting and local regular-index remaps remain consistent. Semantic LIMIT/OFFSET is preserved while producer truncation is cleared.

Unhappy-path audit: the new malformed-batch rejection cleans its current batch, accumulated result and readers through existing owners; empty/NULL/all/none/partial results preserve their established contracts. The change adds no lock, goroutine, retry, wait protocol, mutable cached state or persistent format. Selection remains batch-scoped and candidate accumulation bounded; those bounds do not imply that source/membership scan work is bounded by K. Existing snapshot, tenant and data-format contracts remain unchanged. Mixed-version rollout compatibility was excluded from scope as requested.

Validation inspected and reused: both owning packages, final vet/CPU build, applicable owning race and cache-generation stress; original panic and clipped INT8 baseline failures; corrected PRE/INCLUDE baseline failures; 210 lossy-predicate SQL checks, 112 membership/regular-index/NULL/wrapped/prepared checks, 48 cache/concurrency checks; normal BVT 170/170 twice on the same instance with cleanup zero. The public-test binary was built from the fixed production content before commit stamping; the only later production change deletes the unreachable refsColumn helper. Reused evidence is valid for the reachable final content, rather than inferred from its older embedded commit string.

This review additionally reran the exact four changed UT families at final HEAD on Darwin arm64 / Go 1.26.4, exit 0 (including all four sparse-batch selections and 13 planner ownership cases). Independently ran 576 public SQL comparisons on a fresh isolated instance, exit 0: F32/F64, vector_l2_ops/vector_l2sq_ops, both initial function orders warmed by unfiltered ANN, repeated switching, separate upper/lower bounds, PRE/POST/INCLUDE, persisted-entry presence, and reindex generations. Every indexed query was selected by EXPLAIN and compared with independently expected IDs plus a scalar control. LIMIT exceeded fixture cardinality to avoid masking false positives. Database teardown was asserted zero. The initial separate worktree test attempt was rejected by native-artifact provenance before testing; it is not counted as product failure or passing evidence. No subagent was used, no production code was edited, and CI was not awaited.

Implementation/test/document increments were reviewed separately: production +59/-52 (net +7), Go tests +224/-113, SQL +64/-8, expected results +103/-2, no new docs. Replacing the unused params field and deleting refsColumn remove obsolete state/code. Existing UT/BVT fixtures are extended; the 70-row fixture has a distinct purpose because it exceeds the 50-candidate budget for K=10, rather than providing volume for coverage.

Non-blocking follow-ups:

  1. This is a correctness repair, not a performance improvement claim. Lossy range queries now read/evaluate source vectors, lose index-only access and can do substantial source/membership work in PRE/INCLUDE. Measure representative large, high-dimensional and selective/nonselective workloads using source rows evaluated, bytes decoded, peak memory and latency before making a scale claim. Any optimization must preserve source predicate truth and membership-before-Top-K; removing residual checks is unsafe for domains transported approximately. Non-range queries and identity encodings retain their existing paths.
  2. Replace one permanent 70-row count-only BVT assertion with the complete expected PK set using order-independent comparison. That strengthens the durable oracle without adding another fixture or redundant test matrix; the separately executed public QA already checked full IDs.

No unresolved manual review thread exists on this PR. The #29038 issue comments were checked explicitly, including unfiltered cache warming, separate upper/lower bounds, op_type alias, prepared reuse, concurrent cold use, both functions in one statement and reindex. #29381 and #29536 reproduction contracts are covered. This recommendation does not promise exact ANN recall, exact projected source distances, improved scale performance, or completed CI.

@XuPeng-SH
XuPeng-SH merged commit 112f7f3 into matrixorigin:main Oct 1, 2026
17 of 20 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/fix-29381-ivf-empty-entry-compaction branch October 1, 2026 00:33
XuPeng-SH added a commit that referenced this pull request Oct 1, 2026
## What type of PR is this?

- [x] BUG
- [x] Improvement

## Which issue(s) this PR fixes:

Fixes #29540 (#29540).

Found while investigating the Ubuntu UT failure in #29535 ([job
log](https://github.com/matrixorigin/matrixone/actions/runs/36755422383/job/110024440694?pr=29535)).
This is a transaction/lineage correction independent of that PR's IVF
changes.

## What this PR does / why we need it:

A no-op lifecycle UPDATE still deletes the old Rowid and inserts a
replacement. After TN flush/merge relocates the committed row, advancing
only `TxnOperator`'s snapshot can expose the relocated row alongside the
transaction's own replacement. The failing PICK transaction first
affected one SNAPSHOT registry row, then affected two after a registry
flush, and subsequently failed the uniqueness guard.

- Reuse `Workspace.AdvanceSnapshot`, the existing owner of RC tombstone
relocation, through one stateless lineage timestamp helper. Cover COPY
ALTER, TRUNCATE, internal PITR, CLONE and snapshot creation; replace the
duplicated frontend/compiler timestamp protocol.
- Remove timestamp-only snapshot rewinds from ALTER/TRUNCATE. Once
deletes have moved to new Rowids, restoring only the timestamp leaves
workspace state inconsistent.
- Preserve the physical history boundary (`updated physical − 1ns`),
frontend tenant-less behavior and the publication write barrier required
by commit validation. Keep the one-row registry guard.
- Reuse the existing forced-flush harness for memory and persisted
tombstones; assert exact replacement PK sets and extend statement
rollback coverage to immediate COMMIT. No new state machine, storage
format, background work or SELECT/DML entry allocation.

### Validation

Local Linux amd64 / Go 1.26.4, native artifact source generation
verified:

- Deterministic original-behavior probes reproduce resurrected deletes
after raw advance and after timestamp-only rewind. An isolated
old-behavior mutation makes the replacement regression fail: expected 10
rows, actual 20, for both tombstone modes.
- Focused helper/compiler UTs and existing engine
flush/commit/transaction rollback/statement rollback/subsequent
statement matrix pass.
- Complete owning packages `pkg/frontend`, `pkg/sql/compile`,
`pkg/frontend/databranchutils` pass `-race`.
- Original complete `TestDataBranchPick` passes `-race`, including
`accept_mixed_update_and_insert`; replacement regression passes 17
repetitions under `-race`. Existing engine tests pass adaptive
exact-test race stress; expanded immediate-COMMIT rollback matrix also
passes.
- Public SQL control probe passes `-race`: prior update/insert across
repeated transactional ALTER, commit/rollback, historical snapshot
reads, PITR creation, branch TRUNCATE and exactly one SNAPSHOT registry
row. Existing historical-lineage BVT covers these scenarios; no
duplicate cluster fixture added.
- Incremental golangci-lint reports zero issues; MO analyzer has zero
diagnostics in modified files; `git diff --check` passes.
- Design and independent overall QA review: **gpt-6.1-sol, xhigh**
(user-selected replacement for unavailable `gpt-6`).

### Cost and limits

Production code net −5 lines; tests net +134; documentation unchanged.
Required tombstone-transfer work runs at lineage snapshot advancement,
proportional to existing workspace deletes/object changes. No scale
benchmark was run. The engine witness deterministically covers
visibility; actual SQL PICK supplies commit evidence, without a forced
mid-PICK flush. Partial transfer I/O failure injection was not exercised
separately. CI is pending.

This branch was previously deployed

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

Labels

kind/bug Something isn't working size/L Denotes a PR that changes [500,999] lines

Projects

None yet

3 participants