Skip to content

[4.2-dev] Support scalar-subquery query vectors with IVF-FLAT and HNSW - #30012

Merged
XuPeng-SH merged 8 commits into
matrixorigin:4.2-devfrom
ck89119:issue-23158-4.2-dev
Oct 13, 2026
Merged

XuPeng-SH merged 8 commits into
matrixorigin:4.2-devfrom
ck89119:issue-23158-4.2-dev

Conversation

@ck89119

@ck89119 ck89119 commented Oct 12, 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:

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. Its original bytes are unchanged; SHA-256: 03c8b3878093fe4e6336cef1becc10e5c875870d00efb8fcafd8197ceb18aedd.
  • Design-first approval record. 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. 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, 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 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 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 [4.2-dev] Support IVF-FLAT Top-K through equi-joins #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.
  • 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.

@XuPeng-SH

XuPeng-SH commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: e1a4eeb1047525af681b057093149bb85d23c9e4

Assessment: approve

Reviewed the complete 37-file delta. The scoped scalar-vector implementation preserves fallback semantics, prepared reuse and lifecycle ownership. Prior snapshot, compile-cache and duplicate-dispatch concerns are addressed; nullable candidates correctly retain ordinary execution. No actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a12d8f-8e48-7622-ad17-b605f08450ce · slot 1 · generation 0

Validation:

  • Traced planner admission through plugin dispatch, remapping, compilation, branch activation, cancellation, cleanup and generation reuse; reviewed unit-test oracles and IVF/HNSW SQL expectations.

  • Reused frozen current-head successes for build, Ubuntu UT, arm64 static analysis, coverage and complementary multi-CN BVT jobs.

  • Reconciled revision-specific author validation reports, including 408/408 SQL statements per CN entry. Runtime files remain unchanged from the reported prior race-tested revision.

  • Local reconciliation passed: clean pinned source, diff check, approved-design hash, and generated descriptor comparison showing only nodes 58/59 and field 93. Receipt: checks/1791875175240536088-2.json; log: protocol-reconciliation.log.

  • Preserved the detailed assessment in attempt-1/review-record.json.

Limitations:

  • No local runtime tests were repeated. The supplied bundle contains CI status and author reports, but no raw author execution receipts or logs.

  • Coordinator-local execution is an explicitly approved tradeoff. Mixed-version deployment and quantitative performance or recall claims remain outside the validated scope.

  • Review covers issue [Bug]: vector index didn't take effect #23158 SQL1; SQL2/SQL3 and the separate JOIN feature are excluded.

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

mo-bot review · mo-bot-local · review

Commit: e1a4eeb1047525af681b057093149bb85d23c9e4

Assessment: approve

Reviewed the complete 37-file delta. The scoped scalar-vector implementation preserves fallback semantics, prepared reuse and lifecycle ownership. Prior snapshot, compile-cache and duplicate-dispatch concerns are addressed; nullable candidates correctly retain ordinary execution. No actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a12d8f-8e48-7622-ad17-b605f08450ce · slot 1 · generation 0

Validation:

  • Traced planner admission through plugin dispatch, remapping, compilation, branch activation, cancellation, cleanup and generation reuse; reviewed unit-test oracles and IVF/HNSW SQL expectations.

  • Reused frozen current-head successes for build, Ubuntu UT, arm64 static analysis, coverage and complementary multi-CN BVT jobs.

  • Reconciled revision-specific author validation reports, including 408/408 SQL statements per CN entry. Runtime files remain unchanged from the reported prior race-tested revision.

  • Local reconciliation passed: clean pinned source, diff check, approved-design hash, and generated descriptor comparison showing only nodes 58/59 and field 93. Receipt: checks/1791875175240536088-2.json; log: protocol-reconciliation.log.

  • Preserved the detailed assessment in attempt-1/review-record.json.

Limitations:

  • No local runtime tests were repeated. The supplied bundle contains CI status and author reports, but no raw author execution receipts or logs.

  • Coordinator-local execution is an explicitly approved tradeoff. Mixed-version deployment and quantitative performance or recall claims remain outside the validated scope.

  • Review covers issue #23158 SQL1; SQL2/SQL3 and the separate JOIN feature are excluded.

XuPeng-SH added a commit that referenced this pull request Oct 13, 2026
## 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 #29702.

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

Reimplements the IVF-FLAT equi-join capability from #29767 natively on
`4.2-dev`. This is **not a cherry-pick**: it does not import the
mainline dependency chain or the unrelated CDC changes.

