Skip to content

Handle SIGTERM like Ctrl+C so --json-out-file stays valid - #706

Merged
fcostaoliveira merged 5 commits into
masterfrom
fix-704-sigterm
Oct 16, 2026
Merged

fcostaoliveira merged 5 commits into
masterfrom
fix-704-sigterm

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Decision: the first SIGTERM now takes the same graceful path as Ctrl+C (SIGINT). Threads stop, results are printed, --json-out-file is 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 under timeout and 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() called signal(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_handler is installed for SIGTERM too, so SIGTERM goes through the same g_interrupted path.

  • 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 (SIGTERM or user (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-count note 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.
    • The SIGINT texts are unchanged.
  • Second signal. The handler records the CLOCK_MONOTONIC time of the first signal, as ms modulo 2^32, in a lock-free std::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 to SIG_DFL and 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:

    • Ctrl+C on timeout ... memtier: the terminal signals the whole foreground group and timeout forwards the signal.
    • kill -TERM -pgid, systemd cgroup kills, CI process-tree kills.

    clock_gettime(), the CAS, signal() and raise() 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-count help 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:

case 8b5bec4 cdf2f65
two SIGTERMs back to back, sent directly -15, invalid 0, valid
timeout 100 memtier, group SIGINT -2, invalid 0, valid
timeout 100 memtier, group SIGTERM -15, invalid 0, valid

Startup and thread safety (2ac9ebd)

  • Unopenable --json-out-file exits cleanly. json_handler used to print the fopen() error and then call fprintf(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 a fopen() blocked on a FIFO returns EINTR, because TSAN's interceptor does not restart the call. fopen() is now retried on EINTR. Any other failure prints error: cannot open --json-out-file PATH: REASON and exits 1.
    • New test test_json_out_file_unwritable uses 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_interrupted is now std::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 restores errno, which fixes TSAN's "signal handler spoils errno" report.
  • Compile-time guard. 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 from long long to unsigned int, so no 64-bit atomic is needed.

TSAN results (--enable-thread-sanitizer, CI's tsan_suppressions.txt, setarch -R):

test cdf2f65 2ac9ebd
test_second_signal_terminates FAIL 3/3 (first SIGTERM crashes in fopen EINTR path) PASS 5/5
test_duplicate_signal_counts_once flaky: rc 66 (TSAN race + errno report) in 3 of ~19 runs PASS 5/5; 0/20 failures in a group-SIGINT loop
test_json_out_file_unwritable FAIL on master (rc -11, SIGSEGV) PASS 5/5

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 existing test_interrupt_* tests. All passed: 30/30 normal, 30/30 TSAN.

Interaction with #698 and #707

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 after on 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 no Interrupted by SIGTERM after line, since no run was interrupted.
  • test_second_signal_terminates: --json-out-file is a FIFO with no reader, so memtier blocks in open() 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 -15 within 5 s.
  • test_duplicate_signal_counts_once: three cases, each asserting rc 0 and a valid JSON file with Interrupted: "true":
    • two back-to-back SIGTERMs sent directly;
    • timeout 100 memtier in its own session, with SIGINT sent to the group (os.killpg);
    • the same, with SIGTERM to the group.

Results against a standalone redis, one run per cell plus repeat runs:

test origin/master b1c46f4 first commit only (10c87bd) head
sigterm_closes_json FAIL (rc -15, JSONDecodeError) PASS PASS (8/8 earlier)
sigterm_stops_run_count ERROR (JSONDecodeError) FAIL (note says Ctrl+C) PASS 6/6
sigterm_between_runs_stops_run_count ERROR (JSONDecodeError) FAIL (note says Ctrl+C) PASS 6/6
second_signal_terminates FAIL (first SIGTERM kills) FAIL (second ignored, timeout) PASS 5/5
duplicate_signal_counts_once FAIL (SIGTERM kills) - PASS 5/5 (fails at 8b5bec4: direct 2x SIGTERM rc -15, timeout group 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, and test_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-file finishes with "Interrupted": "true", and the process exits 0. Interrupt messages name the source (SIGTERM vs Ctrl+C), including when --run-count stops 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. timeout or 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_handler retries fopen() on EINTR (e.g. FIFO + signal during open) and exits with a clear error instead of continuing with a null FILE *.

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.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

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

Thanks for this. I went through the handler, the json_handler change and the new tests, and left a few comments. The regression tests fail on master and pass on the head, which is the bar we want for a JSON-output fix. test_sigterm_closes_json and test_json_out_file_unwritable pin both bugs directly.

  1. Exit status on SIGTERM is a behaviour change. Today a SIGTERM'd memtier dies by the signal (143 from a shell). After this PR it exits 0, and the only sign of the interrupt is "Interrupted": "true" in the JSON. That matches Ctrl+C, and the README now documents it. Still, I wonder if anyone relies on the old status: a k8s Job or a CI step that is killed mid-run would now report success instead of an error. timeout itself still returns 124, so that common case is fine. Did you consider exiting non-zero after an interrupted run, or would that be a bigger break for the existing SIGINT=0 behaviour? You already offered the alternative in the description, so this is a question for whoever owns the CLI contract, not a blocker.

  2. signal() vs sigaction(). The duplicate-coalescing logic, and test_second_signal_terminates, which expects open() on the FIFO to restart, both assume BSD signal() semantics: the handler stays installed and the call gets SA_RESTART. That holds on glibc and macOS. On a platform with SysV semantics, though, the handler would reset after the first delivery, and the "duplicate within 1 s" would kill the process. I think sigaction() with explicit SA_RESTART (and no SA_RESETHAND) would make the intent explicit and stop depending on the libc. It could also replace the signal(signum, SIG_DFL) call inside the handler. Not sure it's worth it if we only care about Linux/macOS. What do you think?

  3. Signals during startup. A SIGTERM that lands after the handler is installed but before run 1 starts (cluster slot discovery, TLS setup, a slow connect) is now swallowed until the run loop's first g_interrupted check. Previously it killed memtier at once. "Run 1 always runs" means it will start and then stop right away, which I guess is fine. But if startup itself is stuck, the user now needs a second signal more than 1 s later, where one used to do. I think that's acceptable since it's the same as SIGINT today; a sentence in the README's "Interrupting a run" section might be worth adding.

Nitpicking: the json_handler comment now says it "prints the error and exits". Calling exit(1) from a constructor is a bit surprising, but it matches how main() already handles other startup errors, so fine by me.

Also noting the textual conflict with #707 on the [RUN #%u] Interrupted by ... line, which you already called out. Whichever lands second needs to keep both changes.

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)

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. Both points are addressed in 8b5bec4.

  1. Second signal / escape hatch. Done as you suggested. If g_interrupted is already set, sigint_handler resets the signal to SIG_DFL and re-raises it, so a second SIGTERM or SIGINT terminates memtier at once, wherever it is stuck (setup, join, teardown). The first signal stays graceful.

    • The new test_second_signal_terminates checks this deterministically. --json-out-file points at a FIFO with no reader, so memtier blocks in open() at startup. After the first SIGTERM it must still be alive 1 s later; after the second it must exit with rc -15.
    • That test fails on master, where the first SIGTERM kills memtier, and on 10c87bd, where the second SIGTERM is ignored. It passes 6/6 on this head.
    • The existing SIGINT tests still pass.
  2. Exit code. It stays 0, matching Ctrl+C. Wrappers can still tell an interrupted run from a complete one through "Interrupted": "true" in the JSON Runtime section. This is now documented in a new README section, "Interrupting a run": graceful stop, valid JSON with "Interrupted": "true", exit 0, --run-count series stopped, and a second signal ending memtier immediately. The --run-count help line and man page also mention it. If the owners of the CLI/exit-code contract want a non-zero code for a signalled run, that would be a change for SIGINT as well, so I'd keep it out of this PR.

Also in this push: rebased onto #698. Its skipping the remaining runs note now names SIGTERM, and there are tests for SIGTERM during run 1 and in the settle pause of --run-count 3.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Follow-up on Q1, in cdf2f65. The escalation from 8b5bec4 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 do the same. So the duplicate killed memtier with invalid JSON.

Now only a signal at least 1 s after the first resets to SIG_DFL and re-raises. Signals within that second are treated as the same interrupt. The handler stores the first signal's CLOCK_MONOTONIC time with a lock-free atomic CAS, which is async-signal-safe.

New test test_duplicate_signal_counts_once covers three cases: two direct back-to-back SIGTERMs, and group SIGINT and group SIGTERM sent to timeout 100 memtier. Each case must give rc 0 and valid JSON with Interrupted: "true". It fails at 8b5bec4 (rc -15 and -2, invalid JSON) and passes 5/5 at cdf2f65.

test_second_signal_terminates now sends its second SIGTERM 1.5 s after the first, and passes 5/5. The README now says that a second signal more than about 1 s later kills immediately.

fcostaoliveira and others added 4 commits October 16, 2026 13:06
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]>
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]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

On the rewritten review, as of 9df22b9 (rebased on f308ed6):

  1. Lock-free assert. std::atomic<long long> and ATOMIC_LLONG_LOCK_FREE are gone.

    • The first signal's CLOCK_MONOTONIC time is now stored as ms modulo 2^32 in a std::atomic<unsigned int>. A stored 0 means "no signal yet"; a real 0 is stored as 1.
    • The ">= 1000 ms later" test is now - first >= 1000u in unsigned arithmetic, so the wrap every ~49.7 days gives the right difference. Only a second signal that arrives exactly a multiple of ~49.7 days after the first, within 1 s, would be misread as a duplicate.
    • Only static_assert(ATOMIC_INT_LOCK_FREE == 2) remains. It holds on every target we ship.
  2. Exit-code contract. The README section "Interrupting a run" now states it plainly:

    • exit 0 after a graceful interrupt (first SIGINT or SIGTERM), with "Interrupted": "true" in the JSON as the way to tell it from a complete run;
    • death by the signal after a second signal (130 / 143 in a shell), with an incomplete JSON file.

    I kept exit 0 because it matches what Ctrl+C has done since Signal Handling with Graceful Shutdown with metrics #325. A different code for SIGTERM would make the same interrupt report differently depending on how it was sent. A non-zero code for both would change the existing SIGINT contract, which this PR should not do silently. That can be a separate proposal if the owners want it.

  3. json_handler. The change stays in this PR because interrupting memtier during startup is what reaches it.

    • Under TSAN, a SIGTERM during a blocked fopen() returns EINTR, and the old code then wrote to a NULL FILE *.
    • The same crash was already reachable on master with an unwritable path. test_json_out_file_unwritable fails on master (rc -11, SIGSEGV) and passes here. It is now in the PR body's results table.
  4. EINTR retry. The retry is intended: the first signal only requests a graceful stop, so memtier keeps waiting for the open. Once the open succeeds, the run loop sees g_interrupted on its first check and stops with a complete JSON file. A second signal at least 1 s later kills it at once. This keeps test_second_signal_terminates meaningful, so I did not add an early exit right after the open.

Also, the _run_count_interrupted docstring now reads "seconds from the signal to exit", and sigint_when was renamed to signal_when.

Each signal test was re-run 3x on the normal build and 3x on the TSAN build (CI suppressions, setarch -R). The tests: test_sigterm_closes_json, test_sigterm_stops_run_count, test_sigterm_between_runs_stops_run_count, test_second_signal_terminates, test_duplicate_signal_counts_once, test_json_out_file_unwritable, and the four test_interrupt_* tests. All passed: 30/30 normal and 30/30 TSAN.

@fcostaoliveira

fcostaoliveira commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Re the automated review posted at 12:42, which crossed with my 12:41 reply:

  1. Exit status: the decision is deliberate. After a graceful interrupt the exit status is 0, matching Ctrl+C since Signal Handling with Graceful Shutdown with metrics #325. The README's "Interrupting a run" section now states the contract: 0 with "Interrupted": "true" in the JSON, and death by the signal (130/143) on a second signal. Making interrupted runs exit non-zero would also change the long-standing SIGINT behaviour, so it should be its own change if maintainers want it. The one-line alternative is in the PR description.
  2. signal() vs sigaction(): memtier builds on glibc, musl (the Alpine packages) and macOS. All three give signal() BSD semantics: the handler stays installed, SA_RESTART is set, and the signal is blocked while the handler runs. The coalescing logic and the FIFO test rely on exactly that. CI builds on all three, and runs the signal tests on glibc. Switching to sigaction() is a reasonable hardening, but it's not needed for any platform we ship. It would also mean changing the long-standing SIGINT registration too, so I've kept this PR to the minimal change.
  3. Signals during startup: yes, this is the same as SIGINT today. A first signal sets the flag and the run stops at the first check. If startup itself hangs, a second signal more than about 1 s later kills memtier. The README section already says that a second signal kills immediately.

@fcostaoliveira
fcostaoliveira merged commit 0370514 into master Oct 16, 2026
129 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 16, 2026
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]>
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.

SIGTERM leaves a truncated, invalid --json-out-file (only SIGINT is handled)

1 participant