Repository navigation
Studio: serialize the compare-mode dispatcher lifecycle to fix a start race - #6922
Conversation
…t race _generate_dispatched (compare mode) bypasses _gen_lock so two concurrent compare requests can both reach _start_dispatcher. The check-then-spawn there had no lock, so both could observe no live dispatcher and each spawn one. The extra dispatcher is orphaned (self._dispatcher_thread tracks only the last) and during a later unload it can consume the 'unloaded' reply off _resp_queue before unload_model's _wait_response, hanging the unload on its timeout. Add _dispatcher_lifecycle_lock and take it around the whole body of both _start_dispatcher and _stop_dispatcher, so start/stop cannot interleave and the second concurrent starter sees the dispatcher alive and returns. _start_dispatcher now returns whether it actually spawned the thread, and _generate_dispatched derives dispatcher_preexisting from that atomic result instead of a separate unlocked is_alive() read. No call site holds _mailbox_lock when calling start/stop, so joining the dispatcher (which takes _mailbox_lock) under the new lock cannot deadlock; the lock order is always _gen_lock then _dispatcher_lifecycle_lock and is never inverted.
|
@codex review |
There was a problem hiding this comment.
Code Review
This pull request introduces a new lock, _dispatcher_lifecycle_lock, to serialize the starting and stopping of the dispatcher thread in the orchestrator. This prevents race conditions where concurrent compare-mode requests could spawn multiple dispatcher threads, leading to orphaned threads and hung model unloads. A comprehensive test has been added to verify this behavior. The reviewer suggests accessing instance attributes defensively in _stop_dispatcher using getattr to tolerate partially-constructed objects during cleanup or teardown paths.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| with self._dispatcher_lifecycle_lock: | ||
| if self._dispatcher_thread is None: | ||
| return | ||
| self._dispatcher_stop.set() | ||
| self._dispatcher_thread.join(timeout = _DISPATCH_STOP_TIMEOUT) | ||
| self._dispatcher_thread = None | ||
| logger.debug("Dispatcher thread stopped") |
There was a problem hiding this comment.
The _stop_dispatcher method is part of the cleanup and teardown path (called during subprocess shutdown and atexit cleanup). To prevent potential AttributeErrors when executing on partially-constructed objects (for example, if __init__ fails before these attributes are defined, or when the orchestrator is instantiated via __new__ in tests), we should access these instance attributes defensively using getattr.
| with self._dispatcher_lifecycle_lock: | |
| if self._dispatcher_thread is None: | |
| return | |
| self._dispatcher_stop.set() | |
| self._dispatcher_thread.join(timeout = _DISPATCH_STOP_TIMEOUT) | |
| self._dispatcher_thread = None | |
| logger.debug("Dispatcher thread stopped") | |
| lock = getattr(self, "_dispatcher_lifecycle_lock", None) | |
| if lock is None: | |
| return | |
| with lock: | |
| dispatcher_thread = getattr(self, "_dispatcher_thread", None) | |
| if dispatcher_thread is None: | |
| return | |
| dispatcher_stop = getattr(self, "_dispatcher_stop", None) | |
| if dispatcher_stop is not None: | |
| dispatcher_stop.set() | |
| dispatcher_thread.join(timeout = _DISPATCH_STOP_TIMEOUT) | |
| self._dispatcher_thread = None | |
| logger.debug("Dispatcher thread stopped") |
References
- Ensure that cleanup or teardown paths (such as process termination or object destruction) tolerate partially-constructed objects (e.g., when
__init__raises an exception before all attributes are initialized, or when the object is instantiated via__new__in tests). Access instance attributes in these paths usinggetattr(self, 'attribute_name', None)instead of direct access to preventAttributeError.
There was a problem hiding this comment.
Declining this one. _stop_dispatcher runs only on the fully constructed long-lived orchestrator singleton (subprocess shutdown / atexit on a successfully started instance). There is no production path that calls it on a partially-constructed object; the __new__-in-tests case is a test artifact, and the pre-existing code already accessed _dispatcher_thread directly. Adding defensive getattr in the hot teardown path is noise that obscures the real invariant, so leaving as-is.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d9f9236c3d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| with self._dispatcher_lifecycle_lock: | ||
| if self._dispatcher_thread is not None and self._dispatcher_thread.is_alive(): | ||
| return False | ||
|
|
||
| self._dispatcher_stop.clear() | ||
| self._dispatcher_thread = threading.Thread( | ||
| target = self._dispatcher_loop, | ||
| daemon = True, | ||
| name = "inference-dispatcher", | ||
| ) | ||
| self._dispatcher_thread.start() | ||
| logger.debug("Dispatcher thread started") | ||
| self._dispatcher_stop.clear() |
There was a problem hiding this comment.
Don’t restart the dispatcher after unload stops it
When a compare request has already passed the early _unload_pending check and then blocks here behind an unload's _stop_dispatcher(), it resumes after _wait_dispatcher_idle() has stopped the idle dispatcher and starts a fresh one. The unload path can then return from _wait_dispatcher_idle(), send unload, and wait on _resp_queue while this new dispatcher has no mailbox yet (the later unload recheck happens only after image/cmd setup), so the dispatcher can drop the unloaded reply and hang the unload until timeout. Recheck the unload state under the lifecycle lock or otherwise prevent starts that were queued behind a stop.
Useful? React with 👍 / 👎.
A compare request could pass the early _unload_pending check, then block in _start_dispatcher on _dispatcher_lifecycle_lock behind an unload's _stop_dispatcher. When the unload released the lock the start spawned a fresh dispatcher, which became the resp_queue reader and consumed the worker's unroutable 'unloaded' reply before unload_model's _wait_response saw it, hanging the unload for 300s. Gate _start_dispatcher on _unload_pending under the lifecycle lock, and set _unload_pending under the same lock ahead of the stop, so any start queued behind the stop observes the unload and refuses. Ordering stays _gen_lock -> _dispatcher_lifecycle_lock. Adds a regression test forcing the queued-behind-stop interleaving.
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…her-lifecycle-lock
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
Summary
Follow-up to #6918. Fixes a genuine concurrency race Gemini flagged in the compare-mode dispatcher lifecycle in
studio/backend/core/inference/orchestrator.py.The race
_generate_dispatched(compare mode) deliberately bypasses_gen_lockso two compare requests can be in flight at once. It calls_start_dispatcher, whose body was an unlocked check-then-spawn:Two concurrent compare requests can both observe no live dispatcher and BOTH spawn one. The second dispatcher is orphaned because
self._dispatcher_threadonly tracks the last one. During a later unload that orphan can consume the"unloaded"reply off the shared_resp_queuebeforeunload_model's_wait_responsedoes, hanging the unload on its timeout. This is exactly the failure the surrounding code documents in the unload path.The fix
self._dispatcher_lifecycle_lock = threading.Lock()._start_dispatcherand_stop_dispatcher, so start and stop cannot interleave. The second concurrent starter now sees the dispatcher alive under the lock and returns, so at most one dispatcher ever exists._start_dispatchernow returns whether it actually spawned the thread._generate_dispatchedderivesdispatcher_preexistingfrom that atomic result instead of a separate unlockedis_alive()read, keeping the preexisting/orphaned bookkeeping consistent with the start decision.Deadlock / lock-order analysis
_stop_dispatcherjoins the dispatcher, and the dispatcher loop takes_mailbox_lock. The deadlock to avoid is a thread holding_mailbox_lockwhile acquiring_dispatcher_lifecycle_lock(a joiner then holds the lifecycle lock and waits on the dispatcher, which waits on_mailbox_lock). Every call site was checked:_start_dispatcher(only caller:_generate_dispatched) holds neither_gen_locknor_mailbox_lock._stop_dispatcherin_shutdown_subprocess(reached from the unload wedged paths under_gen_lock) is not under_mailbox_lock._stop_dispatcherin the_generate_dispatchedorphaned-bail runs outside_mailbox_lock(the existing code documents this: "Outside_mailbox_lock:_stop_dispatcherjoins the dispatcher, which itself takes that lock.")._stop_dispatcherin_wait_dispatcher_idleruns after its_mailbox_lockblocks are released; that method is called from unload (under_gen_lock) and before the streaming_gen_lockpath.No call site holds
_mailbox_lockwhen invoking start/stop, so joining under the new lock cannot deadlock. The lock order is always_gen_lockthen_dispatcher_lifecycle_lockand is never inverted (the lifecycle bodies take no other lock; nothing needs the lifecycle lock to let the join complete)._start_dispatcherand_stop_dispatchernever call each other, so the non-reentrant lock is never re-acquired.Test
Added
test_concurrent_start_dispatcher_spawns_exactly_onetostudio/backend/tests/test_orchestrator_unload_cancel.py: 32 threads aligned on a barrier all call the real_start_dispatcher, and it asserts exactly one call returns True (spawned) and exactly one liveinference-dispatcherthread exists (no orphan). Against a lockless check-then-spawn this deterministically observes multiple spawns; with the lifecycle lock exactly one is created. The existing 42 tests in that file still pass (one had its_start_dispatcherstub updated for the new bool return contract).Declined items
Gemini's three medium
getattr/hasattrsuggestions oncancel_loadwere intentionally not applied.cancel_loadonly runs on the fully constructed, long-lived orchestrator singleton; there is no production path where it executes on a partially constructed object (the__new__/partial-init case is test-only and theoretical). Defensivegetattr/hasattrthere would be noise that obscures the real invariant rather than protecting against a reachable state.