- Build a private `A SEMI JOIN B` eligibility relation and feed its
exact membership into existing IVF-FLAT candidate selection.
- Reconnect candidates to the original `INNER JOIN`, preserving
duplicate multiplicity, right-side projections, final ordering, and
pagination. Candidate budget includes `OFFSET`.
- Keep distance predicates in the membership qualification path: the 4.2
executor does not consume `DistRange` annotations, so an annotation
alone cannot enforce upper or lower bounds before candidate truncation.
- Use conservative shape, equality, nullability, replay-safety, and
plugin-capability checks. Reuse existing membership protocol/version
checks and resource handling.

### Scope and compatibility

The new optimization supports ordinary `LIMIT` and explicit `PRE`.
Unsupported shapes and modes retain their existing behavior; `FORCE`
remains the exact-query opt-out. This does not add a JOIN cost model or
promise ANN recall/performance improvements for every workload. No
index-format, CDC, or global scheduler changes are included.

### Validation

- Go 1.26.4 with the repository CGo wrapper: complete `pkg/sql/plan`
tests, `-vet=all`, native build, formatting, and diff checks passed.
- Changed-production statement-block coverage: **170/183 = 92.90%**
(excluding tests/generated files).
- New BVT: **73/73 through each of two CN entry points**, including
duplicate joins, right projections, integer/string primary keys, exact
`FORCE` comparisons, distance bounds, pagination, empty results, and
prepared execution.
- Existing IVF membership/mode/retry BVT: **275/275**.

### Integration note

This branch is independently based on `4.2-dev`; it does not depend on
the scalar-query reimplementation in #30012. The two implementations
overlap at guard/dispatch registration in
`pkg/sql/plan/apply_indices.go`; merging both must retain both
registrations. A combined merge on base `7ca3113da9` passed
planner/compiler/parser tests, native build, and **440/440 BVT
statements through each CN entry point**, with no observed mpool leak or
pipeline cleanup timeout. The temporary integration merge is not
included in this PR.


### Follow-up: preserve scalar-index hint ownership

- Fix the remaining A-side hint loss identified in review. The
eligibility scan inherits hints from the original vector input; the
existing common `copyNode` path forwards the same scoped hint set and
logical owner to later membership copies. No additional hint state,
access-path implementation, runtime protocol, or index-format change is
introduced.
- Add public BuildPlan regressions for INNER, reversed INNER and SEMI
shapes, with unhinted and scoped controls. Every reachable scan must
obey A-side IGNORE/USE restrictions while retaining IVF eligibility.
Cover recursive copying, hint scopes and logical ownership. Extend the
existing BVT with scalar-index negatives, IVF positives and exact
duplicate-preserving FORCE FOR JOIN row checks in both JOIN directions.

Validation for this follow-up (`ce814c96de`, Go 1.26.4, linux/amd64,
fresh matching CPU CGo libraries):

- Before the fix, the public BuildPlan regression failed in all six
A-side IGNORE/USE cases; the three unhinted controls passed. After the
fix, all 12 public hint cases and eight scoped copy cases passed,
alongside retained planner regressions.
- Complete planner normal UT passed. Complete planner race passed using
the existing CI runner method: eight serial groups on one host, all
1,649 discovered tests executed and passed, zero skipped or omitted.
Focused compiler candidate/membership/CN-dispatch/offset tests passed in
normal and race modes.
- Incremental configured SCA across planner and compiler passed:
formatting, `-vet=all`, and diff-based lint (golangci-lint 2.14.0, zero
issues). This is not a claim that a full repository or CI SCA has
completed. An optional whole-file scan reported four preallocation
suggestions in untouched code.
- The complete existing-plus-extended BVT case passed twice through each
of two CN entry points, 116/116 statements per comparison, on the
canonical 3-CN cluster. Schema cleanup was checked between comparisons;
the final direct-JVM validation also passed cluster close. Earlier
monolithic race and Bash-wrapped validation attempts failed and are
excluded from completion evidence.
- Solution and overall review: `gpt-6.1-sol` / `xhigh`. No unresolved
material source/design findings. The fix adds planner-time metadata
propagation only; no measured production latency gain is claimed.

Earlier validation above is author-reported evidence for earlier
revisions. CI for the updated head remains pending.

---------

Co-authored-by: XuPeng-SH <[email protected]>

This branch was previously deployed

1 inactive deployment
ci — 7d1130e4 Deployed Oct 13, 2026 by XuPeng-SH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/enhancement kind/feature size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants