Skip to content

[4.2-dev] fix(export): bound ETL merge memory and LOAD SQL - #32991

Merged
XuPeng-SH merged 6 commits into
matrixorigin:4.2-devfrom
XuPeng-SH:fix/32411-etl-memory-4.2
Nov 20, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:4.2-devfrom
XuPeng-SH:fix/32411-etl-memory-4.2

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Nov 20, 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 #32411.

What this PR does / why we need it:

ETL merge used to retain all CSV records and construct one escaped LOAD statement. A large file could exceed the MySQL packet limit after several full-size allocations.

Read one CSV record at a time. Compute the escaped SQL size before growing the output and encode directly into it. Target 4 MiB per LOAD, with an explicit ceiling of 24 MiB or the destination connection's packet limit, whichever is smaller. A row beyond the limit returns an error and leaves its source file recoverable. Merge no longer uses the shared CSV buffer pool. The deprecated TAE input decoder retains its existing behavior.

Small files use one LOAD. Multi-statement files use one transaction and commit after a clean EOF. An import failure retains the source. One merge at a time can pin a connection, leaving capacity in the shared pool for live reporting.

Validation includes exact comparison against legacy CSV/SQL encoding, record and packet budgets, failure and rollback tests, and a local CN probe that rolled back a multi-chunk import after a source error and checked all 180 mixed-width rows after retry. Encoding-only measurements on Linux/amd64 lowered allocated bytes by about 63% for small fields and 79% for mixed field sizes, with median times about 6% and 8% lower. End-to-end production throughput and RSS remain to be measured.

A SQL failure during BEGIN, LOAD, COMMIT, or ROLLBACK contributes at most one failure per file to the existing reconnect threshold. Source-only errors and caller cancellation during import do not drive CN rotation. The MySQL driver's read and write timeouts bound stalled transaction I/O. If the server commits but its reply is lost, the source is retained. A later retry checks the first record for statement_info. Other tables can replay the file and may produce duplicates depending on destination constraints.

Remove the unused parse_failed metric series. CSV reader errors still count as read_failed.

During connection acquisition and packet-budget lookup, caller cancellation reported by the operation no longer increments the shared reconnect budget. Internal timeouts and independent connection or SQL errors still count, including when they race with caller cancellation. An operation-specific timeout cause keeps the two deadline sources distinct. Transport errors without a caller-context error identity remain conservatively counted.

Final incremental validation with Go 1.26.4 passed for the affected export and metric packages: unit tests under the race detector, gofmt, vet, and repository lint. Public-entry regression tests cover blocked pool acquisition, canceled packet lookup, internal and caller deadline ordering, shared timeout causes, provider failure, and independent SQL failure concurrent with cancellation. Each new concurrency regression also passed 100 race repetitions. Existing transaction tests cover failed BEGIN and COMMIT, failed rollback with the original error preserved, and a canceled LOAD.

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

Copy link
Copy Markdown
Contributor

This pull request is merged.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

QA verification record (independent adversarial probes; repo unit tests untouched)

All probes are new QA32991-prefixed tests executed only via -run 'QA32991'; the SQL path was asserted byte-exactly against sqlmock; build via mo-cgo-test.

Encoding correctness - pass. mergeRowSize + appendMergeRow compared byte-for-byte against the legacy pipeline (SQL-escape + encoding/csv) over an adversarial matrix: empty fields, leading/trailing/interior spaces, tab, NBSP, NUL byte, invalid UTF-8 (\xff\xfe), the \. special case, quote/backslash/comma/CRLF mixes, a 16 KB quote-dense field, emoji/CJK. Byte-identical everywhere; size estimation is byte-exact (buffer pre-sizing neither short nor wasteful).

Chunk / limit / transaction semantics - pass. Accept at n == limit-overhead exactly; +1 byte rejects with clean InvalidInput and zero LOADs issued. Multi-chunk file: BEGIN precedes the first chunk flush, so the first LOAD can never land outside the tx. Oversized first row becomes its own in-tx chunk; single-chunk files stay single-statement. Exec failure leads to deferred Rollback and the original error propagates. 4->2->5 column rows reuse the quotes slice without stale quoting.

Reader semantics - pass; one suspected regression proved to be parity. Comments/blank lines skipped only between records; quoted # is data; unquoted leading-# skipped (same convention as legacy simdcsv); TrimLeadingSpace; record byte-limit exact across the bufio boundary (4095/4499 in, 4501 out) and at exact EOF. The reader normalizes \r\n to \n inside quoted fields; probing legacy simdcsv with identical input also returns c\nd, so this is fidelity parity, not a regression.

Performance re-measured independently (encode path, 10k rows x 6 fields per op, -benchtime=2s -count=3): allocs/op 10011/10014 down to 0; B/op 3.06 MB -> 1.2 KB (small) and 17.7 MB -> ~75 KB (mixed); ns/op ~2.2 ms -> ~1.35 ms (small, -38%) and ~6.5 ms -> ~7.0 ms (mixed, roughly par). The verified story is zero-allocation steady state plus bounded memory (chunks capped by min(4 MiB target, 24 MiB, session packet-2)), not latency.

Non-blocking follow-ups (source-level):

  1. tx.Commit()/tx.Rollback() (merge_file.go :178/:97) carry no deadline - database/sql Tx has no ctx form. A hung COMMIT reply pins mergeFileSlot (process-wide, cap 1) and stalls all merges. Newly introduced by the tx design (legacy had no tx; every statement was 10s-bounded). Suggested: drive BEGIN/COMMIT/ROLLBACK manually over the already-pinned conn via ExecContext with the same WithTimeoutCause(..., CauseWriteRowRecords); the ambiguous-commit case already lands in the retained-source path, so semantics are unchanged.
  2. Commit-reply-lost retains the source: statement_info retries are idempotent via the first-record check; other tables would re-import the whole file - a strictly narrower window than legacy's partial-write replay.
  3. TraceETLMergeParseFailedCounter is unreachable after the ParseRow removal (observability only).

Not covered: end-to-end CN throughput/RSS; the MO-side LOAD parser was not probed directly (covered by the author's local CN probe with rollback/retry).

Also attached as a comment on the head commit for archival: 7fc3314#commitcomment-211003722

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

The earlier QA follow-ups were checked against this head: transaction I/O uses the configured MySQL read/write timeouts, and the unused parse-failure metric was removed. One cancellation path below still contradicts the intended reconnect classification. I reproduced it with a canceled packet-limit query against WriteMergeFile; current CI is green. The documented ambiguous-commit replay limitation for non-statement tables remains.

Comment thread pkg/util/export/etl/db/merge_file.go Resolved
@matrix-meow matrix-meow added size/XL Denotes a PR that changes [1000, 1999] lines and removed size/L Denotes a PR that changes [500,999] lines labels Nov 20, 2026

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

Codex automated review

Reviewed the diff origin/4.2-dev...HEAD at f9dc97d (8 files, +873/−233), which replaces the unbounded whole-file ETL merge (SliceCache + one oversized LOAD, issue #32411) with streaming reads, bounded 4 MiB LOAD chunks capped at min(24 MiB, max_allowed_packet−2), one transaction per multi-chunk file with source retention on failure, a single global merge slot, and a +1 connection in the writer pool. The one previously raised P2 (caller cancellation during conn acquisition or the packet query inflating the shared DBConnErrCount reconnect budget, filed against commit 4b6701f) is addressed on this head by commits de67197 (countPreflightError classification plus 263 lines of synctest-based coverage) and f9dc97d (a distinct errors.Join(CauseWriteRowRecords) timeout cause so callers using the same cause cannot be mistaken for the internal timeout). I verified that classification from first principles and the full pkg/util/export/etl/db suite passes (−v log has all PASS entries) including under −race, so I treat that finding as resolved rather than re-raising it. The earlier QA follow-ups are resolved or documented: the writer pool DSN readTimeout=10s/writeTimeout=15s bounds context-less COMMIT/ROLLBACK I/O, database/sql schedules automatic tx rollback when the task context is canceled, ambiguous commit replies retain the source just like the base autocommit reply loss, and the removed parse-failed metric was dead because ParseRow was a no-op pass-through, so no validation was lost. Independent checks: mergeRowSize/appendMergeRow are byte-identical to the legacy SQL-escape plus encoding/csv pipeline over an adversarial matrix (NUL bytes, invalid UTF-8, NBSP, quote/comma/CRLF mixes, 16 KB fields) verified in a scratch replica of the head code (25/25 checks) and by the author's TestMergeRowEncoding; reader comment/blank-line skipping, EOF and exact-limit boundary semantics including the bufio edge all verify; the packetLimit−2 accounting matches the vendored matrixorigin/mysql connector source exactly; stdlib DB.Conn uses the context for acquisition only, so canceling it before reusing the checked-out conn is safe; chunk/transaction/rollback behavior is covered by ten sqlmock scenarios; the removed TAE r.Close() was a nil-receiver panic that can now never fire; IsRecordExisted's early return preserves the behavior of its single caller; the retry sleep is now cancellable; and no stale references to removed symbols remain. Limitation: pkg/util/export and its new TestContentReaderBoundedRecords could not be compiled in this checkout because the pre-existing etl→objectio→vectorindex→usearch chain needs thirdparties artifacts (usearch.h) that are not built here; per review policy I did not build those prerequisites and verified the reader logic statically plus via a scratch replica instead. No end-to-end import against a live CN was run here; that path is supported by the author's documented local CN probe and the transaction tests. I found no new blocking or non-blocking defects, so there are no findings attached.

This branch was successfully deployed

No deployments
ci — fe253ef2 Deployed Nov 20, 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/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