Skip to content

fix(frontend): escape CSV values before OUTFILE framing - #30719

Merged
mergify[bot] merged 13 commits into
matrixorigin:mainfrom
daviszhen:fix-30702-outfile-unescape
Oct 22, 2026
Merged

mergify[bot] merged 13 commits into
matrixorigin:mainfrom
daviszhen:fix-30702-outfile-unescape

Conversation

@daviszhen

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Fixes #30702.

What this PR does / why we need it:

CSV OUTFILE previously escaped only backslashes and enclosure bytes in selected string branches. Bare field/line delimiters could split values during LOAD DATA. BIT columns, normally unenclosed, could silently change value (e.g. BIT(8) 44 -> 0).

Encode non-NULL values once at the shared CSV output boundary, for both batch and result-set exporters. This covers strings, raw BIT and custom-delimiter collisions in other scalar types. Keep genuine NULL markers on a separate raw-output path. Preserve enclosure doubling, protect literal backslash-N/NULL, default reader quotes and CR/CRLF bytes, and leave source vectors unchanged. Ordinary values use no extra allocation; escaped values use one exactly sized buffer. JSONLINE/Parquet encoders and normal query execution are unchanged.

For separators beginning with characters interpreted by LOAD's escape rules (0, b, n, r, t, Z), use the configured enclosure when a bare value collides. With no enclosure, reject this unrepresentable configuration before creating the output file rather than reporting a successful, non-restorable export.

Verification

  • Frozen main baseline: 04fe057bd73520cdf30754f79f66f6505060ad1f. A standalone real-client replay reproduced the reported string LOAD error and silent BIT 44 -> 0 corruption, inspecting actual file bytes and loaded values.
  • Real MySQL-protocol regression: 11 OUTFILE -> LOAD DATA round-trips plus one early-rejection/file-nonexistence control, all pass. Covers empty/non-ASCII strings, quotes, literal NULL/backslash-N, genuine NULL, comma/LF/CR/CRLF, multi-byte separators, all 256 BIT(8) byte values, BIT(32), FORCE_QUOTE, decimal-dot delimiters and translated-escape delimiters.
  • Exact-base product overlay (verified baseline export.go blob 5b7130572d3fd8f01a58226a0535cea1fe679816) with the identical real-protocol test: all 12 subcases fail; patched product: all pass. This also catches neighboring quoted-CR and literal-NULL cases.
  • Both CSV writer paths round-trip every BIT byte through LOAD's parser in eight enclosure/FORCE_QUOTE combinations, with small read buffers and a NULL control. Plain-value zero-allocation and input-immutability assertions pass.
  • Targeted frontend and embed regressions pass with vet enabled; configured golangci selection reports 0 issues; diff check passes. Native prerequisites were built and provenance-verified through repository tooling.

Validation limits

The final full frontend run hit two unrelated existing timing assertions: TestConnMeasuresOnlyPhysicalOutputWrite and TestConnMeasuresDelayedBufferedFlush require a strictly positive nanosecond duration for an immediate in-memory write. A bounded 10-repeat control on the unchanged main frontend independently reproduces the first failure. No CSV path is involved; those tests are not disabled or modified. An earlier full frontend run passed, but that does not replace the final-run result. The pinned molint invocation also prints inherited unsafe-recover diagnostics in untouched frontend functions; golangci reports 0 actionable issues. Fresh CI is still required.

@daviszhen
daviszhen requested a review from XuPeng-SH as a code owner October 21, 2026 05:36
@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 Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: c35a8e73ad4f6a6483181f91da5e85730b6c7fe4

"interrupted"

@XuPeng-SH

XuPeng-SH commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-xupeng · done

Commit: c35a8e73ad4f6a6483181f91da5e85730b6c7fe4

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

mo-bot review · mo-bot-xupeng · review

Commit: c35a8e73ad4f6a6483181f91da5e85730b6c7fe4

Assessment: request_changes

Reviewed the complete four-file delta and issue #30702. Centralized escaping addresses the reported delimiter failures, but introduces a confirmed round-trip regression for valid custom enclosure characters.

Model: gpt-6-astra / xhigh

Session: 01a15209-2c6d-71e2-b8f3-aa17387fa283 · slot 2 · generation 0

  • P2 pkg/frontend/export.go:269: Export an unforced numeric/BIT value containing an enclosure byte from 0, b, n, r, t or Z. For example, integer 101 with FIELDS TERMINATED BY ',' ENCLOSED BY '0'.
    Impact: The enclosure fallback checks separator bytes but omits the enclosure itself. The writer emits 1\01, which LOAD decodes to 11. Numeric restoration fails; BIT values silently acquire different bytes. Extend the fallback to translated enclosure collisions and add numeric/BIT regression coverage.
    Evidence: Source-extracted writer/parser probe reproduced all six cases: integer text 313031 became 310031; BIT bytes 616e6263 with enclosure 'n' became 610a6263. Corresponding merge-base bare-output controls and the double-quote control passed. Both production exporters reach this boundary; LOAD's BIT conversion accepts the altered bytes. Retained proof: probe-auto.log and checks/1792565160216729567-3.json.

Validation:

  • Reviewed both exporters, SQL option parsing, LOAD parsing/conversion, NULL handling, buffer ownership, file admission and test lifecycle.

  • Isolation preflight passed. The standalone Go probe executed through test-exec: six regression failures and eight passing controls.

  • Verified exact-head CI run 39550533253: frontend-containing race stage, all eight embed batches and configured SCA completed successfully.

  • Clean source and git diff --check passed. Receipts and logs reconciled in evidence-ledger.json; final audit receipt: checks/1792565372075767339-3.json.

Limitations:

  • The counterexample used extracted production functions with documented dependency adapters, not a full SQL execution; details are retained in probe-manifest.json.

  • No local native product tests were repeated. Retained CI summaries lack individual new-test results, and author-reported baseline/normal-package runs were not independently verified.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Addressed the translated custom-enclosure regression in commit a122fe3.

The common CSV value writer now switches to enclosure/doubling when an unforced value contains an enclosure byte 0, b, n, r, t or Z, instead of emitting an ambiguous backslash escape. It also protects the adjacent N enclosure case, where a lone BIT byte would otherwise become LOAD's \N NULL marker. Genuine NULL values still use the separate raw-marker path. Both batch and result-set exporters use this same boundary; LOAD/parser behavior is unchanged.

The regression executes the actual production exporters and LOAD parser, not extracted copies: every BIT byte plus NULL across nine enclosure settings, force/unforced, and batch/result-set paths (36 combinations). Integer IDs include 101, covering the numeric '0' witness. The expanded test fails before the fix and passes after it.

Real SQL SELECT ... INTO OUTFILE followed by LOAD DATA INFILE also passes for all six translated enclosures, N, default/empty enclosures, FORCE_QUOTE, NULLs and existing string/decimal delimiter controls. Multi-byte BIT32 values include anbc and corresponding values for the other translated enclosures, with exact HEX equality after reload.

Validation:

  • Complete frontend suite -vet=all -count=1: PASS (17.256s).
  • Final embedded SQL round-trip root: PASS (7.774s).
  • Final focused -race exporter/parser and allocation controls: PASS (3.136s).
  • Focused production exporter/parser tests and zero-allocation plain-value control: PASS.
  • Configured frontend/embed static checks exit 0; golangci-lint reports 0 issues (inherited molint diagnostics in unchanged files remain separate).

The old exact-head CI was green; the pushed repair will run fresh CI. Please re-review the enclosure repair.

@XuPeng-SH

XuPeng-SH commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: a122fe3c305a78dbcc1df4cb85c947fda14d3f27

Review completed. Read the assessment.

@XuPeng-SH

XuPeng-SH commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-xupeng · superseded

Commit: a122fe3c305a78dbcc1df4cb85c947fda14d3f27

already-reviewed

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Commit: a122fe3c305a78dbcc1df4cb85c947fda14d3f27

Assessment: request_changes

Reviewed the complete four-file delta and affected callers. Centralizing escaping at the shared CSV writer is appropriate, and the previous custom-enclosure defect is fixed. However, N-leading terminators introduce a confirmed regression that silently converts a non-NULL BIT value to NULL.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1586-7a01-9000-d45e20995cf8 · slot 1 · generation 1

  • P2 pkg/frontend/export.go:271: Export BIT(8) value 78 (byte N) without FORCE_QUOTE using FIELDS TERMINATED BY 'N:' and the default double-quote enclosure, then LOAD with matching options. LINES TERMINATED BY 'N:' also triggers the defect.
    Impact: The fallback protects an N enclosure but omits N-leading separators. Escaping the payload produces \N, which LOAD recognizes as SQL NULL. Both exporters use this boundary. Handle NULL-marker collisions in the shared framing policy, including safe handling or rejection without an enclosure, and add exporter/parser and SQL round-trip regressions.
    Evidence: The source-extracted writer/LOAD-parser probe compared the frozen base and head: base bytes 4e4e3a310a restore N with IsNull=false; head bytes 5c4e4e3a310a produce IsNull=true. LOAD's external conversion then appends a NULL value. Field-terminator, line-terminator and no-enclosure cases reproduced; default-comma and forced-quote controls passed. Evidence: csv-probe-final.log and checks/1792571242883539872-3.json.

Validation:

  • Evidence retained under /home/xupeng/.local/state/mo-bot/jobs/22bf8e0ce4e3b764304cdd9d/attempt-1; review-evidence.json records source hashes, commands, exit receipts, logs and review coverage.

  • Reviewed both exporters, SQL option parsing, LOAD parsing/conversion, NULL handling, buffer ownership, file admission, cleanup and all added tests. Existing tests omit N-leading separator cases.

  • Isolation preflight passed. The standalone probe ran through test-exec, reproduced three regression variants, passed two controls and confirmed seven custom-enclosure repairs. Receipt: checks/1792571242883539872-3.json.

  • Source-extracted writer benchmarks measured the allocation/CPU tradeoff: plain 1 KB strings changed from 223 to 873 ns with allocations reduced from two to zero; densely escaped 1 KB strings changed from 3621 to 2442 ns and two allocations to one. Receipt: checks/1792571565064627199-5.json; log: csv-benchmark.log.

  • Frozen evidence reports successful exact-head Ubuntu UT, arm64 SCA, shared build, coverage and multi-CN BVT checks.

  • Final audit verified the frozen patch, clean source, extracted-code provenance and all local check receipts; git diff --check passed. Receipt: checks/1792571666519659637-4.json; log: review-audit.log.

Limitations:

  • The local reproduction uses extracted production functions with documented dependency adapters, not a native product or SQL execution. An initial invocation stopped before compilation on the Go-version requirement; the corrected standalone invocation completed.

  • The supplied local_validation inventory is empty. CI evidence contains job outcomes without individual test logs; author-reported package, race and SQL runs were not independently attested.

  • Benchmark results cover the common writer only, not full SQL throughput. Ordinary non-export SELECT/DML/DDL paths do not call the changed encoding logic.

  • The separate issue #30702 body was not supplied; its behavioral contract was assessed from the PR description.

@XuPeng-SH

XuPeng-SH commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: e10663ded4fe6d6ca5167f4541d60f3a186a3e2b

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Commit: e10663ded4fe6d6ca5167f4541d60f3a186a3e2b

Assessment: request_changes

Reviewed the complete delta and supplied concerns. Centralizing CSV escaping is sound, and previous findings have passing regressions. One confirmed round-trip regression remains in framing admission.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

  • P2 pkg/frontend/export.go:797: Export (id=1, b=6382178) with b BIT(24), backslash field termination, CR enclosure, LF line termination and no FORCE_QUOTE; then LOAD using matching options.
    Impact: OUTFILE succeeds, but automatic quoting inserts CR bytes that LOAD treats as record boundaries, causing error 20301. Reject CR enclosure for LF termination before opening the file, accounting for every boundary recognized by the reader.
    Evidence: Both production exporters and real SQL reproduce this regression. Candidate bytes are 0d310d5c0d6162620d0a; the exact merge-base exporter emits 315c6162620a and reloads successfully. An n: separator with BIT bytes 616e62 also regresses. Ordinary controls pass on both versions. See probes.jsonl and base-probes.jsonl; receipts 1792643420732088320-3.json (exit 1) and 1792643449327463900-3.json (exit 0).

Validation:

  • Isolation preflight passed. Reconciled 192 native inputs and seven outputs with current sources and the retained repository build receipt.

  • Nine focused test roots passed: 88 writer/parser combinations, 44 SQL round trips, 16 rejection cases and both modified timing tests.

  • A 396-configuration diagnostic narrowed failures to CR enclosure with LF termination. Targeted probes confirmed two introduced cases through both exporters and SQL; all 12 corresponding baseline subcases passed.

  • Fifteen export rotation, error, cancellation, ownership and cleanup test roots passed.

  • Verified clean frozen source, patch correspondence, exact baseline overlay, commands, logs and exit receipts. Evidence: /home/xupeng/.local/state/mo-bot/jobs/812a5aceb694afe7197e8322/attempt-1/review-evidence.json. Final audit receipt: 1792643623063941818-3.json.

Limitations:

  • Full repository, race and distributed suites were not repeated. Frozen CI reports success; local_validation is empty and raw author/CI logs were not supplied.

  • Baseline comparisons restore the sole changed production file through an overlay; SQL tests use a single-CN fixture.

  • Audited prior-head helper benchmarks show fewer allocations but higher CPU cost for plain values. These are not current-head or SQL-throughput measurements. Ordinary non-export SELECT/DML/DDL bypass this encoder.

  • The linked issue body was not separately supplied; its contract was assessed from the frozen PR description and discussion.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Addressed the CR-enclosure/LF-termination P2 from the exact-e10663ded4 review.

The shared pre-open CSV admission check now follows the reader's full newline contract: default, LF and normalized CRLF termination recognize both CR and LF. A CR enclosure is therefore rejected even when CR is absent from the configured terminator. This happens before opening the file or creating async reader/writer/group resources, including with escaping disabled. Custom non-newline record terminators still allow CR enclosure. The encoder and LOAD parser are unchanged; the additional check is constant work per file, not per row.

Reproduced against the original production head with new real SQL cases: BIT(24) 6382178 (616262) with backslash field separation and BIT(24) 6385250 (616e62) with n: separation both export successfully but fail matching LOAD with error 20301, with or without FORCE_QUOTE. The generated bytes and LOAD errors are retained in the red log. New custom-line CR-enclosure controls pass on that original code, and remain passing after the fix.

Regression coverage retains all previous cases and adds:

  • Pre-open rejection for both recognized newline bytes across default/LF/CRLF configurations, both field separators, and escaping enabled/disabled; asserts no output file or async resources.
  • Both production exporters plus the real CSV parser: 104 format/width/force/exporter combinations, including all bytes and NULL, with valid CR enclosure/custom-line controls.
  • Real SQL: 48 byte-exact ID/HEX/NULL roundtrips and 20 rejection cases, including the two reported BIT(24) values and forced/unforced variants.

Validation on Go 1.27.1 / darwin-arm64 with repository-native provenance verified:

  • Original production + new rejection regressions: FAIL as expected; actual OUTFILE/LOAD failure reproduced.
  • Focused frontend and real SQL: PASS (1.586s / 8.965s).
  • Complete frontend suite with -vet=all -count=1: PASS (15.812s).
  • Configured frontend/embed static target: exit 0, golangci-lint 0 actionable issues (16.795s); formatting and git diff --check pass.
  • Focused writer/framing/allocation and real SQL with -race -vet=all -count=1: PASS (frontend 3.203s / embed 15.409s). This is a bounded race pass, not a repeated stress or throughput claim; the production delta adds no shared state or synchronization.

The inspected exact-head CI, including UT and CI Required, was already successful, so there was no failing old job to rerun. Fresh checks triggered by this update are separate and are not claimed green. Local SQL uses the single-CN fixture; no new distributed/full-repository suite or SQL-throughput benchmark is claimed. Please re-review the framing correction.

@XuPeng-SH

XuPeng-SH commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: e4e3c9e509274c5dfc55e47b643199ec9cbdf82b

Review completed. Read the assessment.

@XuPeng-SH

XuPeng-SH commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-xupeng · superseded

Commit: e4e3c9e509274c5dfc55e47b643199ec9cbdf82b

"interrupted"

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Commit: e4e3c9e509274c5dfc55e47b643199ec9cbdf82b

Assessment: approve

Reviewed the complete five-file delta, callers, LOAD parser, resource ownership and prior review concerns. Shared-boundary escaping correctly replaces per-type handling, preserves NULL identity and input bytes, and rejects ambiguous configurations before file creation. The added branches follow existing decoder rules without introducing shared state or duplicate execution paths. No actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

Validation:

  • Verified frozen HEAD, merge-base, patch equality and unchanged source. Evidence, commands, source fingerprints, exit receipts and log hashes are reconciled in /home/xupeng/.local/state/mo-bot/jobs/6ea326896da4b202914f79bc/attempt-1/review-evidence.json; final audit receipt: checks/1792656287066221287-4.json.

  • Isolation preflight passed. Rebuilt incompatible native prerequisites through the current repository build target; verified 194 native input hashes and five output hashes before accepting test results.

  • Targeted frontend/embed tests passed: 104 exporter/parser combinations, 48 real MySQL-protocol OUTFILE-to-LOAD round trips, 20 rejection/no-file controls, allocation/immutability checks and both modified timing tests. Receipt: checks/1792655861520642339-4.json; log: focused.jsonl.

  • Independent production-writer/parser matrix passed 384 accepted configurations. Selected cancellation, cleanup, saved-result, error and file-splitting tests also passed. Receipt: checks/1792655967162414552-4.json; log: matrix.jsonl.

  • Current candidate versus merge-base writer benchmarks passed. Median plain 1 KiB cost increased from 259.9 to 943.1 ns while allocations fell from two to zero; escape-heavy values improved from 3825 to 2816 ns with two allocations reduced to one; integer formatting increased from 6.621 to 27.46 ns. This bounded CSV-export tradeoff is acceptable for correctness. Ordinary SELECT/DML/DDL and JSONLINE/Parquet bypass the encoder. Receipt: checks/1792656086300445685-6.json; log: benchmarks.log.

  • Frozen current-head CI reports successful Ubuntu unit tests, arm64 static analysis, coverage and multi-CN PROXY/PESSIMISTIC checks. Earlier delimiter, enclosure, NULL and newline concerns were checked against current code and passing regressions.

Limitations:

  • Local execution was targeted Linux/amd64 validation; no fresh full-suite or race rerun. Raw CI logs and author-reported Darwin/race logs were not supplied and are not counted as locally reproduced.

  • Benchmarks measure the CSV writer, not end-to-end SQL throughput or concurrent workload scaling.

  • The supplied evidence omits issue #30702's body; its behavioral contract was assessed from the frozen PR description, discussion and production-entrypoint regressions.

@mergify mergify Bot added the queued label Oct 22, 2026
@mergify

mergify Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-22 08:08 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-10-22 09:45 UTC · at 75ae9a79d626622e6ccec0bcb28412f5fcf84c7f · squash

This pull request spent 1 hour 37 minutes 39 seconds in the queue, including 1 hour 19 minutes 10 seconds running CI.

Required conditions to merge

This branch was previously deployed

1 inactive deployment
ci — f9bcc1fc Deployed Oct 22, 2026 by mergify[bot]
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/test-ci size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: CSV OUTFILE leaves delimiters unescaped in unquoted values, breaking round-trip

3 participants