Skip to content

Make checkStackSize aware of the running coroutine's stack - #118531

Closed
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fiber-aware-checkstacksize
Closed

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fiber-aware-checkstacksize

Conversation

@groeneai

@groeneai groeneai commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

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 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 above
identical frames filling 92% of it; DataTypeFactory.cpp:122 documents a prior workaround for the same
stack.

CoroutineStack::allocate now records the usable range: 320 KiB in guarded and release builds
alike, the guard page sitting on top of it. StackfulCoroutine carries it and clears it
in unwind, so a forced unwind cannot become an exception. checkStackSize tests the frame against that
range with a 64 KiB reserve, returning on every uncertainty. default_stack_size is 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. silk fibers keep their own bypass: silk::Fiber is only forward-declared, so there is
no stack-bounds API, and enable_silk_runtime is off by default. And a bound only helps where a guard
exists: DataTypeTuple::createSerializationInfo recurses with no checkStackSize call.

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 AsyncTaskExecutor coroutine, brackets the
reported maximum and used size so neither can drift, and fails without the checkStackSize hunk.


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

groeneai and others added 5 commits September 7, 2026 02:03
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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Reviewed cold against the code each round, then adjudicated with the recorded evidence. The final
round returned no findings. Kept short deliberately.

❌ Fixed before publishing. The gtest did not pin the magnitude of the 64 KiB reserve (anything
from a few KiB to ~300 KiB passed), so an over-conservative reserve could have started refusing valid
coroutine work unnoticed; the trip point is now bracketed two-sidedly against the maximum the
exception itself reports, with one recursion frame of slack rather than one OS page so it still
discriminates where pages are 64 KiB. Separately the test measured consumption between two
address-taken locals, which under ASan differences the real stack against the fake stack: it read 0
at every level and the deep case exercised nothing, in exactly the sanitizer configuration this
change came from. It now differences frame addresses, and bounds its own depth so a build that folds
the recursion fails in a second instead of hanging a mandatory job.

⚠️ Watch item. The reserve was measured in sanitizer, debug and release builds, not under TSan.
It is not sanitizer-conditional, so only frame size differs there and a fatter frame trips a
byte-denominated reserve sooner; the worst SQL-reachable in-coroutine descent measures 102392 B
against the 262144 B allowance. This PR's TSan jobs cover that regime.

💡 Changelog category scoped conservatively to CI Fix or Improvement: the only observed
occurrence is a sanitizer fuzzer job and release SQL was measured not to reach within 4x of the
bound, so no user-visible stable-release symptom is demonstrable. Say the word if you read it as
Bug Fix.

@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c052e7a]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, parallel) FAIL
00084_external_aggregation FAIL cidb

AI Review

Summary

This PR records the usable coroutine stack range at allocation time, carries it on StackfulCoroutine, and uses it in checkStackSize so deep recursion inside an AsyncTaskExecutor coroutine raises TOO_DEEP_RECURSION instead of falling through to the guard page. I did not find an unresolved correctness, safety, or test-coverage issue in the current head; the earlier allocator-forwarding problem is fixed by taking CoroutineStack &, and the new gtest covers the ordinary path, the deep-recursion throw, and forced unwind via cancel, restart, and destructor teardown.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit c052e7a.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 126/137 (91.97%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @mstetsyuk @devcrafter, could you review this? checkStackSize returned immediately inside a coroutine, so all 140 guarded call sites were no-ops on a 320 KiB coroutine stack and an over-deep recursion walked into the guard page instead of raising TOO_DEEP_RECURSION; this records the usable range in CoroutineStack::allocate, carries it on StackfulCoroutine (clearing it for boost's forced unwind), and tests the frame against it with an absolute 64 KiB reserve rather than the thread path's ratio, which under TSan would leave this stack only 16384 B. The silk bypass is deliberately left in place, since silk::Fiber exposes no stack-bounds API.

Comment thread src/Common/StackfulCoroutine.h Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... label Sep 7, 2026
`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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c052e7a91 with master 58f74d473 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of d9a179ec7; 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

174 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.
The matched translation units cost +66.6 s (+5%) in total before that adjustment.

Job report

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c052e7a

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. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, parallel) / 00084_external_aggregation flaky: statement 2 dies with Code: 241 ... Query memory limit exceeded: would use 573.03 MiB (attempt to allocate chunk of 1.01 MiB), maximum: 572.20 MiB: While executing SourceFromNativeStream; the job's own randomized-settings diagnosis re-ran it 22 times with 0 failures, and the signature has 12 true-master rows plus 17 other carrier branches in 30 days #118474 (mine, open)

Mergeable Check and PR are red only as rollups of that single child failure. Nothing here is
caused by this PR: its diff is src/Common/CoroutineStack.*, StackfulCoroutine.h,
checkStackSize.cpp and one gtest, while the failing query is a plain GROUP BY spill in
external aggregation that reproduces on master. The sanitizer acceptance arm this head was
waiting for is green: Unit tests (tsan), all four Stateless tests (amd_tsan, ...) jobs and
Stress test (amd_tsan) / (arm_tsan) all pass, with no TOO_DEEP_RECURSION.

Session id: cron:our-pr-ci-monitor:20260907-183129

@Algunenano Algunenano self-assigned this Sep 25, 2026

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🤖 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

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's makecontext trampoline.
  • The interrupted fiber code uses about 6 KiB (29 frames). The next frame returns into the vDSO rt_sigreturn trampoline, 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/x30 saved 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), so StackTrace(ucontext) → unw_backtrace runs on the interrupted fiber's stack.
  • libunwind is built with _LIBUNWIND_REMEMBER_STACK_ALLOC (contrib/libunwind-cmake/CMakeLists.txt). Each DW_CFA_remember_state in parseFDEInstructions does an alloca of a PrologInfoStackEntry, and DW_CFA_restore_state never 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 only arm_asan_ubsan is 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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I verified this against master before replying, and it holds on every point I can check in tree:

  • contrib/libunwind-cmake/CMakeLists.txt:32 sets -D_LIBUNWIND_REMEMBER_STACK_ALLOC=1, which in contrib/llvm-project/libunwind/src/config.h:136-143 selects __builtin_alloca for _LIBUNWIND_REMEMBER_ALLOC and makes _LIBUNWIND_REMEMBER_FREE expand to do {} while (0). _LIBUNWIND_REMEMBER_CLEANUP_NEEDED is not defined on that branch either, so RememberStack::~RememberStack is empty too: nothing is reclaimed until parseFDEInstructions returns, and the peak is the FDE's total remember count rather than its nesting depth (DwarfParser.hpp:609-616 and :625-631). _LIBUNWIND_HIGHEST_DWARF_REGISTER_ARM64 is 95, so 96 register slots per entry, matching the 1584 byte stride you measured, which is why only arm64 reaches it.
  • src/Common/QueryProfiler.cpp:494 installs the handler with SA_SIGINFO | SA_RESTART and no SA_ONSTACK.
  • Your truncated core premise matches what I had measured on that same core independently: 7.78 GiB present against 42.88 GiB declared by the program headers, which is your 8.4 GB / 45.9 GB in the other unit. That truncation is what stopped me from reading the crashing stack, so thank you for walking the frame records.

So I accept the conclusion: nothing on that path calls checkStackSize, it could not throw from a signal handler anyway, and this change cannot prevent that crash.

One measurement in support of your libunwind conclusion: SA_ONSTACK on its own would not be enough. The alternative stack installed per thread is max(UNWIND_MINSIGSTKSZ, MINSIGSTKSZ, page size) with UNWIND_MINSIGSTKSZ = 32 KiB (src/Common/ThreadStatus.cpp:45 and :110-122, installed at :175-183), so a single 306 KB parseFDEInstructions frame overflows it by about ten times, and growing it to fit is paid per thread. _LIBUNWIND_NO_HEAP=1 is set right next to the stack alloc define, so swapping in the malloc branch would cut against that build policy; bounding by nesting depth, as you suggest, looks like the only shape that fits.

On disposition I would rather not close this myself, because #113835 was assigned to me by @ alexey-milovidov specifically to make checkStackSize fiber aware. Which do you want?

  1. Close it, and I open a separate PR for the libunwind side fix.
  2. Close it, and the libunwind side fix is not mine to write.
  3. Keep it, re-scoped and retitled to the bound alone with the crash claim removed from the description, and the crash fixed in a separate PR.

My own lean is 1: without this crash, the bound has no trigger I can demonstrate.

@Algunenano

Copy link
Copy Markdown
Member
  1. Closing it since it's the wrong solution. I'll work on the libunwind changes

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... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants