Skip to content

fix: bound CN spill runs by bytes 4.2-dev - #32155

Merged
XuPeng-SH merged 9 commits into
matrixorigin:4.2-devfrom
XuPeng-SH:codex/32146-cn-spill-byte-bound-42
Nov 4, 2026
Merged

XuPeng-SH merged 9 commits into
matrixorigin:4.2-devfrom
XuPeng-SH:codex/32146-cn-spill-byte-bound-42

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Nov 4, 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:

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.

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.

@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 4, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: bc1d3145f32281d78bb5c09dd84a13ee01e7c957

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Commit: bc1d3145f32281d78bb5c09dd84a13ee01e7c957

Assessment: approve

Approve the scoped 4.2-dev fix. Expanded-payload accounting and byte-aware partitioning extend the existing Sinker while preserving rows, per-object sort order and full non-final blocks. The ownership corrections and opt-in failed-run cleanup reuse the existing buffer, pipeline and deletion owners; the added bounds state is justified by aliases/constants and retained areas. No actionable findings remain after tracing the changed paths and their consumers. Independent product execution was unavailable during dependency setup.

Model: gpt-6.1-sol / max

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

Validation:

  • Read the complete ten-file delta, both discussion entries, linked issue bodies/comments and applicable repository instructions. Traced vector copy/alias accounting, block metadata and transaction consumers, Write/WriteOwned ownership, failure cancellation/drain/deletion, published results and Reset. Recorded source reasoning and regression-test oracles in source-assessment.md; discussion-assessment.json covers both keys exactly once.

  • Private /tmp and loopback preflight passed: preflight.log and checks/1793782899830977460-2.json (exit 0). Assigned cache/tmp environment and Linux/amd64 Go 1.26.6 confirmed: go-env.log and checks/1793782899802070978-2.json (exit 0); go.mod requires >=1.26.4.

  • All ten changed Go files parsed and produced no gofmt differences: gofmt-parse.log and checks/1793783088337105734-2.json (exit 0). This is a parsing/format check, not type checking or runtime validation.

  • Dependency setup was bounded at 60 seconds and timed out while downloading absent modules: dependency-setup.log and checks/1793783003378031510-2.json (exit 124). A cached-only focused go test of objectio/ioutil, colexec, multi_update and insert with the assigned test-exec failed at module resolution: focused-tests-setup.log and checks/1793783094907784135-2.json (exit 1). Zero product test binaries executed.

  • Final audit verified frozen head/base and patch, clean unchanged source, complete discussion coverage, and terminal command/log receipts: review-integrity.json, review-audit.log and checks/1793783447034288002-2.json (exit 0). The retained first audit diagnostic concerned only the supplied patch omitting its final serialization newline; the corrected audit accepts exactly that one-byte difference.

Limitations:

  • No independent product, race, SQL or performance execution completed locally. Dependencies were absent and module download setup timed out; native prerequisites/provenance were also absent, and rebuilding them would not resolve the earlier module-resolution failure.

  • The frozen PR body reports normal/race checks of four packages, static checks, a three-CN SQL exercise and base/candidate fake-sink ABBA measurements. Raw author logs/receipts are unavailable and local_validation is empty, so these remain reported evidence. Product CI was pending/skipped in the supplied snapshot and is not claimed as passing.

  • The run target is soft, permits one-row overshoot and is not an RSS bound. Cleanup is best effort for completed untransferred objects; ambiguous writes, post-handoff failures and crash recovery remain separate work. Its deletion timeout does not bound the preceding pipeline join. The main-branch issue remains outside this 4.2-dev review scope.

@XuPeng-SH XuPeng-SH changed the title fix: bound sorted CN spill runs by bytes fix: bound CN spill runs by bytes Nov 4, 2026
@mergify mergify Bot added the kind/test-ci label Nov 4, 2026
@XuPeng-SH XuPeng-SH changed the title fix: bound CN spill runs by bytes fix: bound CN spill runs by bytes 4.2-dev Nov 4, 2026
@matrix-meow matrix-meow added size/XXL Denotes a PR that changes 2000+ lines and removed size/XL Denotes a PR that changes [1000, 1999] lines labels Nov 4, 2026

@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 a3cfb7551431d7e9d87c33383fb13c44e3757873...7e0f2cdf529279310563a249828ed401ce83060d against the current 4.2-dev base. Approve: no actionable blocking finding in this revision. Approval concerns the implementation; pending CI is not counted as passing.

Design and correctness

  • Read all 15 changed files and followed the existing Sinker, merge/output writer, Vector/Batch copying, pipeline, free-list, multi-update and transaction consumers. The implementation extends the existing run-size and ownership boundaries rather than introducing a parallel writer or persistent payload cache. The additional per-run bound is justified because physical vector size alone does not represent expanded aliases/constants.
  • The byte calculation accounts for physical areas and logical expansion per column. Splitting occurs before copying, applies to ordinary sorted and unsorted CN writes, and preserves full non-final blocks. Single-merged/deduplicated and flushOnSync writers retain their previous behavior.
  • Exact whole-batch payload hints are reused only during the corresponding copy; constants, partial/overlapping sources and unsupported hints fall back to the established copy path. Checked borrowed/constant buffer reuse, short versus extra flat-column lengths, NULLs, alias expansion, partial refills and arithmetic overflow.
  • WriteOwned callers relinquish the input when ownership transferred even if the write then fails. Failed-run cleanup cancels and joins outstanding work before enumerating completed unpublished objects; previously returned result objects are excluded. Reset/close retain failed-deletion references while releasing unrelated memory, without admitting a new generation over an unresolved failure.

Unhappy-path audit

Question Assessment
Q1 — ownership/cleanup Copy versus ownership-transfer paths, merge buffers, pipeline callbacks and staged versus returned objects have distinct owners. Error/panic cleanup uses those owners; Close can retry deletion while the writer remains retained.
Q2 — termination Cancellation precedes pipeline join; submission rejection and worker terminal paths discharge pending work. The deletion timeout bounds deletion, not the preceding join, which still relies on the existing writer/file-service cancellation contract.
Q3 — growth/performance The run target permits one indivisible-row overshoot. Existing input buffers, retained capacity, pipeline work and compression scratch remain outside that target; it is not an RSS cap. No unbounded registry or durable recovery mechanism is added.

Performance and operational scope

Bounding runs can increase object count and object-storage requests. The author's latest measurements explicitly show a wide fake-spill cost (up to +6.3% in the reported cases), so this should not be advertised as universally performance-neutral. The change is a reasonable tradeoff for bounding oversized CN runs, but production S3 latency/throughput has not been established here. Ambiguous writes, process crashes and cleanup after result handoff remain the separately tracked work in #29257 / #29290; this patch does not claim to solve them.

Evidence and limits

  • Inspected tests covering real object readback/layout, row-to-payload correspondence, sorted/unsorted and sync/pipeline modes, allocation limits, ownership-on-error, cancellation/reset barriers, deletion failure/retry and preservation of previously returned objects. The SQL case checks INSERT/UPDATE plus commit/rollback with a scoped small threshold.
  • Independently checked unchanged worktrees, clean git diff --check, and Go 1.26.4 parsing/formatting of every changed Go file. The overlap with #32152 merges cleanly at source level, not yet as a combined runtime validation.
  • The latest-head shared build has passed. Latest-head UT, coverage, SCA and BVT jobs are still running at review time. The PR reports full normal/race runs of six affected packages, repeated three-CN BVT and comparative benchmarks; raw local execution receipts were not obtained, and no independent product/race/SQL/performance run is claimed here.
  • No inline review threads are present to leave unresolved. The older bot assessment was not treated as validation of this new head. #32146 should remain open for its main-branch portion.

@XuPeng-SH

XuPeng-SH commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · superseded

Commit: 0b2887c6d537661fca0afd76b996a252381230f7

Review linked issue or PR description changed before publication; a fresh contextual review is queued.

@XuPeng-SH

XuPeng-SH commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · superseded

Commit: 0b2887c6d537661fca0afd76b996a252381230f7

"interrupted"

@XuPeng-SH
XuPeng-SH merged commit 7283f12 into matrixorigin:4.2-dev Nov 4, 2026
@XuPeng-SH
XuPeng-SH deleted the codex/32146-cn-spill-byte-bound-42 branch November 4, 2026 13:45
@iamlinjunhong iamlinjunhong mentioned this pull request Nov 4, 2026
1 of 7 tasks
XuPeng-SH added a commit that referenced this pull request Nov 9, 2026
## What type of PR is this?

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

## Which issue(s) this PR fixes:

- #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 #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]>
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 pushed a commit to aptend/matrixone that referenced this pull request Nov 22, 2026
## 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)

This branch was successfully deployed

No deployments
ci — 6210cc3f Deployed Nov 4, 2026 by XuPeng-SH
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/documentation Improvements or additions to documentation kind/enhancement kind/refactor Code refactor kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants