Repository navigation
refactor(batch): clean up Batch fields; batch owns extraBuf and selection, lenders own pins - #33184
Conversation
The pool field is meant to become the pool for all of the batch's own memory allocations, not just ExtraBuf. Rename it to mp and document that today it is set only for an accounted ExtraBuf. Issue matrixorigin#33182 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…length While a batch is selected, the vectors' physical row count is the selection bitmap's length: SetSelection already required sel.Len() == physicalRows and every producer builds its bitmap that way. Drop the duplicate field and SetSelection's physicalRows parameter; PhysicalRowCount, ClearSelection and SelectionMask read selection.Len(). Issue matrixorigin#33182 Co-Authored-By: Claude Opus 5.5 <[email protected]>
No production code calls it; only two tests did. Those tests already check the allocation account's Used count, which is the real ownership contract, so drop the assertions (the group test now checks the moved-from batch's ExtraBuf is empty instead). Issue matrixorigin#33182 Co-Authored-By: Claude Opus 5.5 <[email protected]>
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? |
|
This pull request is merged. |
ExtraBuf becomes the private extraBuf, read through ExtraBuf() and set through SetExtraBuf (copy into mp), AdoptExtraBuf (take an allocation from mp) or SetAccountedExtraBuffer. extraBuf is now always pool memory when the batch owns it: - Group writes its partial output through a pooled writer when it has no allocation account, instead of a Go-heap bytes.Buffer. - Decoding with a pool copies extraBuf into it; decoding without a pool borrows the input bytes, as the decoded vectors already do. - releaseExtraBuf frees through mp and keeps mp: the pool belongs to the batch, not to one payload. A nil mp means the batch owns nothing from a pool (a view, or a pool-less decode); views now clear dst.mp. - MoveExtraBufferFrom takes a fallback pool and copies when the source only borrows its payload (for example a filter view reaching pSpool), so the receiver never outlives the real owner's memory. Issue matrixorigin#33182 Co-Authored-By: Claude Opus 5.5 <[email protected]>
checkunsafe forbids importing unsafe in this file; compare the first element addresses instead of unsafe.SliceData. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Port batch-owned selections onto pooled bitmaps (matrixorigin#33144): OwnSelection now takes the pool to allocate from and returns an error; Clean and the new FreeSelection return the words. The filter frees its view's selection in Free, and the blockio reader allocates the output's selection from the output allocation (or the read pool). Keep upstream's DetachNulls for windows that outlive their source batch. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Close the gaps left when batch-owned selections moved onto pooled bitmaps: - FreeWindow and CleanOwned now free the batch's own selection storage (and drop the published selection), not only Clean. - spillView no longer carries a by-value copy of ownSel. - filter Reset frees its view's selection, and Set/ClearAllocationAccount treat those words as live accounted memory. - table_scan Reset frees the reader-published selection in buf. - Add Batch.HoldsSelectionMemory and regression tests for each path; each test fails with its fix reverted. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shrink, ShrinkByMask, Shuffle, Union, UnionWindow, UnionOne, CloneTo (and so Clone/Dup), CloneSelectedColumnsTo, Append and AppendWithCopy read or rewrite physical rows as if they were the logical rows. On a selected batch they left a stale selection or counted excluded rows, silently producing wrong results. They now return an internal error on a selected receiver or source, as the codecs already do; callers compact first. No current caller reaches them with a selection (the reader only publishes one when no orderByLimit is set), so this makes that dependency fail loudly instead of corrupting rows. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Its only caller came from main and was replaced when resolving the merge with matrixorigin#33144; the unused linter fails SCA. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
mo-bot review · Commit: Review completed. Read the assessment. |
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
I reviewed the full diff of #33184 at HEAD 6a354c7 (61 files, +1337/−976) commit by commit against origin/main, including the merged upstream #33144, and re-checked the PR's reviews and inline comments: the PR has no reviews and no inline review comments, so there was nothing raised by other reviewers to defer to and no finding to withdraw as a duplicate. The refactor is internally consistent and I found no blocking correctness, concurrency, or lifetime regression. Key verifications: (1) dropping Batch.physicalRows keeps the invariant, because SetSelection already required sel.Len() to equal the vectors' physical row count and every producer (blockio publishBatchSelection, filter selectionCall, table_scan's published-reader path) sizes its bitmap that way; PhysicalRowCount and ClearSelection preserve their old semantics. (2) The new guards (requireCompacted on Shrink, ShrinkByMask, Shuffle, Union, UnionWindow, UnionOne, CloneTo/Dup/CloneSelectedColumnsTo, Append, AppendWithCopy, and pSpool copyBatch's selection check) can only fire if the selection-edge contract is violated: producers publish only when the parent declares vm.SelectionConsumer, pipeline roots, spool senders, codecs and the remote boundary receive compacted rows; I inventorized callers across operator, frontend, engine and disttae code and every site sits on a path that cannot carry a selection. (3) Moving cache pins from batch leases to ReaderFilterRequest.CachePins preserves pin lifetime: the reader releases them at the next block read after CleanOnlyData, and table_scan releases them in Reset and Free; borrowing is now opt-in (exact-width ColumnUses), so ivfflat and callers without a matching policy get owned copies instead of pinning cache entries for long-lived batches. (4) extraBuf ownership (private field, mp as its pool, copy-on-set, move vs borrow in MoveExtraBufferFrom, nil-mp decode borrowing exactly like the decoded vectors) is sound, the wire format is unchanged, and every release path (Clean, FreeWindow, CleanOwned, FreeSelection, filter and table_scan Reset/Free) returns owned selection words and payload bytes to the pool that allocated them, with the new tests covering these flows plus the allocation-account guards. (5) KeyPayload's private refcount and objectio.CachePins faithfully reproduce the removed bufferlease semantics. Test limitation: I could not execute the focused Go test packages because this checkout lacks the built cgo prerequisites (thirdparties/install with the jemalloc/usearch/roaring headers and libraries is absent, and building them is out of scope for this review); CGO_ENABLED=0 builds of pkg/common/mpool fail for a pre-existing, unrelated reason (no non-cgo stub for malloc.SimpleCAllocator), which I confirmed with recorded compile attempts logged under the review's scratch directory. The verdict therefore rests on static verification plus the author's reported passing runs, including -race for the core packages. The two findings reported are documentation and test-hygiene issues only.
P2 - Stale comment: cache pins attributed to the output batch after ownership moved to the ReaderFilterRequest (pkg/sql/colexec/table_scan/selection.go:26)
The selectionState doc comment still says the reader keeps every borrowed column 'pinned by the scan's output batch until its next CleanOnlyData'. This PR moved pin ownership out of the batch: the pins now live in the scan's ReaderFilterRequest (objectio.CachePins returned by Pins()), are taken by ioutil.LoadColumnsDataIntoBorrowed and TryBorrowCachedVector, and are released by readutil's reader.read (after outBatch.CleanOnlyData) and by tableScan.ctr.readerFilter.ReleasePins() in Reset and Free. The sentence contradicts the contract this same PR documents in pkg/vm/engine/types.go and pkg/vm/engine/tae/blockio/read.go ('the request's owner is the lender'), so a maintainer reading only this comment would expect the batch's lifetime to govern the pins. Line 28 is also an un-wrapped overlong line leftover from the same edit. Comment-only; no code behavior affected.
P2 - Duplicated truncated comment block left above TestBatchRowOpsRejectSelectedBatch (pkg/container/batch/selection_test.go:214)
Lines 214-215 contain a copy of the comment 'Operations that read or rewrite physical rows as the logical rows reject a selected batch on either side and leave it unchanged: the selection would' that is cut off mid-sentence, immediately followed by the real, identical comment at lines 217-220 for TestBatchRowOpsRejectSelectedBatch. It is a leftover from editing commit e92227a ('fix(batch): reject selected batches in physical-row operations'). Cosmetic test-file hygiene only: it compiles and does not affect behavior or coverage.
iamlinjunhong
left a comment
There was a problem hiding this comment.
首次审查 · 请求修改
审查提交为 6a354c78f09412c1abb3e3e47f5feff213160fad,对照 Batch cleanup #33182 和目标分支基准 2b8debdd5f9da4efabc4f9e9a94a9777e423a32e。
- [P1]
pkg/sql/colexec/external/reader_arrow.go:638— 全量物化的 Arrow 批次仍保留原记录,预读可能拒绝本可完成的导入。例如,Arrow IPC File 含两条无需切片的记录,目标仅为 BOOL 列。BOOL 转换会复制到 MatrixOne 自有向量,基准版本在预读前会释放上一记录和消息对范围的引用。当前版本无条件保留第一条记录,再为第二条申请同一语句的额度。当额度覆盖任一记录及转换输出、但小于两条记录与输出之和时,读取失败,首批结果也无法发布。保留记录前应检查最终输出是否仍引用其缓冲区,或将预读延后到上一批释放之后。 - [P2]
docs/design/20261124-row-selection-bitmap-remaplist.md:84— 文档中的OwnSelection(physicalRows int) *bitmap.Bitmap无法按示例调用。当前签名是OwnSelection(mp *mpool.MPool, physicalRows int) (*bitmap.Bitmap, error),复用以同一池且已有容量充足为前提。请同时同步错误处理和FreeSelection的生命周期说明。
Loom 快照中的 34 项检查均已结束,其中 15 项通过、17 项跳过、2 项为 neutral,0 项失败。CI Required 通过。 CI 运行
本轮通过基准与当前源码的调用链对照核实上述发现,未运行本地定向测试。交付差异的原始产物检查通过。快照中没有历史 review 或 inline 线程,因此跳过上轮意见和作者回复核对。
| } | ||
| // The batch borrows record's buffers. Retain it before advancing: the IPC | ||
| // reader releases its current record at the next Next call. | ||
| record.Retain() |
There was a problem hiding this comment.
[P1] 避免全量物化的 Arrow 批次占住上一条记录的读预算。用两条无需切片的 Arrow IPC File 记录导入 BOOL 列时,Arrow bridge 会把该列复制到 MatrixOne 自有向量。这里仍无条件保留第一条记录,随后立即预读下一条。若语句额度足够容纳任一记录及转换输出,却不足以同时保留两条记录和输出,第二次范围申请会报容量错误,首批数据也无法发布。基准版本会在读取第二条前释放第一条的范围。请只为仍引用 Arrow 缓冲区的输出保留记录,或将预读推迟到上一批输出释放之后。
There was a problem hiding this comment.
Fixed in b1bb6c3. The reader now retains the record only when the published batch borrows from it, meaning it has a read-only vector. The bridge points into Arrow memory only through those vectors (borrowed fixed-width values and borrowed varlen areas); materialized vectors and every null bitmap are pool copies. A fully materialized batch, such as BOOL or Date32 -> DATE, leaves the record to the IPC reader, which releases it before the next record's range is admitted. A borrowed batch still holds its record across the read-ahead, as on main.
Tests:
TestExternalArrowMaterializedImportFitsOneRecordBudget(2b4b814) reproduces this failure. It runs a three-record import under an account limit equal to the peak of a one-record import of the same shape, for Date32 -> DATE and forArrowForceMaterialize. With the old unconditional retain, both cases fail withallocation account capacity exceeded. With the fix, the materialized peak is the same for 1, 2 and 3 records (512 bytes here), compared with 816 before.TestExternalArrowRetainsRecordOnlyForBorrowedOutputchecks the mechanism: whether the record is retained, and the pinned range bytes after the read-ahead (one record for a materialized batch, two for a borrowed one).
| // OwnSelection returns the batch's own selection storage, cleared and sized to | ||
| // physicalRows. The caller fills it (or copies an input selection into it and | ||
| // narrows it) and then publishes it with SetSelection. | ||
| func (bat *Batch) OwnSelection(physicalRows int) *bitmap.Bitmap |
There was a problem hiding this comment.
[P2] 示例中的 OwnSelection 缺少 mpool 参数和 error 返回,按原样调用无法编译。实现通过传入的池分配,并在已有容量不足时重新分配。请同步签名、错误处理及 FreeSelection 的生命周期说明。
There was a problem hiding this comment.
Fixed in 392fe42. The design doc now shows OwnSelection(mp *mpool.MPool, physicalRows int) (*bitmap.Bitmap, error) with an error-handling example. It says that words are cleared and reused when the same pool is passed and their capacity covers the new row count, and that otherwise they are reallocated from the pool; a different pool first frees the old words. It also documents FreeSelection and HoldsSelectionMemory, the release paths (Clean, FreeWindow, CleanOwned), freeing in Reset, and the allocation-account checks.
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 6a354c78f09412c1abb3e3e47f5feff213160fad
Assessment: request_changes
The refactor removes shared lease machinery by assigning lifetimes to existing batch and reader owners. The Arrow reader, however, retains source records even when the output is fully materialized, causing avoidable account-capacity failures. The change also removes two distinct concurrency regression oracles. The prior review’s Arrow finding is supported; the review that found no blocking lifetime regression did not cover this materialized-output boundary.
Model: gpt-6.1-terra / max
Session: 01a21136-dc54-7ba1-aace-4039c02570be · slot 2 · generation 3
-
P1
pkg/sql/colexec/external/reader_arrow.go:638: An Arrow IPC file contains consecutive records whose output columns are fully materialized, such as Date32 converted to MatrixOne DATE, and the statement account can hold one record and its converted output but not an unnecessarily retained record plus the next read.
Impact: The reader retains the first record and immediately advances before publishing its converted batch. The next range admission can exhaust the statement account, so an import that could process the records sequentially fails before returning the first batch.
Evidence: For the same two-record Date32 fixture, the frozen head required a minimum account limit of 24,864 bytes; a control that retains the record only when the final output has borrowed vectors required 20,624 bytes. See attempt-1/arrow-default-candidate.log and attempt-2/arrow-controls.log, with receipts checks/1795599420173219591-2.json and checks/1795600656930922298-2.json in their respective attempts. The baseline retained ArrayData only for borrowed columns. Retain the record only when the published output references it, or defer advancing until the prior output is released, while preserving borrowed-vector lifetimes. -
P2
pkg/iscp/iteration_tail_group_test.go:229: The iteration ends or is canceled while a pending tail batch is still being cleaned by its producer.
Impact: The replacement test no longer holds cleanup open and checks that iteration cannot return during it. Checking pool usage after completion can pass if cleanup happens to win the scheduling race even if the producer join is removed. This loses the deterministic regression protection for returning only after pending cleanup; no current production failure is established.
Evidence: The removed test blocked the lease release, waited for cleanup to start, asserted that iteration had not returned, and then released it. The new test only waits for done and samples CurrNB. The production ordering remains significant: pending batches are closed in the producer defer at pkg/iscp/iteration.go:550, and the caller joins that producer at line 736. Restore a deterministic blocked-producer or cleanup-phase oracle using the existing fake source or an equivalent controllable seam. -
P2
pkg/common/hashmap/keycodec/key_payload.go:61: Runtime-filter consumers concurrently retain and release the same KeyPayload.
Impact: The new private reference-count implementation replaces a generic lease whose maintained tests covered concurrent holders and final cleanup, but the remaining KeyPayload tests exercise Retain and Release sequentially. A future regression in this shared ownership transition could release backing too early or more than once without that distinct concurrency oracle. The current implementation passed the retained temporary race probe; this is a test-coverage gap, not a demonstrated current race.
Evidence: The deleted pkg/container/bufferlease/lease_test.go contained TestRefCountedConcurrentLastRelease; pkg/common/hashmap/keycodec/key_payload_test.go:49 exercises the replacement sequentially. The same-head temporary TestReviewKeyPayloadConcurrentOwnership passed under -race in attempt-1/key-payload-race.log and receipt checks/1795598216319021326-2.json. Preserve a small owner-specific concurrent test that checks exactly-once cleanup and rejects resurrection after final release. -
P3
docs/design/20261124-row-selection-bitmap-remaplist.md:84: A maintainer follows the design document’s stated batch-selection API and lifecycle when implementing another producer or reusable view.
Impact: The declaration omits the pool argument and error result, and the surrounding text does not describe FreeSelection for an owning view. It therefore gives an unusable API and an incomplete cleanup contract for pool-backed selection storage.
Evidence: The implementation at pkg/container/batch/selection.go:46 is OwnSelection(mp, physicalRows) (*bitmap.Bitmap, error), and FreeSelection at line 64 releases storage for batches or views that are not Cleaned. Update the design example, allocation-error handling and lifecycle description to match those operations.
Validation:
-
Reviewed the complete frozen delta, pinned repository review policy and applicable lifecycle, testing and compatibility guidance, linked issue, and all eight discussion entries. Their dispositions are recorded in attempt-2/discussion-assessment.json.
-
Reused same-head receipt-backed focused tests from attempt 1 for batch selection and extra buffers, spool copying, KeyPayload, scan/filter/blockio, Arrow bridge and group wire compatibility. The retained KeyPayload concurrency probe also passed under -race.
-
The current attempt’s private /tmp and loopback preflight, frozen diff check and native-input provenance check passed. The paired Arrow controls passed using the assigned executor; attempt-2/arrow-controls.log and checks/1795600656930922298-2.json record both selected tests.
-
The supplied head CI snapshot reports successful shared build, Ubuntu/x86 unit and coverage jobs, and multi-CN proxy and pessimistic BVT jobs.
Limitations:
-
The Arrow comparison exercises the external operator with an in-memory file service and a narrowly modified head control; it is not a SQL frontend test or an independently built base binary. The baseline behavior was checked in source.
-
An earlier Arrow control timed out and was not counted as a pass; the matching control completed in attempt 2. The author-reported broader local and race runs were not independently reproduced.
…om it convertNext retained the source record for every published batch and then read ahead to the next record. A fully materialized batch (no borrowed column) references none of the record's buffers, so that retain only kept its range admitted beside the next record's, and an import that fits one record at a time could fail the statement account before publishing. The reader owns the record's lifetime: it now retains it only when the published batch has a read-only (borrowed) vector. The bridge aliases Arrow memory only in those vectors; materialized vectors and every null bitmap are pool copies. TestExternalArrowRetainsRecordOnlyForBorrowedOutput checks both the retained record and the pinned range bytes; each check fails on its own with the unconditional retain. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The lease-based test blocked cleanup and asserted the iteration could not return during it; its replacement only sampled pool usage after return, which passes whenever cleanup wins the race. Route the producer's pending tail close through closePendingTailBatch (a package seam, like the other iscp hooks) so the test can hold cleanup open again. Removing the producer join now fails the test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Replaces the concurrent coverage lost with bufferlease's lease tests: concurrent holders read the payload and release it, cleanup runs exactly once after the last release, and no Retain succeeds after cleanup. Passes under -race; fails if Retain can resurrect or cleanup can run early. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Design doc: OwnSelection(mp, physicalRows) returns an error; document word reuse within a pool, FreeSelection, Reset freeing, the account checks, the selected-batch guards, and the Arrow reader retaining a record only for borrowed output. - table_scan: cache pins belong to the ReaderFilterRequest, not the output batch. - batch test: drop a duplicated, truncated comment. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reproduces the review's failure directly: an import whose output is fully materialized must complete under an account limit equal to the peak of a one-record import of the same shape. Covers Date32 -> DATE (always materialized) and ArrowForceMaterialize. With the record retained unconditionally, both cases fail with "allocation account capacity exceeded". Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Addressed the review findings at 2b4b814: P1: Arrow reader retains records that a materialized batch doesn't borrow (two reviews). Fixed in b1bb6c3, with a regression test in 2b4b814. Details are in the inline thread. P2: iscp lost its deterministic pending-tail cleanup oracle ( P2: KeyPayload lost concurrent ownership coverage ( P2/P3: design doc P2: stale pin comment in P2: duplicated, truncated comment above Each test was checked against its bug: it fails with the fix reverted. 🤖 Generated with Claude Code |
What type of PR is this?
Which issue(s) this PR fixes:
Issue #33182
What this PR does / why we need it:
The first steps of the
Batchcleanup in #33182: remove fields and methods that are not really part of a batch. One commit per change:Rename
extraBufMPtomp. The field is meant to become the pool for all of the batch's own memory allocations.Drop
physicalRows. While a batch is selected, its physical row count is the selection bitmap's length.SetSelectionalready requiredsel.Len() == physicalRows, and every producer builds its bitmap that way.SetSelection(physicalRows, sel)becomesSetSelection(sel).Remove
HasAccountedExtraBuffer. Only two tests called it. They already check the allocation account'sUsedcount, which is what actually shows who owns the buffer.Make
extraBufprivate and always allocate it frommp.ExtraBuf()and set throughSetExtraBuf(mp, data), which copies;AdoptExtraBuf(mp, data), which takes over an allocation frommp; orSetAccountedExtraBuffer.bytes.Buffer.extraBufinto it. Decoding without a pool borrows the input bytes, the same way the decoded vectors already do.extraBufis freed throughmp, and releasing it keepsmp. A nilmpmeans the batch owns nothing from a pool, as for a view or a decode with no pool.ViewIntoandPhysicalViewnow clear the view'smp.MoveExtraBufferFrom(source, mp)copies intompwhen the source only borrows its buffer. For example, a filter view reachingpSpoolused to hand over a borrowed slice, which only stayed valid because the GC kept Go-heap memory alive.pSpool rejects a selected batch. A selection is borrowed for one operator edge, and pipeline roots always compact (
vm.ConfigureSelectionEdges), so a selected batch should never reach a spool. If one did,copyBatchwould copy all the physical rows but set the selected row count. It now returns an error instead (TestCachedBatchRejectsSelectedBatch).Design doc: a batch's selection is owned or borrowed, like its vectors. Revises
docs/design/20261124-row-selection-bitmap-remaplist.md. The selection's storage moves from the producing operator into the batch. A producer, or a consumer that narrows a selection, fills its output batch's own storage. A forwarder and every view borrow the input's bitmap until the producer's nextCall. Copy only to modify.The batch gets its own selection storage.
BatchgainsownSelandOwnSelection(mp, physicalRows). A batch owns its selection exactly whenselection == &ownSel.ReaderFilterRequest.PublishSelectionbecomes abool, and table_scan drops its bitmap.ViewIntostill borrow.Cleanreleases the storage.ClearSelection,SetRowCountandCleanOnlyDatakeep it for the next batch.Design doc: the lender keeps borrowed memory alive; batches hold no leases. A borrowed vector is valid until its producer's next
Call. Memory the producer owns needs no lease. Only memory from a shared resource, such as the FileService cache, is pinned, and the producer holds the pins.Remove
Batch.leases.HoldLease,MoveLeasesFrom,HeldLeasesandReleaseLeasesgo too.ReaderFilterRequestholds the cache pins (Pins). The reader releases them before it reuses the output batch for the next block, and table_scan releases them inResetandFree.ColumnUsesare borrowed. ivfflat keeps its batches, so it now gets owned copies instead of pinning cache entries until its result is freed.ReleaseBatch, and owns a reusable varlena descriptor scratch (arrowbridge.Descriptors).Convertno longer leases each column; withoutDescriptors, varlen columns are materialized.Remove
pkg/container/bufferlease. With batches no longer lending memory, only two users were left, and neither needed a generic ref-counted lease.keycodec.KeyPayloadis shared by several runtime-filter consumers. It now keeps a private reference count.objectio.CachePins: a plain list of retained cache entries and their capacity reservations.TryBorrowCachedVectorandLoadColumnsDataIntoBorrowedtake it, andReaderFilterRequestholds one. The list is reused across blocks, which removes two allocations per borrowed column per block.Merge with refactor(bitmap): bitmaps own their words through an mpool #33144 (bitmaps own their words through an mpool). This PR keeps its model, where the batch owns its selection, and moves that onto pooled bitmaps instead of taking main's lender-owned
PublishSelection *Bitmap.OwnSelection(mp, physicalRows)allocates frommpand returns an error. Whenmpchanges, it frees the old words first.OutputAllocation, or from the read pool when there is none.DetachNullsis kept for windows that outlive their source batch (the Arrow reader prefix, and the bridge test).Free the batch's own selection on every release path.
Clean,FreeWindowandCleanOwnedall free it. The newFreeSelection()covers a batch that is neverCleaned.Resetfree the selection. Nothing reads the output afterReset, so the words go back to the pool of the run that allocated them.Set/ClearAllocationAccountcount the view's selection as live accounted memory (HoldsSelectionMemory()). main had the same gap with itss.rows.spillViewno longer copiesownSelby value.Reject selected batches in operations on physical rows. The following methods treat every physical row as a real row:
Shrink,ShrinkByMask,ShuffleUnion,UnionWindow,UnionOneCloneTo(and soClone/Dup),CloneSelectedColumnsToAppend,AppendWithCopyOn a selected batch they left the selection stale or counted rows it excludes, and the result was silently wrong. They now return an internal error when either batch has a selection, as the codecs already do. No current caller reaches them with a selection: blockio publishes one only when there is no
orderByLimit, and readutil onlyShuffles in-memory batches, which never carry one. The guards turn that unstated dependency into a loud failure.Performance. Pins last exactly as long as before, just in the request instead of the batch. The Arrow reader now allocates one descriptor buffer per varlen column and reuses it, instead of one per batch. ivfflat copies the columns it used to borrow. Only group's partial output carries an
extraBuf, at one buffer per batch. The accounted path is unchanged. Without an account, the pool-backed writer replaces abytes.Bufferand grows the same way. Decoding copies once, as it did before, but into the pool instead of the Go heap.Investigated and kept:
Attrs: the storage and transaction layers depend on column names, and so does the batch wire format. Removing it is a multi-PR follow-up.Tests
New tests:
TestVarlenWithoutDescriptorsMaterializesandTestDescriptorsReuseColumnBuffercover the Arrow descriptor scratch. Lease tests now count the request's pins, or release the record after the batch.TestBatchSelectionOwnedOrBorrowedcovers producer, forwarder, view, narrower andClean.batch/extra_buf_test.gocovers copying and aliasing inSetExtraBuf; decoding with and without a pool, from bytes and from a reader; decoding over a buffer owned by another pool; moving from an owner versus from aViewInto/PhysicalViewview; and that every pool ends atCurrNB() == 0.TestUnaccountedStreamingGroupWritesPartialOutputFromPoolchecks that the partial output without an account is pool memory, survives being moved, and is freed.TestBatchOwnSelectionPoolcovers reusing the selection storage, switching pools andFreeSelection.TestBatchReleasesFreeOwnSelectionchecks thatClean,FreeWindowandCleanOwnedeach free the storage, and thatspillViewdoesn't carry it.TestFilterAccountGuardsSelectionMemorycovers the account checks.TestFilterSelectionOutputMatchesCompactedOutputandTestTableScanPublishesReaderSelectionnow check thatResetfrees the selection.TestBatchRowOpsRejectSelectedBatchruns each guarded method with a selection on either side. It checks the error, and that the batch's selection, row count and vector length are unchanged and no memory is left allocated.Run with the CGo test wrapper; all pass:
pkg/container/batch,pkg/container/pSpoolpkg/sql/colexecand itsfilter,projection,table_scan,group,order,top,mergetop,dispatchandconnectorpackagespkg/sql/internal/materialized,pkg/sql/compile,pkg/vm/process,pkg/frontendpkg/vm/engine/tae/blockio,pkg/vm/engine/readutilThe
batch,pSpool,group,filter,projection,table_scanandblockiopackages also pass under-race.pkg/vm/engine/disttaepasses too. After the lease change, all ofpkg/container/...,pkg/sql/colexec/...,pkg/vm/...,pkg/vectorindex/...,pkg/objectio/...,pkg/iscp,pkg/cnservice,pkg/iceberg/...,pkg/sql/compileandpkg/frontendpass.arrowbridge,batch,pSpool,external,table_scan,readutil,blockioandcnservicealso pass under-race.go build ./...succeeds.After the merge with #33144 and items 12–13:
go build ./...andgo vet ./pkg/...are clean. All ofpkg/container/...,pkg/sql/colexec/...andpkg/sql/internal/...pass, as dopkg/vm/engine/tae/blockio,pkg/vm/engine/readutil,pkg/vm/engine/disttae,pkg/vm/engine,pkg/vmandpkg/sql/compile.-racewas not rerun for these commits.🤖 Generated with Claude Code