Repository navigation
refactor(api): carry Entry batches in the batch encoding; drop api.Batch/api.Vector - #33269
Conversation
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. |
…tch/api.Vector api.Batch and api.Vector duplicated the batch encoding as protobuf messages, and BatchToProtoBatch/ProtoBatchToBatch converted between the two. They existed only so api.Entry could hold a batch. Entries travel only between the CN and TN of one cluster (commit requests and logtail) and are never persisted, so with shutdown upgrade only there is no compatibility reason to keep a separate format. - api.Entry reserves field 7 and adds attrs (11) and bat (12, bytes in batch.MarshalBinary encoding). api.Batch, api.Vector and the unused Checkpoint/CatalogCkp/MetadataCkp messages are removed. - batch: MarshalVectors, ViewBinary (read-only views of the bytes, every vector must hold the row count) and EncodedRowCount replace the converters; vector.VectorToProtoVector/ProtoVectorToVector are gone. - MarshalBinary encodes into an exactly sized slice appender instead of a growing bytes.Buffer, and its typed writes keep the small headers off the heap (16-row entry round trip: 50 -> 17 allocations). - TAE logtail encodes a dropped column's placeholder as a constant null of the batch's length, so every vector holds the row count. - disttae: toPBEntry and fillRandomRowidAndZeroTs encode; partition state HandleRowsInsert/HandleRowsDelete take the encoded bytes and attrs. The encoding is a copy, so HandleRowsInsert no longer clones its input. - catalog: the mo_database entry check relies on the codec's validation and keeps only the layout checks (names, types, not const, no nulls). Co-Authored-By: Claude Opus 5.5 <[email protected]>
8ae16d6 to
68008cd
Compare
Entry.Bat becomes the gogoproto custom type api.EncodedBatch: the batch encoding held as a list of parts. batch.Encode / EncodeVectors copy only the headers and null bitmaps and borrow each vector's data and area (and the extra buffer) through a new types.WriteBorrowed path, so marshaling the Entry copies the payload once, straight into the message buffer, as the old api.Vector aliasing did. Unmarshal copies the message bytes, and decoders keep borrowing from that copy. At 8192 rows an Entry round trip allocates 1.89 MB again (was 2.83 MB; the old api.Batch path 1.88 MB). Co-Authored-By: Claude Opus 5.5 <[email protected]>
TestLogtailClientReceiveFailureReturnsBuffer could cancel before Receive took the first segment, so no buffer was ever taken and the idle-list assertion failed. Wait until the response is in its buffer before cancelling or breaking the stream. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
mo-bot review · Commit: discussion changed before publication |
iamlinjunhong
left a comment
There was a problem hiding this comment.
- [P2]
pkg/vm/engine/disttae/logtailreplay/partition_state.go:1107Replayed inserts still retain the encoded row-ID and commit-timestamp columns. When a data-bearing CN replays an insert batch, any surviving row or snapshot keeps the user-column views alive. Those views point into the same allocation as both physical columns, so freeing their vector headers leaves 36 bytes per row of the original batch resident even thoughRowEntrystores both values. The base decoder allocated each column separately and could reclaim those bytes. Give the retained columns their own backing storage so replay can release the physical columns after indexing. - [P2]
pkg/sql/compile/remoterunServer.go:1385Release oversized result buffers when the send completes. After a remote fragment sends a batch larger than 64 MiB, the completed send leaves the off-heap allocation on the stream until its next batch or handler teardown. If this is the last batch and the receiver delays its acknowledgement, the handler waits for the acknowledgement with the entire send buffer still allocated. The base used a temporary buffer for each send. Reset the buffer after the synchronous writes finish so the configured retention limit applies between batches and while waiting for acknowledgements.
The earlier delete-replay finding is resolved on this head. The author acknowledged the issue and identified the fix in a583e55b79. Delete replay now gives the retained primary-key vector its own bytes, so the row IDs and timestamps from that batch can be released. Author reply
All 33 checks are complete on 0b237455a56a0eae1c55d9a1757d38da3bd8dbb6. There are 14 successful checks, including CI Required, 17 skipped checks, 2 neutral Mergify checks, and zero failures. CI Required
The read-only artifact check passed. Source inspection established both remaining findings, so I skipped local tests.
| } | ||
| if !p.noData { | ||
| // ProtoBatchToBatch borrows the input vector bytes. RowEntry owns | ||
| // The decoded vectors are views of the input bytes. RowEntry owns |
There was a problem hiding this comment.
[P2] Replayed inserts still retain the encoded row-ID and commit-timestamp columns. When a data-bearing CN replays an insert batch, any surviving row or snapshot keeps the user-column views alive. Those views point into the same allocation as both physical columns, so freeing their vector headers leaves 36 bytes per row of the original batch resident even though RowEntry stores both values. The base decoder allocated each column separately and could reclaim those bytes. Give the retained columns their own backing storage so replay can release the physical columns after indexing.
There was a problem hiding this comment.
Fixed in 33d21a289d. Insert replay now keeps one owned copy of the user columns only (ownReplayRows). The row-ID and commit-time columns stay empty, typed, in their positions; RowEntry already holds both. It reads the received bytes in place, so inserts no longer need the detach copy either. TestReplayInsertKeepsOnlyOwnedUserColumns checks that the kept columns survive the receive buffer being overwritten and share no bytes with the input. It fails when the view is put back.
🤖 Generated with Claude Code
| return moerr.NewInternalErrorNoCtx("remote batch stream is closed") | ||
| } | ||
| // The messages of the previous batch are done: Write has returned. | ||
| out.buf.Reset() |
There was a problem hiding this comment.
[P2] Release oversized result buffers when the send completes. After a remote fragment sends a batch larger than 64 MiB, the completed send leaves the off-heap allocation on the stream until its next batch or handler teardown. If this is the last batch and the receiver delays its acknowledgement, the handler waits for the acknowledgement with the entire send buffer still allocated. The base used a temporary buffer for each send. Reset the buffer after the synchronous writes finish so the configured retention limit applies between batches and while waiting for acknowledgements.
There was a problem hiding this comment.
Fixed in 33d21a289d. sendBatch now resets the stream buffer (deferred, under the stream lock) once its synchronous Writes return, instead of before the next batch. A buffer over the 64 MiB bound is freed before the handler waits for the acknowledgement. TestRemoteBatchBufferFreesOversizedBufferAfterSend checks that an oversized buffer is freed when the send returns and a buffer within the bound is kept. It fails with the old placement.
🤖 Generated with Claude Code
|
mo-bot review · Commit: discussion changed before publication |
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
This PR replaces api.Batch/api.Vector duplicate wire types with the batch.MarshalBinary encoding carried in Entry.bat (an api.EncodedBatch custom type that can borrow source vectors and write them straight into the message buffer), and moves CN/TN message staging onto reused off-heap mpool.MessageBuffer buffers; I reviewed all 34 changed production files end to end and the diff is coherent and internally documented. Because the reused buffers make lifetime explicit, I traced every reader of the reused bytes and confirmed each escapes only through a detach or release path: TN logtail segments copy their chunks before Write; remoterun and dispatch messages point into reused buffers only under morpc Write, which I verified in pkg/common/morpc/server.go signals the sender only after encode plus flush or an explicit drop; commit payloads are held until the transaction terminal hooks (Rollback, FinalizeCommit, FinalizeCommitWithUnknownResult); on the CN receive side, queued logtails are detached before handoff to consumer routines, delayed catalog updates detach in dcaTryDelayEntry, replayed rows detach in HandleLogtailEntry and deletes keep an owned primary-key copy, object-list entries use pooled during-call views, and the stats consumer now takes an owned summary at enqueue. The trusted encode/decode paths still validate framing, sizes, types and row counts, consistent with the documented same-cluster trust contract, and the mo_database catalog check still decodes through the validating ViewBinary. The delete-replay retention P2 from the earlier mo-bot review is genuinely fixed on this head (verified in code plus TestReplayDeleteKeepsOnlyOwnedPrimaryKey), so it is not restated; two further P2 items opened by another reviewer on this same head (insert replay retaining row-id/commit-ts columns in the shared encoding; a >64MiB remoterun send buffer staying allocated while awaiting acknowledgement) remain open and are not duplicated here. For validation, a decoded go list -deps -test -e -json snapshot of the touched targets showed zero metadata errors, but this checkout lacks the prebuilt thirdparties/install prerequisites, so every touched package except pkg/pb/api cannot compile here ('jemalloc.h' file not found when building pkg/common/malloc, and matrixone/cgo needs usearch.h); building those prerequisites is out of scope for this review, so I ran the independently runnable suite go test -v ./pkg/pb/api (all pass, including the six new EncodedBatch tests), plus go vet and gofmt on the changed code, and verified the remaining paths by static tracing. One non-blocking generator-pin finding remains, filed below.
P2 - Regenerated api.pb.go was produced with protoc 36.0 while proto/gen.sh pins 21.1 (proto/gen.sh:19)
pkg/pb/api/api.pb.go was regenerated with protoc 36.0 (stated in the PR description), while proto/gen.sh still pins PROTOC_VERSION='21.1' and only prints 'protoc version does not match' when the installed protoc differs, without failing. The generated code itself is fine on this head: go test -v ./pkg/pb/api passes, go vet is clean, and the PR states that only the embedded gzipped descriptor bytes differ from what 21.1 would emit, so this is non-blocking. The concern is reproducibility: the documented generator no longer reproduces the checked-in file, so the next bash proto/gen.sh run with the pinned protoc rewrites the descriptor bytes in api.pb.go, producing a whole-file diff that can mask future semantic changes until the churn is committed. Consider regenerating the file with the pinned protoc, or bumping PROTOC_VERSION (and the pinned download URL) to the version actually used so the script matches the artifact.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 0b237455a56a0eae1c55d9a1757d38da3bd8dbb6
Assessment: request_changes
The refactor reuses the existing batch codec, but two previously identified memory-retention regressions remain in insert replay and remote result streams. The earlier delete-replay retention concern is resolved.
Model: gpt-6.1-terra / max
Session: 01a21559-2c14-7273-a4d2-83e9387fd8ce · slot 2 · generation 5
-
P2
pkg/vm/engine/disttae/logtailreplay/partition_state.go:1046: A data-bearing CN replays an insert batch and retains at least one row or snapshot from it.
Impact: The retained user-column views keep the entire encoded batch alive, including the row-ID and commit-timestamp columns already copied into RowEntry. For flat physical columns, this retains an extra 36 bytes per original batch row on each affected CN until the last reference to that batch disappears.
Evidence: The 16,384-row replay probe retained a 721,034-byte backing encoding containing 589,824 bytes of physical columns; its retained user vector points into that allocation. The target base decoded separately allocated protobuf vector fields, allowing the two physical columns to be collected after their references were cleared. Retain user columns independently, or otherwise compact the retained representation while preserving snapshot ownership. -
P2
pkg/sql/compile/remoterunServer.go:1385: A remote pipeline sends a result batch larger than the 64 MiB retention limit and then waits for downstream processing or acknowledgement before another batch is sent or the stream closes.
Impact: The oversized off-heap buffer remains allocated for that entire wait. Concurrent slow streams can therefore retain substantially more memory than the intended per-stream bound, even though the transport no longer needs the bytes.
Evidence: Reset runs before the next marshal, while the handler closes the buffer only after its acknowledgement drain. A scaled fragmented-send probe retained 32,768 bytes with an acknowledgement pending under a 16 KiB limit; resetting after the send freed it. The target base used a send-local buffer that became collectible after the call. Reset the reusable buffer after the completed send, including error paths, while retaining small buffers for reuse.
Validation:
-
The supplied isolation preflight passed: checks/1795686677466935061-2.json. Native prerequisites were built from the recorded source inputs in native-input-ledger.txt.
-
The API package and focused codec, catalog, replay, transaction, logtail, dispatch and remote-send tests passed: api-tests.log and focused-tests.log; receipts checks/1795686744480614601-2.json and checks/1795687066902417511-2.json.
-
The in-process CN/TN commit test and insert replay lifetime test passed: commit-integration.log and insert-lifetime.log; receipts checks/1795687423519295480-2.json and checks/1795687604227180650-2.json.
-
Commit-buffer recycling and receive-buffer release racing client close each passed 100 repetitions under the race detector: race-commit-100.log and race-receive-100.log; receipts checks/1795687703637022413-2.json and checks/1795687701582290125-2.json.
-
Read-only overlay probes confirmed the replay and stream-buffer ownership observations with smaller controls: replay-probe.log and retention-probes.log; receipts checks/1795687298643051074-2.json and checks/1795687180986272059-2.json.
Limitations:
-
The ownership probes use scaled buffer limits and do not measure production-scale RSS or multi-CN query throughput.
-
No full distributed SQL or end-to-end performance benchmark was run; the CN/TN commit test uses in-process engines.
…te send buffers after the send From review of matrixorigin#33269. - Insert replay kept a view of the whole received encoding, so every surviving row pinned the row-ID and commit-time columns that RowEntry already holds (36 bytes per row). It now keeps one owned copy of the user columns, with empty typed row-ID and timestamp columns in their positions, and reads the received bytes in place: the receive buffer no longer needs a detach copy for inserts. - A remote stream reset its send buffer only before the next batch, so a buffer past the 64 MiB retention bound stayed allocated while the handler waited for the receiver's acknowledgement. sendBatch now resets it once its synchronous Writes return. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…fields without human review Add references/batch-memory.md and references/vector-memory.md to the mo-dev skill (both .agents and .claude copies), with G-BATCH and G-VECTOR gates. - Batch: field owners, the owned / view / borrowed states, release paths, the borrowed Encode and view-decode rules for messages, and leak and use-after-free tests. Agents must not add a field to Batch, give one a new meaning, or add an encoding section, unless a human developer asked for it or reviewed and approved the design; otherwise they stop and ask. - Vector: moved from docs/ai-skills/sql-engine.md into the skill. One owner and one exact pool per vector, nil pool = read-only, pass-through, never modify an input in place, windows. Adding a Vector field needs a human developer's careful review and confirmation first. Co-Authored-By: Claude Opus 5.5 <[email protected]>
What type of PR is this?
Which issue(s) this PR fixes:
Part of #33182 (batch cleanup, #32921).
Follows #33265 (merged). Eight commits on top of
main, plus a merge ofmain: the format change;perf(api), which removes the extra payload copy;perf(batch), a trusted encode/decode path;perf, which makes Entry batches allocation-free and moves message buffers to reused off-heap mpool memory (see Performance and Memory ownership);fix(logtailreplay), from review: delete replay keeps only an owned copy of the primary key;test(logtail), which fixes a race in a new receive-buffer test; andfix, from review: insert replay keeps only an owned copy of the user columns, and a remote stream frees an oversized send buffer as soon as the send returns. The last,docs(skills), adds the batch and vector memory models to the AI skills.What this PR does / why we need it:
api.Batchandapi.Vectorwere protobuf copies of our own batch encoding: data, area, null bitmap, type, length and const flag.BatchToProtoBatchandProtoBatchToBatchconverted between the two. They existed only soapi.Entrycould hold a batch.api.Entrycarries batches in exactly two flows: the CN→TN commit request and the TN→CN logtail. Both stay inside one cluster and neither is persisted. TAE's WAL uses its own commands, and checkpoints are objectio files. No cross-cluster reader exists: CCPR copies object files, andpublication,cdc,datasyncandiscpnever readEntry.Bat. With shutdown upgrade only, a second format has no compatibility reason to exist.api.Entryreserves field 7 and addsattrs(11) andbat(12), which holdsbatch.MarshalBinarybytes.batis the gogoproto custom typeapi.EncodedBatch. It holds the encoding as a list of byte parts, so the encoder can pass the vectors' buffers without copying them. On the wire it is an ordinarybytesfield.pkg/pb/apistill imports nothing fromcontainer.api.Batch,api.Vectorand the unusedCheckpoint,CatalogCkpandMetadataCkpmessages are removed.protocthangen.shpins: 36.0 against 21.1. Only the embedded gzipped descriptor differs from what 21.1 would produce.batch:Encode,EncodeVectors,ViewBinaryandEncodedRowCountreplace the converters.ViewBinaryreturns read-only views of the bytes and requires every vector to hold the row count.Encodecopies only the headers and null bitmaps. Each vector's data and area of at least 256 bytes, and the extra buffer, are borrowed through the newtypes.WriteBorrowed. An ordinaryio.Writerstill gets a copy, so spill files and other callers are unchanged.MarshalVectorsstays for local replay, which needs an owned copy.MarshalBinaryperformance: it now writes into an exactly sized slice. It used to grow abytes.Buffer, and each header write escaped to the heap. This helps every caller, not just these entries.api.Vectors did. Both builders close their batches only through the callback that runs after the response is sent.toPBEntryborrows the workspace vectors, as before. They stay unchanged until the commit RPC has been classified.fillRandomRowidAndZeroTsencodes an owned copy.PartitionState.HandleRowsInsertandHandleRowsDeletetake the encoded bytes and attrs. Replay borrows from them exactly as it borrowed from the proto's bytes before.HandleRowsInsertno longer clones its input. Its encoding is either the unmarshalled message bytes or the owned local-replay copy, so it never aliases live vectors.Performance
Entry batches.
batch.Encodeallocates and copies nothing.Entry.Batborrows the batch and writes it straight into the message buffer when the Entry is marshaled, through new allocation-freeMarshalToByteswriters on the vector, null bitmap and batch. If the batch no longer has the size it had atEncode, the marshal fails without writing past the encoding.EncodedBatch.Unmarshalkeeps a view of the message buffer.Detachgives bytes of their own to whatever outlives the buffer.ViewTrustedBinaryInto). Object-list replay uses pooled view batches. Consumers that keep a batch (partition-state rows, TNWriteReq) allocate its header because they own it.Encodeskips the varlena disjointness scan, andViewTrustedBinaryskips the null-bitmap and varlen payload scans, while still checking framing, sizes, trailing bytes and row counts. Logtail replay and the TN commit handler use it. The catalog's mo_database check keeps the validatingViewBinary.Memory ownership
mpool.MessageBufferis an off-heap mpool buffer that is allocated once, grows only when a message needs more, and keeps at most a bounded size between messages.Writes return, so a buffer over the 64 MiB bound is freed before the stream waits for an acknowledgement. Messages point into the buffer: a server session'sWritereturns only after the message is encoded or dropped.FreeorReleasesync.Pool)FinalizeCommit,FinalizeCommitWithUnknownResultorRollback, after the commit RPC returned. The in-process test sender gives TN its own copy, as the wire does.dcaTryDelayEntry) and partition-state rows detach their batches; the stats consumer gets a summary taken at enqueue.Replay retention.
RowEntryholds, stay empty. A view would pin the whole encoding: 36 bytes per row. Found in review.AI skills
The mo-dev skill (both
.agentsand.claudecopies) gainsreferences/batch-memory.mdandreferences/vector-memory.md, withG-BATCHandG-VECTORgates.Callstates and their release paths;Encodeand message-view rules;docs/ai-skills/sql-engine.md, in English: one owner and one exact pool per vector, nil pool = read-only, pass-through, no in-place modification of inputs, windows.BatchorVector, give aBatchfield a new meaning, or add a batch-encoding section, unless a human developer asked for it or reviewed and approved the design. Otherwise they stop and ask.Validation
go build ./...passes;go vet ./pkg/... ./cmd/...and gofmt are clean.go test -racepasses on every package the diff touches;go testpasses onsql/colexec/...,sql/compile,frontend,tests/dml,tests/sqlintegration/multicn,txn/...,vm/engine/tae/...,vm/engine/disttae/...,vm/engine/test/...,cnservice/...andtnservice/....mpool.EnableDebugPoisonOnFreefor use after free;-racefor concurrent sends, releases and close.MarshalBinary; random batches round-trip; every way a borrowed batch can change fails the marshal without writing past it.closewaits for an in-flightWrite;TestReplayDeleteKeepsOnlyOwnedPrimaryKey,TestReplayInsertKeepsOnlyOwnedUserColumns).TestRemoteBatchBufferFreesOversizedBufferAfterSend).🤖 Generated with Claude Code