Skip to content

fix(external): decode base64 on jsonline load for binary columns (#30635) - #30663

Merged
XuPeng-SH merged 4 commits into
mainfrom
fix-jsonline-binary-30635
Oct 21, 2026
Merged

XuPeng-SH merged 4 commits into
mainfrom
fix-jsonline-binary-30635

Conversation

@aptend

@aptend aptend commented Oct 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:

issue #30635

What this PR does / why we need it:

SELECT ... INTO OUTFILE FORMAT 'jsonline' writes binary columns (VARBINARY/BINARY/BLOB) as base64 JSON strings (Go encoding/json []byte rule), while the jsonline loader (jsonLineScalarText, used by both jsondata='object' and 'array') passed the string through as plain text — silently storing base64 text AP8= into a column that originally held X'00FF'. Export/import both reported success, so count-checks never catch it.

Fix: decode with base64.StdEncoding for the three binary types; fall back to the legacy plain-text path for anything that is not valid base64 (hand-written JSONL), and leave every other column type untouched.

Tests

  • TestJsonLineBinaryBase64Roundtrip: byte-exact round-trip via transJsonObject2Lines for varbinary/binary/blob; varchar/text unchanged; invalid base64 falls back. Package suite green via mo-cgo-test.

Closes #30635

… columns (#30635)

JSONLINE OUTFILE writes VARBINARY/BLOB/BINARY payloads as base64 JSON
strings (encoding/json's []byte convention), but jsonLineScalarText
shipped the base64 text through verbatim, so LOAD DATA format jsonline
stored the base64 text instead of the original bytes while reporting
success. Decode base64 in jsonLineScalarText for the three binary types;
strings that are not valid base64 and all non-binary columns keep the
legacy plain-text path, so hand-written JSONL files are unaffected.

Both jsonline modes share jsonLineScalarText, covering OBJECT and ARRAY.

Tests: TestJsonLineBinaryBase64Roundtrip (varbinary/blob/binary round
trip, text columns untouched, invalid-base64 fall-through).
@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 20, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: eb50feaa6bf734a85374c2d26022a82b2e8e2c84

Review completed. Read the assessment.

@XuPeng-SH

XuPeng-SH commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: eb50feaa6bf734a85374c2d26022a82b2e8e2c84

"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-xupeng · review

Commit: eb50feaa6bf734a85374c2d26022a82b2e8e2c84

Assessment: request_changes

Reviewed the complete delta and its export, load, and Kafka callers. Two reproducible data-corruption cases remain.

Model: gpt-6-astra / xhigh

Session: 01a14d34-4e51-79a3-a62d-6c9c16279dc8 · slot 0 · generation 0

  • P1 pkg/sql/colexec/external/reader_csv.go:435: Export binary bytes X'5C4E', then load the resulting JSON string "XE4=" into BINARY, VARBINARY, or BLOB.
    Impact: Decoding produces \N, which both callers interpret as NULL. A non-null binary value is silently lost. Preserve null metadata separately from decoded bytes and add materialization regressions for both JSONL shapes.
    Evidence: The callers at lines 357 and 417 compare the decoded value with JsonNull. Diagnostic tests through transJson2Lines and getOneRowData reproduced stored NULL in all six type/shape combinations; see probe-head.log.

  • P1 pkg/sql/colexec/external/reader_csv.go:434: Read existing plain-text JSONL such as {"raw":"test"} into a binary column, including through KafkaReader.
    Impact: Valid base64 syntax does not establish that a value was encoded. This changes the original bytes 74657374 to B5EB2D without an error, altering existing imports and external-table results. Distinguish encoded input explicitly while retaining a plain-text path.
    Evidence: The current converter failed all six binary type/shape preservation cases. The same probes with the byte-exact merge-base converter preserved "test" and passed. VARCHAR/TEXT controls passed on both versions. See probe-head.log and probe-baseline.log.

Validation:

  • Verified the clean frozen checkout, complete two-file patch, and git diff --check.

  • Isolation preflight passed. Compared 190 native inputs and verified retained artifacts through the repository provenance owner.

  • The added PR test passed. Diagnostic probes confirmed both findings; empty, whitespace, JSON-null, and invalid-base64 controls passed.

  • Ran the unmodified external package suite: JSONL tests passed; the command exited 1 because the local MinIO fixture could not start (connection refused).

  • Commands, source fingerprints, overlay hashes, logs, and terminal receipts were reconciled in /home/xupeng/.local/state/mo-bot/jobs/fa5b6bcbe3f880ec104bf24a/attempt-1/review-record.json.

Limitations:

  • No live SQL export/import BVT was executed; reproductions exercise the actual conversion and materialization functions.

  • The complete package suite is not a pass because of the MinIO setup failure.

  • Frozen local_validation was empty; raw CI logs and the standalone linked-issue body were not supplied.

@mergify mergify Bot added the kind/bug Something isn't working label Oct 21, 2026
…te null metadata (#30635)

Address the two P1 findings from review on eb50fea:

- Export side (frontend/export.go): BINARY/VARBINARY/BLOB values are now
  written as {"$binary":"<base64>"} wrapper objects instead of bare base64
  JSON strings, so the loader can distinguish MO-encoded payloads from
  plain-text JSON strings.

- Import side (colexec/external/reader_csv.go): only the explicit wrapper
  is base64-decoded; bare JSON strings keep the legacy byte-exact
  passthrough, so historical plain-text files such as {"raw":"test"} load
  unchanged (previously valid-base64 strings were silently transformed,
  e.g. "test" -> b5eb2d).

- NULL is now decided solely from the undecoded JSON input via
  isJsonNullSentinel: only a raw "\N" string (or JSON null) is NULL. A
  wrapped payload whose decoded bytes equal the sentinel (X'5C4E',
  base64 "XE4=") materializes as a value and is never lost.

- A wrapper with invalid base64 is rejected with an invalid-input error
  instead of silently changing meaning.

KafkaReader shares transJson2Lines and is covered by the same fix.

Regressions: both jsondata shapes (object and array) are covered through
transJson2Lines and getOneRowData materialization
(TestJsonLineBinaryBase64Roundtrip,
TestJsonLineBinaryNullMetadataSeparated,
TestJsonLineBinaryWrapperRejectsInvalidBase64), and vectorValueToJSON
export-shape tests in pkg/frontend.
@aptend

aptend commented Oct 21, 2026

Copy link
Copy Markdown
Contributor Author

Both P1 findings are addressed in eccf5a2381 (pushed on top of a clean merge of origin/main).

Fix design

Binary columns are now explicitly marked on export instead of inferred on load:

  • Export (pkg/frontend/export.go): BINARY/VARBINARY/BLOB values are emitted as {"$binary":"<base64>"} wrapper objects; no more bare base64 strings.
  • Import (pkg/sql/colexec/external/reader_csv.go): only the explicit $binary wrapper is base64-decoded. Bare JSON strings keep the legacy byte-exact passthrough, so historical plain-text files are untouched. A wrapper with invalid base64 is rejected with an invalid-input error.
  • NULL separation (finding 1): NULL is decided solely from the undecoded JSON input via isJsonNullSentinel — only a raw "\N" string (or JSON null) is NULL. Decoded bytes are never re-compared against the sentinel, so X'5C4E' (base64 "XE4=") materializes as a value.
  • KafkaReader shares transJson2Lines, so it is covered by the same change (callers reviewed; no other callers exist for the touched functions).

Verification (all locally replayed)

Unit (mo-cgo-test):

  • TestJsonLineBinaryBase64Roundtrip — wrapped decode for binary/varbinary/blob, object+array shapes; bare "test"/"AP8=" passthrough byte-exact; varchar/text untouched — PASS.
  • TestJsonLineBinaryNullMetadataSeparated — wrapped "XE4=" materializes 0x5C4E, not NULL; raw "\\N" string and JSON null are NULL; both shapes through getOneRowData — PASS.
  • TestJsonLineBinaryWrapperRejectsInvalidBase64 — both shapes — PASS.
  • Test_vectorValueToJSON (frontend) — export wrapper shape incl. sentinel-bytes and empty payloads — PASS.
  • External package sweep -run 'JSON|Json|CSV|Csv|Kafka' — ok ... 33.805s, exit 0 (no MinIO fixtures in this selection).

Live SQL round-trip (mo-service @26001, fresh cluster, root/111):

  • Criterion a: X'5C4E' in binary(2)/varbinary(16)/blob → export ({"$binary":"XE4="}) → load → hex() = 5C4E, is null = 0 for all three — never NULL. ✔
  • Criterion b: plain-text {"raw":"test"} (object) and ["test"] (array) → hex(raw) = 74657374. ✔
  • Criterion c: X'00FF' → export → load → 00FF; SQL byte-exactness check group_concat(hex(b)) src == rt returned 1. ✔
  • Criterion d: varchar/text columns round-tripped unchanged (plain1/text1/test); JSON null row loads as NULL. ✔
  • Criterion e: every case above covered for both jsondata 'object' and jsondata 'array' (array: 74657374, 5C4E non-null, 00FF, NULL). ✔
  • Adversarial: bare "AP8=" (valid base64) into binary column loads as the literal 4 bytes AP8= (passthrough), and wrapper-*** is rejected at both unit and format level.

Would you please re-review? Happy to adjust the wrapper key or the error semantics if you prefer a different marker.

@matrix-meow matrix-meow added size/M Denotes a PR that changes [100,499] lines and removed size/S Denotes a PR that changes [10,99] lines labels Oct 21, 2026
@XuPeng-SH

XuPeng-SH commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: eccf5a2381de0c6e5f663b5b2c2a548300633b37

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

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

@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: eccf5a2381de0c6e5f663b5b2c2a548300633b37

Assessment: approve

Reviewed the complete five-file delta and affected callers. The explicit binary wrapper preserves legacy strings, and raw-input NULL detection preserves decoded sentinel bytes. Both prior P1 concerns are closed. Encoding and decoding remain with the existing owners; no actionable findings remain.

Model: gpt-6-astra / xhigh

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

Validation:

  • Independent SQL probe passed through the real MySQL frontend: JSONLINE export, serial/parallel LOAD DATA, and external-table reads for both JSON shapes. Covered all three binary types, NULL, empty values, sentinel bytes, whitespace, all 256 byte values, legacy strings, and malformed-base64 rejection.

  • Public probe completed successfully in 4.900s; public-probe.log matches checks/1792575825607916544-4.json at the assessed head. Preflight and a fresh native build passed; the earlier prerequisite rejection executed no tests.

  • Frozen patch, clean source, and diff --check verified. Reused supplied exact-head successful UT, coverage, SCA, and BVT status evidence.

  • Commands, source fingerprints, terminal receipts, log hashes, native provenance, and scope are reconciled in /home/xupeng/.local/state/mo-bot/jobs/1f29db9afbeca1fd27096c90/attempt-1/review-record.json.

Limitations:

  • Raw CI logs were not supplied. Author SQL claims were supplemented by the independent local SQL probe.

  • No live Kafka broker test; its parser directly uses the reviewed shared decoder.

  • No throughput benchmark. Binary JSONLINE adds transient wrapper/decode allocations and 12 output bytes per non-NULL binary cell; ordinary SQL paths are unaffected.

  • Legacy unmarked base64 strings intentionally remain literal. New wrapper output requires a compatible reader.

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

mergify Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-21 09:46 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🚫 Left the queue — 2026-10-21 14:11 UTC · at eccf5a2381de0c6e5f663b5b2c2a548300633b37

This pull request spent 4 hours 25 minutes 32 seconds in the queue, with no time running CI.

Reason

Pull request #30663 has been merged manually at 9a7ea39

Hint

You were too fast!

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

  • Requeue this pull request

@XuPeng-SH

Copy link
Copy Markdown
Contributor

QA verification on main@3ad9adbb4c (post-merge)

Built mo-service from current main (local CGo, arm64) and ran the round-trip this commit is about, on a fresh isolated instance:

create table jsrc(id int primary key, b varbinary(4));
insert into jsrc values (1, x'00FF'), (2, x'616263'), (3, null);
select id,b from jsrc order by id into outfile '/tmp/moqa-out/bin.jsonl' format 'jsonline';
create table jdst(id int primary key, b varbinary(4));
load data infile {'filepath'='/tmp/moqa-out/bin.jsonl','format'='jsonline','jsondata'='object'} into table jdst;
select id, hex(b) from jdst order by id;

Exported file content:

{"b":{"$binary":"AP8="},"id":1}
{"b":{"$binary":"YWJj"},"id":2}

Round-trip result: 1|00FF, 2|616263, 3|NULL — byte-exact, no base64 leakage into the column.

Control case: bare (unwrapped) base64 strings are still passed through verbatim by design ({"raw":"AP8="} stays AP8=), matching reader_csv_projection_test.go and preserving hand-written JSONL compatibility. Verified separately: bare AAEC loads as 41414543, not 000102.

Not covered by this run: BLOB larger than 64 KiB per field, jsondata='array' shape end-to-end.

This branch was previously deployed

1 inactive deployment
ci — dfdc97a5 Deployed Oct 21, 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 size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: JSONLINE INTO OUTFILE round-trip silently stores Base64 text in binary columns

3 participants