Skip to content

fix(crash-handler): install sigaltstack, pre-warm symbols, signal-safe backtrace - #416

Merged
fcostaoliveira merged 6 commits into
redis:masterfrom
filipecosta90:fix/issue-412-crash-handler-signal-safety
Jun 1, 2026
Merged

fcostaoliveira merged 6 commits into
redis:masterfrom
filipecosta90:fix/issue-412-crash-handler-signal-safety

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented May 30, 2026 •

Copy link
Copy Markdown
Collaborator

Refs #412

Follow-up to issue #404 / PR #405. The production bug report attached to #404 was truncated mid-stream at "CLIENT LIST OUTPUT" — the crash handler started, printed STACK TRACE / INFO OUTPUT, then re-faulted inside _dl_fixup when it tried to call an stdio function for the first time from the signal context. This PR closes the structural part of #412.

Changes

1. Install sigaltstack(2) on main + every worker thread

SA_ONSTACK was set in sa_flags but sigaltstack was never called anywhere in the codebase (grep -r sigaltstack returned zero on master). The flag was silently inert; a SIGSEGV caused by stack overflow re-faulted on the exhausted stack and produced no report at all.

  • install_alt_signal_stack() helper allocates a 64 KiB per-thread alt stack (TLS-guarded so it's a no-op on second call).
  • Called from setup_crash_handlers() for the main thread.
  • Called from cg_thread_start() for every worker.

2. Pre-warm symbols at startup

prewarm_crash_handler() runs once before the handler is registered and forces the dynamic linker to resolve the PLT entries the handler will need:

  • backtrace() + backtrace_symbols_fd() (output → /dev/null)
  • fprintf(stderr, "") + fflush(stderr) (forces glibc stdio first-use init)
  • event_get_version()

When the handler later fires, those symbols are already bound — no _dl_fixup from the signal path. _dl_fixup is not async-signal-safe; this is the specific failure mode that truncated #404's report.

3. backtrace_symbols_fd instead of backtrace_symbols

print_all_threads_stack_trace no longer mallocs in the signal context. backtrace_symbols allocates from the (possibly corrupt) heap arena and takes the arena lock; the crashing thread may already hold both. backtrace_symbols_fd writes directly to the fd and is the documented async-signal-safe variant.

4. alarm(5) watchdog at top of crash_handler

If the handler itself hangs (e.g. mid-print_client_list while iterating a torn vector under heap corruption), SIGALRM kills the process after 5 s instead of leaving a half-written report. SIGALRM is explicitly set to SIG_DFL in setup_crash_handlers so it terminates rather than recursing into the handler.

Out of scope (TODO follow-ups in #412)

The remaining items from the issue's audit need their own PRs:

  • Replace fprintf/vfprintf with a hand-rolled write(2) + safe-itoa formatter. Pre-warm gets us most of the value; a full rewrite is a larger refactor.
  • Replace localtime + strftime with a static-buffer time formatter.
  • Cache getpid() in a static at startup.
  • Add new test scenarios (stack overflow, double-free, use-after-free, recursive in-handler fault, etc.) that assert both BUG REPORT START and BUG REPORT END are present — the truncated-report mode SIGSEGV / stack smashing when --monitor-input contains a large command line (VLA stack overflow in split_command_to_args) #404 reported is invisible to the current "section headers present" assertions.

Test plan

  • make -j clean
  • make format-check clean
  • Existing tests/test_crash_handler_integration.py (with_active_connections + worker_thread) — both PASS locally
  • Full CI matrix (ASAN/UBSan/TSAN, standalone + cluster, plaintext + TLS) — verified on this PR

🤖 Generated with Claude Code


Note

Medium Risk
Changes run on every fatal signal and every worker thread at startup; incorrect sigaltstack or SIGALRM handling could affect sanitizer CI or crash dumps, but scope is isolated to crash reporting in memtier_benchmark.cpp.

Overview
This PR hardens the memtier_benchmark crash path so bug reports are less likely to truncate or never appear (follow-up to #404 / #412).

Alternate signal stacks are installed on the main thread (setup_crash_handlers) and each worker (cg_thread_start) via a TLS 64 KiB buffer and install_alt_signal_stack(), which respects an existing sanitizer alt stack instead of replacing it. That makes SA_ONSTACK effective for stack-overflow faults.

Startup pre-warming (prewarm_crash_handler) resolves backtrace / backtrace_symbols_fd, stdio, and event_get_version before the handler runs, avoiding lazy _dl_fixup inside the signal context.

In the handler, alarm(5) caps hung reports; SIGALRM is reset to default. Stack printing uses backtrace_symbols_fd to the raw fd instead of malloc-based backtrace_symbols, with notes on avoiding fflush in the handler.

Reviewed by Cursor Bugbot for commit c0b7a46. Bugbot is set up for automated code reviews on this repo. Configure here.

…e backtrace

Follow-up to issue redis#404 / PR redis#405 (and addresses redis#412). The bug report
attached to redis#404 was truncated at "CLIENT LIST OUTPUT": the crash
handler started, printed STACK TRACE / INFO OUTPUT, then re-faulted
inside _dl_fixup when it tried to call an stdio function for the first
time from the signal context. Three structural fixes:

1) sigaltstack(2) is now installed on the main thread (in
   setup_crash_handlers) and on every worker (at cg_thread_start
   entry). Without this, SA_ONSTACK was silently inert and a SIGSEGV
   caused by stack overflow re-faulted on the exhausted stack —
   producing no report at all. 64 KiB per thread, malloc'd best-effort
   (silently no-op on OOM).

2) Pre-warm symbols at startup. Before registering the handler,
   prewarm_crash_handler() calls backtrace(), backtrace_symbols_fd()
   (output discarded to /dev/null), fprintf(stderr, "") + fflush, and
   event_get_version(). Each touch forces the dynamic linker to resolve
   the PLT entry NOW, so when the handler later runs there is no
   _dl_fixup on the signal path. _dl_fixup is not async-signal-safe;
   this is the specific failure mode that truncated redis#404's report.

3) print_all_threads_stack_trace now uses backtrace_symbols_fd (the
   documented async-signal-safe variant) instead of the malloc-using
   backtrace_symbols. The crashing thread may hold the malloc arena
   lock, or the heap may be corrupt; both make backtrace_symbols
   re-fault.

Plus an alarm(5) watchdog at the top of crash_handler: if the handler
itself hangs (e.g. mid-print_client_list while iterating a torn
vector), the process is killed after 5 s instead of leaving a
half-written report. SIGALRM is explicitly reset to SIG_DFL so the
watchdog terminates rather than recursing into the handler.

Out of scope for this PR (left as TODO referencing redis#412):
  - Replacing fprintf with a hand-rolled write()+safe_itoa formatter
    (large refactor; pre-warm gets us most of the value without it).
  - Replacing localtime+strftime with a static-buffer formatter.
  - Caching getpid() in a static at startup.
  - Adding new test scenarios (stack overflow, double-free, etc.) —
    follow-up; existing tests still pass with these changes.

Refs redis#412

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Comment thread memtier_benchmark.cpp Resolved
…de existing

Two ASAN-driven follow-ups to the prior commit:

1) The malloc(64KB) for the per-thread alt stack was never freed and
   showed up under LeakSanitizer as 64 KB * (1 + worker_threads) of
   unreleased memory at clean exit, failing 6 ASAN cells on PR redis#416's
   first CI run. Replace with a __thread static char[64KB] so the
   buffer lives in the TLS region of each thread, no allocation, no
   leak.

2) Skip installation if something upstream (a sanitizer runtime, a
   parent process, etc.) has already registered an alt stack —
   replacing theirs would break their crash reporting. Check via
   sigaltstack(NULL, &existing) and bail when SS_DISABLE is clear and
   the existing stack is large enough.

Refs redis#412

@fcostaoliveira fcostaoliveira left a comment

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.

Review: performance (haiku 4.5)

  • sigaltstack per-thread: 64 KiB TLS buffer allocated once at worker start, installed once via sigaltstack(2). Zero runtime cost in steady state.
  • prewarm_crash_handler at startup: One-shot symbol resolution (~10 µs). Called before handler registration, zero steady-state cost. Symbol binding is unavoidable; pre-warming just moves the cost out of the signal context where it could deadlock.
  • alarm(5) per handler entry: Set only when a signal arrives; no periodic overhead. Watchdog prevents mid-report hangs caused by concurrent heap corruption. Negligible cost.
  • backtrace_symbols_fd over backtrace_symbols: Signal-safe variant; no allocation in the handler. Tradeoff: less symbolic info per frame, but eliminates malloc deadlock risk in crashed state.

Verdict: Approve — startup-only cost, crash-handler robustness win.

@fcostaoliveira fcostaoliveira left a comment

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.

Review: security (opus 4.7)

  • Sanitizer-collision check is correctly gated: install_alt_signal_stack calls sigaltstack(NULL, &existing) and bails out if the previous installer's stack is >= MINSIGSTKSZ and not disabled. ASan/TSan/UBSan all install their own ~64 KiB alt stack at runtime init, so this defers to them rather than clobbering — which would otherwise break sanitizer crash reporting. Good.
  • Per-thread __thread char tls_altstack_buf[64*1024] is 64 KiB per worker thread of static TLS. With memtier's typical -t 64/-c 200 runs that's 4 MiB of always-resident TLS — acceptable, but worth noting that a -t 1024 invocation now reserves 64 MiB just for alt-stacks. Heap-allocated under pthread_setspecific with explicit free in a cancellation cleanup would scale better; the trade-off you took (no signal-path allocation) is defensible.
  • alarm(5) watchdog is a fixed kernel-side timer not exposed to attacker tuning at runtime — fine. The 5 s budget is reasonable for the existing report shape; on a TSAN build where backtrace symbolization can be slow it may fire prematurely (truncating a legitimate-but-slow report). Consider alarm(15) under __has_feature(thread_sanitizer).
  • Pre-warm opens /dev/null with open(O_WRONLY) and explicitly close()s it — no FD leak. Critically, this runs before worker fork/threads spawn, so the transient FD cannot leak across clone(). No O_CLOEXEC needed but adding it costs nothing and is defense-in-depth.
  • backtrace_symbols_fd switch is a clear improvement: removes the malloc-arena-lock re-entry risk that turns SIGSEGV-during-malloc into a hung handler.
  • SIGALRM is explicitly set to SIG_DFL after the SEGV/BUS/etc handlers are installed — correct ordering. However if the user has LD_PRELOADed something that re-registers SIGALRM (e.g. some profilers), our explicit sigaction will lose that arrangement silently. Acceptable for a crash watchdog.
  • The handler still calls fprintf/vfprintf (not async-signal-safe per POSIX, even after pre-warm). Pre-warm avoids _dl_fixup but does not avoid glibc's stdio internal locks; a SIGSEGV in malloc holding the arena lock and then trying to fprintf can still deadlock the handler. The PR description acknowledges this as out of scope; the 5 s alarm is the backstop.
  • Each worker calling install_alt_signal_stack() from cg_thread_start is correct, but the TLS guard tls_altstack_installed is per-thread so re-spawn after a thread-restart loop (recent feature) installs a fresh stack each time — fine.

Verdict: Approve

@fcostaoliveira fcostaoliveira left a comment

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.

Review: docs & commit message (haiku 4.5)

• Title uses Conventional Commits correctly: fix(scope): subject.
• First line correctly uses Refs #412 rather than Fixes — appropriate; the issue covers broader crash-handler hardening, this PR closes the structural part (sigaltstack + pre-warm), leaving fprintf/localtime/pid-cache for follow-ups.
• Test plan is honest: existing crash-handler tests PASS, full CI matrix pending. Defers follow-up test scenarios (stack overflow, double-free, truncated-report assertions) to issue #412.
• "Out of scope (TODO)" section correctly lists four follow-ups with clear separation of concerns.
• No AGENTS.md updates needed — crash handling is an internal detail, not a user-facing feature or new test env var.

Verdict: Approve

@fcostaoliveira fcostaoliveira left a comment

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.

Review: design & API choices (sonnet 4.6)

  • Crash-handler concerns staying in memtier_benchmark.cpp creates a growing grab-bag TU. install_alt_signal_stack, prewarm_crash_handler, setup_crash_handlers, and crash_handler are now ~180 lines of signal-handling infrastructure in a file that also owns main, option parsing, and the thread-launch loop. A crash_handler.{h,cpp} pair would isolate the signal-safety surface, make it testable in isolation, and let future reviewers find the invariants without scrolling through 2 000 lines. The __thread TLS buffer (tls_altstack_buf) would naturally live there.
  • install_alt_signal_stack() API shape is reasonable but the TLS buffer is static __thread char[], exposing a non-trivial lifetime concern. The 64 KiB buffer is permanent for the thread's lifetime regardless of whether the alt stack is ever needed. If crash-handler infrastructure is extracted to its own TU later, the buffer should be documented as part of that module's contract, not buried in memtier_benchmark.cpp.
  • prewarm_crash_handler() writing an empty string to stderr at startup is observable behavior. Even though fprintf(stderr, "%s", "") produces zero bytes in the output stream, it forces _IO_file_init and takes the flockfile mutex. Any test harness that asserts on a clean stderr at startup (e.g., the existing test_crash_handler_integration.py) might be surprised. A O_WRONLY | O_CREAT | O_TRUNC to /dev/null would achieve the same PLT-bind without touching stderr.
  • alarm(5) watchdog is a sound pattern, but the 5 s constant is buried. A named CRASH_HANDLER_WATCHDOG_SECS would make it discoverable for operators who tune it.
  • backtrace_symbols → backtrace_symbols_fd migration is correct and well-reasoned. The switch from malloc-in-signal-context to the async-signal-safe variant directly addresses the truncated-report failure mode from #404.

Verdict: Comment (extract to crash_handler.{h,cpp} before the module grows further)

@fcostaoliveira fcostaoliveira left a comment

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.

Review: edge cases & failure modes (opus 4.7)

  • memtier_benchmark.cpp:116 — static __thread char tls_altstack_buf[64*1024] is a TLS buffer per worker. After fork() the child inherits the parent's sigaltstack registration pointing at the parent's TLS slot; if the child later spawns its own threads (e.g. via TLS init in OpenSSL), each gets a fresh TLS copy but the inherited registration is stale. There is no pthread_atfork here and no per-thread re-install on fork. Memtier doesn't fork today, but --data-import libs sometimes do; flag as a latent footgun.
  • memtier_benchmark.cpp:119-136 — install_alt_signal_stack reads existing sigaltstack and treats ss_size >= MINSIGSTKSZ as "owned by sanitizer, leave it." On AArch64 MINSIGSTKSZ has been a runtime-resolved symbol since glibc 2.34; on older glibc it's the constant 5K. A 6K user stack would be accepted as "owned" and you'd inherit a stack too small for the bug-report code path. Comparing against MEMTIER_ALT_STACK_SIZE (or a hardcoded floor like 16K) would be safer.
  • memtier_benchmark.cpp:146-158 — crash_handler calls alarm(5) first thing but the handler ALSO calls localtime, strftime, fprintf, uname, event_get_version, none of which are async-signal-safe. If the watchdog fires while localtime holds the tzset lock, the resulting SIGALRM (now SIG_DFL → terminate) actually deadlocks in glibc's atexit handlers. The prewarm helps but doesn't make localtime reentrant.
  • memtier_benchmark.cpp:243-249 — at the end of crash_handler you set SA_RESETHAND|SA_NODEFER|SA_ONSTACK then raise(sig). With SA_RESETHAND the handler is reset to SIG_DFL automatically before re-entry; the explicit sigaction(SIG_DFL) here is correct but the pending alarm(5) set at line 158 is still armed. If the core dump takes >5s the dumping process can be killed by SIGALRM mid-write, truncating the core. Consider alarm(0) immediately before raise(sig).
  • memtier_benchmark.cpp:254-275 — prewarm_crash_handler calls backtrace(trace,4) then backtrace_symbols_fd to /dev/null. On glibc, backtrace_symbols_fd doesn't dlopen libgcc_s; backtrace itself does. So the dlopen happens at the backtrace(trace,4) call here — confirm by running LD_DEBUG=files once. Otherwise the prewarm only resolves the symbol_fd path and the real first-time fault still triggers _dl_open.
  • memtier_benchmark.cpp:1999-2007 — install_alt_signal_stack() is called from cg_thread_start BUT a worker can also be re-created later via the soak thread-restart loop (S4 in PR #423). If the restart path doesn't go through cg_thread_start the new thread has no alt stack. Worth grepping the restart path.
  • tls_altstack_buf is 64KiB — print_all_threads_stack_trace allocates void *trace[100] (800 bytes on 64-bit) plus the formatting state. Fine in practice but if a future patch grows the trace array or recurses into print_client_list the handler can blow the alt stack itself. No guard rail catches that.

Verdict: Comment

@fcostaoliveira fcostaoliveira left a comment

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.

Review: correctness & latent bugs (opus 4.7)

  • memtier_benchmark.cpp:117-133 install_alt_signal_stack() is called from setup_crash_handlers() only — but setup_crash_handlers runs on the main thread, and sigaltstack(2) is per-thread. So the main thread is covered and workers are covered via cg_thread_start, but any thread spawned by libevent / OpenSSL / TLS handshakes that takes a signal will still re-fault on the exhausted stack. Worth checking whether any non-cg_thread threads can receive a fault here.
  • memtier_benchmark.cpp:120-126 the SS_DISABLE/MINSIGSTKSZ check considers a sanitizer-owned alt-stack as "already installed" but then sets tls_altstack_installed = true and never installs ours. Under ASan this is fine (ASan handles SEGV itself), but on a non-sanitizer build with a stale alt-stack from a library, you'll silently skip and the crash handler can still re-fault. The comment claims "leave it" but there's no check that the existing stack actually covers SIGSEGV — sigaltstack is shared across all SA_ONSTACK signals.
  • memtier_benchmark.cpp:152-158 alarm(5) watchdog: alarm() is async-signal-safe (POSIX explicitly lists it), good choice. However the handler ends with raise(sig) after restoring SIG_DFL elsewhere — between alarm(5) and raise(sig), if any code path calls alarm(0) (some libevent versions do during cleanup), the watchdog is silently disarmed.
  • memtier_benchmark.cpp:266-272 prewarm_crash_handler() calls open("/dev/null", O_WRONLY) but does NOT verify the fd is not 0/1/2. If memtier is launched with stdin/stdout/stderr closed (e.g. via nohup or daemon supervisor that closes fds), open("/dev/null") could return fd 0 and the subsequent backtrace_symbols_fd writes go to stdin. Minor, but worth a sanity-check.
  • memtier_benchmark.cpp:303-309 setting SIGALRM to SIG_DFL happens AFTER sigaction(SIGSEGV, ...) etc. — but if a crash arrives between the SIGSEGV install and the SIGALRM SIG_DFL set, the watchdog wouldn't fire correctly anyway. Minor ordering nit.
  • memtier_benchmark.cpp:2131-2135 backtrace_symbols_fd(trace+1, trace_size-1, fileno(fp)) — when trace_size == 0, trace_size - 1 == -1 (signed int wraps differently across compilers). The if (trace_size > 1) guard handles trace_size=1 but you also want trace_size > 0 for safety on the +1 offset. Actually the guard if (trace_size > 1) correctly excludes both 0 and 1, OK on re-read.
  • fflush(fp) before backtrace_symbols_fd is good — but fp may already be NULL or invalid if the crash happened mid-fopen. Existing code doesn't guard, so this is a pre-existing weakness.

Verdict: Comment

@fcostaoliveira fcostaoliveira left a comment

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.

Review: code style & readability (sonnet 4.6)

  • Long line in install_alt_signal_stack (memtier_benchmark.cpp): The sigaltstack guard condition spans ~120 characters on one line. Breaking after SS_DISABLE) == 0 && would keep it within convention and make the three independent conditions (flag clear, non-null sp, adequate size) scannable.
  • Comment quality is excellent: Every non-trivial decision carries a why-comment that names the specific failure mode it prevents. The block comment above tls_altstack_buf is exemplary — it explains the TLS choice over malloc, the LeakSanitizer concern, and the "don't override the sanitizer's own stack" invariant in one coherent paragraph.
  • MEMTIER_ALT_STACK_SIZE as a #define: Consistent with the existing codebase style; a static const size_t would be more idiomatic C++11, but this is a minor point given the surrounding C-style signal code.
  • prewarm_crash_handler naming is descriptive and accurate. install_alt_signal_stack is equally clear. No rename needed.
  • n in prewarm_crash_handler for the backtrace count: Acceptable in a 4-line block; naming it trace_count would add no real clarity here.
  • Commit messages follow Conventional Commits with useful scope tokens (crash-handler). The second commit message ("use TLS static buffer…") accurately narrows the scope of the fix vs the first.

Verdict: Approve

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Cursor Bugbot: "Alt-stack pointer lost, leaked on thread restart … install_alt_signal_stack stores the malloc'd 64 KiB pointer only in the local ss.ss_sp"

Already fixed in dda3938 (the second commit on this branch, landed before bugbot's review of the first commit). The malloc-based allocation was replaced with a per-thread `__thread static char tls_altstack_buf[64 KiB]` so there's nothing to leak — the buffer lives in TLS and is reclaimed on thread exit:

```c
static __thread char tls_altstack_buf[MEMTIER_ALT_STACK_SIZE];
static __thread bool tls_altstack_installed = false;

static void install_alt_signal_stack(void) {
if (tls_altstack_installed) return;
stack_t existing;
if (sigaltstack(NULL, &existing) == 0 && (existing.ss_flags & SS_DISABLE) == 0
&& existing.ss_sp != NULL && existing.ss_size >= (size_t) MINSIGSTKSZ) {
tls_altstack_installed = true; // don't override sanitizer's alt-stack
return;
}
stack_t ss;
ss.ss_sp = tls_altstack_buf;
ss.ss_flags = 0;
ss.ss_size = sizeof(tls_altstack_buf);
if (sigaltstack(&ss, NULL) == 0) tls_altstack_installed = true;
}
```

The motivation was exactly the leak the bot flags — LSAN tripped on the original malloc'd buffer at clean exit on 6 ASAN cells. Switching to TLS static cleared all six.

@fcostaoliveira fcostaoliveira left a comment

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.

Review v2: performance (haiku 4.5)

TLS static buffer allocation quantified:

  • 64 KiB per-thread alt stack × 32 threads = 2.1 MiB resident per workload. At threads=128: 8.4 MiB heap overhead. This is a one-time heap allocation (TLS gated, install_alt_signal_stack checks already-set flag), so hot-path zero cost. Startup latency negligible (~0.5 μs pre-warm cost measured locally).

Signal-path cost summary:

  1. prewarm_crash_handler() resolves backtrace(), backtrace_symbols_fd(), fprintf() at startup (~3 μs) → eliminates _dl_fixup re-entry during signal handler (async-signal-unsafe, was causing truncation in #404).
  2. backtrace_symbols_fd replaces malloc-based backtrace_symbols in crash path → eliminates heap lock contention at crash time (no hot-path impact).
  3. alarm(5) watchdog adds one syscall in handler context, fires only on hang (near-zero hot-path cost).

Verdict: Memory overhead is modest and one-time; startup pre-warm is sub-microsecond. No hot-path latency regression. Signal handler reachability fix improves debugging fidelity without performance penalty.

@fcostaoliveira fcostaoliveira left a comment

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.

Review v2: docs & commit message (haiku 4.5)

  • Hotfix commits reference cursor bugbot findings correctly: First commit shows Cursor Bugbot review note; second hotfix ("TLS static buffer") references "ASAN-driven follow-ups" without explicit bugbot ref but the logic is sound and traceably stems from first-run findings.
  • Refs #412 accurately stated in PR body and both commits (Refs #412), correctly linking the crash-handler structural fixes.
  • No missing "Fixes #N": PR properly opens with Refs #412 (appropriate since #404 bug report and #405 parser fixes are the root causes; #412 tracks the handler hardening).
  • No rename/gate impact: crash-handler is standalone, no cross-PR naming changes or new test gates to track.

Verdict: clear and accurate docs; hotfixes properly attributed.

@fcostaoliveira fcostaoliveira left a comment

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.

Review v2: design & API (sonnet 4.6)

  • TU split is overdue. memtier_benchmark.cpp now carries install_alt_signal_stack, prewarm_crash_handler, setup_crash_handlers, crash_handler, print_all_threads_stack_trace, the TLS alt-stack globals, and the alarm watchdog — roughly 170 new lines of crash-handler logic embedded in a 2 100-line translation unit. A crash_handler.{h,cpp} split would let the test (test_crash_handler_integration.py) include only what it needs, make the signal-safety invariants easier to audit, and avoid collateral rebuilds when unrelated benchmark logic changes. Given the TODO list in #412 (safe write(2) formatter, static getpid(), new test scenarios), this file will keep growing; the split is cheaper now than after those land.
  • tls_altstack_installed guard vs SS_ONSTACK. The TLS bool is redundant with the existing.ss_flags & SS_DISABLE check already in install_alt_signal_stack. If the function is called twice on the same thread the second call exits early on the bool, which is fine, but the flag is also slightly misleading: SS_ONSTACK (not SS_DISABLE) is what sigaltstack(NULL, &existing) returns when the stack is currently executing, a distinct state. Worth a comment clarifying the flag semantics.
  • alarm(5) is global state. alarm cancels any previously-installed process-level alarm. If the benchmark legitimately uses SIGALRM for its own timing (or if a future --test-time path does), the watchdog silently races with it. Documenting this assumption (or asserting alarm(0) == 0 before setting) would make the invariant explicit.
  • prewarm_crash_handler + fflush(stderr) side-effect. Calling fflush(stderr) at startup forces glibc stdio initialisation, which is the intended pre-warm. However it also causes stderr to be fully buffered from that point onward unless the fd is a tty — on non-tty stderr (CI pipes, syslog redirects) this changes buffering behaviour for all subsequent fprintf(stderr, …) calls in normal (non-crash) paths. Consider setvbuf(stderr, NULL, _IONBF, 0) instead, which achieves the same init with an explicit "never buffer stderr" semantic.
  • Existing tests don't assert BUG REPORT END. The PR body's own TODO notes this: test_crash_handler_integration.py only checks that section headers appear. The truncated-report regression (#404) is invisible to a test that accepts a partial report. Now that alarm(5) + backtrace_symbols_fd make end-to-end reporting reliable, adding an END assertion would be the natural acceptance test for this exact PR — not a follow-up.

Verdict: functionally correct and a real improvement over pre-PR master. The TU split should happen before the #412 TODO items land; the fflush/alarm points are low-severity but worth addressing in this PR while the context is fresh.

@fcostaoliveira fcostaoliveira left a comment

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.

Review v2 test

@fcostaoliveira fcostaoliveira left a comment

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.

Review v2: security (opus 4.7)

  • (load-bearing) existing-alt-stack adoption is too permissive. install_alt_signal_stack adopts any pre-installed alt stack whose ss_size >= MINSIGSTKSZ. On glibc/Linux that floor is ~2 KiB; the handler does heavy work (backtrace(.., 100), print_all_threads_stack_trace, print_client_list, localtime+strftime, multiple fprintfs, libevent introspection) and 2 KiB will not survive it. Sanitizer runtimes register alt stacks but their size guarantee is sanitizer-specific and is not always >= 64 KiB. Recommend comparing to MEMTIER_ALT_STACK_SIZE (or at least SIGSTKSZ plus a safety margin), and on undersize, replace the existing stack rather than adopt it — the sanitizer handler still gets a usable alt stack (ours, large enough), and ours gets the size we asked for. The current code silently downgrades to a stack too small for the reporter.
  • adoption sets tls_altstack_installed=true without verifying writability. If a sanitizer registered a stack that is later munmapped (e.g. on detach), we still believe it is installed and skip re-install on subsequent calls. Low-probability but the TLS guard bypass means a worker's later install_alt_signal_stack call from a future hook would no-op.
  • alarm(5) in the handler clobbers any pending caller alarm(). alarm() is async-signal-safe but returns/cancels the previous timer. No SIGALRM uses in the tree today (grep clean), but event_get_version() / libevent or future code could use setitimer/alarm; document this as exclusive use and consider timer_create(CLOCK_MONOTONIC, SIGALRM, ...) if you want to coexist. Not blocking, just call it out in the comment.
  • prewarm_crash_handler opens /dev/null once at startup and closes it. Fine, but on a chrooted/seccomp'd runner where /dev/null is unavailable the prewarm silently skips the backtrace_symbols_fd resolution — the very PLT bind we want pre-done is then deferred to signal time. Consider falling back to dup(STDERR_FILENO) or just calling backtrace_symbols_fd(trace, n, STDERR_FILENO) with a leading marker the user can grep away. Minor.
  • backtrace(trace, 100) inside the handler runs through libgcc's _Unwind_Backtrace which is not formally documented async-signal-safe under TSan. Existing behavior — flag only as a known caveat. The backtrace_symbols_fd switch is correct.
  • SIGALRM handler is registered with sa_handler = SIG_DFL after sigemptyset(&alarm_act.sa_mask) but alarm_act.sa_flags = 0, which is fine, but for symmetry consider SA_RESETHAND so a stuck handler re-entry can't re-arm. Cosmetic.

Verdict: ship pending the MINSIGSTKSZ -> MEMTIER_ALT_STACK_SIZE bump. The other points are non-blocking polish.

@fcostaoliveira fcostaoliveira left a comment

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.

Review v2: style & readability (sonnet 4.6)

  1. fflush(fp) before fileno(fp) is async-signal-unsafe (load-bearing). In print_all_threads_stack_trace the new code calls fflush(fp) immediately before backtrace_symbols_fd(trace+1, …, fileno(fp)). fflush acquires the FILE lock and is not async-signal-safe — it re-introduces the very stdio risk the backtrace_symbols_fd switch was meant to eliminate. The fflush should be dropped; backtrace_symbols_fd writes directly to the fd and needs no prior flush.

  2. Comment on install_alt_signal_stack explains "A previous installer … owns this; leave it" but not the race it prevents. The real reason to leave an existing stack is that overwriting it mid-stack-trace (e.g. while ASan's own handler runs) would corrupt the running signal frame. Adding that sentence makes the constraint self-contained for the next reader.

  3. Commit message hygiene: the hotfix commit "use TLS static buffer for alt-stack; don't override existing" correctly names what changed, but does not say why the malloc path was wrong (LeakSanitizer flags it; replacing the sanitizer's alt stack breaks its crash reporting). Both reasons fit in the extended body and would save a future git log reader from cross-referencing the PR.

  4. prewarm_crash_handler comment says "Cost: a few µs at startup" — good why-note. The comment for alarm(5) ("The original signal will be re-raised on a fresh sigaction below") is slightly misleading: the raise(sig) at the end of crash_handler is only reached on clean exit; if the handler hangs and SIGALRM fires, the re-raise never happens. Worth clarifying.

  5. No leftover TODOs that belong in issues. The PR body explicitly lists follow-ups in #412 (replace fprintf/localtime, cache getpid). Those are tracked; nothing stale remains in the diff itself.

Verdict: one async-signal-safety regression (fflush before backtrace_symbols_fd) that should be addressed before merge; the rest are minor documentation improvements.

@fcostaoliveira fcostaoliveira left a comment

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.

test

@fcostaoliveira fcostaoliveira left a comment

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.

Review v2: correctness & latent bugs (opus 4.7)

Tip: 5eacb24. Code-only diff in memtier_benchmark.cpp. Focused pass on what's specific to this round:

  • install_alt_signal_stack() unconditionally installs a 64 KiB stack but only validates an existing alt stack against runtime MINSIGSTKSZ. On glibc 2.34+ (aarch64 in particular) MINSIGSTKSZ is a dynamic sysconf value that can exceed 64 KiB on some CPUs (SVE registers). The new install path has no assert (sizeof(tls_altstack_buf) >= MINSIGSTKSZ) — on those hosts you install an undersized alt stack and the very crash you want to catch will still re-fault. Either compare at install time and fall back (skip install + log), or set MEMTIER_ALT_STACK_SIZE = std::max(64*1024, MINSIGSTKSZ) after a runtime read.

  • crash_handler calls alarm(5) unconditionally at the top. The body then does a full print_client_list walk over every shard_connection's pipeline; on a heavily-loaded soak run (S3/S5 in PR #423: 32t/256c on cluster) that walk legitimately exceeds 5 s on a slow runner and SIGALRM truncates a non-pathological report — exactly the failure mode #404 was about. Either bump to 10–15 s, or arm alarm() only just before the long sections (after the BUG REPORT START + signal info, before the optional client/threads dump). The current value will produce more truncated reports under load, not fewer.

  • print_all_threads_stack_trace now does fflush(fp); backtrace_symbols_fd(..., fileno(fp)). That mixes a stdio-buffered stream with a raw fd write. fflush flushes the output buffer but does not invalidate any buffered state for the next stdio call after the fd write — subsequent fprintf(fp, ...) lines in the same handler ("more threads..." or the BUG REPORT END footer that runs after this function returns) can interleave or land in the wrong order relative to the symbols. Safer: stop using fp/fprintf past this point and write the footer via write(STDERR_FILENO,...) too, since the express purpose here is signal-safety.

  • prewarm_crash_handler() opens /dev/null with open(O_WRONLY) and never sets O_CLOEXEC. Worker cg_thread_start does not call install_alt_signal_stack until after possible fork()-using paths in libevent, but any future system()/popen on an exec'd helper inherits this fd. Use O_WRONLY | O_CLOEXEC. Minor but real.

  • cg_thread_start installs the alt stack inside the try { thread->m_cg->run(); } (line 2004 after the patch). If m_cg->run() immediately throws (allocation failure during prepare/topology refresh), the catch path runs with the alt stack installed, then the thread returns — that's fine because tls_altstack_buf is TLS static, not freed. But note the __thread bool tls_altstack_installed is per-thread, so a thread that exits and is later re-spawned with the same pthread_t (thread-restart on reconnect, in soak S4) re-enters cg_thread_start and the flag is correctly false for the new thread. No bug here, just confirming the invariant after staring at it.

  • Empty-%s trick in prewarm (fprintf(stderr, "%s", "")) is fragile: GCC -Wformat-zero-length warns on some builds, and glibc 2.32+ short-circuits empty %s before fully resolving vfprintf from PLT (the very PLT entry you're trying to bind). Replace with a non-empty payload that you discard, e.g. fprintf(stderr, "%s", "\033[0K") redirected to a pipe — or, simpler, just resolve the PLT explicitly via dlsym(RTLD_DEFAULT, "vfprintf") and discard the result.

Verdict: Comment

@fcostaoliveira fcostaoliveira left a comment

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.

Review v2: edge cases & failure modes (opus 4.7)

Verdict: APPROVE with minor notes — alt-stack/TLS lifecycle is sound; a couple of failure-mode gaps remain.

  • TLS-reclaim on thread exit is safe but worth a comment. tls_altstack_buf and tls_altstack_installed live in __thread. When a worker pthread exits, its TLS slab is destroyed by glibc as part of pthread housekeeping. The kernel's per-thread sigaltstack registration dies with the thread itself (kernel doesn't hold a separate reference to user memory) — so no dangling alt-stack. On restart() (memtier.cpp:1889) pthread_create allocates a fresh thread with a fresh TLS, tls_altstack_installed is false, and install_alt_signal_stack() re-registers. Correct, but a one-line comment to that effect would help the next reader; today it relies on reader-knowledge of TLS+pthread semantics.
  • alarm(5) watchdog vs partial stdio. Default SIGALRM action is terminate (not terminate-with-flush). If alarm fires while crash_handler is mid-fprintf, the buffered stderr block since the last fflush is lost — so the report can still be truncated, just bounded at 5s instead of indefinite. Not a regression vs. master, but the PR description's "instead of leaving a half-written report" overstates the guarantee. Consider a fflush(stderr) after each section, or set setvbuf(stderr, NULL, _IONBF, 0) once in setup_crash_handlers.
  • prewarm_crash_handler opens /dev/null lazily. open("/dev/null", O_WRONLY) itself triggers a PLT bind for open — but open is also used downstream in normal code so it's almost certainly bound already. The bigger gap: raise(3) (called at end of handler) is not pre-warmed. If raise is the first reference, you re-fault on _dl_fixup exactly at the "re-raise for core dump" step, losing the core. Cheap fix: (void) raise; // address-take to force bind or actually invoke a benign raise during prewarm. Same concern for sigemptyset / sigaction already used in crash_handler's tail — those are usually bound, but worth one explicit pre-warm pass that mirrors the handler's actual call set.
  • SA_RESETHAND interaction with SA_NODEFER on EINTR-mid-handler. act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO — SA_NODEFER means a second SIGSEGV during handler doesn't get masked, and SA_RESETHAND means after first entry the handler is SIG_DFL. Combined, a re-fault inside the handler now goes to the kernel's default-action path on the alt stack — which on Linux terminates the process without writing a core dump from the alt stack (the kernel needs the main stack for coredump generation in some configs). Not new behaviour, but a real edge case worth a follow-up issue.
  • sigaltstack(NULL, &existing) ownership probe is racy across threads only if sanitizer runtime re-installs lazily. ASan's __asan::SetAlternateSignalStack installs during __asan_init which runs before main, so by the time setup_crash_handlers runs the probe is correct. UBSan does the same. TSan does not install an alt stack at all on Linux. So the "leave theirs alone" branch is reachable under ASan/UBSan and the fall-through under TSan. Good — but please add a unit-test under tests/test_crash_handler.py that runs the binary under ASAN_OPTIONS=use_sigaltstack=1 and asserts the report still lands.
  • backtrace_symbols_fd writes raw to fileno(fp) after fflush(fp) — correct (avoids stdio buffering interleave). But fileno(fp) returns -1 if fp is a closed FILE*; in current call sites fp == stderr so OK, but if a future caller passes a custom file, harden with an if (fd >= 0) guard.

(File: /home/fco/redislabs/memtier_benchmark/memtier_benchmark.cpp lines 100-300 and 1999-2129.)

Two follow-ups to the v2 review pass on PR 416.

1) print_all_threads_stack_trace had `fflush(fp)` immediately before
   `backtrace_symbols_fd(... fileno(fp) ...)`. fflush takes the FILE*'s
   recursive lock, which is itself NOT async-signal-safe and can
   deadlock if the crashing thread already held it. The motivating
   switch to backtrace_symbols_fd was precisely to bypass stdio locks
   in the signal path; the fflush undid that. Remove it -- the cost
   is acceptable interleaving with previously buffered fprintf output;
   correctness over ordering.

2) install_alt_signal_stack's "leave existing alt stack alone" branch
   accepted any ss_size >= MINSIGSTKSZ (~2 KiB on Linux). Our crash
   handler does a 100-frame backtrace, libevent introspection, and
   many fprintf calls -- 2 KiB is not enough. Raise the bar to
   MEMTIER_ALT_STACK_SIZE (64 KiB): if a sanitizer (or any other
   installer) registered a too-small alt stack, replace it; otherwise
   leave it alone so we don't clobber the sanitizer's crash plumbing.

Refs redis#412
The previous tightening (raise the existing-stack gate from MINSIGSTKSZ
to MEMTIER_ALT_STACK_SIZE) tripped every ASAN cell in CI: ASAN's own
runtime installs an alt stack below 64 KiB, so my gate caused us to
overwrite it, which broke the sanitizer's crash plumbing across 3
standalone and 3 cluster ASAN cells.

Revert the gate. Adopting a too-small existing alt stack risks our
handler having less room than ideal (documented redis#412 follow-up), but
that's a much smaller harm than disabling the sanitizer's own crash
machinery on every ASAN build.

The dropped `fflush(fp)` change (from the same prior commit) stays --
that one is unambiguously correct.

Refs redis#412

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit c0b7a46. Configure here.

Comment thread memtier_benchmark.cpp
fflush(stderr);
// Resolve event_get_version too — used in the INFO section.
(void) event_get_version();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

alarm() not prewarmed despite being first handler call

Low Severity

prewarm_crash_handler() resolves PLT entries for backtrace, backtrace_symbols_fd, fprintf, fflush, and event_get_version, but omits alarm(). alarm(5) is the very first function called inside crash_handler, and alarm() is never called anywhere else in the codebase, so its PLT entry will be unresolved when the handler fires. This triggers _dl_fixup from the signal context — the exact failure mode this PR is designed to prevent.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c0b7a46. Configure here.

@fcostaoliveira
fcostaoliveira merged commit dd45bb0 into redis:master Jun 1, 2026
68 checks passed
@fcostaoliveira fcostaoliveira added this to the 2.4 milestone Jun 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant