Skip to content

refactor: replace IVF search TVF with vector index scan - #27297

Merged
mergify[bot] merged 27 commits into
matrixorigin:mainfrom
aunjgr:codex/ivf-vector-index-scan
Aug 21, 2026
Merged

mergify[bot] merged 27 commits into
matrixorigin:mainfrom
aunjgr:codex/ivf-vector-index-scan

Conversation

@aunjgr

@aunjgr aunjgr commented Aug 18, 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:

issue #26977

What this PR does / why we need it:

Replaces the query-time ivf_search table function with an optimizer-visible VECTOR_INDEX_SCAN plan node so IVF-FLAT search participates in normal costing, join ordering, distribution, explain, prepared-plan rewriting, and operator lifecycle management.

The new path:

  • adds algorithm-neutral planner/executor plugin hooks for vector-index readers;
  • reads IVF metadata, centroids, and entries directly through the current transaction instead of generating nested SQL;
  • supports typed INCLUDE predicates, distance ranges, adaptive disjoint centroid rounds, exact pre-filter membership, prepared parameters, correlated APPLY, and multi-CN entry partitioning;
  • uses a SEMI membership join to preserve the runtime-filter producer/consumer topology;
  • bounds retained candidate memory with streaming post-filter Top-K compaction and drops entry vectors after distance evaluation;
  • removes ivf_search registration and its background-plan explain plumbing.

The plan wire change intentionally has no rolling mixed-version gate: MatrixOne deployment requires all nodes in a cluster to run the same version.

Validation:

  • affected Go package suites, including sql/compile, sql/plan, sql/plan/function, IVF-FLAT, plugin, metric, and brute-force packages;
  • post-merge go vet and mo-service build;
  • focused race tests at -count=100, followed by full apply, compile, and ivfflat package race runs;
  • 407/407 affected vector BVT statements, including multi-CN, all IVF modes, INCLUDE/adaptive rounds, consumers/views, and the newest L1/L2-squared op-type matrix.

@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 →

@aunjgr

aunjgr commented Aug 19, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the snapshot+subscription identity blocker in 6c667eb and strengthened the regression in e5fc8d5. NewPlanReader now matches ordinary relation resolution: SourceTable.PubInfo (the physical publisher) overrides the logical snapshot tenant, while the snapshot timestamp still selects/creates the clone transaction. TestRelationScannerUsesSnapshotCloneAndPublisherAccount now constructs the combined snapshot+subscription spec through NewPlanReader and verifies that the hidden relation is opened with publisher account 42 and the snapshot clone, despite snapshot tenant 99. The standalone precedence test is updated as well. Local affected package suites, focused race tests, vector_prepared_limit, and vector_ivf_snapshot all pass after merging current main.

@XuPeng-SH XuPeng-SH 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.

One P1 prepared-execution correctness blocker remains on exact head e5fc8d5939431e86afbad3e7f51d939be50aab23. The immutable template added for ordinary VECTOR_INDEX_SCAN scopes does not cover the scan specification owned by correlated APPLY.

vectorSource.ApplyPrepare rewrites every spec.PreFilters[i] in place with ConstantFold (pkg/sql/colexec/apply/vector_source.go:64-65). Apply.Prepare creates this source once and reuses it (apply.go:55-65), while Apply.Reset resets executors/batches but does not restore the specification (types.go:115-128). The new Source.vectorIndexScanTemplate / resetVectorIndexScanForExecution path in pkg/sql/compile/compile.go:4037-4045 is only used for a standalone scan datasource, not the nested VectorIndexScan copied once by constructApply (operator.go:2396-2404).

Deterministic counterexample: use an IVF index with INCLUDE(category) and a single-row vector-provider join, then prepare a query whose covered pre-filter is t.category = concat(?, ''). The generated plan is APPLY(provider, VECTOR_INDEX_SCAN) and the filter is stored in VectorIndexScan.PreFilters. Execute first with x: ApplyPrepare folds the RHS parameter subtree to literal x in place. Reset and execute the same prepared statement with y: the parameter node is already gone, so the filter remains category = 'x' and the second execution silently searches the wrong candidate set. I reproduced this with an exact-head two-execution unit probe; expected y, actual x. Existing full apply and ivfflat package runs pass under -race, confirming this generation transition is not covered.

Please give correlated vector sources their own immutable specification template (or otherwise fold only a fresh deep copy per execution), and add a deterministic two-EXECUTE regression with a parameter inside an included-column pre-filter. The test should verify both values reach the reader, not merely that Prepare succeeds.

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

Deep re-review of exact head e5fc8d5939431e86afbad3e7f51d939be50aab23, including the complete diff, every prior review/thread/reply, and the incremental changes after my review at 9c5b769fa95af304e87d50a8373705deb67a141c. The ordinary scan template, APPLY TxnOffset refresh, post-filter over-fetch, MaxUint64 bound, remote snapshot clone, and publisher-account precedence fixes close the earlier issues. One prepared-reuse correctness gap remains in correlated APPLY. Targeted package suites pass (apply, ivfflat, compile, plan), but a temporary two-generation counterexample deterministically fails (x remains after parameters change to y).

Comment thread pkg/sql/colexec/apply/vector_source.go Resolved
@aunjgr

aunjgr commented Aug 20, 2026

Copy link
Copy Markdown
Contributor Author

Structural execution-boundary update pushed at 9ac1753 after merging current main 63223d8. The reusable VectorIndexScan is now immutable; standalone and correlated APPLY derive private execution generations through pkg/sql/colexec/vectorscan, and the plugin reader receives a fully bound request rather than a mixture of plan/runtime state. Result k and candidate budget now have distinct fields and one execution-time derivation; snapshot/account/txn/partition identity is resolved once.

Validation after the merge: all affected package suites; build and vet for every changed Go owner; focused race stress 100x for both immutable-generation and APPLY reuse tests; full race suites for vectorscan, apply, ivfflat, and compile; 89.6% coverage in the new owner package; clean-cluster prepared CROSS APPLY BVT (x -> ids 1,2; y -> ids 3,4); snapshot BVT; and all seven EXPLAIN/BVT consumers affected by semantic-k display.

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

Deep re-review completed against exact head 9ac1753.

I read the complete review/thread history and verified the fixes against both the incremental changes since the previously reviewed heads and the complete PR diff. In particular, I checked correlated APPLY generation isolation and TxnOffset refresh, prepared-statement reuse, nested/top-level snapshot propagation, subscription publisher identity, remote pipeline serialization, vector-scan reader ownership/cleanup, membership and prefilter semantics, candidate limiting/overfetch, MaxUint64 handling, optimizer remapping/visitor coverage, and the algorithm-neutral index-plugin boundary. The previously reported lifecycle and snapshot/identity gaps are closed at this head.

Local exact-head validation passed with the required CGO/thirdparties setup:

  • go test: vectorscan/apply, ivfflat and search plugin, indexplugin tree, vectorindex/sqlexec, planner, compiler
  • race: vectorscan/apply (count=3), ivfflat
  • go vet on the touched execution, IVF, planner, and compiler packages
  • git diff --check

No blocking correctness, lifecycle, or integration issue found.

…x-scan

# Conflicts:
#	pkg/pb/pipeline/pipeline.pb.go
#	pkg/pb/plan/plan.pb.go
#	proto/plan.proto

@XuPeng-SH XuPeng-SH 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.

The previous prepared-execution blocker is fixed on exact head 8c3329da40866d4d097e56b70173fd40195f9410: correlated APPLY and standalone scans now bind fresh execution generations from immutable templates, and the affected race suites pass. One P1 snapshot-identity blocker remains.

relationScanner.ScanRelation clones every non-zero req.Identity.Snapshot unconditionally (pkg/vectorindex/ivfflat/plan_reader.go:531-537). Ordinary table scans only switch to a snapshot operator/context when the requested TS is strictly older than the current transaction snapshot (pkg/sql/compile/compile.go:3980-3999, with the same predicate in the other scan builders). This distinction is observable because raw MO_TS / AS OF TIMESTAMP accept positive equal/ahead timestamps and preserve them in ScanSnapshot: the base/source side remains on the current transaction, but the new IVF hidden-table reader calls CloneSnapshotOp anyway. CloneSnapshotWS is a fresh read-only workspace, so an explicit transaction loses its own source/index writes on the hidden side even though the base join still sees them at TxnOffset; nearest rows can disappear or stale candidates can survive. An ahead timestamp can additionally drive the hidden reader into a future snapshot while the base scan stays current. Identity also applies the snapshot tenant unconditionally, so the account domains can diverge on the same boundary.

Deterministic exact-head probe: current txn SnapshotTS=10, vector ScanSnapshot.TS=20; assert that hidden relation lookup uses the current txn like the generic scanner. The probe fails immediately with an unexpected CloneSnapshotOp({20}).

Please derive the effective historical identity with the same non-zero-and-TS.Less(current SnapshotTS) predicate as ordinary scans, and apply both clone and snapshot-tenant context only in that case (while retaining publisher precedence). Add equal/ahead snapshot tests plus an explicit-transaction regression showing source and all hidden tables keep one transaction/workspace identity. The current CI and existing vector tests do not cover this non-historical snapshot boundary.

@aunjgr

aunjgr commented Aug 20, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the non-historical snapshot identity blocker in 01bd40b; head 00e388a also merges newest main 033f418.

  • Vector scan identity now treats a snapshot as effective only when its TS is non-zero and strictly older than the current transaction SnapshotTS, matching ordinary table scans.
  • Equal/ahead raw timestamps retain the current transaction/workspace and do not apply the snapshot tenant. Publisher identity remains authoritative in every case.
  • The IVF relation scanner defensively repeats the same predicate before creating a clone.
  • Added equal/ahead unit coverage and an explicit-transaction regression: an uncommitted nearest row is visible through a future MO_TS vector scan, then disappears after rollback.

Fresh validation after merging main: full affected-package tests, affected-package build/vet, race suites for vectorscan/apply/ivfflat, exact isolated-cluster snapshot BVT (current 3, historical 1, in-transaction 4, post-rollback 3), and index-plugin structural guards all pass. The worktree is clean.

@XuPeng-SH XuPeng-SH 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.

Re-reviewed exact head 00e388a6f94e27f83a5d3f10acfb7505cbe1db46 against the prior snapshot-identity blocker and the complete execution closure.

The fix now applies the same effective-history predicate as ordinary scans: only a non-zero timestamp strictly older than the current transaction snapshot selects a snapshot clone and snapshot tenant; equal/ahead raw timestamps retain the current transaction/workspace; subscription publisher identity remains authoritative. The decision is shared by standalone/remote and correlated APPLY entry points, and the reader defensively enforces the same transaction predicate.

Verification passed for the new identity/snapshot regressions under -race -count=20, vectorscan/APPLY reuse under -race -count=10, the full ivfflat package under race, and focused compiler/planner suites. No blocking correctness, lifecycle, or integration issue remains.

@mergify

mergify Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-20 15:09 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ❌ Checks failed · in-place
  • 🚫 Left the queue — 2026-08-20 21:54 UTC · at 266a411ff9e70146f18d6cd0f88bf5dbbd192e81

This pull request spent 6 hours 44 minutes 57 seconds in the queue, with no time running CI.

Waiting for
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
    • check-success = Matrixone CI / SCA Test on Linux/arm64
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
All conditions
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
    • check-success = Matrixone CI / SCA Test on Linux/arm64
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]

Reason

The merge conditions cannot be satisfied due to failing checks

Failing checks:

Hint

You may have to fix your CI before adding the pull request to the queue again.
If you update this pull request, to fix the CI, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Requeued — the merge queue status continues in this comment ↓.

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

Deep re-reviewed exact head 266a411ff9e70146f18d6cd0f88bf5dbbd192e81. I read the complete review/comment history and thread replies, checked the incremental changes since my prior approval at 9ac175361071e76558b9a0e94221be2797c9c3fd as well as the full diff, and inspected the final merge from main. The 01bd40b40e2459a646dc0cb811bb89eb339e8a41 historical-snapshot fix correctly preserves the current transaction/workspace for equal or future snapshot specifications, so the previously reported functional issues remain closed on code inspection. However, the current exact head has a new build-blocking regression from the final merge: pkg/sql/plan cannot compile because DeepCopyNode initializes ScanSnapshot twice. I reproduced this with the repository CGO prerequisites and go test ./pkg/sql/plan; it fails before any tests run. The shared build failure reports the same compiler error. Please remove the duplicate initializer and rerun the affected suites/current CI.

Comment thread pkg/sql/plan/deepcopy.go Resolved
@aunjgr

aunjgr commented Aug 21, 2026

Copy link
Copy Markdown
Contributor Author

Resolved the final merge regression in 597d4cc after merging newest main ae01f96.

DeepCopyNode initialized ScanSnapshot twice after the main merge, which made pkg/sql/plan fail to compile. The duplicate initializer is removed; the remaining initializer still deep-copies the snapshot once.

Fresh validation: affected pkg/sql/plan, vectorscan, apply, and ivfflat suites pass with the controlled CGo runner; go vet passes for the same packages; git diff --check is clean. The index-plugin structural guards remain clean. The worktree is clean.

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

Deep re-review completed against exact head 597d4cc91b95732f2973dcd59b7cf317eab9708b.

I read the complete review, inline-thread, reply, and PR-comment history; rechecked the incremental changes after my prior review at 266a411ff9e70146f18d6cd0f88bf5dbbd192e81; and reconciled them with the complete diff against current base ae01f96c4d5c02c973f5bac9e8c4ab82b5dac3a7. The final fix removes only the duplicate ScanSnapshot initializer introduced by the main merge, while retaining the existing single deep copy. The earlier prepared-reuse, correlated APPLY, TxnOffset, over-fetch, MaxUint64, remote snapshot, publisher identity, and non-historical snapshot issues remain closed.

Exact-head validation passed for the affected vectorscan/APPLY, IVF-FLAT/search-plugin, index-plugin, relation-scan, planner, and compiler suites with the required CGo/thirdparties setup; focused vectorscan/APPLY race repetitions; affected-package go vet; and git diff --check. The IVF-FLAT package also passes repeated execution after isolating its process-global centroid cache between repetitions; the temporary probe was removed. Current remote build, UT, SCA, coverage, compose, and standalone checks are green.

No blocking correctness, lifecycle, or integration issue found.

@mergify

mergify Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-21 07:56 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-08-21 09:03 UTC · at f4859c9ce2007571767d994223109c573aa7a8dd · squash

This pull request spent 1 hour 6 minutes 38 seconds in the queue, including 1 hour 6 minutes 10 seconds running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)

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/enhancement kind/refactor Code refactor size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants