Skip to content

Do not exhaust the coroutine stack when sending or receiving a deeply nested Dynamic value - #127880

Merged
fm4v merged 4 commits into
ClickHouse:masterfrom
groeneai:dynamic-binary-write-coroutine-stack-guard
Nov 4, 2026
Merged

fm4v merged 4 commits into
ClickHouse:masterfrom
groeneai:dynamic-binary-write-coroutine-stack-guard

Conversation

@groeneai

@groeneai groeneai commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #113835
Related: #118531
Related: #121441

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

Fixes a crash when a deeply nested Dynamic or JSON value is sent to or received from a remote server, for example as a constant in a remote() query or as a column read through remote(). Such a value now raises TOO_DEEP_RECURSION.

Description

On 26.8.28.14 and 26.9.19.9 (official builds), SELECT CAST(unhex(concat('01', repeat('3000800820000000010161', 1000), '300080082000000000')), 'AggregateFunction(any, Dynamic)') FROM remote('127.0.0.2', system.one) kills the server with SIGSEGV. The AST fuzzer hit it as stack smashing detected in SerializationObject::serializeBinary: https://github.com/ClickHouse/ClickHouse/actions/runs/40328492327/job/121652452311

A remote query sends its scalars and reads the remote blocks inside the RemoteQueryExecutorReadContext coroutine, whose stack is 320 KiB. There checkStackSize() returned immediately, and SerializationDynamic::serializeBinary had no check at all, so the data-driven JSON -> Dynamic recursion ran past the stack (in release builds, which have no guard page, below the heap allocation).

Either part alone still crashes. The new test sends and receives values 1000, 2000 and 4000 levels deep through remote(): an unpatched debug or ASan server dies at the first line, the patched one reports TOO_DEEP_RECURSION. I also ran it with both use_hedged_requests values and with serialize_query_plan. Reading a deep Dynamic column through remote() crashed the same way and now hits the existing IDataType::getSerialization guard. Silk fibers keep their bypass: they expose no stack bounds.


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

Version info

  • Merged into: 26.11.1.1313-master (included in 26.11 and later)

groeneai and others added 3 commits October 26, 2026 17:52
A remote query sends its scalars and reads the remote blocks inside the
coroutine of RemoteQueryExecutorReadContext, whose stack is 320 KiB. There,
checkStackSize() returned immediately, and SerializationDynamic::serializeBinary
had no check at all. A Dynamic/JSON value nested a few thousand levels deep
(the depth comes from the data) therefore overflowed the coroutine stack:
SIGSEGV on the guard page in debug and sanitizer builds, and in release builds,
which have no guard page, the recursion continued below the heap allocation
("stack smashing detected" in the AST fuzzer, STID 3920-0f50).

checkStackSize() now measures the frame against the stack of the current
StackfulCoroutine: CoroutineStack records the usable range of each stack it
allocates, the coroutine keeps it (and clears it before a forced unwind, so a
destructor cannot throw during forced_unwind), and checkStackSize() throws
TOO_DEEP_RECURSION when less than 64 KiB is left. A fixed reserve is used
instead of STACK_SIZE_FREE_RATIO, which is calibrated for 8 MiB thread stacks
(its TSan value would leave a 320 KiB coroutine 16 KiB). Frames outside the
coroutine stack (the parent stack, between publishing the coroutine and
switching to it) are not checked.

Both SerializationDynamic::serializeBinary overloads get the same guard the
deserialization, hashing and text paths already have.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The receive arm accepted empty output at every depth, so a regressed
receive-side guard could pass silently on a release build, where the
coroutine stack has no guard page. At 4000 levels the value exceeds the
coroutine stack on every build, so require the exception there as the
send arm already does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop design narration (why an lvalue ctor, why the frame address is taken early, the size check) and shorten the coroutine-reserve, teardown, parent-stack and Silk comments to one line each.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 rounds, 5 findings) plus my own cold review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The 4000-level receive case accepted success, so it could not fail on a release build AGREE, fixed @ f24ab02 receive 4000 now requires TOO_DEEP_RECURSION, like send 4000
2 ⚠️ No test for the serializeBinary(Field) guard; the send query also returns the deep state DISAGREE Without the send guard the send itself dies (measured at depth 2900, both use_hedged_requests values); a deep Field only comes from paths already guarded per level
3 ⚠️ The test does not pin use_hedged_requests or serialize_query_plan DISAGREE No code in the diff depends on either; the runner randomizes use_hedged_requests per run, and both modes were run locally. The description now says so instead of implying the test pins them
4 ⚠️ Coroutine stacks of 64 KiB or less bypass the check DISAGREE Every CoroutineStack in the tree is default-sized (320 KiB); the early return covers the empty bounds during unwinding
5 💡 Use Critical Bug Fix and the present tense in the changelog entry Tense: AGREE, entry reworded. Category: DISAGREE I leave Critical Bug Fix to a maintainer's call

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT CAST(unhex(concat('01', repeat('3000800820000000010161', 1000), '300080082000000000')), 'AggregateFunction(any, Dynamic)') FROM remote('127.0.0.2', system.one) with async_socket_for_remote = 1, async_query_sending_for_remote = 1 kills an unpatched debug or ASan master server every time, and the official 26.8.28.14 and 26.9.19.9 servers.
b Root cause explained? The constant is sent as a scalar from the RemoteQueryExecutorReadContext coroutine (320 KiB stack). There checkStackSize() returned immediately and SerializationDynamic::serializeBinary had no check, so the JSON/Dynamic recursion, whose depth comes from the data, ran past the stack. gdb shows the 1452-frame recursion above RemoteQueryExecutorReadContext::Task::run.
c Fix matches root cause? Yes. checkStackSize() now works on coroutine stacks (64 KiB reserve), and the binary write path gets the guard its read, hash and text paths have. No stack-size bump, no try/catch.
d Test intent preserved / new tests added? New test 05452_dynamic_deep_value_remote_stack_guard.sh: send and receive at 1000, 2000 and 4000 levels through remote(), each either succeeds or reports TOO_DEEP_RECURSION (at 4000 both the send and the receive must report it), then a remote liveness query. No existing test edited.
e Both directions demonstrated? Unpatched debug and ASan: the server dies at the first line. Patched: 50/50 randomized runs on debug, 10/10 on ASan, 10/10 with serialize_query_plan = 1. Either part of the fix alone still crashes at 2900 levels.
f Fix is general across code paths? The bound now covers every AsyncTaskExecutor coroutine (read context, connection establisher, hedged packet receiver); checked with both use_hedged_requests values. Reading a deep Dynamic column through remote() crashed the same way and is now stopped by the existing IDataType::getSerialization guard. Both serializeBinary overloads (column and Field) are guarded.
g Fix generalizes across inputs (params/datatypes/wrappers)? Depths 1000/2000/4000, send and receive, aggregate state and plain Dynamic column, debug and ASan, distributed plan. Shallow values are unaffected (related deep-value tests and 50 randomized runs pass).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; thread stacks keep their thresholds.
i Invariants and contracts preserved? The bounds are cleared before a forced unwind, so no destructor can throw during forced_unwind; frames outside the coroutine stack are not checked; the exception is rethrown on the thread by AsyncTaskExecutor. After a failed send the connection is not reused; 20 later remote queries succeed.

Session id: cron:clickhouse-impl-slot-41:20261026-172000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @mstetsyuk, could you review this and add the can be tested label so CI runs? A deep Dynamic value sent or received by a remote query recursed on the 320 KiB RemoteQueryExecutorReadContext coroutine stack, where checkStackSize() returned immediately; it now measures coroutine frames against the range CoroutineStack allocated (64 KiB reserve), and both SerializationDynamic::serializeBinary overloads get the guard.

@clickhouse-gh

clickhouse-gh Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c969382]

Summary: ✅


AI Review

Summary

The PR makes checkStackSize enforce coroutine stack bounds and guards both SerializationDynamic::serializeBinary overloads, so deeply nested values transferred through remote raise TOO_DEEP_RECURSION before exhausting the stack. No actionable findings remain after reviewing the current diff, affected code, and prior discussion.

Missing context / blind spots
  • ⚠️ Sanitizer jobs for head c969382e9ed1 are still running. The focused regression 05452_dynamic_deep_value_remote_stack_guard passes in Fast test; completed sanitizer results would close the remaining CI gap. No local build was available for an independent run.
Final Verdict

Status: ✅ Approve. No code changes requested.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... labels Oct 26, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7948036

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 infra, not from this PR: every readiness probe got No connection to LogCluster, so the job ended with LogClusterNotReady: the endpoint never became ready in has_pr_data before comparing anything. 291 of 295 runs since 2026-10-26 22:00 UTC are red, on 237 PRs #126200 (mine, open)
PR praktika rollup of the row above #126200 (the owner of the row above)
CH Inc sync - CH Inc sync (private, not actionable by me)

The first runs of this head stopped at Config Workflow / Pre Hooks because the can be tested label was not set yet; the run after the label was added is the one above. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261027-213006

…in comments

A depth of 5 must pass through `remote` on every build, so a coroutine stack check that fires too early now shows up as a test diff instead of being accepted as `TOO_DEEP_RECURSION`.

Review: ClickHouse#127880
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c969382e9 with master f1e98b9e5 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 9dfa158f3; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

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

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

Compile time of recompiled translation units

185 translation units recompiled, 1684 s compile time in total, 184 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.8 s

Job report

@fm4v
fm4v added this pull request to the merge queue Nov 4, 2026
Merged via the queue into ClickHouse:master with commit dbf654c Nov 4, 2026
185 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 4, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 4, 2026
@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 Nov 14, 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-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... 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-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants