Skip to content

refactor(tae): remove the containers package (#33337) - #33545

Merged
fengttt merged 26 commits into
matrixorigin:mainfrom
fengttt:tae-remove-factory
Dec 1, 2026
Merged

fengttt merged 26 commits into
matrixorigin:mainfrom
fengttt:tae-remove-factory

Conversation

@fengttt

@fengttt fengttt commented Nov 30, 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 #33337

What this PR does / why we need it:

This follows #33541. Together its commits remove the tae/containers package.

Was Now
containers.MakeVector(t, mp) vector.NewVec(t, mp)
containers.BuildBatch(types, opts) batch.NewBatchWithDeletesTypes(types, mp)
containers.BuildBatchWithPool(...) batch.NewBatchWithDeletesFromPool(types, rows, pool)
containers.Options removed; Capacity was never set
containers.BatchFreeList batch.FreeList
containers.OneSchemaBatchBuffer batch.NewFreeListWithLimit(maxBytes)
containers.IBatchBuffer removed; the sinker holds a *batch.FreeList
sinker buffer statistics removed; they never updated
containers.Vector, VectorPool, ReleaseVector, ... the pkg/container/vector originals they forwarded to
GeneralBatchBuffer, Usage(), offHeap, WithOffHeap removed: used only by tests, or stored and never read
ToCNBatch(b), ToTNBatch(b) b.AsBatch(), batch.NewBatchWithDeletesOf(b)
DedupSortedBatches, CopyBatch batch.DedupSorted, Batch.CopyFrom
UpdateValue vector.UpdateAny, or vector.UpdateFixedAt without boxing
MarkNull, CloneVector Vector.TrySetNull, VectorPool.Clone
ForeachWindowBytes vector.ForeachRaw
ForeachVector, ForeachVectorWindow, ForeachWindowFixed, ForeachWindowVarlen, MakeForeachVectorOp typed vector.ForeachFixed and ForeachBytes; two type switches go
getNonNullValue removed; only tests used it

For reviewers:

  • Key types. Persisted dedup (tables/functions.go) now takes its typed probe from its own table. MakeForeachVectorOp had no BIT or YEAR case and panicked on those keys, as far as the code shows; they work now, and TestPersistedDedupKeyTypes covers every key type in the tables. A type without a dedup function is an error, not a panic.

  • Duplicate code. The fixed-size and varlena appendable-block probes share one aBlkMatches.visit.

  • Errors instead of panics. UpdateAny, UpdateFixedAt and TrySetNull return errors, and callers pass them on. TrySetNull refuses a read-only vector; MarkNull did not check.

  • Constant vectors. ForeachRaw handles constant fixed-size vectors (the old code sliced past their one value), and ForeachBytes applies a selection to a constant, which was ignored. A nil or empty selection still means every row.

  • DedupSorted. An empty key after an empty first batch is no longer taken for a duplicate.

  • A nil pool used to mean TAE's default pool. vector.NewVec with a nil pool makes a read-only vector, so a nil now fails on the first append. Literal nils were only in tests, which now name the pool.

  • NewBatchWithDeletesFromPool returns an allocation failure as an error and gives back the vectors it borrowed; BuildBatchWithPool panicked. A transaction append now fails with the error. MakeBufferBatch has no error result and still panics.

  • FreeList reuses a kept batch only if its column type OIDs match the requested types, and then gives it those types; before, it ignored them.

  • FreeList has no mutex; OneSchemaBatchBuffer had one. Its users, GC and TransferFlow, run sequentially and do not enable the sinker's pipeline mode.

  • The limit works as before: a batch that would take the list over it is freed. GC and transfer limits are unchanged.

  • The sinker has two unexported hooks, nil outside tests, where tests that faked the interface inject failures. In multi_update those tests now observe deletes and memory instead; I checked that each fails when the ownership code is broken.

  • UpdateAny and UpdateFixedAt reject a row out of range.

  • Flaky test, not from this change. TestIssue25590TwoDirtyObjectCompactionIsAtomicAcrossReplacements and ...RecordFailureAfterStagedReplacementRetracts read the ledger while the GC pool may still be deleting the rewritten originals. main fails too (20 of 390 stress processes). The fixed count was wrong for a worker that may be anywhere, so they now run with the worker about to delete, deleted but not settled, finished, and racing. Each order checks ownership, the recorded copy, GC claims and files on storage, which replaces the count. Settling before deleting, dropping the recorded copy first, losing the GC claim, and not deleting each fail it. 0 of 240 stress processes fail, and -race is clean.

  • Fix: TransferFlow.Process. It deferred the put-back inside its read loop, so each batch read took a new buffer, all held until the end. It now reads into one buffer, put back before the final transfer and sync. TestTransferFlowReusesReadBuffer counts 51 buffers for 50 batches with the old loop, 1 now.

Testing

  • Unit tests on the final code: pkg/container, pkg/objectio, pkg/vm/engine/tae, disttae, engine/test, pkg/publication, pkg/backup, pkg/datasync, pkg/vectorindex/ivfflat, pkg/tools, pkg/iscp, and pkg/sql/colexec with multi_update. New tests for the moved functions.
  • Sinker write, spill and sync benchmark, 8 interleaved runs, up to the FreeList commit vs. the first commit: median 7.12 ms vs 7.22 ms; 593 allocs/op both.
  • Last commit vs. the one before: index building unchanged; persisted dedup level or faster with fewer allocations (1,038 to 13 per op at 1,024 probes), except a one-row block, about 80 ns more per block (180 to 259 ns). Sinker +2.4%, equal allocations, within its noise.
  • -race on the last commit: container/batch, tae/tables, tae/index, tae/txn, tae/blockio, objectio/ioutil. Before it: container/batch, objectio/ioutil, readutil, tae/db/gc, multi_update, and the transfer, tombstone, GC and sinker tests of disttae and engine/test.
  • Transfer fix: all of disttae and engine/test; -race on their transfer and tombstone tests.
  • make static-check-changed (full graph): 0 issues.
  • Not run locally: BVT.

🤖 Generated with Claude Code

fengttt and others added 14 commits November 30, 2026 10:01
Column loaders fill a *batch.Batch and set its row count; read-filter
searches take []*vector.Vector. containers.Vectors is removed, and objectio
no longer imports the TAE containers package for it.

Batch.InitVectors allocates up to 8 vectors and their pointers at once, and
the Batch stays on the caller's stack. The reader creates its scratch vectors
on the first load, sized to the block: scans that copy straight to the output
never allocate them. LoadColumnsDataFromMeta's release no longer moves the
IOVector to the heap. The checkpoint readers no longer copy vector headers
that share ownership of their buffers.

VectorsCopyToBatch becomes CopyBatch; its test now checks the appends.

In containers, VectorPool picks an element with math/rand/v2 instead of a
linkname to runtime.cheaprand (about 3 ns per GetVector), and both runtime*.go
files are removed; runtime.go was never built.

Add benchmarks for tombstone reads, a reader's life, and the vector pool.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
containers/mock.go holds test data generators but was part of the production
package. Move it, with its test, to tae/testutils. catalog.MockBatch, a wrapper
over it in a non-test file, becomes testutils.MockSchemaBatch, so no production
package imports testutils. It takes an interface: testutils cannot import the
catalog without import cycles.

MockNullableBatch, only the body of MockBatch, is merged into it. The
containers tests that use the mocks become package containers_test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The same switches moved from tae/containers/mock.go to tae/testutils/mock.go;
no entry is added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rixorigin#33337)

batch.BatchWithAttr is a Batch with column names, optional column seqnums and
a delete bitmap. It replaces TAE's Batch and BatchWithVersion; batch.Batch is
unchanged. BatchSplitter becomes a loop over CloneWindow.

Names are found by scanning Attrs up to 8 columns and through a private index
above that, checked against Attrs on each lookup, so removing or reordering
columns cannot make a name find another column, as the old Nameidx could.

Logtail collection walks the columns in seqnum order instead of sorting the
batch, which reordered a live transaction node's columns in place.

VectorPool moves to pkg/container/vector, so that Close can return lent
vectors. Delete, RangeDelete and CloneWindow take the pool they allocate from.

The WAL codec becomes functions (WriteBatch, ReadBatch) with the same bytes; a
golden test pins them to a hash computed with the old code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The type-switch baseline may only shrink: tag MockVector and MockVector2,
whose default handles the remaining types, and drop their baseline entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
BatchWithAttr loses Attrs, Seqnums and the name index, and becomes
BatchWithDeletes. Names and seqnums come from the schema.

- Checkpoint, snapshot, tombstone and object metadata batches are read by the
  positions their schemas give; scans by the position in colIdxes.
- The logtail builders return the column names next to the batch; what goes
  over the wire is unchanged. In-memory rows take the schema of their version.
- The WAL codec takes and returns the names. Replay maps them to the object's
  schema once; a column the record does not have is nil. The bytes are
  unchanged.
- A CN write must name the first columns of the table, in order. It used to
  copy by schema position whatever the names said.
- A transaction's node keeps the schema its rows were built with, for the WAL
  and the logtail.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rixorigin#33337)

containers/batch_codec.go becomes BatchWithDeletes.WriteWAL and batch.ReadWAL,
which take the mpool they allocate from. The bytes are unchanged; the golden
test moves along.

The V1 and V2 readers and the V2 writer are removed. Only append command
version 3 has been registered since matrixorigin#21883, so nothing could reach them. What
only they used goes too: bitmap.UnmarshalV1 and tae/common/bitmap.go.

AppendCmd.ReadFrom returns the error of reading its batch, which it dropped, so
a cut short record is no longer replayed as the part that could be read. The
byte counts it and WriteTo return are now right.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…#33337)

AppendCmd.ReadFrom ignores the error of reading its batch again, and ReadWAL
returns the part it could read. The comment says why that is dangerous.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
MakeVector becomes vector.NewVec; a nil pool no longer means TAE's default
one. BuildBatch and BuildBatchWithPool become batch.NewBatchWithDeletesTypes
and NewBatchWithDeletesFromPool, which returns an allocation failure as an
error instead of panicking. Options goes: its Capacity was never set.

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 30, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

…rs (matrixorigin#33337)

BatchFreeList becomes batch.FreeList, which hands out a kept batch only if
its column types match. IBatchBuffer becomes ioutil.BatchBuffer, what the
sinker calls. GeneralBatchBuffer had only its test; offHeap (WithOffHeap
included) was stored and never read; Usage had no caller.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@qodo-code-review

qodo-code-review Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

refactor(tae): remove the containers package

✨ Enhancement 🐞 Bug fix 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Deletes tae/containers and moves callers to pkg/container/vector and pkg/container/batch
 equivalents.
• Adds batch.FreeList, batch.DedupSorted, typed
 vector.ForeachFixed/ForeachBytes/ForeachRaw, and error-returning UpdateAny/TrySetNull.
• Fixes persisted dedup on BIT/YEAR keys and constant-vector handling; adds tests covering each key
 type.
Merge Risk 🟡 Medium

Blast radius 🟡 Medium 💥 2 capabilities

  • 2 affected capabilities within one bounded functional scope: transactional storage data processing.
  • The changed vector, batch, scan, index, transaction, and logtail calls jointly transform rows between storage stages and serve the same transactional storage behavior; wrapper removal is an implementation hop, not an independent capability.
  • Persisted-block probes, appendable MVCC checks, workspace deduplication, and tombstone filtering determine one end-to-end outcome: whether a key is accepted, rejected, or hidden during transactional operations.
Behavioral complexity 🟡 Medium 🧩 Compatibility cases, Coordinated invariants

  • Before, TAE wrapper methods mediated vector construction, iteration, ownership, null updates, and batch conversion.
  • After, callers use concrete vectors and new batch helpers directly.
  • New correctness conditions are that read-only, pooled, constant, nullable, and zero-copy vectors retain equivalent semantics; batch views must not outlive or accidentally free their owners; and error paths must release every vector.
  • The change also preserves old checkpoint, logtail, and transaction payload formats while changing their in-memory representation, creating compatibility and ownership invariants.
Potential damage 🔴 High 🩹 Integrity

  • A wrong match, missed match, or incorrect NULL or row-ID update can admit duplicate primary keys, reject valid writes, or hide the wrong rows and tombstones.
  • Reverting prevents further bad decisions but cannot automatically remove duplicate persisted rows or restore incorrectly applied deletes; repair requires identifying affected transactions or objects and replaying or compensating them.
  • Rollback is sufficient only before affected writes commit.
  • After commit or object publication, repair, backfill, or transaction-level compensation is required; no automatic repair invocation is shown.
Assessed commit 91a15d6
Diagram

graph TD
  A["Sinker / ioutil"] --> B["batch.FreeList"] --> C["batch.Batch"] --> D["vector.Vector"]
  E["TAE tables / txn"] --> C
  F["tae/containers (removed)"] -.->|"forwarded to"| D
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Keep containers as a deprecated alias shim
  • ➕ Smaller diff: callers keep compiling without touching call sites
  • ➕ Allows incremental migration across teams
  • ➖ Two APIs for the same operations persist indefinitely
  • ➖ Shim functions still need maintenance and tests
  • ➖ The PR already changes roughly 150 files, so the churn is mostly paid
2. Keep sinker buffer statistics and wire them to FreeList
  • ➕ Preserves observability of buffer memory use
  • ➖ Statistics were never updated in the old code, so they were misleading
  • ➖ Adds state to a hot path for no current consumer

Recommendation: Removing the package outright is the right call. Keeping containers as a thin alias layer would leave two APIs for the same operations and keep the drift that this PR is cleaning up. The one real design choice worth a look is the FreeList byte cap, which replaces the sinker's never-updated buffer statistics with a simple limit.

Files changed (13) +938 / -1728

Enhancement (4) +269 / -0
free_list.goAdd FreeList for reusing emptied batches with byte limit +98/-0

Add FreeList for reusing emptied batches with byte limit

• Introduces FreeList, a LIFO cache of emptied batches keyed by column types and mpool. NewFreeListWithLimit frees batches that would push the list over its byte budget. Replaces containers.BatchFreeList and OneSchemaBatchBuffer.

pkg/container/batch/free_list.go

foreach.goAdd typed ForeachFixed, ForeachBytes and ForeachRaw +122/-0

Add typed ForeachFixed, ForeachBytes and ForeachRaw

• Adds typed iteration over fixed-size and varlena vectors, with selection support. ForeachRaw handles constant vectors correctly, where the old code sliced past their single value. Replaces ForeachVector and related helpers.

pkg/container/vector/foreach.go

batch_with_deletes.goAdd batch constructors that carry delete types +39/-0

Add batch constructors that carry delete types

• Adds NewBatchWithDeletesTypes, NewBatchWithDeletesFromPool and NewBatchWithDeletesOf. These replace containers.BuildBatch and ToTNBatch conversions.

pkg/container/batch/batch_with_deletes.go

vector_pool.goAdd VectorPool.Clone as replacement for CloneVector +10/-0

Add VectorPool.Clone as replacement for CloneVector

• Adds a Clone method on VectorPool so callers can copy vectors through the pool instead of the removed CloneVector helper.

pkg/container/vector/vector_pool.go

Bug fix (1) +237 / -223
functions.goPersisted dedup takes typed probes from its own table +237/-223

Persisted dedup takes typed probes from its own table

• Dedup function maps now use dedupOpFactory wrappers (onFixed/onBytes) instead of untyped any values. Key types that lacked a probe, such as BIT and YEAR, now work rather than panicking. A type with no dedup function returns an error.

pkg/vm/engine/tae/tables/functions.go

Refactor (6) +107 / -1382
sinker.goSinker holds *batch.FreeList and drops buffer statistics +18/-34

Sinker holds *batch.FreeList and drops buffer statistics

• Replaces containers.IBatchBuffer with *batch.FreeList and removes the WithOffHeap option. The buffer statistics were never updated, so they are removed. Test-only onGet and onPut hooks inject failures.

pkg/objectio/ioutil/sinker.go

dedup.goAdd DedupSorted for batches in sorted order +52/-0

Add DedupSorted for batches in sorted order

• Moves the sorted-batch dedup helper from containers.DedupSortedBatches into the batch package. Empty first batches are handled so that later non-empty keys are not dropped.

pkg/container/batch/dedup.go

utils.goDelete containers utilities (1248 lines) +0/-1248

Delete containers utilities (1248 lines)

• Removes the containers package's vector, batch, and foreach helpers. Each is replaced by its pkg/container equivalent or removed as test-only code.

pkg/vm/engine/tae/containers/utils.go

factory.goDelete containers vector factory +0/-60

Delete containers vector factory

• Removes MakeVector and related factory helpers. Callers now use vector.NewVec directly.

pkg/vm/engine/tae/containers/factory.go

loadfuncs.goColumn loaders fill *batch.Batch instead of containers.Vectors +9/-14

Column loaders fill *batch.Batch instead of containers.Vectors

• Loaders now populate a batch and set its row count. The release path no longer moves the IOVector to the heap.

pkg/objectio/ioutil/loadfuncs.go

transfer_util.goTransfer utilities use batch.Batch with the new helpers +28/-26

Transfer utilities use batch.Batch with the new helpers

• Switches transfer paths from containers batches to batch.Batch and vector helpers. Also adds transfer_util_test.go with 73 lines of coverage.

pkg/vm/engine/disttae/transfer_util.go

Tests (2) +325 / -123
update_any_test.goTest UpdateAny, UpdateFixedAt and TrySetNull error paths +207/-0

Test UpdateAny, UpdateFixedAt and TrySetNull error paths

• Adds coverage for the new error returns, including refusing a read-only vector in TrySetNull. Tests check that errors are passed on rather than panicking.

pkg/container/vector/update_any_test.go

db_test.goMigrate DB tests to batch and vector helpers +118/-123

Migrate DB tests to batch and vector helpers

• Updates test fixtures from containers builders to the new batch and vector constructors. Behavior is unchanged.

pkg/vm/engine/tae/db/test/db_test.go

@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Reused batches retain wrong column types 🐞 Bug ≡ Correctness
Description
FreeList.reusable compares only type OIDs, and Get returns a matching cached batch without
updating its vectors' other type parameters. If successive requests use the same OID with different
decimal scales, widths or collations, the second request receives vectors carrying the first
request's type.
Code

pkg/container/batch/free_list.go[R92-94]

+	for i, vec := range bat.Vecs {
+		if vec == nil || vec.MPool() != mp || vec.GetType().Oid != typs[i].Oid {
+			return false
Evidence
Get returns the cached batch unchanged when reusable succeeds. The comparison ignores fields
that are part of types.Type, so the returned vectors can disagree with the requested types.

pkg/container/batch/free_list.go[48-58]
pkg/container/batch/free_list.go[87-97]
pkg/container/types/types.go[191-207]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A cached batch can be returned for a requested type with the same OID but different type parameters, leaving its vectors with stale metadata.
## Fix Focus Areas
- pkg/container/batch/free_list.go[87-97]
## Recommended Fix
Compare complete column types in `reusable`, rather than only their OIDs. Add a test that puts a batch with one scale or collation and requests the same OID with a different one.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


2. Updating a negative row leaves it NULL 🐞 Bug ≡ Correctness
Description
UpdateFixedAt writes through SetFixedAtNoTypeCheck, which translates a negative index, but
checks the NULL bitmap using the untranslated index. When a caller updates an existing NULL row
using a valid negative index such as -1, the value changes while that row remains marked NULL.
Code

pkg/container/vector/vector.go[R794-798]

+	if err := SetFixedAtNoTypeCheck(v, i, val); err != nil {
+		return err
+	}
+	if v.nsp.Contains(uint64(i)) {
+		v.UnsetNull(uint64(i))
Evidence
The setter resolves a negative index relative to the fixed column length, whereas the new
NULL-bitmap check converts that same negative integer directly to uint64.

pkg/container/vector/vector.go[767-786]
pkg/container/vector/vector.go[789-800]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`UpdateFixedAt` accepts the negative indexes handled by its setter but fails to clear the corresponding row's NULL bit.
## Fix Focus Areas
- pkg/container/vector/vector.go[789-800]
## Recommended Fix
Normalize a negative index to its physical row before both writing and checking or clearing the NULL bitmap. Add a test that updates the last NULL row using `-1`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #33541
✅ Context preparation
  Commit messages: summarized; full text retained for this review
Review mode: Auto: 🧠 Deep: Broad refactor spans many independent critical code paths with dense logic changes.

Grey Divider

Tip of the day
💡 Did you know, you can pick a display mode instead of tweaking every Display option by hand

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread pkg/container/batch/free_list.go Resolved
Comment thread pkg/container/vector/vector.go Resolved
fengttt and others added 3 commits November 30, 2026 17:28
…origin#33337)

Get compared type ids only, so a batch could keep another width, scale or
collation, or a constant column. UpdateFixedAt and UpdateAny reject a row
out of range; a negative one was written but left NULL.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A completed compaction deletes the originals it rewrote on the GC pool. Two
tests read the ledger right after, and failed when the worker had already
retired those members. Hold the deletions, then check that they settle.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Holding the worker checked one order only. The two tests now run with it
about to delete, after deleting but before settling, finished, and racing,
and check what must hold in each: which objects are owned, recorded, owed to
a GC job and still on storage.

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

XuPeng-SH commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 91a15d67fe2f0077c7ad705f7ba11491d3096a18

"interrupted"

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/enhancement kind/refactor Code refactor size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants