Skip to content

Send TSan crash tests' SIGSEGV only while the main thread sleeps - #828

Merged
fcostaoliveira merged 7 commits into
masterfrom
claude/tsan-crash-tail-20261024
Oct 24, 2026
Merged

fcostaoliveira merged 7 commits into
masterfrom
claude/tsan-crash-tail-20261024

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

test_crash_handler_time_zone_lock_held fails intermittently in the TSan job "OSS-CLUSTER API: TCP TLS (misc)". It exits -14 (the 5 s crash-report watchdog) instead of -11, after printing part of the CLIENT LIST and no END line. It failed on master 1c4c897 (run 40071862306) and on #812's merge commit (run 40009383163). Because of continue-on-error (#827), the master failure went unnoticed.

Root cause

The tests send SIGSEGV with kill(2), and the kernel gives it to the main thread. TSan runs a SIGSEGV handler immediately, as it would for a real fault, whatever that thread was doing. On the failing runs, the main thread was inside the TSan runtime reporting the progress counters' known race (run_stats::get_total_ops). That race is suppressed, but TSan still builds and symbolizes the report before matching the suppression. While doing so, the thread holds the runtime's report, thread-registry and slot locks. The crash handler then needs one of those locks on the same thread, so it waits forever until the watchdog fires. Two paths reproduce this under GDB on a 3-shard TLS cluster:

  • The crash report's first fresh race: print_client_list reads a worker's shard_connection::get_port. This hung 2 of 4 runs, one of them stopping at exactly the hosted row.
  • The handler filling the thread's TSan trace part, which needs ctx->slot_mtx. This hung 4 of 4 runs.

A fault in memtier's own code (or libevent/OpenSSL) does not arrive inside the TSan runtime, so memtier itself needs no change. An external kill -SEGV to a TSan build, or a fault inside libtsan itself, could still meet the same deadlock; that only affects TSan builds. TSan's ignore annotations would remove the first path but not the second, because function entries and interceptor events are still traced.

Fix

Test-only change. For TSan builds, the helper:

  1. stops the process with SIGSTOP;
  2. checks in /proc that the main thread is in nanosleep/clock_nanosleep called from libc's code, i.e. the progress loop's sleep;
  3. if so, sends SIGSEGV to it with tgkill(2); then continues the process;
  4. otherwise continues the process and tries again, failing clearly after 10 s.

test_crash_handler_with_active_connections uses the same helper. On TSan the log now names the thread that is actually signalled (always the main thread). The watchdog, the report assertions and non-TSan builds are unchanged. Two docstrings that wrongly said TSan defers SIGSEGV are corrected; the stderr-lock test stays skipped on TSan, and whether its old CI hang has the same cause is not verified.

Tests

  • Seeded A/B on a 3-shard TLS cluster with auth: the current helper hung 13/20 (every hang inside libtsan); this helper hung 0/20 (all signals landed in libc sleep), with at most 0.21 s of extra wait.

  • test_crash_handler_integration.py under TSan with this change: 10× standalone and 10× on a 3-shard TLS cluster with auth, 0 failures. time_zone_lock_held passed 20/20.

  • make check: 18/18.

  • Head cd72b04 (after review fixes: crash timings start at the signal itself, a ptrace permission error fails fast, the log names the thread actually signalled, the helper fails fast if memtier exits, SIGSTOP is always paired with SIGCONT, both signalling tests kill memtier if the helper raises, the blocked-stderr test fills its pipe only while the main thread is held asleep, and glibc's pre-2.34 libc-<ver>.so name is accepted): test_crash_handler_integration.py under TSan standalone with auth, 5 passed, the stderr-lock test skipped as before; a non-TSan run passes 6/6.

Affected versions

CI only; no product code changes. The failing test and its TSan kill(2) injection were added in 400b637 (#755), which is unreleased; no release tag contains it. Related: #827 (TSan failures masked) and #412 (crash-tail safety). This does not change #412's scope for real crashes.

🤖 Generated with Claude Code

fcostaoliveira and others added 3 commits October 24, 2026 11:02
The TSan crash-handler tests sent SIGSEGV with kill(2). The kernel gives
it to the main thread, and TSan runs a SIGSEGV handler at once, as for a
real fault, whatever that thread was doing. When the main thread was
inside the TSan runtime reporting the progress counters' known race
(run_stats::get_total_ops, suppressed but still built and symbolized),
it held the runtime's report, thread-registry and slot locks. The crash
report's first fresh race (print_client_list reading a worker's
connection fields) or trace-part switch then waited for those locks on
the same thread forever, and the 5 s watchdog killed the process with
part of the CLIENT LIST printed and no END line. That is the
intermittent -14 of test_crash_handler_time_zone_lock_held in the TSan
"OSS-CLUSTER API: TCP TLS (misc)" job. A real crash cannot interrupt the
runtime, so this only affects how the tests inject the signal.

For TSan builds, stop the process, check that the main thread is in
nanosleep or clock_nanosleep called from libc (the progress loop's
sleep), send SIGSEGV to it with tgkill(2) and continue the process;
otherwise continue it and try again. The watchdog and the report
assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A fault inside the TSan runtime itself, or an external SIGSEGV, can
still meet the same deadlock; only faults in memtier's own code cannot.
The stderr-lock test's skip no longer says TSan defers SIGSEGV.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rrors

On TSan builds the SIGSEGV goes to the main thread, but the worker
tests still logged a worker TID; log the actual target in
_signal_thread(). Fail fast when the process exits while the TSan helper
waits for it to stop, and kill memtier if the helper raises in
test_crash_handler_with_active_connections.

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

github-actions Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

🤖 Automated first-pass review — a human maintainer's review is still required before merge.

Thanks, the root-cause write-up is clear. Stopping the process and signalling the main thread only while it is in libc's sleep is a reasonable way to keep the injection out of the TSan runtime, and the A/B numbers (13/20 hangs before, 0/20 after) back it up.

One question about timing in _crash_worker. start and sent_at are still taken before _signal_thread(), and on TSan that call can now spend up to 10 s retrying in _signal_tsan_main() before the SIGSEGV is actually sent. That wait gets counted toward elapsed (the asserts allow 8, 9 and 10 s) and toward the header-time check (5 s tolerance). You measured at most 0.21 s of extra wait, so this isn't a problem today. But if the helper is slow on a loaded runner, I think the failure would blame the watchdog or the time-zone header instead of the helper. Did you consider taking the timestamps right before the tgkill, for example by having the helper return them or by setting them in the before_signal callback?

Nitpicking: if reading /proc/<pid>/syscall fails because of ptrace permissions (e.g. in a locked-down container), _main_thread_sleeping() quietly returns False and the error says the thread "was not seen asleep". It might be worth logging the OSError once so that case is easier to tell apart.

Apart from that, this looks good to me. It's test-only and the non-TSan path is unchanged.

@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 using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit dc873f9. Configure here.

Comment thread tests/test_crash_handler_integration.py Resolved
fcostaoliveira and others added 3 commits October 24, 2026 11:47
…per raises

Send SIGSTOP inside the try whose finally sends SIGCONT, and give
test_crash_handler_worker_thread the same cleanup as
test_crash_handler_with_active_connections.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eeps

On TSan the signal goes to the main thread only while it sleeps between
progress lines. test_crash_handler_watchdog_blocked_stderr filled stderr
first, so a main thread caught mid-tick blocked on its next progress
write, never slept again, and the helper timed out. Run the callback with
the main thread held in that sleep instead.

Also accept glibc's pre-2.34 libc-<version>.so name in the sleep check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
On TSan the helper can wait before it sends the SIGSEGV. Take start and
sent_at right before the signal, so a slow helper is not blamed on the
watchdog or the crash report's time header. A permission error reading
/proc/<pid>/task/<pid>/syscall now says so instead of timing out as
"not seen asleep".

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

Copy link
Copy Markdown
Collaborator Author

Thanks, both points are taken in cd72b04:

  • Timing: start and sent_at are now set in the before_signal callback, after before_crash and right before the tgkill, so the helper's wait no longer counts toward elapsed or the time-header check. The TSan run now shows the watchdog exits at 5.0 s from the signal.
  • ptrace permissions: a PermissionError reading /proc/<pid>/task/<pid>/syscall now raises at once with "cannot read the main thread's system call: ..." instead of retrying until "was not seen asleep".

Also in e605dfe, from review: test_crash_handler_watchdog_blocked_stderr fills its pipe only while the main thread is held asleep (filling first could block main on a progress write so it never slept again), and the libc check accepts glibc's pre-2.34 libc-<ver>.so.

🤖 Generated with Claude Code

Picks up #838, the staircase drain bound that failed this branch's TSan
cluster job.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira
fcostaoliveira merged commit 7ae8c76 into master Oct 24, 2026
150 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 24, 2026
Picks up #828 (TSan crash tests signal only while the main thread
sleeps), which fixes this branch's red TSan crash-handler job, and #838.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 24, 2026
Picks up #812, the reconnect deadline-clock fix for the never-started
client test that failed this branch's plaintext job, plus #828, #838 and
#841.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
## Problem

`redis_protocol::parse_response()` does signed arithmetic on lengths and counts that come from the server. An oversized value makes that arithmetic overflow, which is undefined behaviour (#831):

- `$9223372036854775807` (and `$99999999999999999999`, which `strtol` clamps to `LONG_MAX`): `m_bulk_len + 2` overflows `long` in `rs_read_bulk` (`protocol.cpp:864`). The same happens for RESP3 `!` and `=`.
- RESP3 `%1073741824` / `|1073741824`: `count *= 2` overflows `int` (`protocol.cpp:723`).
- With per-element miss tracking, nested counts such as `*2\r\n*2147483646\r\n*3\r\n` overflow `m_nested_remaining` (`protocol.cpp:747`). So does a nested RESP3 attribute followed by a large count, e.g. `*1\r\n*2\r\n|0\r\n*2147483647\r\n`: the `|` takes a parent slot without being tracked.
- Not UB, but wrong: a count above `INT_MAX` is truncated when stored in `int`, so `*2147483648` is read as a null array.

The existing fixture `bulk_int_overflow.bin` reaches the first case. `test_bulk_int_overflow` still passed under `ubsan.yml` because `halt_on_error=1` without `abort_on_error` makes UBSan exit 1 after printing only `runtime error:`. The harness checks only for negative exit codes and a set of stderr needles that did not include that string. #545's libevent CI aborts on UBSan and failed on it with `exit_code=-6`.

## Root cause

- 84c922a (#134) changed `m_bulk_len` from `unsigned int` to a `long` read with `strtol`. Nothing bounds it, so `m_bulk_len + 2` can overflow.
- 1d5ac99 (#182) added the map/attribute doubling on an unbounded `int`.
- 61a261b (#472) added the `int` nested-element bookkeeping.

## Fix

- Bulk/blob: the length is parsed into a local first. If it is above `LONG_MAX - 2`, the parser returns the existing protocol error (`-1`, "error: response parsing failed.") without changing any parser state, and `line` is freed. Where `long` is 32 bits (LLP64, e.g. MSYS2/Windows), lengths above 2^31 - 3 are now rejected; before, they overflowed (UB) or waited forever.
- Aggregates: the count is parsed with `strtoll`, because `long` is 32 bits on Windows. Negative values are clamped as before. The parser then rejects the aggregate if its elements (doubled for `%`/`|`), plus the elements still outstanding, would exceed `INT_MAX`. A nested aggregate counts as one outstanding slot of its parent. When miss tracking is recording a nested element, the bound also uses `m_nested_remaining - 1`, because a nested attribute can leave `m_nested_remaining` larger than the outstanding count. This keeps `m_total_bulks_count`, `m_nested_remaining` and the doubling within `int`.
- Valid lengths and counts behave exactly as before. That includes `$-1`, `$0`, other negative lengths, `*-1`, and counts up to `INT_MAX`.
- `tests/test_resp_response_fuzzer.py`: add `runtime error:` and `LeakSanitizer` to the crash needles. UBSan is now caught whatever `abort_on_error` is set to. The fixture README is updated to match.

## Tests

- New `check_length_limits()` in `tests/unit/redis_protocol_test.cpp`. It covers the boundaries (LONG_MAX, LONG_MAX-1 and out-of-range bulk lengths are rejected, LONG_MAX-2 waits for data; INT_MAX vs INT_MAX+1 arrays; INT_MAX/2 vs INT_MAX/2+1 maps and attributes; maps nested under outstanding elements; nested outstanding at INT_MAX vs above it; the nested-attribute tracking case at and above the bound). It also checks that ordinary bulk, empty, null, map and nested replies still parse.
- Before (master `protocol.cpp` with the new tests), Ubuntu 24.04 / GCC 13 / system libevent:
  - normal build: `redis_protocol_test` reports 14 `FAIL` lines.
  - UBSan build: `runtime error` at `protocol.cpp:864:80` (`9223372036854775807 + 2`), `:723:27` (`1073741824 * 2`) and `:747:48` (`2147483646 + 2`).
  - `test_resp_response_fuzzer.py` with the CI `UBSAN_OPTIONS`: `test_bulk_int_overflow` FAIL, `needle 'runtime error:' exit_code=1`. With `abort_on_error=1`: FAIL, `exit_code=-6`.
- After:
  - `make check`: 18/18 in both the normal and the ASan+UBSan (`detect_leaks=1`, `abort_on_error=1`) builds.
  - `test_resp_response_fuzzer.py`: 12/12 in the normal build, in ASan+UBSan with the CI UBSan options, and in ASan+UBSan with `abort_on_error=1` (`ASAN_OPTIONS=detect_leaks=1:abort_on_error=1` throughout).
- The bulk boundaries in the unit test are built from `LONG_MAX` at run time, so the test also holds where `long` is 32 bits (MSYS2 UCRT64).
- `clang-format` 18 `--dry-run --Werror` is clean.

**Unrelated CI failure:** `TSAN OSS-CLUSTER API: TCP TLS (misc)` fails on 3b65721 and on the current head a92655a in `test_crash_handler_integration:test_crash_handler_time_zone_lock_held` (watchdog exit -14, missing BUG REPORT END). This is the known TSan crash-tail failure, tracked by #412 and targeted by #828. This PR does not touch the crash handler.

## Release notes

Behaviour change: an aggregate count above what the parser can represent (e.g. `*2147483648`, which used to be truncated and read as a null array) and a bulk length above `LONG_MAX - 2` are now protocol errors (`response parsing failed`). No real server sends these.

## Affected versions

- Bulk length overflow: 84c922a, every tag from 1.4.0 through 2.5.2 (not 1.3.0).
- Map/attribute doubling: 1d5ac99, 1.4.0 through 2.5.2.
- Nested miss-tracking overflow: 61a261b, 2.5.0 through 2.5.2.

Fixes #831



<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core RESP parsing on every connection; malformed oversized frames now error out instead of UB, but legitimate traffic within prior limits is unchanged.
> 
> **Overview**
> Hardens the Redis RESP parser in `parse_response` so malicious or oversized wire values cannot trigger integer overflow (UB) or silent truncation.
> 
> **Bulk/blob lengths** (`$`, `!`, `=`) are validated before updating parser state: if `strtol` yields a length above `LONG_MAX - 2`, parsing fails with `-1` instead of overflowing `m_bulk_len + 2` in the bulk-read path.
> 
> **Aggregate counts** (`*`, `%`, `|`, etc.) are read with `strtoll` (for 32-bit `long` on Windows), negative counts are still treated as zero, and counts are rejected when declared elements (×2 for maps/attributes) plus outstanding/nested miss-tracking slots would exceed `INT_MAX`. Valid replies behave as before.
> 
> **Tests/docs:** adds `check_length_limits()` unit coverage for boundary cases; extends the RESP fuzz harness crash needles (`runtime error:`, `LeakSanitizer`) and updates fixture README expectations.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit a7fe64f. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->






Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
Fixes #843.

The TSan crash tests SIGSTOP memtier and signal the main thread only once `/proc/<pid>/task/<pid>/syscall` shows it in a libc `nanosleep`/`clock_nanosleep` (#828). On arm64 the kernel clears the system call number before a group stop (`do_signal()` calls `forget_syscall()` before `get_signal()`). A thread stopped in a sleep therefore reads `-1 sp pc`, with pc moved back 4 bytes to the `svc` instruction so the call can restart. The `aarch64` entry in `_SYS_SLEEP` could never match, and the tests timed out with "not seen asleep within 10.0 s".

**Confirmed on aarch64 hardware** (Ubuntu 24.04 container, kernel 6.8). A process blocked in sleep reads `115 … pc` while running and `-1 sp pc-4` after SIGSTOP. `wchan` doesn't help, because a stopped thread always shows `do_signal_stop`.

**Fix (test only, `tests/test_crash_handler_integration.py`):**
- The helper reads the main thread's `syscall` file once just before the SIGSTOP.
- On aarch64, a stopped `-1` read whose pc is exactly 4 bytes before the pc of a sleep seen in that earlier read counts as that sleep.
- The sleep-number table and the check that the pc is in libc are unchanged.
- x86_64 takes the same path as before, plus one extra read before the stop.

I didn't drop the aarch64 entry and fall back to a plain `kill(2)`, because that's what #828 replaced after it hung 14 of 60 runs.

**Results** (aarch64 TSan build):

| | master | this PR |
|---|---|---|
| crash tests using the helper | 5 of 6 time out on every run (TCP and TLS) | all 6 pass, in 4 TCP and 4 TLS runs |

With the fix, the crash stack shows the signal arriving in libc `clock_nanosleep`, called from `sleep`. A unit check of the helper with mocked `/proc` files passes all 14 cases for both architectures.

Not changed: a sleep resumed after SIGCONT shows as `restart_syscall` and is still refused. The issue calls this a nit, and the tests don't hit it.


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Test-only changes to TSan crash integration helpers; no production crash-handler or runtime behavior is modified.
> 
> **Overview**
> Fixes **aarch64 TSan crash-handler integration tests** that timed out because the helper could not recognize the main thread as sleeping in libc after `SIGSTOP`.
> 
> The TSan signaling path still stops memtier and only delivers the crash signal when the main thread is in libc `nanosleep`/`clock_nanosleep`. The change **splits syscall inspection** into `_main_thread_syscall()` and extends `_main_thread_sleeping()` with an optional **pre-`SIGSTOP` snapshot**. On **arm64**, when `/proc/.../syscall` shows syscall number `-1` after a group stop but the PC is **4 bytes before** the PC from that snapshot, the code **reuses the earlier syscall number** (kernel clears it via `forget_syscall()`). `_signal_tsan_main()` now reads syscall state immediately before `SIGSTOP` and passes it through. x86_64 behavior is unchanged aside from one extra read; libc mapping checks and the sleep syscall table are the same.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 2b28c96. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant