Repository navigation
feat(vector): enable ANN indexes for scalar subquery vectors - #29493
Conversation
aptend
left a comment
There was a problem hiding this comment.
Deep review of exact head 8347956 against declared base/merge-base 76862df, covering the complete 28-file diff and its planner, compiler, operator, generated-plan, metadata/EXPLAIN and SQL-test consumers. GitHub has no prior reviews or inline threads for this PR; I also read the versioned design/authorization record and both pagination/JOIN follow-ups. The design's SHA-256 matches its pinned approval artifact. No blocking finding remains.
The SQL1-only constraints are preserved: PK/UK at-most-one-row admission and conservative fallback; one statement-local provider evaluation; NULL/empty source retains the original scalar relation; unsupported multirow/correlated/force shapes stay on the old path; prepared metadata comes from the result schema and execution generations do not retain the old vector. Queries containing the selector are confined to the ingress CN, including upper consumers. The private lazy selector is isolated behind an ordinary merge scope, so JOIN's independent build dependency starts concurrently. I traced source Begin/Append/Finish/reader-release/Close and scope cancellation/completion barriers through failed startup, zero demand, early termination, error and reuse; unselected branches are cleaned without being executed.
Exact-head local evidence: complete plan, compile, plan/explain, vectorquery, materialized, pb/plan and vm suites passed; complete compile/vectorquery suites passed under -race; the actual JOIN-scope and lazy-scope tests passed 100 race-enabled repetitions (2.374s). Protobuf regeneration with protoc 3.21.1 plus the repository postprocessor is byte-identical; diff whitespace checks passed.
Current-head CI run 36663000119 is successful. I inspected its compose execution artifact, not just its file-selection list: vector_scalar_query.sql passed 114/114 and vector_prepared_limit.sql passed 49/49, with zero failed/ignored/abnormal cases. The corrected direct-CN author evidence was reviewed separately; I did not start a new cluster or claim fresh production-performance/mixed-version validation. Main-workspace files were not changed.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep review of head 834795660baac3b1da33e35f629c5b7ecce8b939 against declared base/merge-base 76862df5c89e8868bed5963c428f65b9eafb34b3: no blocking finding remains. Reviewed all 28 changed files and the relevant unchanged planner, plugin, placement, merge/scope, materialized-source and allocation-account owners. No subagents or production changes were used.
Design and ownership:
- The pinned, authorized SQL1 design matches its recorded SHA-256. The implementation retains the PK/UK at-most-one-row admission boundary and rejects unsupported/unproven shapes rather than weakening scalar cardinality semantics.
- Existing generic index plugins still own ANN plan construction; existing materialized Source owns retained data, generations, accounting and cleanup; existing lazy scopes own branch startup, completion and cancellation. The selector adds the necessary provider/ANN/original-relation decision, not another cache, storage path or per-algorithm executor. The original relation is necessary for NULL/empty-source semantics, not an error-recovery retry that hides ANN failures.
- Provider completion is checked before publishing the selection. Receiver activation precedes branch startup; terminal errors propagate. Prepared result metadata comes from the result schema, and execution generations do not cache the previous provider vector.
- The earlier outer-pagination and JOIN-startup failures are closed: outer demand stays above the selector, and an ordinary merge boundary prevents an upper JOIN build dependency from becoming a private, never-started selector branch. GitHub has no inline review threads to resolve; I separately checked the recorded design/pagination/JOIN follow-ups.
QA and evidence:
- Traced zero demand, provider/start/result failure, consumer cancellation/error, skipped-branch cleanup, reader release, source Close, allocation-account terminal cleanup and reuse through their actual owners.
- Independent review-only probes passed for outer LIMIT 1 stopping an eight-batch ANN or empty-provider exact stream: exactly the selected branch starts, and terminal account/mpool usage is zero. The corrected production-owner fixture passed 100 race-enabled repetitions. An initial 8-byte residual was from omitting the connector allocation-account terminal protocol in that probe; configuring and finalizing the real owners resolved it without weakening assertions. It is not evidence of a PR leak.
- Independent typed-planner probes passed for multiple CTE/UNION consumers with distinct selector source IDs, constant projection, provider OFFSET/LIMIT 0 and conservative unproven/aggregate/distinct cases. Protobuf regeneration plus the repository postprocessor is byte-identical; diff checks passed.
- Reused the qualifying author normal/race owning-suite evidence after checking freshness of the relevant lifecycle paths. Current-head CI run 36663000119 is successful. I downloaded its compose execution artifact and verified actual execution, not only selection:
vector_scalar_query.sql114/114 andvector_prepared_limit.sql49/49, with zero failed/ignored/abnormal cases. No new cluster or production-scale benchmark was run.
Complexity and performance boundaries:
- Reviewed production (+641/-18), tests (+1322), generated code (+1198/-1151) and documentation (+308) separately. The new runtime logic is scoped to the selector and its planner/compiler integration; tests exercise distinct admission, execution, metadata and SQL-result contracts rather than being exempted by line count. No blocking redundant execution/storage owner or dead compatibility path was found.
- Approval is for the documented CPU IVF/HNSW SQL1 scope, not all of issue #23158 or new GPU support. Eligible non-NULL queries gain an ANN access path, but this is not a measured universal speedup: the entire selector-containing query, including upper JOINs and NULL fallback, stays on the ingress CN. Loss of cross-CN parallelism is an explicit authorized tradeoff. Production throughput and mixed-version execution remain unmeasured and are not claimed by this review.
Merge Queue Status
This pull request spent 19 seconds in the queue, with no time running CI. ReasonThe pull request #29493 has been manually updated Required conditions to merge
Tick the box to put this pull request back in the merge queue (same as
|
#30012) ## What type of PR is this? - [ ] API-change - [ ] BUG - [x] Improvement - [ ] Documentation - [x] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Related to #23158 — **SQL1 only**. SQL2/SQL3 remain out of scope; this PR does not resolve the entire issue. ## What this PR does / why we need it: Reimplements the scalar-subquery query-vector capability from #29493 natively on `4.2-dev`, using the existing IVF-FLAT/HNSW providers and materialized-source facilities. This is **not a cherry-pick** and does not import the mainline dependency chain. - Recognize an independent scalar provider proven to return at most one row by PK/UK equality. - Require a NOT NULL candidate-vector column in the scan schema. Nullable candidates retain the original relational path, preserving NULL-first ordering and pagination; a non-NULL provider alone is not sufficient. - Materialize the provider once per execution generation, then select ANN for a non-NULL vector or the original relational branch for an empty/NULL provider. Provider/ANN errors never silently select fallback; `LIMIT 0` starts no branch. - Introduce a private selector execution domain with delayed datasource initialization. Wait for producer completion beyond EOF; cancel and join started branches before closing the source generation, and clean unstarted branches without waiting for nonexistent producers. General `MergeRun` scheduling is unchanged. - Preserve result metadata, prepared execution, source/batch ownership, and plan consumers (remap, deepcopy, statistics, EXPLAIN, compile, and VM). - Protect the Compile-owned Fold registry and mutable executors across concurrent lazy datasource initialization and active local/remote block-filter consumers, including Reset/Free. ONECN does not imply local serialization; the lock covers Fold operations, not datasource I/O or pipeline startup/join. - Regenerate protobuf bindings with node values 58/59 and source field 93; use VM opcode 67 without renumbering existing operators or filling reserved gaps. ### Design review and approval (specific to this 4.2 reimplementation) The dedicated execution domain, lifecycle, and cross-package/protocol changes trigger the design gate. This PR uses its **own pre-implementation 4.2 design**, not the approval of the mainline #29493 design. All links below are pinned to publication commit `b75a76eda3be0d988e2c0e75b165bcee9fb8aeb2`: - [Approved 4.2 reimplementation design v1](https://github.com/matrixorigin/matrixone/blob/b75a76eda3be0d988e2c0e75b165bcee9fb8aeb2/docs/design/CLAUDE_20261012-vector-query-4.2-reimplementation-v1.md). Its original bytes are unchanged; SHA-256: `03c8b3878093fe4e6336cef1becc10e5c875870d00efb8fcafd8197ceb18aedd`. - [Design-first approval record](https://github.com/matrixorigin/matrixone/blob/b75a76eda3be0d988e2c0e75b165bcee9fb8aeb2/docs/design/CLAUDE_20261012-vector-query-4.2-approval.md). The task owner reviewed v1 and replied **“go ahead” before implementation**. This is a recorded local task-owner approval, not a GitHub `APPROVED` review or a substitute for maintainer review. The snapshot retains its original pre-approval wording to preserve the reviewed hash; the separate record documents the subsequent approval. - [PR-specific lifecycle and implementation mapping](https://github.com/matrixorigin/matrixone/blob/b75a76eda3be0d988e2c0e75b165bcee9fb8aeb2/docs/design/CLAUDE_20261012-pr30012-design-traceability.md). This maps v1 to startup/partial-initialization failure, completion after EOF, cancellation and joining, Compile/source/reader generation ownership, and the coordinating-CN boundary, with fixed source links and named tests. It is a post-implementation traceability supplement, not a newly or retroactively approved design revision. The shared v1 design also covers the independent JOIN work in #30013; its JOIN section is not a dependency of this PR. Publication commit `b75a76eda3` changed documentation only. The subsequent P1 Fold-ownership fix is documented in [the updated traceability, §6](https://github.com/matrixorigin/matrixone/blob/bc5193120aee84e31f2079309ac7f4bc6e1aeb71/docs/design/CLAUDE_20261012-pr30012-design-traceability.md), with fresh validation below. The approved v1 bytes remain unchanged; this fix does not itself constitute reviewer acceptance of the design gate. ### Review follow-up (`b930f9dc05`) The reviewer checked the frozen design and approval record and found the direction reasonable, then requested two P2 fixes and suggested one P3 consolidation. [Updated traceability, §7](https://github.com/matrixorigin/matrixone/blob/b930f9dc05f84d6a6120511ebbe472785a961d74/docs/design/CLAUDE_20261012-pr30012-design-traceability.md) records: - **Snapshot ownership:** conservatively exclude both snapshot providers and snapshot candidate tables from the new lazy selector. Keep their ordinary relational plan and initialization path; mixed statements can still optimize non-snapshot regions. This does not claim the generic `CloneTxnOperator` API is now concurrency-safe. - **Prepared compile reuse:** retain already-local TP/AP_ONECN classifications; only constrain AP_MULTICN. A real public HNSW PREPARE builds a non-empty Compile cache, and the EXECUTE cache consumer returns the same Compile across resets. The pre-fix test failed because that cache was nil. - **Shared dispatch:** the ordinary PROJECT path now calls `applyVectorIndexForSortContext`, removing duplicate policy while retaining exact-sort stabilization, error propagation, and prepared dependency capture. Latest `mo/4.2-dev` (`02b0689fa9`) was merged, not rebased. These fixes await reviewer re-review; they are not a GitHub approval. ### NULL-candidate correctness follow-up (`e1a4eeb104`) IVF/HNSW omit NULL candidates. On the previous binary, a three-row table returned **2/1** for `LIMIT 1`/`LIMIT 1 OFFSET 1`, whereas FORCE and the same table after dropping its index returned **0/2**. The shared scalar admission check now requires the actual candidate column's schema `NotNullable`, selected by scan binding and column position rather than argument order or expression/provider annotations. No new compensation branch is introduced; NOT NULL candidates and NULL/empty-provider handling remain supported. [Traceability §8](https://github.com/matrixorigin/matrixone/blob/e1a4eeb1047525af681b057093149bb85d23c9e4/docs/design/CLAUDE_20261012-pr30012-design-traceability.md) records the proof and validation. ### Scope and compatibility The new optimization supports ordinary `LIMIT` and explicit `PRE` with schema-proven NOT NULL candidate vectors; nullable candidate columns, snapshot-bearing regions, and other unsupported shapes/modes retain their existing behavior. Queries using the selector remain on their entry/coordinating CN, and selector scopes are rejected at remote-dispatch boundaries. This does not claim mixed-version deployment validation, add a general distributed scalar-subquery framework, or change index storage/CDC. ### Validation All runs use Go 1.26.4 and the repository CGo wrapper. #### Latest target merge / conflict resolution (`7d1130e43f`) - Merged `mo/4.2-dev` at `9978492f11` normally after #30013 landed. Preserved both scalar and equi-join guard/dispatch registrations, the single shared plugin helper, upstream regular-index fallback, and scalar NULL/snapshot admission. [Traceability §9](https://github.com/matrixorigin/matrixone/blob/7d1130e43fd7dde2a6e06b9fa39804adca90b459/docs/design/CLAUDE_20261012-pr30012-design-traceability.md). - Complete planner/compiler normal tests with vet, actual frontend PREPARE Compile-cache regression, native build, formatting, and diff checks passed. Runtime synchronization/selector lifecycle is unchanged; prior race evidence is reused, not claimed as rerun. - Fresh-data two-CN comparisons passed scalar **133/133**, current JOIN **128/128**, and existing IVF **275/275**: **536/536 through each entry**, with no ignored/abnormal cases. Existing expected results were compared unchanged. The owned service was stopped; shutdown logs showed no mpool leak, cleanup timeout, or panic. - Added-production statement-block coverage relative to the pre-merge head (including upstream JOIN code): **180/186 = 96.77%**. Whole scalar PR relative to the new target: **484/546 = 88.64%**, with fresh planner profiles and reused unchanged-runtime profiles. The shared helper now belongs to the target, explaining the changed denominator. #### Prior NULL-candidate fix (`e1a4eeb104`, historical provenance) - Public planner counterexamples fail before the fix and pass afterward for IVF/HNSW, nullable/NOT NULL controls, reversed arguments, relocated candidate columns/oppositely nullable unrelated columns, OFFSET, PRE, PREPARE, and IS NOT NULL. Guard tests also reject nullable schema despite a NOT NULL expression annotation and verify no mutation. - Focused scalar tests, complete planner normal tests with `-vet=all`, the actual frontend PREPARE Compile-cache regression, native build, formatting, and diff checks passed. This stateless planner admission change does not modify runtime ownership/concurrency; prior runtime race evidence below is reused, not claimed as rerun. - Fix-only changed-production statement-block coverage: **6/6 = 100%**. Whole-PR coverage: **534/617 = 86.55%**, replacing planner profiles and reusing unchanged-file evidence. - Fresh-data owned two-CN validation: scalar BVT **133/133** plus existing IVF regressions **275/275**, total **408/408 through each entry point**, with no ignored/abnormal cases. New ordinary/PRE/parameterized LIMIT and OFFSET results match FORCE and no-index execution. Generated results were inspected before normal comparisons. - The owned validation services were stopped; shutdown logs showed no mpool leak, cleanup timeout, or panic. No design-v1 bytes, protocol, storage format, or unrelated worktree were changed. Existing review requests remain pending; no new inline thread for this finding was present. #### Prior snapshot/cache/dispatch fixes (`b930f9dc05`, historical provenance) - Complete planner/compiler/frontend normal tests with vet passed; complete compiler/frontend race passed. `TestVectorQueryConcurrentDataSourceFolds` (now including snapshot eager initialization before two lazy scans) and `TestPreparedScalarVectorCompileCache` each passed an exact-selection `-race -count=100` run after single-run measurement. Final frontend AST-cleanup changes were revalidated with focused/repeated/full race and full normal tests. - Public planner tests cover IVF/HNSW with two snapshot providers, mixed current/snapshot regions, snapshot candidate tables, and current-only controls. Both the admission and actual PREPARE-cache tests failed before the fixes for their intended semantic reasons. - Existing prepared index-only dependencies, FORCE/descending/project-child exact-sort stabilization, HNSW, and plugin tests passed through the owning planner suite. - Native build, Go 1.26.4 formatting, and diff checks passed. Fix-only changed-production statement-block coverage: **11/11 = 100%**. Whole-PR coverage: **528/611 = 86.42%**, with fresh changed-file profiles and explicitly reused unchanged-file evidence. - A fresh-data, owned two-CN instance passed scalar BVT **103/103** plus existing IVF regressions **275/275 through each entry point**, total **378/378 per entry**. New old/old snapshot results `(2,2)` and current/old results `(3,2)` match FORCE. Results were inspected after generation and then validated by normal comparison. - The owned service was stopped. Logs through shutdown showed no mpool leak, pipeline cleanup timeout, or panic. Previous data and local validation artifacts were retained, not submitted. #### Prior Fold fix (`bc5193120a`, historical provenance) For the earlier Fold fix: - Reproduced the pre-fix race with two concurrent `InitAllDataSource` calls plus an active block-filter consumer. The value oracle also failed: expected **11**, got **23**. - Complete compiler/planner normal tests with `-vet=all`, complete compiler `-race -count=1`, native build, formatting, and diff checks passed. - Focused race passed; `TestVectorQueryConcurrentDataSourceFolds` and `TestCompileFoldLockTerminalPaths` each passed a separate exact-selection `-race -count=100` run. Tests cover local consumers, remote registration, unique Fold IDs/correct values, error/panic unlock, reset/reuse, and cleanup. Planner tests assert two distinct selectors for both IVF and HNSW filtered queries. - Fix-only changed-production statement-block coverage: **63/65 = 96.92%**. Updated whole-PR coverage: **521/608 = 85.69%**, replacing compiler/planner profiles with fresh runs and reusing unchanged-file profiles; excludes tests/generated files. - IVF/HNSW scalar BVT: **96/96 through each CN entry point**, including the new differently filtered/provider-bound two-selector queries and their FORCE comparisons. Existing IVF membership/mode/mode_advanced/retry suites: **275/275 through each entry**. Total: **371/371 per CN entry** on one owned two-CN instance. Expected results were inspected before normal comparison runs. - The validation service was stopped; logs through shutdown showed no mpool leak or pipeline cleanup timeout. Earlier evidence at implementation revision `1b03471c649d352a8940095d60f353be7ffcb43d`: all six owning packages (planner/compiler/EXPLAIN/merge/vectorquery/VM), vet, reproducible protobuf generation, focused lifecycle race `-count=3`, and full compiler/merge/vectorquery/materialized-source race `-count=1`. The new compiler runs above supersede that package's prior evidence. Unchanged-package evidence is reused, not represented as freshly rerun. Existing lifecycle tests cover cancellation, errors after EOF, initialization panics, unselected readers, owned-batch release, and consecutive zero-LIMIT generations. ### Integration note The scalar implementation was developed independently of #30013. That JOIN PR has now landed in `4.2-dev`, and merge `7d1130e43f` incorporates the latest target while preserving both planner registrations. Fresh combined validation on this actual merged tree is **536/536 through each CN entry**, as listed above. The earlier temporary combined merge's **440/440** on base `7ca3113da9` remains historical evidence only; that temporary merge was never delivered. JOIN changes are now part of the target, not additional scalar-PR scope.
What type of PR is this?
Which issue(s) this PR fixes:
Related to #23158 — SQL1 only. This is a partial implementation and does not close the issue; SQL2 and SQL3 are outside this PR's scope.
What this PR does / why we need it:
Design and approval (pinned revision)
These versioned artifacts publish the prior design-first discussion and task-owner authorization, together with the requested clarification. The record distinguishes the original approval from the later publication; it is not a new GitHub APPROVED review. The authoritative constraint is the entire query containing the selector runs on the coordinating CN, including upper consumers—not just the local vector subgraph.
Summary
Enable eligible scalar-subquery query vectors to use existing IVF-FLAT and HNSW indexes, for example:
Execution boundary
Queries containing the selector run entirely on the coordinating CN, with existing intra-CN parallelism. This is an explicit constraint of the process-local provider source, not a distributed InitPlan implementation. Queries without the selector retain their existing placement.
No index-storage format or CDC/ISCP changes are included. No production-scale performance or mixed-version-cluster claim is made.
Initial implementation validation (
c642c7e46b)All validation used Go 1.26.4, the repository CGo test wrapper, and worktree-built native artifacts. Container SQL validation used linux/arm64 + typecheck.
pkg/sql/plan,pkg/sql/compile,pkg/sql/plan/explain,pkg/sql/colexec/vectorquery,pkg/sql/internal/materialized,pkg/pb/plan, andpkg/vm.compileandvectorquerypackages. The real lazy-scope lifecycle test also passed 100 race-enabled repetitions.vector_scalar_query.sql: 77/77.vector_prepared_limit.sql: 49/49.-Dconf.ymlargument was not read by the tester. Fresh explicit per-CN validation is reported below.The initial single-CN deployment used separate Log/TN/CN/Proxy services. The design-publication commit changed only the two linked documents.
P2 review follow-up (
3dde84cf5c)LIMIT 0failing compilation withvector query requires exactly two readers. The reader-count assertion remains intact; inner Top-K and outer pagination retain separate semantics.mo/mainat9e50a0f2c9. Go 1.26.4 normal tests passed for completeplan,compile, andplan/explainpackages; focused scalar-query tests passed with-count=1normally and under race. Incremental lint: 0 issues. Changed production-line coverage for this follow-up: 21/21 = 100% (coverage-block mapping).vector_scalar_query.sql96/96, existingvector_prepared_limit.sql49/49, 0 ignored, with database teardown checked after each run.SELECT * FROM (...) LIMIT 0shape, nonzero outer LIMIT/OFFSET, empty-provider zero demand, and PREPARE zero-to-nonzero reuse. No new two-CN run is claimed for these expanded cases; placement and the source/lazy-branch lifecycle protocol are unchanged, and the earlier two-CN evidence applies to its original selection.JOIN-scope review follow-up (
d38f54307f)VECTOR_QUERY_TOP; a multiply referenced/materialized CTE is retained only as a distinct control. Actual HashJoin/MergeRun tests cover results, NULL fallback, zero demand, downstream errors/cancellation, and allocation-account/mpool cleanup. SQL regressions cover IVF/HNSW inline CTE self-joins and prepared parameter reuse.mo/mainate5f70bedc4; resolved the generated plan-binding conflict by regenerating protobufs, then verified byte-identical regeneration. Rebuilt and reran final validation after this merge.compile,plan,plan/explain,vectorquery,materialized, andpb/planpackages. Completecompile/vectorqueryrace passed; the new JOIN test passed 100 race-enabled repetitions. Incremental lint: 0 issues. Follow-up production coverage: 4/4 = 100% by coverage-block line mapping (the executable change is one return statement).vector_scalar_query.sql: 114/114; existingvector_prepared_limit.sql: 49/49, 0 ignored, teardown verified after every run. The two CN services share a launch process but have distinct SQL/RPC endpoints; this is not a new Docker multi-process validation claim.mo.ymlin each isolated working directory, binding the intended SQL and diagnostic ports. This replaces the old mislabeled direct-CN BVT evidence. Separatemysql -Pphysical-plan/result probes confirm two selectors beneath the JOIN and all physical scopes on the ingress CN for both IVF/HNSW.All task-owned test services have been stopped. Local TODOs, raw sessions, logs, and test infrastructure are excluded from the commits.