Skip to content

perf(import): pipeline bounded uploads and reduce CSV parsing allocations - #31810

Merged
XuPeng-SH merged 5 commits into
matrixorigin:4.1.6-hotfixfrom
aptend:fix/4.1.6-import-write-pipeline
Nov 1, 2026
Merged

XuPeng-SH merged 5 commits into
matrixorigin:4.1.6-hotfixfrom
aptend:fix/4.1.6-import-write-pipeline

Conversation

@aptend

@aptend aptend commented Oct 30, 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 #26992; performance follow-up to #31166.

What this PR does / why we need it:

Bounded CSV imports can spend excessive time flushing small writer windows and waiting for each upload. Array-valued fields also allocate a normalized string and a temporary split slice for every value. This change reduces those costs while retaining the existing admission and cleanup guarantees.

  • Separate writer batching from source framing, accounting for every index projection and preserving the existing source/output-frame bounds.
  • Reserve each encoding/upload peak within the shared W budget. Transfer buffers, private pools and leases to existing SinkPool jobs; let already-admitted borrowed uploads continue after returning the caller's W. Keep synchronous fallback when another upload cannot be admitted, stable MultiUpdate pool ownership, and joined error/cancel/Reset cleanup.
  • Scan array-literal token views with one result allocation, preserving ASCII-space handling, dimension checks, float precision/result bits and error text.

No new worker pool, tuning switch or dataset-specific threshold. Persistent formats and ordinary join spill thresholds are unchanged. Consolidated design.

TKE evidence

Original Amway importer, 39 tables x 4 continuous rounds. Input hashes, schema/indexes/order, pinned client image, Python/PyMySQL versions and deployment settings match: 2 CNs, each 20 GiB/10 CPU, 2 GiB memory cache, GOMEMLIMIT=16000MiB. Values below sum all 156 import_seconds, excluding DDL and preparation.

Measured source Run Total import time
Historical hotfix before memory admission, ed9d8aa 40467595909, attempt 2 1348.209 s
Historical bounded-memory hotfix, 75d9cd343d 40480188049, attempt 4 2092.413 s
Intermediate pipeline implementation, cb4788b 40843320353 1622.459 s
Complete optimization, 8ef38e7 40891622421 1426.814 s

The complete optimization is 31.81% faster than the historical bounded-memory hotfix and 12.06% faster than the intermediate pipeline implementation. It remains 5.83% above the pre-memory-admission historical time. These are sequential historical comparisons, not a new execution of target dc4e7ee070.

Latest run: 156/156 imports and row-count checks passed, zero retries/OOM/restarts. Against the intermediate run, the two CNs' combined sampled RSS peak was 3.49 -> 3.56 GiB. The comprehensive table's round-2 array-parser cumulative allocation profile decreased from 17.84 to 3.26 GiB; these are allocated bytes, not resident memory.

Validation and source identity

  • Local 22 GiB/no-swap acceptance: 5 continuous rounds, 195/195 successful imports, 6,931,020 verified rows, same PID, no retries/OOM/restarts or forced GC/inter-round pauses; I/D/W returned to zero after every round. Full importer time: 1272.35 -> 1128.88 s versus the intermediate implementation (-11.28%). Sampled RSS/cgroup peaks: 7.77/10.83 GiB.
  • Owning-package and affected-consumer tests, incremental vet/lint passed. Five affected lifecycle tests each passed -race -count=100; both writer packages passed whole-package race runs. Array-parser differential fuzzing passed 52,772 executions in 30 seconds.
  • Target: 4.1.6-hotfix at dc4e7ee070; delivery: 61eb095c01, 5 commits. Workload measurements above executed 8ef38e7; the initial d866e8b5c0 delivery changed only documentation/history. The review fix below changes Insert metadata framing and adds regression tests. Those full native/TKE workloads have not been rerun on this framing-fix head; their original source identities remain unchanged.

Review fix: bounded Insert metadata frames

Completed uploads could be combined into one Insert metadata frame and exceed the unchanged source-derived limit. Insert now spools one complete object per frame for incremental collection and final Sync, preserving all object/block metadata without increasing frame/I limits.

Fresh validation: a 15-object/512-block-per-object metadata burst crosses the frame bound without allocating source rows; empty, single-object and oversized-object rejection controls also pass. Existing real-LocalFS tests cover incremental/final collection, zero/ordinary D credits and cancellation. These assertions fail on the previous code and pass with the fix. The affected pipeline test passed -race -count=100; whole Insert race, normal Insert/colexec/MergeBlock tests, vet and lint passed.

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

Reviewed head d866e8b against 4.1.6-hotfix dc4e7ee. Request changes for the reproducible metadata-frame regression below. The shared coordinator/SinkPool ownership design is otherwise coherent; no second scheduler or admission path is needed.

Independent local validation (macOS arm64): all five changed owning packages passed whole-package UT with -race; affected lifecycle tests plus encode/upload failure-and-reuse challenges passed 30 race repetitions; array differential fuzz passed 69,712 executions. Parser benchmarks confirm 22,528/33,408 -> 4,096 B/op, with 2/3 -> 1 allocations. The additional metadata-burst challenge fails on this head; preserving complete objects and spooling one object per frame passes both control runs. These are white-box writer/real LocalFS checks, not an end-to-end SQL reproduction.

CI SCA and both BVT jobs are green. The separate UT failure contains six cluster-bootstrap timeouts and TestDeleterConcurrentDelete exceeding its 35ms wall-clock assertion; that log does not establish a regression in this upload change. No existing reviewer threads were present.

Comment thread pkg/sql/colexec/insert/controlled_s3.go Resolved

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

Re-reviewed 61eb095 against 4.1.6-hotfix dc4e7ee. The previous P2 is fixed in code, not just marked resolved: both incremental collection and final Sync now spool whole objects independently within the existing frame/output bounds.

Independent local validation (macOS arm64, Go 1.26.4): the original real-writer/LocalFS 20-object backlog challenge now passes. The new 15-object regression fails with the predecessor implementation and passes at this head; empty, single-object and oversized-object controls behave correctly. Insert, colexec and MergeBlock whole-package tests pass; Insert whole-package race and the changed upload test at -race -count=100 pass. Additional partial-burst rejection and spool-write-failure challenges prove pool/FD/lease cleanup and clean reuse.

The shared W coordinator and existing SinkPool remain the authoritative admission/execution owners. No second scheduler, expanded source/output limit or new tuning switch was introduced. Production +499, tests +628 and docs -80 net lines were assessed separately; the added ownership and behavioral coverage have identifiable value. Unchanged admission, sinker, MultiUpdate and parser evidence from the previous review remains applicable, including failure/reuse tests, differential fuzzing and allocation benchmarks.

No remaining code-review blocker found. Latest SCA and both BVT checks are green, but UT is cancelled and CI Required has not passed; this approval does not waive those checks. Full native/TKE importer timing has not been rerun on the final framing fix, so historical timings retain their original source identities.

@XuPeng-SH
XuPeng-SH merged commit 77052f8 into matrixorigin:4.1.6-hotfix Nov 1, 2026
43 of 51 checks passed
XuPeng-SH pushed a commit that referenced this pull request Nov 10, 2026
…32241)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Related to #26992 and #32146. Follow up #31166 and #31810.

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

Preserve bounded import memory, persisted object layout and publication
progress. Head `da633c5deb873932dfd728ad04a30a3886e54561` is based on
`4.1.6-hotfix@a5a8ed4`, with five
commits. [Maintained
design](https://github.com/aptend/matrixone/blob/da633c5deb873932dfd728ad04a30a3886e54561/docs/design/import-memory-control.md).
Paired release PR: #32065.

- 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.

4.1 retains its cancellable legacy D policy. It has no native
statement/CN spill-disk admission API; temporary-volume capacity remains
a deployment requirement. This PR does not backport the 4.2 spill-budget
framework.

Impact: 18 production Go files versus the release base; this correction
touches 8. 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.
- Final `insert`, `multi_update`, and `colexec` owning packages pass
normal and race modes (266 named tests each). Unchanged
publication/ioutil code retains the full owning-package normal/race
evidence from this correction. 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@00da052`. 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=00da05219fb8dce0266de4efa7c4bbfac06491de -c .golangci.yml ./...
make err-check
```

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

Historical acceptance keeps its original revision: `968a69d` completed
two continuous Amway rounds /78 imports (39 tables), 22-GiB cap, RSS HWM
7.789 GiB and cgroup peak 18.641 GiB. Earlier five-round acceptance is a
separate revision. No current-head full-workload performance claim is
made.
XuPeng-SH pushed a commit that referenced this pull request Nov 11, 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 #26992 and #32146. Port #31166 and #31810 together.

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

Port #31166 and #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: #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.

This branch was previously deployed

1 inactive deployment
ci — 61eb095c Deployed Oct 30, 2026 by aptend via Matrixone Coverage execution / Coverage #62394
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/enhancement size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants