Skip to content

refactor(batch): remove Attrs, one batch codec, small BatchSet core; drop mixed-version gates - #33265

Merged
fengttt merged 13 commits into
matrixorigin:mainfrom
fengttt:batch-trim-alloc-account-test
Nov 26, 2026
Merged

fengttt merged 13 commits into
matrixorigin:mainfrom
fengttt:batch-trim-alloc-account-test

Conversation

@fengttt

@fengttt fengttt commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • Refactoring

Which issue(s) this PR fixes:

Part of #33182 (batch cleanup, #32921). Builds on #33199 (remove Attrs), which is now merged into main.

What this PR does / why we need it:

1. Remove Attrs from Batch (#33199, merged)

This section summarizes #33199 for context; that change is now in main. Column names belong to whoever defines the columns: the plan, a table definition, or a workspace entry. They now travel beside the batch where an API needs them.

  • Batch.Attrs, New(attrs), SetAttributes and GetSchema are gone. NewWithTypes replaces NewWithSchema, and Types() replaces GetSchema().
  • SelectColumns, CloneSelectedColumns and InsertVector take no names. BatchToProtoBatch(bat, attrs) takes them explicitly.
  • Relation.Write(ctx, bat, attrs) and Relation.Delete(ctx, bat, attrs, name) take the names. disttae workspace entries own theirs, and CN→TN api.Batch carries the same names as before.
  • On TN, cmd_util.WriteReq and the catalog request structs carry the api.Batch names. AppendDataToTable and containers.ToTNBatch take them as arguments. logtailreplay keeps the logtail names in ReplayBatch.
  • Behaviour changes:
    • Iceberg DML/append: these now trust the plan's column positions.
    • Data-branch hashdiff: only the current base relation's batches are projected to the target layout (currentBaseChangesHandle).
    • Legacy checkDup message: it no longer reads names from a batch that has none.

2. One batch codec; no legacy decoders

MatrixOne supports shutdown upgrade only. The batch encoding is never persisted: every use either travels between CNs within one query, or goes to a query-scoped spill file that is unlinked when it is created. So no reader ever sees bytes from an older binary, and the codec needs no compatibility sections.

  • Format: a batch is its row count, vectors, extra buffer, Recursive and ShuffleIDX. The column-name section is gone, together with MarshalBinaryWithNames, MarshalBinaryWithBufferAndNames and WireNames. Nothing writes names for older coordinators any more: not the remote-run relay, and not the deletion or multi_update relay blobs.

  • Relay wire names from refactor(batch): remove Attrs from Batch #33199 removed. refactor(batch): remove Attrs from Batch #33199 gained, late in review, column names on relay batches for older coordinators: relayWireNames in the remote-run sender, named marshalling in deletion, and mergeblock.WithAttrs. This PR removes them with the rest of the names section, along with relay_wire_names_test.go and the WireNames assertions.

  • Legacy decoders removed:

    • the ROLLUP grouping footer (pipeline_codec.go);
    • the prepared-parameter trailer;
    • the …WithMetadata decode variants.

    The decoders now reject trailing bytes.

  • spill_codec.go removed:

  • mergeblock: it accepts only the insert S3 writer's [BlockInfo, ObjectStats] result. The older layouts are gone: a table-index column, inline data batches, and block infos without stats (which needed an S3 metadata load). MergeBlock.Attrs goes with them.

3. BatchSet: a small rebatching core

BatchSet had grown three copy paths (Extend, Union, UnionRange) with their own fill, provenance and reuse helpers. It is now one append loop with Append (a row range), AppendSels (a selection) and Push (adopt an owned batch), plus the ready-batch counts, pop, take and clean. Shuffle and the delete writer use it.

  • Every batch except the last is full. The one exception is a batch closed early because the next rows come through a different pool.
  • ReadyDelta takes the pool and is exact.
  • A reuse buffer the set takes stays the set's even if the copy fails.
  • Push frees an empty batch.
  • Performance: the rewrite first made BenchmarkShufflePoolProducerTails about 4% slower. Counting instructions retired per op traced it to about 85 extra instructions per bucket append, from a non-inlined call chain. Inline fast paths restore parity: 37,817 → 37,789 instructions per op, and time is equal in alternating runs.
  • Other rebatching code (hash build, sinker, mergeutil, merge-sort reshape, the snapshot datasource) was evaluated and left alone. Each builds rows from values, streams through one buffer, or needs machinery specific to it.

4. Batch test cleanup

  • allocation_account_test.go keeps only the tests that need an allocation account. The rest moved to unmarshal_test.go, framed_codec_test.go and clone_test.go, or were dropped as duplicates.
  • bitmap_test_pool_test.go removed. Its users now allocate their selection bitmaps from their own pool and free them.
  • extra_buf_test.go folded into batch_test.go. It is the only test of MoveExtraBufferFrom and DropExtraBuffer.

5. Remove remote-run and group mixed-version gates

With every CN on one binary, the capability checks for older peers always pass, so they only cost work and failure modes.

  • pkg/sql/compile:
    • Capability predicates: about 45 supports* predicates go, each call site keeping the up-to-date behaviour.
    • Version probes: the worker version probes (remoteWorkersSupportProtocol*, AllCNsSupportProtocol*) go. They sent a query-service RPC per send or placement.
    • Pipeline validators: about 35 validateRemote*Protocol validators go.
    • Stream protocol check: the requiredProtocol floor, confirmProtocolOnStream (a protocol-check round trip per stream for some queries) and the server's PipelineProtocolCheck handler go.
    • Kept: validators that check something real: rebind-required plans, collations, LAST_INSERT_ID / ODKU baselines, auto-ID cache, correlation, IVF placement and GROUP_CONCAT time-zone portability.
  • group / aggexec / hashmap:
    • The retired aggregate row-metadata trailer goes (decoder, gate and spill-record flag byte). A partial with bytes after its states is rejected.
    • The legacy aggregate-state, HLL, DISTINCT float key, H8 CHAR padding and GROUP_CONCAT provenance gates go, together with the entry points they leave without callers.
  • Helpers left without callers go too:
    • the compile-side version predicates for HLL add, variable-length group keys, the DISTINCT key wire, widened decimal SUM and percentile_disc extended types;
    • the remote function-expression walker.
  • Tests: tests that only exercised a gate are deleted. TestRequiredIVFTopologyBroadcastAndRemoteFragment is kept without its protocol-version setup and required-version assertion. It still checks same-version topology invariants: a required IVF membership filter rejects partial, duplicate, shuffled or unreachable senders, and an RPC-decoded fragment keeps producer and reader on one message board.

Not in this PR

  • aggexec's internal legacy state formats. HLL v2 states are persisted by HLL_ADD_AGG / HLL_MERGE_AGG, so separating persisted-format from peer compatibility needs its own pass.
  • Other packages' version gates, which are out of scope: the CDC checks in ddl.go, planner fallbacks, frontend, lockservice, txn RPC and others.

Validation

🤖 Generated with Claude Code

Batch no longer does any allocation accounting of its own; it allocates
from the pool it is given. Most of allocation_account_test.go used an
accounted mpool view only as a leak counter, and several tests repeated
coverage that lives elsewhere.

- Keep in allocation_account_test.go only the tests that need an
  account: adopting an AccountedBuffer, CloneTo's high-water mark, and
  CloneTo's rollback on a metadata-slot allocation failure.
- Move the decoder tests to unmarshal_test.go and the spill-frame tests
  to spill_codec_test.go, checking plain-pool CurrNB instead.
- Replace the clone/dup accounting walk with one deep-copy test
  (clone_test.go).
- Drop tests duplicated by batch_test.go, batch_set_test.go and
  extra_buf_test.go; fold their two unique paths (BatchSet reuse while
  filling, MoveExtraBufferFrom nil/self) into those files.

Package statement coverage is unchanged (77.9%), function by function.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fengttt
fengttt requested a review from XuPeng-SH as a code owner November 25, 2026 19:19
@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 →

@fengttt
fengttt marked this pull request as draft November 25, 2026 19:19
@matrix-meow matrix-meow added the size/L Denotes a PR that changes [500,999] lines label Nov 25, 2026
BatchSet had grown three copy paths (Extend, Union, UnionRange) plus
fill, provenance and reuse helpers, each with its own fast paths. Replace
them with one append loop: fill the last batch, then start new ones,
copying a row range (Append) or a selection (AppendSels). Push adopts an
owned batch or copies it in.

- Every batch but the last is full, except one closed early because the
  next rows come through another pool (a vector has one owner pool).
- ReadyDelta now takes the pool and is exact; ReadyDeltaFor ignored the
  pool and could under-predict a pool change.
- A reuse buffer the set takes stays the set's even if the copy into it
  fails. Whole-batch writes used to hand it back while selection writes
  kept it; the shuffle test now expects the single rule.
- Push frees an empty batch instead of leaking it.
- A range append still requires a compacted source; an empty append no
  longer clears the tail's sorted flag.

Callers: shuffle moves to Append/AppendSels/ReadyDelta, the delete
writer to Append. batch_set.go goes from 513 to 259 lines.

Benchmarks: BenchmarkShufflePoolProducerTails is about 4% slower at
this commit (2650 -> 2780 ns/op shared tail, 2900 -> 3000 producer
tails) with identical allocations. The cause is extra instructions in
the new append path (non-inlined call chain, repeated checks); the next
commit fixes it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The BatchSet rewrite left shuffle about 4% slower. Counting
instructions retired per op (BenchmarkShufflePoolProducerTails, fixed
iteration count) found about 85 extra instructions per bucket append,
not allocator time:

- Append and AppendSels went through appendRows, writableTail and
  copyRows, all over the inlining budget, repeating their checks.
- ReadyDelta ran the shape and pool check through the non-inlined
  writableTail.
- Every append read and wrote each vector's sorted flag.

Append and AppendSels now copy inline when the rows fit a last batch
that already has rows (the common case); appendRows handles the rest.
ReadyDelta checks the tail with the inlinable fits.

BenchmarkShufflePoolProducerTails, alternating old and new binaries:
instructions 37817 -> 37789 per op (old BatchSet vs this), time
2650-2690 vs 2660 ns/op shared tail and 2905 vs 2905 producer tails.

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

Copy link
Copy Markdown
Contributor

This pull request is merged.

Main brought matrixorigin#33199 (remove Attrs) and matrixorigin#33261 (GEOMETRY inequality).
This branch already carries a squash of matrixorigin#33199 and builds on it, so
conflicts resolve to this branch. The mixed-version relay wire names that
matrixorigin#33199 gained late in review (MarshalBinaryWithNames, WireNames,
relayWireNames, mergeblock WithAttrs) are dropped, consistent with this
branch's single batch codec and removal of mixed-version gates. Kept from
main: the preinsert unused-constant cleanup and the GEOMETRY fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The mixed-version gate removal left the compile-side version predicates
(HLL add, variable-length group key, distinct key wire, widened decimal
sum, percentile_disc extended types) and the remote function walker
without callers. Also drop an unused test reader, preallocate a test
slice, and compare backing arrays without unsafe in clone_test.

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

XuPeng-SH commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: db30b4bb3c8009cef6afc1bae5c445b955c05dc0

Review completed. Read the assessment.

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

Assessment: request_changes

Centralizing the batch codec and rebatching logic is consistent with the shutdown-upgrade contract, as is removing old-peer gates. The cleanup also removes a test of live same-version IVF topology invariants without preserving its regression checks.

Model: gpt-6.1-terra / max

Session: 01a214fd-5519-75c1-ba9a-e15d93ce4077 · slot 1 · generation 16

  • P2 pkg/sql/compile/runtime_filter_topology_test.go:459: A distributed IVF PRE query uses a required membership filter across multiple CNs and a remote producer fragment.
    Impact: The deleted test was the direct regression check for complete broadcasts, partition coverage, and shared message-board reconstruction. A future partial domain or disconnected board could cause missing results or a waiting query without these topology boundary checks detecting it. This is a test-coverage gap, not an observed runtime failure.
    Evidence: The removed TestRequiredIVFTopologyBroadcastAndRemoteFragment accepted a complete broadcast, rejected partial or duplicate configurations, and checked that a decoded remote producer and reader share a message board. Those invariants remain enforced by pkg/sql/compile/runtime_filter_topology.go:227 and :425. Remaining required-filter tests exercise local payload handling; the multi-CN vector SQL does not cover these invalid topologies. Restore the same-version assertions using encodeRemoteScope, omitting the obsolete protocol-floor assertion.

Validation:

  • The exact-head source and discussion audit passed; its output and receipt are review-audit.log and checks/1795655162852345274-2.json.

  • The private /tmp and loopback preflight passed; its output and receipt are preflight.log and checks/1795654821575584011-2.json.

  • The supplied evidence reports successful shared-build, Ubuntu/x86 unit-test, and multi-CN BVT CI statuses.

Limitations:

  • No local Go tests ran: the installed Go 1.26.6 is older than the module's required Go 1.27.1, and a bounded automatic toolchain download timed out. The logs and receipts are batch-focused.log, toolchain.log, checks/1795654905092786319-2.json, and checks/1795655006734908310-2.json.

  • Detailed CI logs and test selections were not supplied.

fengttt and others added 2 commits November 25, 2026 17:39
…l floor

The gate removal deleted TestRequiredIVFTopologyBroadcastAndRemoteFragment
with its protocol-version assertion. Its topology checks hold within one
binary: a required membership filter rejects partial, duplicate, shuffled
or unreachable senders, and an RPC-decoded fragment keeps producer and
reader on one message board. Restore it, encoding with encodeRemoteScope
and without the MOProtocolVersion setup and required-version assertion.

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

fengttt commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Re the mo-bot review (6067215473), the P2 on runtime_filter_topology_test.go: fixed in 6e744ba.

TestRequiredIVFTopologyBroadcastAndRemoteFragment is restored. As suggested, it encodes with encodeRemoteScope and drops the MOProtocolVersion / client.version setup and the required-version assertion. Those only made sense for older peers; CNs upgrade by restart, so no CN talks to an older one.

The topology assertions are unchanged, because requiredIVFTopologyError checks same-binary correctness, not versions:

  • a complete broadcast is accepted;
  • local-only, Any, missing-remote, extra-partial, connector-fed, shuffled and duplicate-partition topologies are rejected, as is a fragment with no reachable producer;
  • an RPC-decoded remote fragment keeps producer and reader on one message board.

go test ./pkg/sql/compile/ passes, and golangci-lint and molint are clean.

The branch is also updated with main, and the PR description now covers the dropped #33199 relay wire names and the helpers removed after the gate removal.

@XuPeng-SH

XuPeng-SH commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 6e744bac69c4f8f6e8883ce72af792f441b74615

Review completed. Read the assessment.

@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: 6e744bac69c4f8f6e8883ce72af792f441b74615

Assessment: request_changes

The codec and rebatching consolidation reuses the existing owners and is consistent with the shutdown-upgrade contract. The previous IVF topology-test concern is resolved. The cleanup also removes distinct regression coverage for persisted expression floors that remain in use; the current implementation passes a focused probe, so this is a coverage gap rather than an observed runtime failure.

Model: gpt-6.1-terra / max

Session: 01a21559-2c14-7273-a4d2-83e9387fd8ce · slot 2 · generation 5

  • P2 pkg/sql/compile/odku_result_protocol_test.go:129: A persisted view or expression contains typed JSON MIN/MAX or LAST_INSERT_ID(), including an owner combining those expressions with other versioned semantics.
    Impact: The removed tests were the maintained checks that these owners receive the required persisted floors of 133 and 134 and that mixed requirements select the higher floor. Removing those assertions leaves a durable metadata and admission contract without its distinct regression oracle; this is not evidence that the current code miscomputes the floor.
    Evidence: The deleted TestJSONMinMaxSharedFloorsLocalAndCachedAdmission, TestODKU134SourceCachedAndPersistedFloors, and TestProtocol132FloatComposesWithJSON133AndODKU134 asserted these floors. pkg/sql/plan/persisted_ip.go:190 still computes them, and pkg/sql/plan/build_ddl.go:260 and :463 use the result in stored view metadata. The remaining tests do not assert the 133 or 134 mappings. The diagnostic persisted-floor-probe.log confirms the current mappings pass. Preserve a small owner-level test for JSON MIN/MAX, LAST_INSERT_ID(), and their combined maximum; existing generic admission tests can cover floor enforcement.

Validation:

  • Private /tmp and loopback preflight passed; receipt checks/1795659260387202988-3.json.

  • Focused batch codec and BatchSet tests passed; receipt checks/1795659514030751245-3.json.

  • Focused shuffle tests passed; receipt checks/1795659861208500639-3.json. Focused mergeblock, spillutil, and materialized-source tests passed; receipt checks/1795659877891423932-3.json.

  • Focused compile tests passed, including the restored IVF topology test and retained expression guards; receipt checks/1795660080983805362-3.json.

  • A diagnostic persisted-floor probe passed for JSON MIN, LAST_INSERT_ID(), their combination, and an ordinary control; receipt checks/1795660132919806187-3.json.

  • Diff whitespace and discussion/receipt audits passed; receipts checks/1795660206156195068-3.json and checks/1795660213848649834-3.json.

Limitations:

  • An exploratory probe found that a full, reordered AppendSels selection returns rows in source order. The predecessor Union has the same shortcut, and the current production shuffle caller generates selections in source order, so this is pre-existing rather than a PR regression. The control and failure are retained in batch-selection-probe.log.

  • The PR reports broader build, test, and race results, but detailed logs and selections for those claims were not supplied. The independent checks above were focused rather than a full-suite or multi-CN run.

This branch was previously deployed

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

Labels

size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants