From cdd3ee60c5d780ec6b4fb2cdb3f48b2454ac3197 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 14 Nov 2026 09:00:29 +0000 Subject: [PATCH] fix(tests): abort a swarm step for an I/O wedge only when a task is hung, not when the disk is busy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The swarm watchdog aborted with rc=75 whenever io60 stayed at or above 50 % with any task in D state. At the end of swarm deploys hlth-runtime scans all three nested nodes at once on one runner disk, which keeps D-state tasks around while the disk keeps moving data (PR #1720 odoo#0, PR #1947 Matrix#2, main run 43288523728). A wedge now needs at least one task in D for HUNG_TASK_S without a single context switch, the kernel hung-task test, so a stale NFS mount or a stuck disk still aborts while a busy disk does not. Proposal: the first CI run must show the hung figure during the scans. 🎯 Fix: 80 % 💥 Break: 5 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: ~100 % 🏆 Score: 76 🚦 Gate: ⛔ fix 80 % < 90 (operator pick: draft PR as proposal) Co-Authored-By: Claude Opus 5.5 --- tests/unit/python/utils/env/test_runtime.py | 49 ++++++--- .../tests/swarm/test_run_storage_roots.py | 2 +- .../python/utils/tests/swarm/test_watchdog.py | 101 +++++++++++++++++- utils/env/runtime.py | 44 ++++++-- utils/tests/swarm/watchdog.py | 54 ++++++++-- 5 files changed, 219 insertions(+), 31 deletions(-) diff --git a/tests/unit/python/utils/env/test_runtime.py b/tests/unit/python/utils/env/test_runtime.py index b1d94cf97c..7dbd0bed65 100644 --- a/tests/unit/python/utils/env/test_runtime.py +++ b/tests/unit/python/utils/env/test_runtime.py @@ -25,7 +25,7 @@ from utils.env.runtime import ( mem_available_mb, mem_stall_pct, run_helper, - uninterruptible_procs, + uninterruptible_switches, ) _PRESSURE = ( @@ -222,47 +222,70 @@ class TestPressureStalls(unittest.TestCase): self.assertEqual(io_stall_pct(), 0.0) -class TestUninterruptibleProcs(unittest.TestCase): +_STATUS = "Name:\tx\nvoluntary_ctxt_switches:\t{vol}\nnonvoluntary_ctxt_switches:\t2\n" + + +class TestUninterruptibleSwitches(unittest.TestCase): """A wedged mount leaves processes in D state; the count is the trace.""" - def _run(self, entries: list[str], stats: dict[str, str]) -> int: + def _run( + self, + entries: list[str], + stats: dict[str, str], + statuses: dict[str, str] | None = None, + ) -> dict[str, int]: + if statuses is None: + statuses = {pid: _STATUS.format(vol=pid) for pid in stats} files = {f"/proc/{pid}/stat": text for pid, text in stats.items()} + files |= {f"/proc/{pid}/status": text for pid, text in statuses.items()} with ( patch("utils.env.runtime.os.listdir", return_value=entries), patch("utils.env.runtime.Path", _fake_proc(files)), ): - return uninterruptible_procs() + return uninterruptible_switches() - def test_counts_only_the_d_state(self) -> None: + def test_keeps_only_the_d_state(self) -> None: stats = { "1": "1 (systemd) S 0 1 1 0 -1 4194560 1 2 3", "2": "2 (rsync) D 1 2 2 0 -1 1077936128 4 5 6", "3": "3 (mount.nfs) D 1 3 3 0 -1 1077936128 7 8 9", "4": "4 (python3) R 1 4 4 0 -1 4194304 1 1 1", } - self.assertEqual(self._run(["1", "2", "3", "4"], stats), 2) + self.assertEqual(sorted(self._run(["1", "2", "3", "4"], stats)), ["2", "3"]) + + def test_sums_voluntary_and_involuntary_switches(self) -> None: + stats = {"40": "40 (rsync) D 1 40 40 0 -1 0 0 0 0"} + self.assertEqual(self._run(["40"], stats), {"40": 42}) def test_a_comm_with_spaces_and_parens_does_not_shift_the_state(self) -> None: stats = {"7": "7 (weird )name( here) D 1 7 7 0 -1 0 0 0 0"} - self.assertEqual(self._run(["7"], stats), 1) + self.assertEqual(sorted(self._run(["7"], stats)), ["7"]) def test_non_numeric_proc_entries_are_skipped(self) -> None: stats = {"5": "5 (bash) D 1 5 5 0 -1 0 0 0 0"} self.assertEqual( - self._run(["self", "meminfo", "cpuinfo", "5"], stats), - 1, + sorted(self._run(["self", "meminfo", "cpuinfo", "5"], stats)), + ["5"], ) def test_a_process_vanishing_mid_scan_is_tolerated(self) -> None: stats = {"9": "9 (bash) D 1 9 9 0 -1 0 0 0 0"} - self.assertEqual(self._run(["8", "9"], stats), 1) + self.assertEqual(sorted(self._run(["8", "9"], stats)), ["9"]) - def test_unreadable_proc_returns_zero(self) -> None: + def test_a_d_task_whose_status_vanished_is_skipped(self) -> None: + stats = {"9": "9 (bash) D 1 9 9 0 -1 0 0 0 0"} + self.assertEqual(self._run(["9"], stats, statuses={}), {}) + + def test_a_status_without_the_counters_is_skipped(self) -> None: + stats = {"9": "9 (bash) D 1 9 9 0 -1 0 0 0 0"} + self.assertEqual(self._run(["9"], stats, statuses={"9": "Name:\tx\n"}), {}) + + def test_unreadable_proc_returns_empty(self) -> None: with patch("utils.env.runtime.os.listdir", side_effect=OSError): - self.assertEqual(uninterruptible_procs(), 0) + self.assertEqual(uninterruptible_switches(), {}) def test_empty_stat_is_tolerated(self) -> None: - self.assertEqual(self._run(["11"], {"11": ""}), 0) + self.assertEqual(self._run(["11"], {"11": ""}), {}) class TestIsWsl2(unittest.TestCase): diff --git a/tests/unit/python/utils/tests/swarm/test_run_storage_roots.py b/tests/unit/python/utils/tests/swarm/test_run_storage_roots.py index b5a19287df..5af97fedf7 100644 --- a/tests/unit/python/utils/tests/swarm/test_run_storage_roots.py +++ b/tests/unit/python/utils/tests/swarm/test_run_storage_roots.py @@ -86,7 +86,7 @@ def watch( mock.patch.object(watchdog, "mem_stall_pct", return_value=0.0), mock.patch.object(watchdog, "io_stall_pct", return_value=0.0), mock.patch.object(watchdog, "cpu_stall_pct", return_value=0.0), - mock.patch.object(watchdog, "uninterruptible_procs", return_value=0), + mock.patch.object(watchdog, "uninterruptible_switches", return_value={}), mock.patch("builtins.print", printed), ): rc = watchdog.run_watched(["step"], env={}) diff --git a/tests/unit/python/utils/tests/swarm/test_watchdog.py b/tests/unit/python/utils/tests/swarm/test_watchdog.py index b93b6741da..f133436227 100644 --- a/tests/unit/python/utils/tests/swarm/test_watchdog.py +++ b/tests/unit/python/utils/tests/swarm/test_watchdog.py @@ -11,13 +11,38 @@ the sampling cadence that decides how stale the last sample is. import contextlib import io +import itertools import signal import subprocess import unittest import unittest.mock as mock +from collections.abc import Callable from utils.tests.swarm import watchdog +_HUNG_SAMPLES = watchdog.HUNG_TASK_S // watchdog.SAMPLE_INTERVAL_S +_STUCK_DISK = {"101": 0, "102": 0, "103": 0} +_BUSY_DISK = {str(pid): 1 for pid in range(201, 209)} +_STALE_NFS = {"301": 0, "302": 0} | _BUSY_DISK + + +def _switches(periods: dict[str, int]) -> Callable[[], dict[str, int]]: + """ + Args: + periods: per D-state pid the samples between two of its context + switches; 0 for a task that never switches. + + Returns: + An uninterruptible_switches() stand-in advancing on every call. + """ + calls = itertools.count() + + def sample() -> dict[str, int]: + n = next(calls) + return {pid: n // period if period else 0 for pid, period in periods.items()} + + return sample + class _FakeProc: pid = 4242 @@ -51,6 +76,7 @@ class TestSampleLine(unittest.TestCase): "io_stall": 0.0, "cpu_stall": 0.0, "dstate": 0, + "hung": 0, } fields.update(overrides) return watchdog.sample_line(**fields) # type: ignore[arg-type] @@ -68,6 +94,9 @@ class TestSampleLine(unittest.TestCase): self.assertIn("cpu60 13.5%", line) self.assertIn("dstate 4", line) + def test_it_carries_the_hung_task_count(self) -> None: + self.assertIn("dstate 9, hung 2 ===", self._render(dstate=9, hung=2)) + def test_it_stays_one_greppable_banner(self) -> None: line = self._render() self.assertTrue(line.startswith("=== swarm-matrix: host mem ")) @@ -92,7 +121,7 @@ class TestRunWatched(unittest.TestCase): avail: int = 9324, total: int = 15947, free_mb: int = 38948, - dstate: int = 3, + blocked: dict[str, int] = _STUCK_DISK, ) -> tuple[int, str, _FakeProc]: proc = _FakeProc(timeouts=timeouts, rc=rc) buffer = io.StringIO() @@ -117,7 +146,9 @@ class TestRunWatched(unittest.TestCase): mock.patch.object(watchdog, "mem_stall_pct", return_value=0.0), mock.patch.object(watchdog, "io_stall_pct", return_value=io_stall), mock.patch.object(watchdog, "cpu_stall_pct", return_value=11.0), - mock.patch.object(watchdog, "uninterruptible_procs", return_value=dstate), + mock.patch.object( + watchdog, "uninterruptible_switches", side_effect=_switches(blocked) + ), contextlib.redirect_stdout(buffer), ): returned = watchdog.run_watched(["true"], env={}) @@ -153,7 +184,51 @@ class TestRunWatched(unittest.TestCase): def test_a_busy_disk_with_nothing_blocked_is_not_a_wedge(self) -> None: returned, output, proc = self._watch( - timeouts=_WEDGE_SAMPLES, rc=0, io_stall=99.0, dstate=0 + timeouts=_WEDGE_SAMPLES, rc=0, io_stall=99.0, blocked={} + ) + self.assertEqual(returned, 0) + self.assertFalse(proc.terminated) + self.assertNotIn("I/O WEDGE", output) + + def test_a_busy_local_disk_whose_d_tasks_keep_waking_is_not_a_wedge( + self, + ) -> None: + returned, output, proc = self._watch( + timeouts=_WEDGE_SAMPLES * 2, rc=0, io_stall=99.0, blocked=_BUSY_DISK + ) + self.assertEqual(returned, 0) + self.assertFalse(proc.terminated) + self.assertNotIn("I/O WEDGE", output) + self.assertIn("dstate 8, hung 0 ===", output) + + def test_a_stuck_local_disk_is_a_wedge(self) -> None: + returned, output, proc = self._watch( + timeouts=_WEDGE_SAMPLES, rc=0, io_stall=99.0, blocked=_STUCK_DISK + ) + self.assertEqual(returned, watchdog.ABORT_RC) + self.assertTrue(proc.terminated) + self.assertIn( + f"3 task(s) in D state, 3 hung for {watchdog.HUNG_TASK_S}s+", output + ) + + def test_a_stale_nfs_mount_beside_a_busy_local_disk_is_a_wedge(self) -> None: + returned, output, proc = self._watch( + timeouts=_WEDGE_SAMPLES, rc=0, io_stall=99.0, blocked=_STALE_NFS + ) + self.assertEqual(returned, watchdog.ABORT_RC) + self.assertTrue(proc.terminated) + self.assertIn( + f"10 task(s) in D state, 2 hung for {watchdog.HUNG_TASK_S}s+", output + ) + + def test_a_task_blocked_shorter_than_the_hung_threshold_is_not_a_wedge( + self, + ) -> None: + returned, output, proc = self._watch( + timeouts=_WEDGE_SAMPLES * 2, + rc=0, + io_stall=99.0, + blocked={"401": _HUNG_SAMPLES}, ) self.assertEqual(returned, 0) self.assertFalse(proc.terminated) @@ -218,5 +293,25 @@ class TestRunWatched(unittest.TestCase): self.assertEqual(touched, sorted([signal.SIGINT, signal.SIGTERM] * 2)) +class TestBlockedStreaks(unittest.TestCase): + def test_a_task_without_a_context_switch_extends_its_streak(self) -> None: + streaks = watchdog.blocked_streaks({"7": (40, 2)}, {"7": 40}) + self.assertEqual(streaks, {"7": (40, 3)}) + + def test_a_context_switch_resets_the_streak(self) -> None: + streaks = watchdog.blocked_streaks({"7": (40, 2)}, {"7": 41}) + self.assertEqual(streaks, {"7": (41, 0)}) + + def test_a_task_new_to_d_starts_at_zero_and_a_woken_one_is_dropped( + self, + ) -> None: + streaks = watchdog.blocked_streaks({"7": (40, 2)}, {"8": 0}) + self.assertEqual(streaks, {"8": (0, 0)}) + + def test_only_streaks_spanning_the_hung_threshold_count(self) -> None: + streaks = {"1": (0, _HUNG_SAMPLES), "2": (0, _HUNG_SAMPLES - 1)} + self.assertEqual(watchdog.hung_tasks(streaks), 1) + + if __name__ == "__main__": unittest.main() diff --git a/utils/env/runtime.py b/utils/env/runtime.py index c409cd7000..37819d5acf 100644 --- a/utils/env/runtime.py +++ b/utils/env/runtime.py @@ -131,8 +131,32 @@ def cpu_stall_pct() -> float: return _pressure_pct("cpu", "some") -def uninterruptible_procs() -> int: - """Count the processes in uninterruptible (`D`) state via /proc//stat. +def _context_switches(pid: str) -> int | None: + """ + Args: + pid: process whose /proc//status is read. + + Returns: + Its voluntary plus involuntary context switches so far, None when the + status is unreadable or carries neither counter. + """ + try: + text = Path( + f"/proc/{pid}/status" + ).read_text() # nocheck: cache-read -- live kernel pseudo-file + except OSError: + return None + counts = [ + int(value) + for key, _, value in (line.partition(":") for line in text.splitlines()) + if key in ("voluntary_ctxt_switches", "nonvoluntary_ctxt_switches") + and value.strip().isdigit() + ] + return sum(counts) if counts else None + + +def uninterruptible_switches() -> dict[str, int]: + """Map the processes in uninterruptible (`D`) state via /proc//stat. A process stuck in `D` cannot be killed and is the host-visible trace of a wedged mount. Only the state field is evaluated; the command name is @@ -141,13 +165,14 @@ def uninterruptible_procs() -> int: state is read after the last closing parenthesis rather than by index. Returns: - The number of `D`-state processes, 0 when /proc is unreadable. + The context switches so far of every `D`-state process, keyed by pid; + empty when /proc is unreadable. """ try: entries = os.listdir("/proc") except OSError: - return 0 - count = 0 + return {} + switches: dict[str, int] = {} for entry in entries: if not entry.isdigit(): continue @@ -158,9 +183,12 @@ def uninterruptible_procs() -> int: except OSError: continue fields = stat.rpartition(")")[2].split() - if fields and fields[0] == "D": - count += 1 - return count + if not fields or fields[0] != "D": + continue + count = _context_switches(entry) + if count is not None: + switches[entry] = count + return switches def is_wsl2() -> bool: diff --git a/utils/tests/swarm/watchdog.py b/utils/tests/swarm/watchdog.py index 5c0b5de6a1..c7ff227940 100644 --- a/utils/tests/swarm/watchdog.py +++ b/utils/tests/swarm/watchdog.py @@ -29,7 +29,7 @@ from utils.env.runtime import ( mem_available_mb, mem_stall_pct, mem_total_mb, - uninterruptible_procs, + uninterruptible_switches, ) if TYPE_CHECKING: @@ -41,6 +41,7 @@ MEM_FLOOR_RATIO = 0.06 IO_STALL_CEILING_PCT = 50.0 SAMPLE_INTERVAL_S = 10 STALL_WINDOW_S = 60 +HUNG_TASK_S = 30 WEDGE_SAMPLES = 2 ABORT_RC = 75 _FORWARDED_SIGNALS = (signal.SIGINT, signal.SIGTERM) @@ -88,6 +89,39 @@ def lowest_free_mb() -> tuple[int, str]: ) +def blocked_streaks( + previous: dict[str, tuple[int, int]], switches: dict[str, int] +) -> dict[str, tuple[int, int]]: + """ + Args: + previous: blocked_streaks() of the previous sample. + switches: uninterruptible_switches() of this sample. + + Returns: + Per `D`-state pid its context switches and the number of samples in a + row it has stayed in `D` without a single one. + """ + streaks: dict[str, tuple[int, int]] = {} + for pid, count in switches.items(): + seen, streak = previous.get(pid, (-1, -1)) + streaks[pid] = (count, streak + 1 if seen == count else 0) + return streaks + + +def hung_tasks(streaks: dict[str, tuple[int, int]]) -> int: + """ + Args: + streaks: blocked_streaks() of this sample. + + Returns: + The number of tasks blocked in `D` without a context switch for at + least HUNG_TASK_S. + """ + return sum( + 1 for _, streak in streaks.values() if streak * SAMPLE_INTERVAL_S >= HUNG_TASK_S + ) + + def sample_line( *, avail: int, @@ -98,6 +132,7 @@ def sample_line( io_stall: float, cpu_stall: float, dstate: int, + hung: int, ) -> str: """Render one host-health sample for the step log. @@ -110,6 +145,8 @@ def sample_line( io_stall: `full avg60` I/O pressure in percent. cpu_stall: `some avg60` CPU pressure in percent. dstate: number of processes in uninterruptible state. + hung: how many of them sat in D without a context switch for at + least HUNG_TASK_S. Returns: The banner line, carrying the three resources a lost runner can be @@ -119,7 +156,8 @@ def sample_line( return ( f"=== swarm-matrix: host mem {avail}M/{total}M available, " f"disk {free_mb}M free on {root}, stall60 {mem_stall:.1f}%, " - f"io60 {io_stall:.1f}%, cpu60 {cpu_stall:.1f}%, dstate {dstate} ===" + f"io60 {io_stall:.1f}%, cpu60 {cpu_stall:.1f}%, dstate {dstate}, " + f"hung {hung} ===" ) @@ -153,6 +191,7 @@ def run_watched(cmd: list[str], *, env: dict[str, str]) -> int: def _watch(proc: subprocess.Popen[bytes]) -> int: samples = 0 wedged = 0 + streaks: dict[str, tuple[int, int]] = {} while True: try: return int(proc.wait(timeout=SAMPLE_INTERVAL_S)) @@ -169,7 +208,9 @@ def _watch(proc: subprocess.Popen[bytes]) -> int: avail = mem_available_mb() total = mem_total_mb() io_stall = io_stall_pct() - dstate = uninterruptible_procs() + streaks = blocked_streaks(streaks, uninterruptible_switches()) + dstate = len(streaks) + hung = hung_tasks(streaks) print( sample_line( avail=avail, @@ -180,6 +221,7 @@ def _watch(proc: subprocess.Popen[bytes]) -> int: io_stall=io_stall, cpu_stall=cpu_stall_pct(), dstate=dstate, + hung=hung, ), flush=True, ) @@ -192,14 +234,14 @@ def _watch(proc: subprocess.Popen[bytes]) -> int: ["free", "-m"], ) owns_window = samples * SAMPLE_INTERVAL_S >= STALL_WINDOW_S - breached = io_stall >= IO_STALL_CEILING_PCT and dstate > 0 + breached = io_stall >= IO_STALL_CEILING_PCT and hung > 0 wedged = wedged + 1 if owns_window and breached else 0 if wedged >= WEDGE_SAMPLES: return _abort( proc, "=== swarm-matrix: I/O WEDGE " f"({io_stall:.1f}% full stall60 with {dstate} task(s) in D " - f"state, {wedged} samples at or above " - f"{IO_STALL_CEILING_PCT:.0f}%) - aborting step ===", + f"state, {hung} hung for {HUNG_TASK_S}s+, {wedged} samples " + f"at or above {IO_STALL_CEILING_PCT:.0f}%) - aborting step ===", ["cat", "/proc/pressure/io"], )