Skip to content

Commit b57b64e

Browse files
committed
use small bounded channel for bootstrap, making trait async
1 parent d2e3836 commit b57b64e

17 files changed

Lines changed: 307 additions & 237 deletions

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,7 @@ jobs:
379379
run: sudo tail -n 500 /var/log/clickhouse-server/clickhouse-server.err.log || true
380380

381381
lint:
382-
name: clippy + fmt
382+
name: lint
383383
runs-on: ubuntu-latest
384384
timeout-minutes: 15
385385

‎plans/future/INDEX.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ here as they surface; promote into `plans/` when they land
1313
* [pinned_ddl_baseline.md](pinned_ddl_baseline.md) — schema-event outcome must be a function of config + baseline, not cache warmth; seed baseline at start, plus CH-existence / persisted-baseline options for cross-restart consistency
1414
* [coverage100.md](coverage100.md) — drive `cargo llvm-cov` line coverage toward 100%: tiered work list (pure units → fixtures → live e2e → hard tail)
1515
* [FUZZ.md](FUZZ.md) — continuous coverage-guided fuzzing (cargo-fuzz/libFuzzer) across wal-rs + walshadow + clickhouse-c-rs: tiered targets, round-trip/differential oracles, C-boundary ASan, unattended-VM supervisor
16-
* [parallel_decode_and_insert.md](parallel_decode_and_insert.md) — M decoders feeding N inserters against CH Cloud SMT; coalescing seam, cumulative-ack watermark, substrate-agnostic inserter for `clickhouse-c-rs-async`
16+
* [pipeline_backpressure_and_scaling.md](pipeline_backpressure_and_scaling.md) — parallel decode+insert pipeline (landed, merge-ready); remaining work: WAL-pump backpressure via wire/record split, decode/insert scaling (bootstrap Option B, hot-table sharding, N/M sizing)
1717
* [dependencies.md](dependencies.md) — crates.io replacement candidates for generic object storage, MPMC, retry, throttling, and metrics code
1818
* [clickhouse_async/INDEX.md](clickhouse_async/INDEX.md) — native sans-io async in clickhouse-c (additive `clickhouse-async.h` + would-block/rewind core + thread-free Rust client); phased, with column-resumption design open
1919
* [risks.md](risks.md) — measurement-deferred risks and open questions

‎plans/future/TOAST.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ Two gaps fall out:
4343
`encode_value` (`src/ch_emitter.rs`) returns
4444
`EmitterError::UnsupportedValue { kind: "unresolved TOAST pointer (xact
4545
buffer should have reassembled)" }`. This is the
46-
[[parallel_decode_and_insert]] "Blockers, refined" item 2 — bootstrap
46+
[[pipeline_backpressure_and_scaling]] "Blockers, refined" item 2 — bootstrap
4747
*fails*, it does not ship. Latent only because test fixtures keep values
4848
inline (< ~2 KiB, below `TOAST_TUPLE_THRESHOLD`).
4949
* **Pre-window values can't be rebuilt from WAL alone.** A row whose value
@@ -166,7 +166,7 @@ the short-circuit with a real walk:
166166
to the mirrored CH toast table (a `TableMapping` for `pg_toast_<relid>`),
167167
same as any other table. Reuse `toast_chunk_from_decoded`'s shape check to
168168
validate the 3-column layout before shipping.
169-
* wire this through the shared tail per [[parallel_decode_and_insert]]
169+
* wire this through the shared tail per [[pipeline_backpressure_and_scaling]]
170170
"Base backup through the same pipeline": chunks are just more rows, one
171171
`op=Insert` at `_lsn = start_lsn`, no aborts, no barriers. Per-rfn seqs
172172
cover toast filenodes for free.
@@ -302,7 +302,7 @@ dedup is purely a dedup, never a value change.
302302
## Incremental delivery
303303

304304
Smallest-first, each step independently shippable, tied to the
305-
[[parallel_decode_and_insert]] TOAST blocker.
305+
[[pipeline_backpressure_and_scaling]] TOAST blocker.
306306

