From 39a86c04de5e38382adbe65e9556855c1442e28d Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Thu, 22 Oct 2026 20:20:49 +0000 Subject: [PATCH] fix(test): the fake child sets its signal traps before it writes its pids Cause: `hung_script` wrote the pid file and only then ran `after_start`. For `records_stop_signals`, `after_start` set the traps that record `int` and `term`. A test signals the child as soon as it reads the pids. The child lost a signal that came between the pid write and the traps. The test then failed with `interrupted` false. The production code has no defect. Change: `hung_script` has a new part, `after_spawn`. It runs after the grandchild starts and before the child writes the pids. `records_stop_signals` sets its traps there. The traps cannot go before the start of the grandchild, because the grandchild would then not ignore SIGTERM. The other users of `hung_script` set their traps in `before` or `on_interrupt`, or send no signal. They have no gap. Existing tool considered: the fix needs no tool. The new test reads the mask of caught signals from `/proc//status`, as the module already reads `/proc//stat`. `psutil` is not a dependency, and it has no call for that mask. I estimate that the two test helpers cost about 30,000 tokens and 45 minutes. Tests: `tests/test_support_hung_children.py` makes the pid file a named pipe, so the child waits at the write of its pids. The test checks that the child already catches SIGINT and SIGTERM. It failed on the old order and passes on the new order. It opens the pipe without a block, so a child that exits early fails the test with a message. With the gap widened by `sleep 0.5`, the four stop-signal tests failed 4 of 4 before the fix and pass 4 of 4 after it. When the stop code does not send the SIGKILL, all four stop-signal tests fail with `(True, True, False, False)`. Fail-to-pass: not applicable: the production code is correct and untouched, and the tests that use the fake pass on the base on a quiet host. Fixes #1913 --- changelog.d/1913.md | 3 + ...sts-wait-until-the-fake-records-signals.md | 53 +++++++++++++++ tests/support/hung_children.py | 25 +++++--- tests/test_support_hung_children.py | 64 +++++++++++++++++++ 4 files changed, 136 insertions(+), 9 deletions(-) create mode 100644 changelog.d/1913.md create mode 100644 docs/agent/tasks/task-1913-stop-signal-tests-wait-until-the-fake-records-signals.md create mode 100644 tests/test_support_hung_children.py diff --git a/changelog.d/1913.md b/changelog.d/1913.md new file mode 100644 index 0000000000..f0d603d37f --- /dev/null +++ b/changelog.d/1913.md @@ -0,0 +1,3 @@ +### Fixed + +- The tests that a second Ctrl-C, SIGTERM or SIGHUP cannot skip the SIGKILL of `devops ci test` no longer fail on a busy machine. The fake program now records SIGINT and SIGTERM before it writes its pids. Before, the program lost a signal that came right after it wrote its pids, and the test failed with `interrupted` false ([#1913](https://github.com/dan-petty/devops-cli/issues/1913)). diff --git a/docs/agent/tasks/task-1913-stop-signal-tests-wait-until-the-fake-records-signals.md b/docs/agent/tasks/task-1913-stop-signal-tests-wait-until-the-fake-records-signals.md new file mode 100644 index 0000000000..1c7b1568ca --- /dev/null +++ b/docs/agent/tasks/task-1913-stop-signal-tests-wait-until-the-fake-records-signals.md @@ -0,0 +1,53 @@ +# Task: The Stop-Signal Fake Records Signals Before Its Pids Are Visible (#1913) + +**Issue**: [#1913](https://github.com/dan-petty/devops-cli/issues/1913) +**Scope**: scope/ci +**Feasibility**: I read `hung_script` in `tests/support/hung_children.py` and `_terminate_process_group_async` in `src/devops_cli/core/process.py` at `release/v0.2.39`. I ran `dash` to check how the fake child behaves. I reproduced the failure with a widened gap in the fake child. I measured the natural failure rate under a stress pinned to one core. The production code has no defect, so the change touches no file in `src/`. The section "Evidence" gives the details. + +## Description + +`hung_script` in `tests/support/hung_children.py` used to write the pid file (`echo "$$ $c" > "$0"`) and only then run `after_start`. For `records_stop_signals`, `after_start` set the traps that record `int` and `term`. Until then, the child ran under `trap "" INT TERM`, which ignores both signals. The tests send their first signal as soon as `watch.started` is true. The child lost a signal that came between the write of the pids and the traps. The test then failed with `(True, False, True, False)`, because `interrupted` was false. + +- **The new part.** `hung_script` now has a part `after_spawn`. It runs after the grandchild starts and before the child writes the pids. `records_stop_signals` sets its traps there. `after_start` keeps its place after the pids. It holds nothing that a test needs from the child when it reads the pids. The docstrings say so. +- **The order of the traps.** The traps cannot go before the start of the grandchild. A grandchild that starts after the child sets a trap does not ignore SIGTERM. The test would then not check the SIGKILL. +- **The other users.** Besides the new test, only `tests/test_ci.py` and `tests/test_process.py` import `tests/support/hung_children.py`. Four tests use `records_stop_signals`. They are the three parameters of `test_a_second_signal_to_devops_ci_test_cannot_skip_the_sigkill` and `test_a_further_cancellation_during_the_stop_cannot_skip_its_sigkill`. The change fixes all four. +- **The users with no gap.** `interrupted_like_pytest` and the timeout test set their traps with `before` or `on_interrupt`. Both run before the child writes the pids. The one other `after_start` waits for a file and sends no signal. +- **The new test.** `tests/test_support_hung_children.py` makes the pid file a named pipe. The child waits at the write of its pids until the test opens the pipe. The test first waits until the child catches SIGINT and SIGTERM. It reads the mask of caught signals from the `SigCgt` line of `/proc//status`. The child can be in this state only if it set the traps before it writes its pids. The test needs no sleep and has no race. +- **The bound on the pipe.** The test opens the pipe without a block and waits for the pids with `select`. A child that fails for another reason then fails the test with a clear message. A blocking read waited for a writer that never came, and the test ran until the timeout of the run. + +## Evidence + +- **Production code is ready.** The driver of `devops ci test` installs its SIGTERM and SIGHUP handlers before it starts the child (`_cancelled_by_stop_signals` in `src/devops_cli/commands/ci.py`). So the production code is ready when the test reads the pids. +- **Two facts of `dash`.** A grandchild that starts after `trap` sets a handler does not ignore SIGTERM. So the traps of the fake must follow the start of the grandchild. A trapped signal that interrupts a redirect makes `dash` stop it with "cannot create ...: Interrupted system call". So a test cannot send a signal while the child waits at the write of its pids. The new test reads `/proc//status` and sends no signal. +- **The stress.** Every stress runs six busy Python loops (`nice -n 5`) and one pytest process, all under `taskset -c 3`. Each stress lasted at most 60 s. The busy loops end by themselves after 55 s. A scratch plugin (about 50 lines, in `.data/agent/scratch/`, not committed) repeats one test in one process. It skips the repeats that start after a deadline. +- **The natural rate before the fix.** The rate was too low to measure. `test_a_second_signal_to_devops_ci_test_cannot_skip_the_sigkill` passed 62 of 62 repeats, with the pytest process at nice 0, 5 and 10. `test_a_further_cancellation_during_the_stop_cannot_skip_its_sigkill` passed 400 of 400 repeats. The gap is the time between two commands of `sh`. The stress did not stop `sh` inside it. +- **A widened gap.** A scratch plugin put `sleep 0.5` first in `after_start`. This models a scheduler that holds `sh` back right after it writes its pids. Before the fix, the four tests failed in 4 of 4 repeats with `(True, False, True, False)`, the failure of the issue. After the fix, the same plugin leaves the four tests passing in 4 of 4 repeats. +- **The new test.** Before the fix, the new test failed after 30 s with `(False, True)`. The child did not catch the signals while it waited to write its pids. After the fix, it passes in under 1 s, and it passed 60 of 60 repeats under the stress. A scratch plugin made the child exit at once. The test then failed with `(False, False)` after 90 s, and it did not block. +- **After the fix.** `test_a_second_signal_to_devops_ci_test_cannot_skip_the_sigkill[SIGTERM]` passed 40 of 40 repeats under the stress. `test_a_further_cancellation_during_the_stop_cannot_skip_its_sigkill` passed 100 of 100. +- **The SIGKILL stays tested.** I changed `_terminate_process_group_async` so that it does not send the SIGKILL, and I ran the four tests. All four failed with `(True, True, False, False)`. The child and its grandchild ignore SIGINT and SIGTERM, so the stop code did not end them. I restored the file with `git checkout -- src/devops_cli/core/process.py`. + +## Existing tools considered + +- **The fix.** It needs no tool. It moves two `trap` commands in a shell script. +- **The mask of caught signals.** The new test reads it from `/proc//status`, as `tests/support/hung_children.py` already reads `/proc//stat`. `psutil` is not a dependency of the project. Its `Process` class (version 7.2.2) has no call for the mask of caught signals. The helper `_catches` has 4 lines. I estimate that it cost about 20,000 tokens and 30 minutes to write and check. It needs no upkeep, because the kernel interface is stable. +- **The read of the pipe.** The helper `_pids_the_child_writes_to` uses `os` and `select` from the standard library. I estimate that it cost about 10,000 tokens and 15 minutes. +- **The repeats.** `devops ci test --repeat` repeats whole test files, and `pytest-repeat` is not a dependency. So the scratch plugin repeats the one test. + +## Acceptance Criteria + +- [x] The fake child catches SIGINT and SIGTERM before it writes its pids. So it always records a signal that a test sends after it reads the pids. +- [x] The new test fails on the old order of `records_stop_signals` and passes on the new order. +- [x] The new test fails with a message, and does not block, when the child exits before it opens the pipe. +- [x] The four tests that use `records_stop_signals` fail when the stop code does not send the SIGKILL. +- [x] With the gap widened, the four tests failed 4 of 4 before the fix and passed 4 of 4 after it. +- [x] The stop-signal test of `tests/test_ci.py` passed 40 of 40 repeats under a stress pinned to one core. +- [x] No sleep and no longer deadline is part of the fix. +- [x] `uv run devops ci test tests/test_support_hung_children.py tests/test_process.py tests/test_ci.py` passes. +- Fail-to-pass: not applicable. The production code is correct and untouched, and the base passes on a quiet host. + +## Deliverables + +- [x] `tests/support/hung_children.py`: the part `after_spawn` of `hung_script`, `records_stop_signals` on it, and the docstrings. +- [x] `tests/test_support_hung_children.py`: the test that the fake catches the signals before its pids are visible. +- [x] `docs/agent/tasks/task-1913-stop-signal-tests-wait-until-the-fake-records-signals.md`. +- [x] `changelog.d/1913.md`. diff --git a/tests/support/hung_children.py b/tests/support/hung_children.py index e0f6c942a3..f82c759e6d 100644 --- a/tests/support/hung_children.py +++ b/tests/support/hung_children.py @@ -11,8 +11,9 @@ exited, zombies counted as exited, and on the way out SIGKILLs through the pidfd whichever is still running: a pidfd names one process, never another that later reuses its pid. The watch fails the test when the child leads no session of its own or the grandchild is outside it, -rather than read either as stopped. `default_signal_dispositions` gives a test the signal -dispositions these children rely on. +rather than read either as stopped. A test signals the child as soon as it reads the pids, so the +child is ready for the signal before it writes them (#1913). `default_signal_dispositions` gives +a test the signal dispositions these children rely on. """ from __future__ import annotations @@ -39,13 +40,17 @@ """The record a test writes into the stop-signal log as it sends its second signal.""" -def hung_script(*, before: str = "", on_interrupt: str = "", after_start: str = "") -> str: - """A `sh -c` script, its pid file as `$0`: run `before`, start the sleeping grandchild, write - both pids, run `after_start` and wait. `on_interrupt` is run on SIGINT; in it and in - `after_start`, `$c` is the grandchild's pid.""" +def hung_script( + *, before: str = "", on_interrupt: str = "", after_spawn: str = "", after_start: str = "" +) -> str: + """A `sh -c` script, its pid file as `$0`: run `before`, start the sleeping grandchild, run + `after_spawn`, write both pids, run `after_start` and wait. A test acts on the child as soon + as it reads the pids. Put what that action needs, such as the traps that record a signal, in + `before` or `after_spawn`, never in `after_start`. `on_interrupt` is run on SIGINT; in it and + in `after_spawn` and `after_start`, `$c` is the grandchild's pid.""" trap = f"trap '{on_interrupt}' INT; " if on_interrupt else "" return ( - f'{before}{trap}sleep {GRANDCHILD_HOLD_SECONDS} & c=$!; echo "$$ $c" > "$0"; ' + f'{before}{trap}sleep {GRANDCHILD_HOLD_SECONDS} & c=$!; {after_spawn}echo "$$ $c" > "$0"; ' f'{after_start}while kill -0 "$c" 2>/dev/null; do wait "$c"; done' ) @@ -63,10 +68,12 @@ def interrupted_like_pytest(marker: Path) -> str: def records_stop_signals(log: Path) -> str: """A script whose child and grandchild ignore SIGINT and SIGTERM, so only SIGKILL stops them; - the child records each SIGINT it gets as `int` and each SIGTERM as `term` in `log`.""" + the child records each SIGINT it gets as `int` and each SIGTERM as `term` in `log`, from + before its pids are written. It sets the traps after it starts the grandchild, because a + grandchild that starts after the child sets a trap does not ignore SIGTERM.""" return hung_script( before='trap "" INT TERM; ', - after_start=f"trap 'echo int >> \"{log}\"' INT; trap 'echo term >> \"{log}\"' TERM; ", + after_spawn=f"trap 'echo int >> \"{log}\"' INT; trap 'echo term >> \"{log}\"' TERM; ", ) diff --git a/tests/test_support_hung_children.py b/tests/test_support_hung_children.py new file mode 100644 index 0000000000..84985f4a56 --- /dev/null +++ b/tests/test_support_hung_children.py @@ -0,0 +1,64 @@ +"""The hung child that records stop signals is ready for a signal as soon as its pids are visible +(#1913).""" + +from __future__ import annotations + +import os +import select +import signal +import subprocess +from pathlib import Path + +import pytest + +from tests.support.hung_children import hung_with_grandchild, records_stop_signals, watching +from tests.support.waits import THREAD_HANDOFF_BOUND_SECONDS, wait_until + +pytestmark = pytest.mark.live("sh") + +RECORDED_SIGNALS = (signal.SIGINT, signal.SIGTERM) +"""The signals `records_stop_signals` records.""" + + +def _catches(pid: int, wanted: tuple[signal.Signals, ...]) -> bool: + """Whether process `pid` has a handler for each signal in `wanted`. `/proc//status` lists + the signals a process catches as a mask with one bit for each signal number, from 1.""" + status = Path(f"/proc/{pid}/status").read_text(encoding="utf-8").splitlines() + mask = int(next(line for line in status if line.startswith("SigCgt:")).split()[1], 16) + return all(mask >> (sig - 1) & 1 for sig in wanted) + + +def _pids_the_child_writes_to(pipe: Path) -> str: + """The pids the child writes into the named pipe `pipe`, or "" when it writes none within the + bound. The test opens the pipe without a block, so a child that fails for another reason fails + the test with a message. A blocking open would wait for a writer that never comes. The open + also lets the child go on.""" + reader = os.open(pipe, os.O_RDONLY | os.O_NONBLOCK) + try: + ready, _, _ = select.select([reader], [], [], THREAD_HANDOFF_BOUND_SECONDS) + return os.read(reader, select.PIPE_BUF).decode() if ready else "" + finally: + os.close(reader) + + +@pytest.mark.usefixtures("default_signal_dispositions") +def test_the_child_that_records_stop_signals_catches_them_before_its_pids_are_visible( + tmp_path: Path, +) -> None: + """A test signals the child as soon as it reads the pids. A signal that comes before the child + records signals is lost. The pid file here is a named pipe, so the child waits at the write of + its pids until the test reads them. A child that catches SIGINT and SIGTERM before that point + has them in place whenever a test can first read its pids.""" + published = tmp_path / "published" + os.mkfifo(published) + argv = hung_with_grandchild(published, records_stop_signals(tmp_path / "signals")) + with ( + subprocess.Popen(argv, start_new_session=True) as child, + watching(tmp_path / "pids") as watch, + ): + caught = wait_until(lambda: _catches(child.pid, RECORDED_SIGNALS)) + # The watch reads the pids from its pid file and ends the child and its grandchild. + watch.pid_file.write_text(_pids_the_child_writes_to(published), encoding="utf-8") + started = wait_until(watch.started) + + assert (caught, started) == (True, True)