Repository navigation
Handle SIGTERM like Ctrl+C so --json-out-file stays valid - #706
Conversation
|
🤖 Automated first-pass review — a human maintainer's review is still required before merge. Thanks for this. I went through the handler, the
Nitpicking: the Also noting the textual conflict with #707 on the The core fix looks solid to me. I'd mainly like the exit-status question (1) settled explicitly by a maintainer before this merges. (would file this as a comment, not a formal block) |
80d55e6 to
8b5bec4
Compare
|
Thanks. Both points are addressed in 8b5bec4.
Also in this push: rebased onto #698. Its |
|
Follow-up on Q1, in cdf2f65. The escalation from 8b5bec4 counted one user action as two signals. Ctrl+C on Now only a signal at least 1 s after the first resets to New test
|
Only SIGINT had a handler. SIGTERM, which kill, timeout, docker stop, Kubernetes and most CI runners send, took the default action and killed the process on the spot. The JSON file is opened and the configuration section written at startup, while the results and closing braces are written only at the end, so the file was left truncated and could not be parsed. Install the existing handler for SIGTERM too. It goes through the same g_interrupted path: threads are stopped, results are printed, the JSON file is closed and its Runtime section says "Interrupted": "true". The handler now records the signal so the stderr message names SIGTERM instead of claiming a Ctrl+C; the SIGINT message is unchanged. Fixes #704 Co-Authored-By: Claude Opus 5.5 <[email protected]>
After the rebase onto #698, its "skipping the remaining runs" note still said "Interrupted by user (Ctrl+C)" for a SIGTERM. It now names the signal, like the per-run interrupt message, through one helper. A second SIGINT or SIGTERM now resets the handler to the default action and re-raises, so it terminates memtier immediately. This keeps a way out of a shutdown that is stuck, which a process without a handler always had. Document the interrupt behaviour in the README and the --run-count help line (and man page), and add tests: SIGTERM during run 1 and in the settle pause of --run-count 3, and a second SIGTERM killing memtier while it is held in open() of a --json-out-file FIFO. Fixes #704 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The second-signal escalation counted one user action as two signals. Ctrl+C on `timeout ... memtier` delivers SIGINT twice within microseconds (the terminal signals the foreground group and timeout forwards it), and process-group kills (kill -TERM -pgid, systemd, CI tree kills with a wrapper in the group) do the same. The duplicate killed memtier at once with invalid JSON, a regression from master for SIGINT. Record the CLOCK_MONOTONIC time of the first signal and escalate only for a signal at least 1 s later; signals inside that second are ignored. clock_gettime(), the lock-free atomic CAS, signal() and raise() are all async-signal-safe. Fixes #704 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d atomic json_handler printed the fopen() error and went on writing to a NULL FILE *, so an unwritable --json-out-file crashed memtier with SIGSEGV. Under TSAN the same happened when SIGTERM interrupted a fopen() blocked on a FIFO: its interceptor does not restart the call, so fopen() returns EINTR. Retry on EINTR, and otherwise print "error: cannot open --json-out-file PATH: REASON" and exit 1. TSAN also flagged the signal handler: the kernel may run it on a worker thread while the main thread reads g_interrupted (a data race on a volatile sig_atomic_t), and clock_gettime()/raise() may change errno. Make g_interrupted a std::atomic<int>, save and restore errno in the handler, and static_assert that the int and long long atomics it uses are lock-free, so the handler stays async-signal-safe. Fixes #704 Co-Authored-By: Claude Opus 5.5 <[email protected]>
cdf2f65 to
2ac9ebd
Compare
std::atomic<long long> is not lock-free on every target (e.g. armv5te), and the handler must only use lock-free atomics to stay async-signal-safe. Store the first signal's CLOCK_MONOTONIC time as ms modulo 2^32 in an std::atomic<unsigned int> (0 = no signal yet) and take the difference modulo 2^32 as well, so the wrap every ~49.7 days cannot break the ">= 1000 ms later" test. Only the ATOMIC_INT_LOCK_FREE assert remains. State the exit-status contract in the README: 0 after a graceful interrupt (with "Interrupted": "true" in the JSON), death by the signal after a second one. Make the --run-count test helper signal-neutral. Fixes #704 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
On the rewritten review, as of 9df22b9 (rebased on f308ed6):
Also, the Each signal test was re-run 3x on the normal build and 3x on the TSAN build (CI suppressions, |
|
Re the automated review posted at 12:42, which crossed with my 12:41 reply:
|
main() only perror()'d a failed fopen() of --out-file and carried on with outfile == NULL. The whole benchmark ran (the full --test-time), and then the first fprintf(outfile, ...) of the results crashed with SIGSEGV (rc 139), losing the run and printing the crash-handler bug report. Treat it as a fatal configuration error, the same way #706 now handles an unopenable --json-out-file: print "error: cannot open --out-file PATH: REASON" and exit 1. The open still happens before any connection or thread is started, so no run is wasted. fopen() is retried on EINTR, as json_handler does. Regression test test_out_file_unwritable in tests_oss_simple_flow.py uses a path in a non-existent directory with --test-time 60 and expects exit 1, the message, no "Launching threads", and an exit within 20 s. Fixes #716 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Decision: the first SIGTERM now takes the same graceful path as Ctrl+C (SIGINT). Threads stop, results are printed,
--json-out-fileis closed as valid JSON with"Interrupted": "true", and memtier exits 0, as it does after Ctrl+C. A second SIGINT or SIGTERM sent at least 1 s after the first ends memtier immediately (default action, rc -15 / 143 from a shell), so a stuck shutdown can still be killed. Signals within that second count as the same interrupt: Ctrl+C undertimeoutand process-group kills deliver the signal twice. If a maintainer prefers a hard kill on the first SIGTERM, the alternative is to document that next to the Ctrl+C behaviour.Problem
Only SIGINT had a handler. SIGTERM, which
kill,timeout,docker stop, Kubernetes and most CI runners send, killed the process at once. The JSON file is opened and the configuration section is written at startup (new json_handler(...)). The results and the closing braces are written only at the end (delete jsonhandler), so the file was left with about 1.8 KB of configuration and could not be parsed (JSONDecodeError: Expecting property name ... line 74).Root cause
main()calledsignal(SIGINT, sigint_handler)and ignored SIGPIPE, but never installed a handler for SIGTERM, so SIGTERM took the default action.Fix
Same handler for SIGTERM.
sigint_handleris installed for SIGTERM too, so SIGTERM goes through the sameg_interruptedpath.Signal number recorded. The handler stores the signal number; every reader only tests it as true/false. A small
interrupt_source()helper picks the label (SIGTERMoruser (Ctrl+C)) for both stderr messages:[RUN #N] Interrupted by SIGTERM after X secs, stopping threads...Interrupted by SIGTERM, skipping the remaining runs (N of M done)., the--run-countnote added by Stop the --run-count series on Ctrl+C #698. It is printed both when the signal hits a run and when it lands in the settle pause between runs, where no run was interrupted.Second signal. The handler records the
CLOCK_MONOTONICtime of the first signal, as ms modulo 2^32, in a lock-freestd::atomic<unsigned int>CAS (0 means no signal yet). The difference is also taken modulo 2^32, so the wrap every ~49.7 days cannot break the 1 s test. A later signal at least 1 s after it resets the signal toSIG_DFLand re-raises it, so memtier terminates at once. This keeps the escape hatch SIGTERM had before (and adds one for a deliberate second Ctrl+C). Signals within 1 s are ignored, because one user action often delivers two:timeout ... memtier: the terminal signals the whole foreground group andtimeoutforwards the signal.kill -TERM -pgid, systemd cgroup kills, CI process-tree kills.clock_gettime(), the CAS,signal()andraise()are all async-signal-safe.Docs. New README section "Interrupting a run". It states the exit status: 0 after a graceful interrupt, with
"Interrupted": "true"in the JSON; death by the signal (130/143 in a shell) after a second signal. The--run-counthelp line and man page now say that Ctrl+C or SIGTERM ends the series.Group-signal check,
--run-count 3. Each cell is rc and the JSON result:timeout 100 memtier, group SIGINTtimeout 100 memtier, group SIGTERMStartup and thread safety (2ac9ebd)
--json-out-fileexits cleanly.json_handlerused to print thefopen()error and then callfprintf(NULL, ...), which crashed with SIGSEGV. This was already reachable on master with an unwritable path: rc -11. With this PR it was also reachable under TSAN, where SIGTERM interrupting afopen()blocked on a FIFO returns EINTR, because TSAN's interceptor does not restart the call.fopen()is now retried on EINTR. Any other failure printserror: cannot open --json-out-file PATH: REASONand exits 1.test_json_out_file_unwritableuses a path in a non-existent directory and expects rc 1 plus that message. It fails on master (rc -11) and passes on this head.g_interruptedis nowstd::atomic<int>. TSAN reported a data race when the handler runs on a worker thread while the main thread reads the flag. The handler also saves and restoreserrno, which fixes TSAN's "signal handler spoils errno" report.static_assert(ATOMIC_INT_LOCK_FREE == 2)keeps the handler async-signal-safe. The handler uses only int-sized atomics, which are lock-free on every target we ship. In 9df22b9, the first-signal time moved fromlong longtounsigned int, so no 64-bit atomic is needed.TSAN results (
--enable-thread-sanitizer, CI'stsan_suppressions.txt,setarch -R):At 9df22b9 each signal test was re-run 3x on the normal build and 3x on the TSAN build. The tests: the five SIGTERM/second-signal/duplicate tests,
test_json_out_file_unwritable, and the four existingtest_interrupt_*tests. All passed: 30/30 normal, 30/30 TSAN.Interaction with #698 and #707
--run-countpath: the skip note names the signal, and the new tests reuse its_run_count_interrupted()helper with asigargument."[RUN #%u] Interrupted by user (Ctrl+C) after %.1f secs"fprintfto use wall time,ts_diff(cfg->benchmark_start_time, now). The two PRs conflict on that line. Whichever lands second must keep both Report connection errors and Ctrl+C of clients that never connected #707's wall time and theinterrupt_source()label from this PR. Report connection errors and Ctrl+C of clients that never connected #707's test regexInterrupted by user \(Ctrl\+C\) afterstill matches, because the SIGINT text is unchanged.Test evidence
New tests in
tests/tests_oss_simple_flow.py:test_sigterm_closes_json: SIGTERM 2 s into a 60 s run. Checks rc 0,Interrupted by SIGTERM afteron stderr, a JSON file that parses,Runtime.Interrupted == "true", and a duration under 10 s.test_sigterm_stops_run_count: SIGTERM during run 1 of--run-count 3. Checks rc 0, a single run (no[RUN #2),Interrupted by SIGTERM, skipping the remaining runs (1 of 3 done),"Runs completed": 1, valid JSON, and the Interrupted flags.test_sigterm_between_runs_stops_run_count: SIGTERM in the settle pause after run 1. Same checks, plus noInterrupted by SIGTERM afterline, since no run was interrupted.test_second_signal_terminates:--json-out-fileis a FIFO with no reader, so memtier blocks inopen()at startup; this is deterministic. After the first SIGTERM memtier must still be alive 1.5 s later; after the second, sent outside the 1 s window, it must exit with rc-15within 5 s.test_duplicate_signal_counts_once: three cases, each asserting rc 0 and a valid JSON file withInterrupted: "true":timeout 100 memtierin its own session, with SIGINT sent to the group (os.killpg);Results against a standalone redis, one run per cell plus repeat runs:
timeoutgroup SIGINT rc -2, both invalid JSON)These existing tests still pass with this head:
test_interrupt_signal_handling,test_interrupt_stops_run_count,test_interrupt_between_runs_stops_run_count,test_interrupt_last_run_marks_aggregate,test_sigpipe_immunity.py, andtest_prometheus.py:test_F27_interrupt_run_end_counts_every_op.Affected versions
1.2.9 through 2.5.2 (latest) and master.
Fixes #704
🤖 Generated with Claude Code
Note
Medium Risk
Changes async signal handling and shutdown paths that affect all benchmark runs and JSON output; behavior is well-tested but signal-handler logic is inherently sensitive.
Overview
SIGTERM now follows the same graceful shutdown path as Ctrl+C: threads stop, results print,
--json-out-filefinishes with"Interrupted": "true", and the process exits 0. Interrupt messages name the source (SIGTERMvs Ctrl+C), including when--run-countstops after the current run or during the settle pause.The signal handler records which signal arrived (
std::atomic<int>), coalesces duplicate signals within ~1s (e.g.timeoutor process-group kills), and re-raises the signal after 1s so a stuck shutdown can still be killed immediately. SIGTERM is registered alongside SIGINT.json_handlerretriesfopen()on EINTR (e.g. FIFO + signal during open) and exits with a clear error instead of continuing with a nullFILE *.README,
--help, and the man page document interrupt behavior; integration tests cover SIGTERM, double-signal escalation, duplicate signals, and unwritable JSON paths.Reviewed by Cursor Bugbot for commit 2ac9ebd. Bugbot is set up for automated code reviews on this repo. Configure here.