Skip to content

Drain worker threads without racing their start - #11400

Merged
danielhanchen merged 2 commits into
mainfrom
ci/drain-threads-without-racing-start
Sep 21, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
ci/drain-threads-without-racing-start

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

#11392 fixed one test that joined a thread it had found through threading.enumerate():

RuntimeError: cannot join thread before it is started

start() puts a thread in CPython's _limbo, where it is enumerable but not yet joinable, and enumerate() returns it in that state. That is not specific to the diffusion test. Five other drains in the backend suite have the same shape and the same latent failure:

File Sites
test_mlx_repair.py 3
test_mlx_autorepair_no_torch_optout.py 3
test_sandbox_files_and_storage_roots.py 1
test_mcp_http_sessions.py 1

Why the obvious guards do not work

  • Thread.name is set at construction, so matching on "mlx-autorepair" says nothing about whether the thread has started. Every one of these drains filters by name.
  • Thread.ident is assigned in _bootstrap_inner before the _started event that join() waits on, so an ident check can pass and the very next line still raise.
  • is_alive() is False both before a thread starts and after it finishes, so skipping on it silently drops the worker the drain existed to wait for, which is worse than the crash.

The reliable signal is the exception itself. It means "not started YET", and a thread that has been started always gets there.

Change

studio/backend/tests/thread_drain.py adds join_when_started(thread, timeout), which retries until the thread joins or the caller's deadline passes, and returns whether it actually finished. The return value matters: callers keep asserting on a leaked worker instead of having one absorbed into a green run.

Joining the current thread raises the same RuntimeError for a reason that never resolves, so that case is refused up front rather than retried. Without that guard the relevant test takes 31s to fail instead of raising immediately, which is the measurement that justifies the special case.

Where a test owns its worker outright, recording it from inside the thread is still better than enumerating at all, which is what #11392 does. This helper is for the drains that legitimately cannot name their thread in advance.

Guard

tests/test_thread_drain.py pins both halves, because a helper that swallowed both would turn a hung worker into a passing test:

  • an unstarted thread does not raise and is reported as not running
  • a thread still running at the deadline is reported as such
  • and the premise, that a bare join() on an unstarted thread really does raise, so the first case cannot pass for the wrong reason

Each was checked by breaking the helper one way at a time against a green baseline: returning True unconditionally fails the deadline case, letting the RuntimeError escape fails the unstarted case, and dropping the current-thread guard fails that case after burning the full timeout.

One thing this does not fix

test_a_traversal_id_stays_inside_the_sandbox_root_and_opens_nothing fails on my machine with and without this patch, so it is not introduced here and is not addressed here.

#11392 fixed one test that joined a thread it had found through
threading.enumerate() and hit

  RuntimeError: cannot join thread before it is started

start() puts a thread in CPython's _limbo, where it is enumerable but not yet
joinable, and enumerate() returns it in that state. Five other drains in the
backend suite have the same shape and the same latent failure:

  test_mlx_repair.py (three sites)
  test_mlx_autorepair_no_torch_optout.py (three sites)
  test_sandbox_files_and_storage_roots.py
  test_mcp_http_sessions.py

Filtering does not help them. Thread.name is set at construction, so matching
on 'mlx-autorepair' says nothing about whether the thread has started.
Thread.ident is assigned before the _started event join() waits on, so an ident
check passes and the next line still raises. is_alive() is False both before a
thread starts and after it finishes, so skipping on it drops the very worker
the drain exists to wait for.

The exception is the reliable signal: it means not started YET, and a started
thread always gets there. join_when_started retries until the thread joins or
the caller's deadline passes, and returns whether it finished so callers keep
asserting on a leaked worker rather than having it absorbed.

Joining the current thread raises the same RuntimeError for a reason that never
resolves, so that case is refused up front instead of spending the timeout.
Without the guard the new test takes 31s to fail rather than raising at once.

tests/test_thread_drain.py pins both halves: an unstarted thread does not raise,
and a thread still running at the deadline is still reported. It also pins the
premise, that a bare join() on an unstarted thread raises, so the first case
cannot pass for the wrong reason. Each behaviour was checked by breaking the
helper one way at a time against a green baseline.

Unrelated to this change,
test_a_traversal_id_stays_inside_the_sandbox_root_and_opens_nothing fails on
this host with and without the patch, so it is not introduced here.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-21T02:37:50.634391Z f8b1c20 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: df86a76e32

ℹ️ 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 thread studio/backend/tests/thread_drain.py Outdated
Comment on lines +55 to +56
if remaining <= 0:
return not thread.is_alive()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Report an unstarted thread as undrained at the deadline

When a runner is loaded enough that an enumerated thread remains in CPython's _limbo past this deadline, join() still raises and is_alive() is False because _started has not been set, so this branch returns True even though the thread is still scheduled and can run later. The MLX fixture callers assert this result and then restore their monkeypatches, allowing that worker to execute against a subsequent test—the exact leak this helper is intended to prevent. A deadline reached while join() still reports “before it is started” must be reported as undrained rather than inferred from is_alive().

Useful? React with 👍 / 👎.

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.

Correct, and it is the exact leak the helper was written to stop rather than a rounding error. A thread still in _limbo at the deadline has _started unset, so join() keeps raising and is_alive() is False for the same reason it is False after a thread finishes. Reading the answer off is_alive() therefore called that thread drained while it was still scheduled, and the MLX fixtures assert the result and then restore their monkeypatches, so it would have gone on to run the real repair and detection against the next test.

Fixed in f8b1c20: the answer comes from join() rather than from is_alive(). True is now reserved for a thread that actually finished, and a thread join() still refuses at the deadline is reported undrained.

The test for that case asserts False now, and putting the is_alive() read back fails it.

If a thread is still in _limbo when the deadline passes, join() keeps raising
and is_alive() is False, because _started was never set. Reading the answer off
is_alive() therefore returned True and called that thread drained, when in fact
it has not run yet and still will.

That is the leak this helper exists to prevent, not a harmless inaccuracy: the
MLX fixtures assert the result and then restore their monkeypatches, so a worker
reported as drained goes on to run the real repair and detection against the
next test.

The answer now comes from join() rather than from is_alive(). True is reserved
for a thread that actually finished; a thread join() still refuses at the
deadline is reported undrained.

The test for the unstarted case now asserts False, and putting the is_alive()
read back fails it.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: f8b1c20e34

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

@danielhanchen
danielhanchen merged commit 655c1df into main Sep 21, 2026
41 of 43 checks passed
@danielhanchen
danielhanchen deleted the ci/drain-threads-without-racing-start branch September 21, 2026 03:34
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
* Drain worker threads without racing their start

unslothai#11392 fixed one test that joined a thread it had found through
threading.enumerate() and hit

  RuntimeError: cannot join thread before it is started

start() puts a thread in CPython's _limbo, where it is enumerable but not yet
joinable, and enumerate() returns it in that state. Five other drains in the
backend suite have the same shape and the same latent failure:

  test_mlx_repair.py (three sites)
  test_mlx_autorepair_no_torch_optout.py (three sites)
  test_sandbox_files_and_storage_roots.py
  test_mcp_http_sessions.py

Filtering does not help them. Thread.name is set at construction, so matching
on 'mlx-autorepair' says nothing about whether the thread has started.
Thread.ident is assigned before the _started event join() waits on, so an ident
check passes and the next line still raises. is_alive() is False both before a
thread starts and after it finishes, so skipping on it drops the very worker
the drain exists to wait for.

The exception is the reliable signal: it means not started YET, and a started
thread always gets there. join_when_started retries until the thread joins or
the caller's deadline passes, and returns whether it finished so callers keep
asserting on a leaked worker rather than having it absorbed.

Joining the current thread raises the same RuntimeError for a reason that never
resolves, so that case is refused up front instead of spending the timeout.
Without the guard the new test takes 31s to fail rather than raising at once.

tests/test_thread_drain.py pins both halves: an unstarted thread does not raise,
and a thread still running at the deadline is still reported. It also pins the
premise, that a bare join() on an unstarted thread raises, so the first case
cannot pass for the wrong reason. Each behaviour was checked by breaking the
helper one way at a time against a green baseline.

Unrelated to this change,
test_a_traversal_id_stays_inside_the_sandbox_root_and_opens_nothing fails on
this host with and without the patch, so it is not introduced here.

* Do not call an unstarted thread drained

If a thread is still in _limbo when the deadline passes, join() keeps raising
and is_alive() is False, because _started was never set. Reading the answer off
is_alive() therefore returned True and called that thread drained, when in fact
it has not run yet and still will.

That is the leak this helper exists to prevent, not a harmless inaccuracy: the
MLX fixtures assert the result and then restore their monkeypatches, so a worker
reported as drained goes on to run the real repair and detection against the
next test.

The answer now comes from join() rather than from is_alive(). True is reserved
for a thread that actually finished; a thread join() still refuses at the
deadline is reported undrained.

The test for the unstarted case now asserts False, and putting the is_alive()
read back fails it.
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