Skip to content

feat(load): zip and zstd compressed sources - #29301

Merged
fengttt merged 4 commits into
matrixorigin:mainfrom
fengttt:feat-load-zip-zstd
Sep 24, 2026
Merged

fengttt merged 4 commits into
matrixorigin:mainfrom
fengttt:feat-load-zip-zstd

Conversation

@fengttt

@fengttt fengttt commented Sep 24, 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 #29242

What this PR does / why we need it:

LOAD DATA and external tables can now read zstd and zip files, alone or mixed with the existing formats under one filepath pattern. Two existing bugs in the compressed-source path are fixed along the way.

load data infile {'filepath'='/data/part_*.csv.zst'} into table t
  fields terminated by ',' ignore 1 lines parallel 'true';
load data local infile {'filepath'='export.zip'} into table t
  fields terminated by ',' ignore 1 lines;

zstd

  • Detection: from .zst / .zstd, or with compression 'zstd'.
  • Decoding: streams through klauspost/compress, which is already a direct dependency. Each reader gets one decoding goroutine, like lz4. A parallel load already runs one reader per file, and the library default would start GOMAXPROCS decoders for each one.
  • Multi-frame files: the frames the zstd CLI writes for large inputs decode as one stream.

zip

  • Detection: from .zip, or with compression 'zip'.
  • Streaming read: a load source is a sequential stream: an object body, a file, or the client's bytes for LOAD DATA LOCAL. So the archive is read from its local file headers, the way unzip - does, and the central directory at the end is never needed. There's no random access and no buffering of the file, and LOAD DATA LOCAL works.
  • Entry chosen: the first entry that is neither a directory nor hidden, which is the rule tar archives already use.
  • Methods:
    • Deflate entries are self-delimiting.
    • Stored entries must carry their size in the local header, which is what zip tools write to a seekable output.
  • Integrity: CRC-32 and size are verified when the entry ends, from the header or the data descriptor, including the zip64 forms.
  • Rejected with explicit errors instead of being parsed as CSV: encrypted entries, other compression methods, truncated archives, and input that isn't a zip.

Fixes

  • One compression detector. Planning and execution each had their own extension-to-compression detector, and they disagreed. The planner's version looked only at the last extension, was case sensitive, and didn't know tar.gz/tar.bz2. So bind-time parallel and S3-write decisions could be made for a different compression than the one decompressed at execution, e.g. a.CSV.GZ. plan.GetCompressType is now the single detector, and an explicit option is lower-cased, so NONE is recognised.
  • Decompressors close their source. The file or object stream under every compressed load stayed open until a GC finalizer ran. The decoders' Close (gzip, flate, zlib) doesn't close its input, and lz4, bzip2 and tar were wrapped in io.NopCloser. Closing the reader now closes the source exactly once. This matters most for a pattern load that opens one reader per file.
  • parse_jsonl closed nothing when creating the decompressor failed, and crashed on an empty compressed file.

Verification

  • Unit tests (pkg/sql/crt):
    • the detector table;
    • a source-close round trip for every format (it fails on the old code: gzip closed 0 times);
    • zstd multi-frame;
    • zip deflate/stored/entry selection/rejections/corruption/truncation/zip64 local header.
  • Other affected packages pass: plan, colexec/external, colexec/table_function, compile, parsers/tree.
  • New BVT load_data/load_data_zip_zstd, with resources written by the zstd and Info-ZIP command-line tools. It covers:
    • auto and explicit detection;
    • stored and deflated zip entries;
    • a two-file archive;
    • LOAD DATA LOCAL for both formats;
    • a pattern mixing zstd, lz4, zip and plain CSV;
    • a non-zip file named as zip, which now errors;
    • external tables.
  • Existing suites, run locally:
    • load_data has 6 failures, all from a root-owned resources/into_outfile/load_data directory in the local sandbox (into outfile then cascades). They're unrelated to compression.
    • table passes. system_table_cases_2 needs the metrics series populated after server start; on a server started seconds earlier its metrics queries return nothing, and a rerun passes 84/84.
  • make static-check: 0 issues.

🤖 Generated with Claude Code

fengttt and others added 3 commits September 23, 2026 17:57
Planning and execution each had their own extension-to-compression
detector. The planner's looked only at the last extension, case
sensitively, and did not know tar.gz/tar.bz2, so the bind-time
parallel/S3-write decisions and the decompressor chosen at execution
could disagree about the same file (e.g. "a.CSV.GZ"). plan.GetCompressType
is now the single detector; crt delegates to it. An explicit compression
option is lower-cased, so "NONE" is recognised.

Every decompressor now owns its source. The decoders' Close (gzip, flate,
zlib) or io.NopCloser (lz4, bzip2, tar) left the file or object stream of
a compressed load open until a finalizer ran; closing the reader now
closes the source exactly once. parse_jsonl also closed nothing on a
decompressor error and crashed on an empty compressed file.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
LOAD DATA and external tables read zstd-compressed files: detected from a
.zst or .zstd extension, or selected with compression 'zstd'. Decoding
streams through klauspost/compress (already a direct dependency) with one
decoding goroutine per reader, like lz4, since a parallel load already
runs one reader per file. Concatenated frames, as the zstd CLI writes for
large inputs, decode as one stream.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
LOAD DATA and external tables read zip archives: detected from a .zip
extension, or selected with compression 'zip'.

A load source is a sequential stream (an object body, a file, or the
client's bytes for LOAD DATA LOCAL), so the archive is read from its
local file headers, as `unzip -` does, without the central directory at
the end: no random access and no buffering of the file. The entry loaded
follows the tar rule: the first entry that is neither a directory nor
hidden. Deflate entries are self-delimiting; stored entries must carry
their size in the local header (what zip tools write to a seekable
output). CRC-32 and size are verified at the end of the entry, from the
header or the data descriptor, including zip64 forms. Encrypted entries,
other methods, truncated archives and non-zip input are rejected with
explicit errors instead of being parsed as CSV.

BVT covers zstd and zip written by the zstd and Info-ZIP tools: auto and
explicit detection, stored and deflated entries, a two-file archive,
LOAD DATA LOCAL, a glob mixing zstd/lz4/zip/plain files, a non-zip file
named as zip, and external tables.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@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 →

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Unresolved reader-leak, ZIP integrity-validation, and write-side compression-detection issues remain.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 2 Medium severity

Open (2)
What changed in this PR

Adds streaming ZIP and zstd support for LOAD DATA and external tables, with unified compression detection and improved reader cleanup.

Changes:

  • Adds ZIP/zstd detection, decoding, validation, and tests.
  • Updates parser constants and load planning.
  • Expands BVT coverage for compressed and mixed sources.
File Summary
test/​distributed/​resources/​load_data/​zipzstd/​mix/​m_3.csv Mixed-format test fixture
test/​distributed/​cases/​load_data/​load_data_zip_zstd.sql ZIP/zstd BVT scenarios
test/​distributed/​cases/​load_data/​load_data_zip_zstd.result Expected BVT results
pkg/​sql/​plan/​build_load.go Unified compression detection
pkg/​sql/​parsers/​tree/​update.go ZIP/zstd constants
pkg/​sql/​crt/​zip.go Streaming ZIP reader and validation
pkg/​sql/​crt/​zip_test.go ZIP behavior and integrity tests
pkg/​sql/​crt/​crt.go Decompressor support and source ownership
pkg/​sql/​crt/​compress_test.go Compression and lifecycle tests
pkg/​sql/​colexec/​table_function/​parsejsonl.go JSONL decompressor and empty-source handling

💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread pkg/sql/crt/zip.go Resolved
Comment thread pkg/sql/plan/build_load.go Resolved
…dation

Address review on matrixorigin#29301.

The zip reader verified CRC and uncompressed size but discarded the
compressed size from the data descriptor, and never checked the header's
compressed size for a deflate entry, so an entry whose deflate stream
ended cleanly was accepted even when its recorded compressed size was
wrong. Deflate now reads through a counting io.ByteReader (flate still
consumes exactly the entry's bytes), and the count is verified against
the descriptor or the header.

Writable external tables validated WRITE_FILE_PATTERN with their own
suffix list, which stopped at .lz4: a .zst or .zip pattern passed
validation, the writer emitted plain bytes, and reads then tried to
decompress them. effectiveWriteCompression now uses GetCompressType, the
read path's detector; its error names the canonical type ('gzip', not
'gz').

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

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

P2 — Required approved design revision is missing

This feature changes public compression-option and compatibility semantics, including a custom streaming ZIP contract: it selects the first eligible entry, does not validate the central directory, and rejects streamed stored entries. These decisions are implemented at zip.go:31–43 and change source ownership at crt.go:129–155. They trigger the required configuration/compatibility and lifecycle design gates. Neither this PR nor issue #29242 links an exact reviewed design revision or approval record.

Please provide the versioned design and traceable approval covering format interoperability, ownership/cancellation, resource bounds, and validation before implementation approval. This is a missing mandatory artifact, not a claim of a runtime defect.

@fengttt

fengttt commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

P2 — Required approved design revision is missing

This feature changes public compression-option and compatibility semantics, including a custom streaming ZIP contract: it selects the first eligible entry, does not validate the central directory, and rejects streamed stored entries. These decisions are implemented at zip.go:31–43 and change source ownership at crt.go:129–155. They trigger the required configuration/compatibility and lifecycle design gates. Neither this PR nor issue #29242 links an exact reviewed design revision or approval record.

Please provide the versioned design and traceable approval covering format interoperability, ownership/cancellation, resource bounds, and validation before implementation approval. This is a missing mandatory artifact, not a claim of a runtime defect.

Feature is trivial. No design doc necessary.

@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 2399dd7302adc30636c53229a5a736113c47ee60 against base 95b1d2bfd9d756d08320569858080cb16f230fff. No P0/P1 findings. All 28 checks are complete (12 SUCCESS, 14 SKIPPED, 2 NEUTRAL; no failures), and GitHub reports the PR mergeable.

The P3 ZIP descriptor compatibility edge is in the inline comment and is advisory.

Prior review disposition:

  • The two Copilot P2 comments (descriptor compressed-size verification and write-side compression detection) received author replies and are fixed at this head; the added tests cover both.
  • XuPeng-SH's prior P2 asked for a versioned approved design revision for the ZIP stream and ownership choices documented at pkg/sql/crt/zip.go:31-43 and pkg/sql/crt/crt.go:129-155. The author explicitly replied in the PR conversation: “Feature is trivial. No design doc necessary.” No artifact was linked; I record the P2 as explicitly answered and non-blocking under the review precedence.

With no P0/P1 and an explicit author reply to the prior P2, the event is APPROVE; the P3 remains advisory.

Comment thread pkg/sql/crt/zip.go
if _, err := io.ReadFull(br, word[:]); err != nil {
return d, zipTruncated(ctx, err)
}
if binary.LittleEndian.Uint32(word[:]) == zipDescriptorSig {

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.

P3 — Ambiguous unsigned ZIP data descriptor when the CRC matches the signature

A valid streamed DEFLATE entry can set general-purpose bit 3 and use a data descriptor without the optional signature. If its CRC-32 is exactly 0x08074b50, this branch consumes the CRC as the signature and shifts the remaining fields; zipEntryReader.verify then rejects the valid entry. PKWARE APPNOTE 6.3.10 §4.3.9.3 says readers should accept descriptors with or without this marker (specification). Please disambiguate using the computed entry CRC or validate both candidate layouts. Trigger: an unsigned descriptor whose entry CRC is 0x08074b50. This is a rare, low-priority interoperability edge.

@fengttt
fengttt merged commit f19024d into matrixorigin:main Sep 24, 2026
28 checks passed
fengttt added a commit that referenced this pull request Sep 24, 2026
… of #29245, #29301] (#29321)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue #29242

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

Ports two `LOAD DATA` / external-table features from `main` to
**4.2-dev** as separate cherry-picks, in their original order.

| Ported commit | Feature |
| --- | --- |
| `a702fab7f0` (#29245) | filepath patterns resolve for every format,
and multi-file CSV reads are split across threads by whole file; also
fixes rows being silently dropped when a TP-classified plan had more
than one scope (`IsSingleScope`, `compileMultiUpdate`, `compileLock`) |
| `d0eb3934af` (#29301) | zip and zstd compressed sources, alone or
mixed with other formats under one pattern |

### Adaptations for 4.2-dev

#29301 applied cleanly. #29245 conflicted in
`pkg/sql/compile/compile.go` and `pkg/sql/plan/build_load.go` because
4.2-dev doesn't have main's Arrow external format. So this port leaves
out:

- the `tree.ARROW` exclusions (Parquet is still excluded from the
multi-file fanout)
- the parquet/arrow parameters that main's
`compileExternScanWholeFileFanout` takes (`ParquetWholeFileFanout`,
`ArrowDistributedExecution`)
- `parquetLoadFileFanoutSaturates` / `parquetLoadFileFanoutDOP`, which
exist only on main

The same cuts are made in `load_glob_fanout_test.go`. Everything else is
ported unchanged: the remote-shard `CreateSql` serialization
(`resolvedExternParamJSON`), the `max_dop` cap on file fanout (4.2-dev
already has `Query.MaxDop`), per-file `IGNORE n LINES`, and a pattern
that matches one file collapsing to that file's path.

## Verification (on a 4.2-dev build)

- `go vet` is clean. `go test` passes for the full `pkg/sql/compile`
suite and for
`pkg/sql/{plan,crt,colexec/external,colexec/table_function}`, including
all the ported tests.
- BVT: `load_data/load_data_glob` 63/63, `table/external_table_glob`
41/41, `load_data/load_data_zip_zstd` 35/35,
`stage/writable_external_table` 169/169. The full `stage` suite passes.
- The full `load_data` suite has 6 failures, all in `load_data.sql`'s
`into outfile` statements. They come from a root-owned
`resources/into_outfile/load_data` folder in the local sandbox, and the
original #29245 hit the same failures.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>

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

kind/bug Something isn't working kind/feature size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants