fix(watch): fall back to Timer timeout when watch() runs off the main thread

#4724 wrapped each watch-loop rebuild in _rebuild_timeout(), which arms
SIGALRM. signal.signal() only works on the main thread and raises
ValueError('signal only works in main thread') anywhere else. watch()'s
dispatch loop is run in a worker thread both under test
(test_watch_handler_honors_graphifyignore, gh-928) and when embedded, so
that ValueError escaped the loop's 'except TimeoutError' guard and tore
the watcher down before _rebuild_code ran: a non-ignored .py write never
triggered a rebuild.

Gate the SIGALRM path on threading.current_thread() is main_thread();
off the main thread, use the existing signal-free Timer fallback, which
bounds the rebuild just the same. Adds a behavioral regression test that
runs _rebuild_timeout() off the main thread and asserts it yields without
raising.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
safishamsiandClaude Opus 4.8 committed 2026-10-26 12:50:53 +00:00
1 parent 290b7f0b30
commit dac063456b
3 files changed
+38 -2

No files matched your search

+1 -1
View File
@@ -25,7 +25,7 @@ Full release notes with details on each version: [GitHub Releases](https://githu
- Fix: **ts** chained TypeScript decorators (`@(Link().toMany())`) are recovered as a decorator reference, and a lossy-parse warning names the real error region (#4711, #4715, thanks @Deepjyoti-Sarmah).
- Fix: **js** a `const X = require('pkg')` binding for an external package keeps its node (with the package as source) so `new X()` still resolves, while a require of a corpus-local file still folds to the required module (#4688, #4702, thanks @ayushcodes10).
- Fix: **detect** generated MSBuild `obj/` and `bin/` output is pruned only when build evidence is present (restore/runtime markers nearby), so a C# project scanned after a build no longer ingests generated sources while a real `src/bin` stays (#4742, thanks @Great-Peace).
- Fix: **watch** each watch rebuild is bounded by `GRAPHIFY_REBUILD_TIMEOUT` (default 600s, `0` disables), with a thread-Timer fallback where `SIGALRM` is unavailable, so a hung rebuild no longer stalls the watcher (#2173, #4724, thanks @danieldutu).
- Fix: **watch** each watch rebuild is bounded by `GRAPHIFY_REBUILD_TIMEOUT` (default 600s, `0` disables), with a thread-Timer fallback where `SIGALRM` is unavailable or `watch()` runs off the main thread (a `SIGALRM` arm there raises `ValueError` and would tear the watcher down before the rebuild ran), so a hung rebuild no longer stalls the watcher (#2173, #4724, thanks @danieldutu).
- Fix: **robot** each duplicate test-case name gets its own node (salted by line), so two tests with the same name are kept distinct (#4697, thanks @ayushcodes10).
- Fix: **vbnet** external namespaces and types emit a sourceless stub carrying an empty `source_file` sentinel like other languages, instead of a node that fails validation (#4725, #4728, thanks @madanlalit; reported by @alopezradicle).
- Fix: **rust** a `use` is scoped to the crate it names, so `use serde_json::Value` no longer resolves to a same-named type in another crate; a named `pub use` re-export is followed and a manifest-less binding stays `INFERRED` (#4699, #4712, thanks @Deepjyoti-Sarmah).
+8 -1
View File
@@ -3078,7 +3078,14 @@ def _rebuild_timeout():
if timeout <= 0:
yield
return
if hasattr(signal, "SIGALRM"):
# SIGALRM can only be armed from the main thread: signal.signal() raises
# ValueError ("signal only works in main thread") anywhere else. watch()'s
# dispatch loop is not always the main thread (it is run in a worker thread
# both under test and when embedded), and that ValueError would escape the
# `except TimeoutError` guard and tear the watch loop down before the
# rebuild runs (#4724 regressed gh-928). Off the main thread, fall back to
# the signal-free Timer path, which bounds the rebuild just the same.
if hasattr(signal, "SIGALRM") and threading.current_thread() is threading.main_thread():
def _sigalrm_bail(*_a):
# Kill workers before raising: TimeoutError would otherwise block in
# the pool's shutdown(wait=True) on a worker the alarm cannot stop.
+29
View File
@@ -2139,3 +2139,32 @@ def test_watch_rebuild_timeout_arms_a_timer_without_sigalrm():
assert kill_at < exit_at, "_bail exits before killing workers"
loop = ast.dump(_watch_fn("watch"))
assert "_rebuild_timeout" in loop, "watch() does not wrap its rebuild in _rebuild_timeout (#2173)"
def test_watch_rebuild_timeout_runs_off_the_main_thread():
"""SIGALRM can only be armed from the main thread: signal.signal() raises
ValueError anywhere else. watch()'s dispatch loop runs in a worker thread
both under test and when embedded, so _rebuild_timeout must not reach for
SIGALRM there — otherwise the ValueError escapes the loop's
`except TimeoutError` guard and tears watch() down before the rebuild runs
(#4724 regressed gh-928). The context manager must yield (run its body)
cleanly off the main thread."""
import threading
import graphify.watch as watch_mod
ran: list[bool] = []
errors: list[BaseException] = []
def _body():
try:
with watch_mod._rebuild_timeout():
ran.append(True)
except BaseException as exc: # noqa: BLE001 - record any escape
errors.append(exc)
t = threading.Thread(target=_body)
t.start()
t.join(timeout=10)
assert not t.is_alive(), "_rebuild_timeout blocked the worker thread"
assert errors == [], f"_rebuild_timeout raised off the main thread: {errors!r}"
assert ran == [True], "_rebuild_timeout never ran its body off the main thread"