Skip to content

refactor(tae): remove the TAE vector wrapper; use *vector.Vector directly (#33336) - #33342

Merged
fengttt merged 13 commits into
matrixorigin:mainfrom
fengttt:tae-remove-vector
Nov 27, 2026
Merged

fengttt merged 13 commits into
matrixorigin:mainfrom
fengttt:tae-remove-vector

Conversation

@fengttt

@fengttt fengttt commented Nov 26, 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:

issue #33336 (part of #33335)

What this PR does / why we need it:

containers.Vector was an interface implemented by a wrapper around *vector.Vector. It is now an alias for *vector.Vector, and both the wrapper and containers/vector.go are gone.

Where the wrapper's methods went

  • Vector package (general): MustAppendValue (panics; for tests and test/dump helpers), GetValue (NULL-aware, copies varlena), NullCount, and Equal, which replaces VectorEquals. The old one compared a vector with itself for decimal, TS and Rowid, so those always compared equal.
  • pool.go: ReleaseVector, and a new VectorPool.CloneWindow(src, offset, length) (Vector, error).
  • batch.go: the vector write/read framing and approxSize/vectorAllocated, unexported.
  • Everything else (Window, CloneWindow, Extend*, Compact*, PreExtend, CopyRow, Foreach, TryConvertConst, PPString, ...) is done at the call site with the vector API.

Append errors are handled

AppendValue used to panic on an error, as the wrapper's Append did, so an allocation failure crashed the TN. Production callers now use vector.AppendAny/AppendFixed/AppendBytes/AppendMultiFixed, return the error, and release what they allocated. These functions now return an error for that:

  • collectCheckpointMetadata and DataChangeToLogtailBatch;
  • anode.Scan, tableSpace.Scan/HybridScan;
  • ReserveRowsLocked;
  • CollectAppendLocked/CollectAppendSnapshotLocked and FillInCommitTSVecLocked;
  • duplicatedRowIDs.add/Merge;
  • logtail visitObject and the catalog/txnbase tuple appenders, which used to drop AppendFixed errors silently.

These still panic, on purpose:

Also fixed along the way:

  • UpdateValue's NULL path now goes through SetNull/UnsetNull, so it honors the read-only check.
  • memoryNode.Scan now checks the error from getDataWindowLocked.
  • A const-NULL vector leaked in getDataWindowLocked is now freed.
  • The unused ObjectMVCCNode.AppendTuple and GetCommitTSVecInRange are removed.
  • WW-conflict messages print the vector with common.MoVectorToString, without the old [T=...] prefix and [lent] suffix.

About 130 files change; most of the diff is mechanical.

Releasing vectors

Close() becomes ReleaseVector(v). A vector lent by a VectorPool goes back to its pool, and any other vector is freed with its own pool.

To keep pooled release safe without adding a field to Vector:

  • The pool lends a fresh vector struct holding the pooled buffers, moves the buffers back on release, and records what is lent in a package-level map.
  • A stale second release therefore finds an empty struct and can never reach the next borrower of the same buffers.
  • Release stays idempotent, as Close was. The persisted-node load path relies on that.

Behavior changes, all deliberate

  • Copy-on-write. The wrapper copied a read-only vector on its first write. The mutating functions now panic on a read-only vector instead, so a hidden copy can't go unnoticed. The full TAE suite found two sites:
    • checkpoint backup (replay.go) appends to loaded checkpoint vectors, so it now Dups a cache-backed one first, as the wrapper did;
    • TestNull1 updated a window of a mock batch.
  • Read-only vectors are now freed on release. Free drops their references and frees an owned null bitmap. The wrapper skipped Free for them, which leaked that bitmap.
  • Allocated. VectorAllocated, used by Batch.Allocated, keeps the wrapper's 0 for a read-only vector. vector.Allocated would report the capacity it references.

How the call sites were changed

A one-off tool rewrote them from compiler errors: each "X.M undefined" error located a call to rewrite. Then I reviewed by hand:

  • the former GetAllocator() calls, now MPool(), which is the same pool for an owned vector;
  • the CloneWindow calls that need a pool;
  • Allocated(), which the compiler can't flag because the method exists on both with different meaning;
  • every former ToTNVector site, for copy-on-write.

Tests

  • New: release_test.go covers pooled, unpooled, read-only, placeholder and closed-pool release, and that a stale release can't affect the next borrower.
  • New: vector/value_test.go covers MustAppendValue, GetValue, NullCount and Equal; TestVectorPoolCloneWindow covers the pool clone.
  • These pass:
    • the full ./pkg/vm/engine/tae/..., ./pkg/objectio/... and ./pkg/publication/...;
    • ./pkg/vm/engine/test/... and ./pkg/datasync/...;
    • containers under -race.
  • The whole module builds.
  • molint and golangci-lint report 0 issues on the changed packages.

🤖 Generated with Claude Code

fengttt and others added 8 commits November 26, 2026 11:50
Design and phased plan for issue matrixorigin#10181. Measures the 949 type-id
switches in pkg/, identifies the ones that run per row, and proposes an
Oid-indexed traits table in types, per-package operation tables with
completeness tests, and the exhaustive linter for the switches that stay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eSwitchFamilies

Step 1 of docs/design/20261126-type-vft.md (matrixorigin#10181). optools/oidscan is a
standalone, standard-library-only module that scans pkg/ for switch
statements over types.T and reports their count, case-count histogram, the
ones inside a loop, and which of those have a loop-invariant type (the
worklist for moving dispatch out of row loops). It is a report, not a check.

The design doc now builds on the existing TestTypeSwitchFamilies check
(families, typeswitch:partial tags, shrinking baseline) instead of proposing
the exhaustive linter, and records steps 1 and 2 as done.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Step 2 of docs/design/20261126-type-vft.md (matrixorigin#10181).

- multi_update and preinsert each had a copy of the zero-temporal check
  that switched on the column type for every row. Both now call
  colexec.CheckZeroTemporalVector, which switches once per vector and runs
  a typed row loop. Error codes, messages and row numbers are unchanged.
- postdml decides how to quote the primary key once per batch instead of
  per row.
- deletion copied each deleted row's key by boxing it (getNonNullValue)
  and unboxing it again (AppendAny): two type switches per row, and the
  getNonNullValue copy panicked on key types it did not list (the
  low-precision floats, year, most vector types). The key is now copied
  with UnionOne, and that copy of getNonNullValue is removed.
- typeswitch_baseline.txt regenerated: removals only (the two deletion
  entries plus 12 entries already fixed upstream).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Step 3 of docs/design/20261126-type-vft.md (matrixorigin#10181).

traits_table.go holds one row per T_ constant: family flags, TypeLen,
FixedLength, the default type TryToType returns, and the String and
OidString names. String, OidString, TypeLen, FixedLength, TryToType, the
T.IsXxx predicates and Type.IsInt/IsUInt/IsFloat/IsDecimal read the table
instead of each switching on the type id. AllOids() lists the T_ constants
for other packages' completeness tests.

No change in behavior: the switch implementations are kept in
traits_legacy_test.go and TestTraitsMatchLegacy compares every method on
all 256 T values, including the panics for types with no size. A field
left out of a row means "absent" (panic, false or "unknown"), so a
forgotten size fails loudly. TestTraitsCoverEveryOid fails when a T_
constant has no row; TestTraitsFlagFamilies ties the float and vector
flags to the TestTypeSwitchFamilies families. Benchmarks: the table is
as fast as or faster than the switches (FixedLength 106 vs 124 ns,
IsFloat 31 vs 39 ns per pass over all types).

typeswitch_baseline.txt: two entries removed, both switches in types.go
that are now table rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
-list prints every type-id switch (file:line, function, type ids named,
default branch, inside a loop); -dir keeps the switches in files directly
in one directory. Used to pick the switches each step of
docs/design/20261126-type-vft.md moves.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…able

Step 4 (pilot) of docs/design/20261126-type-vft.md (matrixorigin#10181).

type_ops.go has one row per type id with the Go element type that stores
it (fixedOps[T] or varlenOps), and lists the 7 type ids no operation here
supports. GetAny, AppendAny, Shrink, ShrinkByMask, Shuffle and
shuffleWithBufData read their per-type function from the table instead of
each switching over 47 type ids; all six had the same type-to-Go-type
mapping. Each keeps its own behavior for an unsupported type: GetAny
returns nil, AppendAny does nothing, the others panic with their own
message.

No change in behavior: the six switch implementations are kept in
type_ops_legacy_test.go, and TestTypeOpsMatchLegacy runs both on random
vectors (with NULLs and out-of-line varlenas) of every type id, comparing
values, vectors, errors and panics. A row with the wrong element type
fails it even when the size matches. TestTypeOpsCoverEveryOid fails when
a T_ constant is neither a row nor listed as unsupported; TestTypeOpsRows
checks each row's element size against types.T.TypeLen.

Benchmarks are within noise: GetAny +1% (int64) to -1% (Blockid),
Shrink unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ch onto the type-ops table

Step 4b of docs/design/20261126-type-vft.md (matrixorigin#10181).

- getUnionAllFunction: 853 lines of per-type closures become
  unionAllFixed[T] and unionAllVarlen, built per row of the table; T_any
  keeps its own closure. unionNsp moves to package level, unchanged.
- MakeAppendBytesFunc and NewFunctionResultWrapper read the fixed-size
  case from the table (varlena types are still handled first, as before).
- canonicalVectorTypeSize and isVarlenaMarshalType read the table instead
  of listing the type ids again.

getConstSetFunction stays a switch: its hand-written closures run per row
in SetJoinBatchValues, and the generic version measured about 1 ns (8%)
slower per call. TestConstSetCoversTypeOps ties it to the table instead:
it must return a function for every supported type id and panic for every
other one but T_any.

No change in behavior: the replaced functions are kept in
type_ops_legacy_test.go, and TestTypeOpsConstructorsMatchLegacy compares
them on every type id (union from plain, const and const-null sources
into a vector with a different area; append-bytes; function result;
canonical size with right and wrong sizes). Checked that it fails when a
varlena type is given the fixed-size union. Union benchmarks are within
+-1%.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ctly

Fixes matrixorigin#33336 (part of matrixorigin#33335).

containers.Vector was an interface implemented by a wrapper around
*vector.Vector. It is now an alias for *vector.Vector, the wrapper is
gone, and its methods are free functions in containers/vector.go with the
same behavior (GetValue, AppendValue, UpdateRow, Extend, Compact,
Window, CloneWindow, WriteVector/ReadVector, ...). GetDownstreamVector()
and ToTNVector() calls are removed: they were identity on the vector.
TAE Batch stays (matrixorigin#33337); its Vecs are now []*vector.Vector.

Release: Close() becomes ReleaseVector(v). A vector lent by a VectorPool
goes back to its pool; any other vector is freed with its own pool. To
keep pooled release safe without a field on Vector, the pool lends a
fresh vector struct holding the element's buffers and moves them back on
release; a package-level registry records what is lent. A stale second
release then finds an empty struct, so it can never reach a later
borrower of the same buffers, and release stays idempotent as Close was
(pnode.go relies on it).

Behavior changes, all deliberate:
- The wrapper copied a read-only vector on first write (copy-on-write).
  The mutating functions now panic on a read-only vector instead. The
  full TAE suite found two sites: checkpoint backup (replay.go) appends
  to loaded checkpoint vectors, so it now Dups a cache-backed one first,
  as the wrapper did; and TestNull1 updated a window of a mock batch.
- ReleaseVector frees a read-only vector too (dropping references and an
  owned null bitmap); the wrapper skipped Free for those, which leaked
  an owned null bitmap.
- VectorAllocated (used by Batch.Allocated) keeps the wrapper's 0 for a
  read-only vector; vector.Allocated reports referenced capacity.

The call sites were rewritten from compiler errors with a one-off tool
(each "X.M undefined" error located the call to rewrite), then reviewed
by hand: the former GetAllocator() calls (now MPool(), the same pool for
an owned vector), the CloneWindow calls that need a pool, Allocated(),
and every former ToTNVector site for copy-on-write.

Tests: release_test.go covers pooled, unpooled, read-only, placeholder
and closed-pool release, and that a stale release cannot affect the next
borrower. Full ./pkg/vm/engine/tae/..., ./pkg/objectio/...,
./pkg/publication/..., ./pkg/vm/engine/test/... and ./pkg/datasync/...
pass; containers passes under -race.

Co-Authored-By: Claude Opus 5.5 <[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 →

@mergify

mergify Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

returnToPool dropped the lent-vector registry entry before moving the
buffers back, so a second, overlapping ReleaseVector missed the entry
and freed buffers the pool had just taken back. Claim the take-back
with a CAS on the element's lent pointer, delete the entry only after
the lent struct is emptied, and leave vectors without an mpool
untouched in ReleaseVector so late releases write nothing.

Add TestReleaseVectorPooledConcurrent, and port the deleted
vector_test.go selection/window oracles to foreach_test.go for
ForeachVectorWindow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fengttt

fengttt commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. Both items are fixed in the latest push.

P2 pool.go overlapping releases. Confirmed. returnToPool dropped the registry entry before the take-back emptied the lent struct, so a second release that missed the entry would Free buffers the pool had just taken back.

  • returnToPool now Loads the entry and claims the take-back with e.lent.CompareAndSwap(vec, nil). A release that loses the swap does nothing: either another release is taking vec back, or it already has and the element has been lent again as a different struct.
  • The entry is deleted only after vec is emptied, so a release that misses it can only see the empty struct.
  • ReleaseVector now leaves a vector with no mpool untouched (a read-only view, or a lent vector already taken back). Before, a late release still ran Free on the empty struct, which writes its fields; under -race that showed as a write race between the late releasers.
  • Regression test: TestReleaseVectorPooledConcurrent (8 goroutines released together through a barrier, 5000 rounds) checks that the pool and the mpool both still account for the buffers. Against the old pool.go it fails at round 274 with a "double free" panic, and with 28 data races under -race. It passes with the fix, with and without -race.

P2 iteration oracles. I ported them to containers/foreach_test.go, testing ForeachVectorWindow:

  • TestForeachVectorWindowSelections: every mock type, flat vectors, with and without a NULL on a selected row. It is table-driven over windows × selection {2, 6}: whole vector, window holding both, past the first, between them, starting on the last, and empty. Values and NULL flags are checked row by row.
  • TestForeachVectorWindowOnView: window views at bias 0 and 1. Rows and selections are relative to the view (the old TestVector6 cases).
  • TestForeachVectorWindowTypedSelections: the typed-op form for fixed-width and varlen columns, with a selection inside a nonzero window.

@XuPeng-SH

XuPeng-SH commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 13d9aa5c6dc228658ff2f2baadb1114a18b84966

Review completed. Read the assessment.

@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: 13d9aa5c6dc228658ff2f2baadb1114a18b84966

Assessment: request_changes

The shared-vector refactor removes the TAE wrapper and uses a loan registry to preserve pooled ownership. The previously reported pooled-release race and iteration coverage concerns are addressed, but concurrent release remains unsafe when the same pool falls back to an unpooled vector.

Model: gpt-6.1-terra / max

Session: 01a21cb3-a707-7531-b8de-81ca7f1f3651 · slot 0 · generation 24

  • P2 pkg/vm/engine/tae/containers/pool.go:410: A VectorPool has no available slot, so GetVector returns its unpooled fallback, and two cleanup paths concurrently release that vector.
    Impact: Both releases can enter Vector.Free concurrently and free the same allocation. This can panic with an invalid-pointer double-free error and terminate the process.
    Evidence: The removed wrapper guarded Close with an atomic compare-and-swap for pooled and unpooled vectors alike. The new registry guards only pooled loans; fallback vectors reach this unsynchronized Free. A race probe that reserves the only fixed-width pool slot reproduced both a data race and double-free panics; the pooled control passed. Preserve exactly-once concurrent release for fallback vectors as well, and add a regression test covering pool exhaustion.

Validation:

  • Private /tmp and loopback preflight passed; receipt checks/1795780243390479946-3.json.

  • Focused race tests for pooled concurrent release, selected/window iteration, and batch V2 compatibility passed; focused-regression.log and checks/1795781082921722946-3.json.

  • The saturated-pool race probe failed with the reported race and double-free panics; saturated-release-probe.log and checks/1795781292174287565-3.json. The separate pooled control passed in release-probe-native.log.

  • The required jemalloc prerequisite was built in the diagnostic directory using the checkout's pinned source and Makefile; native-inputs.txt and checks/1795780963760118668-7.json.

Limitations:

  • The failing interleaving was reproduced at the vector-pool API level; no production incident was established.

  • The full CI matrix was not rerun locally.

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

Codex automated review

The PR replaces the containers.Vector wrapper interface with the shared *vector.Vector, moves the wrapper's operations onto callers and the shared vector API, returns append errors instead of panicking at production call sites, and preserves pooled-buffer reuse and idempotent release through a package-level loan registry. I verified at HEAD 13d9aa5 that the two findings from the first prior review are fixed: returnToPool claims the take-back with lent.CompareAndSwap and removes the registry entry only after the lent struct is emptied, with TestReleaseVectorPooledConcurrent covering overlapping pooled releases, and the deleted iteration oracles were ported to containers/foreach_test.go (TestForeachVectorWindowSelections, TestForeachVectorWindowOnView, TestForeachVectorWindowTypedSelections). The latest prior review's remaining finding - concurrent release of the same pool fallback vector reaching an unsynchronized vec.Free in ReleaseVector (pkg/vm/engine/tae/containers/pool.go) - remains unaddressed and stays out of my findings per the no-duplication rule. My independent review found the other ownership patterns sound: sequential repeat releases are no-ops because a taken-back lent vector has a nil MPool and vector.Free clears data/area so mpool.Free of nil slices and the idempotent Bitmap.Free do nothing; pointer identity prevents a stale release from touching a re-lent element; the batch compact-in-place paths (Batch.Compact, anode.WindowColumn, TransferDeletes) only shrink writable vectors, since compactInvisibleAppendRows is skipped under WithPreservePhysicalRows, the only context that also requests zero-copy read-only loads; const destinations are converted before extends in pnode.Scan; and the deliberate replacement of copy-on-write with read-only panics is compensated at the known sites (replay.go Dups a cache-backed vector; memoryNode.Scan checks getDataWindowLocked errors). The Equal rewrite that finally compares decimal/TS/Rowid columns affects test paths only (Batch.Equals has no production callers). A repository-wide scan found no references to removed wrapper APIs. Limitation: Go tests cannot run in this checkout - every reviewed package's test closure requires pkg/common/malloc, a cgo package needing the unbuilt jemalloc under thirdparties/install, and CGO_ENABLED=0 fails because pkg/common/mpool references malloc.SimpleCAllocator without a fallback (go list snapshot decoded cleanly with no metadata errors; the attempted CGO_ENABLED=0 container test run exited 1 on that compile error and is logged). Validation of the focused containers/vector tests at this head therefore rests on the prior reviewer's executed receipts plus this static review.

@XuPeng-SH

XuPeng-SH commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 13d9aa5c6dc228658ff2f2baadb1114a18b84966

New discussion was assessed; the previous review remains unchanged.

@fengttt
fengttt merged commit b199953 into matrixorigin:main Nov 27, 2026
4 of 6 checks passed
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 27, 2026
Upstream squash-merged the commits this branch stacked on (matrixorigin#33338,
matrixorigin#33339, matrixorigin#33342). The merged tree is upstream/main plus this branch's
step 5 change; conflict in containers/utils.go UpdateValue resolved to
keep main's const and read-only checks (SetNull/UnsetNull) on top of the
SupportsAny/SetAny dispatch. value_access_test uses Vector.GetValue,
since containers.GetValue was removed by matrixorigin#33342.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 28, 2026
Upstream squash-merged the commits this branch stacked on (matrixorigin#33342,
matrixorigin#33343, matrixorigin#33344). The merged tree is upstream/main plus this branch's
step 7 change; the design-doc step table keeps main's row 6b and this
branch's row 7.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 28, 2026
Upstream squash-merged the commits this branch stacked on (matrixorigin#33342,
matrixorigin#33343, matrixorigin#33344, matrixorigin#33346). The merged tree is upstream/main plus this
branch's step 8 change, which applied cleanly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 28, 2026
Picks up the step 8 branch, which now includes upstream/main (with
matrixorigin#33342, matrixorigin#33343, matrixorigin#33344 and matrixorigin#33346 squash-merged). Two uses of APIs
matrixorigin#33342 removed are updated: containers.AppendValue in mock.go becomes
Vector.MustAppendValue, and containers.Window in the decimal256 index
test becomes Vector.Window.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt added a commit that referenced this pull request Nov 30, 2026
…gather kernel (#33181 PR 9 + 10 + 11) (#33333)

## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

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

- **PR 9 (`cd6e5f6e7c`):** sorts apply their permutation with the gather
kernel, and `Shuffle` / `ShuffleWithBuf` go away.
- **PR 10 (`aa315ff03e`):** the hash join's build-side gathers use one
many-source gather kernel, and `TryUnionFlatFixedRows` goes away.
- **PR 11 (`d196b27585`):** the TN merge gathers columns with
`UnionRowsFrom`, and its transfer map comes from
`remaplist.List.InvertInto`.

### PR 9: Permute replaces Shuffle

- **`Vector.Permute(rows, mp)` and `Batch.Permute`** reorder in place:
row i becomes old row `rows[i]`. They use the gather kernel's value loop
per payload width and its word-wise NULL gather. They replace `Shuffle`
/ `Batch.Shuffle` in order, mergeorder, top, mergetop, window, s3util,
TN mergesort, logtail replay, readutil and publication. Every caller
already had `[]int64` rows, so `pkg/sort` and the callers' lists are
unchanged.
- **`Vector.PermuteWithScratch`** replaces `ShuffleWithBuf` for 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).
- **The identity permutation of the full length is a no-op**, the common
case when a sort sees data already in order.
- **Untyped (ANY) vectors keep `Shuffle`'s rules** (#33058): only their
NULLs and length follow the rows, a constant takes the new length, and
one holding values is rejected. `Batch.Permute` rejects a selected
batch, as `Batch.Shuffle` did.
- The per-type `Shuffle` switches, `shuffleWithSortedProof` and the
type-ops table's `shuffle` / `shuffleWithBuf` entries are deleted.
`Permute` is one loop per payload width for every type, so it needs no
table entry.

#### Rebase onto main (PR 9)

- Upstream routed `Shuffle` through the type-ops table (#33339) and
added the ANY rules (#33058) and the selected-batch check. `Permute`
carries the ANY rules and the check, and the table drops its shuffle
entries; the legacy-switch comparison in `type_ops_test.go` no longer
covers a shuffle, since `Permute` is tested against `UnionOne` instead.
- Upstream's ANY tests (`shuffle_any_null_test.go`, now
`permute_any_null_test.go`), the selected-batch test and
`join_util_test.go` call `Permute` / `PermuteWithScratch` with their
assertions unchanged.
- `GetDownstreamVector` is gone upstream, so publication and TN
mergesort call `Permute` on the column directly. `TestBatchPermute` uses
`batch.NewWithSize`.

#### Benchmarks (PR 9)

Pinned to one core, minimum of five runs, PR 8 → PR 9 (measured before
the rebase):

| benchmark | old | new |
| --- | --- | --- |
| permute 8192 rows, random order, int64 / int64 with NULLs | 3.5 / 8.6
µs | 3.5 / 8.7 µs |
| same, decimal128 / varchar with NULLs | 22.6 / 28.9 µs | 22.7 / 29.0
µs |
| same with a reused scratch (`PermuteWithScratch`), decimal128 /
varchar | — | 10.9 / 13.4 µs |
| scratch permute of already sorted input, int64 / varchar | 2.7 / 4.3
µs | 1.1 / 1.1 µs |
| scratch permute in reverse order, int64 / varchar | 2.9 / 6.7 µs | 2.7
/ 6.8 µs |
| `BenchmarkTopUnaccountedResident` / `TopAccountedResident` | 1124 /
1139 µs | 1114 / 1126 µs |
| `BenchmarkReviewSmallVarlenTop` | 5783 µs | 5694 µs |
| `BenchmarkMergeTopUnaccountedResident` | 15.9 ms | 16.0 ms |
| `BenchmarkOrderUnaccountedResident` | 8.79 ms | 8.81 ms |
| mergeorder `BenchmarkOrder` / `MergeOrderUnaccountedResident` | 3029 /
724 µs | 3016 / 723 µs |
| TN `BenchmarkSortBlockColumns` | 636 µs | 638 µs |

The operators are flat: the permutation is a small part of a sort.
`order`'s `BenchmarkOrder` panics ("mismatched multi-column semantic
types") before and after this change, so it is left out.

#### Tests (PR 9)

- New tests: `Permute` and `PermuteWithScratch` against `UnionOne` for
every payload width and NULL rate, with lists that repeat, drop and add
rows; sorted flag, constants, pool mismatch; `Batch.Permute` with a
vector shared by two columns; the scratch alias, reuse and
string-metadata tests rewritten for `PermuteWithScratch`.
- After the rebase: `vector` and `batch` pass with `-race`;
`pkg/container/...`, `bitmap`, `remaplist`, `pkg/sql/colexec/...`,
`publication`, TN `mergesort` and `blockio`, `readutil`,
`logtailreplay`, `objectio` and `plan/function` pass. `go vet ./pkg/...`
is clean and `make static-check-changed` reports 0 issues.
- BVT not run.

### PR 10: UnionRowsFrom for hash-join build gathers

- **`Vector.UnionRowsFrom(srcs, rows, mp)`** gathers row `rows[i]` of
`srcs[i]`.
- When every source is a flat vector of the destination's type, it takes
one pass per column: NULLs a word at a time, the fixed-width value loop
per payload width, and varchar payloads copied into an area grown once
for the whole call.
- Any other source (a constant, a different type, the destination
itself) falls back to `UnionOne` per row, with the same result.
- A row outside its flat source returns an error and leaves the
destination unchanged.
- **Hash join build side:** a matched build row is an ordinal over all
build batches. Each ordinal is decoded into (batch, row) once per output
chunk and used for every build column, varchar included. The probe side
already used `Union` and is unchanged.
- **Removed:** `TryUnionFlatFixedRows`, `FixedSourceRow` and the
run-wise varchar fallback.
- **`unsafe`:** the lint allows `unsafe` in `vector` only in `tools.go`
and `vector.go`, so the gather's two unchecked per-row reads
(`fixedAtUnchecked`, `varlenaAtUnchecked`) live in `tools.go`. Every row
is checked against its source's length before them. The bounds-checked
`util` casts instead cost 10–15% on the fanout benchmark (int64 68.2 →
77.9 µs); the helpers are within 1% of inline `unsafe`.

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

| benchmark | old | new |
| --- | --- | --- |
| fanout, int64 | 78.9 µs | 69.5 µs |
| fanout, decimal128 | 109.1 µs | 81.2 µs |
| fanout, varchar 8 B (inline) | 134.8 µs | 115.3 µs |
| fanout, varchar 48 B | 287.2 µs | 255.3 µs |
| `HashJoinUniqueProjection`, 256 rows from alternating build batches,
int32 / decimal128 / varchar | 2.87 / 4.20 / 18.3 µs | 2.58 / 3.33 /
15.4 µs |
| `HashJoinSmallDuplicatePayload`, `HashJoinMembershipProjection`,
`RightExistentialRepeatedKeys` | | within ±1.5% |

The 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 with `UnionOne`.
- `TestUnionRowsFromUnusualSources`: window, constant NULL and self
sources.
- `TestUnionRowsFromErrors`.
- The former `TryUnionFlatFixedRows` tests are rewritten for
`UnionRowsFrom`, including the allocation-account admission case (the
destination is unchanged on rejection).
- After the rebase: `pkg/container/vector` and
`pkg/sql/colexec/hashjoin` pass with `-race`; `pkg/container/...`,
`pkg/sql/colexec/...` and `pkg/sql/compile/...` pass. `go vet ./pkg/...`
is clean and `make static-check-changed` reports 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: `srcRows` entries, with -1 for every
source row the list leaves out. A repeated or out-of-range source 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 then gathered one at a time per output block with
`UnionRowsFrom` (PR 10).
- `InvertInto` derives the map. It is allocated from the merge's pool
and freed by the merge's release function.
- **Map type:** the map is `[]int64`, and so is
`UpdateMappingAfterMerge`'s argument.
- **Behaviour change:** a heap merge with more rows than the layout
returns an error instead of indexing past the blocks.
- **Unchanged:** `ReshapeBatches`' rules for which blocks it creates and
which rows past the layout it drops.
- **Not converted:** `AddSortPhaseMapping` inverts straight into the
transfer slab's `TransferDestPos` entries, and an `int64` map 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.go` conflicted with upstream's removal of the TAE vector
wrapper (#33342) inside the per-row `UnionOne` loop this PR deletes; the
loop stays deleted.
- With the wrapper gone, the gather takes each batch's column directly
(no `GetDownstreamVector`, no staging slice), and the new tests and
benchmark build their columns with `containers.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:

| benchmark | old | new |
| --- | --- | --- |
| `BenchmarkMergeAObjGather` | 1864 µs, 265 KB Go heap | 1020 µs, 134 KB
|
| `BenchmarkReshapeBatchesGather` | 1282 µs, 266 KB | 632 µs, 134 KB |

#### Tests (PR 11)

- `TestInvertInto`, `TestInvertIntoErrors` (96.6% coverage of
`remaplist`).
- `TestReshapeBatchesMapping` and `TestAObjMergeMapping` check 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.
- Before the rebase: `./pkg/vm/engine/tae/...` passed (32 packages).
- After the rebase: `remaplist` and `mergesort` pass with `-race`; TAE
`mergesort`, `tables`, `containers` and `rpc`, `objectio` and
`pkg/container/...` pass. `go vet ./pkg/...` is clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

This branch was successfully deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/refactor Code refactor size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants