Skip to content

feat(load): distribute multi-file CSV reads across threads - #29245

Merged
fengttt merged 4 commits into
matrixorigin:mainfrom
fengttt:feat-external-glob-fanout
Sep 23, 2026
Merged

fengttt merged 4 commits into
matrixorigin:mainfrom
fengttt:feat-external-glob-fanout

Conversation

@fengttt

@fengttt fengttt commented Sep 22, 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 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.

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

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 parquet
paths — 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. 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.

Verification

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

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-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 — REQUEST_CHANGES

发现两个 P2:

  1. 非首个 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 回归。

  2. 远端 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]>
@fengttt

fengttt commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Thanks for the review. Both findings are fixed in dc2026c.

  1. UNIQUE row locks on non-first LOAD shards. compileLock now merges whenever len(ss) > 1, the same rule compileMultiUpdate uses, so the lock operator covers every fanout shard in a TP-classified plan. Regression test: TestCompileLockMergesMultiScopeTpPlan.
  2. Remote CSV shards losing external-table semantics. Remote whole-file shards now send the compile-time normalized ExternParam as CreateSql. It includes ExternType from the plan and any stage-resolved S3 settings, and it's marked Resolved so the receiver skips re-deriving S3 settings from Option. An older CN ignores the flag and behaves as before. Regression test: TestCompileExternScanMultiFileFanoutRemoteKeepsNormalizedParam, which sends each shard through the real encode/decode and Prepare. The test fails without the fix.

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

REQUEST_CHANGES — two P2 issues remain at this exact head.

  1. Rolling-upgrade S3 compatibility: pkg/sql/compile/compile.go around line 4058 sends the normalized ExternParam JSON with Resolved=true. An older CN ignores that field and re-runs InitS3Param, 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.

  2. max_dop is not honored: getHiveFileFanoutNodes around line 4461 sizes local fanout from c.ncpu without applying the session's effective max_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 focused max_dop=1 test.

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

本次只确认到两项 P2,没有 P0/P1。最新一轮既有 review(2026-09-23 05:27 UTC)的两项 P2 尚未见作者回复;04:20 UTC 的作者回复针对的是更早一轮问题,并说明已在当前 head 修复。因此按 P2-only 且未回复的规则提交 COMMENT。

  1. 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 格式。

  2. 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 且 INFILE pattern 命中多个文件时,会并发创建多个 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]>
@fengttt

fengttt commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH @iamlinjunhong Thanks. Both P2s from this round are fixed in d965edc.

  1. Rolling-upgrade S3 compatibility. The Resolved field is gone; ExParam and External.Prepare are unchanged from main. The remote shard now writes the resolved S3 settings (endpoint, region, credentials, bucket, provider, role_arn, external_id) back into Option, using the keys InitS3Param already parses. Stale values for those keys and filepath are replaced, and unrelated keys (hive, format, compression) are kept. So an older CN running its existing unmarshal-then-InitS3Param path rebuilds the same S3Param, and it reads ExternType from a field it already knows. No wire-format change and no capability gate needed.
    Regression tests: TestCompileExternScanMultiFileFanoutRemoteKeepsNormalizedParam now also simulates the legacy receiver (plain json.Unmarshal + InitS3Param on the payload) for a stage-backed source whose original Option has a stale bucket/filepath. It checks ExternType, ScanType, Filepath and S3Param. TestS3ParamOptionsRoundTripsThroughInitS3Param covers every S3 key.
  2. max_dop. getHiveFileFanoutNodes (and the matching parquetLoadFileFanoutDOP) now caps readers per CN at the query's MaxDop, the same per-CN cap compileQuery hands CalcQueryDOP. This applies to both the local c.ncpu branch and the S3 worker Mcpu branch. With max_dop=1, a multi-file scan on one CN falls back to the single-scope serial reader.
    Regression test: TestFileFanoutHonorsMaxDop covers max_dop 0/3/1 locally, the end-to-end fanout at max_dop=1 (one scope, all files), and max_dop=2 across two S3 workers (2 per CN).

Both new tests fail without the corresponding fix. compile, external and plan package tests, go vet and make static-check pass locally. As before, I haven't run a live mixed-version or multi-CN deployment.

@fengttt
fengttt merged commit 1b03559 into matrixorigin:main Sep 23, 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]>
fengttt added a commit that referenced this pull request Sep 25, 2026
…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]>

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/feature size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants