Repository navigation
feat(vector,remaplist): Permute, UnionRowsFrom and InvertInto on the gather kernel (#33181 PR 9 + 10 + 11) - #33333
Conversation
…igin#33181 PR 9) Vector.Permute(rows, mp) and Batch.Permute apply a sort's permutation in place with the gather kernel's value loop and word-wise NULL gather. They replace Shuffle and Batch.Shuffle in order, mergeorder, top, mergetop, window, s3util, TN mergesort, logtail replay, readutil and publication; all callers already had []int64 rows, so pkg/sort is unchanged. Vector.PermuteWithScratch replaces ShuffleWithBuf for the TN merge sort: it gathers into a caller-kept Go-heap scratch and copies back, so the column is not reallocated. A scratch that overlaps the vector's data is replaced instead of kept. The identity permutation of the full length is a no-op. The old per-type Shuffle switches and shuffleWithSortedProof are gone. Permute matches Shuffle on random permutations; already-sorted input drops from 2.7-4.3 us to 1.1 us per 8192 rows; sort and top-k operator benchmarks are flat. An untyped (ANY) vector keeps Shuffle's rules: only its NULLs and length follow the rows, a constant takes the new length, and one holding values is rejected. Batch.Permute rejects a selected batch. The type-ops table loses its shuffle entries, and the ANY, selection and type-ops tests move to Permute. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rom (matrixorigin#33181 PR 10) Vector.UnionRowsFrom(srcs, rows, mp) gathers row rows[i] of srcs[i]. It takes one pass per column when every source is a flat vector of the destination's type: NULLs a word at a time, the fixed-width loop per payload width, varlena copied into an area grown once. Other sources fall back to UnionOne per row. A row outside its flat source is an error and the destination is unchanged. The hash join decodes build ordinals into (batch, row) once per output chunk and uses it for every build column, varlena included. TryUnionFlatFixedRows, FixedSourceRow and the run-wise varlena fallback are removed. BenchmarkHashJoinDuplicateFanout (8192 output rows over 4 build batches), pinned, min of 6 interleaved runs: int64 78.9 -> 69.5 us, decimal128 109.1 -> 81.2 us, varchar inline 134.8 -> 115.3 us, varchar 48 B 287.2 -> 255.3 us. Other hash-join benchmarks unchanged. The gather's unchecked per-row reads (a fixed value, a varlena header) live in tools.go, which may import unsafe; gather_sources.go does not. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…xorigin#33181 PR 11) List.InvertInto(srcRows, dst) writes the old row -> new row map of a forward list into a caller-owned List, -1 for source rows the list leaves out; a repeated or out-of-range row is an error. MergeAObj and ReshapeBatches used to copy each kept row with UnionOne per column and fill a []int map by hand. Now the heap (or the scan in input order) only records the kept rows as global row ids; the columns are gathered one at a time per output block with UnionRowsFrom, and InvertInto derives the map. The map comes from the merge's pool and is freed by its release function; it is []int64, and so is UpdateMappingAfterMerge's argument. A heap merge with more rows than the layout now returns an error instead of indexing past the blocks. AddSortPhaseMapping is unchanged: it inverts straight into the transfer slab. 4 x 8192 rows, int64 key + int64, decimal128, varchar, 10% deleted, pinned, min of 5 interleaved runs: MergeAObj 1864 -> 1020 us, ReshapeBatches 1282 -> 632 us, Go heap per merge 265 KB -> 134 KB. Rebased onto PR 10 after upstream removed the TAE vector wrapper: the gather takes each batch's column directly, and the tests build columns with containers.MakeVector. Co-Authored-By: Claude Opus 5.5 <[email protected]>
0c10004 to
d196b27
Compare
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? |
|
Queue requested — the merge queue status continues in this comment ↓. |
🛑 Queue command cancelledTick the box to add this pull request to the merge queue (same as
|
There was a problem hiding this comment.
🟡 Changes recommended
Active findings identify a critical scratch-buffer aliasing flaw that can corrupt live rows or retain released memory, plus cancellation gaps during materialization and quadratic duplicate detection in wide batches.
3 open issues
What changed in this PR
This PR completes steps 9–11 of the row-selection plan for #33181, consolidating sorting, hash-join gathers, and TN merge materialization around shared gather kernels.
Changes:
- Replaces
ShuffleAPIs withPermuteand reusable-scratch permutation across callers. - Adds
UnionRowsFromfor multi-source gathers, including variable-length payloads. - Adds
InvertIntoand pooledint64transfer maps for TN merges, with regression tests and benchmarks.
| File | Description |
|---|---|
pkg/vm/engine/tae/tables/jobs/flushTableTail.go |
Uses int64 merge mappings. |
pkg/vm/engine/tae/mergesort/task.go |
Accepts int64 transfer mappings. |
pkg/vm/engine/tae/mergesort/mergesort_test.go |
Updates expected mapping types. |
pkg/vm/engine/tae/mergesort/merge_gather.go |
Adds chunked column gathers and inverse maps. |
pkg/vm/engine/tae/mergesort/merge_gather_test.go |
Tests merge values, mappings, layouts, and errors. |
pkg/vm/engine/tae/mergesort/merge_bench_test.go |
Benchmarks merge and reshape gathers. |
pkg/vm/engine/tae/mergesort/func.go |
Uses permutation and gather-based reshaping. |
pkg/vm/engine/tae/mergesort/aobj_merger.go |
Separates merge ordering from payload gathering. |
pkg/vm/engine/tae/blockio/read_test.go |
Migrates empty-selection regression to Permute. |
pkg/vm/engine/readutil/reader.go |
Uses batch permutation after selection. |
pkg/vm/engine/disttae/logtailreplay/change_handle.go |
Migrates replay sorting to Permute. |
pkg/sql/plan/function/shuffle_between_regression_test.go |
Migrates sorted-consumer regressions. |
pkg/sql/plan/function/func_unary_test.go |
Migrates cardinality regression. |
pkg/sql/plan/function/func_builtin_jq_test.go |
Migrates constant-result regression. |
pkg/sql/plan/function/base_template_null_test.go |
Migrates constant-NULL cardinality regression. |
pkg/sql/colexec/window/window.go |
Permutes window inputs and auxiliary vectors. |
pkg/sql/colexec/top/top.go |
Uses permutation for top results. |
pkg/sql/colexec/s3util.go |
Uses permutation for key sorting. |
pkg/sql/colexec/order/order.go |
Migrates sorted-run permutation and related comments. |
pkg/sql/colexec/mergetop/top.go |
Uses permutation for merged top results. |
pkg/sql/colexec/mergeorder/batch_sort.go |
Permutes sorted chunks and ordering vectors. |
pkg/sql/colexec/join_util_test.go |
Migrates reordered-varlen regression. |
pkg/sql/colexec/hashjoin/join.go |
Uses multi-source build-side gathers. |
pkg/sql/colexec/hashjoin/gather_fanout_bench_test.go |
Benchmarks duplicate-key join gathers. |
pkg/publication/filter_object.go |
Permutes rewritten tombstone columns. |
pkg/publication/filter_object_batch.go |
Permutes columns before object creation. |
pkg/objectio/mergeutil/types.go |
Uses reusable-scratch permutation. |
pkg/objectio/ioutil/sinker_bounded_test.go |
Migrates sorting-accounting regression. |
pkg/container/vector/vector.go |
Removes superseded shuffle and gather implementations. |
pkg/container/vector/vector_test.go |
Migrates vector movement regressions. |
pkg/container/vector/vecblock_test.go |
Migrates block-scaled vector regression. |
pkg/container/vector/union_test.go |
Tests multi-source gathers and admission failures. |
pkg/container/vector/type_ops.go |
Removes shuffle dispatch entries. |
pkg/container/vector/type_ops_test.go |
Removes obsolete shuffle dispatch checks. |
pkg/container/vector/type_ops_legacy_test.go |
Removes legacy shuffle implementations. |
pkg/container/vector/tools.go |
Adds unchecked reads for validated gather rows. |
pkg/container/vector/shuffle_sorted_test.go |
Tests permutation ordering, scratch reuse, and aliases. |
pkg/container/vector/permute_any_null_test.go |
Migrates untyped-NULL selection regressions. |
pkg/container/vector/lowprec_test.go |
Migrates low-precision movement tests. |
pkg/container/vector/gather.go |
Implements permutation APIs on shared gather loops. |
pkg/container/vector/gather_test.go |
Compares permutations with scalar gathers. |
pkg/container/vector/gather_sources.go |
Implements multi-source row gathering. |
pkg/container/vector/gather_sources_test.go |
Tests source combinations, NULLs, and errors. |
pkg/container/vector/gather_permute_bench_test.go |
Benchmarks both permutation variants. |
pkg/container/batch/selection_test.go |
Checks selected-batch rejection for Permute. |
pkg/container/batch/batch.go |
Adds batch permutation with shared-vector handling. |
pkg/container/batch/batch_test.go |
Tests shared columns and empty permutations. |
pkg/common/remaplist/invert.go |
Adds inverse mapping into caller-owned storage. |
pkg/common/remaplist/invert_test.go |
Tests inversion, reuse, and invalid inputs. |
docs/design/20261124-row-selection-bitmap-remaplist.md |
Documents steps 9–11 and benchmark results. |
Review effort: Balanced
|
mo-bot review · Commit: "interrupted" |
- PermuteWithScratch checks the scratch against the full capacity of both buffers, so a scratch in the vector's spare capacity is replaced rather than kept (later appends make that memory live; Free releases it). - Batch.Permute finds repeated columns with a set above 16 columns, so wide batches stay linear in the width. - The TN merge gather checks the context before each chunk and releases its partial output when cancelled; MergeAObj passes its context. Co-Authored-By: Claude Opus 5.5 <[email protected]>
🛑 The queue request has been cancelled: new commits were pushedDetails@fengttt pushed to this pull request after |
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
I revalidated the PR at the new head e1aa863 (50 files, +1808/-826 against origin/main) and reviewed the increment since d196b27, which is the author's fix commit 473399e plus a merge of main. The fix commit is correct: PermuteWithScratch now compares the scratch against the full backing capacity of both buffers, so a scratch sitting in the vector's spare capacity is replaced instead of retained; Batch.Permute keeps a 16-column prefix scan and switches to a pointer set above that width, keeping the repeated-column check linear; mergeOrder.gather now takes the ctx, checks it before each chunk, and releases its partial output on cancellation, with MergeAObj passing its context and ReshapeBatches unchanged in its context-less form. The merged main-side commits (SIMD min/max utilities, thirdparties build files) do not touch the PR's gather kernels, and none of them appears in the net diff against origin/main. The rest of my earlier analysis still holds at this head: Permute/PermuteWithScratch reproduce Shuffle's value and NULL movement, sorted-flag rule, constant and ANY rules, pool checks and error atomicity; UnionRowsFrom matches UnionOne for constants, windows, self-aliasing destinations, type mismatches and out-of-range rows; MergeAObj and ReshapeBatches keep the old mapping contract (global row id to output row, -1 for dropped) and block-creation parity, and return an error where the previous code index-panicked on a layout too small for the kept rows; the []int64 mapping is threaded consistently through the merger signatures, UpdateMappingAfterMerge and flushTableTail. Testability limitation, confirmed at this head: a fresh go list -deps -test -e -json probe (exit 0, 456 packages, all three test variants present, zero dependency errors) still shows pkg/common/malloc compiling jemalloc_allocator.go with -I/thirdparties/install/include, and thirdparties/install does not exist in this checkout, so the prior go test -v runs of ./pkg/container/vector, ./pkg/container/batch and ./pkg/common/remaplist failed at build with "fatal error: 'jemalloc.h' file not found" (exit 1 each) and CGO_ENABLED=0 fails with undefined malloc.SimpleCAllocator; per policy I did not build the make cgo or thirdparties targets, so no tests executed and conclusions come from static analysis. The three other reviewers' issues on this PR were addressed by the author in 473399e, now part of the reviewed head; my two findings below remain non-blocking.
P2 - UnionRowsFrom fast path lost TryUnionFlatFixedRows' zero-width guard and panics on flat all-NULL T_any vectors (pkg/container/vector/gather_sources.go:116)
The removed TryUnionFlatFixedRows (pkg/container/vector/vector.go, deleted in this PR) refused destinations with v.class != FLAT and size <= 0, so its callers appended all-NULL T_any rows row by row through UnionOne's null path. UnionRowsFrom validates its sources (class, type, alias to v, FLAT row range) and falls back to unionRowsOneByOne for them, but it checks neither the destination's class nor the payload width, and T_any reaches the fixed path: for types.T_any, TypeSize() is 0 and IsVarlen() is false (FixedLength 0). Line 117's target v.data[oldLen*width : (oldLen+len(rows))width] then computes v.data[oldLen:oldLen] on a flat T_any destination whose data is nil, which panics for oldLen > 0, and the default branch's copy(target[iwidth:(i+1)width], w.data[rwidth:(r+1)*width]) computes w.data[r:r] on a nil all-NULL source, which panics for any r >= 1 once such a source holds more than one row. Permute and ShrinkByRows show the intended convention for this family: they special-case types.T_any at entry. Both in-tree callers (hash-join build projection in pkg/sql/colexec/hashjoin/join.go and the TN merge columns in pkg/vm/engine/tae/mergesort/merge_gather.go) pass concrete typed columns, so the defect is latent in the exported API rather than reachable through current callers. Routing Oid == T_any (or width == 0) to unionRowsOneByOne restores the replaced contract and makes flat all-NULL ANY gathers behave like UnionOne, matching the vector package's existing ANY support.
P2 - Comments still document the removed Shuffle entry point (pkg/container/vector/type_ops.go:281)
The comment above typeOpsUnsupported still says "Shrink, ShrinkByMask and Shuffle panic (Shrink, ShrinkByMask and Shuffle first handle an all-NULL T_any vector themselves)". This PR deletes Vector.Shuffle and its typeOps.shuffle/shuffleWithBuf fields; Permute dispatches by payload width in gather.go and never consults typeOps, so the sentence names a removed API and attributes to it a T_any pre-check that now lives in Permute and PermuteWithScratch. Similarly, pkg/container/batch/batch_set_test.go:488 introduces BenchmarkBatchSetAppendSels with the comment "Shuffle's pattern: small selections into a long tail, recycling each full batch as the next reuse buffer", whose name reference is gone. Rewording both to Permute (or to the row-list gather generally) keeps the removed-API references accurate.


What type of PR is this?
Which issue(s) this PR fixes:
issue #33181
What this PR does / why we need it:
PRs 9, 10 and 11 of the row-selection plan in
docs/design/20261124-row-selection-bitmap-remaplist.md, as three commits on current main (PRs 1–8 have merged). #33299 (PR 9) and #33329 (PRs 9 + 10) are closed and folded in here.cd6e5f6e7c): sorts apply their permutation with the gather kernel, andShuffle/ShuffleWithBufgo away.aa315ff03e): the hash join's build-side gathers use one many-source gather kernel, andTryUnionFlatFixedRowsgoes away.d196b27585): the TN merge gathers columns withUnionRowsFrom, and its transfer map comes fromremaplist.List.InvertInto.PR 9: Permute replaces Shuffle
Vector.Permute(rows, mp)andBatch.Permutereorder in place: row i becomes old rowrows[i]. They use the gather kernel's value loop per payload width and its word-wise NULL gather. They replaceShuffle/Batch.Shufflein order, mergeorder, top, mergetop, window, s3util, TN mergesort, logtail replay, readutil and publication. Every caller already had[]int64rows, sopkg/sortand the callers' lists are unchanged.Vector.PermuteWithScratchreplacesShuffleWithBuffor the TN merge sort: it gathers into a Go-heap scratch the caller keeps and copies back, so the column is not reallocated per sort. A scratch that overlaps the vector's own data is replaced instead of kept (the old code handled that alias only for the identity permutation).Shuffle's rules (fix: handle untyped NULL vectors during selection #33058): only their NULLs and length follow the rows, a constant takes the new length, and one holding values is rejected.Batch.Permuterejects a selected batch, asBatch.Shuffledid.Shuffleswitches,shuffleWithSortedProofand the type-ops table'sshuffle/shuffleWithBufentries are deleted.Permuteis one loop per payload width for every type, so it needs no table entry.Rebase onto main (PR 9)
Shufflethrough the type-ops table (refactor(vector): dispatch vector operations through a type-ops table (#10181 steps 4, 4b) #33339) and added the ANY rules (fix: handle untyped NULL vectors during selection #33058) and the selected-batch check.Permutecarries the ANY rules and the check, and the table drops its shuffle entries; the legacy-switch comparison intype_ops_test.gono longer covers a shuffle, sincePermuteis tested againstUnionOneinstead.shuffle_any_null_test.go, nowpermute_any_null_test.go), the selected-batch test andjoin_util_test.gocallPermute/PermuteWithScratchwith their assertions unchanged.GetDownstreamVectoris gone upstream, so publication and TN mergesort callPermuteon the column directly.TestBatchPermuteusesbatch.NewWithSize.Benchmarks (PR 9)
Pinned to one core, minimum of five runs, PR 8 → PR 9 (measured before the rebase):
PermuteWithScratch), decimal128 / varcharBenchmarkTopUnaccountedResident/TopAccountedResidentBenchmarkReviewSmallVarlenTopBenchmarkMergeTopUnaccountedResidentBenchmarkOrderUnaccountedResidentBenchmarkOrder/MergeOrderUnaccountedResidentBenchmarkSortBlockColumnsThe operators are flat: the permutation is a small part of a sort.
order'sBenchmarkOrderpanics ("mismatched multi-column semantic types") before and after this change, so it is left out.Tests (PR 9)
PermuteandPermuteWithScratchagainstUnionOnefor every payload width and NULL rate, with lists that repeat, drop and add rows; sorted flag, constants, pool mismatch;Batch.Permutewith a vector shared by two columns; the scratch alias, reuse and string-metadata tests rewritten forPermuteWithScratch.vectorandbatchpass with-race;pkg/container/...,bitmap,remaplist,pkg/sql/colexec/...,publication, TNmergesortandblockio,readutil,logtailreplay,objectioandplan/functionpass.go vet ./pkg/...is clean andmake static-check-changedreports 0 issues.PR 10: UnionRowsFrom for hash-join build gathers
Vector.UnionRowsFrom(srcs, rows, mp)gathers rowrows[i]ofsrcs[i].UnionOneper row, with the same result.Unionand is unchanged.TryUnionFlatFixedRows,FixedSourceRowand the run-wise varchar fallback.unsafe: the lint allowsunsafeinvectoronly intools.goandvector.go, so the gather's two unchecked per-row reads (fixedAtUnchecked,varlenaAtUnchecked) live intools.go. Every row is checked against its source's length before them. The bounds-checkedutilcasts instead cost 10–15% on the fanout benchmark (int64 68.2 → 77.9 µs); the helpers are within 1% of inlineunsafe.Benchmarks (PR 10)
Pinned to one core, minimum of six interleaved runs, PR 9 → PR 10, measured before the rebase.
BenchmarkHashJoinDuplicateFanout(new) joins 64 probe rows against 4 × 8192 build rows with 128 matches per key: 8192 output rows, 3 build columns.HashJoinUniqueProjection, 256 rows from alternating build batches, int32 / decimal128 / varcharHashJoinSmallDuplicatePayload,HashJoinMembershipProjection,RightExistentialRepeatedKeysThe machine was shared with other load, so only the interleaved minimums are compared. TPC-H join queries have not been run yet.
Tests (PR 10)
TestUnionRowsFromMatchesUnionOne: every gather test type, several NULL rates and destination prefixes, compared withUnionOne.TestUnionRowsFromUnusualSources: window, constant NULL and self sources.TestUnionRowsFromErrors.TryUnionFlatFixedRowstests are rewritten forUnionRowsFrom, including the allocation-account admission case (the destination is unchanged on rejection).pkg/container/vectorandpkg/sql/colexec/hashjoinpass with-race;pkg/container/...,pkg/sql/colexec/...andpkg/sql/compile/...pass.go vet ./pkg/...is clean andmake static-check-changedreports 0 issues.PR 11: InvertInto for the TN merge transfer map
List.InvertInto(srcRows, dst)writes the inverse of a forward list into a list the caller owns:srcRowsentries, with -1 for every source row the list leaves out. A repeated or out-of-range source row is an error.MergeAObjandReshapeBatchesused to copy each kept row withUnionOneper column and fill a[]intmap by hand. Now:UnionRowsFrom(PR 10).InvertIntoderives the map. It is allocated from the merge's pool and freed by the merge's release function.[]int64, and so isUpdateMappingAfterMerge's argument.ReshapeBatches' rules for which blocks it creates and which rows past the layout it drops.AddSortPhaseMappinginverts straight into the transfer slab'sTransferDestPosentries, and anint64map in between would be an extra pass.Rebase (PR 11)
PR 11's commit is cherry-picked onto PR 10 (aa315ff) rather than merged, since the old branch still carried the pre-squash PR 7–10 commits.
aobj_merger.goconflicted with upstream's removal of the TAE vector wrapper (refactor(tae): remove the TAE vector wrapper; use *vector.Vector directly (#33336) #33342) inside the per-rowUnionOneloop this PR deletes; the loop stays deleted.GetDownstreamVector, no staging slice), and the new tests and benchmark build their columns withcontainers.MakeVector.Benchmarks (PR 11)
The input is 4 appendable batches of 8192 rows with an interleaving int64 sort key, an int64, a decimal128 and a varchar column, with every 10th row deleted. Pinned to one core on a quiet machine, minimum of five interleaved runs, PR 10 → PR 11, measured before the rebase:
BenchmarkMergeAObjGatherBenchmarkReshapeBatchesGatherTests (PR 11)
TestInvertInto,TestInvertIntoErrors(96.6% coverage ofremaplist).TestReshapeBatchesMappingandTestAObjMergeMappingcheck every kept row, with all its columns and NULLs, against where the map says it went. Dropped rows must map to -1. The cases cover deletes, rows past the layout, a block larger than one gather chunk, a full block making the next one, and everything deleted.TestAObjMergeErrors: too many rows for the layout, cancelled context../pkg/vm/engine/tae/...passed (32 packages).remaplistandmergesortpass with-race; TAEmergesort,tables,containersandrpc,objectioandpkg/container/...pass.go vet ./pkg/...is clean.🤖 Generated with Claude Code