Skip to content

Studio: serialize the compare-mode dispatcher lifecycle to fix a start race - #6922

Merged
danielhanchen merged 5 commits into
mainfrom
danielhanchen/dispatcher-lifecycle-lock
Jul 7, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
danielhanchen/dispatcher-lifecycle-lock

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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_lock so two compare requests can be in flight at once. It calls _start_dispatcher, whose body was an unlocked check-then-spawn:

if self._dispatcher_thread is not None and self._dispatcher_thread.is_alive():
    return
... create + start a new dispatcher thread ...

Two concurrent compare requests can both observe no live dispatcher and BOTH spawn one. The second dispatcher is orphaned because self._dispatcher_thread only tracks the last one. During a later unload that orphan can consume the "unloaded" reply off the shared _resp_queue before unload_model's _wait_response does, hanging the unload on its timeout. This is exactly the failure the surrounding code documents in the unload path.

The fix

  • Add self._dispatcher_lifecycle_lock = threading.Lock().
  • Take it around the whole body of both _start_dispatcher and _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_dispatcher now returns whether it actually spawned the thread. _generate_dispatched derives dispatcher_preexisting from that atomic result instead of a separate unlocked is_alive() read, keeping the preexisting/orphaned bookkeeping consistent with the start decision.

Deadlock / lock-order analysis

_stop_dispatcher joins the dispatcher, and the dispatcher loop takes _mailbox_lock. The deadlock to avoid is a thread holding _mailbox_lock while 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_lock nor _mailbox_lock.
  • _stop_dispatcher in _shutdown_subprocess (reached from the unload wedged paths under _gen_lock) is not under _mailbox_lock.
  • _stop_dispatcher in the _generate_dispatched orphaned-bail runs outside _mailbox_lock (the existing code documents this: "Outside _mailbox_lock: _stop_dispatcher joins the dispatcher, which itself takes that lock.").
  • _stop_dispatcher in _wait_dispatcher_idle runs after its _mailbox_lock blocks are released; that method is called from unload (under _gen_lock) and before the streaming _gen_lock path.

No call site holds _mailbox_lock when invoking start/stop, so joining under the new lock cannot deadlock. The lock order is always _gen_lock then _dispatcher_lifecycle_lock and is never inverted (the lifecycle bodies take no other lock; nothing needs the lifecycle lock to let the join complete). _start_dispatcher and _stop_dispatcher never call each other, so the non-reentrant lock is never re-acquired.

Test

Added test_concurrent_start_dispatcher_spawns_exactly_one to studio/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 live inference-dispatcher thread 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_dispatcher stub updated for the new bool return contract).

Declined items

Gemini's three medium getattr/hasattr suggestions on cancel_load were intentionally not applied. cancel_load only 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). Defensive getattr/hasattr there would be noise that obscures the real invariant rather than protecting against a reachable state.

…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@gemini-code-assist gemini-code-assist Bot 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.

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.

Comment on lines +557 to +563
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")

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.

medium

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.

Suggested change
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
  1. 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 using getattr(self, 'attribute_name', None) instead of direct access to prevent AttributeError.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +535 to +539
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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

danielhanchen and others added 2 commits July 7, 2026 04:21
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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: a1529ed275

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 7, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@danielhanchen
danielhanchen merged commit 9674e88 into main Jul 7, 2026
39 checks passed
@danielhanchen
danielhanchen deleted the danielhanchen/dispatcher-lifecycle-lock branch July 7, 2026 05:09
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.

1 participant