Skip to content

ReaderExecutor: pipeline-based read orchestration - #103706

Draft
CheSema wants to merge 749 commits into
masterfrom
reader-executor
Draft

CheSema wants to merge 749 commits into
masterfrom
reader-executor

Conversation

@CheSema

@CheSema CheSema commented Apr 29, 2026 •

Copy link
Copy Markdown
Member

Builds on top of #103234 (ReadPipeline). Gated by SET use_reader_executor = 1 (experimental, default off).

This commit replaces the matryoshka of ReadBuffer wrappers with a ReaderExecutor that owns offset mapping, cache decisions, prefetch and decryption in one place. Caches plug in via a uniform ICacheProvider / ICacheHandle API.

What this brings

Zero-copy page-cache hits. Reads served from PageCache reach the caller as a shared_ptr into the mmap'd cell — no memcpy between cache and working buffer (compare to CachedInMemoryReadBufferFromFile's per-block copy).

Connection reuse across remote read calls. Sequential reads against the same S3/Azure/HTTP object reuse an open buffer instead of issuing a new HTTP request per window. SourceBufferLimit caps live connections globally (max_remote_read_connections, default 1000); over-limit reads fall back to stateless open-read-close. Visible via system.remote_read_connections.

Coordinated cache + prefetch decisions. The matryoshka design had each layer making independent choices (prefetch ahead in AsynchronousBoundedReadBuffer, decide what to cache in CachedOnDiskReadBufferFromFile, gather across objects in ReadBufferFromRemoteFSGather). The executor sees the whole window:

  • prefetches only what isn't already cache-hit
  • retains source over-read only when paired with a live connection (drops it otherwise)
  • knows which bytes are user-requested vs cache-fill, so it doesn't account cache-fill bytes against the user's read budget

Per-object cache identity, not per-pipeline. DiskCacheProvider derives FileCacheKey / FileCacheOriginInfo per StoredObject (etag-keyed caching for StorageObjectStorageSource, segment-key-type classification for Data vs System queues). The old single-key-per-executor approach silently shared cache identity across all objects in a gather-mode read.

Foundation for new cache backends. New caches (vector cache, distributed cache, etc.) implement one interface (ICacheProvider::lookup) and plug into the chain without touching read paths.

Observability

  • system.remote_read_connections — open connections (path, query id, position, elapsed)
  • system.reader_executor_log — per-executor stats (cache hit/miss/populate bytes, prefetch hits/cancellations, source request count, decrypt time, …)
  • ProfileEvents: ReaderExecutor* counters and microsecond timers; LiveSourceBuffer* counters
  • HistogramMetrics: cache get/populate/source-read/prefetch-wait latencies

Server settings

  • reader_executor_prefetch_pool_size (default 8) — shared prefetch thread pool size
  • reader_executor_prefetch_queue_size (default 0 = pool_size * 10) — pool queue depth
  • max_remote_read_connections (default 1000) — live-buffer slot count, reload-able

Internals

  • Rope / RopeNode / OwnedRopeBuffer — refcounted buffer chains with mixed provenance (owned, page-cache-pinned), built-in cursor (peek/advance/tryRewind), sorted-on-insert nodes, disjoint-interval coverage tracking.
  • ICacheProvider / ICacheHandle — uniform cache API (lookup → status/get/put). Two implementations: PageCacheProvider (file-level, zero-copy), DiskCacheProvider (per-object, FileCache-backed).
  • ISourceReader — stateless range-read interface. LocalSourceReader, ObjectStorageSourceReader, BufferSourceReader (adapter for backup / BufferCreator).
  • OffsetMap — replaces ReadBufferFromRemoteFSGather's gather logic with a logical-to-(object, object-offset) lookup; supports single-object unknown-size (S3 HEAD without Content-Length → streams to EOF).
  • ReaderExecutor — owns: position, offset map, cache chain, prefetch handle, live buffer, over-read tail, source-buffer slot.
  • PipelineReadBuffer — thin ReadBufferFromFileBase exposing the executor through BufferBase::set/next/seek (so legacy callers see no change).
  • PrefetchThreadPool — shared bounded pool, returns nullptr on overflow (sync fallback), task cancellation is race-free.

Testing

~3,700 lines of tests (≈46% of the PR), 130+ gtest cases:

  • gtest_rope — 31 cases (append / peek / advance / tryRewind / slice / copyTo / coverage queries / shift).
  • gtest_reader_executor — 41+ cases (cache-chain combinations, per-object lookup, prefetch races, EOF release, slot leak fixes, unknown-size streaming, …).
  • gtest_filecache — 22 cases including over-read / bypass-mode / partial coverage scenarios.
  • gtest_read_pipeline — known/unknown size selection through the executor.
  • Functional: 04262_reader_executor_observability plus opt-outs (SET use_reader_executor = 0) on tests that intentionally exercise the legacy path.

Load tesing

the simpliest cache API"

┌─────────┬────────────┬──────────┬───────┬────────────────────────┐
│ regime  │ legacy QPS │ exec QPS │ QPS Δ │ per-query-type latency │
├─────────┼────────────┼──────────┼───────┼────────────────────────┤
│ cold    │      0.252 │    0.320 │  +27% │       −12% (faster) ✅ │
├─────────┼────────────┼──────────┼───────┼────────────────────────┤
│ warm    │      0.407 │    0.252 │ −38%¹ │       +27% (slower) ❌ │
├─────────┼────────────┼──────────┼───────┼────────────────────────┤
│ partial │      0.247 │    0.251 │   +2% │       +37% (slower) ❌ │
└─────────┴────────────┴──────────┴───────┴────────────────────────┘

changed cache API (stream aware):

Full clean verdict — 9e9abe9d (26.6.1.1)

