Repository navigation
Conversation
checkStackSize() returned immediately inside a coroutine, so all 140
guarded call sites were no-ops on a 320 KiB coroutine stack. An over-deep
recursion there walks into the guard page and takes the server down
instead of raising TOO_DEEP_RECURSION. A complete AST fuzzer
(arm_asan_ubsan) core shows one thread of 386 with its SP in the guard
page above 192 byte-identical frames at a 1584 B stride, filling 92% of
the usable stack. DataTypeFactory.cpp:122 already documents this stack
being overflowed by an ordinary path, and caps parse depth to work
around it.
What was missing is the running coroutine's stack range, so record it
where it is known and carry it to where it is checked:
- CoroutineStack::allocate() records the usable range, derived from the
same `if constexpr` that decides whether a guard page is added. The
guard page sits on top of stack_size rather than inside it, so usable
is 327680 B in guarded and release builds alike; allocate() therefore
loses const, since it now has an observable effect on the object.
- StackfulCoroutine reads it in the constructor body. boost's
create_fiber1 calls salloc.allocate() on the reference it was
forwarded and only afterwards stores its own decayed copy, in both the
ucontext and fcontext backends, so the mem-initializer has already
populated what the body reads.
- operator=(&&) transfers it. AsyncTaskExecutor::createCoroutine() does
`coroutine = StackfulCoroutine(coroutine_stack, Routine{*this})`, so
without this every production coroutine would carry empty bounds and
the check would fail open everywhere while direct-construction tests
still passed. The move constructor stays defaulted: the moved-from
object keeps a stale copy, which is inert because its impl is empty,
so unwind() returns early and it is never published as current.
- unwind() clears it before boost's teardown. unwind() publishes the
coroutine as current around a forced unwind, so an unbounded check
would be live while forced_unwind propagates, and a destructor near
the allowance would throw TOO_DEEP_RECURSION into an unwind that
AsyncTaskExecutor::Routine must rethrow untouched, out of a noexcept
function. Teardown is deliberately fail-open, not checked.
- checkStackSize() compares the frame against that range and returns on
every uncertainty: no usable range, or a frame outside it, which is
what the parent's own frames look like between resume()'s publish and
the stack switch. It reuses throwTooDeepRecursion, so no new error
string is introduced.
The reserve is absolute rather than STACK_SIZE_FREE_RATIO. That ratio is
calibrated against ~8 MiB thread stacks, and its TSan value of 20 would
leave a 320 KiB coroutine stack a 16 KiB allowance, less than the
15768 B an ordinary secure handshake already uses, so inheriting it
would refuse ordinary connects. 64 KiB is one page-aligned value in the
window that admits every measured legitimate workload: against the
resulting 256 KiB allowance, the worst SQL-reachable in-coroutine
descent (Map(String, ...) nested to the depth the AST cap accepts)
measures under 104 KiB in a sanitizer build at parse-depth cap 150, and
under 64 KiB in a release build at cap 300, where -O3 frames shrink
faster than the doubled cap grows.
createCoroutine() runs outside coroutine_lock, but the record-then-read
pair is same-thread within one call, so this inherits rather than widens
the single-writer assumption the assignment already depends on. Were
that assumption ever violated, the failure mode is bounds belonging to
another stack, which the frame-inside-range test rejects, so it fails
open rather than throwing spuriously.
Silk keeps its own bypass. silk::Fiber is only forward-declared in the
public header, its stack member lives in the library's own translation
unit, and MemoryMapCallback receives (ptr, size) with no Fiber *, so
there is no way to build a fiber-to-range map without changing the
contrib API. Nothing in the shipping server runs work on a silk fiber
yet and enable_silk_runtime defaults to false, so this leaves no
reachable gap.
This is a general bound on recursion over a coroutine stack. It is not
proven to stop the specific occurrence above: not one of the 192
repeating frames holds a pointer into the text image, exactly one ASan
frame descriptor exists in the whole 464 KiB region, and the frame
pointer chain does not thread it, so the recursing function cannot be
named from that artifact.
Co-Authored-By: Claude Opus 5 <[email protected]>
Nothing in the test pinned the magnitude of COROUTINE_STACK_RESERVE: the ordinary-depth case checks a nearly empty stack, the deep-recursion case only needs a throw somewhere before its 7/8 budget, and the teardown case only needs one at its deepest point, so any reserve from a few KiB up to roughly 300 KiB passed all three. That left the most dangerous axis of the change unguarded, since an over-conservative reserve would start refusing valid coroutine workloads with TOO_DEEP_RECURSION and no test would notice. expectCoroutineStackBounds now also parses the used `stack size:` field out of the same message and brackets it against the maximum it already parsed: at or above `maximum - 64 KiB`, so the guard did not fire early, and below that plus one page, so it did not fire late. Bracketing against the reported maximum instead of a literal keeps the pin independent of the constant it mirrors, and the page of slack absorbs the single-frame overshoot of the trip point (measured 262160 B against a designed 262144 B). Both recursion helpers measured consumption by subtracting pointers to automatic objects in different frames, which [expr.add]/5 leaves undefined outside a single array object. They now convert to uintptr_t before subtracting, as the production hunk in this PR already does. This was latent rather than diagnosed: -fsanitize=pointer-subtract is not part of -fsanitize=undefined and is not enabled anywhere in the tree, but -fno-sanitize-recover=all means that if it ever is, the whole unit_tests_dbms binary aborts instead of one case failing. What the condition measures does not change, and `here` stays address-taken so -O3 cannot elide the frame that makes the probe consume stack. Also write three names in added comments as `allocate`, `resume` and `STACK_SIZE_FREE_RATIO`, which is how the in-tree style guide asks for function and constant names in prose.
… used-size bracket The comment above `COROUTINE_STACK_RESERVE` stated its comparison backwards. With `STACK_SIZE_FREE_RATIO = 20`, its TSan value, a 320 KiB coroutine stack is allowed 327680 / 20 = 16384 B, and the secure-handshake watermark this reserve is sized against is 15768 B. So the ratio's allowance does not fall short of the handshake: it exceeds it by 616 B, or 3.8%. The conclusion is unchanged and sharper stated accurately, since a handshake consuming 96.2% of the allowance leaves nothing for any frame past it. The comment now says only that, and deliberately carries none of these numbers, which belong here rather than at the line a reader is looking at. The same backwards comparison is in a6a41df's message, which the in-tree rule against amending leaves in place; this is the correction. Two more literal names in the test's comments, `AsyncTaskExecutor` and `TOO_DEEP_RECURSION`, are now written as inline code, so the file is consistent about the convention the rest of this change already follows. The used-size bracket takes its slack from a named `frame_slack` of 4096 B rather than from `getPageSize`. What that bound has to absorb is the single recursion frame between the last check that passed and the throw: 16 B observed against a designed trip point of 262144 B, bounded above by the 48 B frame the recursion's prologue allocates. A page is the wrong unit for it. Where pages are 64 KiB, a supported configuration this tree already enumerates for ARM64, the interval widens to 65536 B, and a 48 KiB reserve then trips at 278576 B, which is inside 262144 + 65536: the over-conservative reserve the two-sided pin exists to reject would pass. The reported-maximum bracket keeps its page of slack, because that allocation genuinely is rounded up to a page. Co-Authored-By: Claude Opus 5 <[email protected]>
`gtest_coroutine_stack_guard` bounded both of its recursions by differencing two address-taken locals: `&first_frame` in `CoroutineTask::run` against `&here` one frame down. Under ASan an address-taken local does not live on the running stack. `detect_stack_use_after_return` defaults to on for Linux (`contrib/llvm-project/compiler-rt/lib/asan/asan_flags.inc:52-54`) and ClickHouse never overrides it, so such a local is allocated on the separately mapped fake stack instead. The subtraction then differenced two unrelated mappings, its unsigned result cleared the budget on the very first level, and the recursion returned at depth 0. Both tests failed on this tree in an `address,undefined` build, and the deep-recursion one exercised nothing at all. The vacuity was in exactly the sanitizer configuration the `arm_asan_ubsan` crash behind this change came from. Frame addresses are immune to it. `__builtin_frame_address(0)` is the frame of the running function on the stack it is actually running on, whichever stack that is, so the difference between two levels is the consumption the test means to bound. It is also what the guard in `checkStackSize.cpp` measures itself, in every build type. Reading both endpoints from the frame address is not sufficient on its own, because doing so removes the last escaping address of a local. At `-O3` LLVM then rewrites `f(depth + 1) + accumulator` into a loop, the frame address stops advancing, and the recursion does not terminate: measured depth 2,254,967,808 with the consumed size at 0 on every level, `recurseUntilGuardTrips` present exactly once in four `eu-stack` samples of the live process, and the self-`call` replaced by a backward jump in both `-O3` arms and only there. `TailRecursionElimination.cpp:114-193,296` marks a call tail only when no alloca-derived value has escaped, so escaping `&here` explicitly restores the per-level frame the measurement needs. The empty `asm` with `&here` as an operand is the construct `src/Common/examples/check_pointer_valid.cpp:27` already uses for this. The numbers, from throwaway probes reverted afterwards. Before, under `address,undefined`: depth 0, the budget satisfied at the first level, 2 failed tests. After: depth 1624 in the deep shape and 1792 in the teardown shape, `budget_reached` false, `past_allowance` true, 3 of 3 passing. Release reaches 5446 and 4480, debug 5445 and 4480. All three arms report a used size between 262160 and 262192 B against a designed trip point of 262144 B, so the two-sided pin on the reserve stays well inside its 4096 B of slack. The ASan arm's much shallower depth is the reason for keeping `here` on the real stack: its frames are roughly 3.3 times fatter, and that is the regime the guard has to hold. No production file changes. The guard, `CoroutineStack` and `StackfulCoroutine` are untouched; only the test measured the wrong thing. Co-Authored-By: Claude Opus 5 <[email protected]>
… hanging Both recursions in `gtest_coroutine_stack_guard` stop on measured consumption, which is the right bound while every level owns a frame and no bound at all once a level does not. Measured on this file with its `asm` escape removed, both `-O3` arms spin forever: the runs were killed at 120, 200 and 600 s, the consumed size read 0 at every level, the depth counter reached 2,254,967,808, and `recurseUntilGuardTrips` appeared exactly once in four `eu-stack` samples of the live process, so there was one physical frame under a backward jump. That shape on a mandatory unit-test job is a job that never reports. The same `recursion_budget` bounds the depth as well, so nothing new is introduced and no existing number moves. A level that consumed even one byte cannot repeat more often than the budget has bytes, so the depth bound is unreachable in any build where the measurement works: the deepest level any arm of this file has been measured to reach is 5974, against a budget of 286720. A folded loop consumes nothing per level, so it reaches the bound instead, and it reaches it in milliseconds. With both `asm` lines deleted, the whole filter now completes in 1 s in `-O3` and 2 s in `-O3 -fsanitize=address,undefined`, returning 1, with the deep test failing and reporting the fold. The other two tests stay green there: `descendThenSuspend` carries a `CheckingOnDestruction` whose destructor runs after the recursive call, so that recursion is not a tail call and does not fold. The fold-specific message has to precede the generic `FAIL()` rather than follow the `try`, because `GTEST_FATAL_FAILURE_` expands to `return` (`contrib/googletest/googletest/include/gtest/internal/gtest-internal.h:1295`, against `GTEST_NONFATAL_FAILURE_` at `:1298`). The first fatal failure leaves the test body, so anything after it is unreachable on the very path it would diagnose. The fold path is also the only path that can set the witness: a guard throw means the frame address was advancing, so the depth bound cannot have fired. Today's tree cannot fold. The escape is present and measured effective in all three arms, where the honest depths are 1624, 5446 and 5445 with the depth bound never reached. What the bound insures against is a toolchain that discards the escape again, since whether a recursion keeps its frame is a property of the optimizer rather than of the source (`contrib/llvm-project/llvm/lib/Transforms/Scalar/TailRecursionElimination.cpp:114-193,296` marks a call tail only when no alloca-derived value has escaped). On such a toolchain the tree without this bound hangs, and with it fails in a second naming the cause. No production file changes. `checkStackSize.cpp`, `CoroutineStack` and `StackfulCoroutine` are untouched by this commit. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewReviewed cold against the code each round, then adjudicated with the recorded evidence. The final ❌ Fixed before publishing. The gtest did not pin the magnitude of the 64 KiB reserve (anything
💡 Changelog category scoped conservatively to |
|
Workflow [PR], commit [c052e7a] Summary: ❌
AI ReviewSummaryThis PR records the usable coroutine stack range at allocation time, carries it on Final Verdict
LLVM Coverage ReportMeasured on commit c052e7a.
Changed lines: Changed C/C++ lines covered: 126/137 (91.97%) · Uncovered code |
|
cc @mstetsyuk @devcrafter, could you review this? |
`StackfulCoroutine`'s constructor perfect-forwarded its allocator into `boost::context::fiber` and then read `lastAllocatedBounds()` back out of the same parameter. The bounds do not exist until the fiber's mem-initializer has run the allocation, so they can only be read afterwards, but by then an rvalue allocator has been moved into the fiber's own record and what that record holds is not reachable from the parameter. Such a call would store empty bounds, and `checkStackSize()` would silently go back to measuring a coroutine frame against the thread's stack. Narrowing the parameter to `CoroutineStack &` puts the requirement in the signature: the caller keeps owning the allocator, which is what the only in-tree call site, `AsyncTaskExecutor::createCoroutine`, already does. Nothing changes there, because `StackAlloc` already deduced to `CoroutineStack &` for an lvalue argument, so `boost::context::fiber` is instantiated exactly as before. clang-tidy reports the same read as `bugprone-use-after-move` and `hicpp-invalid-access-moved` at `StackfulCoroutine.h:37`, which the `arm_tidy` build turns into an error through `-warnings-as-errors`. Co-Authored-By: Claude Opus 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units174 translation units recompiled, 1516 s compile time in total, 174 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
CI finish ledger - c052e7aEvery failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link
Session id: cron:our-pr-ci-monitor:20260907-183129 |
Algunenano
left a comment
There was a problem hiding this comment.
🤖 I analyzed the core dump behind this PR. This change does not fix the crash: the overflow is not a recursion and never reaches checkStackSize. I suggest closing it.
How it was analyzed
- The core cited in the description (PR #100371,
core.QueryPipelineEx.126-2991) is truncated: the file is 8.4 GB but its program headers reference 45.9 GB, and the crashing thread's stack is not in the file. I used the complete core from the same failure on PR #113939 (https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113939&sha=9d822541880e3756c06d580a9243251b121d6561&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29),core.TCPHandler.127-3014. Both cores have the same fingerprint: the two innermost frames are 0x810 bytes each, with the same PC to LR distance. - The build artifacts have expired, so the frame chain was walked from raw memory through the
x29frame records.
What the core shows (LWP 136, the thread that last logged Connection (127.0.0.3:9440): Connecting to 127.0.0.3:9440)
- SP is in the guard page below a coroutine stack. Sanitizer builds use
BOOST_USE_UCONTEXT, and the bottom frame returns into libc'smakecontexttrampoline. - The interrupted fiber code uses about 6 KiB (29 frames). The next frame returns into the vDSO
rt_sigreturntrampoline, so a signal handler is running on the fiber stack. - One frame in the handler path is 306,032 bytes. It holds 191 structures at a 1584-byte stride that decode as libunwind
PrologInfoStackEntry(x29/x30saved at CFA-16/CFA-8). These are the "identical frames" the description mentions; they are not call frames.
Root cause
- The query profiler signal handler is installed without
SA_ONSTACK(src/Common/QueryProfiler.cpp), soStackTrace(ucontext)→unw_backtraceruns on the interrupted fiber's stack. - libunwind is built with
_LIBUNWIND_REMEMBER_STACK_ALLOC(contrib/libunwind-cmake/CMakeLists.txt). EachDW_CFA_remember_stateinparseFDEInstructionsdoes anallocaof aPrologInfoStackEntry, andDW_CFA_restore_statenever frees it. Stack use grows with the total number of remember/restore pairs in one FDE, not with their nesting depth. On ARM64 an entry is about 1.6 KB (96 registers), so an FDE with 191 pairs takes about 300 KB. This is why onlyarm_asan_ubsanis affected.
No function on this path calls checkStackSize, and it could not throw from a signal handler anyway, so the bound added here cannot trigger for this crash. The fix belongs in libunwind: bound the remember-state storage by nesting depth (reuse restored entries) instead of total count.
|
I verified this against master before replying, and it holds on every point I can check in tree:
So I accept the conclusion: nothing on that path calls One measurement in support of your libunwind conclusion: On disposition I would rather not close this myself, because #113835 was assigned to me by @ alexey-milovidov specifically to make
My own lean is 1: without this crash, the bound has no trigger I can demonstrate. |
|
Related: #113835
Related: #100371
Related: #113991
CI report for the core this was measured from (
AST fuzzer (arm_asan_ubsan), PR #100371):https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100371&sha=ad61a2a689c80c003cfa300ceb67807082f7644b&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
checkStackSizereturned immediately inside a coroutine, so all 140 guarded call sites were no-ops ona 320 KiB coroutine stack: an over-deep recursion there trips the guard page and kills the server
instead of raising
TOO_DEEP_RECURSION. A complete core shows one thread's SP in the guard page aboveidentical frames filling 92% of it;
DataTypeFactory.cpp:122documents a prior workaround for the samestack.
CoroutineStack::allocatenow records the usable range: 320 KiB in guarded and release buildsalike, the guard page sitting on top of it.
StackfulCoroutinecarries it and clears itin
unwind, so a forced unwind cannot become an exception.checkStackSizetests the frame against thatrange with a 64 KiB reserve, returning on every uncertainty.
default_stack_sizeis untouched.The reserve is absolute, not
STACK_SIZE_FREE_RATIO: that ratio is calibrated for 8 MiB thread stacks,and its TSan value leaves this stack a 16384 B allowance that an ordinary secure handshake (measured
15768 B) all but exhausts. Against the resulting 256 KiB allowance, the worst SQL-reachable in-coroutine
descent measures under 104 KiB under sanitizers, 64 KiB in release.
Two residuals.
silkfibers keep their own bypass:silk::Fiberis only forward-declared, so there isno stack-bounds API, and
enable_silk_runtimeis off by default. And a bound only helps where a guardexists:
DataTypeTuple::createSerializationInforecurses with nocheckStackSizecall.This is a general bound and I cannot show it stops that occurrence: the recursing function is not
identifiable from the core. @ alexey-milovidov asked for one on that understanding:
#113835 (comment) .
A gtest, not a functional test: the throw is not observable from SQL, since no SQL path I can construct
reaches the allowance. It fires the guard inside a real
AsyncTaskExecutorcoroutine, brackets thereported maximum and used size so neither can drift, and fails without the
checkStackSizehunk.Workflow [PR]
Sync PR [sync-upstream/pr/118531]