Skip to content

refactor(bitmap): bitmaps own their words through an mpool - #33144

Merged
fengttt merged 8 commits into
matrixorigin:mainfrom
fengttt:bitmap-mpool-ownership
Nov 25, 2026
Merged

fengttt merged 8 commits into
matrixorigin:mainfrom
fengttt:bitmap-mpool-ownership

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

What this PR does / why we need it:

What

A bitmap.Bitmap now carries the mpool.MPool that owns its words. Words are allocated off-heap from that pool and returned by Free. A bitmap without a pool is read-only: every write panics (bitmap.ErrReadOnly) and growth returns an error.

This lets a cached (read-only) vector reference its encoded null bitmap without the defensive bytes.Clone, and makes a write to such a bitmap fail loudly instead of corrupting the FileService cache. Null bitmaps are now also counted in pool and allocation-account accounting.

Bitmap and nulls

  • Ownership: Init(mp), Free(), MPool() and IsReadOnly(). Reset() frees and keeps the pool. Swap moves the pool along with the words.
  • Pool-taking constructors: InitWithSize, InitWith, Clone, Filter, InitWithRows and InitWithInvertedBits take a pool and return an error.
  • Growth: Reserve and TryExpand* grow from the bitmap's own pool and return errors. In-place writers that may grow (Nulls.Add/Set/AddRange/Or) panic with the pool's error.
  • Views: InitView(src, start, end) makes a zero-copy read-only view with a bit shift. Reads of read-only bitmaps go through a word accessor that applies the shift and masks at Len. Marshal and WordsCovering (C) write clean, unshifted words.
  • Decoding: Unmarshal copies into the pool when there is one and references the bytes otherwise. UnmarshalNoCopy always references.

Vector

  • Null bitmap ownership: the null bitmap uses the vector's pool, and Vector.Free releases it.
  • Window: NULLs are a view of the source's bitmap, so nothing is copied.
  • Read-only decode: references the null bytes; the bytes.Clone is gone.
  • Stream decode: reads straight into pool words, making one copy instead of two.
  • DetachNulls(mp): gives a window that must outlive its source (the Arrow stable prefix, whose lease moves) its own copy.
  • Function results: a nullable result reserves NULL capacity when it is prepared, so an admission failure is an error rather than a panic inside an in-place write. Results proven to emit no NULLs reserve nothing.
  • ResetWithSameType: keeps the bitmap's words for reuse, like data capacity.

Callers

Every bitmap user now has a pool and a matching Free:

  • bloom filters, including the GC coarse filter, which returns a release function
  • TAE batch deletes (windows get views; Close/Reset/CleanOnlyData/Compact release them), RowSelection.Holes (with Release), dedup "maybe present" rows, persisted and visibility deletes
  • objectio's bitmap pool (Release frees non-pooled bitmaps)
  • hash, dedup, right-dedup and loop join matched bitmaps, plus their worker-to-merger mailboxes
  • the join map's delete rows and the hash-build dedup bitmaps
  • filter and table-scan selections, and deletion and multi-update per-block bitmaps
  • the integer IN operator, now registered with a free hook
  • function-framework temporaries

The unused tae/compute.ShuffleByDeletes is removed.

Behavior changes

  • Memory is now charged: NULL bitmaps count against pools and allocation accounts. A nullable function result keeps ceil(rows/64) words reserved (about 1 KiB per 8192 rows).
  • No length stretch: an in-place filter (FilterInPlaceOrdered, FilterByMaskWithOffset) no longer grows the bitmap's logical length to the new row count. Rows past Len already read as not-NULL, and only Dup's capacity sizing reads the length (it takes the max with the vector length).

Bugs found on the way

  • Arrow use-after-free: the Arrow stable prefix kept window null views of a batch it then cleaned. Fixed with DetachNulls.
  • Multi-update leak: a delete bitmap was dropped when its block was flushed.

Testing

  • New tests:
    • Bitmap ownership: the pool drains to zero, and every write method panics on a read-only bitmap.
    • Decoding copies into the pool or references the bytes, as intended.
    • About 480 random view shapes are compared against owned copies.
    • Vector windows are zero-copy null views, and a read-only decode shares the null bytes.
  • Full ./pkg/... unit suite: 412 packages pass. The three failures are unrelated:
    • util/metric/v2/dashboard needs Grafana on localhost:80.
    • TestWriteSkewIsAllowed and TestTaskSchedulerExpiresLostRunnerWithoutReplay are cluster-timing flakes under load; both pass alone.
    • TestMoCtlUseSnapshot also failed in an earlier full run, and fails identically on clean main.
  • golangci-lint: clean on the changed packages.

Gobra verification

  • The proofs are re-done for the new model. bitmap.go and nulls.go are verified against the pool-owned contracts:
    • bitmap_mem.gobra specifies the trusted memory primitives (allocWords, replaceWords, Free, prepareInit, mustWrite), with an mpool stub.
    • Inv now implies an owned bitmap. The verified methods' branches into the read-only/view code (bitmap_view.go) are proven dead.
  • Results:
    • Bitmap: all 63 per-member Gobra runs verify.
    • Nulls: 0 errors.
    • Vacuity check: injecting assert false at the entry and exit of each changed function makes it fail, in both packages.
  • Bounded memory: both gobra/verify.sh scripts cap each Gobra JVM at 2 GB (GOBRA_JAVA_OPTS), and the bitmap script sizes VERIFY_JOBS from available memory. Uncapped JVMs grow to a quarter of RAM, and parallel runs exhausted a 61 GB machine.

Leak review fixes

A codebase-wide review of bitmap/nulls ownership found:

  • objectio.BitmapPool regression: a Get with no free slot allocates a bitmap outside the pool, and its Put dropped it without Free. That was harmless when bitmaps were GC-backed; with pool-owned bitmaps it leaked. It is now freed through the pool's finallyFunc.
  • TAE baseObject.Scan / HybridScanByBlock: a partly built batch (vectors and Deletes) leaked on error. On some errors the batch was closed but still handed back, and ReadMergeSettingsBatch then used it. Now a batch the call is responsible for is closed and set to nil on error. A caller's batch is left alone on errors before the scan.
  • pnode.Scan: vectors not yet in the batch are closed on its two error paths.
  • frontend convertRowsIntoBatchInLocation: earlier columns' vectors and nulls leaked when a later column failed. They are now cleaned.
  • batch.OwnReadOnlyVectors: replaced originals are freed also when a later Dup fails. A read-only vector can own its nulls (Arrow validity, DetachNulls).
  • Hardening:
    • vector.WindowInto rejects a target that owns its nulls.
    • blockio releases a discarded objectio.Bitmap.
    • hashbuild frees IgnoreRows before reallocating.
    • The unused anode.FillBlockView, which aliased a delete bitmap into another batch, is removed.

Known but not changed:

  • leaks only on panic paths in hash/dedup join and index_util;
  • bloomfilter.Clean ignores the reference count (no production sharing today);
  • nulls.Or frees reserved capacity when both inputs are empty (changing it needs re-verification);
  • the TAE vector wrapper does not free a read-only vector's owned nulls.

Leak-fix tests

Each test fails on the code before its fix:

  • TestBitmapPoolOverflowReleaseFrees
  • TestHybridScanByBlockClosesBatchWhenScanFails
  • TestHybridScanByBlockClosesBatchWhenTombstonesFail
  • TestHybridScanByBlockKeepsCallerBatchBeforeScan
  • TestOwnReadOnlyVectorsFreesReplacedOnDupError
  • TestWindowIntoRejectsTargetOwningNulls
  • Test_convertRowsIntoBatchFreesPartialBatchOnError

The two pnode.Scan error branches have no test: they need a persisted object with a compat column plus an allocation failure.

Docs

The mo-dev skill gains references/bitmap-memory.md and a G-BITMAP gate. Every bitmap is in one of three states:

  • owned by a Vector;
  • read-only (mp == nil), and never outliving its source;
  • owned by a named component that Frees it on every exit path.

Not done

  • No BVT run yet.

🤖 Generated with Claude Code

A bitmap now carries the pool that owns its words. Words are allocated
off-heap from that pool and returned by Free; Reset frees them too and
keeps the pool. A bitmap without a pool is read-only: every write panics
and growth returns an error. Creating functions (InitWithSize, InitWith,
Clone, Filter, InitWithRows, InitWithInvertedBits) take the pool and
return errors.

InitView makes a zero-copy, read-only view of a bitmap's rows with a bit
shift. Readers of read-only bitmaps mask at Len, so a view sharing a word
with later rows never exposes them; Marshal and the C word accessors
write clean, unshifted words.

Vectors: the null bitmap uses the vector's pool and Vector.Free releases
it. Window's nulls are a view of the source's bitmap instead of a Go-heap
copy, a read-only decode references the encoded null bytes instead of
cloning them, and the stream decoder reads straight into pool words.
DetachNulls gives a window that must outlive its source (an Arrow prefix
whose lease moves) its own copy. A nullable function result reserves its
null capacity when it is prepared, so an admission failure is an error
rather than a panic in an in-place write. ResetWithSameType keeps the
bitmap's words for reuse.

Every bitmap user now has a pool and a matching Free: bloom filters, TAE
batch deletes (windows get views), row selections and dedup bitmaps,
objectio's bitmap pool, join matched bitmaps and their mailboxes, the
join map's delete rows, filter and table-scan selections, deletion and
multi-update block bitmaps, the integer IN operator (now with a free
hook) and function temporaries.

The unused tae/compute.ShuffleByDeletes is removed. Tests that pinned
"null bitmaps are Go-owned and uncharged" now assert that they are
charged and that accounts drain to zero.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt and others added 2 commits November 24, 2026 10:03
Resolve conflicts with matrixorigin#33115 (vector test consolidation) and
matrixorigin#33127/matrixorigin#33133 (dedupjoin captured-vector owner pool): carry the
read-only-NULL fixture to minmax_test.go, keep the pool-owned bitmap
tests in mpool_test.go, and free both the captured vectors (with their
owner pool) and the worker's matched/captured bitmaps in
freeWorkerJoinMsg. Port upstream's new tests to the pool-taking
bitmap API.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- bitmap_mem.go: use util.UnsafeSliceCast for the word/byte views, as
  molint checkunsafe forbids importing unsafe in this file (SCA).
- TestChaos1 read view.Deletes after view.Compact(), which now releases
  the deletes bitmap, so the count was always 0. Count first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Gobra:
- bitmap core: all 63 per-member runs verify; nulls verifies against the
  new pool-owned bitmap contracts (bitmap_mem.gobra, mpool stub).
- verify.sh caps each Gobra JVM at 2 GB (GOBRA_JAVA_OPTS) and sizes
  VERIFY_JOBS from available memory, so parallel runs no longer exhaust RAM.

Leak review fixes:
- objectio.BitmapPool: free bitmaps allocated on pool overflow (regression
  from pool-owned bitmaps); test proves the pool returns to baseline.
- tae Scan/HybridScanByBlock: close a partly built batch on error; fixes a
  use of a closed batch in ReadMergeSettingsBatch.
- frontend convertRowsIntoBatchInLocation, batch.OwnReadOnlyVectors: free
  partial results on error.
- blockio: release a discarded bitmap; hashbuild: free IgnoreRows before
  reallocating; vector.WindowInto rejects a target owning its nulls;
  remove unused anode.FillBlockView (aliased delete bitmap).

Docs: mo-dev skill reference bitmap-memory.md (ownership model, G-BITMAP).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- HybridScanByBlock: a Scan failure and a tombstone failure close the
  partly built batch and return nil; an error before Scan keeps the
  caller's batch. baseObject.Scan and HybridScanByBlock share
  closeBatchOnError.
- batch.OwnReadOnlyVectors frees the replaced originals (one owning its
  nulls) when a later Dup fails.
- vector.WindowInto rejects a read-only target that owns its nulls.
- frontend convertRowsIntoBatch frees earlier columns when a later one
  fails to convert.

Each test fails on the code before the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fengttt
fengttt marked this pull request as ready for review November 24, 2026 21:48
@XuPeng-SH

XuPeng-SH commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: bfb7551d5e7a73cfb524c070d3ce6f0e3db9ba9c

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

Reviewed the full three-dot diff (3,915 additions across 105 files) of PR #33144 plus the PR conversation; no prior reviewer reviews or inline threads exist (only bot comments), so no findings were withheld for duplication and no prior evidence had to be weighed. The PR moves bitmap/nulls words under mpool ownership, adds a read-only state enforced by panics, makes window nulls zero-copy views with a bit shift, drops the defensive bytes.Clone in read-only vector decode, and converts every caller. Verified from first principles: every mutating Bitmap entry point (Add, AddMany, Remove, AddRange, RemoveRange, Or, OrBounded, And, Negate, Clear, both Remap families) calls mustWrite, so a write to a cached vector's null bitmap fails loudly instead of reaching FileService memory. Read paths of read-only bitmaps dispatch to shifted/lword readers that mask at Len, liveWords masks the tail, and Marshal/WordsCovering emit clean unshifted words. The zero-fill-on-grow invariant holds because allocWords clears the whole class-sized region and TryExpandWithSize re-zeroes newly exposed capacity words, so reused and re-extended storage never leaks stale set bits. Pool mechanics are correct: words come from mpool.Alloc with the block identity at data[:1] for Free; prepareInit enforces pool stickiness; Swap carries pool and shift; Free is nil-safe and per-struct idempotent; grep found no by-value copies of Bitmap/Nulls outside tests, so each word block has exactly one owner. Caller audits hold up: objectio's bitmap pool now frees overflow allocations via finallyFunc, all FindTombstonesOfObject/CoarseFilter/GC/bloom-filter/RowSelection/TAE scan error paths free exactly once (loop-defers are closures), the multi-update delete-bitmap leak and the Arrow stable-prefix use-after-free are fixed with tests the author shows fail pre-fix, and Deletion/hashbuild/join/mailbox bitmaps have matching frees. The removal of filter length stretching is contained: only Vector.dup reads Nulls.Len and it takes the max with vector length; rows past Len read as non-null everywhere else, including the C (ptr,len) consumers. Failed growth surfaces as errors at reserved boundaries (nullable function results, PreExtendNulls, Range, Filter) and as panics only for in-place writers, which is the documented contract. Local test execution was blocked: make ut's cgo prerequisite (thirdparties/install jemalloc headers) is absent in this checkout and building it is out of scope for this review; CGO_ENABLED=0 is separately blocked by a pre-existing mpool SimpleCAllocator gap unrelated to this PR (mpool/malloc untouched). The review is therefore static, corroborated by the green upstream UT and BVT check runs on this head. Conclusion: the refactor is sound and internally consistent, with one non-blocking contract gap reported below at the native CXCall boundary.

P2 - CXCall still hands shifted window nulls to bitmap.Ptr, which now panics (pkg/container/vector/vector.go:8353)

Vector.FillRawPtrLen (pkg/container/vector/vector.go:8349-8357) exposes a vector's null bitmap to native kernels through nulls.Ptr, which returns bitmap.Bitmap.Ptr (pkg/common/bitmap/bitmap_ext.go:84-92). This PR made Ptr panic with 'bitmap Ptr on a shifted view; use WordsCovering' whenever the bitmap is a view whose window start is not 64-aligned, whereas before the PR every window carried a private copied null bitmap, so the raw (ptr, len) pair worked for any window. Windowed vectors are handed downstream at arbitrary row offsets throughout colexec (for example pkg/sql/colexec/partition/hash.go:148, pkg/sql/colexec/mergeorder/batch_sort.go:335, pkg/sql/colexec/spillutil/join_spill.go:992), and the _xc L2-distance overloads push their argument vectors through c_xcall into FillRawPtrLen (pkg/sql/plan/function/cxcall.go:72-74). If such an argument arrives with a non-64-aligned window whose view nulls hold set bits, the query now panics instead of evaluating; other C-facing consumers (cbloomfilter, docfilter) were converted to WordsCovering in this PR, but this boundary keeps a raw pointer contract that a shifted view cannot satisfy, and nothing here detaches or rejects the input. I could not construct an end-to-end reproducer in-tree, so this is a latent gap rather than a demonstrated break. Suggested options: reject shifted-view nulls at the CXCall boundary with a clear error, or detach them (the pattern reader_arrow.go already uses via DetachNulls) before passing raw pointers.

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

Reviewed bfb7551d5e7a73cfb524c070d3ce6f0e3db9ba9c against c0cef5c9cce2164fedd201c188bfffe4d2d09a96. The bitmap ownership change introduces failure paths that can skip persisted-key checks, panic after successful memory admission, or leave vectors unreleased.

  • [P1] Propagate bitmap allocation errors from persisted dedup (pkg/vm/engine/tae/tables/base.go:529). With a matching key in a persisted block, MayContainsAnyKeys now allocates a candidate bitmap. If the pool rejects that allocation, BatchDedup propagates the error, but this branch skips the block and returns success without checking the key. GetByFilter can report not found for the existing key, and DedupSnapByPK can miss the duplicate. The same error branch exists in persistedContains and the workspace tombstone loop in txnimpl/table.go. Propagate the error or perform the exact probe before treating a block as clear.
  • [P1] Keep word allocation at the caller boundary required by #33030 (pkg/common/bitmap/bitmap_mem.go:133). Initializing an empty bitmap with InitWithSize(64, mp) reaches mp.Alloc here, and Free returns the block from inside Bitmap. The linked issue explicitly requires a caller-provided slice and forbids allocation and deallocation inside Bitmap. The issue follow-up asks for a pool on Nulls. Keep allocation at the caller boundary or record an explicit change to that acceptance criterion.
  • [P1] Preserve the source's logical end when composing views (pkg/common/bitmap/bitmap_view.go:59). Take outer = InitView(src, 0, 1) over an owned bitmap with bits 0 and 1 set, then take inner = InitView(outer, 0, 2). Both ranges pass the guards. The inner view reports Count() == 1 from outer.CountRange, but Contains(1) is true because it sees the raw bit beyond outer.Len(). Marshal then writes a count of one with two set bits, which Validate rejects on decode. Preserve the source's logical end when reading shared words or explicitly reject a window outside the source domain where padding is unsupported.
  • [P1] Keep reserved validity storage through JSON/numeric comparisons (pkg/container/vector/functionTools.go:707). compareJSONNumericVectors frees this reservation with output.GetNulls().Reset() at pkg/sql/plan/function/json_numeric_comparison.go:234, then grows it with Add. For a 65-row nullable comparison with NULLs at rows 0 and 64 and 16 bytes of pool headroom for validity, the 16-byte reservation succeeds. After reset, the first NULL holds 8 bytes and the second tries to allocate another 16 before freeing the first, so Add panics on capacity rejection. Clear the bits while retaining the reservation.
  • [P1] Keep later aliases alive when a vector copy fails (pkg/container/batch/batch.go:1344). For a supported batch layout [small, big, small], let small.Dup succeed and big.Dup fail on the destination pool cap. The last column still points at small, but the defer frees it and clears its length, payload, and nulls. The batch now has a zero-length column even though that column was never replaced. Replace all aliases of each successful copy before freeing its original, or preserve the original while any slot still references it.
  • [P1] Release loaded block vectors when the destination delete bitmap cannot be allocated (pkg/vm/engine/tae/tables/pnode.go:169). When appending a persisted block with invisible rows to a batch without deletes, the new allocation at line 168 can fail after LoadPersistedColumnData has returned the block's vectors and release callback. This exit frees only deletes. The vectors have not been installed in the batch, and closing the batch cannot release them or this block's I/O backing. Close vecs and invoke release before returning the allocation error.
  • [P1] Release materialized row IDs when the visibility bitmap cannot be allocated (pkg/vm/engine/tae/tables/utils.go:154). For an appendable persisted block with an invisible row and a requested physical row-ID column, PreparePhyAddrData has already put a vector in vectors at line 93. If the new bitmap allocation fails, this branch closes vecs from LoadColumns2 and returns no vectors, leaving the separately acquired row-ID vector checked out. Close the populated entries of vectors on this exit as well.

CI on this head recorded 43 completed checks. Of those, 26 succeeded, 15 were skipped, and 2 were neutral. CI Required succeeded. This was the first review, so there were no prior findings or author replies to recheck.

git diff --check passed on the reviewed range. The findings follow from the base and head source and the traced callers, so no additional local tests were run.

mp,
)
if err == nil || !moerr.IsMoErrCode(err, moerr.OkExpectedPossibleDup) {
sels.Free()

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] Propagate bitmap allocation errors from persisted dedup. With a matching key in a persisted block, MayContainsAnyKeys now allocates a candidate bitmap. If the pool rejects that allocation, BatchDedup propagates the error, but this branch skips the block and returns success without checking the key. GetByFilter can report not found for the existing key, and DedupSnapByPK can miss the duplicate. The same error branch exists in persistedContains and the workspace tombstone loop in txnimpl/table.go. Propagate the error or perform the exact probe before treating a block as clear.

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.

Confirmed. Fixed in #33231: persistedGetDuplicatedRows, persistedContains and the workspace tombstone probe in txnimpl/table.go now return any BatchDedup error other than OkExpectedPossibleDup, so they no longer treat a failed probe as a block with no matching keys.

if n.mp == nil {
return nil, errNoPool()
}
b, err := n.mp.Alloc(capWords*8, true)

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] Keep word allocation at the caller boundary required by #33030. Initializing an empty bitmap with InitWithSize(64, mp) reaches mp.Alloc here, and Free returns the block from inside Bitmap. The linked issue explicitly requires a caller-provided slice and forbids allocation and deallocation inside Bitmap. The issue follow-up asks for a pool on Nulls. Keep allocation at the caller boundary or record an explicit change to that acceptance criterion.

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.

This one is a design question, not a code defect. The follow-up on #33030 ("Give nulls a mpool") is the direction #33144 implemented: the bitmap owns its words through its pool. The decision will be recorded on #33030. #33231 doesn't change it.

n.data = src.data[first:last:last]
}
n.shift = bit % 64
n.numBits = end - start

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] Preserve the source's logical end when composing views. Take outer = InitView(src, 0, 1) over an owned bitmap with bits 0 and 1 set, then take inner = InitView(outer, 0, 2). Both ranges pass the guards. The inner view reports Count() == 1 from outer.CountRange, but Contains(1) is true because it sees the raw bit beyond outer.Len(). Marshal then writes a count of one with two set bits, which Validate rejects on decode. Preserve the source's logical end when reading shared words or explicitly reject a window outside the source domain where padding is unsupported.

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.

Confirmed. Fixed in #33231: when the source is read-only, InitView now stops the view at the source's end, so rows past the source's Len read clear. Owned sources keep clear tails, so their padded views are unchanged. Regression test: TestBitmapViewOfViewStopsAtSourceEnd, which fails on main.

// Or), which cannot fail within the reserved rows. A result proven to emit
// no NULLs reserves nothing.
if nullable && targetSize > 0 {
if err := fr.vec.ensureNullCapacity(targetSize); err != nil {

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] Keep reserved validity storage through JSON/numeric comparisons. compareJSONNumericVectors frees this reservation with output.GetNulls().Reset() at pkg/sql/plan/function/json_numeric_comparison.go:234, then grows it with Add. For a 65-row nullable comparison with NULLs at rows 0 and 64 and 16 bytes of pool headroom for validity, the 16-byte reservation succeeds. After reset, the first NULL holds 8 bytes and the second tries to allocate another 16 before freeing the first, so Add panics on capacity rejection. Clear the bits while retaining the reservation.

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.

Confirmed. Fixed in #33231: compareJSONNumericVectors and the three <=> kernels in func_compare.go now call Clear() instead of Reset(), so the reservation is kept. nulls.Or of two empty inputs also clears the result in place, keeping its storage (Gobra proof re-run, 0 errors). Regression test: TestOrOfEmptyKeepsReservedStorage.

// later Dup fails. A read-only vector can still own its nulls bitmap.
defer func() {
for vec := range copied {
vec.Free(nil)

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] Keep later aliases alive when a vector copy fails. For a supported batch layout [small, big, small], let small.Dup succeed and big.Dup fail on the destination pool cap. The last column still points at small, but the defer frees it and clears its length, payload, and nulls. The batch now has a zero-length column even though that column was never replaced. Replace all aliases of each successful copy before freeing its original, or preserve the original while any slot still references it.

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.

Confirmed. Fixed in #33231: OwnReadOnlyVectors now copies every read-only vector before replacing any column. On a failed copy the batch is left unchanged and the copies made so far are freed. The originals are freed only after every alias has been replaced. TestOwnReadOnlyVectorsLeavesBatchOnDupError now covers the [small, big, small] layout.

(*bat).Deletes = nulls.NewWithSize(1024)
if (*bat).Deletes == nil && !deletes.IsEmpty() {
if (*bat).Deletes, err = nulls.NewWithSize(1024, mp); err != nil {
deletes.Free()

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] Release loaded block vectors when the destination delete bitmap cannot be allocated. When appending a persisted block with invisible rows to a batch without deletes, the new allocation at line 168 can fail after LoadPersistedColumnData has returned the block's vectors and release callback. This exit frees only deletes. The vectors have not been installed in the batch, and closing the batch cannot release them or this block's I/O backing. Close vecs and invoke release before returning the allocation error.

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.

Confirmed. Fixed in #33231: on that exit the loaded vecs are closed and release is called. The merged delete bitmap is also reserved for every row the merge can set, so the later Adds can't fail.

for _, vec := range vecs {
vec.Close()
}
return nil, nil, nil, err

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] Release materialized row IDs when the visibility bitmap cannot be allocated. For an appendable persisted block with an invisible row and a requested physical row-ID column, PreparePhyAddrData has already put a vector in vectors at line 93. If the new bitmap allocation fails, this branch closes vecs from LoadColumns2 and returns no vectors, leaving the separately acquired row-ID vector checked out. Close the populated entries of vectors on this exit as well.

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.

Confirmed. Fixed in #33231: that exit now also closes the populated entries of vectors (the row-ID vector), as well as the vecs from LoadColumns2.

@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: bfb7551d5e7a73cfb524c070d3ce6f0e3db9ba9c

Assessment: request_changes

The refactor can silently skip persisted primary-key checks and introduces several allocation and ownership failures. The substantive concerns in the earlier reviews remain open; the aggregate-flush and retained-capacity issues are additional findings. Pool-owned bitmaps and borrowed views reduce copies, but move allocation, cleanup, and error handling across several owners. That allocation boundary also conflicts with the closing requirement in issue #33030 and needs a specific owner decision.

Model: gpt-6.1-terra / max

Session: 01a210f8-b777-70a1-a3ad-a08c80a9ee9e · slot 1 · generation 10

  • P1 pkg/vm/engine/tae/tables/base.go:528: A bloom-positive persisted block needs a candidate bitmap, but the pool rejects its allocation.
    Impact: The loop treats the error as a negative result and ultimately returns success. GetByFilter can report an existing key absent, and DedupSnapByPK can miss a duplicate.
    Evidence: MayContainsAnyKeys now returns allocation errors from pkg/vm/engine/tae/index/filter.go:206; BatchDedup preserves them. This branch, persistedContains, and the workspace tombstone loop at pkg/vm/engine/tae/txn/txnimpl/table.go:2311 must propagate non-sentinel errors or perform the exact probe.

  • P2 pkg/common/bitmap/bitmap_ext.go:88: A nullable vector window beginning at a non-64-aligned row reaches l2_distance_xc or l2_distance_sq_xc.
    Impact: FillRawPtrLen calls Ptr on the shifted bitmap and panics instead of evaluating the function.
    Evidence: pkg/sql/plan/function/cxcall.go:72 passes every argument through FillRawPtrLen. The retained attempt-1/raw_ptr_window_native.log shows the shifted case failing and the aligned control passing. Normalize the bitmap for the native boundary or avoid requesting an unused input bitmap pointer.

  • P2 pkg/common/bitmap/bitmap_view.go:52: A view is composed with an end beyond its parent bitmap's logical end, a range currently accepted by InitView.
    Impact: The child can expose bits outside the parent domain while Count excludes them; marshaling then produces a bitmap that Validate rejects.
    Evidence: The retained attempt-2/boundary-probe.log reproduces Count=1 with rows [0,1] and invalid marshaling, while an in-domain control passes. Preserve the parent's logical end when reading shared words, including the supported clear-padding case.

  • P2 pkg/container/batch/batch.go:1342: OwnReadOnlyVectors processes aliased columns such as [small, big, small], successfully copies the first vector, and then fails to copy the second.
    Impact: The deferred cleanup frees small even though the final column still references it. A caller retaining the batch after the error can observe a zero-length, cleared column.
    Evidence: The alias case is supported by the function's contract and reproduced in attempt-2/boundary-probe.log. The workspace caller at pkg/vm/engine/disttae/txn.go:391 retains the entry on error. Replace all aliases before freeing an original, or keep it alive while any slot references it.

  • P2 pkg/container/vector/functionTools.go:707: A nullable JSON/numeric comparison has reserved validity capacity, then compareJSONNumericVectors calls Reset before emitting NULL rows.
    Impact: Reset now frees the reservation. Near the pool limit, later bitmap growth can panic after admission succeeded instead of returning a capacity error.
    Evidence: pkg/sql/plan/function/json_numeric_comparison.go:234 resets the result bitmap. The 65-row overload probe in attempt-2/json-reservation.log fails at the pool cap and passes with available capacity. Preserve reserved capacity through result initialization and audit equivalent empty-union resets.

  • P2 pkg/sql/colexec/aggexec/result.go:511: An aggregate such as MEDIAN flushes an empty group when its pool has no remaining capacity.
    Impact: The new in-place NULL write allocates bitmap storage and panics, although Flush has an error return.
    Evidence: attempt-2/aggregate-null-cap.log shows the capped empty-group case panicking and the available-capacity control passing. Reserve validity storage at a fallible boundary or propagate the allocation failure through Flush.

  • P2 pkg/container/vector/vector.go:501: A vector with reserved null-bitmap capacity is returned to a size-limited reusable batch buffer.
    Impact: CleanOnlyData retains the newly pool-charged bitmap, but Vector.Allocated omits it. Buffers and vector pools can retain charged memory beyond their configured limits and deny later allocations.
    Evidence: OneSchemaBatchBuffer.Putback uses Batch.Allocated for admission. In attempt-2/retained-capacity.log, a 1,024-byte buffer reports zero while retaining 24,576 pool bytes; the data-capacity control passes. Include owned bitmap capacity in retained-size accounting.

  • P2 pkg/vm/engine/tae/tables/pnode.go:168: A persisted block with invisible rows is appended to an existing batch without a delete bitmap, and allocation of that destination bitmap fails.
    Impact: The newly loaded block vectors and their I/O release callback are lost before ownership transfers to the batch, leaking resources on the error path.
    Evidence: LoadPersistedColumnData returns vecs and release at line 118; this exit frees only deletes. Close the loaded vectors and invoke release before returning the error.

  • P2 pkg/vm/engine/tae/tables/utils.go:147: A persisted appendable block requests a physical row-ID column, contains an invisible row, and visibility-bitmap allocation fails.
    Impact: The separately acquired row-ID vector remains checked out because the error exit returns no vectors and closes only the vectors returned by LoadColumns2.
    Evidence: PreparePhyAddrData installs the row-ID vector in vectors at line 93; the new failure branch closes vecs at lines 151–153 but not vectors. Close the populated output vectors on this exit.

  • P2 pkg/common/bitmap/bitmap_mem.go:133: The PR claims to close issue #33030 while Bitmap allocates and frees its own words.
    Impact: This contradicts the issue's explicit caller-provided-slice and no-allocation-inside-Bitmap requirement, and introduces bitmap-owned cleanup and failure responsibilities across callers.
    Evidence: The linked issue body states that boundary; its later comment asks to give Nulls a pool but does not expressly change the Bitmap requirement. Align the implementation with the stated boundary or obtain an explicit issue-owner decision revising it. This is a design requirement question, not a named-reviewer approval gate.

Validation:

  • The frozen source checkout remained at bfb7551 with no working-tree changes. Current-attempt private /tmp and loopback preflight passed.

  • Reused same-head, receipt-backed probes for shifted pointers, nested views, batch aliases, JSON result reservation, aggregate flush, and retained bitmap capacity. Their failing cases exited nonzero; the relevant passing controls are retained in the logs.

  • Reused the same-head TestBitmapMailboxConcurrentSealPreservesSingleOwner race run: it passed once, with receipt and output retained in attempt-2.

  • The supplied CI rollup reports successful Ubuntu/x86 UT, proxy and pessimistic multi-CN BVT, and CI Required checks for this head. It does not include named test logs.

Limitations:

  • The current l2_distance_xc function-boundary probe timed out after 120 seconds before emitting test output; it is neither a pass nor a product-test failure. The shifted-pointer finding rests on the completed lower-boundary probe and source trace.

  • The two persisted-scan cleanup failures were established by source tracing rather than local fault-injection runs.

  • The PR body's local-suite and Gobra claims were not independently verified from retained logs.

@fengttt

fengttt commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up for the reviews that have no inline threads: the mo-bot review (XuPeng-SH) and the Codex automated review (gouhongshen). All findings are addressed in #33231.

  • P1 persisted dedup error swallowing (base.go:528, txnimpl/table.go): errors other than OkExpectedPossibleDup are now returned.
  • P2 CXCall Ptr on shifted window nulls (Codex P2 too): FillRawPtrLen passes C a clean copy of a read-only null bitmap and keeps it alive across the call. Test: TestFillRawPtrLenShiftedWindowNulls.
  • P2 composed views past the parent's end: InitView stops at a read-only source's end. Test: TestBitmapViewOfViewStopsAtSourceEnd.
  • P2 OwnReadOnlyVectors alias: everything is copied first, then swapped and the originals freed. A failed call leaves the batch unchanged.
  • P2 JSON/numeric Reset freeing the reservation: Clear() there, in the <=> kernels, and in nulls.Or of empty inputs.
  • P2 aggregate flush at pool cap: null storage is reserved via PreExtendNulls, and flushAll returns the error. Test: TestFlushAllEmptyGroupNullsAtPoolCap.
  • P2 retained bitmap capacity in Allocated: owned null-bitmap capacity is now counted. Test: TestAllocatedCountsOwnedNulls.
  • P2 pnode.go / utils.go error-path leaks: loaded vectors, the row-ID vector and the I/O release are freed, and the merged delete bitmap is reserved up front.
  • P2 [Subtask]: Enforce bitmap takes a slice #33030 allocation boundary: not a code change. refactor(bitmap): bitmaps own their words through an mpool #33144 follows the issue's follow-up ("Give nulls a mpool"), and the decision will be recorded on [Subtask]: Enforce bitmap takes a slice #33030.

This branch was successfully deployed

No deployments
ci — 95881c41 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/bug Something isn't working kind/refactor Code refactor kind/test-ci 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