┌─────────────┬─────────────────────────┬───────────────────────────────────────────────────┐
│   Regime    │   Executor vs legacy    │                       Note                        │
├─────────────┼─────────────────────────┼───────────────────────────────────────────────────┤
│ ✅ cold     │ −15% (win)              │ 0 slot fail; coalesced reads                      │
├─────────────┼─────────────────────────┼───────────────────────────────────────────────────┤
│ ✅ warm     │ −8% (win)               │ 0 slot fail; cache reads healthy                  │
├─────────────┼─────────────────────────┼───────────────────────────────────────────────────┤
│ ⚠️ partial  │ +7%                     │ S3-source over-read / churn on uncached half      │
├─────────────┼─────────────────────────┼───────────────────────────────────────────────────┤
│ ❌ populate │ +17% (worst)            │ 50% connection reuse on cache-fill path — churn   │
├─────────────┼─────────────────────────┼───────────────────────────────────────────────────┤
│ ✅ stress   │ 27 ok / 1 OOM vs 4 / 11 │ controlled degradation = net win (bounded, alive) │
└─────────────┴─────────────────────────┴───────────────────────────────────────────────────┘


stress details:

┌───────────────────────┬───────────┬──────────┐
│                       │  legacy   │ executor │
├───────────────────────┼───────────┼──────────┤
│ queries finished (ok) │         4 │       27 │
├───────────────────────┼───────────┼──────────┤
│ failed                │        11 │        1 │
├───────────────────────┼───────────┼──────────┤
│ OOM                   │        11 │        1 │
├───────────────────────┼───────────┼──────────┤
│ connection reuse      │     86.8% │    98.8% │
├───────────────────────┼───────────┼──────────┤
│ connection resets     │   233,618 │   38,581 │
├───────────────────────┼───────────┼──────────┤
│ peak TCP recv-buffer  │ 4,152 MiB │  813 MiB │
├───────────────────────┼───────────┼──────────┤
│ TCP sockets           │    17,333 │    1,548 │
├───────────────────────┼───────────┼──────────┤
│ cgroup mem            │  24.4 GiB │ 24.6 GiB │
└───────────────────────┴───────────┴──────────┘

sha -- 494fcfe8825c

┌─────────┬──────────────┬──────────────┬──────────────┐
│ regime  │ baseline QPS │ executor QPS │  exec/base   │
├─────────┼──────────────┼──────────────┼──────────────┤
│ cold    │        0.207 │        0.292 │ 1.41× (+41%) │
├─────────┼──────────────┼──────────────┼──────────────┤
│ warm    │        0.330 │        0.307 │  0.93× (−7%) │
├─────────┼──────────────┼──────────────┼──────────────┤
│ partial │        0.375 │        0.420 │ 1.12× (+12%) │
└─────────┴──────────────┴──────────────┴──────────────┘

That is good outcome. I need to optimize the work with caches. Need to stream data from available cache segments without any additional costs.

sha -- dd4ae00fdaac (26.7.1.1)

┌──────────┬──────────────┬──────────────┬──────────────┐
│ regime   │ baseline QPS │ executor QPS │  exec/base   │
├──────────┼──────────────┼──────────────┼──────────────┤
│ cold     │        0.230 │        0.328 │ 1.43× (+43%) │
├──────────┼──────────────┼──────────────┼──────────────┤
│ warm     │        0.244 │        0.302 │ 1.24× (+24%) │
├──────────┼──────────────┼──────────────┼──────────────┤
│ partial  │        0.332 │        0.325 │ 0.98× (−2%)  │
├──────────┼──────────────┼──────────────┼──────────────┤
│ populate │        0.348 │        0.384 │ 1.10× (+10%) │
└──────────┴──────────────┴──────────────┴──────────────┘

First build with every regime at parity or better. The warm coordination-CPU tax and the populate cache-write regression are both gone; populate over-read down to 14%. Run under production-default networking (disk_connections_rcvbuf=204800, max_remote_read_connections=1000), with reader_executor_use_long_connections=1 set explicitly (its default flipped to 0 on this build). Long-connection hit rate 99.5–100% on all regimes.

sha -- fcccec1c7e6c (26.7.1.1) — equal-workload methodology

┌──────────┬───────────────┬───────────────┬──────────────┐
│ regime   │ baseline wall │ executor wall │   speedup    │
├──────────┼───────────────┼───────────────┼──────────────┤
│ cold     │         959 s │         705 s │ 1.36× (+36%) │
│ warm     │         665 s │         450 s │ 1.48× (+48%) │
│ partial  │         592 s │         540 s │ 1.10× (+10%) │
│ populate │         552 s │         516 s │ 1.07× (+7%)  │
│ evict    │         601 s │         565 s │ 1.06× (+6%)  │
└──────────┴───────────────┴───────────────┴──────────────┘

Methodology fix: both arms now run the identical query multiset (--iterations, sequential — no --randomize), metric = total wall time. The earlier windowed-QPS numbers systematically penalized the faster arm (a free benchmark worker draws a new random query, so the faster arm attracts more heavy queries) — warm was reported −9…−14% but is actually +48%; evict = new regime with the FileCache as a transit buffer (continuous eviction, no cross-query hits).

The executor is faster in all five cache regimes; the 128-thread stress arm now completes without stuck queries (previously required KILL QUERY), with 4× fewer sockets than legacy. No correctness errors or crashes across the campaign since c089b7e5.

Known remaining costs (per-query analysis): (1) cold/partial S3 over-read 2.2–2.8× from prefetch speculation; (2) on mixed cache regimes small queries regress 2-3× — cache_get returns zero bytes for data that is present (FileSegmentWait on DOWNLOADING segments, then reads from source anyway) plus block-granular request amplification on narrow columns (~90 MiB requested for a 5 MiB column), paid at S3 first-byte latency with ~90% of prefetches cancelled.

sha -- 018c0257567b (26.7.1.1) — plan-look-ahead window build

┌──────────┬───────────────┬───────────────┬──────────────┐
│ regime   │ baseline wall │ executor wall │   speedup    │
├──────────┼───────────────┼───────────────┼──────────────┤
│ cold     │         810 s │         619 s │ 1.31× (+31%) │
│ warm     │         477 s │         450 s │ 1.06× (+6%)  │
│ partial  │         785 s │         518 s │ 1.52× (+52%) │
│ populate │         532 s │         478 s │ 1.11× (+11%) │
│ evict    │         579 s │         581 s │ 1.00× (par)  │
└──────────┴───────────────┴───────────────┴──────────────┘

Same equal-workload methodology (identical 186-query multiset per arm). Since the workload is fixed, executor wall times are directly comparable across builds: vs fcccec1c the executor improved on cold (705→619 s, −12%), populate (516→478 s, −7%) and partial (540→518 s, −4%) — the plan-window changes helped. Baseline wall times swing between rounds (legacy path + master merge + day variance), so cross-build conclusions should use the executor-vs-executor columns, not the ratios.

Also corrected with the fixed workload: the true equal-work S3 over-read is ~2.0× on cold and ~2.3× on partial (the earlier 2.8–2.9× figures were inflated by the windowed methodology — the faster arm simply ran more queries per window). Stress arm self-completed again (4th consecutive build). No Code: 33, no crashes.

sha -- 2b43930ebbcf (26.8.1.1) — read-path log cut + settings-history dedup

┌──────────┬───────────────┬───────────────┬──────────────┐
│ regime   │ baseline wall │ executor wall │   speedup    │
├──────────┼───────────────┼───────────────┼──────────────┤
│ cold     │         496 s │         315 s │ 1.57× (+57%) │
│ warm     │         223 s │         226 s │ 0.99× (par)  │
│ partial  │         326 s │         254 s │ 1.28× (+28%) │
│ populate │         242 s │         240 s │ 1.01× (par)  │
│ evict    │         281 s │         304 s │ 0.92× (−8%)  │
└──────────┴───────────────┴───────────────┴──────────────┘

Two rounds this cycle. The morning round (head a6465d03) exposed a hot-read-path logging tax: PipelineReadBuffer logged one Trace message per window advance (6.3M messages per warm arm) plus ~1M per-buffer Debug "Created" messages, costing 795 s of thread time per arm (baseline: 6.7 s) — roughly 14% of the CPU budget on cache-served regimes, which showed as warm/populate 0.95×. The same-day fix (da34b431) is verified by this round: logger time dropped 795 → 170 s, allocation volume dropped 5.85 → 1.94 TB ≈ baseline's 1.84 TB (most of the long-standing "executor allocates ~4× more" observation was log-message formatting), and executor UserTime is now below baseline on warm. Populate flipped to parity-plus; warm is at 0.99× with the residual logger time still 34× baseline — a few more sites may be worth demoting.

S3 over-read: populate 1.01× and evict 1.03× (the executor no longer over-fetches where the cache absorbs writes), cold 1.20× while making 7× fewer GETs at ~11 MiB each (this is what buys the 1.57× cold wall), partial 1.38× — the remaining cost item.

The evict 0.92× turned out to be regime noise: a clean repeat pair on the settled cluster came back 323/279 s = 1.16× in the executor's favor, matching the morning round's 1.17× (evict has a history of single-pair swings — 0.78× → 1.18× between two runs of one build earlier). Verdict: executor ≥ baseline in all five regimes.

Environment notes for cross-entry comparison: starting with this cycle the staging instance's default profile compatibility was bumped 25.12 → 26.8, which changes effective defaults for both arms — all walls in this entry are ~2× faster than in previous entries for that reason; compare ratios, not walls, across entries. Relatedly, the settings-history dedup in this head means Cloud compatibility no longer resurrects the pre-release 8 MiB reader_executor_plan_look_ahead_max_window introduction default on private builds.

Zero failed queries, no Code: 33, no crashes across all 20 arms of both rounds.

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Add experimental ReaderExecutor for pipeline-based read orchestration with unified cache API (PageCacheProvider, DiskCacheProvider), connection reuse for remote reads, a shared prefetch pool, and observability via the system.reader_executor_log table and ReaderExecutor* ProfileEvents / CurrentMetrics. Enable with SET use_reader_executor = 1.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Workflow [PR]
Sync PR [sync-upstream/pr/103706]

@CheSema
CheSema force-pushed the reader-executor branch 4 times, most recently from 77b9b0a to fb8ddfb Compare April 30, 2026 01:32
@CheSema
CheSema changed the base branch from read-pipeline-redesign to master April 30, 2026 02:57
@clickhouse-gh

clickhouse-gh Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [efa6e0a]

Summary: ❌

job_name test_name status info comment
Style check FAIL
system_table_documentation_pages FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Apr 30, 2026
Comment thread src/IO/ReaderExecutor.cpp Resolved
Comment thread src/IO/ReaderExecutor.h Resolved
Comment thread src/IO/ReaderExecutor.cpp Resolved
Comment thread src/IO/Rope.cpp Resolved
@CheSema
CheSema force-pushed the reader-executor branch 2 times, most recently from 8e5f067 to f9d35b8 Compare April 30, 2026 04:47
Comment thread src/IO/ReadPipeline.cpp Resolved
Comment thread src/IO/LocalSourceReader.cpp Resolved
Comment thread src/IO/ReadPipeline.cpp Resolved
Comment thread src/IO/PipelineReadBuffer.cpp Resolved
@CheSema
CheSema changed the base branch from master to read-pipeline-redesign April 30, 2026 05:31
@CheSema
CheSema changed the base branch from read-pipeline-redesign to master April 30, 2026 05:34
Comment thread src/IO/ReaderExecutor.cpp Resolved
@CheSema
CheSema force-pushed the reader-executor branch 7 times, most recently from cd5c38a to fbb1388 Compare April 30, 2026 06:39
Master's `c3f40eb660cf` (`enable_silk_runtime`, `Common/SilkFiberScheduler.h`) and this
branch's reader-executor fiber machinery (`disk_connections_use_silk`,
`Common/SilkScheduler.h`) both started the process-wide `silk::FiberScheduler` directly:
with both settings on the server would trap on the contrib double-init, the merged
`unit_tests_dbms` would trap the same way (the branch's eager gtest environment plus
master's lazy `initializeFiberSchedulerForTests`), and the two sides' fiber categories
collided (`SilkFiberCategory::FETCH` and `CLICKHOUSE_FIBER_CATEGORY` were both 1) while
their switch hooks blind-cast the fiber parameters to incompatible types.

Now `Silk::initializeFiberScheduler` is the single owner of the contrib runtime and its
switch hooks dispatch on the fiber category: fibers spawned via `Silk::spawn` keep the
FiberLocalStorage swap, and fibers of one extra registered category (the reader executor's
FETCH, moved to 2) are forwarded to the hooks registered via the new
`Silk::setFiberHooksForCategory`. `initializeSilkScheduler` keeps the io_uring probe and
reuses an already-started scheduler; the gtest environment shares the lazy test helper.
`Throttler::sleep` (resolved in the merge) checks both fiber-detection conventions. The
`current_thread` swap for FETCH fibers goes through the `FiberLocal` API now that master
converted `current_thread` from plain TLS.

Verified: `unit_tests_dbms --gtest_filter='*Silk*:*Fiber*:*Rope*'` (both conventions in
one process), `*ReaderExecutor*`/`*ReadPipeline*`, and `FileCacheTest*` all pass;
`clickhouse local` smoke with `use_reader_executor` 0/1 agrees.
…`/`reader_executor_block_size` in the 26.8 settings-history block

The 26.8 block listed `reader_executor_window_size` twice (8388608 from the current
introduction and a stale 4194304 pair left behind by an earlier merge);
`reader_executor_block_size` was likewise listed twice. Kept the entries matching the
current defaults in `src/Core/Defines.h`.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Kept the branch current — it had gone CONFLICTING again. Pushed three commits, head 13afe503.

Merge 5601152 (criss-cross again; merged via git merge-tree --merge-base=<parent2-of-previous-merge>, only 5 content conflicts). Notable resolution: master landed its own Silk integration (enable_silk_runtime, Common/SilkFiberScheduler.*, current_thread as FiberLocal) in parallel with this branch's Common/SilkScheduler.* fiber machinery, so Throttler::sleep now checks both fiber-detection conventions, and gtest_silk_fiber_stream_socket.cpp took master's rewrite onto the lazy initializeFiberSchedulerForTests harness.

11f7215 — unified the two Silk runtime initializations. Without this, a server with both enable_silk_runtime and disk_connections_use_silk on, and the merged unit_tests_dbms (this branch's eager gtest environment + master's lazy helper), would trap on the contrib scheduler's double-init; also SilkFiberCategory::FETCH collided with master's CLICKHOUSE_FIBER_CATEGORY (both 1) while the two hook sets blind-cast fiber parameters to incompatible types. Now Silk::initializeFiberScheduler is the single owner of the contrib runtime, its switch hooks dispatch on the fiber category (new Silk::setFiberHooksForCategory), FETCH moved to 2, and initializeSilkScheduler keeps the io_uring probe but reuses an already-started scheduler. The current_thread swap for FETCH fibers goes through the FiberLocal API; they keep sharing the carrier's FiberLocalStorage for the other slots (same semantics as the old plain-TLS world). Left for you: whether to eventually move the FETCH fibers onto Silk::spawn/FiberLocalStorage outright, and that master's shutdown path destroys the shared scheduler when enable_silk_runtime is on (this branch's machinery assumed never-destroyed).

13afe50 — removed a stale duplicate introduction of reader_executor_window_size/reader_executor_block_size in the 26.8 settings-history block (kept the entries matching the current 8 MiB / 1 MiB defaults).

Verified locally (aarch64 release): ninja clickhouse unit_tests_dbms green; --gtest_filter='*Silk*:*Fiber*:*Rope*' 25/25 pass with both fiber conventions in one process; *ReaderExecutor*/*ReadPipeline* 182 pass; FileCacheTest* 46 pass; clickhouse local smoke with use_reader_executor 0/1 agrees. The PR is MERGEABLE again.

# Conflicts:
#	tests/queries/0_stateless/03413_experimental_settings_cannot_be_enabled_by_default.sql
`master` moved on to `26.9`, so the entries this branch had added to the
`26.8` block of `src/Core/SettingsChangesHistory.cpp` no longer sit in the
current-version block and the `settings_changes_history` style check fails
(which drops every other CI job).

Moved the branch's own records to the `26.9` block:

- session settings `enable_reader_executor_log`,
  `reader_executor_plan_look_ahead_max_window`, `reader_executor_hold_consumed`
  and `reader_executor_use_fibers` (new here);
- `reader_executor_window_size` as a value change `4194304` -> `8388608`
  (`DEFAULT_READER_EXECUTOR_WINDOW_SIZE`), leaving the released `26.8` record
  that master already carries untouched;
- `reader_executor_max_tail_for_drain` as a value change `1048576` -> `524288`
  (`DEFAULT_READER_EXECUTOR_MAX_TAIL_FOR_DRAIN`), leaving the `26.7` record
  untouched;
- `MergeTree` settings `merge_reader_executor_window_size`,
  `merge_reader_executor_plan_look_ahead_max_window`,
  `merge_reader_executor_fill_ahead_lead` and `merge_reader_executor_hold_consumed`.

The file is now a pure addition on top of master, so no released record is
reattributed to another version.
A master merge left the header included twice, which `clang-tidy`
(`readability-duplicate-include`) rejects, failing the `arm_tidy` build.
Master landed the spun-off, reviewed memory-pressure work
(`reader-executor-memory-pressure`) that this branch still carried in its
earlier form, so the conflicts are that subsystem meeting itself:

- `Common/MemoryPressureMonitor.{h,cpp}`, its gtest, `MemoryTracker::getPressure`
  and `ThreadGroup`'s monitor: take master's version wholesale. It is the
  reviewed iteration - shared server-wide thresholds with a generation, a
  lock-free `PressureCooldown`, and a per-scope monitor hierarchy - replacing
  this branch's `PressureLevelMachine` / `IMemoryPressureMonitor` design.
- `Server.cpp`: master's reload path, i.e. the renamed
  `reader_executor_memory_pressure_{elevated,high,critical}_level_pct` server
  settings and `setMemoryPressureThresholds`; this branch's Silk scheduler
  startup and disk-socket handling are kept.
- `ServerSettings.cpp`: dropped this branch's superseded
  `..._level_{1,2,3}_pct` declarations and their `system.server_settings` rows,
  which master now reports from `getMemoryPressureThresholds`.
- `Defines.h`: master's `MIN_READER_EXECUTOR_SIZE` of 128 KiB and the default
  threshold percents, with this branch's 512 KiB
  `DEFAULT_READER_EXECUTOR_MAX_TAIL_FOR_DRAIN`.
- `ReaderExecutor.{h,cpp}` and its gtest: keep this branch's rewritten executor,
  which already expresses master's pressure-adjusted sizing through
  `effectiveWindowSize` / `effectiveBlockSize` (including the long-connection
  admission rule master tightened), and retarget it at the new monitor API
  (`CurrentThread::getMemoryPressureMonitor`, `MemoryPressureLevel::Count`).
  Also size the dropped connection's drain scratch by the pressure-adjusted
  block, as master does.
- `PrefetchWindowRespondsToMemoryPressure` drives the level through the query's
  group memory tracker, the way master's pressure tests do, since the fake
  monitor and its RAII installer no longer exist.
- `test_reader_executor_memory_pressure_config` follows the renamed settings.
`master` reshaped the fill-coordination contract while this branch kept
rewriting the executor on top of the older one, so the merged tree did not
build. Adapt this branch to what landed:

- `CacheWriter::Claim` is `CacheWriter::FillRole`, and `committed` is the end of
  the committed prefix instead of an `IntervalSet`. `committedPartsIn` derives
  the one overlapping range from that prefix, and the mocks in
  `gtest_reader_executor` report their interval ledger's first gap.
- `claimLeadRole` is back as a non-virtual helper on `CacheWriter`, over
  `committed` + `takeFillRole`: this branch asks per sub-range of a cell (a
  window covers only part of one), and it is exactly what the two forms answer
  together. A range fully inside the committed prefix takes no role.
- `ICacheProvider::populatesOnMiss` is gone: a tier that does not populate
  resolves its misses without a writer, so the plan builder keys the fill cell
  off `res.writer` and the decryption-header populate off a miss that carries
  one.
- `MemoryPressureLevel` gained a `Count` enumerator, the per-`ThreadGroup`
  machine became a per-scope `MemoryPressureMonitor`, and the level is read
  through `CurrentThread::getMemoryPressureMonitor`.
- `DiskCacheWriter::committed` is now the segment's live frontier rather than a
  per-writer ledger, so a continuation writer sees the sibling's prefix:
  `SecondWriterContinuesFromCommittedFrontier` asserts the completed cell.

Also, drop this branch's `reader_executor_window_size` settings-history entry -
`master` records the same 4 MiB to 8 MiB change in the same `26.9` block - and
count the bytes a reused long connection discards to bridge a cached gap into
`ReaderExecutorPrefetchIssuedSourceBytes`, so a discarded prefetch reports the
bandwidth it actually cost (an automated-review finding).

`ninja clickhouse unit_tests_dbms` is green; 301 `ReaderExecutor` / `ReadPipeline`
/ cache-buffer / residency / memory-pressure / `FileCacheTest` / Silk gtests pass.
…, per-query cache accounting

Four findings the AI review lists under "minimum required actions", plus the
non-Silk reload warning:

- `FileCache::tryReserve`: `QueryContext::add` returns nothing, so the
  freshly-inserted per-query record stayed unreachable - it was never sized on
  the success path, and neither the `catch` nor the `createBaseDirectory`
  rollback could drop it, leaving a zero-sized record behind for a reservation
  that failed. Read the record back under the same lock, and roll it back on
  both failure paths: remove it when this reservation inserted it, or give back
  just the size it added when the record predates it. A record is removed
  rather than invalidated because the query context keys its records by key and
  offset, so an invalidated one would be handed back by the next `tryGet`.
- `LocalSourceReader` carries the caller's `read_hint`, which is what
  `createReadBufferFromFileBase` sizes the buffer and keys the mmap / direct-IO
  thresholds on, and no longer passes `StoredObject::UnknownSize` as a concrete
  `file_size` - the sentinel is a huge number and would turn every stat-failed
  read into a direct-IO one.
- `DiskLocal::prepareRead` attaches the prefetch pool when the local read method
  is `pread_threadpool` and `local_filesystem_read_prefetch` is set, mirroring
  the remote path's gate. Without it `PipelineReadBuffer::prefetch` reached an
  executor with no pool to schedule on, so the setting was a silent no-op on the
  executor path.
- `ReadPipeline` skips the disk cache for an unknown-size object, as it already
  skips the page cache: streaming until EOF has no file length to bound cache
  segments with, and `UnknownSize` would be taken for one.
- A build without Silk now warns when `disk_connections_use_silk` is turned on
  by a config reload; its one-shot boot warning only covers the setting being on
  at startup. Also drop the duplicate `max_remote_read_connections` extern and
  the externs of the renamed memory-pressure settings left by the merge.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Kept the branch current and worked through the AI review's blocking list. Pushed three commits, head 5535501a661e.

1. master merge (fade1861). Single merge base this time, but a substantive one: master landed the spun-off, reviewed memory-pressure work (reader-executor-memory-pressure) plus the cache-writer API reshape, both of which this branch still carried in their earlier form. Resolutions:

  • Common/MemoryPressureMonitor.{h,cpp}, its gtest, MemoryTracker::getPressure, ThreadGroup's monitor and Server.cpp's reload path: took master wholesale — shared server-wide thresholds with a generation, a lock-free PressureCooldown, a per-scope monitor hierarchy, and the renamed reader_executor_memory_pressure_{elevated,high,critical}_level_pct settings. This branch's PressureLevelMachine / IMemoryPressureMonitor and the ..._level_{1,2,3}_pct declarations (with their system.server_settings rows) are gone; the integration test follows the new names. Your Silk startup and disk-socket handling in Server.cpp are kept.
  • Defines.h: master's MIN_READER_EXECUTOR_SIZE of 128 KiB and the default threshold percents, with this branch's 512 KiB DEFAULT_READER_EXECUTOR_MAX_TAIL_FOR_DRAIN.
  • ReaderExecutor.{h,cpp} and its gtest: kept this branch's rewritten executor — it already expresses master's pressure-adjusted sizing through effectiveWindowSize / effectiveBlockSize, including the long-connection admission rule master tightened — retargeted at the new monitor API, and sized the dropped connection's drain scratch by the pressure-adjusted block as master does. PrefetchWindowRespondsToMemoryPressure drives the level through the query's group memory tracker now, the way master's pressure tests do.

2. API reconciliation (a7bdf34f) — the merged tree did not build, because master reshaped the fill-coordination contract underneath this branch's rewrite:

  • Claim → FillRole; committed is the committed-prefix end, not an IntervalSet (committedPartsIn derives the single overlapping range; the gtest mocks report their ledger's first gap).
  • claimLeadRole is back as a non-virtual helper on CacheWriter over committed + takeFillRole. This branch asks per sub-range of a cell (a window covers only part of one), which is exactly what the two forms answer together; a range fully inside the committed prefix takes no role. Say the word if you would rather have the two call sites open-coded against takeFillRole.
  • ICacheProvider::populatesOnMiss is gone, so the plan builder keys the fill cell off res.writer and the decryption-header populate off a miss that carries one.
  • DiskCacheWriter::committed is the segment's live frontier now, not a per-writer ledger, so a continuation writer sees the sibling's prefix — SecondWriterContinuesFromCommittedFrontier asserted the opposite and now asserts the completed cell.
  • Dropped this branch's duplicate reader_executor_window_size settings-history entry: master records the same 4 MiB → 8 MiB change in the same 26.9 block.

3. Review findings (5535501a) — the "minimum required actions" that do not need a design call from you:

  • FileCache per-query accounting. QueryContext::add returns nothing, so the inserted record was unreachable: never sized on the success path, and undroppable on either rollback. It is read back under the same lock; both rollbacks now undo exactly this reservation (remove the record it inserted, or give back only the size it added to a pre-existing one). Removed rather than invalidated, because the context keys records by key and offset and would hand an invalidated one back.
  • Local-read parity. LocalSourceReader carries read_hint, and no longer passes StoredObject::UnknownSize as a concrete file_size (the sentinel is huge and made every stat-failed read a direct-IO one).
  • Local prefetch. DiskLocal::prepareRead attaches the prefetch pool under the same gate the remote path uses (pread_threadpool + local_filesystem_read_prefetch), so the setting stops being a no-op on the executor path. This is the pass's one behaviour change that touches every local MergeTree read — worth an eye on the fresh CI run.
  • Unknown-size objects skip the disk cache as they already skip the page cache: streaming until EOF has no length to bound segments with.
  • Prefetch accounting. The bytes a reused long connection discards to bridge a cached gap are counted into ReaderExecutorPrefetchIssuedSourceBytes, so a discarded prefetch reports the bandwidth it really cost.
  • Non-Silk builds warn when disk_connections_use_silk is turned on by a reload; the boot warning only covered it being on at startup.
  • Changelog entry corrected: it promised a system.remote_read_connections table that the code does not register. (The body's "Observability" prose still lists that table — left for you, since it reads as a roadmap item rather than a claim about this diff.)

Three findings from the verdict are deliberately not acted on:

  • mergeRanges coalescing across a small sibling-owned hole — this looks intended, not a defect: the comment right above says holes below min_bytes_for_seek are bridged because reading through is cheaper than reopening, writes stay gated by the roles (nothing lands in the sibling's cell), and the bridged bytes are the same file bytes the sibling would commit. Re-reading a few KiB is the price of not breaking the connection.
  • filesystem_cache_log / filesystem_read_prefetches_log rows on the executor path — a real gap, but threading the sinks through the executor (or rejecting the settings when it is selected) is your architecture call.
  • 04331:76 and test_reader_executor_metric/test.py:410 — both need minio, which I cannot run here; tightening an inequality I cannot verify would only risk adding a flake.

Verified locally (aarch64 release): ninja clickhouse unit_tests_dbms green (0 errors); 301 gtests pass across *ReaderExecutor*, *ReadPipeline*, *CacheBuffers*, *Residency*, *MemoryPressure*, FileCacheTest*, *Silk*/*Fiber*; check_style.py clean; and a clickhouse local smoke check agrees across use_reader_executor 0/1, with long connections, with pread_threadpool + local prefetch, and at a 128 KiB window. Still a draft — nothing merged.

qid = str(uuid.uuid4())
node.query(query, query_id=qid, settings=_pc_settings(use_long_conn, extra) if pc else _settings(use_long_conn, extra))
node.query("SYSTEM FLUSH LOGS")
extra = ["ReaderExecutorModeledCostMicroseconds", "ReaderExecutorRequestedBytes"]

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.

_measure is selecting the wrong counter here. The current implementation emits ReaderExecutorDeliveredBytes (src/Common/ProfileEvents.cpp / src/IO/ReaderExecutorStats.cpp), not ReaderExecutorRequestedBytes.

On system.query_log, an unknown ProfileEvents[...] key reads back as 0, so _cost_per_mib below collapses to zero and the fixed-small-vs-variable assertions stop proving anything about the cost-per-byte KPI. Please switch this test to ReaderExecutorDeliveredBytes, which is the denominator the production metric actually exposes.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Fixed in 178355a56836: _measure now reads ReaderExecutorDeliveredBytes (stored as Delivered), and _cost_per_mib divides by it, so the cost-per-MiB KPI and the fixed-small-vs-variable comparison are no longer vacuous.

Comment thread src/IO/ReaderExecutor.cpp Outdated
/// drain - this is reachable from the noexcept destructor. No longer LENT: the lane
/// may open a fresh one.
stats += m->stats;
stats.add(Stats::PrefetchWastedSourceBytes, m->stats.get(Stats::PrefetchIssuedSourceBytes));

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.

ReaderExecutorPrefetchWastedSourceBytes is documented as real wasted bandwidth and explicitly says it excludes cache puts that already persisted in the same window, but this line still charges the cancelled machine's entire PrefetchIssuedSourceBytes.

That overstates the wasted-bandwidth metric whenever the running prefetch had already committed earlier tiles via pushChainToWriters: those bytes remain reusable from cache and are not actually discarded. Please charge only the source bytes from the uncommitted residue, or otherwise subtract the tiles that were already accepted by a cache writer before cancellation.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Fixed in 178355a56836: cancelMachine now charges PrefetchWastedSourceBytes with issued - min(issued, persisted), where persisted is the cancelled machine's own BytesPushedToCacheSync (what pushChainToWriters committed per tile). Tiles already accepted by a cache writer stay reusable and are no longer counted as discarded bandwidth, matching the counter's description.

alexey-milovidov and others added 4 commits September 16, 2026 20:00
# Conflicts:
#	src/Core/SettingsChangesHistory.cpp
#	src/IO/ReadPipeline.h
#	src/IO/tests/gtest_read_pipeline.cpp
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
…tidy

`Build (arm_tidy)` failed on the previous head with
`readability-duplicate-include` in `programs/server/Server.cpp` and
`src/Core/ServerSettings.cpp`: the 2026-09-08 master merge brought a
second `#include <Common/MemoryPressureMonitor.h>` into both files while
the branch already had one in sorted position. Keep the first copy.

CI: https://github.com/ClickHouse/ClickHouse/actions/runs/34248611479/job/102138170336
PR: #103706

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Master now requires every `SystemLog` element to declare the common
`clickhouse_version` and `system_processor` columns (`SystemLog.cpp`
throws `LOGICAL_ERROR` at construction otherwise). `system.reader_executor_log`
is the only log this branch adds, and it did not declare them, so a server
with `reader_executor_log` configured (as the stateless test config does)
failed to load its metadata after the master merge. Add both columns and
their inserts, mirroring `FilesystemCacheLog`.

Verified: server starts, `SYSTEM FLUSH LOGS reader_executor_log` produces
rows with both columns populated.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… prefetch accounting, test strength

Implements the blocking and major items of the AI review on the previous head.

- `Server.cpp`: the merged-view check of the memory-pressure threshold triple
  runs after `config().replace`, so a failed `SYSTEM RELOAD CONFIG` (file valid
  alone, merge with a command-line override out of order) kept publishing the
  rejected values through `config()` and `system.server_settings`. Keep the
  previous `default` layer (`LayeredConfiguration::find`) and put it back when
  the merged view is rejected, before rethrowing. Verified with a live server
  started with `--reader_executor_memory_pressure_high_level_pct=80`: a reload
  setting `elevated=85` is rejected and `system.server_settings` keeps 75; a
  following valid reload applies.
- `DiskLocal::prepareRead`: attach the executor prefetch pool for both
  prefetch-capable local methods (`pread_threadpool` and `pread_fake_async`,
  the set `MergeTreePrefetchedReadPool::checkReadMethodAllowed` accepts), so
  `local_filesystem_read_prefetch = 1` is no longer a silent no-op under
  `pread_fake_async` with `use_reader_executor = 1`.
- `ReaderExecutor::cancelMachine`: `ReaderExecutorPrefetchWastedSourceBytes`
  now charges only the issued bytes the cancelled worker did not already commit
  into cache writers (its `BytesPushedToCacheSync`), as the counter's own
  description promises.
- `ReaderExecutorPrefetchInFlight`: describe what the gauge measures (machine
  lifetime, including completed-but-uncollected read-ahead).
- `test_reader_executor_metric`: `_measure` read a non-existent
  `ReaderExecutorRequestedBytes` (always 0), which made the cost-per-MiB KPI
  vacuous; switch to `ReaderExecutorDeliveredBytes`. `test_page_cache_path`
  now also asserts every warm sample issued bytes from the page-cache tier
  (`ReaderExecutorBytesFromPageCache`), not only fewer source requests.
- `04331_reader_executor_s3_read_introspection`: assert the contract the test
  comment states for the warm scan directly: zero `bytes_from_source` and zero
  `source_requests`.

Not changed, with reasons on the threads: the per-query `FileCache` charging
gate is identical to master and is being fixed in
#114165.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Kept the branch current and worked through the AI review's blocking list again. Pushed four commits, head 178355a56836.

1. master merge (d675c895). Single merge base, 4 conflicts: SettingsChangesHistory.cpp (union; the file stays a pure addition over master), ReadPipeline.h (master's cached getReadPipelineLogger plus the branch's comment), gtest_read_pipeline.cpp (master and the branch both added a boundRecordingCreator; kept master's TestReadBuffer-based one and renamed the branch's right-bounded variant to rightBoundedRecordingCreator, used by NonLiveSourceReadIsRightBounded), ReadFromMergeTree.cpp (extern union).

2. 6a714ef6 - Build (arm_tidy) was red on the previous head: readability-duplicate-include for Common/MemoryPressureMonitor.h in Server.cpp and ServerSettings.cpp, left by the previous master merge. Removed the second copies; swept every changed source for other duplicates (none).

3. a1e37c94 - merge regression: master now requires every SystemLog to declare clickhouse_version and system_processor, and system.reader_executor_log (the one log this branch adds) did not, so a server with reader_executor_log configured (the stateless test config) failed to load metadata after the merge. Added both columns, mirroring FilesystemCacheLog; verified rows are produced with them populated.

4. 178355a5 - review items (replies on each thread):

  • Blocker, Server.cpp: a rejected merged-view threshold triple no longer stays published through config() / system.server_settings - the previous default layer is restored before rethrowing. Verified live with a command-line override plus a file reload that is valid alone but out of order when merged.
  • Major, DiskLocal.cpp: the executor prefetch pool is attached for pread_fake_async as well as pread_threadpool, so local_filesystem_read_prefetch = 1 is honoured on both local async methods.
  • Major, ReaderExecutor.cpp: PrefetchWastedSourceBytes of a cancelled running prefetch excludes the bytes it already committed to cache writers.
  • Major, ReaderExecutorPrefetchInFlight: description now says the gauge spans the machine lifetime, including completed-but-uncollected read-ahead.
  • Tests: test_reader_executor_metric reads the real ReaderExecutorDeliveredBytes (the KPI was dividing by a non-existent counter) and asserts warm page-cache reads issue bytes from the page-cache tier; 04331 asserts zero bytes_from_source / source_requests on the warm scan.

Not changed: the FileCache per-query charging gate is identical to master's and is being fixed in #114165 (reasoning on the thread). The findings already dismissed by the author (mergeRanges sibling holes, filesystem_cache_log / filesystem_read_prefetches_log sinks, the PR-body observability section) are left as they are.

Verified locally: incremental ninja clickhouse unit_tests_dbms green; 281 ReaderExecutor / ReadPipeline / FetchMachine / FileCacheTest / DiskCache gtests pass; 04316/04327/04328/04335/04604 pass against a scratch server; clickhouse local results agree across use_reader_executor 0/1 for pread, pread_fake_async, pread_threadpool with prefetch on. The S3 / MinIO tests (04331, test_reader_executor_metric) could not be run here - please watch them in the fresh CI run.

alexey-milovidov and others added 3 commits September 23, 2026 15:49
Conflict resolution:
- `SystemLog.h`: master moved system log descriptions into `SYSTEM_LOG_DOCUMENTATION_*` constants;
  added `SYSTEM_LOG_DOCUMENTATION_READER_EXECUTOR_LOG` for `system.reader_executor_log`.
- `MergeTreeReaderWide`: master turned the streams map into the mutex-guarded `FileStreams` class;
  `updatePlannedLastMark` / `updateRequestMap` now iterate through the new `FileStreams::forEach`.
- `ReadPipeline`: kept the executor early return, added master's `interruptible_reads` query status
  plumbing into `buildGatherStage` and its executor fallback; the unknown-size fallback stays removed
  as on the branch.
- `DatabaseOrdinary.cpp`, `02242_system_filesystem_cache_log_table.sh`: took master.
- `.gitignore`: kept both additions.

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

The `settings_changes_history` style check requires every record this PR adds to sit in the
current version block; master bumped to `26.10`, so the records added in the `26.9` blocks of
`getSettingsChangesHistory` and `getMergeTreeSettingsChangesHistory` are moved there. Also drop the
duplicate `Interpreters/Context.h` include in `ReadPipeline.cpp` left by the master merge.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=103706&sha=178355a568363312d1b10cf197199c853f5c79a9&name_0=PR&name_1=Style%20check
PR: #103706

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`MergeTreeReaderStreamSingleColumn::getLeftOffset` loaded the marks of every stream to convert the
planned mark ranges into file offsets, including streams whose data file is empty (for example, the
`SharedVariant` streams of `JSON` paths with a single type). All marks of an empty file point to its
beginning, so return 0 without loading them, as `getRightOffset` does. This broke
`05109_json_empty_streams_marks_not_loaded` (34 marks files loaded instead of 22) on both the legacy
and the `ReaderExecutor` path.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=103706&sha=178355a568363312d1b10cf197199c853f5c79a9&name_0=PR&name_1=Fast%20test
PR: #103706

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

Copy link
Copy Markdown
Member

🕵 Merged master again and fixed both reds of the previous head (178355a5). New head is efa6e0a922ba.

  • Merge (8be4fbea109c): 8 conflicts.
    • SystemLog.h: master moved the log descriptions into SYSTEM_LOG_DOCUMENTATION_* constants, so I added SYSTEM_LOG_DOCUMENTATION_READER_EXECUTOR_LOG.
    • MergeTreeReaderWide: master turned the streams map into the mutex-guarded FileStreams class. updatePlannedLastMark and updateRequestMap now go through a new FileStreams::forEach.
    • ReadPipeline: the executor early return is kept. Master's interruptible_reads query_status plumbing is added to buildGatherStage, together with its executor fallback. The unknown-size fallback stays removed, as on the branch.
    • The rest were trivial.
  • Style check settings_changes_history (8ede859ec2c9): master is now 26.10, so the 9 records this PR adds moved from the 26.9 blocks to 26.10. I verified this locally with the hook parser.
  • Fast test 05109_json_empty_streams_marks_not_loaded (efa6e0a922ba): the red was caused by this PR. MergeTreeReaderStreamSingleColumn::getLeftOffset loaded marks for empty data files in order to build the request map (34 marks files loaded instead of 22), on both the legacy and the executor path. It now returns 0 for an empty file without loading marks, as getRightOffset does.

ninja clickhouse builds. Against a scratch server with reader_executor_log.xml, the server starts, and 05109, 04335, 02263, 03310, 01475* and 02703 pass with both use_reader_executor = 0 and 1. Results agree for pread, pread_fake_async and pread_threadpool with prefetch on. I could not run the S3-backed executor tests (04327, 04330, 04331, 04334, ...) locally: they need the CI storage policies.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-io IO library: ReadBuffer / WriteBuffer and their implementations over files and memory, read and wr... pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants