Skip to content

feat(load): multi-file CSV fanout + zip/zstd sources [port to 4.2-dev of #29245, #29301] - #29321

Merged
fengttt merged 3 commits into
matrixorigin:4.2-devfrom
fengttt:port-load-glob-zip-4.2-dev
Sep 24, 2026
Merged

fengttt merged 3 commits into
matrixorigin:4.2-devfrom
fengttt:port-load-glob-zip-4.2-dev

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:

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 feat(load): distribute multi-file CSV reads across threads #29245 hit the same failures.

🤖 Generated with Claude Code

fengttt and others added 2 commits September 23, 2026 22:38
…gin#29245)

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

issue matrixorigin#29242

`LOAD DATA` expanded a filepath pattern only for the columnar formats,
so
`load data infile '/data/*.csv'` stat-ed the pattern verbatim and failed
with
`the file does not exist in load flow`. A CSV external table did expand
its
glob, but read every match sequentially on a single thread.

This resolves the pattern for every format and adds **one rule** for
parallelising the read:

> More than one file means whole files are distributed to threads — one
shard
> per scope, each file read start to finish by a single reader.
Splitting a
> file by byte offset is reserved for the single-file case, where it is
the
> only parallelism available.

Whole files are also the only shape a compressed source can take (an
offset
split cannot find line boundaries inside a gzip or lz4 stream), which is
what
makes `*.csv.lz4` parallel at all. Mixed compression under one pattern
works,
since the type is detected per resolved file.

```sql
-- both now run one reader per file, in parallel
load data infile {'filepath'='/data/part_*.csv.lz4'}
  into table t fields terminated by ',' ignore 1 lines parallel 'true';

create external table t (...) infile{'filepath'='/data/part_*.csv.lz4'}
  fields terminated by ',' ignore 1 lines;
```

Degree of parallelism is `min(files, ncpu)` for a local read, and
spreads
across CNs for S3 (`min(files, Σ min(cn.Mcpu, 10))`). Shards are
balanced by
bytes, not file count.

Parquet and arrow keep their own layouts, which split and redistribute
row
groups and record batches across files. Hive partitioning keeps its
existing
whole-file fanout. The rule excludes all three, and the new path reuses
`compileExternScanWholeFileFanout` — already shared by the hive and
parquet
paths — so the shard split, whole-file offsets and balanced assignment
are
unchanged code.

**Scopes dropped from a TP-classified plan.** `IsSingleScope` answered
`true`
for *any* list under a TP query, and callers act on that by keeping
`ss[0]` and
discarding the rest (`compileSinkNode`). The same shortcut sat in
`compileMultiUpdate`'s non-S3 branch. `execType` is predicted from
plan-node
**stats** before any scope exists, so 100 small compressed files — a few
hundred KB, far under every TP threshold — produced a TP-classified plan
holding one scope per shard, of which only the first reached the table.
Both
sites now merge whenever `len(ss) > 1`, matching what the WriteS3 branch
already did. Promoting `execType` instead is not available here:
`scheduleQueryWorkers` and `CalcQueryDOP` consume it before scope
building.

**`IGNORE n LINES` under a fanout.** The prescan seeds the byte-offset
split by
recording one file's header length in `FileStartOff` and zeroing
`Tail.IgnoredLines`. Under a fanout that offset would apply to every
file, so
it is skipped for a pattern; the CSV reader re-applies `IGNORE` on each
file it
opens. A pattern matching exactly one file collapses back to that path,
keeping
single-file behaviour reachable and making "still a glob" mean "at least
two
files" everywhere downstream.

`EXPLAIN ANALYZE` over 100 lz4 shards (20000 rows):

| | before | after |
|---|---|---|
| external table | no `dop`, `outputRows min=20000 max=20000` |
`dop=24`, `min=800 max=1000` |
| `LOAD` | failed to resolve the pattern | `dop=24`, `min=800 max=1000`
|

Parquet and arrow external tables still report no `dop`.

New BVT: `load_data/load_data_glob` (63) and `table/external_table_glob`
(41)
— csv / lz4 / mixed-compression patterns, per-file `IGNORE n LINES` (a
leaked
header shows up as `id = 9999`), `__mo_filepath` pruning across shards,
single-match and zero-match patterns, rollback, `INSERT … SELECT` into
plain,
primary-key and fulltext-indexed tables (three different fan-in shapes),
joins
and aggregates over a fanned-out scan.

Suites run locally with no failures attributable to this change: `table`
(1976), `stage` (1422), `dml` (7766), `pitr`, `query_result`,
`save_query_result`, `result_count`, `join`, `optimizer`, `subquery`,
`window`, `operator`, `expression`, `distinct`, `union`, `cte`.
`load_data`
has 6 failures from a root-owned `into_outfile` directory in the local
sandbox, reproducible with a one-line `into outfile` and unrelated to
this
change.

Not covered locally: S3 external-table fanout builds cross-CN
`Magic=Remote`
shards; every stage in the BVT suite is a `file://` stage, so that path
is
exercised only by the existing hive parquet case.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
## 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 matrixorigin#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.

```sql
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](https://claude.com/claude-code)

---------

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 →

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

GPT-6 high review — APPROVE at exact head d0eb393.

Reviewed the 4.2 port against the merged source changes, including fanout scope/locking, maxDOP, ZIP, and ZSTD fixes. Target BVT evidence is green; broader-suite outfile failures are environment-specific. No blocking findings.

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

审查 head d0eb3934af21480349daa2080c09546f92070f71(base 5c79c3b20226dcbe3ec9204ff8edf2d40ca16198)。已核对完整 diff、相关调用链和测试;当前 checks 无失败,mergeable=true、mergeable_state=behind。

结论:没有确认的 P0/P1/P2;以下 P3 兼容性问题仍存在,因此按首次 review 规则提交 COMMENT。

P3 — pkg/sql/plan/build_load.go:462-464
LoadFilepathHasGlob 将路径中任意 *?[ 直接视为 glob,没有字面量/转义回退。触发场景:非 LOCAL LOAD 读取一个真实文件 etl:/in/data[1].csv;此前 StatFile 按字面量处理,现在会进入 ReadDir,由 path.Match 把 [1] 当字符类,导致文件找不到(或在同目录存在 data1.csv 时误匹配)。建议支持显式转义,或在 glob 无匹配时回退到字面量文件。

历史 review 只有 exact head 上的 APPROVED,review threads 为空,未发现作者针对 P2/P3 的回复。

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/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants