Skip to content

fix(outfile): accept FIELDS ESCAPED BY/LINES STARTING BY and reject non-UTF-8 Parquet exports (#30710) - #31100

Merged
XuPeng-SH merged 26 commits into
matrixorigin:mainfrom
daviszhen:fix-30710-outfile-syntax-utf8
Oct 28, 2026
Merged

XuPeng-SH merged 26 commits into
matrixorigin:mainfrom
daviszhen:fix-30710-outfile-syntax-utf8

Conversation

@daviszhen

@daviszhen daviszhen commented Oct 25, 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:

issue #30710 (consolidates #30754)

What this PR does / why we need it:

Fix two defects in SELECT INTO OUTFILE: rejected FIELDS ESCAPED BY / LINES STARTING BY syntax, and successful Parquet exports whose text contains invalid UTF-8.

  • Reuse LOAD's FIELDS/LINES grammar, preserving OUTFILE defaults and explicit empty escaping. Serialize both clauses and regenerate the MySQL parser.
  • Update both CSV writers: prefix every data record, leave the header unprefixed, honor the escape byte for all value types, and reject the covered framing/value combinations which LOAD would silently misread. LOAD's clause/default mapping is shared with the replay validator, not independently maintained.
  • Validate NULL lazily once per statement for each actual boundary (field separator versus record terminator), safely shared by conversion workers and reused across file rotation. Statements without an offending NULL still export normally. Keep the existing corruption regressions, including overlapping NN/NNN separators and enclosure/escape collisions.
  • Validate raw textual Parquet values before publishing the affected row group. Binary-flagged VARCHAR/VAR_STRING/STRING/TEXT/BLOB-family columns use unannotated BYTE_ARRAY, rather than incorrectly tagging arbitrary binary bytes as UTF8. Other text retains STRING/UTF8 annotation. Existing files are not rewritten.

Compatibility limits are deliberate, including for existing OUTFILE syntax: delimiters beginning with double quote, CR, LF, NUL or an invalid rune are rejected before opening the file, even without either new clause. For example, FIELDS TERMINATED BY '"|' ENCLOSED BY '' no longer emits a file for an external-only consumer. Ambiguous enclosure/terminator and prefix/terminator combinations are also rejected. This is not a blanket unchanged-writer or universal-round-trip claim; disabling escaping can still emit unprotected separators. Details and alternatives: OUTFILE framing contract.

Validation:

  • Full frontend, external, MySQL parser, tree and csvparser package tests pass. Incremental vet and configured lint across all changed Go package roots report 0 issues.
  • Serialized Parquet footer and library-reader regressions distinguish binary BYTE_ARRAY from text STRING/UTF8. The new assertions fail against pre-fix production sources, including actual VARBINARY/BINARY metadata forms.
  • The new concurrent NULL-boundary test passes 100 race repetitions; the complete frontend package passes under race.
  • On the preceding reviewed head, independent-process Docker topology (LOG/TN/CN1/CN2/proxy), normal golden comparison in CI's -n mode: HNSW 58/58 and CSV/Parquet 240/240 pass twice via the proxy, and twice via direct CN2. Account/user/global/database cleanup is checked after each run; all owned processes are stopped and joined. Earlier -launch checks used multiple CNs inside one process and are not independent-cache validation.
  • Merged main 66c9e7624e, preserving both its bounded strict-CSV-probe constructor and this PR's shared LOAD configuration, and regenerating the SQL parser from the combined grammar, including the newly merged integer-literal precision handling. The previous reviewed head's full CI is green; new merge-head CI is pending. The upstream HNSW freshness fixture remains unchanged by this PR; no redundant cache-eviction workaround is retained.
  • Benchmarks cover both real CSV writers, eight-column ordinary/50%-NULL rows, default/custom escaping and 128-row batches. Paired precompiled-binary samples versus pre-fix head 4c51b0a show NULL-heavy formatting 61–68% faster; ordinary controls range from 0.8% faster to 12.2% slower, with unchanged allocations. These are shared-development-host, in-memory formatting measurements, not full file/network throughput or a no-regression certification; detailed results are in the review reply.

… INTO OUTFILE (matrixorigin#30710)

The OUTFILE grammar only accepted TERMINATED BY/ENCLOSED BY in a fixed
order, rejecting two clause families that LOAD DATA accepts end to end
(serialized as issue matrixorigin#30754). Reuse the LOAD field_item productions for
the OUTFILE FIELDS clause (any order, merged over the historical OUTFILE
defaults) and mirror load_lines for the LINES clause, so both statements
from matrixorigin#30754 parse and keep their semantics.

The writer now honors them byte-exactly: LINES STARTING BY prefixes
every data record while the CSV header stays unprefixed, so LOAD's
startingBy line filter skips the header instead of importing it; the
FIELDS ESCAPED BY byte (including '' disabling escaping) reaches the
existing escaping path. STARTING BY containing the record terminator is
rejected up front with the same error text LOAD's csvparser reports.
ExportParam.String() tolerates the now-optional EscapedBy and renders
STARTING BY.

Parser/serialize round-trip tests pin the clause matrix; writer tests
round-trip output through LOAD's csvparser; a distributed BVT case
covers the exported bytes and LOAD round-trip.
…trixorigin#30710)

A Parquet String() column is UTF-8 by definition, but the export wrote
VARCHAR-family bytes verbatim, reporting success for a file that
MatrixOne's own parquet loader then refuses (ERROR 20301, invalid UTF-8
value for VARCHAR). NewParquetWriter now classifies every column whose
values land in a String() node with string semantics, and
writeBatchChunk rejects the first invalid value with the same error
shape and code the loader reports, before any row group reaches the
file. Binary-declared columns (BINARY_FLAG: VARBINARY/BINARY/binary
BLOB) keep the loader's exemption and round-trip losslessly.

Unit tests pin the VARCHAR/TEXT/CHAR rejection message, the
no-bytes-emitted behavior, the valid-UTF-8 control, the binary-flag
exemption, and the column predicate; a distributed BVT case replays the
issue scenario and all controls through LOAD DATA.
@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 →

@matrix-meow matrix-meow added the size/XXL Denotes a PR that changes 2000+ lines label Oct 25, 2026
@daviszhen

Copy link
Copy Markdown
Contributor Author

Verification evidence (head f5306f7508551b54a7c8e13806d35e9958824f45)

Part A — FIELDS ESCAPED BY / LINES STARTING BY in SELECT INTO OUTFILE

Root cause: pkg/sql/parsers/dialect/mysql/mysql_sql.y export_fields had
rigid alternatives for FIELDS TERMINATED BY/[OPTIONALLY-less] ENCLOSED BY
only (no ESCAPED BY), and export_lines_opt accepted only
LINES [TERMINATED BY]. Both clause values already exist on
tree.Fields/tree.Lines and the CSV writer already honors EscapedBy, so
only the grammar blocked them.

Fix: mysql_sql.y reuses LOAD's field_item_list merge for
export_fields and mirrors load_lines in export_lines_opt (mysql_sql.go
regenerated with repo goyacc, 0 conflicts); pkg/frontend/export.go
(constructByte, exportDataFromResultSetToCSVFile, validateCSVFraming)
emits the STARTING BY prefix per data record (header intentionally unprefixed)
and rejects terminator-containing prefixes with the same text as LOAD's
csvparser.

UTs: TestSelectIntoOutfileFieldsEscapedBy,
TestSelectIntoOutfileLinesStartingBy,
TestSelectIntoOutfileFieldsLinesCombined,
TestSelectIntoOutfileFieldsLinesInvalid, TestExportParamStringClauses,
TestOutfileLinesStartingByPrefixedOnDataRecords,
TestOutfileLinesStartingByHeaderUnprefixed, TestOutfileEscapedByHonored,
TestOutfileStartingByContainingTerminatorRejected.

Live (image matrixorigin/matrixone:main-a648b13e53, port 26010):

Pre-fix:

select 1 into outfile '/tmp/o1.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '' ESCAPED BY '\\';
-- ERROR 1064 (42000): ... syntax error at line 1 column 83 near " ESCAPED BY '\\'";
select 1 into outfile '/tmp/o2.csv' LINES STARTING BY '>>' TERMINATED BY '\n';
-- ERROR 1064 (42000): ... syntax error at line 1 column 50 near " STARTING BY '>>' TERMINATED BY '\n'";

Post-fix (same instance, binary sha below):

-- both statements above now execute; exported bytes:
o1.csv:      1
o2.csv:      >>1
prefix.csv:  a,b              <- header never prefixed
             >>"alpha","beta"
             >>"gamma","delta"
             >>"x##y","p,q"   <- ESCAPED BY '#'
LOAD DATA INFILE '/tmp/prefix.csv' ... ESCAPED BY '#' LINES STARTING BY '>>' ...
select * from sb_back order by a;  -> alpha/beta, gamma/delta, x#y/p,q (exact)

Part B — Parquet export of non-UTF-8 VARCHAR

Root cause: pkg/frontend/export_parquet.go vectorValueToParquet
converted T_char/T_varchar/T_text bytes verbatim into a Parquet String()
(UTF-8 logical type) node; the loader
(pkg/sql/colexec/external/parquet.go) refuses the same bytes for those
targets via utf8.Valid, so a "successful" export could not be read back.

Fix: NewParquetWriter marks columns whose values land in a String()
node with string semantics (text family without BINARY_FLAG);
writeBatchChunk validates utf8.Valid and fails with the loader's error
text/code before any bytes are written. BINARY_FLAG columns are exempt,
matching the loader, so VARBINARY/BINARY stay lossless.

UTs: TestParquetExportRejectsInvalidUTF8,
TestParquetUTF8ColumnPredicate.

Live: with src(id,s) = (1,'plain'),(2,x'FF'),(3,'after'),(4,x'61FF62'):

Pre-fix: export succeeded, wrote a 444-byte parquet; LOAD DATA ... format='parquet' →
ERROR 20301 (HY000): invalid input: invalid UTF-8 value for VARCHAR.

Post-fix:

SELECT id,s FROM src ORDER BY id INTO OUTFILE '/tmp/mo_bad_utf8_30710.parquet' FORMAT 'parquet';
-- ERROR 20301 (HY000): invalid input: invalid UTF-8 value for VARCHAR
-- in-container: ls /tmp/mo_bad_utf8_30710.parquet -> No such file or directory (no partial file)
-- source bytes unchanged: 706C61696E / FF / 6166746572 / 61FF62
-- TEXT variant rejects identically: invalid input: invalid UTF-8 value for TEXT

Controls on the same instance — valid-UTF-8 VARCHAR parquet round-trip
(68C3A96C6C6F / E4B896E7958C / 706C61696E), VARBINARY parquet round-trip
(706C61696E / FF / 61FF62, lossless), default CSV framing unchanged — all
byte-exact.

Fixed binary (built from f5306f75):
69e024723c0cc9cbddfc6f3cae0825ca454bf8cd51ba5e2d346f61e29b52fad2 /tmp/mo-30710

BVT: new deterministic cases
test/distributed/cases/stage/select_into_outfile_fields_lines.sql and
test/distributed/cases/stage/parquet_outfile_invalid_utf8.sql replay green
against their goldens; neighboring outfile/stage cases replay identically vs
the pristine image.

@XuPeng-SH

XuPeng-SH commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: f594e545ccaaef8957e0cc2217cb98e37071c046

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: f594e545ccaaef8957e0cc2217cb98e37071c046

Assessment: request_changes

Reviewed the complete delta and affected callers. Grammar reuse and Parquet validation fit the existing owners, but the new prefix/header policy can silently import header fragments as data.

Model: gpt-6-astra / xhigh

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

  • P2 pkg/frontend/export.go:574: Use LINES STARTING BY with the default header enabled when the prefix occurs in a column name. For example, export SELECT 'alpha' AS name with LINES STARTING BY 'n', then LOAD using matching clauses.
    Impact: LOAD imports an extra 'ame' row alongside 'alpha', violating the claimed automatic header-skipping contract. Validate header/prefix collisions before opening the file or adopt an unambiguous header policy, and add a SQL regression.
    Evidence: The SQL probe produced bytes "name\nn"alpha"\n" and loaded [["alpha"],["ame"]]. csvparser.readRecord uses bytes.Index on the entire line, so leaving the header unprefixed does not guarantee exclusion. Reproduction: review_pr31100_test.go, sql-probes.log; receipt checks/1792936494381538125-3.json.

Validation:

  • Preflight passed. All 192 native build inputs matched retained artifacts, and the repository provenance verifier passed.

  • Parser regeneration matched the candidate byte-for-byte. All pkg/sql/parsers/... tests and focused frontend export tests passed; receipts 1792936071682352889-3, 1792936127612800242-3 and 1792936181442917166-3.

  • SQL probes passed CSV prefix/custom-escape round trips with multiline values and NULLs. The header-collision assertion failed as described above.

  • Parquet SQL probes passed valid text/binary round trips, early invalid UTF-8 rejection, late failure without an unsplit file, and subsequent successful export. All 147 retained split files loaded successfully, containing rows 1–8967; receipt 1792936561938782819-3.

  • An initial diagnostic error-message expectation had incorrect capitalization; correcting it and rerunning the Parquet scenario passed. This was not a product failure.

  • Commands, source fingerprints, exit receipts and logs were reconciled in /home/xupeng/.local/state/mo-bot/jobs/b92277cc81af58436b7b80a6/attempt-1/review-audit.json. Source remains unchanged.

Limitations:

  • Author runtime evidence names an earlier commit; it was not treated as current-head validation. Raw CI logs and separate linked-issue bodies were absent.

  • SQL validation used the local single-CN fixture, not distributed BVT replay.

  • Performance was assessed structurally, without benchmarks: prefix work scales with emitted bytes and UTF-8 validation scans textual Parquet values; ordinary non-export execution paths are unchanged.

@mergify mergify Bot added the kind/bug Something isn't working label Oct 25, 2026

@iamlinjunhong iamlinjunhong 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 f594e545ccaaef8957e0cc2217cb98e37071c046 against base 12eeeb0205b5e87faef48660ddbcd8cb5e18baea, including all 13 changed files, generated parser consistency, CSV writer/loader paths and Parquet validation/finalization. Two nonblocking correctness findings remain; no confirmed P0/P1. Event: COMMENT.

  1. [P2] Do not assume an unprefixed header is excluded by STARTING BY — pkg/frontend/export.go:574–579.

    Trigger: SELECT 'alpha' AS name INTO OUTFILE 'out.csv' LINES STARTING BY 'n' with the default header, then LOAD into a one-column VARCHAR table using the matching clauses. The output is name\nn"alpha"\n. openNewFile writes the header unchanged, while csvparser.readRecord searches the entire line with bytes.Index, rather than requiring the prefix at offset zero. It therefore consumes the n in name and imports ame as an extra row before alpha. The same ambiguity recurs for split-file headers. Validate header/prefix collisions before opening a file, or use an unambiguous header policy, and cover a prefix occurring inside a column name. The existing header test uses only the noncolliding >> prefix.

  2. [P2] Preserve literal NULL-marker text with custom escape bytes — pkg/sql/parsers/dialect/mysql/mysql_sql.y:6958–6959.

    Trigger: export a VARCHAR containing the two bytes 5C4E (literal backslash followed by N) with FIELDS ESCAPED BY '#' HEADER 'false', then LOAD with the same fields configuration. The newly accepted escape setting reaches addEscapeToString, which leaves that value unchanged and writes a quoted "\N" record. LOAD's newCSVParserFromReader still configures a Null list containing literal \N and leaves QuotedNullIsText false; unescapeString therefore returns IsNull=true, silently replacing the string with SQL NULL. With the previous/default backslash escape, the writer emits two backslashes and the loader correctly preserves the non-NULL value. This is newly reachable through the OUTFILE grammar, and violates the explicit custom-escape round-trip acceptance criterion. Ensure literal marker text and SQL NULL remain distinguishable and add a regression including both values; the current custom-escape tests cover NULL but not literal \N.

Validation:

  • Regenerated mysql_sql.go with the repository goyacc in a temporary directory and ran gofmt: byte-identical to the committed file, with no conflicts reported.
  • Ran isolated probes using an unchanged copy of csv_parser.go and unchanged selected CSV writer helpers. They reproduced both findings; the noncolliding-prefix and default-backslash controls preserved the expected rows/values. Only error construction, bytes-to-string conversion and the configuration limit used minimal dependency shims. These probes did not run a SQL server or storage layer.
  • Attempted focused Go package tests for csvparser, MySQL parsing and tree serialization. Compilation was blocked by missing native dependency headers (roaring.h, xxhash.h, usearch.h, jemalloc.h); these tests are not reported as passing. Full frontend/runtime/BVT tests were not rerun locally.
  • git diff --check and the Loom PR artifact check passed. Source remains unchanged.
  • Dispatched checks: all 30 completed (14 success, 14 skipped, 2 neutral). Live read-only metadata confirms the same head/base, mergeable=true, mergeable_state=behind.

History: no previous review from this reviewer is present. Review 5643569067 independently reported the header collision; its severity does not warrant REQUEST_CHANGES under this review policy. The author's verification comment predates that review and is not a response to it. No corresponding author reply is present in the reviewed conversation/review comments, so the P2-reply approval exception does not apply.

Comment thread pkg/frontend/export.go Resolved
…matrixorigin#30710)

LOAD's startingBy line filter only skips a line entirely when the prefix is
absent from it; a line merely containing the prefix keeps its remainder as a
record. The CSV header is written unprefixed so the filter skips it, but a
column name containing the prefix (e.g. `name` with LINES STARTING BY 'n')
would keep the mangled remainder as a data row on LOAD. Detect the collision
exactly the way the reader scans the raw line bytes and reject the statement
before any file is opened, with HEADER 'false' as the documented escape
hatch. Adds UT coverage for single-cell and terminator-spanning prefixes and
a BVT probe replaying the reported scenario.
@daviszhen

Copy link
Copy Markdown
Contributor Author

Fixed the actual-following-delimiter review finding in f2132ef.

Before the fix, a real local Docker OUTFILE/LOAD probe reproduced the reported corruption: NULL,12 with separator NN and escape # produced hex 5C4E4E4E31320A; LOAD returned non-NULL backslash and N12.

The shared replay now uses the exact emitted boundary and explicit last-column position from both writers. Non-final fields include an empty next-field witness and must decode to precisely the expected fields and one record. This catches suffix/delimiter overlap, rejects unsafe NULL framing before publishing a row, and retains safe last-column NULLs and default-backslash controls. It preserves the existing rejection policy and error class rather than changing NULL quoting policy.

Extended the existing regression suites: NULL first/middle/last, NN/NNN/comma, custom/default escape, both batch and result-set writers, plus final/non-final pooled-parser reuse. The new counterexample suite had eight incorrect acceptances before the fix and passes after it. An old type-formatting fixture that concatenated fifteen fields without any boundaries now uses normal export-parameter initialization; its success assertion is retained.

Validation on Go 1.27.1 / Linux arm64:

  • Focused OUTFILE regressions, full frontend and CSV parser packages: pass.
  • Exact pooled-parser test under race: measured 0.20 seconds; adaptive budget 30 seconds selected 100 repetitions, all pass. Full frontend under race also passes.
  • Incremental golangci-lint 2.14.0: 0 issues.
  • Repository-built real service, existing stage/select_into_outfile_fields_lines.sql, normal result/metadata comparison: 194/194 twice, with zero ignored tests. Added public-path rejection and matching LOAD controls; expected values were independently specified, not generated from the implementation. The initial local expected-file framing omission was corrected without changing expected values or comparisons.
  • Post-run catalog checks: zero fixture databases and stages; generated output directory absent after cleanup. Existing user databases/containers were not cleared.

New exact-head CI and reviewer re-review are pending. No review state or branch protection was changed.

@XuPeng-SH

XuPeng-SH commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: f2132ef1fc5c07458f403c053d19f7c89ae4671c

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: f2132ef1fc5c07458f403c053d19f7c89ae4671c

Assessment: approve

Reviewed the complete 15-file delta and frozen discussion. Grammar reuse, shared CSV formatting, pooled LOAD-parser validation and Parquet UTF-8 validation fit the existing owners. Prior findings are resolved, including NULL overlap with the actual following delimiter. The added export-local validation cost is justified; no actionable finding remains.

Model: gpt-6-astra / xhigh

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

Validation:

  • Evidence retained under /home/xupeng/.local/state/mo-bot/jobs/7ba59d4096527feed07be24a/attempt-1. review-audit.json reconciles 12 command/source/exit receipts with logs; final audit receipt 1793078036963108175-4 passed. Source remains unchanged.

  • Read all 45 raw discussion items and their index entries. discussion-assessment.json accounts for all 43 nonempty items exactly once and reconciles prior findings with author responses and current evidence.

  • Isolation preflight passed. Retained native build qualified against all 200 current native inputs and seven output hashes. Focused native frontend, grammar and tree regression tests passed.

  • Generated mysql_sql.go matches regeneration byte-for-byte. Independent complete-row checks passed 660 accepted round trips and 76 explicit rejections. The exploratory identical-separator failure was reproduced with merge-base helpers and classified as preexisting.

  • Exact pooled-parser race test passed 100 repetitions. The full frontend race run had one read-only-fixture failure and no race report; that exact test passed with only its output filenames relocated, preserving production code and assertions.

  • Helper benchmarks measured ordinary text at 35.9–42.8 ns versus 33.9–35.9 ns at base, and default NULL at 131–216 ns versus approximately 12 ns, with zero amortized allocations. Parquet adds a text-byte validation scan without another text copy.

  • Reused frozen exact-head successful build, UT, SCA and active BVT statuses, plus the author's current-head report of two 194/194 SQL result/metadata runs, as supporting public-path evidence.

Limitations:

  • No live SQL server or distributed run was repeated locally. Raw author/CI execution logs and separate linked-issue bodies were not supplied.

  • The unmodified full frontend race command failed on the read-only fixture; it is not reported as a passing command. Recovery evidence is recorded separately.

  • Benchmarks measure formatter cost, not end-to-end SQL throughput. Disabled escaping retains documented verbatim semantics; identical field/record separators retain their preexisting limitation.

@mergify

mergify Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue

1 h 1 min in the queue, with no time running CI.

So far

  • ✅ Entered the queue Tue 27 Oct, 06:24 · rule main · triggered by rule Automatic queue on approval for main
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 07:25 · 4c51b0a

Reason

The pull request can't be updated

GitHub response: refusing to allow a GitHub App to create or update workflow .github/workflows/python-sdk.yml without workflows permission
GitHub only lets Mergify write to .github/workflows/ with the workflows permission. An organization owner can accept Mergify's pending permissions at https://dashboard.mergify.com/orgs/matrixorigin/repositories.

Hint

You should update or rebase your pull request manually. If you do, this pull request will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Requeued — the merge queue status continues in this comment ↓.

Times in UTC · dashboard · how the merge queue works

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

Reconsidering my previous approval: the two underlying defects are real, but the current solution still leaves a correctness gap and adds avoidable work to a common export path.

  1. Binary Parquet schema / incomplete UTF-8 contract. valueRequiresValidUTF8 exempts BINARY_FLAG, but buildParquetNode still maps MYSQL_TYPE_VAR_STRING and MYSQL_TYPE_STRING to parquet.String() regardless of the flag. Actual VARBINARY/BINARY metadata uses those types with BINARY_FLAG. Thus arbitrary bytes such as 61 ff 62 are written under a UTF-8 logical type: MO can round-trip the bytes, but an external consumer treating the schema as UTF-8 can fail. I independently reproduced this using the same parquet-go schema/writer and PyArrow: materializing the String-schema value raises UnicodeDecodeError, while a BYTE_ARRAY binary-schema control reads successfully. This schema bug predates the PR, but the new test only checks success/MO round-trip and the PR claims the resulting binary files are valid. Please address the schema/contract consistently and add a schema plus external-consumer or equivalent independent regression check. The reproduction was library-level, not a live MO SQL run.

  2. Repeated NULL replay in the default CSV hot path. formatOutputNull replays the same marker through the LOAD parser for every NULL, even with ordinary default framing. The result is determined by the statement configuration and actual following boundary, so repeating it per row is unnecessary. The prior review's helper benchmark on f2132ef measured approximately 131–216 ns versus 12 ns at base for a default NULL; that is not an end-to-end throughput measurement, and the CSV parser changed after that head. Please avoid repeating invariant checks (e.g. a safe default fast path or a lazy per-boundary result), preserve errors when a NULL is actually encountered, and measure the current head with representative NULL-heavy and ordinary exports.

  3. Existing OUTFILE compatibility. The new framing checks reject delimiters that existing OUTFILE statements could previously emit, for example a field delimiter beginning with a double quote, solely because MO LOAD rejects them. OUTFILE consumers need not use MO LOAD. Please explicitly settle the intended compatibility/round-trip contract and either avoid broadening the restriction or document and test the deliberate behavior change on existing syntax.

The real corruption cases behind the extra CSV checks should remain covered, but please also review the duplicated LOAD configuration and the large test matrix for opportunities to share the authoritative configuration and consolidate redundant setup. The PR description should reflect the actual writer validation changes. Current-head frontend UT was not rerun locally because the matching CGo artifacts were unavailable.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Implemented the latest review in 655fdbf.

  1. Parquet binary contract: VARBINARY/BINARY and other binary-flagged string-family metadata now produce unannotated BYTE_ARRAY. Schema selection and UTF-8 validation use the same predicate. Serialized-footer assertions fail with the old production code for all four previously mislabeled metadata forms, while binary BLOB controls pass. Fixed files also decode byte-exactly through the library reader, independent of MO LOAD; valid text still has STRING/UTF8 annotation.
  2. NULL hot path: at most one lazy replay for the field boundary and one for the record boundary per statement, shared with sync.Once. Success and failure are retained independently; a statement without an offending NULL stays allowed. No per-NULL parser replay, new worker, unbounded map or I/O. The shared LOAD clause/default builder replaces the duplicated exporter configuration (including its stale tab default).
  3. Compatibility decision: retained the fail-before-write restriction, using the review's document-and-test option. The maintained framing contract explicitly states that quote/CR/LF/NUL/invalid-rune delimiters can reject previously accepted syntax even for external-only consumers. Both absent-clause UTs and a public old-syntax regression verify this; the latter also asserts no file exists. The PR description now describes the actual writer changes and limits, rather than saying no writer change is needed.

Validation:

  • Full frontend/external/mysql-parser/tree/csvparser packages pass; incremental vet and configured lint: 0 issues.
  • NULL-boundary concurrency regression: 100 race repetitions; full frontend race: pass.
  • Owned Docker launch, normal golden comparison: 240/240 (196 CSV + 44 Parquet), ignored/abnormal=0. Services stopped and joined.
  • Measured both real writers, eight-column ordinary / 50%-NULL rows, default/custom escaping, 128-row batches. Go 1.27.1 Linux/arm64, GOMAXPROCS=4, 300 ms, three samples each. Precompiled binaries alternated before/after/after/before/before/after; before is exact pre-fix head 4c51b0a, not the PR merge-base.
Escape / NULLs / writer Before ns/op After ns/op Time change allocs/op
escape-/null-heavy-false/result-set-4 408.4 458.3 12.2% 11 → 11
escape-/null-heavy-false/batch-128-4 39660 42953 8.3% 151 → 151
escape-/null-heavy-true/result-set-4 873.5 311.9 -64.3% 7 → 7
escape-/null-heavy-true/batch-128-4 117978 44049 -62.7% 158 → 158
escape-#/null-heavy-false/result-set-4 466.5 494.5 6% 11 → 11
escape-#/null-heavy-false/batch-128-4 43816 43455 -0.8% 151 → 151
escape-#/null-heavy-true/result-set-4 828.2 263.4 -68.2% 11 → 7
escape-#/null-heavy-true/batch-128-4 109825 42434 -61.4% 670 → 158

NULL-heavy formatting is 61–68% faster in these samples; ordinary controls range from -0.8% to +12.2% elapsed time with unchanged allocations. Initial sequential samples had even greater ordinary variance (+19.6–48.5%); pairing reduced but did not eliminate shared-host uncertainty. These are in-memory formatting measurements (batch includes duplication/cleanup), not full file/network throughput or a no-regression certification.

Latest old-head CI diagnosis, from downloaded artifacts of job 122067530681: only three failures, all in vector_hnsw_delete_insert.sql—both serving-generation waits return 0 after 120 s, and the nearest-neighbor query returns old id 777 rather than 2001. Coverage then explicitly reports a missing/incomplete required producer profile; no coverage verdict was calculated. No claim that this HNSW failure is pre-existing without clean-baseline proof, and no unrelated HNSW code or assertions changed. The old Mergify cancellation separately cites App workflow-write permission; no permissions/workflow settings were changed.

Pushed normally. New-head CI is pending, not counted as passed.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Updated the branch against main 00c103b68b and addressed the actual failing checks at head 655fdbf42d in commit 6b81c5a1db.

  • SCA: job 122085298155 fails on ST1016: the new ExportConfig method used receiver oq, unlike the other methods' ec. The receiver is now consistent, without a behavior change. Configured incremental vet/lint and a separate production-package ST1016 scan without changed-line filtering pass; the latter matters because the diagnostic was reported at an unchanged method line.
  • Proxy BVT: job 122089149137 fails the HNSW serving-generation checks. Its model was published, but a warmed CN can legitimately retain the old remote cache for around 10 minutes, exceeding the fixture's 120s wait. After publication, the fixture now broadcasts the existing cache-eviction command for this exact index only, then retains all serving-readiness and nearest-neighbor assertions. No production refresh policy, timeout or expected result is weakened.
  • Coverage: job 122104898161 explicitly reports an incomplete required producer and calculates no coverage verdict. This was not a changed-code coverage-threshold failure.

Validation: full frontend, external, MySQL parser and tree tests pass; focused CSV/NULL/Parquet writer tests pass under race. A fresh two-CN+proxy service passes HNSW 63/63 and the CSV/Parquet SQL regressions 240/240, each twice on the same instance with cleanup verified. Services are stopped and joined afterward.

The three implementation findings from the earlier review remain covered: binary Parquet fields use unannotated BYTE_ARRAY; NULL replay is lazy and statement-scoped; deliberate existing-syntax delimiter restrictions are documented and tested. The canonical parser generator resolved the main-merge conflict. Fresh CI on the updated head is pending; the prior formatting benchmark still does not certify zero end-to-end performance regression.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Follow-up on current head 6b81c5a1db: run 40491925721 now passes UT, UT Coverage, both active BVT legs (PROXY and PESSIMISTIC), and the final Coverage job.

The sole failing prerequisite is SCA job 122147817239. Its GitHub failure annotation is: “The self-hosted runner lost communication with the server.” The Static Code Analysis step has no terminal result and its post-job steps never ran. Direct log downloads, including a fresh request, return BlobNotFound/404, so there is no completed SCA log establishing a new lint/code error. Whether the runner loss was caused by networking, host resource pressure or runner termination is not established.

I retried only this failed job on the unchanged head. No speculative production fix, empty commit, lint suppression, timeout increase or workflow/permission change was made. The retry result is pending, not green.

There is no newer reviewer finding than review5663628758. Its three requests remain addressed by the existing code and tests: binary Parquet columns use unannotated BYTE_ARRAY consistently with validation; NULL replay is lazy and cached separately per actual boundary; and the deliberate existing-syntax framing restrictions are documented and tested. The implementation and validation details are in the prior correction reply. The branch is currently mergeable; a fresh reviewer assessment is still needed, not self-assumed approval.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Resolved the merge conflict by merging main d4ffbae43d in adfdba35ae.

Main now owns the HNSW freshness test fix. Both its SQL and result file are adopted byte-for-byte, including the scoped all-CN freshness interval and restoration. The earlier PR-specific cache-eviction workaround is removed rather than layered on top; the test no longer appears in this PR's diff against main.

Validation used five separate mo-service -cfg processes (LOG, TN, CN1, CN2, proxy), not multiple CNs inside a single -launch process. HNSW 58/58 and CSV/Parquet 240/240 pass twice through the proxy and twice through direct CN2. These are normal result comparisons using CI's -n metadata mode; no SQL/data assertion was skipped. Account/user/global/database cleanup checks pass, and all five owned processes join with exit 0. The initial local strict-metadata attempt differed only on the new main fixture's Boolean JDBC metadata; its failed result was not counted as a pass.

The previous head 6b81c5a1db is now fully green after the single-job SCA runner-loss retry. The new merge changes no production/grammar/native input, so the qualifying UT/race/static evidence is reused; fresh merge-head CI is pending. The three requests from review5663628758 remain addressed in the existing implementation, schema/library-reader tests, lazy NULL-boundary cache and documented compatibility decision. No review approval or branch protection was changed.

@XuPeng-SH

XuPeng-SH commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: adfdba35ae09414a2f96b671b293b50598466075

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: adfdba35ae09414a2f96b671b293b50598466075

Assessment: approve

Reviewed the complete 17-file delta and discussion. Prior concerns are resolved: binary Parquet schemas use BYTE_ARRAY, NULL validation is cached per boundary, and LOAD configuration has one owner. The deliberate delimiter compatibility restrictions are documented and tested. No actionable findings remain.

Model: gpt-6-astra / xhigh

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

Validation:

  • 38 focused tests passed under race across frontend, external, MySQL parser, tree and csvparser.

  • Full frontend race suite: 2,702 tests passed; one existing test skipped. NULL-cache and parser-pool tests each passed 100 race repetitions.

  • Canonical parser regeneration matched byte-for-byte; diff checks passed; source remained unchanged.

  • All 53 discussion keys reconciled in discussion-assessment.json. Current-head CI reports successful build, UT, SCA, coverage and both active multi-CN BVT legs.

  • review-audit.json maps 11 checks to source fingerprints, exit receipts and retained logs. Final audit receipt checks/1793115638477083107-4.json passed. Artifacts: /home/xupeng/.local/state/mo-bot/jobs/51f9bb95ffdc69dc6fd6caea/attempt-1.

Limitations:

  • Full frontend race used a test-only overlay relocating two fixture output filenames; production code and assertions were unchanged.

  • SQL topology and throughput measurements were not rerun locally. Author reports and frozen CI statuses are supporting evidence; their raw execution logs were unavailable.

@mergify

mergify Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue

13 min in the queue, with no time running CI.

So far

  • ✅ Entered the queue Tue 27 Oct, 15:42 · rule main · triggered by rule Automatic queue on approval for main
  • 🚫 Left the queue 15:55 · adfdba3

Reason

Pull request #31100 has been dequeued

Queue conditions are not satisfied:

  • -conflict [📌 queue requirement]

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Requeued — the merge queue status continues in this comment ↓.

Times in UTC · dashboard · how the merge queue works

@daviszhen

daviszhen commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Resolved the merge conflicts in e42d06fc39 and a61cb78581, finally merging main 66c9e7624e. Main advanced by one additional integer-precision commit while the first merge was being validated, so the final merge was validated again rather than treating the earlier results as new-head passes.

  • Preserved main's block-size-aware CSV parser constructor and routed it through this PR's authoritative CSVConfigForLoad. Strict boundary probes retain their smaller read block; LOAD and OUTFILE replay still share exactly one clause/default mapping. The configuration builder is byte-identical to the approved head.
  • Regenerated mysql_sql.go from the combined grammar, retaining upstream SOUNDS LIKE, TOKEN_FILTER and integer-literal precision as well as OUTFILE clauses. Repeat canonical generation matches the committed file byte-for-byte; no generated parse tables were merged by hand.
  • No new reviewer blocker was reported. XuPeng-SH's exact-head approval confirms the previous binary-Parquet, cached NULL validation and framing-compatibility findings were addressed; those implementations and regressions remain intact.

Validation on the new merge commit, Go 1.27.1 Linux/arm64:

  • Rebuilt native dependencies through top-level make cgo with clean, matching provenance; the old usearch artifacts were not reused across the upstream native update.
  • Full frontend, external, MySQL parser, tree and csvparser package tests pass (-count=1), including OUTFILE/Parquet, MODUMP and bounded strict-probe regressions.
  • go vet passes; configured lint over the five complete package roots reports 0 issues, without changed-line filtering. Delivery diff against main passes whitespace checks and the worktree is clean.

The preceding reviewed head's full CI passed. Mergify dequeued it because of the merge conflict, not a failing UT/SCA/BVT. New merge-head CI is pending, not counted as green. Earlier race, benchmark and independent-process SQL evidence remains historical supporting evidence; no fresh race/topology/performance run is claimed here. No workflow, permission, timeout, assertion or expected-result suppression was used.

Delivery note: Git transport became unavailable during the final push. The final commit was published through GitHub Git Data API instead, checking uploaded blob hashes, the complete tree hash and the exact commit SHA before a non-forced ref update. Remote readback confirms the same locally validated a61cb78581; no substitute commit or history rewrite was used. Proxy settings were changed only for individual commands, not globally.

@mergify

mergify Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue

1 h 8 min in the queue, with no time running CI.

So far

  • ✅ Entered the queue Wed 28 Oct, 04:28 · rule main · triggered by rule Automatic queue on approval for main
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 05:36 · b0cc5de

Reason

Pull request #31100 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Merge conditions: 2 of 3 met

This pull request

Condition Required by
✅ #review-threads-unresolved = 0 GitHub branch protection
✅ github-review-approved GitHub branch protection

The batch, tested in place

Condition Required by
❌ any of: check-neutral = CI Required, check-skipped = CI Required, check-success = CI Required GitHub branch protection

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

Times in UTC · dashboard · how the merge queue works

@XuPeng-SH

XuPeng-SH commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: a61cb785817b51369a4d51e1582dfaffbb167e33

Review belongs to an older commit; it is not a review of the current head.

@daviszhen

Copy link
Copy Markdown
Contributor Author

All required checks are green on head b0cc5de8f2a291ce2f3ce36427e1e94f54510801 (run 40634780001, attempt 2; the earlier UT leg was a harness-timeout runner flake — no test failures, identical log signature re-verified — and cleared in the quieter window).

Approvals held: 5669964190 (mo-bot review) and 5676953374 (fengttt). Nothing is outstanding on this PR's side.

Requesting the Mergify queue for main — thank you!

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued kind/bug Something isn't working size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants