Skip to content

refactor(batch): clean up Batch fields; batch owns extraBuf and selection, lenders own pins - #33184

Merged
fengttt merged 21 commits into
matrixorigin:mainfrom
fengttt:batch-cleanup-mp
Nov 25, 2026
Merged

fengttt merged 21 commits into
matrixorigin:mainfrom
fengttt:batch-cleanup-mp

Conversation

@fengttt

@fengttt fengttt commented Nov 24, 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 #33182

What this PR does / why we need it:

The first steps of the Batch cleanup in #33182: remove fields and methods that are not really part of a batch. One commit per change:

  1. Rename extraBufMP to mp. The field is meant to become the pool for all of the batch's own memory allocations.

  2. Drop physicalRows. While a batch is selected, its physical row count is the selection bitmap's length. SetSelection already required sel.Len() == physicalRows, and every producer builds its bitmap that way. SetSelection(physicalRows, sel) becomes SetSelection(sel).

  3. Remove HasAccountedExtraBuffer. Only two tests called it. They already check the allocation account's Used count, which is what actually shows who owns the buffer.

  4. Make extraBuf private and always allocate it from mp.

    • The field is read through ExtraBuf() and set through SetExtraBuf(mp, data), which copies; AdoptExtraBuf(mp, data), which takes over an allocation from mp; or SetAccountedExtraBuffer.
    • Without an allocation account, group writes its partial output through a pool-backed writer instead of a Go-heap bytes.Buffer.
    • Decoding with a pool copies extraBuf into it. Decoding without a pool borrows the input bytes, the same way the decoded vectors already do.
    • The ownership rule: extraBuf is freed through mp, and releasing it keeps mp. A nil mp means the batch owns nothing from a pool, as for a view or a decode with no pool. ViewInto and PhysicalView now clear the view's mp.
    • MoveExtraBufferFrom(source, mp) copies into mp when the source only borrows its buffer. For example, a filter view reaching pSpool used to hand over a borrowed slice, which only stayed valid because the GC kept Go-heap memory alive.
  5. 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, copyBatch would copy all the physical rows but set the selected row count. It now returns an error instead (TestCachedBatchRejectsSelectedBatch).

  6. 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 next Call. Copy only to modify.

  7. The batch gets its own selection storage.

    • Batch gains ownSel and OwnSelection(mp, physicalRows). A batch owns its selection exactly when selection == &ownSel.
    • blockio fills the output batch's own selection. ReaderFilterRequest.PublishSelection becomes a bool, and table_scan drops its bitmap.
    • filter narrows into its output view's own selection, keeps the view across calls instead of zeroing it, and drops its bitmap.
    • projection, evalProjection and ViewInto still borrow.
    • Clean releases the storage. ClearSelection, SetRowCount and CleanOnlyData keep it for the next batch.
    • Since the merge with refactor(bitmap): bitmaps own their words through an mpool #33144 the storage is pool memory (item 11).
  8. 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.

  9. Remove Batch.leases. HoldLease, MoveLeasesFrom, HeldLeases and ReleaseLeases go too.

    • Scan: the scan's ReaderFilterRequest holds the cache pins (Pins). The reader releases them before it reuses the output batch for the next block, and table_scan releases them in Reset and Free.
    • Borrowing is opt-in: only columns explicitly retained in ColumnUses are borrowed. ivfflat keeps its batches, so it now gets owned copies instead of pinning cache entries until its result is freed.
    • Arrow: the reader retains the record a published batch came from until ReleaseBatch, and owns a reusable varlena descriptor scratch (arrowbridge.Descriptors). Convert no longer leases each column; without Descriptors, varlen columns are materialized.
    • sirius: its lease had no release function, so it is removed.
  10. Remove pkg/container/bufferlease. With batches no longer lending memory, only two users were left, and neither needed a generic ref-counted lease.

    • keycodec.KeyPayload is shared by several runtime-filter consumers. It now keeps a private reference count.
    • The scan's cache pins had exactly one holder, so each lease's refcount never did any work. They are now an objectio.CachePins: a plain list of retained cache entries and their capacity reservations. TryBorrowCachedVector and LoadColumnsDataIntoBorrowed take it, and ReaderFilterRequest holds one. The list is reused across blocks, which removes two allocations per borrowed column per block.
  11. 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 from mp and returns an error. When mp changes, it frees the old words first.
    • filter allocates its view's selection from its own pool. blockio allocates the output's selection from OutputAllocation, or from the read pool when there is none.
    • main's DetachNulls is kept for windows that outlive their source batch (the Arrow reader prefix, and the bridge test).
  12. Free the batch's own selection on every release path.

    • Clean, FreeWindow and CleanOwned all free it. The new FreeSelection() covers a batch that is never Cleaned.
    • filter and table_scan Reset free the selection. Nothing reads the output after Reset, so the words go back to the pool of the run that allocated them.
    • filter Set/ClearAllocationAccount count the view's selection as live accounted memory (HoldsSelectionMemory()). main had the same gap with its s.rows.
    • spillView no longer copies ownSel by value.
  13. Reject selected batches in operations on physical rows. The following methods treat every physical row as a real row:

    • Shrink, ShrinkByMask, Shuffle
    • Union, UnionWindow, UnionOne
    • CloneTo (and so Clone/Dup), CloneSelectedColumnsTo
    • Append, AppendWithCopy

    On 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 only Shuffles 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 a bytes.Buffer and 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:

  • TestVarlenWithoutDescriptorsMaterializes and TestDescriptorsReuseColumnBuffer cover the Arrow descriptor scratch. Lease tests now count the request's pins, or release the record after the batch.
  • TestBatchSelectionOwnedOrBorrowed covers producer, forwarder, view, narrower and Clean.
  • batch/extra_buf_test.go covers copying and aliasing in SetExtraBuf; 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 a ViewInto/PhysicalView view; and that every pool ends at CurrNB() == 0.
  • TestUnaccountedStreamingGroupWritesPartialOutputFromPool checks that the partial output without an account is pool memory, survives being moved, and is freed.
  • TestBatchOwnSelectionPool covers reusing the selection storage, switching pools and FreeSelection.
  • TestBatchReleasesFreeOwnSelection checks that Clean, FreeWindow and CleanOwned each free the storage, and that spillView doesn't carry it.
  • TestFilterAccountGuardsSelectionMemory covers the account checks. TestFilterSelectionOutputMatchesCompactedOutput and TestTableScanPublishesReaderSelection now check that Reset frees the selection.
  • TestBatchRowOpsRejectSelectedBatch runs 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.
  • Every fix in items 12 and 13 was checked by reverting it: its test fails without the fix.

Run with the CGo test wrapper; all pass:

  • pkg/container/batch, pkg/container/pSpool
  • pkg/sql/colexec and its filter, projection, table_scan, group, order, top, mergetop, dispatch and connector packages
  • pkg/sql/internal/materialized, pkg/sql/compile, pkg/vm/process, pkg/frontend
  • pkg/vm/engine/tae/blockio, pkg/vm/engine/readutil

The batch, pSpool, group, filter, projection, table_scan and blockio packages also pass under -race. pkg/vm/engine/disttae passes too. After the lease change, all of pkg/container/..., pkg/sql/colexec/..., pkg/vm/..., pkg/vectorindex/..., pkg/objectio/..., pkg/iscp, pkg/cnservice, pkg/iceberg/..., pkg/sql/compile and pkg/frontend pass. arrowbridge, batch, pSpool, external, table_scan, readutil, blockio and cnservice also pass under -race. go build ./... succeeds.

After the merge with #33144 and items 12–13: go build ./... and go vet ./pkg/... are clean. All of pkg/container/..., pkg/sql/colexec/... and pkg/sql/internal/... pass, as do pkg/vm/engine/tae/blockio, pkg/vm/engine/readutil, pkg/vm/engine/disttae, pkg/vm/engine, pkg/vm and pkg/sql/compile. -race was not rerun for these commits.

🤖 Generated with Claude Code

fengttt and others added 3 commits November 24, 2026 14:44
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-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 24, 2026 •

Copy link
Copy Markdown
Contributor

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]>
@fengttt fengttt changed the title refactor(batch): rename extraBufMP to mp, drop physicalRows and HasAccountedExtraBuffer refactor(batch): clean up Batch fields (mp, physicalRows, private pool-owned extraBuf) Nov 24, 2026
@matrix-meow matrix-meow removed the size/S Denotes a PR that changes [10,99] lines label Nov 24, 2026
@matrix-meow matrix-meow added the size/L Denotes a PR that changes [500,999] lines label Nov 24, 2026
@fengttt
fengttt marked this pull request as draft November 24, 2026 23:08
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]>
fengttt and others added 4 commits November 24, 2026 21:34
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]>
@XuPeng-SH

XuPeng-SH commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 6a354c78f09412c1abb3e3e47f5feff213160fad

Review completed. Read the assessment.

@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

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

首次审查 · 请求修改

审查提交为 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()

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.

[P1] 避免全量物化的 Arrow 批次占住上一条记录的读预算。用两条无需切片的 Arrow IPC File 记录导入 BOOL 列时,Arrow bridge 会把该列复制到 MatrixOne 自有向量。这里仍无条件保留第一条记录,随后立即预读下一条。若语句额度足够容纳任一记录及转换输出,却不足以同时保留两条记录和输出,第二次范围申请会报容量错误,首批数据也无法发布。基准版本会在读取第二条前释放第一条的范围。请只为仍引用 Arrow 缓冲区的输出保留记录,或将预读推迟到上一批输出释放之后。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 for ArrowForceMaterialize. With the old unconditional retain, both cases fail with allocation 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.
  • TestExternalArrowRetainsRecordOnlyForBorrowedOutput checks 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

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.

[P2] 示例中的 OwnSelection 缺少 mpool 参数和 error 返回,按原样调用无法编译。实现通过传入的池分配,并在已有容量不足时重新分配。请同步签名、错误处理及 FreeSelection 的生命周期说明。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

fengttt and others added 5 commits November 25, 2026 09:00
…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]>
@fengttt

fengttt commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

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 (pkg/iscp/iteration_tail_group_test.go). Restored in 42b41af. The producer now closes pending tail batches through closePendingTailBatch, a package seam like the other iscp hooks. The test blocks that cleanup, waits for it to start, asserts that the iteration has not returned, and then releases it. Removing the producer join (changeHandelWg.Wait()) now fails both the cancel and incomplete-eof cases.

P2: KeyPayload lost concurrent ownership coverage (pkg/common/hashmap/keycodec). Added TestKeyPayloadConcurrentOwnership in f9be213. In one phase, 128 holders concurrently retain, read and release the payload, and cleanup runs exactly once after the last release. In the other, 64 contenders race Retain against the final release, and no Retain succeeds after cleanup. It passes under -race. It fails if Retain can resurrect a released payload, or if cleanup can run before the last release.

P2/P3: design doc OwnSelection signature and lifecycle. Fixed in 392fe42. Details are in the inline thread.

P2: stale pin comment in table_scan/selection.go. Fixed in 392fe42. The comment now says the scan's ReaderFilterRequest holds the cache pins; the reader releases them before it reuses the output batch, and the scan releases them in Reset and Free. The overlong line is rewrapped.

P2: duplicated, truncated comment above TestBatchRowOpsRejectSelectedBatch. Removed in 392fe42.

Each test was checked against its bug: it fails with the fix reverted. go build ./..., go vet ./pkg/..., golangci-lint and molint are clean. Tests pass for external, iscp, keycodec, batch, arrowbridge, table_scan and filter, and external, iscp, keycodec and batch also pass under -race.

🤖 Generated with Claude Code

This branch was previously deployed

1 inactive deployment
ci — a9b69002 Deployed Nov 25, 2026 by fengttt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

5 participants