Repository navigation
[4.2-dev] Support IVF-FLAT Top-K through equi-joins - #30013
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
mo-bot review · Commit: Assessment: request_changes Reviewed the complete 11-file delta and current review concerns. The late-decline fallback is repaired, but successful ANN adoption still drops an explicit JOIN-index hint. Model: Session:
Validation:
Limitations:
|
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: c1854ffffa9014ae3995bbcc417a529689e94b44
Assessment: request_changes
Reviewed the complete 11-file delta and current review concerns. The late-decline fallback is repaired, but successful ANN adoption still drops an explicit JOIN-index hint.
Model: gpt-6-astra / xhigh
Session: 01a12d8f-7dea-77c2-a565-38d45b5564e4 · slot 0 · generation 0
- P2
pkg/sql/plan/apply_indices_equi_vector.go:241: An IVF-indexed left table with a non-null vector, varchar primary key and idx_document(document_id): SELECT a.id,b.label FROM equi_chunks a FORCE INDEX FOR JOIN(idx_document) JOIN equi_documents b ON a.document_id=b.document_id WHERE b.label='allowed' ORDER BY l2_distance(a.v,'[0,0]') LIMIT 2. Both ordinary and PRE modes adopt IVF.
Impact: The guard suppresses ordinary JOIN-index selection, while successful adoption only resumes filter-index optimization here. The requested index disappears from every reachable scan, violating the explicit access-path contract and making index use depend on join order. Preserve the hint through the existing owner or decline the ANN rewrite when it cannot honor it.
Evidence: TestReviewEquiVectorAdoptedJoinHints exercises the public parser/BuildPlan entry point. Current head produces IVF=1 and indexes=[] for ordinary/PRE; FORCE-vector and reversed-join controls retain idx_document. A diagnostic overlay restoring all changed production Go files to the merge-base retains idx_document in all four cases. Reproducer, logs and receipt mapping are preserved in evidence-audit.json.
Validation:
-
Focused planner checks passed: 62 top-level tests, 274 passing test/subtest records. Log: focused-planner.log; receipt: checks/1791869117286965467-4.json.
-
Independent hint probe reproduced two current-head failures with two passing controls; all four merge-base cases passed. Receipts: checks/1791869166440147582-3.json and checks/1791869271362483936-4.json.
-
Private /tmp and loopback preflight passed. Verified 170 native build inputs and 43 retained artifacts against repository-owned build evidence before testing.
-
Frozen exact-head CI reports successful build, unit tests, static analysis, coverage and multi-CN BVT. Source remains unchanged; supplied patch content and git diff --check verified.
Limitations:
-
Local execution covered production planning with mock catalog metadata, not a SQL cluster. Workload performance was not measured.
-
The linked issue body and detailed current CI logs were not supplied. Earlier author test summaries were not treated as exact-head execution evidence.
-
Evidence is preserved under /home/xupeng/.local/state/mo-bot/jobs/c0b0bcc4528336244485c987/attempt-1. An initial baseline diagnostic import error was corrected before the recorded passing comparison.
|
mo-bot review · Commit: Assessment: approve Reviewed the complete 11-file delta and surrounding ownership paths. Previous guard-scaling, scalar-index, hint-inheritance and JOIN-index fallback concerns are resolved. No actionable findings remain. Model: Session: Validation:
Limitations:
|
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 4bdd7a4e32bae19f9c64ee2bc9720c6fc7fc9fbc
Assessment: approve
Reviewed the complete 11-file delta and surrounding ownership paths. Previous guard-scaling, scalar-index, hint-inheritance and JOIN-index fallback concerns are resolved. No actionable findings remain.
Model: gpt-6-astra / xhigh
Session: 01a12d8f-7dea-77c2-a565-38d45b5564e4 · slot 0 · generation 0
Validation:
-
Complete pkg/sql/plan suite passed: 1,653 top-level tests, 4,320 passing records including subtests; three unrelated subtests skipped.
-
Executed all 128 BVT statements through each of two embedded CN frontends. Row results, column names and 32 EXPLAIN assertions per CN passed, including duplicates, pagination, distance bounds, prepared reuse and forced JOIN hints.
-
Ordinary projection guards allocated zero bytes and scaled approximately linearly across 256–4,096 projections; public BuildPlan benchmarks also completed.
-
Isolation preflight passed. Verified 170 native inputs and 43 retained artifacts against repository-owned build evidence. Frozen patch, clean source, formatting, whitespace and plugin-dispatch checks passed.
-
Commands, source fingerprints, successful exit receipts and retained logs are reconciled in /home/xupeng/.local/state/mo-bot/jobs/f149fda14701e7c0956a4378/attempt-1/evidence-audit.json; review rationale is in review-record.json.
Limitations:
-
The frozen evidence omits linked issue #29702's body and current-head CI results. Earlier author-reported runs were not counted as current-head validation.
-
SQL validation used a diagnostic MySQL harness on an embedded two-CN cluster, rather than the canonical Java BVT harness; JDBC type-code formatting was not compared.
-
Production-scale ANN recall and performance were not measured. No fresh race suite was run for these sequential planner changes.
#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 #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.A SEMI JOIN Beligibility relation and feed its exact membership into existing IVF-FLAT candidate selection.INNER JOIN, preserving duplicate multiplicity, right-side projections, final ordering, and pagination. Candidate budget includesOFFSET.DistRangeannotations, so an annotation alone cannot enforce upper or lower bounds before candidate truncation.Scope and compatibility
The new optimization supports ordinary
LIMITand explicitPRE. Unsupported shapes and modes retain their existing behavior;FORCEremains 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
pkg/sql/plantests,-vet=all, native build, formatting, and diff checks passed.FORCEcomparisons, distance bounds, pagination, empty results, and prepared execution.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 inpkg/sql/plan/apply_indices.go; merging both must retain both registrations. A combined merge on base7ca3113da9passed 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
copyNodepath 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.Validation for this follow-up (
ce814c96de, Go 1.26.4, linux/amd64, fresh matching CPU CGo libraries):-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.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.