Skip to content

The hang watchdog dumps one thread, and every reader of that dump knows it (#793) - #818

Merged
lmoresi merged 4 commits into
developmentfrom
bugfix/watchdog-unsafe
Oct 6, 2026
Merged

lmoresi merged 4 commits into
developmentfrom
bugfix/watchdog-unsafe

Conversation

@lmoresi

@lmoresi lmoresi commented Oct 5, 2026

Copy link
Copy Markdown
Member

test_0053_hang_watchdog segfaulted inside CPython's faulthandler during
full tier_a runs, state-dependently (#793). Two causes, both measured, and
then three readers that had to follow.

What crashed

The dump walked every thread state (all_threads=True) while the watchdog
created and destroyed a threading.Timer on every checkpoint() call. A
thread state torn down between the dump starting and that state being read
gives EXC_BAD_ACCESS inside _Py_DumpTracebackThreads. The native stack
pointed at dump_traceback + 496 with a cursor part-way through a thread
list.

Probed in isolation:

condition segfaults
thread churn, all_threads=True 4 / 6
no churn 0 / 6
all_threads=True 2 / 8
all_threads=False 0 / 8

The timer churn is gone: one uw-watchdog thread waits on an event with a
deadline that arm() moves, so a checkpoint updates a timestamp instead of
replacing a thread. cancel() sets the event and joins.

Two alternatives were measured and rejected. A pure-Python watcher loop files
1 report in 5 on a rank blocked in a collective, because it needs the lock
that rank is holding. dump_traceback_later() files 5 in 5, but
cancel_dump_traceback_later() then hangs 3 times in 3.

Why the first commit was not the fix

all_threads=False changes the line faulthandler writes. A dump that walks
every thread labels the signalled stack Current thread 0x...; a dump that
walks the signalled thread alone writes Stack (most recent call first): and
nothing else. Three readers were keyed to the first form.

underworld3.utilities.hang_report — the analyser that reads a directory of
per-rank dumps and names the divergent rank — split dumps on ^Current thread 0x... only. After the writer change it found no dumps at all in the
watchdog's own files, and would have reported a hang with no evidence. It now
accepts either form, which it has to: the watchdog writes the second, and
scripts/mpi_supervisor.py registers all_threads=True and writes the first.

test_0054's _dump_count counted the same string, so both of its end-to-end
tests sat out their full 600 s cap waiting for dumps that were arriving all
along. That is 16 of the 28 minutes a level_1 and tier_a run took.

Tests

tests/parallel/test_0778_hang_watchdog_mpi.py is the parallel half that
test_0053's module docstring has always named and that did not exist. A
bounded planted block — rank 0 is late to an allreduce by a fixed interval,
then joins, so the collective always completes — puts every other rank inside
MPI with no Python of its own able to run. The blocked ranks file repeat dumps
naming the frame they are stuck in, at np=2 and np=4.

test_0063_mpi_hang_supervisor is not a substitute for it. That covers
scripts/mpi_supervisor.py, a separate SIGUSR1 mechanism with its own
registration, and nothing in this change touches it.

Both new tests fail with all_threads=True restored in the installed tree.

The repeat is asserted on the faulthandler dumps rather than on the labelled
report, because the labelled report has no guarantee on a blocked rank: it is
formatted in Python from sys._current_frames(), needs the interpreter lock,
and _Watchdog.report says so. The pre-#793 threading.Timer filed none
there, the persistent reporter thread files one, and neither number is a
contract. faulthandler filed every dump in both cases.

A docstring that was wrong

watch()'s Warnings section said other threads are deliberately not dumped.
The labelled report has always dumped every one of them. There are two report
paths, they carry different things, and the docstring now says which is which:
the Python path holds the interpreter lock and so cannot read a half-built
thread state, which is why it was never the unsafe one.

Verification

result
test_0053 + test_0054, repeat runs 0 failures in 30 (pre-rebase), 0 in 15 (post-rebase)
test_0053 + test_0054 + test_0063 26 passed in 2:01, against the 600 s stall
test_0778 passes on every rank at np=2 and np=4
level_1 and tier_a before 2 failed, 1393 passed, 28:37
level_1 and tier_a after 1396 passed, 0 failed, 12:34, no segfault markers

Closes #793.

Underworld development team with AI support from Claude Code

…one thread

test_0053 segfaulted inside CPython's faulthandler during full tier_a runs
(#793). Two measured causes, both addressed here.

The dump walked every thread state (`all_threads=True`) while the watchdog
created and destroyed a `threading.Timer` on every `checkpoint()` call. A
thread state torn down between the dump starting and that state being read
gives `EXC_BAD_ACCESS` inside `_Py_DumpTracebackThreads`. Probed in
isolation: thread churn 4/6 crash against 0/6 without it, and
`all_threads=True` 2/8 against `all_threads=False` 0/8.

The timer churn is now gone: one `uw-watchdog` thread waits on an event
with a deadline that `arm()` moves, so a checkpoint updates a timestamp
instead of replacing a thread. `cancel()` sets the event and joins. The
registration asks for this thread only, which is the thread that is stuck
in the collective and the only one the report was ever read for.

Two alternatives were measured and rejected. A pure-Python watcher loop
files only 1 of 5 reports on a rank blocked in a collective, because it
needs the GIL the blocked thread is holding. `dump_traceback_later()` files
5 of 5 but `cancel_dump_traceback_later()` then hangs 3 of 3.

Verified at 0/30 serial failures of test_0053.

Underworld development team with AI support from Claude Code
…writer

Registering faulthandler with all_threads=False changes the line it writes,
and three readers were keyed to the old one. The fix for #793 was incomplete
without them.

A dump that walks every thread labels the signalled stack "Current thread
0x...". A dump that walks the signalled thread alone writes "Stack (most
recent call first):" and nothing else.

underworld3.utilities.hang_report split dumps on the first form only, so it
found no dumps at all in the watchdog's own files and reported a hang with no
evidence. It now accepts either, which it has to: the watchdog writes the
second, and scripts/mpi_supervisor.py registers all_threads=True and writes
the first.

test_0054's _dump_count counted the first form, so both of its end-to-end
tests sat out their full 600 s cap waiting for dumps that were arriving all
along -- 20 of the 28 minutes of a level_1 tier_a run. It now counts either.

Two tests are added, both of which fail with all_threads=True restored:

tests/parallel/test_0778_hang_watchdog_mpi.py is the parallel half that
test_0053's docstring has always named and that did not exist. A bounded
planted block -- rank 0 is late to an allreduce by a fixed interval, then
joins -- puts every other rank inside MPI with no Python of its own able to
run. The blocked ranks file repeat dumps naming the frame they are stuck in,
at np=2 and np=4. tests/test_0063_mpi_hang_supervisor.py is not a substitute:
it covers scripts/mpi_supervisor.py, a separate SIGUSR1 mechanism with its
own registration.

The repeat is asserted on the faulthandler dumps rather than on the labelled
report. The labelled report is formatted in Python from
sys._current_frames(), needs the interpreter lock, and has no guarantee on a
blocked rank: the pre-#793 threading.Timer filed none there, the persistent
reporter thread files one, and neither is a contract. faulthandler filed every
dump in both cases.

Claiming otherwise is also what the watch() docstring did. It said other
threads were deliberately not dumped, and the labelled report has always
dumped every one of them. Corrected, along with the registration comment: the
Python path holds the lock and cannot read a half-built thread state, so it
was never the unsafe one.

Verified: level_1 tier_a 1393 passed with no segfault; test_0053, test_0054
and test_0063 26 passed in 2 minutes against the 600 s stall; test_0778 passes
on every rank at np=2 and np=4.

Underworld development team with AI support from Claude Code
Copilot AI balanced review requested due to automatic review settings October 5, 2026 08:25

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Reporter cancellation can time out and permit stream use after unwatch(), including reviving an old reporter during nested watching.

Review effort: Balanced
Findings: 1 Medium severity · 3 Low severity

Open (4)
What changed in this PR

This PR hardens hang diagnostics by avoiding unsafe all-thread traceback walks and eliminating per-checkpoint thread churn.

Changes:

  • Adds a persistent watchdog reporter thread and single-thread faulthandler dumps.
  • Updates hang-report parsing for both traceback formats.
  • Adds serial and MPI regression coverage.
File Description
src/​underworld3/​mpi.py Revises watchdog reporting and lifecycle.
src/​underworld3/​utilities/​hang_report.py Parses both dump headers.
tests/​test_0053_hang_watchdog.py Adds serial regression coverage.
tests/​test_0054_hang_report.py Updates dump counting.
tests/​parallel/​test_0778_hang_watchdog_mpi.py Adds blocked-rank MPI tests.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/underworld3/mpi.py
Comment on lines +574 to +575
if reporter is not None and reporter is not _threading.current_thread():
reporter.join(timeout=5.0)
Comment thread src/underworld3/mpi.py
Comment on lines +639 to +640
first. It needs the interpreter lock, so it is the one that goes missing
on a rank blocked inside MPI.
Comment on lines +44 to +49
pytestmark = [
pytest.mark.mpi(min_size=2),
pytest.mark.timeout(120, method="thread"),
pytest.mark.level_1,
pytest.mark.tier_a,
]
)


def test_the_faulthandler_dump_walks_one_thread(report):
A report in flight on the reporter thread can reach _rearm_timer after
cancel() has cleared self._reporter and stopped waiting for the thread. It
would then clear the stop event and start a replacement: a reporter nobody
holds, writing into a stream the caller is about to close -- which is the
descriptor hazard unwatch() exists to avoid.

The `cancelled` test in report() does not close it, because that value is read
before cancel() sets it and acted on afterwards. The pair
(self._reporter, self.cancelled) is now read and written under one lock, and
_rearm_timer refuses outright once cancelled. cancel() holds the lock only for
the swap and joins outside it.

arm(resume=True) clears the latch before re-arming, so restoring an outer
watchdog after a nested `watching` block still starts its thread.

Underworld development team with AI support from Claude Code
@lmoresi

lmoresi commented Oct 5, 2026

Copy link
Copy Markdown
Member Author

Adversarial review

Ours, before asking for anyone else's. Findings and evidence; one is fixed in
d1fca6ec, the rest stand as stated limits.

Fixed: a leaked reporter thread on the cancel/re-arm race

A report() in flight on the reporter thread can reach _rearm_timer after
cancel() has cleared self._reporter and stopped waiting for the thread. It
would then clear the stop event and start a replacement — a reporter nobody
holds, writing into a stream the caller is about to close, which is the
descriptor hazard unwatch() exists to avoid. The cancelled test in
report() does not close it: that value is read before cancel() sets it and
acted on afterwards.

The window is narrow and the old threading.Timer code had the same latch, but
the persistent thread makes the consequence worse, because _stop_reporter.clear()
resurrects a loop that was deliberately stopped. (self._reporter, self.cancelled)
is now read and written under one lock and _rearm_timer refuses once cancelled.

Capability lost, and not mitigated

all_threads=False means the C dump carries the signalled thread only. On a
rank blocked inside MPI the labelled Python report is all but silent, so that
single stack is the whole of the evidence. A rank stuck because a helper
thread is holding something the main thread wants is therefore no longer
diagnosable from the watchdog alone — scripts/mpi_supervisor.py is the tool
for that, and it still registers all_threads=True. We traded it for not
segfaulting and we think that is the right trade, but it is a trade.

Unexplained behaviour we are asserting around, not on

A blocked rank files exactly one labelled report in a 3 s block at a 0.5 s
limit, at np=2 and np=4. We do not know why one rather than none or six. The
plausible reading is that comm.allreduce on a Python object yields the
interpreter lock during pickling and the reporter catches it once, in which
case a buffer-mode comm.Allreduce would file none. test_0778 asserts the
repeat on the faulthandler dumps for exactly this reason, so no test depends on
the number — but the mechanism is unexplained and the number could move.

Unverified claim in the new test

test_0778 carries pytest.mark.timeout(120, method="thread") because the
default method takes ITIMER_REAL, which the watchdog takes over — we saw the
RuntimeWarning saying so. We did not verify that the thread-method timeout
actually fires, only that it does not break collection. If it is also inert,
this file has no hang guard of its own and relies on the block being bounded
by construction.

Races we are living with

self._deadline is read and written without a lock by the reporter thread and
by arm(). A read-modify-write in _reporter_loop can lose a checkpoint's
extension and file a spurious report. The failure mode is a report that says
"stuck" about a job that was moving, not a crash or a missed hang, and taking a
lock on the checkpoint() path is the wrong price for it.

The reporter is a daemon thread, so interpreter shutdown kills it where it
stands. Mid-print, that truncates a report. Pre-existing, and the same for
the Timer it replaces.

Retractions

Four things we said during this investigation that were wrong:

  • test_0063_mpi_hang_supervisor covers the parallel case. It does not — it
    covers scripts/mpi_supervisor.py, a separate SIGUSR1 mechanism with its own
    all_threads=True, untouched by any of this. The file test_0053's docstring
    named had simply never been written.
  • test_0778 is the risk to this fix, because it asserts on multi-rank dump
    content. There was no such file to be a risk.
  • The crash is a frame chain read mid-update on the interrupted thread. The
    native stack showed the main thread parked in nanosleep with static frames;
    it is the thread state list that is read, not the frames.
  • Other threads are deliberately not dumped — which we wrote into the watch()
    docstring. The labelled report has always dumped every thread, and always
    safely, because sys._current_frames() holds the interpreter lock. Corrected
    in f6a42bd7.

What the first commit missed

Worth stating plainly, because it is the shape of the mistake rather than a
detail: we changed what the writer emits and shipped it with 0 failures in 30
runs of the test that had been crashing, and that measurement was real and
irrelevant. Three readers were keyed to the old marker, including the library's
own analyser, and only a full tier_a run found them. A writer change needs its
readers enumerated, not its own test re-run.

Underworld development team with AI support from Claude Code

tests/test_0054_hang_report.py spawns processes designed never to exit, both
busy-polling, both with start_new_session=True so that nothing but the killpg
in each `finally` reaps them. A killed pytest never runs its finally, and
interrupting pytest is exactly what one does during a hang investigation --
which is when this file is being worked on.

Four ranks and their prterun, orphaned to init for 15 hours at ~100% CPU each,
were running on this machine while the fix was written. The 15-minute load
average went from 25.2 to 12.9 when they were killed.

Each script now watches the TEST RUNNER's pid, injected at spawn the way DUMPS
and READY already are, and exits when it goes. Watching os.getppid() instead
looks equivalent and is not: under mpirun a rank's parent is prterun, so a
SIGKILLed pytest leaves the rank's parent alive and the rank never notices.
Measured -- with the getppid() version all four ranks and prterun survived the
full 70 s of the probe at 100% CPU; with the runner-pid version every one of
the five is gone 5 s after the kill. A 900 s cap sits behind it as a backstop
against a recycled pid, not as a measurement.

Teardown now sends SIGTERM to the group before SIGKILL. SIGKILL alone removes
mpirun from under its own ranks, which is how they end up re-parented to init;
SIGTERM on prterun alone took all four ranks down with it when the orphans
above were cleared.

26 passed across test_0053, test_0054 and test_0063, with no leftover
processes after a clean run.

Closes #639.

Underworld development team with AI support from Claude Code
@lmoresi

lmoresi commented Oct 5, 2026

Copy link
Copy Markdown
Member Author

Issues in this branch's territory

Under the rule in docs/review-adjudicates-issues: every open issue in the
territory a branch touches gets a verdict, and refusing to close is one of
them. Territory here is src/underworld3/mpi.py,
src/underworld3/utilities/hang_report.py, scripts/mpi_supervisor.py and
tests/test_005{3,4}, tests/test_0063.

issue verdict
#793 test_0053 SIGSEGV in faulthandler closed by this branch — level_1 tier_a 1396 passed, no segfault markers, against 2 failed + 1393 before
#639 test_0054 leaks a spinning child closed by this branch — see below
#807 test_adapt_with_repair hangs at np=2 still live — a different hang, in the adaptation path, not the watchdog; nothing here touches it
#698 cell_size() on a cell-less rank still live — names the watchdog only as the thing that reported the hang; the defect is in cell_size
#611, #679 still live — not territory; they are evaluate and swarm hangs that the watchdog would diagnose, not cause

#639, which this branch nearly left open

Four ranks and their prterun, orphaned to init for 15 hours at ~100% CPU
each
, were running on this machine while we wrote the fix — from this
worktree's own test_0054 runs. The 15-minute load average was 25.2 and went
to 12.9 when they were killed. The issue is a year-round tax on this machine,
not a hypothetical, and we had been running the file that causes it all day.

We would have shipped the wrong fix. The first attempt had each child watch
os.getppid() for init, which the issue's own evidence supports — every leak
it recorded had ppid=1. Probed: with pytest SIGKILLed, all four ranks and
prterun survived the full 70 s at 100% CPU
. Under mpirun a rank's parent
is prterun, so a dead pytest leaves the rank's parent alive and the rank
never notices; ppid=1 was true of the prterun the issue's ps had sampled,
not of the ranks.

Watching the test runner's pid directly, injected at spawn the way DUMPS and
READY already are, kills all five 5 s after the pytest kill.

Separately, the issue's suggestion (3) is right and we can show why: SIGTERM
to prterun alone took all four orphans down with it, where SIGKILL is what
removes mpirun from under its own ranks and orphans them in the first place.
Teardown now does TERM, then KILL.

What this says about the other 131

#639 is what the backlog looks like from the inside: filed in August with a
full diagnosis and a correct recommended fix, left open, and still costing
four cores today — while the sessions walking past it were editing the very
file it is about. Nothing was blocking it. It was simply never anybody's turn.

Underworld development team with AI support from Claude Code

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.

2 participants