307307
1. **Fail-fast cleanly.** Make the bootstrap `ExternalToast` path surface a
308308
documented, counted error instead of a bare `UnsupportedValue` deep in
@@ -319,7 +319,7 @@ Smallest-first, each step independently shippable, tied to the
319319
fallback in the R2 reassembler (hydrate the `chunks` map from the CH
320320
toast table, then call `reassemble` unchanged). Bootstrap and pre-window
321321
WAL values now resolve. This resolves the
322-
[[parallel_decode_and_insert]] blocker fully.
322+
[[pipeline_backpressure_and_scaling]] blocker fully.
323323
4. **WAL chunk durability.** Route same-xact `ToastChunk`s to the CH toast
324324
table too (second sink), so a future re-emit of a pre-window referrer
325325
finds its chunks. Without this, step 3's fallback only covers

plans/future/parallel_decode_and_insert.md renamed to plans/future/pipeline_backpressure_and_scaling.md

Lines changed: 104 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
1-
# Parallel decode and insert, pooled decoders feeding pooled inserters
1+
# Pipeline backpressure and scaling (parallel decode+insert: landed; remaining work)
22

3-
Move serial decode+send tail into two pools:
3+
The parallel decode+insert pipeline (pooled decoders feeding pooled inserters)
4+
has landed and is merge-ready; this doc now tracks the remaining work —
5+
WAL-pump backpressure and decode/insert scaling — over the landed design
6+
reference below.
7+
8+
Original thesis — move serial decode+send tail into two pools:
49

510
* M decoders for CPU work: tuple parse, catalog projection, type coercion,
611
detoast, Native encoding
@@ -11,11 +16,14 @@ RTT plus object-storage part commit, so throughput comes from keeping
1116
many INSERTs in flight. CPU parallelism matters only once decode cannot
1217
feed inserters.
1318

14-
`clickhouse-c-rs-async` has landed. Current emitter uses one
15-
`AsyncClient` in `ch_emitter.rs`, so IO no longer parks tokio workers, but
16-
one connection still serializes INSERTs at `EndOfStream`. Remaining work
17-
is fan-out from one connection to N inserter tasks, with shared
18-
`InsertBatcher` stage and cumulative ack accounting.
19+
`clickhouse-c-rs-async` and the pooled decode→insert pipeline have landed.
20+
WAL and bootstrap both run the pooled tail (M decoders / N inserters, default
21+
1/1); out-of-order INSERTs reconcile by `_lsn` and the contiguous-done
22+
watermark drives slot feedback. As of 2026-06-09 the branch is **merge-ready**
23+
and superior to `main` on every axis: N concurrent `AsyncClient` inserters,
24+
async IO that never parks tokio workers, bootstrap through the shared tail,
25+
and bounded bootstrap backpressure. What remains is post-merge future work,
26+
not ship-blockers — see "Post-merge future work" and "Backpressure".
1927

2028
Out-of-order INSERTs are OK. `_lsn` plus `ReplacingMergeTree(_lsn)` makes
2129
final state order-independent (`ch_ddl.rs`,
@@ -71,16 +79,21 @@ Ship-blockers remaining: none. Both cleared — see "Status (2026-06-09)".
7179
2026-06-09 the fail-fast is explicit at the producer (the bootstrap drain),
7280
not a generic encoder rejection deep in the tail.
7381

74-
Known gaps:
82+
Known gaps (none ship-blocking):
7583

76-
* Backpressure goal unmet: pump-to-worker still `mpsc::UnboundedSender`
77-
(`queueing_record_sink.rs`), ack events still `mpsc::unbounded_channel`
78-
(`ack.rs`), bootstrap drain channel `mpsc::unbounded_channel`
79-
(`pipeline/bootstrap.rs`). This is a robustness gap (unbounded buffering
80-
against slow ClickHouse), not a correctness blocker at the validated pool
81-
sizes — see Next step 3 and "Backpressure"
84+
* Backpressure is now correct per channel, not one uniform "bound everything"
85+
goal (the old framing was wrong — the three ingress channels have different
86+
constraints). Bootstrap ingress is bounded: `BackupSink` is async end to end
87+
and the page-walk→drain channel is a bounded `mpsc::channel`
88+
(`BOOTSTRAP_TUPLE_CHANNEL_CAP`), so a saturated inserter parks the page walk
89+
and the source fetch instead of buffering a whole relation (2026-06-09). The
90+
ack-events channel (`ack.rs`) stays unbounded by design — the collector is
91+
pure-sync `state.apply`, strictly faster than any producer, so it cannot
92+
back up. The pump→worker channel (`queueing_record_sink.rs`) is soft-capped,
93+
not hard-bounded, on purpose: a hard bound deadlocks shadow apply. Closing it
94+
needs a wire/record split, post-merge. See "Backpressure"
8295

83-
Next:
96+
Post-merge future work:
8497

8598
1. DONE (2026-06-09). Daemon e2e at pool sizes >1
8699
(`pgbench_acceptance_ddl_intermix_pooled`, M=2/N=2); out-of-order INSERTs
@@ -91,8 +104,11 @@ Next:
91104
serialized Tap sink events that gated `object_store` (Blockers, refined #5)
92105
landed earlier, so both Direct and ObjectStore route through the tail. Decode
93106
pool for bootstrap (parallel-decode Option B) remains gated on measurement
94-
3. Replace unbounded pump-to-worker + ack channels with bounded ones to close
95-
the backpressure chain (the one remaining ship-relevant item)
107+
3. Bound the pump→worker backpressure by splitting wire delivery from record
108+
dispatch so the wire side runs ahead (paced by shadow apply) while record
109+
dispatch blocks on a bounded queue. Architectural, not a channel swap; the
110+
ack channel stays unbounded by design and the bootstrap ingress is already
111+
bounded (see "Backpressure")
96112

97113
Deferred indefinitely:
98114

@@ -150,13 +166,16 @@ Coverage:
150166
* `pipeline::bootstrap` unit tests — per-rfn seq counts, unmapped-skip,
151167
reappearing-rfn (object_store interleave) yields fresh dense seqs.
152168

153-
Still open: parallel-decode Option B gated on measurement; backpressure
154-
(unbounded pump→drain channel, Next step 3). TOAST is now an explicit
169+
Still open: parallel-decode Option B gated on measurement. The bootstrap
170+
page-walk→drain channel is now bounded + async (see "Backpressure"), so this
171+
path's backpressure is closed; only the WAL pump→worker bound remains
172+
(post-merge, Post-merge future work step 3). TOAST is an explicit
155173
producer-side fail-fast (Blockers, refined #2 — done).
156174

157-
## Status (2026-06-09) — ship-blockers cleared
175+
## Status (2026-06-09) — merge ready
158176

159-
Both ship-blockers from the 2026-06-07 status are resolved:
177+
Both ship-blockers from the 2026-06-07 status are resolved, and the bootstrap
178+
ingress backpressure is now closed:
160179

161180
* **Live daemon coverage at pool >1.** `pgbench_acceptance.rs` factors the DDL-
162181
intermix drill into `run_ddl_intermix(ports, decoder_pool, inserter_pool,
@@ -167,11 +186,19 @@ Both ship-blockers from the 2026-06-07 status are resolved:
167186
sum + the `c` column) proves out-of-order INSERTs across connections stay
168187
`_lsn`-correct through the DDL barrier. Both run green concurrently (~22s).
169188
* **TOAST fail-fast, surfaced cleanly.** See Blockers, refined #2 (done).
170-
171-
Remaining work is no longer ship-blocking: backpressure (Next step 3, a
172-
robustness gap), parallel-decode Option B (gated on measurement), and TOAST
173-
assembly (separate work item, [TOAST.md](TOAST.md)). The DDL-type-aware barrier
174-
is deferred indefinitely.
189+
* **Bootstrap backpressure, bounded.** `BackupSink` is async end to end (the
190+
shared sink `Mutex` is now `tokio::sync::Mutex`, all methods `async fn`), so
191+
`PageWalkSink::chunk` awaits a bounded page-walk→drain channel
192+
(`BOOTSTRAP_TUPLE_CHANNEL_CAP`) directly. A saturated inserter parks the page
193+
walk → tar body read → object-store fetch — empty-channel backpressure, no
194+
whole-relation buffer. Lib + clippy green, 384 lib tests pass. See
195+
"Backpressure".
196+
197+
This branch is merge-ready and strictly better than `main`. Remaining items
198+
are post-merge future work, none ship-blocking: the WAL pump→worker bound
199+
(needs a wire/record split, Post-merge future work step 3), parallel-decode
200+
Option B (gated on measurement), and TOAST assembly (separate work item,
201+
[TOAST.md](TOAST.md)). The DDL-type-aware barrier is deferred indefinitely.
175202

176203
## Current serial path
177204

@@ -334,14 +361,20 @@ only reason it doesn't already use the tail is history, not difficulty.
334361
```text
335362
BackupSource (Direct | ObjectStore)
336363
-> MultiplexSink { DiskLanderSink (Keep catalogs), PageWalkSink (Tap heap) }
337-
-> PageWalkSink::chunk [SYNC, under Arc<std::Mutex<dyn BackupSink>>]
364+
-> PageWalkSink::chunk [under Arc<Mutex<dyn BackupSink>>]
338365
-> decode_block_data per LP_NORMAL slot [WALL 1: single-threaded]
339366
-> BackfillTuple -> mpsc::unbounded
340367
-> drain_backfill: BackfillTuple -> CommittedTuple
341368
-> serial Emitter (one AsyncClient) [WALL 2: one INSERT at a time]
342369
-> per-rfn force-flush (flush_timeout=0)
343370
```
344371

372+
Status: Wall 2 is gone — bootstrap routes through the shared N-inserter tail
373+
(DONE 2026-06-07) — and the sink mutex + `chunk` are now async over a bounded
374+
channel (DONE 2026-06-09). Wall 1 (decode still single-threaded on the sink
375+
task) remains, gated on measurement (Option B). The bullets below describe the
376+
original (pre-pipeline) walls for context.
377+
345378
* **Wall 1, decode under the sink mutex.** Page-walk *and* the per-tuple
346379
`decode_block_data` run inside `PageWalkSink::chunk`
347380
(`backup_page_walk.rs`), which every source worker drives while holding
@@ -402,10 +435,11 @@ PageWalkSink::chunk (decode stays here, single-threaded)
402435

403436
This captures the Cloud win (Wall 2) with the smallest change. Decode
404437
(Wall 1) stays single-threaded; remove it only if measurement shows
405-
page-walk decode can't feed N inserters (Option B below). The
406-
`PageWalkSink::chunk` is sync under a `std::Mutex`, so it can't `.await` a
407-
bounded batcher send; the producer→channel→async-drain split stays, with
408-
the channel now bounded (see Backpressure).
438+
page-walk decode can't feed N inserters (Option B below). `PageWalkSink::chunk`
439+
is async (the sink `Mutex` is now `tokio::sync::Mutex`), so `ship_tuple`
440+
awaits the bounded page-walk→drain channel directly: a full channel parks the
441+
page walk and the source fetch, no intermediate buffer (DONE 2026-06-09, see
442+
"Backpressure").
409443

410444
### Synthetic seq scheme
411445

@@ -628,40 +662,52 @@ concurrent-part sink interleaving that used to make this unsafe is now fixed
628662
errors out: incremented files need a disk-resident base to overlay, which
629663
the streaming page-walk doesn't produce. Orthogonal to this plan.
630664

665+
## Backpressure
666+
667+
One bottleneck: the CH inserter pool. `clickhouse-c-rs` keeps no internal send
668+
queue — `AsyncClient::send_data` writes to the socket inside the await and
669+
`drain_to_end_of_stream` awaits the server's `EndOfStream` — so each inserter
670+
task's await *is* the drum, and the internal WAL chain
671+
(reorder→decode→batcher→inserter) is bounded end to end: every stage awaits a
672+
bounded `mpmc`/`mpsc`, the terminal await is the CH send itself. Steady-state
673+
memory there is the sum of those bounded buffers.
674+
675+
The three ingress channels are not one problem with one fix (the earlier
676+
"bound every channel" framing was too coarse):
677+
678+
* **Bootstrap page-walk → drain: bounded (DONE 2026-06-09).** `BackupSink` is
679+
async end to end (sink `Mutex` → `tokio::sync::Mutex`, all methods
680+
`async fn`); `PageWalkSink::ship_tuple` awaits a bounded `mpsc::channel`
681+
(`BOOTSTRAP_TUPLE_CHANNEL_CAP`). A full channel parks the page walk → the tar
682+
body read → the object-store fetch. No standing buffer; the bootstrap paces
683+
to CH. Deadlock-free: bootstrap runs before shadow start, so the drain
684+
consumes on a separate task with no cycle.
685+
* **Ack events (`ack.rs`): unbounded by design, leave it.** The collector loop
686+
is pure-sync `state.apply` (BTreeMap bookkeeping), strictly faster than any
687+
producer, so the channel cannot back up. Bounding it buys zero memory and
688+
would force `ack.acked` off its non-blocking fire-and-forget on the inserter
689+
hot path.
690+
* **Pump → worker (`queueing_record_sink.rs`): soft-capped on purpose; real
691+
bound is post-merge.** `on_record` and shadow-wire delivery are lockstep in
692+
`wal_stream.rs::drain_records`, and `ReorderSink::maybe_sweep_dropped` →
693+
`ShadowCatalog::wait_for_replay` couples decode to shadow apply, which needs
694+
the pump to keep feeding *subsequent* wire bytes (walreceiver flush
695+
granularity). A hard-bounded blocking `on_record` therefore re-introduces the
696+
shadow-starvation deadlock the queueing sink exists to avoid; the soft cap
697+
(yield past `soft_cap`) is the deliberate trade. Under sustained
698+
CH-slower-than-WAL this buffer can still grow, buffering WAL in walshadow RAM
699+
rather than letting the PG slot hold it on disk. The fix is to split wire
700+
delivery (runs ahead, paced by shadow apply) from record dispatch (blocks on
701+
a bounded queue) — architectural, not a channel swap. Post-merge (Post-merge
702+
future work step 3).
703+
631704
## Sizing
632705

633706
* **N inserters** ~= `insert_round_trip / time_to_seal_one_batch`, enough
634707
to avoid Cloud latency binding throughput
635708
* **M decoders** ~= enough that decode throughput >= aggregate insert
636709
throughput; keep M lower than N unless measurements show CPU bottleneck
637710

638-
## Backpressure
639-
640-
Use bounded channels everywhere. Current pump-to-worker mpsc is
641-
unbounded; replace it as part of pool work.
642-
643-
Backpressure chain:
644-
645-
```text
646-
inserter queue full -> InsertBatcher stalls -> decoders block -> job queue fills
647-
-> reorder stalls -> pump soft_cap yields -> walsender queues
648-
```
649-
650-
Bootstrap has the same gap and then some: the `PageWalkSink -> drain`
651-
channel (`backup_page_walk.rs::out_tx`) is `mpsc::unbounded` *by necessity*
652-
today, because `chunk()` is sync under a `std::Mutex` and `blocking_send`
653-
panics in the runtime. Bounding it needs a sync `try_send` + capacity (drop
654-
to a parking strategy on full) or moving the page split off the sink task.
655-
Its chain mirrors WAL:
656-
657-
```text
658-
inserter queue full -> batcher stalls -> bootstrap drain blocks
659-
-> PageWalkSink channel fills -> sink chunk() parks -> BackupSource backpressures
660-
(DirectSource bounded events channel / ObjectStoreSource buffer_unordered)
661-
```
662-
663-
Goal is bounded overlap, not unbounded buffering against slow ClickHouse.
664-
665711
## Build order
666712

667713
1. Add instrumentation: decode CPU, inserter drain wait, pump idle

0 commit comments

Comments
 (0)