Skip to content

Bound filesystem prefetches by a shared per-read-step budget - #114072

Closed
groeneai wants to merge 25 commits into
ClickHouse:masterfrom
groeneai:groeneai/respect-filesystem-prefetches-limit-json-substreams
Closed

groeneai wants to merge 25 commits into
ClickHouse:masterfrom
groeneai:groeneai/respect-filesystem-prefetches-limit-json-substreams

Conversation

@groeneai

@groeneai groeneai commented Aug 9, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #113380

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed filesystem_prefetches_limit and filesystem_prefetch_max_memory_usage not bounding the read buffers that filesystem prefetches hold. Reading a JSON column from a Wide part on remote storage allocated one prefetch buffer per substream per reader, unbounded, so a query over a single such column could fail with MEMORY_LIMIT_EXCEEDED at default settings. Both now bound the prefetch buffers alive at one moment within a read step, counted per prefetched substream. Three behaviour changes follow at unchanged defaults: a read of more columns than filesystem_prefetches_limit prefetches its first N substreams rather than nothing; a read below the limit in columns but above it in substreams stops prefetching partway, in block column order (150 Nullable columns are 300 substreams against a limit of 200); and filesystem_prefetch_max_memory_usage now also applies without the prefetched read pool.

Description

Both settings were enforced in units that do not consume the memory. Pool admission counts required_readers_num, incremented once per column, and MergeTreeReaderWide compared it against num_columns, while each prefetched substream allocates its own buffer. One JSON column is 1 by both measures, while one reader of it prefetched 42 substreams here. The two also compose: the pool admits up to the limit, and each admitted reader may prefetch up to it again. Measured on master, a read step with four concurrent readers of 150 Nullable(UInt64) columns holds 1200 prefetch buffers at a limit of 200.

This adds one count-and-bytes budget per read step, created in createForQuery and shared by every reader of the step. It is charged once per prefetch buffer at the two buf->prefetch() sites and released when that buffer is destroyed, which is when the memory is returned; a refusal falls back to a synchronous read. Counting substreams rather than columns is a deliberate call: it is the unit the setting documents, and the second behaviour change above is its cost.

Provenance: Stateless tests (amd_debug, distributed plan, s3 storage, parallel) on #112918 @ 13a6b631b995b64, where 04675_cancelled_json_prefix_read_does_not_report_broken_part died with Code: 241 ... would use 4.66 GiB ... MergeTreeSelect(pool: ReadPool).

04841 covers both bounds over both read pools, on remote, encrypted and packed storage; 03394's reference records the visible change, its two data_wide limit-5 rows going 0 to 5.

One over-count is deliberate: a stream whose prefetch() no-ops keeps its reservation until it dies, so at most one unallocated buffer per stream is charged.


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

groeneai and others added 3 commits August 9, 2026 14:25
filesystem_prefetches_limit is documented as the maximum number of prefetches, but
MergeTreeReaderWide::prefetchForAllColumns compared it against num_columns, the number
of columns in the block. The prefetches are issued per substream: prefetchForColumn's
enumerateStreams callback calls buf->prefetch() for each one, each call resizes that
stream's own read buffer, and those buffers live in the reader's streams map for the
reader's lifetime.

A JSON/Object column expands into arbitrarily many substreams through
SerializationObject -> SerializationDynamic -> SerializationVariant, which recurses per
variant discriminator. Reading one such column therefore allocates one live buffer per
substream while the admission test compares the limit against 1, so the guard cannot
fire at any non-zero limit. The plain read pool consults no
filesystem_prefetch_max_memory_usage budget either (that setting is read in
MergeTreePrefetchedReadPool only), so nothing bounded the fan-out and the query could
fail with MEMORY_LIMIT_EXCEEDED. Observed in CI on Stateless tests (amd_debug,
distributed plan, s3 storage, parallel), where SELECT count() FROM t_wide WHERE
length(JSONAllPaths(j)) > 0 needed 4.66 GiB of 1.25 MiB read buffers while running with
filesystem_prefetches_limit = 10.

Count the prefetches actually issued and stop at the limit, at both issuance sites: the
data path in prefetchForColumn and the structure-prefix path in
deserializePrefixForAllColumnsWithPrefetch. Those are the only two ->prefetch() sites
under src/Storages/MergeTree. Compact-part readers do not go through
prefetchForAllColumns, and MergeTreePrefetchedReadPool already bounds by both count and
memory, so neither changes.

The counter is a reader member reset at the three sites that clear prefetched_streams,
so its lifetime tracks the set of live buffers: prefetchBeginOfRange followed by a
same-mark readRows share one budget instead of spending it twice against buffers that
are all still owned by streams. It is deliberately not decremented on the
prefetched_streams.erase paths, where a stream is re-prefetched from a later mark after
prefix deserialization, because the erased stream's buffer stays allocated; refunding
there would reintroduce the unbounded shape. The existing column-count early-out is
kept, so this can only ever issue fewer prefetches than before rather than newly
allowing partial prefetching in the many-columns case.

Because the cap sits at the single issuance point inside the substream callback, below
every enumerateStreams recursion, it is wrapper-agnostic: Nullable(JSON), Array(JSON)
and Map(String, JSON) are bounded by construction rather than by a type predicate that
would have to strip each wrapper.

A skipped prefetch is a synchronous read later, never a failure, and results are
unchanged. Zero still means unlimited and the default of 200 is untouched, so no
SettingsChangesHistory entry is needed.

Co-Authored-By: Claude Fable 5 <[email protected]>
The regression test asserted a query-level bound, RemoteFSPrefetches <= limit, but the counter
being tested is a reader member reset wherever prefetched_streams is cleared. The invariant the
code establishes is therefore per reader per prefetch epoch, and the query-level form only held
because the fixture happened to collapse to a single epoch and a single reader. Nothing pinned
that: index_granularity was absent from the CREATE, so the runner injected it from
random.randint(1, 65536), floored to 100 only on slow builds. On a release stateless job a
granularity of 1 turns the 100-row table into ~100 marks, the budget is spent once per epoch, and
a correct build goes red. Measured: 7 prefetches against a limit of 5 on an index_granularity = 1
table, 9 on the Array(JSON) row.

Pin index_granularity in the CREATE and clamp the randomizer with a Random settings limits line so
neither path can shrink it, and pin the per-query settings that could add a second reader or a
second epoch. Then assert equality rather than <=. The <= form was also satisfiable by zero: had a
change disabled prefetching outright for non-zero limits, all three capped rows would still have
passed, since the limit = 0 control only witnesses fan-out in the unlimited configuration.
Equality witnesses enforcement and liveness at once, and it is only assertable once the fixture is
pinned, which is why both go together.

The Array(JSON) row measured nothing. It queried length(ja), which optimizeFunctionLength rewrites
to ja.size0, so only the array-offset stream was read and the nested JSON substreams the row
claimed to cover were never touched: one prefetch against a limit of five, an arm with no headroom
whose pass was vacuous. It now reads a path out of the array elements, which issues 123 prefetches
unbounded, and optimize_functions_to_subcolumns is pinned so the arm cannot change meaning when
the randomizer flips it.

Co-Authored-By: Claude Fable 5 <[email protected]>
…h-count test

The test asserts an exact per-reader prefetch count, so every input that can
change the number of read epochs or the number of readers has to be pinned.

index_granularity is only an upper bound on rows per granule: adaptive
granularity is the default and derives the actual value from
index_granularity_bytes, which the runner randomizes independently between 1 KiB
and 30 MiB. At 1 KiB the 100-row fixture is cut into 101 one-row granules, the
per-epoch prefetch budget is spent once per epoch, and the equality assertions
observe 7, 12 and 9 instead of 5, 10 and 5 on correct code. Pinning the byte
granularity in the CREATE and clamping it in the random-settings limits keeps the
fixture in a single granule.

The asserted count is also per MergeTreeReaderWide, and each replica has its own,
while query_log's ProfileEvents column only records the local thread group -
remote replicas' events are forwarded to the client-facing queue instead. The
no-parallel-replicas tag excludes the test from the job that enables parallel
replicas, matching what 03394_filesystem_prefetches_limit already does for the
same setting. The query_log lookups additionally filter is_initial_query, since
replica queries carry the same log_comment.

The JSON serialization layout was measured rather than pinned: across all values
of the object, shared-data, dynamic, string and nullable serialization settings,
individually and combined, the fixture never exposed fewer than 42 prefetchable
substreams against a largest asserted limit of 10, so pinning a layout would only
narrow coverage.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds, all findings resolved)

An independent reviewer and a second model reviewed this change cold across three rounds before it
was published. The C++ was settled in round 0 and untouched since; rounds 1 and 2 were test-only.

# Finding Verdict
❌ The oracle was RemoteFSPrefetches <= limit, which zero satisfies, so a capped row could pass without witnessing enforcement. Fixed: the oracle now asserts equality on a fixture pinned to one read epoch, plus a limit = 0 control asserting > 10.
❌ The Array(JSON) row used length(ja), which optimizeFunctionLength rewrites to ja.size0, so it read only the offsets stream and measured 1 prefetch. Fixed: it now reads a path out of the array elements. Unbounded count on that arm is 83-124 against an asserted 5.
❌ An exact-count oracle needs every granularity input pinned; only index_granularity was. index_granularity_bytes is randomized independently and adaptive granularity derives rows-per-granule from bytes, so a low value cut the fixture into ~100 one-granule epochs and produced 7/12/9 where 5/10/5 is asserted. Fixed: index_granularity_bytes pinned in the CREATE and clamped. The mutation arm reproduces 7/12/9 without the pin and 5/10/5 with it at the same injected value, so the two arms are distinguishable and the probe is not vacuous.
❌ The count is per reader, but the test carried no no-parallel-replicas tag, so it would run in a job whose profile enables parallel replicas, where each replica has its own reader and query_log only records the initiator's local events. Fixed: tag added (verified it actually skips the test under --no-parallel-replicas), and is_initial_query added to both query_log lookups. Each arm still matches exactly one row, so the filter did not make the oracle vacuous.
⚠️ Equality also requires the fixture to expose at least limit prefetchable substreams, and five randomized serialization settings decide how many JSON paths collapse into shared streams. Unmeasured in either direction. Measured rather than assumed: 21 per-setting arms plus 12 combined arms (both extreme corners and 10 pseudo-random draws over eight settings). Worst unbounded counts are 42 and 83 against asserted 10 and 5, i.e. 4.2x headroom on the tightest row. Nothing pinned - pinning a serialization version would narrow layout coverage for no gain.
💡 The regression test measures the data-path issuance site. The structure-prefix site is unreachable on a single-granule fixture, because the first prefetch pass spends the budget before prefix deserialization runs, so its cap is covered by construction (same predicate, same increment) rather than by measurement. Noted, not blocking. Reaching it would need the multi-epoch fixture that was deliberately removed to make the oracle exact.

Validation on the final tree: the three capped rows and the unlimited control pass on the fixed
binary and the test fails on the unfixed one on exactly those three rows; --test-runs 50 is 50/50
and an 18-run parallel arm is 18/18; both prefetch issuance sites are capped and the counter resets
exactly where the reader clears its prefetched-stream set. The final review round returned no
findings.

Session id: cron:clickhouse-review-slot-9:20260809-200002

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One JSON column in a Wide part on a local_blob_storage disk, SELECT count() FROM t WHERE length(JSONAllPaths(j)) > 0 SETTINGS filesystem_prefetches_limit = 10, remote_filesystem_read_prefetch = 1, remote_filesystem_read_method = 'threadpool', then read ProfileEvents['RemoteFSPrefetches'] from system.query_log. Reports far more prefetches than the limit on every run (122 on the wider probe table, 42 on the smaller test fixture, against a limit of 10), not a low-rate flake.
b Root cause explained? prefetchForAllColumns gates prefetching on num_columns > filesystem_prefetches_limit, a COLUMN count, while prefetchForColumn's enumerateStreams callback issues one buf->prefetch() per SUBSTREAM, each resizing a read buffer that then lives in the reader's streams map. SerializationObject -> SerializationDynamic -> SerializationVariant expands one JSON column into arbitrarily many substreams, so with one column the guard compares against 1 and cannot fire at any non-zero limit. The plain read pool has no filesystem_prefetch_max_memory_usage budget either, so nothing bounds the fan-out.
c Fix matches root cause? Yes. The setting is enforced against the quantity it documents ("Maximum number of prefetches"), at the exact site that issues them. No widened bound, no no-random-* tag, no dataset reduction, no guard at the allocation site.
d Test intent preserved / new tests added? No existing test weakened or removed. New regression test 04841_json_prefetch_count_respects_limit.sh asserts the prefetch count is exactly the requested limit (not merely <=, which zero would also satisfy), on a fixture pinned to a single read epoch: BOTH index_granularity and index_granularity_bytes pinned in CREATE and clamped with # Random settings limits: index_granularity=(8192, None); index_granularity_bytes=(33554432, None) (rows per granule are derived from the BYTE granularity under adaptive granularity, which is the default), prewhere and subcolumn optimizations pinned off, no-parallel-replicas tagged because the asserted count is per reader and query_log records only the local thread group, and the query_log lookups filter is_initial_query. A limit = 0 control proves the test observes the setting rather than measuring a naturally small number.
e Both directions demonstrated? Yes, same runner invocation per arm, Build IDs asserted via SELECT lower(buildId()). Base eb4b3ece5365b485: [ FAIL ], the three equality assertions flip 1 -> 0 while the unlimited control stays 1. Fix 3ecee8823ced0135: [ OK ], and --test-runs 50 is 50/50 with randomization on. Counts per reader epoch: limit 5 -> 42 vs 5, limit 10 -> 42 vs 10, Array(JSON) at limit 5 -> 123 vs 5. Query results identical in both arms.
f Fix is general across code paths? Both ->prefetch( sites under src/Storages/MergeTree/ are capped (structure-prefix path and data path); grep -rn -- "->prefetch(" src/Storages/MergeTree/ confirms these are the only two. Compact readers do not go through prefetchForAllColumns (0 prefetch hits in MergeTreeReaderCompact*). MergeTreePrefetchedReadPool left untouched: it already bounds by count and by memory. Fixed at the source, not at the crash site.
g Fix generalizes across inputs (params/datatypes/wrappers)? The cap sits at the single issuance point inside the substream callback, below every enumerateStreams recursion, so it is wrapper-agnostic by construction (deliberately the layer that avoids the removeNullable-but-not-LowCardinality miss of #105384 / #107868). Both the Nullable(JSON) and Array(JSON) arms in the test read the nested JSON substreams and are bounded exactly (unbounded: 42 and 123 respectively; at limit 5 both give exactly 5). Limits 0, 5 and 10 all behave per contract. The count also holds at exactly the limit across 21 individually forced randomized query settings (read method, page cache, filesystem cache, max_block_size, direct/mmap IO, prefetch step marks/bytes, range-split injection, query condition cache, lazy materialization), and across a further 21 forced MergeTree serialization-layout arms plus 12 combined ones (all values of object_serialization_version, object_shared_data_serialization_version, its zero-level-part twin, object_shared_data_buckets_for_wide_part, dynamic_serialization_version, serialization_info_version, string_serialization_version, nullable_serialization_version): the fixture's unbounded substream count never fell below 42 for Nullable(JSON) or 83 for Array(JSON), against asserted limits of 10 and 5.
h Backward compatible? Yes. No default changed (filesystem_prefetches_limit stays 200), no format or serialization change, so no SettingsChangesHistory.cpp entry is needed. 0 still means unlimited, so the previous unbounded behaviour remains available explicitly.
i Invariants and contracts preserved? The counter is a plain size_t member incremented only immediately after a successful buf->prefetch(), so no early return or throw can leave it stale in a way that RAISES the bound; the only failure direction is under-prefetching, which is a synchronous read later and never a wrong result. It is reset at exactly the three sites that clear prefetched_streams, so its lifetime tracks the live buffer set, and deliberately NOT decremented on the prefetched_streams.erase paths, since an erased stream's buffer stays allocated. The existing catch in prefetchForAllColumns is untouched. No on-disk state, so no crash or restart re-entry obligation.

Session id: cron:clickhouse-impl-slot-7:20260809-185000

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @Avogar, could you review this? filesystem_prefetches_limit was compared against the block's COLUMN count in MergeTreeReaderWide::prefetchForAllColumns, but prefetches are issued per SUBSTREAM, so one JSON column (which expands through Object -> Dynamic -> Variant) allocated one live read buffer per substream while the guard compared the limit against 1 and could never fire. I now count the prefetches actually issued and stop at the limit, at both issuance sites.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [facbff2]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Logical error: Got read request from replica A for unknown stream B. (STID: 5217-5b3d) FAIL cidb, issue

AI Review

Summary

This PR changes filesystem_prefetches_limit / filesystem_prefetch_max_memory_usage from per-column heuristics to a shared per-read-step budget, wires byte accounting through the relevant ReadBuffer wrapper chains, and gives lazy materialization its own budgeted read step. After reviewing the current diff, the existing discussion, and the updated tests, I did not find a remaining correctness, safety, or evidence gap in the changed paths.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit facbff2.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 114/119 (95.80%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 9, 2026
The style check requires every test reading system.query_log to carry a
current_database = currentDatabase() condition. It greps for that literal
(or the unbraced $CLICKHOUSE_DATABASE), so the '${CLICKHOUSE_DATABASE}'
form the two lookups used did not satisfy any of its four alternatives.

The predicate is equivalent: CLICKHOUSE_CLIENT already runs with
--database=$CLICKHOUSE_DATABASE, so currentDatabase() is that database.
Re-verified the oracle still matches exactly one row per arm with the
same counts, so the stricter spelling did not turn it vacuous.
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Style check was red on the new test: it reads system.query_log and the checker requires a
current_database = currentDatabase() condition. The lookups used '${CLICKHOUSE_DATABASE}',
which matches none of the checker's four accepted spellings (it greps for the literal
currentDatabase, or the unbraced $CLICKHOUSE_DATABASE).

Fixed in 078ad9b - 2 lines, test only, no source change. The predicate is equivalent
because CLICKHOUSE_CLIENT already runs with --database=$CLICKHOUSE_DATABASE.

A stricter WHERE can silently make an oracle match zero rows and go green for the wrong
reason, so I re-checked non-vacuity rather than just re-running: each of the four arms still
matches exactly one initial-query row, with the same counts as before (5 / 10 / 5, unlimited 42).
A negative control confirms the predicate discriminates - the same log_comment issued from a
second database gives 2 rows globally and 1 through the test's scoped lookup.

Both directions re-established through the runner on this head: fixed build [ OK ], pre-fix
build [ FAIL ] on exactly the three equality rows (printing 0, not empty) with the unlimited
control still 1. --test-runs 50 50/50, -j 6 --test-runs 18 18/18, shellcheck unchanged.

Finish Workflow / Post Hooks was downstream of this gate - all five Bugfix validation jobs
were dropped or skipped when the workflow was cut short (169 of 175 checks skipped), so there is
nothing else outstanding for the previous head and no ledger was owed for it.

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing facbff253 with master 592da49d0 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

556 object files changed (+256.92 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreePrefetchBudget.cpp.o new 21.46 KiB +21.46 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

3032 translation units recompiled, 15406 s compile time in total, 3031 of them have a recent master baseline.

Job report

…it-json-substreams

Conflict in MergeTreeReaderWide::prefetchForColumn's substream callback: master
added a substream-relevance filter at the same spot this branch added the
prefetch-budget gate. Both are side-effect-free early returns, so both are kept;
the relevance filter stays next to the sibling ephemeral-subcolumn check it
belongs with, and the budget gate follows it, so a substream that is never
prefetched no longer consumes budget.
@Avogar Avogar self-assigned this Aug 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 08c0cd1

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Logical error: Context has expired (STID 1805-460a) trunk bug: CastOverloadResolverImpl::buildImpl consults the query context while building a CAST, and the context is already gone. Aborts at CastOverloadResolver.cpp:195 via WithContextImpl::getContext. New signature with onset 2026-08-13, breadth 22 rows / 17 distinct PRs / 0 master in 30 days. #114769 (ours, open)
Stress test (arm_tsan) / Hung check failed, possible deadlock found trunk bug: a cancelled INSERT ran 426 s inside QueryPlan::optimize. The lldb backtrace shows optimizeTreeSecondPass / materializeQueryPlanReferences / cloneSubplanAndReplace over a plan whose node list holds 1,670,597 entries, with each ReadFromSystemNumbersStep::clone() re-resolving the LIMIT through the full analyzer. is_cancelled: 1, read_rows: 0, so cancellation is observed nowhere on that path. a fix task is created (investigating at full effort, fixing PR link to follow on this PR)

Neither is PR-caused. This PR limits JSON-substream prefetching in MergeTreeReaderWide plus its
own new test; it touches nothing under src/Functions/ or src/Processors/QueryPlan/, and the
hung query has no JSON column and no prefetch.

Session id: cron:our-pr-ci-monitor:20260814-200000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_tsan) hung check on my CI finish ledger above: #114938. Sibling correlated subqueries in one expression each referenced the input subplan root as it stood during their own iteration, so materializeQueryPlanReferences cloned each referenced root together with the references nested inside it and the plan node count doubled per sibling, which is what produced the 1,670,597-node plan.

@groeneai groeneai added the groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@Avogar

Avogar commented Sep 9, 2026

Copy link
Copy Markdown
Member

I dug into this. The direction is right — the limit does have to be enforced where prefetches are actually issued — but the per-reader counter doesn't compose with the pool's budget, so the failure this fixes still reproduces with default settings, and there's a unit change here that I think deserves an explicit decision rather than being inherited.

Where the limit is checked today

Two places, in two different units, covering two disjoint sets of read paths.

  1. MergeTreePrefetchedReadPool::fillPerThreadTasks — a running global budget for the whole read step, initialized at MergeTreePrefetchedReadPool.cpp:540 and spent per task at MergeTreePrefetchedReadPool.cpp:634-646, side by side with the filesystem_prefetch_max_memory_usage budget. The unit it is spent in is part_stat.required_readers_num, which update_stat_for_column increments once per column (MergeTreePrefetchedReadPool.cpp:443-456). Note it is a whole-task admission test, not a cap: a task either gets a prefetching reader or it gets none. That is why the reader never needed a counter.

  2. MergeTreeReaderWide::prefetchForAllColumns — the num_columns > filesystem_prefetches_limit early-out at MergeTreeReaderWide.cpp:120. This exists because prefetchForAllColumns runs from readRows for every pool, not only the prefetched one, so the pool's budget covers only part of the prefetching that happens. It was added in Always apply filesystem_prefetches_limit #83999: "Previously it was applied only from MergeTreePrefetchedReadPool ... now it will be respected for all reads." With no counter available in the reader, the column count was the only proxy at hand.

So 200 was never really a column limit — in the pool it already means "number of read buffers", and required_readers_num is one-per-column only because the pool assumes one buffer per column. Counting substreams is the documented unit and matches that intent. The problems are elsewhere.

The per-reader cap does not compose with the pool's admission

startPrefetches creates readers and fires prefetchBeginOfRange for every admitted task at once (MergeTreePrefetchedReadPool.cpp:222-250). With one JSON column per task, required_readers_num == 1, so at the default the pool admits ~200 tasks, and with this patch each of their readers may issue up to 200 prefetches. The effective bound becomes limit × limit.

For the case in the description: at filesystem_prefetches_limit = 10 the fix works because 10 tasks × 10 prefetches = 100 buffers. At the default 200 the same query gets ~200 tasks × 122 substreams ≈ 24k buffers, and the new cap never even fires, since 122 < 200. The patch doesn't make that worse, but the OOM it targets is still reachable with default settings — the test passes only because it pins the limit low.

filesystem_prefetch_max_memory_usage can't cover for this either

Worth stating explicitly, since the setting's own doc recommends the memory budget over the count: as implemented it is broken in exactly the same way. estimated_memory_usage_for_single_prefetch is accumulated once per column as min(column_compressed_size, prefetch_buffer_size) (MergeTreePrefetchedReadPool.cpp:455), so a JSON column is accounted as ~1 MiB while the reader allocates one ~1 MiB buffer per substream — ~122 MiB by your own measurement. And it lives only in the pool's admission loop, so it does not apply on the readRows -> prefetchForAllColumns path at all.

The unit change is a silent behavior change for non-JSON reads

Substream counts are 2-3x column counts for Nullable/Array/Map/Tuple. A read of 150 Nullable columns prefetches fully today (150 < 200) and would stop after 200 substreams with this patch — and which columns lose prefetching is arbitrary: block column order, with the prefix substreams from deserializePrefixForAllColumnsWithPrefetch consuming the budget before any data substream gets a chance. That is unrelated to the bug being fixed, and it is the part of reusing the 200 default that I'd want decided deliberately.

The counter's release point

issued_prefetches is reset at every prefetched_streams.clear(), including the one at the end of each readRows, but a stream keeps its memory after the prefetch is consumed, so budget is returned while the buffers are still allocated. Worth deciding which of the two the limit is meant to bound: in-flight prefetch requests (release at prefetch_future.get() in AsynchronousBoundedReadBuffer::nextImpl) or allocated prefetch buffers (release on reader destruction). The OOM is caused by the latter, which is also what the memory setting implies. As written the counter implements neither. The header comment notes the erase case, but clear has the same problem.

Suggestions

Option A, small and shippable: make required_readers_num and estimated_memory_usage_for_single_prefetch substream-aware in update_stat_for_column. The data is available without deserializing prefixes — columns_substreams.txt records the real substream list per column including dynamic types, and MergeTreeDataPartWide::getColumnSizeImpl already relies on it for exactly this reason (MergeTreeDataPartWide.cpp:204-216); the reader-side interface exposes it as getColumnsSubstreams (IMergeTreeDataPartInfoForReader.h:80), with enumerateStreams as the other branch for parts without the file. Then a 122-substream JSON part is admitted as 122 instead of 1, the default admits exactly one prefetching task instead of ~200, and both settings work as designed with no change in the reader at all. It slightly over-counts versus actual issuance (isPrefetchNeededForSubstream skips some substreams, shared Nested offsets are counted per column), which is the safe direction for a budget.

Option B, what I'd actually want in master: one shared budget (count + bytes) created per read step in MergeTreeReaderSettings::createForQuery and passed through the reader settings already copied into every reader via MergeTreeReadTask::Extras; consumed at the two buf->prefetch() sites, which are the only ones in the tree (MergeTreeReaderWide.cpp:545 and :580), and released on reader destruction. The reader is the right place to enforce — it is the only place that knows the real count — it just needs a shared counter rather than a per-reader one. Then the num_columns early-out can go, since it was always a stand-in for this; the pool's admission test stays only as a coarse pre-filter that avoids eager reader creation; and every read path is bound by the same rule in the unit the setting documents. One caveat to make explicit: dropping the early-out changes reads of more than 200 columns from "prefetch nothing" to "prefetch the first 200 substreams". I think that's better and it's what the setting says, but it should be a conscious call.

Given B, filesystem_prefetches_limit becomes a strictly weaker duplicate of the byte budget, so deprecating it rather than repairing it is worth considering as a follow-up.

@Avogar Avogar left a comment

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.

Look at the comment above

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed, and I am going with B.

I checked the composition arithmetic before conceding it. allowed_prefetches_num starts at the limit (MergeTreePrefetchedReadPool.cpp:540) and every admitted task subtracts part_stat.required_readers_num (:645), which update_stat_for_column increments once per column (:443, :456), so a one-JSON-column read admits ~200 tasks at the default; startPrefetches then drains the whole queue in a single pass (:224-250), so all of those readers hold their buffers at the same time. The cap in this PR is limit * limit, and at 122 substreams it never fires. Blocker accepted: as it stands this does not fix the failure at default settings, and the test passes only because it pins the limit to 5 and 10 with max_threads = 1.

Three things I found while checking your points, which settle the rest:

Deleting the num_columns early-out costs nothing outside query reads. filesystem_prefetches_limit is assigned in exactly one place, MergeTreeReaderSettings::createFromContext (MergeTreeIOSettings.cpp:145). createForMergeMutation (:160) and createFromSettings (:170) leave it at 0, so the early-out short-circuits there and has never bounded merge, mutation or metadata reads. The only reads it bounds today are exactly the query reads that would get the shared budget, so nothing is left unbounded by removing it. That also shifts where the budget should be created: createFromContext rather than createForQuery, since LazilyUnorderedReadFromMergeTree builds its settings from the former directly (LazilyUnorderedReadFromMergeTree.cpp:56).

The substream unit is a correction of the pool's own accounting, not a new policy. isPrefetchNeededForSubstream filters out only the JSON shared-data Data substream (ISerialization.cpp:735-743), so a Nullable column already issues two prefetches and allocates two buffers while required_readers_num counts it as one. The pool is therefore already under-counting buffers by 2 to 3x for Nullable/Array/Map/Tuple, in the same way it under-counts a JSON column by ~122x. I accept the consequence you name for the wide-Nullable case: 150 columns go from 300 buffers to the limit. On the ordering, prefixes going first is a dependency and not an accident (a dynamic column's data cannot be read before its prefix); within data substreams the order is arbitrary, which is the property the pool's admission already has at task granularity.

The release point is allocated buffers, released on reader destruction. nextImpl does prefetch_buffer.swap(memory) (AsynchronousBoundedReadBuffer.cpp:267), so consuming a prefetch moves the allocation rather than freeing it, and releasing at prefetch_future.get() would hand budget back while the memory is still held. It is also the lifetime filesystem_prefetch_max_memory_usage is spent in beside it. So the resets at prefetched_streams.clear() go away instead of being extended to cover clear() as well as erase.

So B as you describe it: one shared count-and-bytes budget created in createFromContext, carried by the reader settings already copied into MergeTreeReadTask::Extras, spent at the two buf->prefetch() sites, released when the reader is destroyed, num_columns early-out deleted, and the pool's admission left as the coarse pre-filter. For the byte half, prefetch() allocates nothing when the page cache is in use (AsynchronousBoundedReadBuffer.cpp:171-172), so that path accounts zero. And yes on the caveat: for reads above the limit, prefetching the first N substreams is what the setting says, so I will take it over prefetching nothing.

The test changes shape with it: the assertion moves to the whole read step at the default limit with more than one reader, so the composition is what is covered, rather than a single reader with the limit pinned low. filesystem_prefetches_limit deprecation stays out of this PR.

groeneai and others added 7 commits September 9, 2026 22:57
filesystem_prefetches_limit and filesystem_prefetch_max_memory_usage were enforced
where prefetching is decided, in units that are not the unit that consumes memory.
MergeTreePrefetchedReadPool's admission counts required_readers_num, which
update_stat_for_column increments once per column, and MergeTreeReaderWide compared the
limit against num_columns. One JSON column expands into ~122 prefetched substreams, so
both tests compared the limit against 1, while the reader allocated one ~1 MiB read
buffer per substream.

The two enforcement points also compose multiplicatively: the pool admits up to
`limit` tasks and each reader may then issue up to `limit` prefetches of its own, so
`limit * limit` buffers can be alive with every individual check satisfied. A per-reader
counter cannot see that, which is why this replaces the one added in
f9b1245 rather than tightening it.

Add MergeTreePrefetchBudget, one shared count-and-bytes budget per read step, created in
MergeTreeReaderSettings::createForQuery and carried by the reader settings that every
read pool copies into its tasks. A reservation is an RAII slot held by the
MergeTreeReaderStream that owns the buffer, so it is returned when that buffer is
destroyed and never earlier: the slot is declared before read_buffer_holder precisely so
member teardown destroys the buffer first. ~AsynchronousBoundedReadBuffer blocks waiting
for an in-flight prefetch, so releasing before that wait would let another reader take
the capacity while the memory is still held.

The charge is once per stream rather than once per prefetch() call. Consuming a prefetch
moves the allocation into the read buffer (prefetch_buffer.swap(memory)) rather than
freeing it, so a stream allocates one prefetch buffer however many times it is
prefetched; charging per call would instead exhaust the budget after the first granule
batch, since prefetched_streams is cleared at the end of every readRows and every
substream is prefetched again on the next one. That also removes the three
issued_prefetches resets, which handed budget back while the buffers stayed allocated.

The byte figure has to come from the buffer, not from the reader settings: what
prefetch() allocates is min(remote_fs_settings.buffer_size, object size), the page cache
replaces it with page_cache_block_size, and DiskObjectStorage::prepareRead can raise it
to large_buffer_size under filesystem_cache_prefer_bigger_buffer_size. Deriving it from
settings would undercount by up to 8x, the unsafe direction for a memory budget. Hence
ReadBuffer::prefetchBufferSize, a narrow query beside prefetch() itself, overridden in
the classes a MergeTree part-read chain resolves to, including
CachedCompressedReadBuffer (whose file_in is created lazily and is still null when the
reservation is decided) and ReadBufferFromEncryptedFile (whose absence would silently
zero the byte accounting on every encrypted disk). The page-cache path reports zero
because it allocates nothing of its own.

The reader-side num_columns early-out from ClickHouse#83999 is deleted: it made a read of more
columns than the limit prefetch nothing at all, where the budget now prefetches the
first N. The pool's admission is left exactly as it is, as a coarse pre-filter that
avoids creating readers eagerly. A refused reservation means a synchronous read, never a
failure, and results are unchanged. Merges, mutations and part maintenance leave the
budget null, which preserves today's behaviour: filesystem_prefetches_limit is 0 on
those paths, so the deleted early-out never bounded them either.

Co-Authored-By: Claude Opus 5 <[email protected]>
04841 previously asserted a per-reader prefetch count with max_threads = 1, where the
composition of the pool's admission with a per-reader cap is invisible. It now measures a
read step with four concurrent readers at the default filesystem_prefetches_limit of 200:
four wide parts of 150 Nullable(UInt64) columns offer 1200 prefetchable substreams, and the
shared budget admits exactly 200 of them.

The bound is on the prefetch buffers alive at one moment, while
ProfileEvents['RemoteFSPrefetches'] counts submissions, so an exact count is only assertable
where no stream is destroyed mid-query. That holds for plain Nullable columns, whose readers
all live to the end of the query; it does not hold for a JSON column, because
release_stream_callback erases prefix streams after deserialization and legitimately returns
their capacity. The JSON count is therefore compared against the same fixture read without a
limit rather than against a fixed number, and the equalities are left to the Nullable
fixtures. Measured per row against unpatched master: 1200 -> 200 for the four-reader step,
300 -> 200 for a single reader, 42 -> 0 for the byte budget, and 168 -> 54 for the JSON
comparison.

The byte half is measured on an encrypted disk, since decryption wraps the buffer that owns
the prefetch allocation: without ReadBufferFromEncryptedFile forwarding its prefetch buffer
size, that row reads zero bytes and the bound is escaped silently. Deleting the forward
reddens that row alone.

Two settings are pinned that the runner would otherwise randomize into the measurement:
read_through_distributed_cache, which replaces the buffer owning the allocation, and
ratio_of_defaults_for_sparse_serialization, because the all-false null maps are entirely
default and a sparse null map changes the substream count.

04756's guard comment described the deleted column-count early-out. Its predicate is kept,
since a low limit can still starve the shared offsets stream, and the comment now says so.

Co-Authored-By: Claude Opus 5 <[email protected]>
The assertion rows move from a single reader on the prefetched pool to the two
cases the bound is claimed for: the plain read pool, reached through
MergeTreeReaderWide::readRows and the pool the reported query failed on, and a
JSON read step at the default limit rather than at a limit pinned low enough to
bite on its own.

A JSON count cannot be compared against a literal. ProfileEvents counts prefetch
submissions over the whole query while the bound is on the buffers alive at one
moment, and a JSON reader releases a prefix stream as soon as it is deserialized,
so the two JSON rows are the same fixture read with and without the limit. That
fixture needs eight concurrent readers to demand more than the default 200 live
buffers: measured on three Nullable(JSON) columns, four readers submit 504
prefetches with no refusal at all, while eight submit 1008 of which 250 to 440
are refused. Hence eight parts read at max_threads 8, which makes max_threads a
per-row parameter.

The plain-pool rows read one part on purpose. Readers there are created as
threads pick tasks up, so with several parts one pair can charge the budget,
finish, release it and let the next pair charge it again, which makes the
cumulative count a multiple of the limit instead of the limit.
…/respect-filesystem-prefetches-limit-json-substreams

# Conflicts:
#	src/Storages/MergeTree/MergeTreeReaderStream.h
The deleted num_columns early-out made a read of ten columns at
filesystem_prefetches_limit = 5 skip prefetching entirely, so the reference
recorded 0. With the read step's budget the same read prefetches the first five
instead, on both read pools.

Measured on the s3_cache disk the test asks for: the two data_wide limit-5 rows
go 0 to 5, the two limit-10 rows stay at 10, and all four data_compact rows stay
at 0, since a Compact part prefetches nothing either way.
ReadBufferFromFileView keeps impl's buffer state in itself between operations:
the constructor swaps it out, and every other forwarding method in the file
swaps it back for the duration of the call. The size an asynchronous descriptor
buffer reports for a prefetch comes from exactly that state, since
AsynchronousReadBufferFromFileDescriptor returns internal_buffer.size() and
prefetch() then allocates that much, so reading it without the swap charged zero
bytes for a buffer that is allocated in full.

Reachable through packed part storage, which routes the data file through
PackedFilesReader::readFile and so through this view. On a local disk with
local_filesystem_read_method = pread_threadpool the wrapped buffer is the
asynchronous descriptor one, which is why the byte half of the budget did not
bind there. A remote impl reports a member instead and was never affected, which
is why no existing assertion moved.
The capacity pre-check exists so that an exhausted budget does not make the
reader open a stream it is then refused, since getStream() forces the stream's
marks to be loaded and possibly a remote read. It was consulted before the
per-stream question, so once the budget was saturated it stopped every reader,
including one whose own streams hold the reservations.

A stream keeps its reservation while it lives, because consuming a prefetch
moves the allocation into the read buffer rather than freeing it, so
re-prefetching a stream that already holds one allocates no new memory. readRows
clears prefetched_streams at the end of every call, so on a saturated read step
the second and every later batch prefetched nothing and read synchronously,
which is the regime this change creates. Only an unreserved stream now has to
find capacity.
Two rows added. t_batches reads one part with one thread over five granules of
eight equally sized substreams, at a limit of four and with a prefetch buffer
under a granule's worth of data, so a reserved stream is prefetched again in
each batch: the bounded read submits four per batch where the unbounded one
submits eight, and each count divided by its limit is the same batch count.
Without the reservation-aware pre-check the bounded count stays at four. Neither
count is compared against a literal because compression block sizes are
randomized and the last batch can find nothing left to prefetch, which was
measured as one run in fifty at four batches rather than five.

t_packed reads a packed part on the default disk with a byte budget of one.
Local descriptor prefetches increment no ProfileEvents counter, so that row
counts system.filesystem_read_prefetches_log instead: nothing is logged with the
file view reporting its buffer size correctly, and forty prefetches without.

Two existing rows are re-shaped on measurement. step_default_limit asserted an
exact 200, but the count is the limit times the number of reader waves: readers
of one step are created as threads pick their tasks up, so a pair can charge the
budget, finish, release it and let the next pair charge it again. It was measured
at 400 in two of fifty runs, and in three of fifty on a build without the
pre-check change, so it now asserts the multiple, that the count is not zero, and
that the step never reaches what its readers asked for. json_step_limit runs at a
limit of 50 rather than 200 because releasing a prefix stream returns its
capacity to the budget, so the bounded count grows with the query's churn: at 200
it came within six per cent of the unbounded count over fifty runs, at 50 it
stays around a fifth of it. Widening the fixture was measured first and does not
change that ratio.
The first row asserted `count_of(step_default_limit) % 200 = 0 AND > 0`. On a build
with one budget per reader instead of one per read step the count is 4 x 200 = 800,
which satisfies both conjuncts, and an unfixed build submits 1200, which the file
pins two rows later and which is also a multiple of 200. The row could not fail, and
a cumulative modulo says nothing about a peak in any case. Rows 2 and 3 already
carry what it was meant to say, so it is deleted and the wave mechanism it explained
moves to row 2's comment, where it is what makes that row an inequality.

The two rows asserting that nothing is prefetched (`json_enc_bytes = 0` for the
encrypted chain, `logged_count_of(packed_bytes) = 0` for the file-view chain) were
the only oracles for their forwarding chains, and an environment that stopped
prefetching on those fixtures for any unrelated reason passed them. The packed row
was the more exposed one: it counts rows in filesystem_read_prefetches_log, so an
empty log read as a pass. Each now has a companion that differs only in the byte
bound and asserts a positive count, so such an environment fails the pair instead.
The doc comment claimed that every override of prefetch() which allocates or
forwards must override prefetchBufferSize() too. That is false of the tree:
CompressedReadBufferWrapper::prefetch and PeekableReadBuffer::prefetch both
forward and do not override it. Nothing is under-counted, because
MergeTreeReaderStream::init only ever makes data_buffer a raw
ReadBufferFromFileBase, a CachedCompressedReadBuffer or a
CompressedReadBufferFromFile, and neither of those derives from
CompressedReadBufferWrapper -- but the rule was stated as universal in one of
the highest-fan-out headers in the tree, where a reader has no way to check it.
It now names the surface that has to report: a buffer that can serve as a
MergeTree data buffer.

The JSON comment in 04841 said the bounded count "stays around a fifth of it",
which reads as the count being a fifth of the unbounded one. The measurement is
818 against 1008, so it is the gap that is about a fifth.
The previous commit rewrote the clause to say the bounded count is about a fifth
below the unbounded one. Measured on the fixture and settings the test itself
uses (8 parts, 3 Nullable(JSON) columns, max_threads 8, 8 repetitions per limit):
unbounded 1008 in 8/8 runs, limit 50 gives 158-212, limit 200 gives 653-810.

At the limit the row actually runs, 50, the count is 16-21% of the unbounded one,
so "around a fifth of it" was already the accurate reading and the rewrite made
it wrong. The gap being about a fifth describes limit 200, which is the other
clause in the same sentence.
t_packed was the only table in 04841 pinning neither disk nor storage_policy,
so it followed <merge_tree><storage_policy>. The s3 and azure stateless jobs
replace that with an object-storage policy, and both packed reads pass
remote_filesystem_read_prefetch 0 while prefetchForAllColumns selects the
remote flag for a part on a remote disk. On those jobs the packed reads
therefore prefetched nothing: packed_bytes = 0 passed vacuously and
packed_unlim > 0 failed.

Measured on a server carrying the two CI config files verbatim
(s3_storage_policy_by_default.xml and
s3_storage_policy_for_merge_tree_by_default.xml), only their MinIO port
changed:

  unpinned, default policy s3       part on cached_s3 (remote), 0 prefetches, file FAILS
  pinned,   default policy s3       part on default (local),   40 prefetches, file 3/3 OK
  pinned,   default policy default  part on default (local),   40 prefetches, file 3/3 OK

No test config redefines the default disk or policy, so the pin lands on a
local disk on every job class. A no-s3-storage tag would instead skip the
whole file on the job class where the reported failure was found, and turning
remote prefetching on for these two rows would stop exercising
ReadBufferFromFileView: on a remote disk the file view wraps
AsynchronousBoundedReadBuffer, which reports a plain member rather than the
state swapped in by executeWithOriginalBuffer.

The pin also falsifies the old reason given for remote_filesystem_read_prefetch 0
("so that a run whose default disk is object storage submits nothing"), so
that clause is replaced by what holds now.
filesystem_prefetches_limit read "Maximum number of prefetches. Zero means
unlimited" and filesystem_prefetch_max_memory_usage read "Maximum memory usage
for prefetches." Neither said the bounds are on the prefetch buffers alive at
the same time within one read step, and neither said the count is per
prefetched substream rather than per column, which is the unit a user is
counted in: 150 Nullable columns are 300 substreams against a limit of 200.
The byte bound now applies to the reader's own prefetches as well, not only to
prefetched-pool admission.

The count setting also pointed at filesystem_prefetches_max_memory_usage,
which does not exist; the setting is filesystem_prefetch_max_memory_usage.

No default and no type changes, so nothing is owed in
SettingsChangesHistory.cpp. The autogenerated docs regions carry the same text
and are regenerated by docs_autogen_nightly.py; editing them here would fail
the docs job's generated-region guard.
The comment stated two measured fractions of the unbounded count and one was
false. Over 53 runs at the limit the row actually uses (50), json_step_limit is
144-366 against a rock-steady json_step_unlim of 1008; at limit 200 it is
653-810, not "within 6%" of 1008. So the removed fractions were accurate at 50
and false at 200, and the line is now free of both. Neither is load-bearing:
the row is an inequality between two counts taken on the same fixture at the
same max_threads, so nothing is compared against a literal.

The row is also the file's shared-budget oracle, which was invisible in the
file. With one budget per reader instead of one per read step, a JSON reader
never holds 50 substreams at once (it releases each prefix stream as it
deserializes), the bound never binds, and both reads submit 1008: measured
1008 = 1008 in 23 of 23 runs on that mutant, failing this row and no other.

MergeTreePrefetchBudget::hasCapacity is deliberately stricter than tryReserve
at exactly-full bytes. tryReserve accepts a zero-byte reservation there while
hasCapacity refuses it, so a candidate that would charge nothing is skipped
rather than admitted; admitting it would cost a getStream() marks load per
remaining substream once the budget is spent, which is what the pre-check
exists to avoid.
@groeneai groeneai changed the title Respect filesystem_prefetches_limit when prefetching JSON substreams Bound filesystem prefetches by a shared per-read-step budget Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

This is option B, as asked: one count-and-bytes budget per read step, created in
MergeTreeReaderSettings::createForQuery, shared by every reader of the step, charged at the two
buf->prefetch() sites, and the num_columns early-out removed. The pool's admission test is left
alone as the coarse pre-filter.

One deliberate deviation from the sketch: the reservation is released when the buffer holding the
prefetch allocation is destroyed, which for a JSON prefix stream is release_stream_callback rather
than reader teardown. That is finer than "on reader destruction" and is what the byte budget implies,
since the memory really does come back at that point.

The call you asked to be conscious is in the changelog entry, with the two other behaviour changes at
unchanged defaults: a read above the limit now prefetches its first N substreams instead of nothing, a
read below the limit in columns but above it in substreams stops partway in block column order, and
the byte bound now also applies without the prefetched read pool.

Reviewed cold against the tree, then adjudicated against the implementation evidence. This round: 0
findings from the independent gate, and 3 nits of my own dismissed (two comment-budget calls where the
comment states a non-obvious invariant, one redundant-but-parsed randomisation clamp). The blocker
from the previous round was mine and is fixed here: the packed-storage fixture read the default
MergeTree policy, which the s3-storage and azure test configurations replace with object storage,
where those two reads prefetch nothing by design, so one row passed vacuously and its control failed
deterministically on those jobs. It is now pinned to the local default policy and measured against
the two CI config files verbatim.

Unrelated but worth knowing: #118479 edits the same function for a different reason (it stops
re-reading JSON/Dynamic metadata streams at the current mark). It is not a competing fix and I
have not acted on it. A small textual conflict is possible whichever merges first; every JSON
assertion in the new test is relative, so the counts it changes do not move any of them.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CheSema, could you review the packed-IO part of this? ReadBufferFromFileView::prefetchBufferSize() reports the wrapped buffer size from inside executeWithOriginalBuffer, because the asynchronous local-descriptor buffer reports internal_buffer.size() and the view holds that state outside the swap, so a chain that skipped the swap would charge zero bytes for a full-size prefetch buffer and escape the new memory bound entirely.

groeneai and others added 5 commits September 10, 2026 13:59
The flaky check runs the tests a PR changes 50 times per lane, and 6 of the
amd_msan runs of this file crossed the 180s per-file budget (230.6s worst,
99.4s median), so the job went red on the test this PR adds.

Two costs, removed without weakening an assertion:

43 client invocations, one per statement, where spawning an instrumented
client costs more than the statement it carries. Every prefetch bound here is
a per-query setting, so the statements are now grouped into four invocations
with the settings moved from command-line flags into per-statement SETTINGS
clauses. That also drops a dependence on --allow_repeated_settings: the two
packed arms produced local-descriptor prefetches only because the runner
allows a repeated flag and keeps the last occurrence.

Fixtures larger than the thresholds they have to cross. The wide tables go
from 150 to 40 Nullable columns with the count bound co-reduced from the
default 200 to 50, so the bound still binds below the 80 substreams one part
offers, and the pinned counts move with it (50, 80, 4 x 80). The JSON tables
go from 40 to 20 paths per column, which halves the substreams a JSON reader
holds while a read step still demands 528 of them against a limit of 50.
t_batches and t_packed go from 40960 to 24576 rows, three granules of the
pinned 8192, so the batched read still spans more than one batch.

Measured on this file, old vs new, same rig and same run count:

  master asan binary, 12 runs at 6 workers: 36.7-51.7s -> 11.7-13.4s
  this branch debug,  20 runs at 6 workers: 13.0-20.5s -> 3.2-5.2s

Both directions re-established on the resized fixtures: 20 of 20 runs pass on
this branch, and 12 of 12 fail on pristine master, where the six rows that
assert a bound flip to 0 while the six that assert the fixture prefetches at
all stay 1.
Nothing in the file failed if a slot stopped refunding the budget it holds.
The bounded JSON read would then admit its first 50 streams and stop, which
still satisfies `bounded < unbounded`; the batched read reuses reservations it
already holds, so it never exercises a refund either.

The bounded JSON step submits 133 to 343 prefetches against a limit of 50
(68 runs today), and it can only exceed the limit by reusing capacity a
finished stream gave back: `createForQuery` builds one budget per read step,
a stream holding a slot never takes a second one, and every stream of this
fixture prefetches once, since the smallest buffer the runner can draw
(`max_read_buffer_size` >= 500000) covers a whole substream here. So
`> 50` is exactly the refund.

Proven by mutation: with the two decrements in `MergeTreePrefetchBudget::
release` cancelled out, this row is the only one of the thirteen that flips,
3 runs of 3, and the binary rebuilds bit-identically (04f57f3da7a0) once the
mutation is reverted. 20 of 20 randomized runs pass with the row in place.
The JSON arms read eight parts at max_threads 8 and compared two cumulative
submission counts against each other. How many readers of a read step are alive
at the same time is decided by thread scheduling, so on a loaded runner the step
degenerates to one reader at a time; each one then prefetches all of its own
substreams while releasing its prefix streams as it goes, never exceeding the
bound, and the bounded arm reaches the same total as the unbounded one. The
comparison inverted that way on `Stateless tests (amd_asan_ubsan, flaky check)`
for fda5922: `a bounded JSON read step prefetches fewer substreams than an
unbounded one` printed 0.

Read one part with one thread instead. Then the count is exact - the reader's
substreams minus what the bound refuses - and the fixture is the same for every
arm, so the difference of two bounded counts is the difference of their limits
whatever the prefix churn is. Measured over 50 randomized runs at the flaky
check's concurrency: limit 5 submits 6 every time, limit 15 submits 16, the
unbounded arm 22. The eight-part fixture, for contrast, submitted between 143
and 303 for the same limit.

That also removes the file's dominant cost. The flaky check judges wall-clock
time per run against a 180s cap, and on the runner every file operation costs
milliseconds rather than microseconds, so the verdict tracks how many files the
fixture touches. The three-column, eight-part JSON table was 22120 of the 26742
file opens of the slowest recorded run (215s), between its eight inserts, its
two reads and dropping its eight parts. One column in one part leaves about
1300. The assertion block also scanned query_log fifteen times and spent half
its statements printing labels; it now scans once into a temporary table and
prints each label beside its result, which is 52 statements per run rather than
71.

Co-Authored-By: Claude Opus 5 <[email protected]>
Nothing in the file distinguished one budget per read step from one budget per
reader. `step_limit` reads four parts at a limit of 50, and four independent
budgets submit 4 x 50 = 200, which satisfies the only assertion made about it,
`< 320`. The JSON arms that came closest needed several readers of the step to
be alive at the same time, which thread scheduling decides, so they were not an
oracle either.

A read task's own readers are the case where overlap is structural: its PREWHERE
reader and its main reader are both built for the task and both live until it
ends. Read c1..c8 in PREWHERE (16 substreams) and c9..c40 in the main reader
(64) with a bound of 70, and the two are below the bound apiece but above it
together. One budget for the task admits 70; one per reader refuses nothing and
admits 80, the same as the unbounded arm. `RowsReadByPrewhereReaders` pins that
the two readers exist, so the arm cannot pass as a single reader that happens to
be bounded at 70.

Measured 70 and 80 over 50 randomized runs at the flaky check's concurrency,
with no spread. Mutation-proven both ways: on pristine master and with a
per-reader budget built into MergeTreeReaderWide, `one budget for the task, not
one per reader` is the only one of the seventeen rows that changes.

The fixture is the table the plain arms already use, so this costs two reads and
no new part.

Co-Authored-By: Claude Opus 5 <[email protected]>
`CachedCompressedReadBuffer::prefetchBufferSize` forwards to the buffer that owns
the prefetch allocation, and nothing exercised it: every read in the file pinned
`use_uncompressed_cache = 0`, so the MergeTree data buffer was always the
uncached one. Drop that override and the cached chain reports the base-class
zero, which lets a one-byte memory bound admit every buffer, with all assertions
still green.

Pin the setting off for the session instead of inside each statement's SETTINGS
clause, so the two new arms can ask for it: a value repeated within one clause
keeps its first occurrence, while a statement's clause does win over the session.
The pair is the plain one-part table read with the byte bound at one byte and at
10Gi, and its counts are 0 and 80 over 50 randomized runs at the flaky check's
concurrency. Mutation-proven: with the override returning zero, `and the memory
bound stops prefetching there too, through the uncompressed cache` is the only
one of the nineteen rows that changes.

Co-Authored-By: Claude Opus 5 <[email protected]>
optimizeLazyMaterialization copies the main step's MergeTreeReaderSettings into
LazilyReadFromMergeTree, so both steps shared one MergeTreePrefetchBudget through
the shared_ptr in it. A reservation lives until the reader's stream dies, and the
main step's readers outlive its last chunk: LazyMaterializingTransform waits for
main_input to finish before it pulls lazy_input, and a MergeTreeSelectProcessor
that stopped short of exhausting its tasks (read in order under a LIMIT) still
holds the task whose readers own those buffers. The lazy step therefore began
with the main step's slots already charged.

Measured on one part, one granule read per step, three substreams per step, at
filesystem_prefetches_limit = 3 (RemoteFSPrefetches, max_threads = 1, five runs
each, no spread):

                     before  after
  main step               3      3
  lazily read step        0      3

With eight substreams per step at a bound of eight the lazy step got none of its
eight, so the step lost prefetching entirely while staying within its own bound.
Lazy materialization is on by default, so this reached any ORDER BY ... LIMIT
query over a part it did not read to the end. A read without a second step is
unchanged: it still gets exactly the bound, 8 of the 16 substreams it wants.

Both bounds are documented per read step and were created per read step in
createForQuery; this restores that for the second step a query can have, at the
cost of the two steps holding up to the bound apiece. LazilyUnorderedReadFromMergeTree
needs nothing: it stores a settings object it never reads and builds its own
ReadFromMergeTree, which creates a budget of its own.

The regression rows read three substreams in each step at a bound of three, so
neither step alone reaches the bound and one shared budget refuses the second
everything. That row prints 0 before this change and 1 after. A companion at a
bound of two asserts exactly four prefetches, which is what separates a budget
per step from no budget at all on the second step: unbounded it would prefetch
all three of its substreams next to the main step's two. An EXPLAIN row pins that
the plan really does have two read steps.

A fourth row gives the lazy step a one-byte memory bound, so that a budget copied
with the count bound alone fails it: the step would prefetch all three of its
substreams where a bound of its own refuses every one.

The analyzer is pinned in those reads because lazy materialization is off without
it whatever its own setting says, and the old-analyzer job classes turn it off by
profile; on the EXPLAIN row it is pinned on the outer statement too, since a
subquery may not turn it on below a top level that has it off.

Also adds the byte bound the existing arms were missing. Every one of them used
either one byte, which refuses each buffer on its own size, or ten gigabytes,
which refuses nothing, so none of them needed bytes counted across the buffers
alive together. The new arm bounds the eight-stream batched read at 14 KiB, three
and a half of its 4096-byte buffers, and asserts three per batch. The bound is not
a multiple of the buffer size on purpose: at 16 KiB four buffers reach it exactly
and testing a candidate against the whole bound instead of the remaining capacity
passes, while at 14 KiB that admits a fourth buffer and takes the read to 16 KiB,
over the limit. Making tryReserve test only the candidate turns that row alone
from 1 to 0.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - facbff2

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Logical error: Got read request from replica A for unknown stream B. (STID 5217-5b3d) trunk defect in the parallel replicas reading coordinator, not reachable from this diff: 162 distinct pull requests and 14 non-PR runs carry this signature in 90 days, and 24 mutually unrelated pull requests hit the same check today between 00:22Z and 07:25Z (22 in this bucket, 2 in the sibling 5217-505b one) #118084 (mine, open), the in-flight fix for this family; the entry path behind today's burst is a different one and stays under investigation at full effort
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260911-080108

@Avogar

Avogar commented Sep 11, 2026

Copy link
Copy Markdown
Member

The shape is right and the RAII/ownership discipline is careful (slot declared before the buffer it accounts for, released with the stream rather than with the prefetch). Four things I think need resolving before this lands.

1. The pool's admission still applies both settings, in the old per-column units. MergeTreePrefetchedReadPool.cpp isn't in the diff, so fillPerThreadTasks keeps spending filesystem_prefetches_limit against required_readers_num (one per column) and filesystem_prefetch_max_memory_usage against a per-column byte estimate, in local counters unrelated to the new budget. = 200 now means both "admit <=200 tasks, counted in columns" and "<=200 live prefetch buffers per step". The shared budget dominates so this isn't a correctness bug, but the double meaning the PR set out to remove just moved one level up — and the pool still eagerly creates readers (a marks load each) for tasks whose prefetches the budget will refuse.

2. LazilyUnorderedReadFromMergeTree lost its bound entirely. The budget is created only in createForQuery, but that step builds its readers with createFromContext (LazilyUnorderedReadFromMergeTree.cpp:56), which sets filesystem_prefetches_limit and leaves prefetch_budget null — and a null budget makes tryReservePrefetchBuffer always succeed. With the num_columns early-out removed, that path goes from bounded to unbounded. Given the care taken over the sibling LazilyReadFromMergeTree with forSeparateReadStep, this reads as an oversight.

3. The new bound is globally much tighter than the one it replaces, with no perf evidence. 200 is now a hard cap on prefetch buffers alive across the whole read step, all threads included. Previously the pool admitted ~200 / num_columns tasks and each prefetched all of its substreams: for a 20-column read of Nullable/Array data that is roughly 400 buffers today against 200 after, and the gap widens with substreams per column. That deserves a perf run before merge, and it may mean the default has to move.

4. Slots are first-come and held for the stream's whole life, so a step can starve itself. Correct for memory accounting, but startPrefetches fires all admitted readers at once, so the earliest ones take the entire step budget and hold it until their tasks finish while everything behind them prefetches nothing. A per-step cap with no per-reader floor needs an explicit argument that this is acceptable.

@CheSema

CheSema commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

This PR make our wrong prefetches looks more mature by their complication.
The main problems with prefetches:

  • budget is allocated in the perpendicular order than the execution order -- that leads to the second problem
  • we prefetch the data which will be needed lated and in the moment now we jam the cannel with not urgent work
  • they use the expensive data in memory instead utilize/fill the caches
  • we trigger prefetch on the several different position of a file and open several connection to the one blob, waste them
  • when prefetch is done, we keep the connections and try to use them later: but the are several to one file, most of them would be just closed in prefer to other; while a connection is not read (reading order != prefetch order -> most prefetches are idle until reading catch them up) s3 sends the dat to the clients kernel, that memory is expensive and limited.

They are not adressed here, instead wrong budget allocation become more complex.

But I would not think the bots should address this issues. They would do it chaotically. The issue needs owner ship and the consistent development vector. Otherwise we would follow with such PR's like this and make things complicated without any improvements.

@CheSema CheSema closed this Sep 11, 2026
@CheSema CheSema self-assigned this Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, and I am not reopening this.

Answering the four points in the review above, since three of them hold regardless of this PR:

  1. Right. I did not touch the pool, so filesystem_prefetches_limit ends up meaning two different things one level apart instead of one, which is the opposite of what this PR set out to do.

  2. This one does not hold, and the precise version is worth having because the trap is real but sits elsewhere. The settings object built at LazilyUnorderedReadFromMergeTree.cpp:56 is handed to LazyUnorderedReadFromMergeTreeSource and then never read: in that source's .cpp the name reader_settings appears only as the ctor parameter and the member init, and the header declares no accessor. Its readers come from the ReadFromMergeTree that buildPipe() constructs, and that ctor builds its own settings through createForQuery (ReadFromMergeTree.cpp:516), so the path stays bounded like any other read step. What is true is that the unused member would make the first change that starts reading it silently unbounded.

  3. Right, I have no perf evidence for the tighter bound, and the 400 against 200 arithmetic matches how the pool admits today.

  4. Right, and I measured that shape across the two read steps: while both shared one budget, the lazily materialized step got zero prefetches, because the main step's readers hold their reservations until their tasks finish and under a LIMIT they stop short of finishing. The same first-come effect applies inside one step, and it is also an instance of the first objection in the closing comment: the budget is spent in reader creation order rather than in the order the data is needed.

If it is useful, I can record the measurement from the description as an issue, so whoever picks up prefetching has it without reading a closed PR. Your call, and I will leave it off the tracker if you would rather.

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

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants