Repository navigation
feat(load): distribute multi-file CSV reads across threads - #29245
Conversation
A LOAD DATA filepath pattern was expanded 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 one thread.
Resolve the pattern for every format and add 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 then 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. Parquet and
arrow keep their own layouts, which redistribute row groups and record batches
across files, and hive partitioning keeps its existing whole-file fanout.
The rule reuses compileExternScanWholeFileFanout, already shared by the hive
and parquet paths, so the shard split, the whole-file offsets and the balanced
assignment are unchanged. The degree of parallelism is min(files, ncpu) for a
local read and spreads across CNs for S3.
Two supporting fixes, both for silent row loss rather than the feature itself:
- 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.
- The IGNORE n LINES 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
that matched exactly one file collapses back to that path, keeping the
single-file behaviour reachable and making "still a glob" mean "at least
two files" everywhere downstream.
Verified with EXPLAIN ANALYZE over 100 lz4 shards: scan_time dop=24 with
outputRows min=800 max=1000, against a single instance reporting all 20000
rows before. Parquet and arrow external tables still report no dop.
Fixes matrixorigin#29242
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
XuPeng-SH
left a comment
There was a problem hiding this comment.
GPT-6 high review — REQUEST_CHANGES
发现两个 P2:
-
非首个 LOAD shard 没有 UNIQUE 行锁。 新的多文件 fanout 在小型单步 TP LOAD 中可产生多个 scope(compile.go:3024);但
compileLock只给ss[0]附加锁(compile.go:9175)。对没有显式主键、仅有 UNIQUE key 的表,后续 shard 可不经唯一键行锁直接到 writer。planner/compiler 探针确认多个 scope 和锁只附加到首个 scope;本次没有复现已提交的重复行。建议合并所有输入 scope 后统一应用所需锁,并补小型多文件 UNIQUE-only LOAD 回归。 -
远端 CSV shard 丢失 external-table 语义。 外部表 fanout(compile.go:4026)进入远端 codec 时传递原始 DDL 参数,丢失规范化后的
ExternType。一列 external table 读取1,extra:本地路径成功,远端 encode/decode 后报 “not equal to input columns”。已在真实 codec/operator 边界复现,尚未在 live 双 CN 部署复现。请保留规范化外部扫描参数并补远端 CSV external-table 回归。
当前 exact-head CI substantive checks 通过(BVT 63/63、41/41),但现有用例未覆盖以上边界。
… shards Address review on matrixorigin#29245. compileLock attached the lock operator to ss[0] and merged only for AP plans, so a TP-classified multi-file LOAD fanout sent every other shard's rows to the writer without row locks (UNIQUE-only tables rely on them). Merge whenever len(ss) > 1, as compileMultiUpdate already does. A remote whole-file shard is rebuilt from CreateSql, which for an external table is the stored DDL: it lacks the plan's ExternType, so the reader applied LOAD's exact column-count rule, and stage-resolved S3 settings, which InitS3Param cannot rebuild from Option. Remote shards now ship the compile-time normalized param, marked Resolved so the receiver uses it as is. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
@XuPeng-SH Thanks for the review. Both findings are fixed in dc2026c.
|
XuPeng-SH
left a comment
There was a problem hiding this comment.
REQUEST_CHANGES — two P2 issues remain at this exact head.
-
Rolling-upgrade S3 compatibility:
pkg/sql/compile/compile.goaround line 4058 sends the normalizedExternParamJSON withResolved=true. An older CN ignores that field and re-runsInitS3Param, but does not have the resolved bucket/endpoint/credential fields, so remote S3 shards can fail during mixed-version rollout. The new encode/decode regression only exercises same-version code. Please add a capability/version-gated compatible path (or otherwise preserve resolved settings for older workers) and a mixed-version regression. -
max_dopis not honored:getHiveFileFanoutNodesaround line 4461 sizes local fanout fromc.ncpuwithout applying the session's effectivemax_dop. A multi-file CSV external-table scan can therefore create more concurrent readers than the configured cap. Derive the fanout ceiling from the effective DOP and add a focusedmax_dop=1test.
The findings are source-confirmed; I did not run a live mixed-version S3 deployment. Exact-head CI passes (including LOAD and external-table BVT), but does not cover these boundaries.
iamlinjunhong
left a comment
There was a problem hiding this comment.
本次只确认到两项 P2,没有 P0/P1。最新一轮既有 review(2026-09-23 05:27 UTC)的两项 P2 尚未见作者回复;04:20 UTC 的作者回复针对的是更早一轮问题,并说明已在当前 head 修复。因此按 P2-only 且未回复的规则提交 COMMENT。
-
P2 — stage-backed S3 shards 与旧 CN 不兼容。
compile.go:4105将Resolved=true写入远端 shard 参数。滚动升级期间,旧 CN 不认识该字段,仍会在External.Prepare中调用InitS3Param;该函数先清空已序列化的S3Param,再从Option重新解析。stage 凭据不在这些选项中,因此新 CN 将 stage-backed S3 glob shard 分派给旧 CN 时,旧 CN 会因 bucket/凭据丢失而无法读取文件。请为旧 worker 保留兼容的解析路径或按能力选择 wire 格式。 -
P2 — 多文件 external-table fanout 绕过
max_dop。compile.go:4027让所有多文件 external-table 扫描进入 fanout;普通INFILE路径随后按compile.go:4461的c.ncpu建立 scope,而qry.MaxDop只限制传给CalcQueryDOP的局部ncpu(compile.go:1478-1483)。当max_dop=1、c.ncpu>1且INFILEpattern 命中多个文件时,会并发创建多个 reader;S3 stage 分支同样按各 worker 的Mcpu扩展且未应用该上限。请让 fanout scope 数遵守查询的有效 DOP,并补max_dop=1回归。
Address second review round on matrixorigin#29245. Remote whole-file shards no longer rely on a new Resolved field that an older CN would ignore before re-running InitS3Param and wiping the stage-resolved S3 settings. The resolved settings are instead written back into Option in the keys InitS3Param already reads, so CNs of every version rebuild the same S3Param through the unchanged path. Resolved is removed from ExParam and External.Prepare is back to its main form. File fanouts sized readers per CN from c.ncpu / worker Mcpu, bypassing the query's max_dop. Apply the same per-CN cap CalcQueryDOP gets in getHiveFileFanoutNodes and parquetLoadFileFanoutDOP. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
@XuPeng-SH @iamlinjunhong Thanks. Both P2s from this round are fixed in d965edc.
Both new tests fail without the corresponding fix. |
… 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]>
…mer (#29303) ## What type of PR is this? - [ ] API-change - [x] BUG - [ ] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: No tracked issue. This was found while investigating memory use of parallel multi-file `LOAD` (the glob fan-out from #29242 / #29245). ## What this PR does / why we need it: After a wide parallel `LOAD`, about 1.6 GB of off-heap memory stayed resident indefinitely. `select mo_memory_usage('')` pins it to the `write-arena` mpool: the `WriteArena` free lists in `pkg/objectio/arena_pool.go`. - Each concurrent S3 writer (the sinker) takes a large-tier arena. - `Reset` grows it to the next power of two of its biggest cycle, up to `arenaMaxSize` (128 MB). - `PutArena` parks it: up to `2 × GOMAXPROCS` arenas. - The only release was `drainArenaPools`, run 10 minutes after the *last* `ScheduleArenaDrain()`. Every TAE checkpoint and every sinker `Close` called it, so on a live server the timer was pushed back indefinitely. The memory is off-heap, so Go heap profiles don't show it. ### Fix Arenas now age out individually. - **The free list is a stack of `{arena, parkedAt}`.** `GetArena` takes the most recently parked arena, so the arenas a steady workload cycles stay on top and warm, while the surplus of a burst sinks to the bottom. - **A one-shot timer frees idle arenas.** It's armed only while arenas are parked, frees those parked longer than `arenaIdleTTL` (one minute), and re-arms for the oldest remaining one. The excess is released while other work continues, and an idle server releases too, with no permanent goroutine. - **The old debounce is removed.** `ScheduleArenaDrain` / `drainArenaPools` and their two call sites (checkpoint runner, sinker) are gone. - **The count cap is unchanged.** **Trade-off:** an arena left unused for more than a minute is reallocated on its next use. That's at most one allocation per object write cycle, which is negligible next to the write. ### Verification Same machine (24 cores, single node), one glob `LOAD` of 40 lz4 CSV files (300 M rows) with `parallel 'true'`: | after the load | before | after | |---|---|---| | `write-arena` at load end | 1,598 MB | 1,548 MB | | `write-arena` 60–80 s later | 1,598 MB | 64 MB → 0 MB | | `write-arena` 13 min later | 1,598 MB | — | | process RSS, settled | ~2,420 MB | 1,172 MB | Two minutes after the load, TAE flush and merge of the new data use a few arenas again (~80 MB). Those are live work and age out the same way. - **New `pkg/objectio/arena_pool_test.go`:** - reuse within the TTL; - freed after the TTL with pool memory back to baseline; - a burst's surplus released while one arena stays in use; - the count cap. Passes with `-race` (`-count=3`). - **`go test`:** `pkg/objectio`, `pkg/objectio/ioutil`, `pkg/vm/engine/tae/db/checkpoint` and `pkg/vm/engine/tae/mergesort` pass. - **`make static-check`:** 0 issues. ### Also in this PR: an unrelated CI fix Since about 19:00 UTC on 2026-09-24, the SCA job has failed on every PR against `main` with a govet `lostcancel` warning in `pkg/proxy/heartbeat_test.go` (lines 153 and 179). `TestServerHeartbeatSendsImmediately` skipped `cancel()` on its `t.Fatal` timeout path. Commit `b6615ed3db` adds `defer cancel()` right after the context is created. It changes only the test, and it can be merged separately if preferred. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
What type of PR is this?
Which issue(s) this PR fixes:
issue #29242
What this PR does / why we need it:
LOAD DATAexpanded a filepath pattern only for the columnar formats, soload data infile '/data/*.csv'stat-ed the pattern verbatim and failed withthe file does not exist in load flow. A CSV external table did expand itsglob, but read every match sequentially on a single thread.
This resolves the pattern for every format and adds one rule for
parallelising the read:
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.lz4parallel at all. Mixed compression under one pattern works,since the type is detected per resolved file.
Degree of parallelism is
min(files, ncpu)for a local read, and spreadsacross CNs for S3 (
min(files, Σ min(cn.Mcpu, 10))). Shards are balanced bybytes, not file count.
Not changed
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 parquetpaths — so the shard split, whole-file offsets and balanced assignment are
unchanged code.
Two supporting fixes (silent row loss, not the feature itself)
Scopes dropped from a TP-classified plan.
IsSingleScopeansweredtruefor any list under a TP query, and callers act on that by keeping
ss[0]anddiscarding the rest (
compileSinkNode). The same shortcut sat incompileMultiUpdate's non-S3 branch.execTypeis predicted from plan-nodestats 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 branchalready did. Promoting
execTypeinstead is not available here:scheduleQueryWorkersandCalcQueryDOPconsume it before scope building.IGNORE n LINESunder a fanout. The prescan seeds the byte-offset split byrecording one file's header length in
FileStartOffand zeroingTail.IgnoredLines. Under a fanout that offset would apply to every file, soit is skipped for a pattern; the CSV reader re-applies
IGNOREon each file itopens. 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.
Verification
EXPLAIN ANALYZEover 100 lz4 shards (20000 rows):dop,outputRows min=20000 max=20000dop=24,min=800 max=1000LOADdop=24,min=800 max=1000Parquet and arrow external tables still report no
dop.New BVT:
load_data/load_data_glob(63) andtable/external_table_glob(41)— csv / lz4 / mixed-compression patterns, per-file
IGNORE n LINES(a leakedheader shows up as
id = 9999),__mo_filepathpruning across shards,single-match and zero-match patterns, rollback,
INSERT … SELECTinto 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_datahas 6 failures from a root-owned
into_outfiledirectory in the localsandbox, reproducible with a one-line
into outfileand unrelated to thischange.
Not covered locally: S3 external-table fanout builds cross-CN
Magic=Remoteshards; every stage in the BVT suite is a
file://stage, so that path isexercised only by the existing hive parquet case.
🤖 Generated with Claude Code