Skip to content

Vector join bug - #27057

Merged
XuPeng-SH merged 14 commits into
matrixorigin:mainfrom
cpegeric:vector_join_bug
Aug 15, 2026
Merged

XuPeng-SH merged 14 commits into
matrixorigin:mainfrom
cpegeric:vector_join_bug

Conversation

@cpegeric

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 #25974 #25967

What this PR does / why we need it:

Three commits. The first two are independent defects found while verifying the third;
they are kept separate so each can be reviewed or reverted on its own.

1. A consumer above a vector Top-K disabled the index (#25967, #25974)

An outer ORDER BY over a Top-K CTE (#25967), or a relational JOIN consuming one
(#25974), silently fell back to a full table scan with an exact sort. Results stayed
correct, so nothing surfaced in the result set — only the plan showed it, and only if you
looked.

-- both of these lost ivf_search / hnsw_search / cagra_search / ivfpq_search
with knn as (select id, l2_distance(v,'[…]') d from t
             order by l2_distance(v,'[…]') limit 3)
select id, d from knn order by d;                       -- #25967

with knn as (…same…)
select k.id, m.name from knn k left join meta m on k.id = m.id;   -- #25974

Root cause. The rewrite is anchored at a PROJECT whose direct child is the Top-K
SORT, so any consumer between them hides it — and applyIndices dispatches on
TABLE_SCAN / JOIN / PROJECT, never SORT. In both plans the Top-K sort survives
intact, with its limit, and nothing rewrites it.

Fix — a second, SORT-anchored entry point. applyIndicesForSort /
buildVectorSortContextFromSort fire for a Top-K whose parent is not a project.
applyIndices already repoints parents from the returned node id, so one mechanism covers
outer sort, join input, and any future consumer shape:

  • requires sortNode.Limit != nil, so a bare outer ORDER BY is never mistaken for the
    Top-K and the user's ordering is never discarded;
  • spliceVectorRewrite — with a project it repoints projNode.Children[0] and returns the
    same node id as before; without one it returns the new subtree root and publishes the
    column remap into idxColMap, which applyIndices applies to every ancestor on the way
    back out;
  • the plugin dispatch loop is now shared by both anchors, so they cannot drift on which
    algorithms they try; hnsw/cagra/ivfpq receive idxColMap (previously ivfflat only).

Two things the anchor has to get right, both found during self-review and both fixed
here:

  • applyIndices walks children before the node, so the sort anchor would otherwise claim
    the classic PROJECT → SORT → SCAN shape. With no project to read column requirements
    from, ivfflat disables the index-only scan and every plain ORDER BY dist LIMIT k
    grows a join back to the base table
    . collectSpecialIndexGuards now marks
    project-anchored sorts and applyIndicesForSort yields to them.
  • A Top-K reached only through the sort anchor still owns its TABLE_SCAN. Without a
    guard entry, applyIndicesForFilters rewrites that scan into a secondary-index join
    first and the ANN rewrite then finds a JOIN instead of a scan — so it never fires.
    detectVectorGuardFromSort reserves the scan. Without this the fix only worked for
    filter-free inner queries.

Hardening carried in the same commit (each traced to a concrete failure):

Change Why
Bounds-check ORDER BY ColPos in buildVectorSortContextFrom and pushdownVectorIndexTopToTableScan `select
count(*) from () t` prunes the derived projection to length 0 while the sort keeps its pre-pruning ColPos →
panic
Decline a sort-anchored rewrite when idxColMap is nil writing to a nil map panics; dropping the remap would
splice a tree whose ancestors reference a replaced project
Remap the child's pass-through columns when ORDER BY carries the distance call directly the child is detached
either way, so its columns must not dangle
Skip non-column entries in replaceColumnsForColRefList vector remaps now reach every ancestor, including nodes
with UpdateCtxList; a function-valued remap hit an unchecked type assertion

2. table_scan panic on a partially materialized batch

evalFilter called bat.Shrink(sels), which walks every vector assuming each holds
bat.RowCount() rows. The vector-TopN pushdown breaks that:
blockio.materializeVectorTopNRows loads only the selected rows and then
CleanOnlyData()s the ORDER BY vector column itself — its values were already consumed to
compute the distances — leaving that column at 0 rows among siblings holding
len(selectRows). The reader still presents the batch as fully loaded
(loadedColumns=nil whenever r.orderByLimit != nil), so shrinking by row index indexed
the empty column:

internal error: panic runtime error: index out of range [4] with length 0
  vector.shrinkFixed → vector.Shrink → batch.Shrink → table_scan.evalFilter

Reproduced deterministically on an IVF-FLAT include-mode entries scan
(ORDER BY vec_dist LIMIT 100 + a predicate on an INCLUDE column). shrinkPopulatedVecs
shrinks every vector the reader filled and skips the ones it did not. Not vector-specific —
it fixes the shape for any caller reaching the filter with a partially materialized batch.

3. Six GPU cases failing on show create table

SHOW CREATE TABLE quotes INCLUDE column names (INCLUDE (`c_i32`, …), see
indexIncludeColumnsToString), but six gpu_cases still carried the unquoted form — 16
failures across cagra/ivfpq filter, filter_quant, postfilter. Regenerated; the diff
is quoting plus column metadata, no result value changes. Pre-existing on main (clean
HEAD with MO_CL_CUDA=1 fails the identical 16); they survived because gpu_cases need a
GPU runner.
intact, with its limit, and nothing rewrites it.

Fix — a second, SORT-anchored entry point. applyIndicesForSort /
buildVectorSortContextFromSort fire for a Top-K whose parent is not a project.
applyIndices already repoints parents from the returned node id, so one mechanism covers
outer sort, join input, and any future consumer shape:

  • requires sortNode.Limit != nil, so a bare outer ORDER BY is never mistaken for the
    Top-K and the user's ordering is never discarded;
  • spliceVectorRewrite — with a project it repoints projNode.Children[0] and returns the
    same node id as before; without one it returns the new subtree root and publishes the
    column remap into idxColMap, which applyIndices applies to every ancestor on the way
    back out;
  • the plugin dispatch loop is now shared by both anchors, so they cannot drift on which
    algorithms they try; hnsw/cagra/ivfpq receive idxColMap (previously ivfflat only).

Two things the anchor has to get right, both found during self-review and both fixed
here:

  • applyIndices walks children before the node, so the sort anchor would otherwise claim
    the classic PROJECT → SORT → SCAN shape. With no project to read column requirements
    from, ivfflat disables the index-only scan and every plain ORDER BY dist LIMIT k
    grows a join back to the base table
    . collectSpecialIndexGuards now marks
    project-anchored sorts and applyIndicesForSort yields to them.
  • A Top-K reached only through the sort anchor still owns its TABLE_SCAN. Without a
    guard entry, applyIndicesForFilters rewrites that scan into a secondary-index join
    first and the ANN rewrite then finds a JOIN instead of a scan — so it never fires.
    detectVectorGuardFromSort reserves the scan. Without this the fix only worked for
    filter-free inner queries.

Hardening carried in the same commit (each traced to a concrete failure):

Change Why
Bounds-check ORDER BY ColPos in buildVectorSortContextFrom and pushdownVectorIndexTopToTableScan `select
count(*) from () t` prunes the derived projection to length 0 while the sort keeps its pre-pruning ColPos →
panic
Decline a sort-anchored rewrite when idxColMap is nil writing to a nil map panics; dropping the remap would
splice a tree whose ancestors reference a replaced project
Remap the child's pass-through columns when ORDER BY carries the distance call directly the child is detached
either way, so its columns must not dangle
Skip non-column entries in replaceColumnsForColRefList vector remaps now reach every ancestor, including nodes
with UpdateCtxList; a function-valued remap hit an unchecked type assertion

2. table_scan panic on a partially materialized batch

evalFilter called bat.Shrink(sels), which walks every vector assuming each holds
bat.RowCount() rows. The vector-TopN pushdown breaks that:
blockio.materializeVectorTopNRows loads only the selected rows and then
CleanOnlyData()s the ORDER BY vector column itself — its values were already consumed to
compute the distances — leaving that column at 0 rows among siblings holding
len(selectRows). The reader still presents the batch as fully loaded
(loadedColumns=nil whenever r.orderByLimit != nil), so shrinking by row index indexed
the empty column:

internal error: panic runtime error: index out of range [4] with length 0
  vector.shrinkFixed → vector.Shrink → batch.Shrink → table_scan.evalFilter

Reproduced deterministically on an IVF-FLAT include-mode entries scan
(ORDER BY vec_dist LIMIT 100 + a predicate on an INCLUDE column). shrinkPopulatedVecs
shrinks every vector the reader filled and skips the ones it did not. Not vector-specific —
it fixes the shape for any caller reaching the filter with a partially materialized batch.

3. Six GPU cases failing on show create table

SHOW CREATE TABLE quotes INCLUDE column names (INCLUDE (`c_i32`, …), see
indexIncludeColumnsToString), but six gpu_cases still carried the unquoted form — 16
failures across cagra/ivfpq filter, filter_quant, postfilter. Regenerated; the diff
is quoting plus column metadata, no result value changes. Pre-existing on main (clean
HEAD with MO_CL_CUDA=1 fails the identical 16); they survived because gpu_cases need a
GPU runner.

Tests

Unit — anchor arbitration (the index-only regression), sort-anchored context
construction, the pruned-projection guard, the nil-idxColMap decline, both splice
behaviours, and three shrinkPopulatedVecs cases (the exact populated/emptied/populated
batch, the select-everything no-op, RowCount()==0).

BVT — all four algorithms, each asserting the index is actually resolved in the plan:

Case Marker asserted
cases/vector/vector_ivf_topk_consumers Table Function on ivf_search
cases/vector/vector_hnsw_topk_consumers Table Function on hnsw_search
gpu_cases/vector/vector_cagra_topk_consumers Table Function on cagra_search
gpu_cases/vector/vector_ivfpq_topk_consumers Table Function on ivfpq_search

Shapes covered: outer ORDER BY, ORDER BY … DESC (a naive "skip the outer sort" fix
would silently reverse this), ordering by a non-metric column, LEFT and INNER join
consumers, count(*) over a Top-K plain and filtered, both consumers stacked, sibling
Top-Ks sharing idxColMap, LIMIT … OFFSET inside the CTE, and the filtered inner Top-K
with a competing secondary index (the guard fix — no other case has a filtered inner
query). Every row set is cross-checked against the same Top-K computed with mode=force,
which disables the index, so a plan that reaches the index but returns wrong rows still
fails. pre / post / auto are exercised separately, since force is index-free by
definition and would otherwise be the only other mode tested.

The IVFFLAT case additionally asserts the absence of a base Table Scan on the classic
shape — that assertion is what catches the index-only regression, and it was verified
load-bearing by pointing it at a string the plan does contain
(Regex pattern 'Sort Key' found but should not be present).

Results (CUDA build, suite started only after ISCP-Task Start):

Suite Result
gpu_cases/vector 891 / 891, 0 failed
cases/vector 1589, 1 failed — pre-existing (below)
vector_ivf_topk_consumers 46 / 46
vector_hnsw_topk_consumers 37 / 37
pkg/sql/plan, table_scan, readutil ok, except 2 pre-existing (below)

Notes for reviewers

  • Index-only scan is intentionally disabled for sort-anchored rewrites. With no project
    above, requiredCols cannot see what the consumers reference, so dropping the base scan
    could drop a column still in use. The ANN rewrite is the win; index-only is an extra, and
    the classic shape keeps it.
  • Not covered: the vector-provider join under a consumer. buildVectorSortContextThroughJoin
    is reachable only from the project anchor, so in principle a consumer hides it too — but no
    SQL shape I could construct produces that context (it needs a single-row, NOT NULL, limit-1
    provider join simultaneously; from t, probe p where p.pid = 1 and scalar subqueries with
    and without NOT NULL all fail to reach it, and the baseline without a consumer does not
    use the index either). A fallback would be unverifiable, so it is deliberately left out.

cpegeric and others added 3 commits August 12, 2026 16:35
SHOW CREATE TABLE quotes INCLUDE column names -- indexIncludeColumnsToString
emits `c_i32` rather than c_i32 (build_show_util.go) -- but these six GPU
cases still carried the unquoted form, so every `show create table t;` in
them failed on a real GPU run: 16 failures across cagra/ivfpq filter,
filter_quant and postfilter.

The server output is the correct one, so this only regenerates the
expectations. The diff is the quoting plus refreshed column metadata; no
result value changes.

Pre-existing on main: clean HEAD with MO_CL_CUDA=1 fails the identical 16.
They survived because gpu_cases need a GPU runner to execute.

Verified: gpu_cases/vector 891/891, 0 failed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
evalFilter called bat.Shrink(sels) on the eager path, which walks every
vector and assumes each holds bat.RowCount() rows. The vector-TopN pushdown
breaks that: blockio.materializeVectorTopNRows loads only the rows the
in-block Top-K selected and then CleanOnlyData()s the ORDER BY vector column
itself (outputBat.Vecs[topColPos]) -- its values were already consumed to
compute the distances -- so that column sits at 0 rows among siblings holding
len(selectRows).

The reader still presents the batch as fully loaded: readutil/reader.go
passes loadedColumns=nil whenever r.orderByLimit != nil, which is also what
disables late materialization. Shrinking by row index then indexed the empty
column and panicked with "index out of range [N] with length 0", killing the
query. Reproduced deterministically on an IVF-FLAT include-mode entries scan
(ORDER BY vec_dist LIMIT 100 with a predicate on an INCLUDE column).

shrinkPopulatedVecs shrinks every vector the reader did fill and skips the
ones it did not: an empty vector has no rows to realign, and shrinking it is
precisely the crash. Not vector-index specific -- it fixes the shape for any
caller that reaches the filter with a partially materialized batch.

Tests cover the exact batch layout (populated / emptied / populated), the
select-everything no-op, and RowCount()==0.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…atrixorigin#25967, matrixorigin#25974)

An outer ORDER BY (matrixorigin#25967) or a relational JOIN (matrixorigin#25974) over a vector Top-K
disabled the IVFFLAT/HNSW/CAGRA/IVFPQ rewrite: results stayed correct, but the
plan silently fell back to a full scan with an exact sort, which is a large
regression on real vector tables and invisible from the result set.

The rewrite was anchored at a PROJECT whose DIRECT child is the Top-K SORT, so
any consumer between them hid it, and applyIndices dispatched on
TABLE_SCAN/JOIN/PROJECT but never SORT. Add a SORT-anchored entry point:

  - applyIndicesForSort / buildVectorSortContextFromSort, requiring
    sortNode.Limit != nil so a bare outer ORDER BY is never mistaken for the
    Top-K and its ordering is never discarded;
  - spliceVectorRewrite: with a project it repoints projNode.Children[0] and
    returns the same node id as before; without one it returns the new subtree
    root (applyIndices repoints the parent) and publishes the column remap into
    idxColMap, which applyIndices applies to every ancestor on the way out;
  - the plugin dispatch loop is shared by both anchors so they cannot drift on
    which algorithms they try; hnsw/cagra/ivfpq now receive idxColMap.

Two things the anchor has to get right. applyIndices walks children first, so
the sort anchor would otherwise claim the classic PROJECT -> SORT -> SCAN shape
and, having no project to read column requirements from, disable the index-only
scan -- every plain Top-K would grow a join back to the base table.
collectSpecialIndexGuards now marks project-anchored sorts and applyIndicesForSort
yields to them. And a Top-K reached only through the sort anchor still owns its
TABLE_SCAN: without a guard entry applyIndicesForFilters rewrites that scan into
a secondary-index join first, and the ANN rewrite then finds a JOIN instead of a
scan and never fires -- so detectVectorGuardFromSort reserves it. Without that,
the fix only worked for filter-free inner queries.

Also hardened on the way through: bounds-check the ORDER BY ColPos against the
child projection in buildVectorSortContextFrom and in
pushdownVectorIndexTopToTableScan (`select count(*) from (<top-k>) t` prunes the
projection to nothing while the sort keeps its pre-pruning ColPos, which
panicked); decline a sort-anchored rewrite when idxColMap is nil rather than
writing to a nil map; remap the child's pass-through columns even when the
ORDER BY carries the distance call directly; and skip non-column entries in
replaceColumnsForColRefList instead of an unchecked type assertion, now that
vector remaps reach every ancestor including nodes with UpdateCtxList.

Tests: unit coverage for the anchor arbitration (the index-only regression),
the sort-anchored context, the pruned-projection guard, the nil-map decline and
both splice behaviours. BVT cases for all four algorithms assert the index is
resolved (ivf_search / hnsw_search / cagra_search / ivfpq_search) across outer
ORDER BY, DESC, non-metric ordering, LEFT/INNER join, count(*) plain and
filtered, sibling Top-Ks sharing idxColMap, LIMIT+OFFSET, and pre/post/auto
modes -- each cross-checked against the same Top-K computed with mode=force,
which disables the index. The IVFFLAT case additionally asserts the ABSENCE of
a base Table Scan on the classic shape, so the index-only regression cannot
return unnoticed.

Verified on a CUDA build: gpu_cases/vector 891/891; cases/vector 1589 with one
pre-existing failure (vector_ivf_retry, identical on clean HEAD).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@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 →

`select l2_distance(v,'[1,1,1,1]') as d from t order by l2_distance(v,'[1,1,1,1]')
limit 3` panics the CN on any table with an IVFFLAT / HNSW / CAGRA / IVF-PQ
index:

  internal error: panic interface conversion: interface {} is int64, not float64
    vector.AppendAny (vector.go:6026)
    table_function.(*ivfSearchState).call (ivf_search.go:162)

The search table functions declare pkid / score (plus IVFFLAT's INCLUDE
columns) and then write to hard-coded slots -- Vecs[0], Vecs[1], Vecs[2+i] --
but createResultBatch sizes the batch from TableFunction.Attrs, i.e. the columns
the PLANNER kept. A score-only SELECT reads no pk, so pkid is pruned, Vecs[0]
becomes the float64 score, and appending the int64 pk into it kills the query.
Nothing enforced the layout the runtime assumed.

Resolve the output slots by name instead, and treat an absent column as "the
planner does not want it" rather than writing it elsewhere. All four algorithms
had the same assumption; CAGRA and IVF-PQ are GPU-only, so a partial fix would
have left two copies uncovered by CPU CI.

requestedIvfIncludeColumns had the matching bug: it scanned attrs[2:] and bailed
on len(attrs) <= 2, so pruning pkid or score ahead of the INCLUDE columns would
drop or mis-map them. It now matches by prefix anywhere in Attrs.

Pre-existing on main: reproduced on 6b81a6d with no other change present.
Found while investigating why extending index-only scan to sort-anchored Top-K
rewrites crashed -- that extension only routed more shapes into this contract.

Tests: unit coverage for the slot lookup (pkid pruned must not alias onto the
score slot; score pruned shifts an INCLUDE column) and for position-independent
INCLUDE discovery, plus a BVT block in all four algorithms' consumer cases
asserting the pruned-pk query keeps using the index and returns the right rows.

Verified: gpu_cases/vector 896/896; cases/vector 1595 with the two pre-existing
vector_ivf_retry failures.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
cpegeric and others added 2 commits August 14, 2026 13:29
…g one clustering

Two cases in vector_ivf_retry asserted outcomes that ivfflat clustering decides
at random, so the suite failed or passed depending on how k-means happened to
partition that build. Both failures reproduce on main and on this branch; the
"1 vs 2 failures" difference between branches was luck, not a code fix.

Test 5.4 -- `filter_col = 0 ... limit 5 by rank` -- ran with probe_limit = 1,
set a few lines earlier to force low recall for the fallback tests around it.
The 20 matching rows lie on one tight line and k-means splits them across the 5
lists differently from build to build, so the single probed cluster held 4 rows
in some runs and 5 in others; the recorded expectation of 4 was one of those.
The case is about "at least limit rows if available", not about recall, so it
now probes every cluster and restores probe_limit = 1 for the test below it.

Tests E.2 / E.3 on t_edge ordered a THREE-WAY TIE: the fixture used three unit
vectors, so every distance from '[0,0,0]' was exactly 1.0 and `limit 2` had no
deterministic answer -- (2,1) and (1,3) were equally correct. The vectors now
have distinct norms, giving distances 1, 2 and 3.

vector suite 1542/1544, 0 failed, three consecutive runs.

Co-Authored-By: Claude Opus 5 <[email protected]>
(cherry picked from commit f8a7ff2)
@cpegeric

Copy link
Copy Markdown
Contributor Author

fixed

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

Request changes: the SORT-anchored rewrite has a correctness hole.

  1. [P1] Preserve the evaluation boundary for volatile/realtime child projections (pkg/sql/plan/apply_indices_vector.go:711-723)

The new SORT anchor removes the PROJECT below the Top-K and publishes every non-distance output as its raw expression in idxColMap. Each ancestor then calls replaceColumnsForNode, which deep-copies that expression at every reference.

That is unsafe for expressions such as rand(), uuid(), and now(). The optimizer already treats these specially in exprCanRemoveProject and deliberately refuses to inline their PROJECT. This new path bypasses that invariant.

For example:

WITH knn AS (
  SELECT id,
         rand() AS r,
         l2_distance(embedding, '[1,2,3]') AS dist
  FROM items
  ORDER BY dist
  LIMIT 10
)
SELECT k.id, k.r
FROM knn AS k
JOIN thresholds AS t ON k.r < t.value;

Before the rewrite, r is evaluated once in the child PROJECT and both consumers read the same value. After this rewrite, the JOIN predicate and the outer projection each receive an independent copy of rand(); the returned r can therefore disagree with the value that admitted the row. Moving evaluation above the JOIN can also change evaluation multiplicity.

Please preserve a PROJECT boundary around non-removable expressions, or conservatively decline the SORT-anchored ANN rewrite when the detached child projection contains CannotFold / realtime expressions. Add a plan-level regression that proves one volatile child output is not duplicated across multiple ancestors.

  1. [P2] Resolve projected TVF slots once, outside the emitted-row loop (pkg/sql/colexec/table_function/ivf_search.go:165-172, plus the HNSW/CAGRA/IVF-PQ counterparts)

vectorSearchAttrPos is a linear string scan, but it is currently called for every emitted row (and once per INCLUDE column per row for IVF-FLAT). With an 8192-row batch and the supported INCLUDE width this performs avoidable repeated name scans in the vector-search output hot path. The helper comment itself says “Resolve ... once.” Cache the pk/score/include positions when the result layout is initialized, then use integer slots in call.

Validation on exact head c3ef8ee6751297aa645664ad1ebf25ca319f3230:

  • full tests passed for ./pkg/sql/plan, ./pkg/sql/colexec/table_scan, and ./pkg/sql/colexec/table_function
  • focused race tests passed
  • list/build/vet passed
  • a temporary white-box counterexample confirmed that one volatile child output is copied into independently evaluated JOIN and outer-project expressions

@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 review of exact head c3ef8ee6751297aa645664ad1ebf25ca319f3230: REQUEST_CHANGES.

[P1] Preserve the child PROJECT evaluation boundary for volatile/realtime expressions in the new SORT-anchored rewrite. I independently confirmed the current vectorRemapForChildProject/ spliceVectorRewrite path detaches the project below Top-K and publishes each non-distance projection expression through idxColMap. applyIndices then substitutes that expression independently into every ancestor that references the projected column. This bypasses the planner's existing exprCanRemoveProject rule, which explicitly keeps functions with CannotFold or IsRealTimeRelated at their project boundary.

For a Top-K CTE projecting rand() AS r, with r used both by an ancestor JOIN predicate and the outer result projection, the rewrite creates separate rand() evaluations. The returned value can differ from the value that admitted the row, and evaluation multiplicity can change across join rows. Please retain a PROJECT for non-removable expressions or conservatively decline the sort-anchored ANN rewrite when the detached project contains them, with a plan regression covering one volatile output referenced by multiple ancestors.

[P2] Resolve vector-search output slots once per result layout, not inside the emitted-row loop. vectorSearchAttrPos linearly scans batch.Attrs for pk/score on every row, and IVF-FLAT repeats it for every INCLUDE column per row. Cache those integer positions during layout/result-batch initialization for all four vector table functions.

Validation on this exact head: full ./pkg/sql/plan, ./pkg/sql/colexec/table_scan, and ./pkg/sql/colexec/table_function pass with the required CGo/thirdparties setup; git diff --check is clean. The volatile-expression lifecycle gap remains blocking.

…e vector-search output slots

Two review items.

[P1] The SORT-anchored rewrite detaches the PROJECT below the Top-K and republishes
each of its non-distance expressions through idxColMap. applyIndices then
substitutes that expression into EVERY ancestor referencing the column, deep-copying
it per reference. Sound for a column reference; wrong for anything evaluated:

  with knn as (select id, rand() as r, l2_distance(v,'[…]') as d
               from t order by d limit 10)
  select k.id, k.r from knn k join thresholds x on k.r < x.value

would give the JOIN predicate and the outer projection their own rand(), so the r
returned can differ from the r the row was admitted on, and moving the evaluation
above a JOIN changes how many times it runs. removeSimpleProjections already
refuses to inline such a PROJECT; this rewrite must not route around that rule.

The context builder now declines when the child project holds an expression
exprCanRemoveProject rejects -- reusing the planner's own predicate rather than
restating it, so the two cannot drift. Scoped to the SORT anchor: the PROJECT
anchor applies its remap to that one node (spliceVectorRewrite), so the expression
is still evaluated exactly once and keeps the optimization. The distance entry is
exempt either way -- it becomes a single score ColRef, not a copy per ancestor.

[P2] vectorSearchAttrPos linearly scanned batch.Attrs for pkid/score on every
emitted row, and IVF-FLAT scanned again per INCLUDE column per row -- tens of
thousands of name comparisons per 8192-row batch in the vector-search output path.
The layout is fixed once createResultBatch builds it, so resolveVectorSearchSlots
now caches pk/score (and one slot per INCLUDE column) at that point and the emit
loops index integers. Applied to all four: IVF-FLAT, HNSW, IVF-PQ, CAGRA.

Also fixes TestIvfpqSearch, which has been failing on main since the quantization
guard landed (matrixorigin#25095): its IndexTableConfig omits parttype, so KeyPartType
defaulted to 0 and the TVF rejected the vecf32 query as a base-type mismatch. The
file is //go:build gpu, so CI never compiles it and nobody saw it go red -- the
same false-green shape as the mo-cgo-test finding.

Tests: a plan regression proving the rewrite declines for rand()/uuid() in the
child project while the project anchor still rewrites and the distance entry stays
exempt; slot-resolution tests covering a pruned pkid, an absent INCLUDE column and
an empty layout.

pkg/sql/plan, table_scan and table_function (incl. -race and gpu tags) all pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
@cpegeric

Copy link
Copy Markdown
Contributor Author

fixed

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

Reviewed exact head b206810. The SORT-anchored rewrite now declines to detach child PROJECTs containing non-removable/volatile expressions, preserving evaluation boundaries, while the new vector-search slot layout resolves pruned pk/score/INCLUDE positions once per batch. Exact-head focused plan/table-function/table-scan tests pass and CI is green.

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

Deep-reviewed exact head b206810e3fa34660a3b2a409975757d2355fffac: APPROVE. The latest revision closes both prior blockers: the SORT-anchored rewrite now reuses exprCanRemoveProject and declines to detach volatile/realtime child projections, preserving their single-evaluation boundary; vector-search pk/score/INCLUDE slots are resolved once per fixed result layout rather than scanned per emitted row. I also traced the sort/project anchor arbitration, scan guards, remap propagation through ancestors, IVF index-only boundary, pagination/offset handling, partial-vector shrink path, plugin dispatch for all four ANN algorithms, and DML ColRef-only metadata paths; I found no remaining reachable correctness or lifecycle blocker. Exact-head full tests pass for ./pkg/sql/plan, ./pkg/sql/colexec/table_scan, and ./pkg/sql/colexec/table_function; CI is green.

@XuPeng-SH
XuPeng-SH requested a review from aptend August 15, 2026 10:06

This branch was previously deployed

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

Labels

kind/bug Something isn't working size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants