Repository navigation
Conversation
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]>
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
Validation on the final tree: the three capped rows and the unlimited control pass on the fixed Session id: cron:clickhouse-review-slot-9:20260809-200002 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260809-185000 |
|
cc @CurtizJ @Avogar, could you review this? |
|
Workflow [PR], commit [facbff2] Summary: ❌
AI ReviewSummaryThis PR changes Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit facbff2.
Changed lines: Changed C/C++ lines covered: 114/119 (95.80%) · Uncovered code |
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.
|
Style check was red on the new test: it reads Fixed in 078ad9b - 2 lines, test only, no source change. The predicate is equivalent A stricter Both directions re-established through the runner on this head: fixed build
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes556 object files changed (+256.92 KiB total), 1 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units3032 translation units recompiled, 15406 s compile time in total, 3031 of them have a recent master baseline. |
…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.
CI finish ledger - 08c0cd1Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Neither is PR-caused. This PR limits JSON-substream prefetching in Session id: cron:our-pr-ci-monitor:20260814-200000 |
|
Fixing PR for the |
|
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.
So The per-reader cap does not compose with the pool's admission
For the case in the description: at
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. The unit change is a silent behavior change for non-JSON reads Substream counts are 2-3x column counts for The counter's release point
Suggestions Option A, small and shippable: make Option B, what I'd actually want in master: one shared budget (count + bytes) created per read step in Given B, |
|
Confirmed, and I am going with B. I checked the composition arithmetic before conceding it. Three things I found while checking your points, which settle the rest: Deleting the The substream unit is a correction of the pool's own accounting, not a new policy. The release point is allocated buffers, released on reader destruction. So B as you describe it: one shared count-and-bytes budget created in 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 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.
Internal second-model reviewThis is option B, as asked: one count-and-bytes budget per read step, created in One deliberate deviation from the sketch: the reservation is released when the buffer holding the The call you asked to be conscious is in the changelog entry, with the two other behaviour changes at Reviewed cold against the tree, then adjudicated against the implementation evidence. This round: 0 Unrelated but worth knowing: #118479 edits the same function for a different reason (it stops |
|
cc @CheSema, could you review the packed-IO part of this? |
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.
CI finish ledger - facbff2Every 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
Session id: cron:our-pr-ci-monitor:20260911-080108 |
|
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. 2. 3. The new bound is globally much tighter than the one it replaces, with no perf evidence. 4. Slots are first-come and held for the stream's whole life, so a step can starve itself. Correct for memory accounting, but |
|
This PR make our wrong prefetches looks more mature by their complication.
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. |
|
Understood, and I am not reopening this. Answering the four points in the review above, since three of them hold regardless of this PR:
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. |
Related: #113380
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
filesystem_prefetches_limitandfilesystem_prefetch_max_memory_usagenot bounding the read buffers that filesystem prefetches hold. Reading aJSONcolumn 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 withMEMORY_LIMIT_EXCEEDEDat 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 thanfilesystem_prefetches_limitprefetches 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 (150Nullablecolumns are 300 substreams against a limit of 200); andfilesystem_prefetch_max_memory_usagenow 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, andMergeTreeReaderWidecompared it againstnum_columns, while each prefetched substream allocates its own buffer. OneJSONcolumn 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 150Nullable(UInt64)columns holds 1200 prefetch buffers at a limit of 200.This adds one count-and-bytes budget per read step, created in
createForQueryand shared by every reader of the step. It is charged once per prefetch buffer at the twobuf->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, where04675_cancelled_json_prefix_read_does_not_report_broken_partdied withCode: 241 ... would use 4.66 GiB ... MergeTreeSelect(pool: ReadPool).04841covers both bounds over both read pools, on remote, encrypted and packed storage;03394's reference records the visible change, its twodata_widelimit-5 rows going0to5.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]