Skip to content

Skip the custom-key parallel replicas read when the requested stage cannot absorb finalized data - #113742

Merged
alexey-milovidov merged 3 commits into
masterfrom
fix/merge-custom-key-child-stage
Aug 12, 2026
Merged

alexey-milovidov merged 3 commits into
masterfrom
fix/merge-custom-key-child-stage

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 6, 2026 •

Copy link
Copy Markdown
Member

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):

Fix CANNOT_CONVERT_TYPE and an exception in GroupingAggregatedTransform when reading a Merge table with one child being a Distributed table under custom-key parallel replicas (parallel_replicas_mode = 'custom_key_sampling' or 'custom_key_range'). Closes #113741.

Documentation entry for user-facing changes

The custom-key parallel replicas branch of the planner replaces the plan of a table expression with a remote read at the fixed stage WithMergeableStateAfterAggregationAndLimit, ignoring the stage the plan was requested up to. A Merge table over a Distributed child plans all of its children up to WithMergeableState through an interpreter, so a MergeTree child's plan produced finalized (post-aggregation, post-LIMIT) data where the parent ReadFromMerge expected partial aggregation states: CANNOT_CONVERT_TYPE for count, and the exception Chunk should have AggregatedChunkInfo/ChunkInfoWithAllocatedBytes in GroupingAggregatedTransform when the finalized type structurally coincides with the state type. Only the analyzer path is affected.

The fix allows the custom-key read only when the requested stage is Complete or WithMergeableStateAfterAggregationAndLimit itself; a child planned to a partial stage now runs as a plain local read, as it does when parallel replicas are off.

Found by the targeted AST fuzzer on #110972, where it is unrelated: the failure reproduces on master without parallel_replicas_allow_merge_tables (verified on a binary with that PR's changes swapped out to the merge base). Fuzzer report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110972&sha=ac0a584ce316ace31f4dbc16b38e1262a2344751&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 (STID 3970-479a).

Closes: #113741
Related: #110972

Version info

  • Backported to: 26.7.4.29, 26.6.3.42, 26.5.7.52, 26.3.18.31, 25.8.30.19

…annot absorb finalized data

The custom-key parallel replicas branch of the planner replaces the plan of a
table expression with a remote read at the fixed stage
`WithMergeableStateAfterAggregationAndLimit`, ignoring the stage the plan was
requested up to. A `Merge` table over a `Distributed` child plans all of its
children up to `WithMergeableState` through an interpreter, so a MergeTree
child's plan produced finalized (post-aggregation, post-LIMIT) data where the
parent `ReadFromMerge` expected partial aggregation states:
`CANNOT_CONVERT_TYPE` for `count`, and the exception `Chunk should have
AggregatedChunkInfo/ChunkInfoWithAllocatedBytes in GroupingAggregatedTransform`
when the finalized type structurally coincides with the state type. Allow the
custom-key read only when the requested stage is `Complete` or
`WithMergeableStateAfterAggregationAndLimit` itself.

Found by the targeted AST fuzzer on #110972 (an unrelated PR):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110972&sha=ac0a584ce316ace31f4dbc16b38e1262a2344751&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

Closes: #113741

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

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ea4a1f8]

Summary: ✅


AI Review

Summary

This PR narrows the analyzer-side parallel_replicas_custom_key shortcut so it no longer replaces a child plan with a stage-4 remote read when the caller asked for a lower processing stage, and it adds a focused stateless regression test for the merge()/Distributed reproduction from #113741. I did not find a remaining correctness, safety, or metadata issue in the current diff.

Final Verdict

✅ No actionable review findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · 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 6, 2026
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit ea4a1f8 - the build was skipped, reused from cache, or predates profile upload.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update:

  • Merged master into the branch (no conflicts) and re-ran the PR's test 04815_parallel_replicas_custom_key_merge_distributed_child on the merged branch locally — passes.
  • The AI review blocker about dropped additional_table_filters / row policies is refuted empirically on a 3-replica loopback cluster (details and measurements on the review thread); the thread is resolved. While verifying it, the unmerged bare-aggregate results of the custom-key path showed up — that is the known pre-existing issue Custom key parallel replicas wrong result for count() #50593, unrelated to this gate.
  • The only red check, Stress test (amd_asan_ubsan) "Hung check failed, possible deadlock found", is unrelated to this PR: the hung query is from test 04010_text_index_incompelete_granules (hasToken over a text index), stuck ~978 s in MergeTreeMarksLoader::loadMarks waiting for asynchronous skip-index mark loading, with the loading thread grinding through tiny filesystem-cache reads and send_logs_level=test logging under ASan + ThreadFuzzer (WaitMarksLoadMicroseconds ≈ 709 s, LoggerElapsedNanoseconds ≈ 663 s). No contact with the planner change; this "Hung check failed" test name fails on dozens of unrelated PRs and on master daily (10–67 failures/day over the last week per CI DB).

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113742&sha=f7d93499dfda46c29fed32cb0d05236fdb3d8883&name_0=PR&name_1=Stress%20test%20%28amd_asan_ubsan%29 (text-index async mark loading effectively livelocking a query for ~16 minutes under sanitizers — 04010_text_index_incompelete_granules) and provide a fix in a separate PR. If the fix is already in progress, link it here. I found no open issue tracking it.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator

Investigated. That hung check is not caused by your change, and it is two separate defects rather than one. I re-derived the numbers from the job log for f7d93499d (the S3 report and result_*.json are 403 for me; the log is the source below).

The processlist snapshot at 02:31:45 shows elapsed 978.06, is_cancelled 1, read_rows 0, max_execution_time randomized to 60. So the query was already cancelled and kept running for 918 s = 15.3 min past its own deadline. Splitting the cost:

elapsed 978.06 s
WaitMarksLoadMicroseconds 708.90 s (72.5%)
LoggerElapsedNanoseconds 663.14 s, 93.5% of that wait
wait minus logger 45.76 s

1. The 918 s of unkillable wait: my open PR #113436. The two threads are the query thread in future::get under MergeTreeMarksLoader::loadMarks, reached via MergeTreeIndexReader::initStreamIfNeeded <- MergeTreeIndexReader::read <- filterMarksUsingIndex; and the marks pool thread inside ReadBufferFromRemoteFSGather::readImpl, reached from seek -> ReadBuffer::ignore (src/IO/ReadBuffer.h:103). #113436 puts a throwIfKilled in exactly that readImpl, and opts in exactly at filterMarksUsingIndex, the frame in this stack. is_cancelled in system.processes is the same is_killed that check reads (src/Interpreters/ProcessList.cpp:871), and the pool thread does see it because threadPoolCallbackRunner installs a ThreadGroupSwitcher. So this artifact is a direct carrier for that PR. With that checkpoint the pool thread unwinds at its next buffer fill instead of finishing the load, which is what removes the 918 s overshoot; it does not make the load itself faster.

2. The 663 s itself is log amplification, and that half has no PR yet. The pool thread's stack top is LOG_TEST at CachedOnDiskReadBufferFromFile.cpp:1522 ("Reading file segment: {}") -> OwnSplitChannel -> Poco::FileChannel::log -> mutex -> ThreadFuzzer injection. LogTest is 272839 against 136390 cached reads, i.e. exactly 2.000 messages per read, at 2.43 ms each. stress_runner.sh rewrites <level>trace</level> to <level>test</level>, and this run drew Async logging: 0, so both message construction and the sink mutex are on the reading thread. Cancellation alone does not remove this, because it is the reason a load of a single 96-byte mark takes 709 s in the first place. If the query is never killed, the hung check still fires.

I am opening a separate PR for the logging half and will link it in this thread. Note it is not specific to text indexes or to the filesystem cache. It is LOG_TEST with eagerly evaluated arguments in a hot read loop, so it inflates any level=test stress run.

Two smaller things worth recording:

  • This signature is invisible to the CI DB. The row for this sha exists, but its test_context_raw is truncated at 32473 bytes with zero occurrences of MergeTreeMarksLoader::loadMarks, WaitMarksLoad or 04010_text_index_incompelete_granules. The evidence is past the cut, so the stack is only in the job log.
  • On breadth I would not use the Hung check failed name: it is a symptom bucket. Keyed on the marks-loader frame instead, 30 days gives 134 rows / 15 PRs / 2 master, and 119 of those 134 rows are one PR (108443, 3 shas), and every other PR contributes exactly one. Keyed on that bucket the same window gives 625 rows / 392 PRs / 115 master, about 4.7x wider and mostly unrelated causes.

There is also a third, smaller axis in this artifact: 6851617 bytes were read to obtain a single 96-byte mark. That read amplification is the subject of my open #112644, but that PR clamps PackedFilesReader::patchSettings while this read reaches the packed member through DataPartStorageOnDiskPacked's own buffer creator, so I am not claiming it covers this one.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator

The logging half is now open as #113885.

It removes the four LOG_TEST statements in the cache-hit read path of
CachedOnDiskReadBufferFromFile: two fired unconditionally per buffer refill in
readFromFileSegment, a third per refill in the tail-batch resize branch, and a fourth on the
readBigAt path. On the artifact from this PR those two unconditional lines are 272,762 of the
272,839 LogTest messages (99.972%), against 136,381 cached reads.

The cost is message construction rather than sink throughput, so no log limiter removes it:
LOG_IMPL bumps the counter, evaluates the format arguments, builds the message and constructs a
Poco::Message before the channel is reached. Each of these also evaluated getInfoForLog, which
takes the FileSegment mutex.

Scope is deliberately narrower than the class, and I measured the boundary instead of asserting it:
the download path still logs per refill from prepareReadFromFileSegmentState and the FileSegment
downloader lifecycle. On the fixed binary a cold run logs 29,293 messages over 4,854 misses while
the warm run logs 115 over 5,005 hits, and the query in this artifact was a warm read (136,380 hits
against 1 miss), so the cache-hit path is the one that mattered.

Same shape as #111546, which removed the equivalent per-block logging from
CompressedReadBufferFromFile.

The other two axes visible in that artifact are not in this PR, one concern per PR. The
cancellation overshoot is #113436, already open. The read amplification is adjacent to #112644 but
not covered by it, as noted above.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update:

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good.

@alexey-milovidov alexey-milovidov self-assigned this Aug 11, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 11, 2026
Merged via the queue into master with commit 14898bd Aug 12, 2026
181 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix/merge-custom-key-child-stage branch August 12, 2026 00:40
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 12, 2026
@nickitat nickitat added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Aug 13, 2026
@nickitat

Copy link
Copy Markdown
Member

Added the backport label in response to the bot's demand: #113741 (comment)

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 13, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 13, 2026
…when the requested stage cannot absorb finalized data
clickhouse-gh Bot added a commit that referenced this pull request Aug 13, 2026
Backport #113742 to 26.7: Skip the custom-key parallel replicas read when the requested stage cannot absorb finalized data
robot-ch-test-poll3 added a commit that referenced this pull request Aug 14, 2026
Cherry pick #113742 to 25.8: Skip the custom-key parallel replicas read when the requested stage cannot absorb finalized data
robot-clickhouse added a commit that referenced this pull request Aug 14, 2026
…when the requested stage cannot absorb finalized data
alexey-milovidov added a commit that referenced this pull request Aug 14, 2026
Resolve the single conflict in `src/Planner/PlannerJoinTree.cpp`. On 26.5 the
`parallel_replicas_enabled_for_storage` and `allow_parallel_replicas_for_join_tree` lambdas
differ from master, so git overlapped the whole block with the small hunk of #113742.
Took the 26.5 side for the block and re-applied only the PR's own change: the
`to_stage_supports_custom_key` gate (`Complete` or
`WithMergeableStateAfterAggregationAndLimit`) on the custom-key parallel replicas `if`.

Original pull-request: #113742
robot-clickhouse-ci-2 added a commit that referenced this pull request Aug 14, 2026
Cherry pick #113742 to 26.3: Skip the custom-key parallel replicas read when the requested stage cannot absorb finalized data
robot-clickhouse added a commit that referenced this pull request Aug 14, 2026
…when the requested stage cannot absorb finalized data
robot-clickhouse-ci-2 added a commit that referenced this pull request Aug 14, 2026
Cherry pick #113742 to 26.5: Skip the custom-key parallel replicas read when the requested stage cannot absorb finalized data
robot-clickhouse added a commit that referenced this pull request Aug 14, 2026
…when the requested stage cannot absorb finalized data
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 14, 2026
alexey-milovidov added a commit that referenced this pull request Aug 14, 2026
Backport #113742 to 26.5: Skip the custom-key parallel replicas read when the requested stage cannot absorb finalized data
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 15, 2026
…when the requested stage cannot absorb finalized data
clickhouse-gh Bot added a commit that referenced this pull request Aug 15, 2026
Backport #113742 to 26.6: Skip the custom-key parallel replicas read when the requested stage cannot absorb finalized data
alexey-milovidov added a commit that referenced this pull request Aug 15, 2026
Backport #113742 to 26.3: Skip the custom-key parallel replicas read when the requested stage cannot absorb finalized data
alexey-milovidov added a commit that referenced this pull request Aug 15, 2026
Backport #113742 to 25.8: Skip the custom-key parallel replicas read when the requested stage cannot absorb finalized data
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
CTE/AN/QP: Merge with a Distributed child under custom-key parallel replicas -> exc.
Effect in the production build a394e92: its upstream test(s) 04815_parallel_replicas_custom_key_merge_distributed_child fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv).
Upstream patch unchanged, with its test(s): 04815_parallel_replicas_custom_key_merge_distributed_child.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

5 participants