Skip to content

Fix large-value write memory usage on v4.2.8-hotfix - #32710

Merged
XuPeng-SH merged 8 commits into
matrixorigin:v4.2.8-hotfixfrom
iamlinjunhong:codex/v428-hotfix-mem-backports
Nov 13, 2026
Merged

XuPeng-SH merged 8 commits into
matrixorigin:v4.2.8-hotfixfrom
iamlinjunhong:codex/v428-hotfix-mem-backports

Conversation

@iamlinjunhong

@iamlinjunhong iamlinjunhong commented Nov 13, 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:

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 fix: bound CN spill runs by bytes 4.2-dev #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 [4.2] Fix flaky spill pipeline reset test #32439's unordered two-observation reset assertion and fix(mpool): avoid coverage crash in realloc failure test #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 fix(mpool): avoid coverage crash in realloc failure test #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.

aptend and others added 7 commits November 13, 2026 22:07
…atrixorigin#32081)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes matrixorigin#32051

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

Backports matrixorigin#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.

(cherry picked from commit 88e5fb5)
## 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)
…origin#32332)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#32157 (first batch only; keep the tracking issue open)

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

Backport six focused startup, RPC, and memory-lifetime fixes onto
`4.2-dev@02fcfbc`. These old paths are
still present on that release baseline. This is deliberately not a bulk
backport of the tracking issue's 30 entries and is not release approval.

| Source PR | Backported behavior | Failure/compatibility boundary |
| --- | --- | --- |
| matrixorigin#30761 | Hand off a first-catalog-replay disconnect to the existing
reconnect owner; do not publish readiness while paused. |
Before/during/after replay handoff, retry and cancellation, then actual
SQL after recovery. No Main worker-lifecycle refactor. |
| matrixorigin#29586 | Preserve live user-unary Futures during idle GC and
atomically seal admission when truly idle. | Heartbeats do not keep idle
connections alive; completed/canceled work can be reclaimed; saturated
cleanup remains capacity-accounted. Retains the source PR's
logical-row-count/NULL correction in `readSingleTaskRunner`. |
| matrixorigin#29559 | Claim FIN in the existing stream entry without holding its
mutex over synchronous send; release rejected responses once. | Writer
exit, full queue, invalid/duplicate FIN and later requests; update the
CN drop-release callback at the same ownership boundary. |
| matrixorigin#30536 | Public session close disconnects transport; only the writer
finalizer or failed-start path releases the writer's Goetty reference. |
Active Encode/Flush, blocked socket output and failed writer startup;
tested together with FIN. |
| matrixorigin#28384 | Detach address-keyed ownership/profile state before off-heap
realloc can recycle the old address; restore it if allocation fails. |
No change to accounted allocation or allocate-copy-free ownership paths;
allocator failure and address reuse are explicit oracles. |
| matrixorigin#29352 | Drop a completed non-constant Scope's Reader reference after
pipeline cleanup. | The existing TableScan/Pipeline owner still closes
the Reader; no additional Close call; prepared reuse must rebuild/read
correctly. |

Each source retains an independent `cherry-pick -x` commit.
Release-adaptation commit `72fb70919a9b98213af778cc7a4d6525e97dd7c4`
uses 4.2's existing Future predicate and queue instrumentation rather
than importing unrelated Main machinery. The real first-replay
regression uses 4.2's existing `pkg/embed` cluster owner, with
process-wide faults isolated in a dedicated test package, and also
checks real MySQL prepared-statement reuse.

### Scope and design review

- No wire, catalog or persisted-data format changes, new configuration,
external dependency versions, SQL optimization rules, or background
cleanup subsystem.
- MORPC and mpool are shared code: their changes also affect other roles
that use them, not only CN. Excluding TN storage/WAL changes is not a
claim that TN executes no changed code.
- Resource ownership remains with the existing Pipeline, RPC writer,
client cleanup pool, allocator and connector. FIN adds one terminal bit
to an existing live stream entry; replay adds one notification channel
per connector, not a second recovery state machine.
- Idle GC scans existing Futures only after the idle-age check; it does
not add per-request bookkeeping. The other changes replace cleanup
ordering or remove references. No throughput improvement or
zero-regression guarantee is claimed.
- Q1: response/Future/transport/Reader cleanup owners checked, including
rejected admission and failed startup. Q2: FIN no longer holds the
receive-state lock over send completion; disconnect interrupts socket
I/O; first replay wakes the existing reconnect path. Q3: no new growing
registry or queue; bounded backend cleanup is retained.

### Deliberately not included

- matrixorigin#29725: 4.2 already enters allocator recovery on Unlock errors; Main's
bypass guard is absent. Do not label this as the same confirmed
release-branch Unlock leak.
- matrixorigin#29448, the NULL-completeness subset of matrixorigin#29558, and matrixorigin#28693 remain
follow-up candidates with separate
authentication/planner/transaction-helper validation; absence here does
not mean they are unimportant.
- The TN/WAL, mixed-lock, HNSW and ISCP task-lifecycle changes need
dedicated adaptation and upgrade/recovery coverage. CDC already has
matrixorigin#32232; do not duplicate it. No rollback/upgrade of any running cluster
is part of this PR.

### Tested with

Original backport validation:
`72fb70919a9b98213af778cc7a4d6525e97dd7c4`. Local runs used Go 1.26.4,
Darwin arm64, native libraries built from this release tree,
`GOMAXPROCS=2`, `-p=1` and normally `GOMEMLIMIT=2GiB`. Earlier
pre-commit runs retain their working-tree identity; their relevant
source content matches that original validation commit. No historical
Main test result is presented as a test of this backport.

| Evidence | Result |
| --- | --- |
| MORPC, mpool, ISCP, compile and disttae owning packages | Normal and
race PASS. |
| CN owning package | Normal and race PASS with the
environment-sensitive scalar memory-limit test split as described below;
all tests in that partition covered. |
| New real embed regression | Normal and race PASS: inject disconnect
during first catalog replay, recover startup, observe a fresh TN
timestamp, and execute one actual MySQL prepared statement twice with
results `[1,2]`, then `[2]`. The dedicated test package isolates faults
from the shared embed cluster. |
| Existing `TestSingleCNCluster` | Race PASS. |
| Linux amd64 on server 50 | Both Linux-only realloc tests PASS in
normal/race; full mpool (71 top-level tests) and MORPC (315 top-level
tests) normal/race PASS. |
| Matched Linux baseline controls | Clean `02fcfbc898` plus only
regression probes reproduces three real failures: stale metadata at
allocator-cache publication, queued-FIN close deadlock, and buffers
freed during active Encode. Candidate passes the same oracles. The
baseline physical-allocation-failure test already passes and is retained
as compatibility coverage, not claimed as a new failing counterexample.
|

Linux used existing immutable build image
`sha256:44069beb9d61e8d1d6766f1d214eb94843257616bc8c9291ee53fae1edbbd7fa`,
fresh candidate/base native builds and separate source/cache
directories. Containers had 2 CPUs, 4 GiB memory+swap limit, 512 PIDs
and no network. Existing services on 50 were not changed.

The first capped full CN runs failed
`Test_service_handleGoMemLimit/set_4Gi`: that test assumes the initial
Go memory limit is `MaxInt64`, but the explicit test environment
supplied 2 GiB. The exact capped case on clean baseline `02fcfbc898`
fails with the same expected-MaxInt64/actual-2147483648 signature. We
did not weaken its assertion or change product code. The package is run
with that one case excluded under the cap, and the exact scalar-only
case is separately run in normal/race with `GOMEMLIMIT` unset. Original
failed receipts remain failed.

Stress: 21 individually selected MORPC/mpool/compile/disttae cases
passed independent `-race -count=100` runs on Darwin. The isolated embed
recovery case passed its proportional repeat (`T=17.25s`, `B=30s`,
`N=1`). Linux cache-publication retirement passed `-race -count=100`;
physical allocation failure passed `-race -count=29` (`T=1.03s`,
`B=30s`). Selections are non-empty and recorded by individual test name.

Commands use the repository CGo wrapper, with serial package builds:

```sh
GOMAXPROCS=2 GOMEMLIMIT=2GiB .agents/skills/mo-dev/scripts/mo-cgo-test -p=1 -count=1 -timeout=240s ./pkg/common/morpc ./pkg/common/mpool ./pkg/iscp ./pkg/sql/compile ./pkg/vm/engine/disttae
GOMAXPROCS=2 GOMEMLIMIT=2GiB .agents/skills/mo-dev/scripts/mo-cgo-test -p=1 -race -count=1 -timeout=240s ./pkg/common/morpc ./pkg/common/mpool ./pkg/iscp ./pkg/sql/compile ./pkg/vm/engine/disttae
# CN package: normal/race separately, then the one default-limit oracle separately.
GOMAXPROCS=2 GOMEMLIMIT=2GiB .agents/skills/mo-dev/scripts/mo-cgo-test -p=1 -count=1 -skip '^Test_service_handleGoMemLimit$' ./pkg/cnservice
env -u GOMEMLIMIT GOMAXPROCS=2 .agents/skills/mo-dev/scripts/mo-cgo-test -p=1 -count=1 -run '^Test_service_handleGoMemLimit$' ./pkg/cnservice
# Also repeated with -race; each stress command selects exactly one test.
# Original test path at 72fb; the follow-up moves it to ./pkg/embed/firstreplay.
GOMAXPROCS=2 GOMEMLIMIT=2GiB .agents/skills/mo-dev/scripts/mo-cgo-test -p=1 -race -count=1 -timeout=240s -run '^TestCNFirstReplayDisconnect$' ./pkg/embed
```

`go vet` passed for all seven affected production/test packages; `git
diff --check` passed. Incremental golangci-lint was **not validated**:
locally installed versions are incompatible with the repository's v2
config/Go 1.26 toolchain. No lint configuration or dependencies were
changed to bypass this limitation. No full BVT, production workload
benchmark or rolling-upgrade qualification is claimed; PR CI and release
qualification remain separate.

### Incidental bug findings

`pkg/tests/service.buildCNConfig` on the target baseline validates a
newly generated CN UUID before registering its service runtime, causing
a nil-runtime panic before the cluster starts. This is already addressed
upstream by matrixorigin#30380 (`0723ae37b1`); disposition: **Duplicate / not
included**. The new regression uses the existing embed fixture, which
already registers the runtime and catalog definitions. It does not patch
or claim validation of the legacy service fixture, and does not pull in
the broader CN-drain changes from matrixorigin#30380.

Ordinary off-heap profiling has a separate pre-existing
enable/allocate/disable/free boundary: the pool returns to zero but the
profile pointer/in-use sample remains recorded. An isolated baseline
probe reproduced it; disposition: **Created matrixorigin#32334 / not included**.
This is diagnostic metadata retention, not a demonstrated native-buffer
leak or customer OOM, and does not change this batch's scope or review
conclusion.

### CI test follow-up

Follow-up commit: `6404268dae8b5d78a12fb0459b67991c8893a9cd`.

After the 4.2-dev merge,
[UT](https://github.com/matrixorigin/matrixone/actions/runs/42341756945/job/128310805969)
and
[coverage](https://github.com/matrixorigin/matrixone/actions/runs/42341756945/job/128310839394)
exposed a process-admission deadlock in `TestCNFirstReplayDisconnect`:
the shared embed fixture held the runner-wide lock while its test
process waited for a child that needed the same lock. Move the existing
recovery test into its own test package, remove the recursive
subprocess, and acquire the existing process admission before starting
replay deadlines. Fault injection remains process-isolated, and the real
fresh-TN-timestamp and two prepared-execution result oracles are
retained.

The coverage run also failed an existing dropped-user authorization
assertion across two CNs. The reader uses its locally applied statement
snapshot, so the test now fences the committed DROP and verifies through
independent CN1 SQL that the user is absent before checking that the
already-authenticated session is denied. This establishes denial after
visibility; it does not claim instantaneous cross-CN revocation or prove
the precise cause of that CI failure. The unmodified 4.2-dev baseline
passed three normal repetitions.

Follow-up validation on Linux/amd64, Go 1.26.4, matching branch-local
native libraries:

- The original full-order reproduction fails on `6c7dca5d` after the
shared cluster starts; the independent test passes with the same lock
held by another process for over 40 seconds, then released, including
under `-race`. A separate cancellation control confirms admission times
out before faults or a cluster start.
- Complete `pkg/embed` and `pkg/embed/firstreplay` suites run together
with `-p=2`: PASS (230.547s and 17.923s). Existing process-admission
exclusivity, reentrancy and cancellation tests also pass under `-race`.
- Full `TestIssue29399AuthorizationScopeAndRevokedRole`: three normal
repetitions and one `-race` run pass, including the CN1 public-SQL
visibility and retained-session denial checks.
- Scoped CI-style `-tags matrixone_test -short -covermode=set` execution
of both scenarios passes with cnservice, MORPC, mpool, ISCP, compile,
disttae and frontend instrumented. This is not the full CI coverage
producer.
- Incremental gofmt and `go vet` pass for the affected packages;
repository-configured golangci-lint 2.6.2 built with Go 1.26.4 reports 0
issues for the follow-up diff. The original backport diff passed arm64
SCA on `6c7dca5d`.
- Independent design: `gpt-6.1-terra/max`. Independent overall review:
`gpt-6.1-sol/max`, no material code blocker; final evidence reconciled
before delivery.

The follow-up changes only tests; it adds no production hot-path work.
Full post-push CI and release/upgrade qualification are separate and are
not claimed as passed here.

---------

Co-authored-by: XuPeng-SH <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
(cherry picked from commit a860d63)
## What type of PR is this?

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

## Which issue(s) this PR fixes:

- matrixorigin#32154

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

Spill merge failures could lose track of an output buffer or leave
cleanup ownership ambiguous when output moves to accumulated results or
an asynchronous pipeline. Keep ownership explicit across buffer
acquisition, merge, transfer and failure, and reset the executor on
synchronous exit. Errors and panics continue to propagate. Regression
tests cover failures and ownership transfers, multi-block content, reset
and real sink readback.

Validation on `0fac11533824441409e5e36d276b91c0e4bc1125` (Darwin arm64,
Go 1.27.1, CGO), newly executed after rebasing onto official
`4.2-dev@7283f12`:

- `GOWORK=off go build -mod=readonly ./pkg/objectio/ioutil` and matching
`go vet` passed with repository CGo include/library paths.
- `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=240s
./pkg/objectio/ioutil` and the same command with `-race` passed (78 test
roots each).
- All 17 named ownership/failure/transfer/readback regressions passed
focused race execution, then separate exact-name `-race -count=N` runs
(N=13–100, measured 30-second per-test budget capped at 100; 1,601 root
repetitions total). This includes the target branch's immediate-release
regression.
- `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=240s -run
'^TestS3Writer_SortAndSync$' ./pkg/sql/colexec` passed. Delivery
artifact check passed.

Conflict resolution preserves matrixorigin#32155's byte-bounded staging and
borrowed/constant-vector normalization. Failed buffer acquisition
immediately releases partial allocations before retiring its ownership
claim; its regression now checks immediate mpool baseline restoration.
The previous head's required CI passed; CI for this rebased revision
will run after push. No new cluster or performance benchmark was run.

The change adds constant-time ownership bookkeeping and defers, without
a new per-row scan or I/O. An accumulated spill can retain one existing
preallocated output block slightly longer. Reset's wait for accepted
pipeline work is supported by source review; the existing test does not
establish that Reset has entered its wait, and completion still depends
on the downstream sink returning.

---------

Co-authored-by: XuPeng-SH <[email protected]>
(cherry picked from commit e4f70a7)
…origin#32398)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#32389

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

Backport the missing behavior from matrixorigin#27890 and matrixorigin#28926 to 4.2-dev. A
normal StopSending during parallel reader construction must not publish
a terminal execution error while the query remains live.

Normalize the result before the pre-publication ParallelRun cleanup
chooses End versus Error. Construct readers from the source scope
context so reader cancellation and cleanup classification observe the
same lifetime. Reuse the branch-local normalizer and retain rate-limited
cancellation diagnostics; do not backport main's newer outcome/protocol
refactors. Real query cancellation, deadline, storage errors and mixed
primary/cancellation errors remain terminal.

Validation (base 6d4dc2f):
- Base behavior: FAIL — new deterministic construction-cancellation
regression and real local/remote reader-context boundary tests detect
the old behavior.
- PR-head behavior: PASS — eight focused tests; each also passes 100
race repetitions. Full pkg/sql/compile normal and race tests pass; full
colexec and connector normal tests pass.
- BVT: test/distributed/cases/vector/vector_ivf_sampling_cancel.sql and
.result. Both standalone and two-CN topology pass 27/27 assertions twice
on the same instance; teardown checked after each run. Service logs
confirm SAMPLE 100 PERCENT LIMIT 10000, using 10,001 low-dimensional
vectors and sequential L2/cosine/IP creation/query/drop.
- Static/build: make cgo, service build, compile go vet, incremental
golangci-lint and git diff --check pass.
- Retained unrelated failure: full pkg/vm/process normal tests hit
TestHarvestExternalCounterSetAndTerminalWait at
operator_analyzer_test.go:552 (strictly positive duration around an
empty callback). The unchanged baseline reproduces the same assertion in
46/100 targeted runs; no test was skipped or modified to hide it.
- Earlier setup/oracle attempts retained locally: macOS binary loader
path corrected; IP BVT ordering corrected to ASC for this branch's
negative dot-product function; direct race binary cwd corrected to the
package directory for resource-relative tests. Final checks above use
the corrected inputs.

QA required: yes — the original fixed-version SIFT 1M/128-dimensional
TKE scenario is NOT RUN in this PR preparation. These tests close the
known missing mechanisms; they do not prove the first cancellation owner
of the reported incident or that the original intermittent failure has
disappeared. Keep this PR Draft and matrixorigin#32389 open pending QA. No
performance or zero-intermittency claim.

No public API, SQL syntax, configuration, catalog, storage format, retry
or timeout change.

Review follow-up: the cancellation fixture now owns and closes its
private AutoIncrementService before restoring the prior runtime. Worker
cleanup cancels and joins through a separate completion channel even
when the result is unread. A regression checks service closure,
private-runtime reference removal, old-runtime restoration, and worker
completion after an early subtest return. This follow-up changes only
tests; the product and SQL BVT evidence above is reused.

Follow-up validation: four directly affected tests pass normally and
each passes 100 race repetitions; full pkg/sql/compile normal and race
pass; incremental lint and git diff --check pass. Astra medium re-review
confirms the original P2 is resolved with no remaining confirmed
blocker.

---------

Co-authored-by: XuPeng-SH <[email protected]>
(cherry picked from commit 899f08b)
…rixorigin#32454)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#29384 (4.2-dev backport; main fix matrixorigin#29432)

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

A Merge writer can grow WriteArena.serialBuf on the Go heap and leave
that large capacity parked in the arena pool after the task finishes.
Limit pooled serialization capacity to 16 MiB per arena before
publication, retain large scratch only while an active write cycle needs
it, and clear it on FreeBuffers. Add a pooled-capacity gauge with
accounting ordered before lock-free publication. No wire-format changes
or off-heap arena-size tuning.

Regression coverage includes a real object writer and two sequential
MergeObjects tasks in one TAE engine. Before the fix the writer retained
16,785,408 bytes and the Merge test observed 19,079,168 pooled bytes;
both tests pass with this patch. Build and vet passed for objectio,
metric, TAE jobs and DB consumers. Full objectio/metric normal and race
suites passed. Focused race stress passed for the new tests
(49/68/100/13 runs).

TAE package race passed in 134 s with only Test_RWDB4 excluded. The
unfiltered package timed out at 600 s in Test_RWDB4; that test also
timed out at 120 s both on this branch and on a clean 4.2-dev baseline
at 9dd4d33. This baseline timeout is an existing validation gap, not
a passing full-suite claim.

The cap trades occasional reallocation for bounded parked Go-heap
retention. The gauge may briefly overcount an arena between accounting
and CAS publication, but settles after the transfer.

(cherry picked from commit c8264f1)
…in#32065)

## 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 matrixorigin#26992 and matrixorigin#32146. Port matrixorigin#31166 and matrixorigin#31810 together.

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

Port matrixorigin#31166 and matrixorigin#31810 together while preserving native 4.2
allocation-owned HashBuild, SpillEngine, PipelineEdge, scheduling and
RETURNING behavior. Supported local CSV graphs reserve
producer/data/upload memory; unsupported graphs retain whole-statement
fallback. Head `9a2948051e43ea3ad5d49e5651dfa9e62a5f01ec` is based on
`4.2-dev@c0532d1`, with five commits.
[Maintained
design](https://github.com/aptend/matrixone/blob/9a2948051e43ea3ad5d49e5651dfa9e62a5f01ec/docs/design/import-memory-control.md).
Paired release PR: matrixorigin#32241.

- Legacy partition EOF preflush retires all source D before replay,
avoiding sibling self-wait. Until a complete metadata frame is handed
off, the existing sinker/block-info/spool owns its successful objects.
Partial flush, cancellation and failed decode remove only unhanded
files; Free/Reset share one bounded cleanup deadline across partitions.
Compact cleanup names stay in the existing private spool, avoiding a
second object registry.
- Protected publication Apply observes an atomic worker TTL/notification
snapshot. Earlier/later renewal and unregister wake its existing
expiration observer; stale replies from removed registrations cannot
update a replacement. Exit cancels and joins the observer. Source-buffer
admission, fixed-name tombstone layout and accepted-worker ownership are
retained.
- INSERT/MultiUpdate keep admitted compact metadata in memory, migrating
unread records to the configured LOCAL spill service only on capacity
denial. Legacy/raw-delete output streams per frame with
delete-before-insert order. Files no longer use OS TMPDIR. Persistent
object and transaction protocols are retained; no new setting, worker
pool or polling interval is added.

INSERT metadata, MultiUpdate metadata and transaction-local delete-key
deduplication reuse existing statement/CN spill-disk and FD
reservations. Dedup bucket storage is admitted before sizing the file,
each distinct RowID before append; duplicates need no growth.
Close/Reset/Free return the reservations. Regressions verify cumulative
rejection before writing, shared-file quota reuse, partial creation and
cancellation; removing admission fails both consumer oracles. The
explicit-transaction nonblocking guard and upstream
serialization-retention/grouping-key fixes remain.

Impact: 91 production Go files versus the release base; the latest dedup
correction touches 2 production files (+11/-6), one existing test file
and the maintained design. Shared writer/admission and publication paths
include ordinary DML/publication; this is not a LOAD-only change. This
correction adds no planner, allocator hot-path or merge-policy change.

Validation:

- Physical LocalFS regressions cover late write failure/cancellation,
Reset, partial consumer handoff, successful INSERT handoff, failed
decode and successful-upload prefixes. Actual handed-off files remain;
producer-owned files are removed. Earlier original-behavior overlays
fail the ownership/TTL runtime oracles. The cleanup-deadline regression
also fails before sharing the deadline.
- Real worker/coordinator/FilterObject virtual-time tests cover expiry,
extension, shortening, unregister, parent cancellation and stale renewal
generations. The directly affected TTL/renewal tests pass 100
repetitions; final partition tests pass 100 repetitions per branch.
- The final `multi_update` owning package passes normal and race modes
(150 named tests each). A pre-fix real delete-preparation test fails its
storage-ownership oracle; fixed tests cover bucket/record quota denial
before writing, duplicate lookups at capacity, shared metadata/dedup
charges, Reset refund and reuse. Unchanged
insert/colexec/publication/ioutil code retains source-valid normal/race
evidence. Native binaries embed this final commit and pass 20 SQL
statements each: two partitions, 36,000 committed rows plus
same-transaction rows, exact counts/sums, DELETE, rollback/commit and
teardown. Test services are stopped and generated data is removed. This
is a functional control, not a SQL low-memory failure reproduction or a
current-head throughput result.
- Local SCA compares against latest fetched
`main@61b5a4e`. Its incremental
selector selects `./...`, including tests and reverse dependencies; Go
1.26.4, CGO and built thirdparties artifacts are used. Repository-pinned
molint `222a0b8adf07` and golangci-lint v2.6.2 pass; lint reports zero
issues:

```sh
go vet -mod=readonly -p=2 ./...
go vet -mod=readonly -p=2 -vettool=/d/mo-worktrees/v42-import-memory-lab-20261103/bin/molint ./...
golangci-lint run --timeout=25m --concurrency=2 --new-from-rev=61b5a4ee202578d2b186559f49af94b7c12b85a9 -c .golangci.yml ./...
make err-check
```

License/header checks and native builds pass. New GitHub CI and
re-review are pending.

Historical workload evidence retains its original
revisions/configurations:

- [Amway baseline attempt
2](https://github.com/matrixorigin/mo-nightly-regression/actions/runs/41761321029/attempts/2),
`10d204b876`, versus [candidate attempt
4](https://github.com/matrixorigin/mo-nightly-regression/actions/runs/41763229702/attempts/4),
`67179b6eed`: identical workflow `93631633b7`, importer `35e18afa1b`,
inputs/schema/index/order; two CNs, each 10 CPU/20 GiB, cache 2 GiB,
GOMEMLIMIT 16000 MiB; TN 5 CPU/15 GiB. Both complete four rounds/156
row-count checks. Candidate completes 156 retry-free imports with zero
OOM/restarts; baseline completes 150 retry-free imports with seven
retries and six restarts/OOM in rounds 2–4. Highest observed single-CN
cgroup usage: 18.904 → 2.872 GiB; sampled RSS: 18.247 → 2.663 GiB. Clean
first-round importer calls: 379.434 → 368.488 s (-2.88%); four-round
total including baseline recovery: 2358.215 → 1469.192 s (-37.70%).
Calls include DDL/rename/validation. Clean-round S3 writes increase
about 865 → 3293 while bytes decrease 8.211 → 7.933 GiB. [Baseline
artifacts](https://github.com/matrixorigin/mo-nightly-regression/actions/runs/41761321029/artifacts/13303009140)
/ [candidate
artifacts](https://github.com/matrixorigin/mo-nightly-regression/actions/runs/41763229702/artifacts/13315437176).
- [TPCH
baseline](https://github.com/matrixorigin/mo-nightly-regression/actions/runs/41586981094),
`10d204b876`, versus
[port](https://github.com/matrixorigin/mo-nightly-regression/actions/runs/41586985050),
`dfb9dd56be`: identical workflow `968b31e224`, pinned clients, three CNs
×14 CPU/55 GiB with 12-GiB cache; TN 14 CPU/55 GiB with 5-GiB cache.
Both runs/result checks pass.

| TPCH runner total | Baseline | Port | Change |
| --- | ---: | ---: | ---: |
| 100G LOAD, 8 tables | 311.592 s | 347.026 s | +11.37% |
| 1T LOAD, 8 tables | 3468.715 s | 3130.165 s | -9.76% |
| 100G queries, all 3 measured rounds | 288.795 s | 302.525 s | +4.75% |
| 1T queries, all 2 measured rounds | 2100.224 s | 2127.282 s | +1.29% |

LOAD excludes DDL/preparation; query sums include all 22 queries and
exclude warmup. One sequential pair does not establish statistical
significance. TPCH combined three-CN RSS peak: 95.369 → 99.137 GiB;
working-set peak: 135.168 → 124.451 GiB (15-second sampling). Historical
local `dfb9dd56be` acceptance completed five continuous Amway rounds
/195 imports/6,931,020 rows on one PID under 22 GiB, zero
OOM/retries/restarts/forced GC/deliberate pauses. These are historical
acceptance results.

(cherry picked from commit 1bde992)
@mergify
mergify Bot requested a review from XuPeng-SH November 13, 2026 14:13
@mergify mergify Bot added kind/bug Something isn't working kind/enhancement labels Nov 13, 2026
@iamlinjunhong
iamlinjunhong marked this pull request as ready for review November 13, 2026 14:14
@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 13, 2026 •

Copy link
Copy Markdown
Contributor

Queue requested — the merge queue status continues in this comment ↓.

@mergify

mergify Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🛑 Queue command cancelled

Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.

  • Queue this pull request

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed head cc1d6c51a156e232182030b093bbf9bfc1ae95c1 against v4.2.8-hotfix@b572b5cd95a25d404cd0f0df32629b39c6fff120. One confirmed revision request is inline: this bundle omits the already-merged #32439 correction and reintroduces its known scheduling-dependent test failure. This is a test defect, not evidence that the production OOM fix fails.

Customer problem and design assessment

The production direction is appropriate for the reported large-value MOI migration. The common CN writer/sinker changes also apply to COPY ALTER's data rewrite; their effect is not restricted to LOAD admission. Byte-bounded spill runs, materialized-size accounting for aliased/constant values, and bounded serialization/arena retention address the large-row amplification. The explicit workspace/admission path, source-to-worker ownership transfers and joined pipeline cleanup address the associated allocation and lifetime problems rather than merely raising the container limit. The on-disk object format is not replaced; retaining full non-final blocks is an important compatibility invariant.

All seven backports retain their upstream production changes; the only patch-context difference found in #32155 is unchanged documentation context. The target's existing #32704 is retained. This is nevertheless a broad backport (217 files), including shared MPool/MORPC/readers and ordinary write paths, not a minimal two-patch or LOAD-only fix. The full graph admission remains restricted to supported local CSV plans; unsupported graphs keep the legacy route, while the shared writer improvements still apply.

Current evidence and release boundaries

The updated body now records an actual-head native build and a successful actual-head full-data migration: 196,092 rows, 147,941 converted rows, PK/count/payload lengths/CRC sums/final status/INT type checks, no reported OOM. I accept this as attributed author evidence for that fixture; I have not independently executed or inspected the private customer-data run. It supersedes the earlier historical-combination-only evidence.

The reported RSS peak of 12.4115 GiB is not container headroom: sampled cgroup usage was 19.7955 GiB and the kernel high-water reached the 20-GiB limit. This does not invalidate the successful run, but it does not establish safety under arbitrary concurrent workload. Logical restore changed physical object layout, the backend was shared DISK rather than the customer's object-storage path, and companion tables were placeholders; the evidence covers the token migration, not every MOI deployment phase or every old-object layout.

Normal/race regression results are still marked in progress. The target branch name v4.2.8-hotfix is excluded by .github/workflows/entrypoint.yaml's PR branch filters, so the currently green Iceberg/MongoDB checks are not kernel UT/BVT approval. Before releasing, record terminal results for the scoped writer/sinker, MPool/MORPC, pipeline cancellation/reset and ordinary SQL write/rollback checks, reusing applicable upstream evidence where the semantic inputs are unchanged. This does not require publishing customer data or rerunning the full migration merely for the test-only #32439 correction.

Reviewer validation: source/provenance and lightweight diff checks; the local focused Go-test attempt stopped at the missing native cgo/libmo.dylib prerequisite, before any tests executed. No local UT pass or zero-regression performance claim is made. No additional production correctness blocker was established in the traced customer write/lifecycle paths during this review.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Follow-up on the unchanged head cc1d6c51a156e232182030b093bbf9bfc1ae95c1.

The #32439 finding is test-only: it corrects an ordering assumption in a _test.go assertion and does not change the shipped MO binary, data format, or customer execution. The release owner has elected to defer this test correction for the customer hotfix. I am recording it as a known non-blocking test-maintenance item for this release, not claiming it was fixed. My earlier REQUEST_CHANGES should not be interpreted as a production correctness blocker.

There is also new validation evidence since that review: the PR body now records terminal PASS for nine owning packages (2,302 tests/subtests), the compile import/cancellation selector (153), and focused race checks across mpool, rscthrottler, objectio and ioutil (93), using the native CGo wrapper and -count=1. This supplements the already recorded actual-head full-data migration and data-integrity checks. I reuse this as attributed author evidence; I did not independently execute the private-data run. Full-repository CI is not being claimed green.

Based on the prior production-code/lifecycle review plus the completed scoped validation, I have no other established production blocker requiring another cherry-pick before this customer hotfix. The common writer changes target the COPY ALTER failure and the documented 196,092-row migration completed under the stated 20-GiB configuration. Approval is for this reviewed code/bundle, not a claim of zero risk or arbitrary-concurrency OOM safety. The previously documented physical-layout/backend and full-MOI-phase coverage limits remain. In particular, the 12.41-GiB RSS result is not evidence of 7.6 GiB spare container memory. Keep the tested resource settings and avoid competing heavy jobs during the customer migration.

No release/tag/registry mutation is performed by this review.

@XuPeng-SH XuPeng-SH closed this Nov 13, 2026
@XuPeng-SH XuPeng-SH reopened this Nov 13, 2026
@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 →

Carry the unordered spill reset assertion from matrixorigin#32439 and the coverage-safe RLIMIT target from matrixorigin#28467. Capture the increment service installed by the fixture process, and adapt first-replay setup to the target embed API with TCP-only SQL transport. Production backports remain unchanged.
@mergify

mergify Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

queue

🛑 The queue request has been cancelled: new commits were pushed

Details

@iamlinjunhong pushed to this pull request after queue was requested. Review the new commits and request it again.

This branch had an error being deployed

1 failed deployment
ci — b6b9f3ba Deployed Nov 14, 2026 by iamlinjunhong
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/enhancement size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants