Skip to content

fix: bound compression scratch growth and merge batches on 4.2-dev - #32081

Merged
XuPeng-SH merged 2 commits into
matrixorigin:4.2-devfrom
aptend:fix/merge-row-size-boundary-42dev-20261103
Nov 3, 2026
Merged

XuPeng-SH merged 2 commits into
matrixorigin:4.2-devfrom
aptend:fix/merge-row-size-boundary-42dev-20261103

Conversation

@aptend

@aptend aptend commented Nov 3, 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:

Fixes #32051

What this PR does / why we need it:

Backports #32052 to 4.2-dev.

Avoid an allocator-limit panic when a legal LZ4 scratch request above 1 GiB rounds up to 2 GiB: use the exact request when only power-of-two growth would exceed mpool.MaxAllocationSize(). Allocation failures retain the existing panic behavior.

Check output batch bytes after every appended row in sorted merge and reshape, flushing through the existing writer path when the batch exceeds 1.5 times the target object size (192 MiB for a 128 MiB target). Preserve the schema row limit and source transfer stride. One indivisible row can exceed the soft byte threshold.

The regression fixture uses this branch's existing test host because the main-branch JSON readback fixture is absent. Coverage remains limited to the allocation boundary and persisted data/order/transfer mappings for sorted merge and reshape with skewed and deleted rows.

Validation on Go 1.26.4 with CGO and matching native dependencies:

  • go test -p 4 ./pkg/objectio ./pkg/vm/engine/tae/mergesort -count=1 — both complete package test suites passed.
  • make static-check — passed on the full package graph (0 issues); uses this branch's pinned golangci-lint 2.6.2, molint v0.0.0-20260602145143-222a0b8adf07 and license-eye 0.4.0.

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

@XuPeng-SH

XuPeng-SH commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 34efd92414e92645c94602818c2c8e90b94ab752

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: 34efd92414e92645c94602818c2c8e90b94ab752

Assessment: approve

No actionable defects found. The backport fixes scratch-capacity rounding and prompt batch flushing while preserving transfer mappings.

Model: gpt-6.1-sol / max

Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0

Validation:

  • Reviewed all six changed files, affected owners/consumers, linked issue and both discussion entries.

  • Local source, whitespace and review-record checks passed; receipts and logs retained.

  • Reused supplied exact-head package-test, UT, coverage, static-analysis and BVT results.

Limitations:

  • Go suites were not rerun locally; raw author/CI logs were unavailable.

  • No GiB-sized allocation or comparative performance benchmark was run.

@XuPeng-SH
XuPeng-SH merged commit 88e5fb5 into matrixorigin:4.2-dev Nov 3, 2026
@XuPeng-SH XuPeng-SH mentioned this pull request Nov 4, 2026
5 of 7 tasks
XuPeng-SH added a commit that referenced this pull request Nov 4, 2026
## What type of PR is this?

- [ ] API-change
- [x] BUG
- [x] Improvement
- [x] Documentation
- [ ] Feature
- [x] Test and CI
- [x] Code Refactoring

## Which issue(s) this PR fixes:

Addresses the `4.2-dev` portion of #32146. The issue also covers `main`
and should remain open until that branch is addressed.

## What this PR does / why we need it:

A CN spill can receive an 8192-row batch whose variable-length columns
greatly exceed the staging target. The old 2 GiB compression-buffer
rounding defect was separately fixed on `4.2-dev` by #32081; this change
addresses the remaining oversized CN spill runs and associated memory
amplification.

- Admit rows against the existing conservative byte target before
copying. Close an underfull run before the next row would exceed its
budget; isolate and immediately spill a row larger than the target.
Preserve full-except-last block layout, per-object ordering, complete
object-stats handoff and the existing exceptions for single-result
merge/dedup and `flushOnSync` modes.
- Enable the same bounded-run and unpublished-run cleanup contracts for
CN tombstone writers. Tombstone primary keys may be variable length, and
the shared sorted sinker otherwise has the same oversized-run risk.
- Count physical varlen areas and logically expanded constants/aliases.
Avoid copying dead area when compacting a source, and keep per-column
copy hints local to the current call. Wide schemas allocate hint storage
only when an eligible aliased variable-length column requires a scan.
- Retain the distinct opt-in contracts for byte-bounded runs and for
deleting unpublished objects from factories that write to the supplied
file service. On failure, cancel and drain in-flight jobs before
cleaning known unpublished objects; retain failed-delete references and
preserve the original error. Preserve batch ownership on returned
errors, and remove an unreachable batch-cleanup branch.
- The design contract and invariants are recorded in the [PR design
document](https://github.com/XuPeng-SH/matrixone/blob/codex/32146-cn-spill-byte-bound-42/docs/design/20261104-cn-spill-byte-budget.md).

### Validation

- Tombstone follow-up on head `0b2887c6d5`: actual variable-length PK
objects were read back and checked row-for-row; the complete stats list
was checked; an injected second-object write failure verified cleanup of
the earlier unpublished object. The affected normal package closure
passed; the final `colexec` package and both tombstone tests were rerun
after the fixture refactor. Full race packages `ioutil`, `colexec` and
`multi_update` passed, and both tombstone tests passed under race.

- `go test` and `-race` on `pkg/container/batch`,
`pkg/container/vector`, `pkg/objectio/ioutil`, `pkg/sql/colexec`,
`pkg/sql/colexec/multi_update` and `pkg/sql/colexec/insert`;
`multi_update` was rerun after its final cleanup. Tests include actual
object readback, sorted/unsorted and sync/pipeline modes, mixed
NULL/inline/dead/aliased values, exact thresholds, oversized rows,
ownership, cancellation and cleanup failure. Thirteen individually
selected async, cancellation, cleanup and ownership tests also passed
adaptive race stress: 12 at 100 iterations and one at 34 iterations
(1,234 successful top-level runs).
- On an isolated local 1-log/1-TN/1-CN service built from the final
production code, the existing SQL case passed twice on the same instance
(24/24 statements each). After each run, the test database was absent
and fault injection was disabled on both CN and TN.
- The pre-follow-up production delta passed incremental formatting, `go
vet`, pinned `molint` and golangci-lint 2.6.2 over the affected package
closure; `molint` reports two `unsafe` diagnostics in unchanged vector
test files, which reproduce on the exact base. The tombstone follow-up
passed `gofmt`, `git diff --check` and package compilation. A local `go
vet` rerun could not compile because this host lacks the `usearch.h`,
`roaring.h` and `xxhash.h` CGo headers; arm64 CI SCA passed on head
`0b2887c6d5`.
- Full vector package tests in the host's America/New_York timezone fail
the pre-existing `TestRowToString` negative-offset expectation on both
base and candidate. The package and race checks pass with `TZ=UTC`.

### Performance and limits

An interleaved base/original-PR/final local fake-sink comparison used
the normal 128 MiB threshold, off-heap buffers and the actual CN
bounding/cleanup options, four 500 ms samples per version. Median
under-threshold time was 746 vs 811 vs 810 ns for an 8192-row fixed-only
batch, 22.37 vs 22.13 vs 22.51 µs for fresh variable-length data, and
5.33 vs 5.98 vs 5.18 ms for 65-column aliased data. The fixed-only path
is approximately 8.5%/64 ns slower than base per Write+Reset iteration
with no added allocations; the wide alias path is approximately 13.4%
faster than the original PR. These are microbenchmarks, not production
SQL or cloud object-store throughput measurements.

In a separate real object-writer/readback test using an in-memory file
service, two 96 MiB values at the default 128 MiB target changed from
one 201,326,648-byte decoded block to two 100,663,324-byte blocks;
tracked mpool peak during the probe changed from 548,233,216 to
201,785,344 bytes. This is one controlled compressible input, not a
process-RSS bound.

A separate no-spill tombstone `Write+Reset` microbenchmark (8192 rows,
GOMAXPROCS=1, five 300 ms samples, no I/O) measured median int64-PK
times of 3.247/3.209 µs and 24-byte varchar-PK times of 53.64/52.14 µs
for unbounded/bounded accounting; both reported 0 allocs/op. One
unbounded varchar sample was an outlier, so this is only narrow evidence
that accounting adds no obvious no-spill cost, not an end-to-end
throughput result.

More runs can increase object count, request and metadata costs. The
target does not bound input batches, retained capacity, bitmaps,
pipeline concurrency, serialization/compression scratch, or an
indivisible oversized row. Cleanup is best effort: a failed deletion can
be retried while the writer is retained, but a caller that discards it
loses that retry owner. Ambiguous writes, post-result handoff, cross-CN
cleanup and crash recovery remain separate work in #29257 / #29290; the
deletion timeout does not bound the earlier pipeline drain. The
pre-existing direct `WriteOwned` panic-before-return ownership ambiguity
is described in the design and is not claimed fixed here.
XuPeng-SH added a commit that referenced this pull request Nov 13, 2026
## What type of PR is this?

- [ ] API-change
- [x] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Related to #32146.

## What this PR does / why we need it:

Backport the large-variable-length write memory fixes and their
lifecycle dependencies to `v4.2.8-hotfix`. A 196,092-row fixture with
very large JSON/text values completes its batched UPDATE on 4.2.8 but
OOM-kills a 20-GiB CN during the subsequent VARCHAR-to-INT COPY ALTER.
The backports bound CN spill runs and pooled writer retention while
preserving buffer/object ownership through completion, cancellation, and
failure.

Cherry-picked with source provenance, in order: #32081, #32155, #32332,
#32164, #32398, #32454, and #32065. The target branch's existing #32704
is retained. There are no manual production-code changes to the seven
backports.

Validation on head `cc1d6c51a156e232182030b093bbf9bfc1ae95c1`:

- Fresh native build succeeds with actual-head version/commit metadata.
Formatting and `git diff --check` pass. All seven commits have identical
added/removed lines and paths to their source commits; only #32155 has
documentation-only unchanged-context differences.
- Actual-head full-data run PASS: 196,092 rows, 147,941 converted rows;
PK/row count, payload byte lengths and CRC sums, final statuses, and INT
type verified. All roles report `OOMKilled=false`.
- CN limit and total memory+swap are both 20 GiB, 6 CPUs, GOMEMLIMIT 1
GiB, cache 2 GiB. Sampled CN RSS peak: **12.4115 GiB** (2-second
sampling). Sampled cgroup usage peak: 19.7955 GiB; kernel cgroup
high-water reached 20 GiB, with zero failcnt/OOM. RSS is not total
container memory, so this does not imply 7.6 GiB of container headroom.
- Driver start through final verification: **431.90 s (7m12s)**,
including token UPDATE **221.59 s**, token COPY ALTER **200.84 s**, and
remaining validation/setup. Service startup and cold-backup restore are
excluded.
- Native-toolchain scoped regressions pass: nine owning packages (2,302
tests/subtests); compile import/cancellation selector (153); focused
race checks across mpool, rscthrottler, objectio and ioutil (93). Runs
use `-count=1`, the repository CGo test wrapper, and default vet checks.
No failures; task services are stopped. Full-repository CI/review is not
part of this local validation, and further GitHub results are not
awaited.

The workload measures the MOI offset212 token-table migration, with
placeholder companion tables, rather than all MOI deployment phases.
Logical restore uses a shared DISK backend and changes the original
physical object layout; customer data and raw logs are not included in
this PR. Single-run timings are not a statistical performance benchmark.


Revision `b6b9f3ba40d7bb9e598b2a8846b7ed166b4a48b7` (test-only
follow-up):

- Carries #32439's unordered two-observation reset assertion and
#28467's 512-MiB RLIMIT target; closes the actual fixture-owned
increment service; adapts first-replay setup to this release's embed API
and TCP SQL transport. Production changes in the seven backports remain
identical to their sources.
- New local validation (Darwin/arm64, Go 1.27.1, CGo wrapper,
`-count=1`): owning production packages build; all four changed test
packages vet; `objectio/ioutil` full coverage and race pass; `mpool`
coverage passes; `sql/compile` full normal and race pass with
`TMPDIR=/private/tmp`; first-replay
startup/disconnect/reconnect/prepared SQL passes normal and race.
Spill-reset and fixture-ownership tests each pass `-race -count=100`.
Formatting, diff whitespace, and delivery artifact checks pass.
- Run 43449877707 attempt 1 failed SCA job 131969091882 (`make
static-check-analysis`) on missing `embed.WithDataPath`; coverage job
131969165708 reports that build error, RLIMIT runtime allocation
failure, and the fixture closure assertion. These backported test
defects are addressed here; the old run is not rerun because the push
triggers fresh CI. Pinned molint rebuilt for the local Go version exits
zero but emits inherited analyzer diagnostics; this is not a
zero-diagnostic SCA claim.
- Local Parquet fanout failures also reproduce in an unmodified archive
of target base `b572b5cd95a25d404cd0f0df32629b39c6fff120`; full PR
compile normal/race pass with a short temporary root. No Parquet
code/test is changed. Linux-only RLIMIT execution is reused from
#28467's upstream coverage/race evidence; not executed on this Darwin
host. Original migration and other upstream validation above retain
their stated revisions/configurations; the customer-data migration was
not repeated for these test changes. New CI is not awaited. Raw local
logs remain outside the source tree.

---------

Co-authored-by: aptend <[email protected]>
Co-authored-by: XuPeng-SH <[email protected]>
Co-authored-by: GreatRiver <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: 和光同尘 <[email protected]>
Co-authored-by: jiangxinmeng1 <[email protected]>
aptend pushed a commit to aptend/matrixone that referenced this pull request Nov 22, 2026
## What type of PR is this?

- [ ] API-change
- [x] BUG
- [x] Improvement
- [x] Documentation
- [ ] Feature
- [x] Test and CI
- [x] Code Refactoring

## Which issue(s) this PR fixes:

Addresses the `4.2-dev` portion of matrixorigin#32146. The issue also covers `main`
and should remain open until that branch is addressed.

## What this PR does / why we need it:

A CN spill can receive an 8192-row batch whose variable-length columns
greatly exceed the staging target. The old 2 GiB compression-buffer
rounding defect was separately fixed on `4.2-dev` by matrixorigin#32081; this change
addresses the remaining oversized CN spill runs and associated memory
amplification.

- Admit rows against the existing conservative byte target before
copying. Close an underfull run before the next row would exceed its
budget; isolate and immediately spill a row larger than the target.
Preserve full-except-last block layout, per-object ordering, complete
object-stats handoff and the existing exceptions for single-result
merge/dedup and `flushOnSync` modes.
- Enable the same bounded-run and unpublished-run cleanup contracts for
CN tombstone writers. Tombstone primary keys may be variable length, and
the shared sorted sinker otherwise has the same oversized-run risk.
- Count physical varlen areas and logically expanded constants/aliases.
Avoid copying dead area when compacting a source, and keep per-column
copy hints local to the current call. Wide schemas allocate hint storage
only when an eligible aliased variable-length column requires a scan.
- Retain the distinct opt-in contracts for byte-bounded runs and for
deleting unpublished objects from factories that write to the supplied
file service. On failure, cancel and drain in-flight jobs before
cleaning known unpublished objects; retain failed-delete references and
preserve the original error. Preserve batch ownership on returned
errors, and remove an unreachable batch-cleanup branch.
- The design contract and invariants are recorded in the [PR design
document](https://github.com/XuPeng-SH/matrixone/blob/codex/32146-cn-spill-byte-bound-42/docs/design/20261104-cn-spill-byte-budget.md).

### Validation

- Tombstone follow-up on head `0b2887c6d5`: actual variable-length PK
objects were read back and checked row-for-row; the complete stats list
was checked; an injected second-object write failure verified cleanup of
the earlier unpublished object. The affected normal package closure
passed; the final `colexec` package and both tombstone tests were rerun
after the fixture refactor. Full race packages `ioutil`, `colexec` and
`multi_update` passed, and both tombstone tests passed under race.

- `go test` and `-race` on `pkg/container/batch`,
`pkg/container/vector`, `pkg/objectio/ioutil`, `pkg/sql/colexec`,
`pkg/sql/colexec/multi_update` and `pkg/sql/colexec/insert`;
`multi_update` was rerun after its final cleanup. Tests include actual
object readback, sorted/unsorted and sync/pipeline modes, mixed
NULL/inline/dead/aliased values, exact thresholds, oversized rows,
ownership, cancellation and cleanup failure. Thirteen individually
selected async, cancellation, cleanup and ownership tests also passed
adaptive race stress: 12 at 100 iterations and one at 34 iterations
(1,234 successful top-level runs).
- On an isolated local 1-log/1-TN/1-CN service built from the final
production code, the existing SQL case passed twice on the same instance
(24/24 statements each). After each run, the test database was absent
and fault injection was disabled on both CN and TN.
- The pre-follow-up production delta passed incremental formatting, `go
vet`, pinned `molint` and golangci-lint 2.6.2 over the affected package
closure; `molint` reports two `unsafe` diagnostics in unchanged vector
test files, which reproduce on the exact base. The tombstone follow-up
passed `gofmt`, `git diff --check` and package compilation. A local `go
vet` rerun could not compile because this host lacks the `usearch.h`,
`roaring.h` and `xxhash.h` CGo headers; arm64 CI SCA passed on head
`0b2887c6d5`.
- Full vector package tests in the host's America/New_York timezone fail
the pre-existing `TestRowToString` negative-offset expectation on both
base and candidate. The package and race checks pass with `TZ=UTC`.

### Performance and limits

An interleaved base/original-PR/final local fake-sink comparison used
the normal 128 MiB threshold, off-heap buffers and the actual CN
bounding/cleanup options, four 500 ms samples per version. Median
under-threshold time was 746 vs 811 vs 810 ns for an 8192-row fixed-only
batch, 22.37 vs 22.13 vs 22.51 µs for fresh variable-length data, and
5.33 vs 5.98 vs 5.18 ms for 65-column aliased data. The fixed-only path
is approximately 8.5%/64 ns slower than base per Write+Reset iteration
with no added allocations; the wide alias path is approximately 13.4%
faster than the original PR. These are microbenchmarks, not production
SQL or cloud object-store throughput measurements.

In a separate real object-writer/readback test using an in-memory file
service, two 96 MiB values at the default 128 MiB target changed from
one 201,326,648-byte decoded block to two 100,663,324-byte blocks;
tracked mpool peak during the probe changed from 548,233,216 to
201,785,344 bytes. This is one controlled compressible input, not a
process-RSS bound.

A separate no-spill tombstone `Write+Reset` microbenchmark (8192 rows,
GOMAXPROCS=1, five 300 ms samples, no I/O) measured median int64-PK
times of 3.247/3.209 µs and 24-byte varchar-PK times of 53.64/52.14 µs
for unbounded/bounded accounting; both reported 0 allocs/op. One
unbounded varchar sample was an outlier, so this is only narrow evidence
that accounting adds no obvious no-spill cost, not an end-to-end
throughput result.

More runs can increase object count, request and metadata costs. The
target does not bound input batches, retained capacity, bitmaps,
pipeline concurrency, serialization/compression scratch, or an
indivisible oversized row. Cleanup is best effort: a failed deletion can
be retried while the writer is retained, but a caller that discards it
loses that retry owner. Ambiguous writes, post-result handoff, cross-CN
cleanup and crash recovery remain separate work in matrixorigin#29257 / matrixorigin#29290; the
deletion timeout does not bound the earlier pipeline drain. The
pre-existing direct `WriteOwned` panic-before-return ownership ambiguity
is described in the design and is not claimed fixed here.

(cherry picked from commit 7283f12)
aptend added a commit to aptend/matrixone that referenced this pull request Nov 22, 2026

This branch was previously deployed

1 inactive deployment
ci — 34efd924 Deployed Nov 3, 2026 by aptend
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 size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants