Skip to content

Do not hold a lock across marks loading in JSON prefix reads - #114252

Merged
Avogar merged 16 commits into
ClickHouse:masterfrom
groeneai:fix-mutex-across-marks-load-in-json-prefix-deserialization
Sep 17, 2026
Merged

Avogar merged 16 commits into
ClickHouse:masterfrom
groeneai:fix-mutex-across-marks-load-in-json-prefix-deserialization

Conversation

@groeneai

@groeneai groeneai commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #114136

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 a latency pathology when reading an Object/JSON column from a Wide part: the per-dynamic-path prefix deserialization tasks all queued behind a single mutex that was held across marks loading, so marks were loaded one after another instead of in parallel. Closes #114136.

Description

Found while investigating a Stress test (arm_asan_ubsan, s3) hung check (CI report).

Root cause. SerializationObject::deserializeBinaryBulkStatePrefix fans per-path prefix deserialization into a thread pool. The Wide reader's callbacks were not thread safe, so all ran under one callbacks_mutex, held across settings.getter(), which reaches MergeTreeReaderStream::init() -> loadMarks(): a blocking wait on marks I/O. Every task then queues behind the holder. A convoy, not a deadlock: 100 of 152 threads waited on it, and WaitMarksLoadMicroseconds was 96% of elapsed time.

The change. MergeTreeReaderWide owns a FileStreams holder encapsulating the stream map, the prefetched set and their mutex. Only the containers are guarded, so both blocking operations stay outside the lock; element access needs none because parallel tasks own disjoint stream names, now stated as an invariant. With the callbacks thread safe the serialization layer needs no fallback, so callbacks_mutex, the six safe_* wrappers and the prefix_deserialization_callbacks_are_thread_safe flag are gone; MergeTreeReaderWide is their only in-tree producer. It also removes the TSAN lock-order inversion between the nested mutexes.

Validation. A failpoint sleeps in loadMarksSync; the test asserts WaitMarksLoadMicroseconds exceeds wall-clock time, which requires concurrent waits. Only the asynchronous arm asserts that ratio, because its wait is a wait on background loads, so a co-scheduled runner inflates both of its terms together; it reddens (0.98 against the 1.15 threshold) once the getter is re-serialized behind one mutex. The two other arms run for their code paths and keep deterministic checks: their duration also carries data-stream reads, which made their ratios false-red in the flaky check.


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

Version info

  • Merged into: 26.10.1.23 (included in 26.10 and later)

groeneai and others added 4 commits August 10, 2026 14:32
…ialization

Reading an Object/JSON column from a Wide part fans per-dynamic-path prefix
deserialization out into a thread pool. The reader's callbacks were not thread
safe, so SerializationObject wrapped all of them under one stack-local mutex.
That mutex only needs to serialize mutations of the reader's stream containers,
but it was held across settings.getter(), which resolves a stream and calls
MergeTreeReaderStream::init() -> estimateMarkRangeBytes() -> loadMarks() ->
future.get(): a blocking wait on marks I/O.

The result is a convoy rather than a deadlock. Every pool task queues behind the
one holder, so marks loads that should overlap run strictly one after another,
and the tasks the holder is waiting for are themselves queued behind it. In the
CI report below 100 of 152 dumped threads were waiting on that mutex and
WaitMarksLoadMicroseconds accounted for 96% of a query's elapsed time, which
crossed the 1000 s hung-check threshold.

Make the reader's callbacks genuinely thread safe with a streams_mutex that
covers only container mutation, and set the existing
prefix_deserialization_callbacks_are_thread_safe flag so the serialization layer
stops wrapping them. No lock is then held across marks loading anywhere:

  - getStream() resolves or creates the stream under the mutex and does
    adjustRightMark()/seekToStart()/seekToMark()/getDataBuffer() outside it.
  - getOrAddStream() constructs the stream and calls startAsyncLoad() outside the
    mutex, because scheduling blocks when the marks pool queue is full.
  - release_stream_callback extracts the map node under the mutex and destroys it
    outside, because ~MergeTreeMarksLoader waits for an in-flight load.
  - has_uniform_marks_callback looks the stream up under the mutex and calls
    hasAtMostNDistinctMarks() outside.
  - The prefetch callback resolves its per-column SubstreamsCache on the serial
    thread instead of indexing the shared `caches` map from pool tasks, where
    operator[] could insert, rehash and invalidate references held elsewhere.

Per-stream exclusivity outside the lock was already load-bearing: each parallel
task owns a disjoint batch of dynamic paths, the stream name embeds the path, and
the read from the returned ReadBuffer already happened with the lock released.

SerializationObject.cpp and ISerialization.h are unchanged. The safe_* wrappers
there are now unused by the only in-tree producer of the pool, but remain the
correct fallback for a caller that supplies non-thread-safe callbacks.

Adds a failpoint that sleeps in MergeTreeMarksLoader::loadMarksSync and a test
asserting WaitMarksLoadMicroseconds exceeds the query's wall-clock time, which is
only possible if several marks loads waited concurrently. On master the ratio is
exactly 1.00; with this change it is 1.47 on the test's shape.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114063&sha=7f28dc544f58b8bbfa775a4da6d4bbc167a8482c&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29
Related: ClickHouse#114136
Run the test under clickhouse-local instead of the shared server. It enables a
process-global, persistent failpoint and asserts a timing ratio, so a concurrent
copy clearing the failpoint after the prefix phase would leave the precondition
satisfied (the serial data-phase loads still slept) while the ratio fell to about
0.98 - the test would then report a regression on a correctly fixed build. Each
clickhouse-local invocation owns its own failpoint state, so that window does not
exist, and no no-parallel tag is needed. A trap removes the temp directory on
every exit path.

The memory limit is set in the generated config rather than on the command line:
sized from the enclosing cgroup it becomes whatever unrelated processes have left.

Add a second arm with load_marks_asynchronously = 1 so the carriers that only
exist while a marks load is in flight are executed, asserted through
BackgroundLoadingMarksTasks, and make the JSON column carry a typed
LowCardinality path so the uniform-marks check runs too. Measured coverage:
reverting the getter split flips the ratio from 1.47 to 1.00, while scheduling
the asynchronous load back under the mutex does not change the result, because
244 loads never saturate the 10000-entry queue. That leg stays justified by
inspection, and the uniform-marks check is reachable only from the serial
typed-path pass.

Lower the wait precondition from ten seconds to one. It was sized for the
synchronous arm; the asynchronous arm waits about four seconds, so it reported
"failpoint did not fire" when the background-task counter proved otherwise. The
same query without the failpoint waits under 15 ms.

Also drop the issue reference and the duplicated exclusivity argument from two
comments, leaving the invariant each one states.
…cy test

Two arms are added to 04864 so the reader callbacks the fix touches are actually
executed by the test rather than only justified by reading the code.

A second clickhouse-local instance constrains the marks-pool queue below the
number of loads, so scheduling a marks load has to wait for a running one to
finish. That wait used to happen while the reader held its container mutex.
Note that ThreadPool raises queue_size to max_threads, so only the queue is
constrained: shrinking the pool instead caps the achievable concurrency and
inverts the ratio oracle, making the arm pass on an unfixed build and fail on a
fixed one.

The third arm enables local_filesystem_read_prefetch, which is off by default,
so the prefix prefetch callback runs at all. It asserts one prefetch per dynamic
path from system.filesystem_read_prefetches_log; without the setting that count
is zero.

Both new arms redden on an unfixed build with a diagnostic ratio. The queue arm
proves the blocking schedule call executes (240 loads against a queue of 50, and
an instrumented build counted 135-150 schedule calls that had to wait) but it
does not discriminate a mutation that puts scheduling back under the mutex:
WaitMarksLoadMicroseconds is incremented only inside loadMarks(), so scheduling
delay never enters the numerator, and serializing it moves the ratio away from
the failure threshold. That carrier remains justified by inspection.

Also corrects two comments that stated mechanisms which do not hold: the
prefetch callback's own cache lookup cannot insert, and the runner's compression
codec pin never reaches a clickhouse-local test.

Co-Authored-By: Claude Fable 5 <[email protected]>
SYSTEM DROP MARK CACHE affects server-wide shared state, so the style check
requires a no-parallel tag on any test that contains it. The tag would be wrong
here: the test runs under clickhouse-local because the failpoint it needs is
process-global, so there is no shared server to protect, and the tag is
discouraged where it can be avoided.

Setting mark_cache_size to zero in the generated config has the same effect on
the arms below. A zero size still constructs the cache object, so the
asynchronous loading path that dereferences it unconditionally keeps working, but
every entry is evicted on insert, so every lookup misses and every arm loads
marks cold. Removing the statements does not warm any arm: all four assertions
still redden on an unfixed build with their diagnostic ratios, and stripping the
config line makes the asynchronous arms report their vacuity preconditions
instead of passing quietly.

The queries against system.parts and system.query_log now filter on
currentDatabase(), which the style check also requires. Not only cosmetic: the
queue arm's instance reuses the same log_comment namespace.

Also states the true local invariant at the prefix prefetch callback: sibling
prefix tasks resolving the same key would modify the cache map concurrently,
which is why it is resolved on the serial thread.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 rounds, adjudicated)

An independent reviewer read the resulting code cold, then a second model re-reviewed each round.
Verdicts below; the final round returned no findings.

# Finding Verdict
❌ The PR body stated the fix guards against operator[] "rehash and invalidate live references". That is not a real C++ property: rehashing an unordered_map invalidates iterators, not references or pointers to elements, which is precisely why handing a raw SubstreamsCache * to a task is sound. The body would have described the fix as resting on something that does not hold. ❌ Fixed. Rewritten to the true hazard: a non-const lookup can insert, so it modifies the map while sibling tasks read it.
⚠️ Closes: was only inside the template's HTML comment block, so it did not render. ⚠️ Fixed. Moved onto its own visible line.
⚠️ The validation table claimed streams_mutex guards the containers "on every access". Eight accesses are in fact unlocked. ⚠️ Fixed (wording). All eight run on the reader thread after deserializePrefix has joined every pool task, so they are correct; the claim was just broader than the invariant. Narrowed.
⚠️ The test's arms redden without the fix, but do not each discriminate every mechanism the fix touches. ⚠️ Coverage claims narrowed rather than arms added. Making the queue-full arm discriminate is not currently possible: no ProfileEvent records marks-pool scheduling-admission wait (ThreadPool.cpp stops its stopwatch before the job_finished wait), so it would require instrumenting a hot shared primitive. That carrier is justified by inspection and said so.
⚠️ The test failed Style check three times (SYSTEM DROP MARK CACHE without no-parallel, missing currentDatabase() predicates). ⚠️ Fixed by disabling the mark cache in the generated config instead of dropping it, so the no-parallel tag is not needed. Re-verified whole-tree: zero violations, with a positive control confirming the rule still fires on a synthetic violator.
💡 Remove Closes #114136 from the changelog entry. 💡 Disagreed. The shorthand in the entry and the full-URL relationship line serve different consumers (CHANGELOG.md text vs GitHub auto-close); neither the template nor CI forbids both.
💡 Drop the no-random-settings tag, since randomized settings do not reach a clickhouse-local test. 💡 Disagreed. Correct today (randomization is delivered through client options only), but the tag costs nothing and prevents a flake the first time this test grows a client arm. The one genuinely wrong part, a comment naming a mechanism that does not apply, was already corrected.

Independently re-derived rather than taken on report: the invariant-carrier list (six callbacks,
matching the plan item for item); that none of the 31 deserializeBinaryBulkStatePrefix
implementations writes the shared per-column SubstreamsCache, which is what makes the blanket
mutex removable; that stream names embed the dynamic path and the shared-data prefix is
deserialized after the pool joins, so unlocked per-stream work is safe; that the lost-insert race
destroys the loser's stream outside the lock; and the style-check result.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Answer
a Deterministic repro? Yes. SYSTEM ENABLE FAILPOINT merge_tree_marks_load_sync_sleep, then SELECT count() FROM (SELECT j FROM t LIMIT 1) over a JSON column with 40 dynamic paths in a Wide part, merge_tree_use_prefixes_deserialization_thread_pool = 1. With a 1 s sleep per marks load: 244.3 s elapsed for 244 loads, i.e. exactly serialized. Not timing-sensitive: the assertion is a ratio, not a duration. No setting overrides are needed to reach the bug, because local_filesystem_read_prefetch defaults to false, so the prefetch pre-pass that would warm the streams never runs.
b Root cause explained? Yes. SerializationObject.cpp:601 wraps the reader's callbacks under one callbacks_mutex; safe_getter holds it across settings.getter() -> MergeTreeReaderWide::getStream -> MergeTreeReaderStream::init() -> estimateMarkRangeBytes() -> loadMarks() -> future.get(). A container lock held across blocking marks I/O. The tasks the holder waits for are queued behind it.
c Fix matches root cause? Yes. The lock is narrowed to container mutation and the blocking work moved outside it, so nothing serializes. Not a widened bound, a size reduction, a no-random-* tag, or a guard at the symptom site.
d Test intent preserved / new test added? Yes. No existing test weakened. New test 04864_json_prefix_deserialization_marks_load_not_serialized.sh asserts marks loading overlaps in four arms (synchronous, asynchronous, prefetching, and a second instance whose marks-pool queue is smaller than the number of loads), plus preconditions that the failpoint fired, that the asynchronous arms really scheduled background loads, and that the prefetch callback ran, so no ratio can be evaluated vacuously. It runs under clickhouse-local so the process-global failpoint cannot be cleared by a concurrent copy mid-measurement (which would make the test accuse a correct build), and a trap removes its temp directories on every exit path.
e Both directions demonstrated? Yes, with two binaries differing only in the reader fix (both carry the failpoint). Without: ratio 1.00, test FAILS, elapsed 244.3 s, all 244 loads on 1 thread. With: ratio 1.47, test PASSES, elapsed 166.2 s, loads spread over 40 threads. WaitMarksLoadMicroseconds (244 s) exceeding wall-clock (166 s) is only possible if loads waited concurrently. The asynchronous arm behaves the same way: 0.99 without, 14.1 with.
f General across code paths? Yes. Every callback touching the reader's containers was audited, not only the reported one. Four carriers besides getStream were fixed: seek_to_start_callback, has_uniform_marks_callback (hasAtMostNDistinctMarks loads marks), release_stream_callback (~MergeTreeMarksLoader waits for an in-flight load, so the node is extracted under the lock and destroyed outside), and startAsyncLoad (pool scheduling blocks on a full queue). check_stream_exists_callback touches no container and stays unlocked. Compact readers never set the pool (MergeTreeReaderWide.cpp:433 is the only assignment). All four test arms redden without the fix, and getter is discriminated by mutation; the other two arms are narrower than that. The queue arm's shipped assertion, BackgroundLoadingMarksTasks > 50 against a queue of 50, is a cumulative count: it shows more loads than the queue holds, not that the queue was full at any instant (240 schedule calls did wait, measured with a throwaway instrumented build, not by the test). It also cannot catch a mutation putting scheduling back under the mutex: WaitMarksLoadMicroseconds has one increment (MergeTreeMarksLoader.cpp:140), inside loadMarks(), so scheduling delay never enters the numerator and serializing it moves the ratio away from the threshold. That carrier stays justified by inspection (ThreadPool.cpp:465-474 waits on job_finished with no timeout). The prefetch arm covers the prefetched_streams pair for execution only (39 prefix prefetches per query from system.filesystem_read_prefetches_log; 0 without local_filesystem_read_prefetch), and that execution is the serial pre-pass at SerializationObject.cpp:537-554, before the pool section at :579, so it does not exercise the caches resolution under concurrency. has_uniform_marks_callback is only reached from the serial typed-path pass, so its locking is defensive.
g Generalizes across inputs? Yes. Content checksums are identical across 8 arms: pool off/on, local_filesystem_read_prefetch=1 (exercises the prefetch callback), load_marks_asynchronously=1 (exercises startAsyncLoad outside the lock), both together, merge_tree_use_deserialization_prefixes_cache=0, max_threads=1, and max_threads=32, max_block_size=113. A mutation control on shifted data changes the checksum, so the oracle discriminates rather than being blind.
h Backward compatible? Yes. No new or changed setting, no format change, no SettingsChangesHistory.cpp entry needed. prefix_deserialization_callbacks_are_thread_safe already exists and is internal. No user-visible behaviour change beyond latency.
i Invariants and contracts preserved? Yes. streams_mutex guards every access to streams and prefetched_streams that a parallel prefix task can reach; the remaining accesses (readRows/prefetchBeginOfRange and the data-phase callbacks) run on the reader thread after deserializePrefix has joined every pool task. Per-stream exclusivity outside the lock was already load-bearing: the read from the returned ReadBuffer already happened unlocked, and each task owns a disjoint batch of dynamic paths whose name is embedded in the stream name. The non-atomic prefetched_streams contains/insert pair is now one locked check plus one locked insert. A lost insert race in getOrAddStream returns the winner's stream and destroys the loser's outside the lock. TSAN over the parallel path reports no races, with a positive control (ratio 1.48) confirming the path executed.

Regression check on both arms with identical server configuration: no test fails with the fix that does not already fail without it (json suite 18 vs 31 failures, all environmental on a single-node config; object/dynamic/variant identical 26/26). 04357_geojson_real_world, the carrier test in the CI report, times out at 600 s without the fix and passes with it. 50/50 randomized runs of the new test: 50 passed, 0 failed; 6 concurrent copies also pass, leaving no temporary directories behind.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @KochetovNicolai, could you review this? The Wide reader's prefix callbacks were not thread safe, so SerializationObject wrapped them all in one mutex, and that mutex was held across settings.getter(), which blocks in loadMarks(). Every parallel prefix task then queued behind the holder, so marks loaded serially instead of in parallel.

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

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e7a48e1]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR removes the serialization-side fallback mutex and moves stream synchronization into MergeTreeReaderWide so parallel Object/JSON prefix deserialization no longer holds a lock across marks loading. The reader-side refactor itself looks coherent on the current head, but the new regression test no longer covers the synchronous marks-loading path it claims to validate, so the evidence is still incomplete for the full bug-fix contract.

Tests
  • ⚠️ [tests/queries/0_stateless/04864_json_prefix_deserialization_marks_load_not_serialized.sh:82] The arm labeled sync never sets load_marks_asynchronously = 0, while that setting defaults to true. As written, the query still uses background marks loads, so the test does not exercise the pure synchronous loadMarksSync path and the stronger failpoint-witness rationale in the comment below no longer matches the executed query. Please pin load_marks_asynchronously = 0 in that arm and keep the surrounding comments / reference output aligned with the actual mode under test.
Final Verdict
  • Status: ⚠️ Request changes
  • Add real synchronous coverage to 04864 by forcing load_marks_asynchronously = 0 in the sync arm. After that, the reader-side locking change looks ready.

LLVM Coverage Report

Measured on commit e7a48e1.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 80.50% 80.60% +0.10%

Changed lines: Changed C/C++ lines covered: 147/153 (96.08%) · 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 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit e7a48e115220d6d498a890299f9bb88812b7c65d with master failed: RuntimeError: CI logs cluster query failed: SELECT count() AS c FROM binary_sizes W….

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a09644c

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.

CI is fully finished on this head and there are no failures to own: the praktika report for
this commit is top-level OK (175 jobs, 157 OK, 18 genuine skips, 0 dropped), and CIDB
records 0 FAIL/ERROR test rows for this pull request.

Check / test Reason Owner / fixing PR
(none) no failing check on this head n/a
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260811-073000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

Release-transition baseline: compared against the last 26.8 master because no 26.9 master baseline exists at or before the trusted base-commit anchor.

This PR is a concurrency fix that only affects how marks are loaded during parallel JSON/dynamic-subcolumn prefix deserialization in wide parts. Neither ClickBench nor TPC-H reads JSON columns, so none of the flagged deltas — including the large TPC-H Q4 (x19.7 faster) and Q7 (x6.7 faster) speedups — can be attributed to this change. Every directional flag was measured against a thin baseline of only 2 base instances, so the shifts are run-to-run/baseline variance and are downgraded to not sure. The one envelope-suppressed no_change (ClickBench Q13) is correctly classified.

clickbench

⚠️ 11 inconclusive

Flagged queries (11 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 277 196 -29.2% <0.0001 This PR only changes marks-loading concurrency during JSON/dynamic-column prefix deserialization; ClickBench reads no JSON columns, so this -29.2% is thin-baseline variance (2 base runs).
⚠️ 5 not_sure 368 258 -29.9% <0.0001 Off the changed path: the PR only touches JSON/dynamic-subcolumn prefix marks-loading in wide parts, which this query doesn't exercise, so the -29.9% is run-to-run variance on a thin baseline.
⚠️ 9 not_sure 340 384 +13.1% <0.0001 The PR only affects JSON/dynamic-column marks-loading concurrency; this query reads no JSON, so the +13.1% is thin-baseline noise, not a PR regression.
⚠️ 15 not_sure 223 165 -26.0% <0.0001 PR only changes JSON/dynamic-column prefix marks-loading concurrency; this query reads no JSON, so the -26.0% is thin-baseline variance (2 base runs).
⚠️ 16 not_sure 760 618 -18.7% <0.0001 Off the changed path: no JSON/dynamic columns are read here, so the -18.7% cannot come from this marks-loading concurrency fix; it is thin-baseline variance.
⚠️ 17 not_sure 541 246 ×2.2 faster <0.0001 The PR only touches JSON/dynamic-subcolumn prefix marks-loading; this query reads no JSON, so the x2.2 faster result is a thin-baseline artifact, not a PR effect.
⚠️ 18 not_sure 1226 1064 -13.2% <0.0001 Off-path for this PR (JSON/dynamic-column marks-loading concurrency only); the -13.2% on a 12-run base is run-to-run variance, not attributable to the change.
⚠️ 28 not_sure 1022 1091 +6.7% 0.0002 Left as not sure: the two tests disagree and the base measurements were noisy. The PR's JSON marks-loading change does not touch this query's path anyway.
⚠️ 30 not_sure 266 235 -11.7% <0.0001 PR only changes JSON/dynamic-column prefix marks-loading; this query reads no JSON, so the -11.7% is thin-baseline variance.
⚠️ 31 not_sure 362 309 -14.6% <0.0001 Off the changed path: no JSON/dynamic columns here, so the -14.6% is run-to-run variance on a thin baseline, not this concurrency fix.
⚠️ 32 not_sure 1287 1372 +6.6% 0.0062 Left as not sure: mixed test signals on a noisy base. The PR's JSON marks-loading path is not exercised by this query.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 4 inconclusive

Flagged queries (4 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 1044 53 ×19.7 faster <0.0001 TPC-H reads no JSON/dynamic columns, so this x19.7 faster result cannot come from a JSON marks-loading concurrency fix; base median (1044 ms, 2 runs) is a cold/slow baseline artifact.
⚠️ 7 not_sure 554 83 ×6.7 faster <0.0001 Off-path: no JSON columns in TPC-H, so the x6.7 faster reading is thin-baseline variance (2 base runs) rather than this PR's effect.
⚠️ 8 not_sure 163 90 -44.8% <0.0001 The PR only touches JSON/dynamic-column marks-loading; TPC-H reads none, so the -44.8% is a thin-baseline artifact, not attributable to the change.
⚠️ 17 not_sure 65 105 +61.5% <0.0001 Off the changed path and very noisy source measurements; the +61.5% (+40 ms) on a thin baseline is run-to-run variance, not a regression from this JSON marks-loading fix.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 84fdb96e-f7c7-4c81-9a99-0bfe4e6e1500
  • MIRAI run: 1da63038-6d9d-46af-b9e5-06f1e3e6805a
  • PR check IDs:
    • clickbench_107302_1787879154
    • clickbench_107459_1787879172
    • clickbench_107556_1787879175
    • tpch_adapted_1_official_107728_1787879370
    • tpch_adapted_1_official_107841_1787879409
    • tpch_adapted_1_official_107944_1787879433

Master adds `merge_tree_sequential_source_sleep_before_read` and
`replicated_sends_sleep_before_file_send` where this branch adds
`merge_tree_marks_load_sync_sleep`. Kept all three.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b41337513d0b8c68551348409d0f467de9c98f7e

CI has finished on this head. Every failure below has an owner: a fixing PR, or a full-effort fix
task whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / test_s3_plain_rewritable/test.py::test[s3_plain_rewritable_with_metadata_cache-data_with_cache/] node death, not this diff: the test's ALTER TABLE test MODIFY SETTING gets Code: 210. DB::NetException: Connection refused (172.16.5.9:9000) because the shard's server process was killed a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)

Attribution measured in CIDB over 7 days for that exact test and check: 19 rows across 17 distinct
PRs, including 2 true-master runs, first seen 2026-08-29 15:13:22. Two sibling cases
(test_projections[s3_plain_rewritable] and [cache_s3_plain_rewritable]) appeared in the same
window after passing continuously since 2026-07-31. Counts are given rather than PR links so this
does not cross-reference unrelated PRs.

The diagnostics prerequisite for this family, #117104, merged earlier today, but it is explicitly not
the fix: it preserves the kernel's memory-kill record so the breaching cgroup can be named, and its
merge commit is not an ancestor of this head. The mechanism half is what the new fix task owns.

Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114252&sha=b41337513d0b8c68551348409d0f467de9c98f7e&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%206%2F6%29

Session id: cron:our-pr-ci-monitor:20260830-180000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_s3_plain_rewritable node death: #117202, merged 2026-08-31.

The node was not crashing. On a hung docker compose stop every node of a cluster crosses the same 60 second stacktrace deadline at once, so several gdb processes attach simultaneously and each reads the whole binary's debug info. Together they pin the cgroup that holds the nested containers at its 40.78 GiB cap, and the kernel kills whatever is largest in it, which while gdb is still small is a ClickHouse server. The mid-flight test then sees Code: 210. #117202 serializes the attach.

@Avogar Avogar self-assigned this Sep 1, 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
…ndows

The previous commits guarded `streams` and `prefetched_streams` with a
`streams_mutex` taken and released at six call sites, each carrying a comment
about which blocking call had to stay outside the critical section. That mutex
protected the containers but not the elements: `getOrAddStream` handed back a
raw `MergeTreeReaderStream *` that callers used with the lock released, while
`release_stream_callback` could destroy the same node concurrently, so the
"parallel tasks own disjoint stream names" invariant became load-bearing for
memory safety rather than just for correctness.

Move all of it into a `FileStreams` holder owning both containers and the
mutex. `getOrCreate` runs the stream factory with the mutex released, because
creating a stream schedules a marks load that blocks when the pool queue is
full. `release` drops the stream outside the lock, because
`~MergeTreeMarksLoader` waits for an in-flight load. Values are `shared_ptr`,
so a stale erase can no longer free a stream another task is reading. Folding
`prefetched_streams` into the same holder removes the last unguarded container
access, and every call site is one line again with no locking commentary.

With the reader's callbacks genuinely thread safe, the serialization layer
needs no fallback: drop `callbacks_mutex`, the six `safe_*` wrappers and the
`wrap_callbacks` branch from `SerializationObject`, and the
`prefix_deserialization_callbacks_are_thread_safe` flag from `ISerialization`.
`MergeTreeReaderWide` is the only in-tree producer of
`prefixes_deserialization_thread_pool`, so with the flag always set that code
was unreachable and untested. The contract is now stated once on the pool
field itself. This also removes the TSAN lock-order-inversion between nested
stack-local mutexes, which existed only because of the coarse mutex.

`seek_stream_to_mark_callback` used a non-const `operator[]` that would insert
a null `unique_ptr` and dereference it if the stream were missing; it now
throws `LOGICAL_ERROR`.

04864 passes unchanged, with the sync arm at ratio 1.46 against its 1.15
threshold (1.00 when marks loading is serialized).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Avogar

Avogar commented Sep 11, 2026

Copy link
Copy Markdown
Member

@groeneai I reworked the fix

@groeneai

Copy link
Copy Markdown
Collaborator Author

Checked 63d3fdbc on a debug build (assertions active): 04864 passes, all four arms.

Mutation arm, so that pass is not vacuous on the new structure: holding one mutex across MergeTreeReaderWide::getStream, which is the shape of the original regression, reddens every arm (sync ratio 1.00, async/prefetch/queue 0.99) while the preconditions stay green. The oracle keys on real overlap, not on the old code shape.

I also re-checked the riskiest deletion: MergeTreeReaderWide.cpp:446 is the only in-tree assignment of prefixes_deserialization_thread_pool, so the safe_* fallback in SerializationObject was indeed unreachable.

I updated the PR description to match your implementation; it still described the flag plus narrowed-mutex version.

…s invariant

Review pointed out that the `shared_ptr` in `FileStreams` did not buy the
lifetime guarantee it was supposed to. `getStream` drops its own reference on
return and hands the caller a bare `ReadBuffer *`, so a concurrent
`release` would still destroy the stream under an in-flight read. The
guarantee held for the short uses that keep the pointer for their whole
duration and lapsed for the longest one, which is worse than not claiming it:
the safety of element access rests on parallel tasks owning disjoint stream
names, and that is the only thing worth writing down.

So go back to `unique_ptr` in the map and return `MergeTreeReaderStream *`,
which also keeps this reader consistent with `IMergeTreeReader::FileStreams`
and `MergeTreeReaderCompact`, and drops an atomic refcount pair from every
lookup in the read path. `release` still moves the stream into a local
declared before the lock guard, so it is destroyed after the mutex is
released, because `~MergeTreeMarksLoader` waits for an in-flight marks load.

The invariant comment now states its full scope: a stream, and any
`ReadBuffer` taken from it, stays valid until the owning task calls
`release`. That is the window the review flagged, and it is unchanged from
`master`, where the coarse mutex did not cover the buffer read either.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Re-measured on 77331df8, since my note above was against 63d3fdbc.

04864 passes, 13/13 lines. Mutation arm on the new structure, so that is not a vacuous pass: one process-wide mutex held across MergeTreeReaderWide::getStream reddens every arm (sync 1.00, async and prefetch 0.99, queue 0.98) with the preconditions still green. Going back to unique_ptr did not cost the property, and the oracle is not keyed to either code shape.

On the lifetime window, the claim that it is unchanged from master holds. On master safe_getter takes callbacks_mutex, calls settings.getter(path) and returns the bare ReadBuffer *, so the lock is already gone before the caller reads from that buffer, while safe_release_stream_callback destroys the stream under the same mutex. The window is pre-existing, not introduced here. What closes it in both versions is the disjointness the new comment states, and that checks out: sorted_dynamic_paths is built by iterating a map so it holds no duplicates, the tasks take disjoint index ranges of it, ObjectDynamicPath appends the escaped path name to every stream name (ISerialization.cpp:403), and release_stream_callback fires from the task that owns the path.

I refreshed the PR description to match this head.

…two builds

The arm ran a second clickhouse-local instance with
load_marks_threadpool_queue_size = 50 and asserted
WaitMarksLoadMicroseconds / query_duration_ms > 1.15.

That ratio is a one-sided witness only. When marks-load waits never overlap
their sum cannot exceed the query duration, so a build that holds one mutex
across MergeTreeReaderWide::getStream is pinned at ratio <= 1 (measured 0.99
with such a mutex added on top of this head). The converse does not hold: with
a queue shorter than the number of loads, ThreadPool::scheduleImpl blocks the
scheduling thread on job_finished, that block is not accounted as marks-load
wait, and it also delays the consumer past the completion of its own load, so
the accounted wait shrinks while the duration grows. On a correct build the
ratio then lands in the same region: CI measured 0.45 to 1.15 for this arm on
this head across 26 flaky-check runs, 11 of them below the 0.99 that the
serialized build produces, while the same arm reports 5.2 to 5.9 on an idle
384-core box. No threshold separates the two builds, so the arm was reporting
a serialization regression on a build that has none.

The three arms of the first instance keep the coverage. They redden on the same
serialized build (sync 1.00, async 0.98, prefetch 0.99), and their numerators
are dominated by the injected sleeps rather than by machine speed: 8 copies
pinned to 4 CPUs give sync 1.46 (duration 16459 to 16468 ms), async 13.8 to
15.1 and prefetch 9.2 to 9.9 against the same 1.15 threshold. 50 runs of the
trimmed test at 10-way self-parallelism pass, 12 copies pinned to 4 CPUs pass,
and the serialized build still fails on all three arms.

The removed configuration also needs a non-default
load_marks_threadpool_queue_size: the default is 10000, raised to at least
max_threads, so a query would need more than 10000 pending marks loads to reach
the blocking path the arm aimed at.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 8fcf9825, test only: I removed the fourth arm of 04864, the second clickhouse-local instance with load_marks_threadpool_queue_size = 50.

It was the only failing line in all 26 flaky-check failures at 77331df8 (amd_binary 7, amd_tsan 6, amd_debug 6, amd_asan_ubsan 6, amd_msan 1; printed ratios 0.45 to 1.15), and its oracle cannot separate the two builds:

  • WaitMarksLoadMicroseconds / query_duration_ms > 1.15 is a one-sided witness. When marks-load waits never overlap their sum cannot exceed the query duration, so a build holding one mutex across getStream is pinned at ratio <= 1, which is the 0.98 I quoted for this arm above.
  • With the queue shorter than the number of loads, ThreadPool::scheduleImpl blocks the scheduling thread on job_finished. That block is not accounted as marks-load wait, and it also delays the consumer past the completion of its own load, so the accounted wait shrinks while the duration grows. 11 of the 26 CI values sit below 0.98, that is below what the serialized build produces, so no threshold separates the two.

I could not reproduce those values locally: 82 runs here, up to 40 copies pinned to a single CPU, kept the arm between 2.14 and 7.39. Its margin is a property of the machine, not of the code under test, which is what makes it unusable rather than merely noisy.

The three remaining arms are not machine-speed sensitive, because their numerator is the injected sleep and not the elapsed work: 8 copies pinned to 4 CPUs give sync 1.46 (duration 16459 to 16468 ms), async 13.8 to 15.1 and prefetch 9.2 to 9.9 against the same 1.15 threshold, and one mutex across getStream still reddens all three (1.00, 0.98, 0.99). 50 runs at 10-way self-parallelism pass, as do 12 copies pinned to 4 CPUs, with no leftover temp directories.

The removed configuration also needed a non-default load_marks_threadpool_queue_size: the default is 10000, raised to at least max_threads, so reaching that blocking path takes more than 10000 pending marks loads in one query.

@groeneai

Copy link
Copy Markdown
Collaborator Author

prefetch went red again at 8062beae, so I took the fallback I offered above

One failure in 50 runs of Stateless tests (amd_asan_ubsan, flaky check); the other four flaky-check
jobs were 50/50 clean. The prefetch arm printed 0.86 after drawing 1.046 and 0.804 on its two
retries. Its numerator held at 4.5 to 5.3 s across all three draws while the query duration went from
about 0.5 s at rest to 5.1 to 5.6 s, so the term that moved is the denominator, not the concurrency
the arm is there to witness.

The arms are not equally exposed to that, and the reason is structural rather than a matter of
margin. async waits on background loads, so a machine that slows the query down slows the loads it
is waiting for with it and contention lands in both terms of the ratio at once. In sync and
prefetch each consumer waits for its own load, while the duration additionally carries the query's
data-stream reads, serial in sync and prefetched in prefetch, which inflate on their own. With 16
copies of the measurement pinned to 4 CPUs: async 13.53 to 14.98, prefetch 8.05 to 9.99, sync
1.461 to 1.465. In CI async has never missed the threshold at any head of this PR, sync missed at
8fcf9825 and prefetch at 8fcf9825 and again here.

Pushed d33ba14, test file only: the ratio is asserted for async alone. sync and prefetch still
run and keep their deterministic checks, the measurable marks-load wait, the scheduled background
loads and the prefix-prefetch count, so both code paths stay covered under every sanitizer; they no
longer carry a timing verdict. Threshold, fixture and the bounded re-measurement are unchanged. The
description is updated to match.

I did not retune the threshold (0.804 and 0.86 sit below the 1.0 a serialized build cannot cross, so
no value separates the two builds), did not add retries (that run already spent 109.3 s of the 180 s
per-test ceiling the job enforces) and did not add no-parallel. Replacing the ratio with a
deterministic max-concurrency oracle from system.opentelemetry_span_log does not work either: a
trace is started only by the server handlers, never by clickhouse-local, so the span log stays
empty.

Both directions on this head: the fix passes in 20.2 s; the serialized mutation still fails on the
async arm at 0.98 with both retries spent; forcing the in-query measurement to miss on a correct
build has the retries restore the verdict byte-identically; 50 runs in 5 waves of 10-way
self-parallelism pass 50 of 50.

Session id: cron:clickhouse-maint-slot-14:20260912-030800

04357 drives the nested prefix pass without prefetching and 04864's JSON is flat,
so prefixes_prefetch_callback has only ever run from the outer level's pass, on
the reader thread. It is the one caller of the reader's callbacks that no test
invokes from a prefix pool task, which is where it has to be thread safe now that
SerializationObject does not wrap the callbacks under a mutex of its own.

The added read prefetches prefixes over two array-of-object paths. Measured at
this head: 29 prefetch submissions, 13 of them from 8 PrefixReader threads, two
for substreams that exist only below a nested object. Clearing
settings_copy.prefixes_prefetch_callback in the pool task, so the nested level
stops invoking it, turns the new assertion red and leaves the rest of the test
green.

The arm gets its own table, reads it exactly once, and pins the part layout: a
column the earlier queries already read is served from the uncompressed cache and
is then never prefetched at all, while packed part storage, long file name hashing
and a remote disk each change what the prefetches log records for a substream.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Added the nested prefix-prefetch coverage in 82b4f74: 04357 now does one prefetching read over a table with two array-of-object paths.

The gap was real. prefixes_prefetch_callback has a single call site, the enumeration pass in SerializationObject::deserializeBinaryBulkStatePrefix, and that pass runs before the pool tasks are scheduled, so it reaches a pool task only through a nested object's own prefix pass. 04864's JSON is flat, so measured there: 119 prefetch submissions, none for a nested substream. The new arm submits 29, of which 13 come from 8 PrefixReader threads and 2 are for substreams that exist only below a nested object.

One correction to the premise, because it moves where the safety argument sits: deserializePrefixForAllColumnsImpl inserts caches[<column>] before it builds the callback, so a lookup inside the callback finds an existing key. The column_cache capture removes a non-const operator[] on a shared map, not an insert; what makes the callback safe is FileStreams' own mutex plus tasks owning disjoint stream names.

The arm asserts that a substream below the nested object was prefetched, and deliberately not which thread did it: trySchedule failure is ignored and the caller executes tasks itself through tryExecute, so with a one-thread prefixes pool the nested callback still runs while nothing is submitted from a PrefixReader thread. Asserting the thread would report a correct build as broken.

Verification: 50/50 with randomization under self-parallel load; clearing settings_copy.prefixes_prefetch_callback in the pool task, so the nested level stops invoking it, turns the new assertion red 3/3 and leaves every other line green; local_filesystem_read_prefetch = 0 and a synchronous read method each turn it red too. The arm has its own table, read exactly once, with the part layout pinned, because the uncompressed cache, packed part storage, long file name hashing and a remote disk each remove what the prefetches log would otherwise name.

Session id: cron:clickhouse-maint-slot-13:20260912-044000

The `async` arm of 04864_json_prefix_deserialization_marks_load_not_serialized
turned red in `Stateless tests (amd_asan_ubsan, flaky check)` at 82b4f74, 1 run
of 50, on its wait precondition. That line had never flipped before:

    -async: marks-load wait is measurable
    +async: UNEXPECTED: no marks-load wait, failpoint did not fire

The precondition asserted an absolute floor, WaitMarksLoadMicroseconds > 1 s, on
all three arms, but only the synchronous arm can make that statement. There the
marks are loaded on the thread that waits for them, so the measured window
contains the injected 100 ms sleep itself. An asynchronous arm waits on a
background load, so the same counter measures only what is left of that load once
its consumer reaches it, which a co-scheduled machine drives towards zero with the
failpoint firing exactly as before.

Measured on the test's own fixture (240 marks loads, so 24.0 s of injected sleep):

    perturbation           sync             async            prefetch
    at rest                24.06 s          12.36 s           9.44 s
    marks pool 50 -> 400   24.06 s           7.86 s           4.66 s
    12 copies, 4 CPUs      24.05 - 24.22 s  12.35 - 13.86 s   7.74 - 10.01 s

The synchronous arm observes 100% of the injected sleep under every perturbation,
to within 0.7%. The two asynchronous arms observe 32-51% of it and move whenever
the schedule moves. The CI run that failed observed under 4%.

So the floor stays on the arm that owns it, which is enough for the other two: the
failpoint is process-global and stays enabled across all three arms. The
asynchronous arms keep the BackgroundLoadingMarksTasks check, which is what proves
they loaded marks at all, and the retry's copy of the wait floor becomes that same
check, so a starved re-measurement no longer abandons the remaining budget.

The floor still catches a failpoint that stopped firing: without it the
synchronous arm waits 9.7 ms against the 1 s floor, and deleting the SYSTEM ENABLE
FAILPOINT statement reddens the test on the sync line.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Moved 04864's marks-load wait floor onto the arm that measures the injected sleep, in aa076eb. The flaky check at 82b4f74 failed 1 run of 50 on the wait precondition, which had never flipped before:

-async: marks-load wait is measurable
+async: UNEXPECTED: no marks-load wait, failpoint did not fire

The precondition asserted WaitMarksLoadMicroseconds > 1 s on all three arms, but only sync can make that statement. It loads marks on the thread that waits for them, so its measured window contains the injected 100 ms sleep itself. An asynchronous arm waits on a background load, so the same counter measures only what is left of that load once its consumer reaches it, and a co-scheduled machine drives that towards zero with the failpoint firing exactly as before. On the test's own fixture, 240 marks loads means 24.0 s of injected sleep:

perturbation sync async prefetch
at rest 24.06 s 12.36 s 9.44 s
marks pool 50 -> 400 24.06 s 7.86 s 4.66 s
12 copies on 4 CPUs 24.05 - 24.22 s 12.35 - 13.86 s 7.74 - 10.01 s

sync observes 100% of the injected sleep under every perturbation, to within 0.7%. The asynchronous arms observe 32-51% of it and move whenever the schedule moves; the CI run that failed observed under 4%. One attestation is enough for all three arms, since the failpoint is process-global and stays enabled across them.

The asynchronous arms keep the BackgroundLoadingMarksTasks check, which is what proves they loaded marks at all, and the retry's copy of the wait floor becomes that same check, so a starved re-measurement no longer abandons its remaining budget. Threshold, fixture, arms and retry count are unchanged, and this is test-file only.

Verification: the serialized mutation still fails on the async ratio (0.97-0.99, both retries spent); deleting SYSTEM ENABLE FAILPOINT reddens the test on the sync line, so the floor still catches a failpoint that stopped firing; forcing the in-query threshold to 99 makes the retry reproduce the reference byte for byte; removing the retry arm's background loads makes the new check refuse a measurement whose ratio of 1.46 would otherwise have passed; 50/50 under self-parallel load, and 12/12 with 12 copies pinned to 4 CPUs.

Local starvation still does not reproduce the sub-second draw itself: the minimum async wait over 12 pinned copies was 12.35 s. That is now a sixth recorded non-reproduction, and it is the reason the floor is argued from which arm owns the sleep rather than from a re-tuned constant.

Session id: cron:clickhouse-maint-slot-13:20260912-080900

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - aa076eb

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: Virtual row has different type for A. Expected B, got C (STID 1637-309b) trunk regression, not caused by this PR: 74 CIDB rows across 71 distinct pull requests and 2 true-master runs in 30 days, onset 2026-09-10 16:22Z, on Upgrade check (amd_release) and Stress test (*) across every arch #119385 (mine, merged 2026-09-12 10:39Z), merged master @ 4eb4dfc0c3f2 to pick it up
Sync - CH Inc sync (private, not actionable by me)

The failing tree predates the fix, measured rather than inferred: the needle sorting_key_types
in src/Storages/ReadInOrderOptimizer.cpp reads 0 at aa076ebf and 2 at the new head, with the
pre-fix negative control 0, the at-fix positive control 2 and live master 2. Mergeable Check named
Upgrade check (amd_release) as the sole gating blocker, so master was merged instead of only
naming the owner. Nothing of mine was dropped: compare(aa076ebf...4eb4dfc0) is ahead, behind_by 0.

Session id: cron:our-pr-ci-monitor:20260912-143024

@Avogar

Avogar commented Sep 14, 2026

Copy link
Copy Markdown
Member

@groeneai fix the conflicts

…-deserialization

One conflict, in src/Storages/MergeTree/MergeTreeReaderWide.cpp: master's
56f22cc ("Don't load marks and don't prefetch data of streams with an empty
data file") edits the stream-construction body that this branch moved into the
factory passed to `FileStreams::getOrCreate`, so both of its parts are applied
inside that factory: the `data_file_size` hoist, and the `data_file_size != 0`
guard around `marks_loader->startAsyncLoad()`. Construction stays outside the
streams mutex, which is what this branch fixes.

Its other two changes (the empty-file early return in `prefetchForColumn`, and
`partially_read_columns_are_refilled` in `readData`) merged into this branch's
rewritten bodies without conflict and are kept as master has them.

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

Copy link
Copy Markdown
Collaborator Author

Conflicts resolved by merging master 6b982cac in 56c5e7ed; the PR is mergeable again.

One conflict, in MergeTreeReaderWide.cpp: master's 56f22cc75527 ("Don't load marks and don't prefetch data of streams with an empty data file") edits the stream-construction body that this branch moved into the factory passed to FileStreams::getOrCreate. Its data_file_size hoist and the data_file_size != 0 guard around startAsyncLoad() are applied inside that factory, so construction still runs outside the streams mutex. The same commit's other two edits (the empty-file early return in prefetchForColumn, and partially_read_columns_are_refilled in readData) merged into the rewritten bodies with no conflict and are kept as master has them.

Checks on the result: it differs from the previous head by exactly those three edits, and from master by exactly this PR's ten files. Debug build is clean, and 04864 plus 04357 pass 10/10 each locally with settings randomization on.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 56c5e7e

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
AST fuzzer (amd_debug, targeted) / Server unresponsive: memory limit exceeded infra: the server alone reaches the RSS cap it derives for itself and rejects a system-log flush with Code: 241. 62 rows / 26 PRs / 3 true-master in 30 days, and two other carriers hit it within 2 hours of this run #118467 (external, open)
Build profile diff infra: RuntimeError: CI logs cluster query failed after two ReadTimeoutErrors against the CI logs cluster, and the job fails closed. 33 unrelated PRs hit the same error in the same 4-hour window #118708 (ours, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

Nothing on this head is attributable to this PR's diff. Bugfix validation (functional tests, amd64/aarch64) does publish a FAIL row for 04357_json_nested_prefixes_deserialization_pool
while both job conclusions are success: that check inverts its status, so a raw FAIL row
there is the wanted direction for a bugfix PR.

Session id: cron:our-pr-ci-monitor:20260915-003145

…tex-across-marks-load-in-json-prefix-deserialization
The arm enables local_filesystem_read_prefetch and then asserts one prefetch per
dynamic path in system.filesystem_read_prefetches_log, but it left
local_filesystem_read_method at its default. That default is only conditionally
'pread_threadpool': applySettingsQuirks switches it to 'pread' when
preadv2(RWF_NOWAIT) is unavailable - an old kernel, a filesystem answering
EOPNOTSUPP, or a container runtime whose seccomp profile rejects the system call -
and clears the changed flag, so the substitution reads as the default. A
synchronous method then builds ReadBufferFromFilePReadWithDescriptorsCache, which
is not given the prefetches log and whose prefetch() is the ReadBuffer no-op, so
the log stays empty and the assertion reports a count of zero for a property of
the host rather than a regression.

Measured on this head with the method forced to the value the quirk picks:
'UNEXPECTED prefix prefetch count: 0', every other line unchanged. Pinning is safe
where the quirk would have fired, because ThreadPoolReader::submit gates only its
page-cache fast path on the probe and otherwise hands the read to the pool. On a
host where the default already holds, the arm is unchanged: 10/10 both before and
after.

Same pin, for the same reason, as 04357_json_nested_prefixes_deserialization_pool.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed e7a48e1 on top of the master merge: one setting added to 04864's prefetch arm, local_filesystem_read_method = 'pread_threadpool'.

Why it is not cosmetic. That arm asserts one prefetch per dynamic path in system.filesystem_read_prefetches_log, but the default read method is only conditionally pread_threadpool: applySettingsQuirks swaps it for pread when preadv2(RWF_NOWAIT) is unavailable (kernel older than 5.11, a filesystem answering EOPNOTSUPP, or a container runtime whose seccomp profile rejects the call) and then clears the changed flag, so it reads as the default. A synchronous method leaves prefetch() as the ReadBuffer no-op with no prefetches log attached. Forcing that value locally reproduces UNEXPECTED prefix prefetch count: 0 on 3/3 runs, so the test would have gone red for a property of the host rather than a regression. It has not fired in CI (2536 OK rows in 30 days, and no CIDB row anywhere carries that line), and behaviour here is unchanged: 10/10 both before and after. 04357 already pins the same setting for the same reason.

One thing I did not change, and it is your call. The arm labelled sync never sets load_marks_asynchronously = 0, and the default is true, so it measures BackgroundLoadingMarksTasks = 160 and is not in fact synchronous. Its wait-floor assertion is still live, since deleting the SYSTEM ENABLE FAILPOINT statement reddens that line and the no-failpoint wait is 9.7 ms against a 1 s floor, so this is a matter of accuracy and not a dead oracle. The fix is one setting plus a correction to the comment above it, and I would rather not re-tune a timing arm on a PR you have approved without your agreement. I will push it if you want it.

-- carries the overlap verdict at the end of this query; the other two run for the code paths they
-- reach and for the deterministic checks below.
SELECT count() FROM (SELECT j FROM t LIMIT 1)
SETTINGS merge_tree_use_prefixes_deserialization_thread_pool = 1, log_comment = 'sync'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

load_marks_asynchronously defaults to true (src/Core/Settings.cpp), so this arm is still running with background marks loads enabled. That means 04864 no longer exercises the pure synchronous loadMarksSync path it claims to cover, and the "only sync can attest the injected sleep" argument below is no longer true for the query that is actually executed here.

If a later change reintroduced the convoy only for load_marks_asynchronously = 0, this test would stay green. Please pin load_marks_asynchronously = 0 in the sync arm and keep the nearby comments / reference output aligned with the actual mode under test.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Premise confirmed, and quantified. In query_log for that arm, unpinned: LoadedMarksFiles = 160, BackgroundLoadingMarksTasks = 160, WaitMarksLoadMicroseconds = 10.43 s, so 65.2 ms per load. With load_marks_asynchronously = 0: same 160 files, BackgroundLoadingMarksTasks = 0, wait 16.04 s, so 100.3 ms per load, which is the injected sleep itself to within 0.3%. The failpoint sleeps at the top of loadMarksSync, and loadMarksAsync's pool task calls that same function, so the sleep fires either way and only the place it is counted changes. Unpinned, the arm measures 65% of a sleep that is already running on a pool thread, which is what the comment further down says an asynchronous arm measures.

The comment was accurate when it was written. load_marks_asynchronously became true in 26.9, and it reached this branch through my own master merge 4eb4dfc0, a month after the arm and that comment were written in aa076ebf. It is also invisible in query_log: Settings['load_marks_asynchronously'] is empty for the arm, because the value is the default rather than a set one.

What I could not confirm is the consequence. The reason to treat this as urgent would be a fragile floor, so I tried to break it: restricted to a single core, three runs hold at 10.68 s, 10.77 s and 10.68 s against the 1 s floor, the same margin as unrestricted. taskset starves the loaders and the consumers equally, and a consumer here calls loadMarks immediately after startAsyncLoad, so there is no window in which the background loads finish first. No red is latent. The real content is your coverage point: nothing in this test exercises inline loadMarksSync, and a regression confined to load_marks_asynchronously = 0 would stay green, which is the mode that was the default up to 26.8.

The pin costs more than it looks, which is why I am not just taking it. The 160 injected sleeps stop overlapping across the 50-thread marks pool and run inline, so the arm goes from 614 ms to 8.45 s and the whole test from 3.6 s to 11.3 s, a factor of 3.1. The change is written and verified anyway: 10/10 with the pin, and the oracle stays live, since with the failpoint off the pinned arm waits 8 ms and the floor still reddens. It needs no edit to the comment below, because the pin makes that comment true as written.

A 3x test-cost change on an approved PR is the reviewer's call and not mine to spend, and the same question has been open on this PR since earlier today, now with the number attached. I will push it as soon as it is wanted.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e7a48e1

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
Build profile diff job-level RuntimeError: CI logs cluster query failed: SELECT count() AS c FROM binary_sizes, raised in has_pr_data at ci/jobs/build_profile_diff_job.py:723: the readiness probe collapses every non-ok response into a bare False, so a transient CI logs cluster refusal is fatal and the job prints a single opaque line. Not reachable from this diff: the job only reads binary_sizes on the logs cluster. Measured 137 red heads across 123 distinct pull requests since 13:14Z today and 204 error rows in 7 days; the job runs on pull requests only, so there is no master arm #120121 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

PR is the workflow rollup of the rows above, not an independent failure. No test-level failure was
ingested for this head; the two Bugfix validation (functional tests, *) rows for
04357_json_nested_prefixes_deserialization_pool are that job asserting the new test fails without
the fix, and both of its jobs are green.

Session id: cron:our-pr-ci-monitor:20260915-213215

@Avogar
Avogar added this pull request to the merge queue Sep 17, 2026
Merged via the queue into ClickHouse:master with commit fda9f2f Sep 17, 2026
175 of 177 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 17, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 4, 2026
Conflicts, all context-only:
- SerializationVariant.cpp, SerializationVariantElement.cpp: 26.8 has
  `clone()` without the clone context (ClickHouse#126298 is not in 26.8); keep it and
  add only the copies of the new `variant(s)_absent_in_storage` flags.
- MergeTreeReaderWide.cpp: 26.8 has `addStream`, not
  `FileStreams::getOrCreate` (ClickHouse#114252 is not in 26.8); add only the new
  `isReadWithTypeInPart` before it.

Semantic fix: `IMergeTreeReader::hasSubcolumnInPart` (ClickHouse#120632) is not in
26.8, so `isReadWithTypeInPart` uses `type->hasSubcolumn`, as the 26.8
readers already do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 4, 2026
Conflicts, all context-only:
- SerializationVariant.cpp, SerializationVariantElement.cpp: 26.9 has
  `clone()` without the clone context (ClickHouse#126298 is not in 26.9); keep it and
  add only the copies of the new `variant(s)_absent_in_storage` flags.
- MergeTreeReaderWide.cpp: 26.9 has `addStream`, not
  `FileStreams::getOrCreate` (ClickHouse#114252 is not in 26.9); add only the new
  `isReadWithTypeInPart` before it.

Semantic fix: `IMergeTreeReader::hasSubcolumnInPart` (ClickHouse#120632) is not in
26.9, so `isReadWithTypeInPart` uses `type->hasSubcolumn`, as the 26.9
readers already do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
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-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

4 participants