Skip to content

Hold the diffusion load worker on an event instead of a sleep - #11392

Merged
danielhanchen merged 2 commits into
mainfrom
ci/diffusion-concurrent-load-event
Sep 20, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
ci/diffusion-concurrent-load-event

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

studio/backend/tests/test_diffusion_backend.py::test_begin_load_rejects_concurrent failed on run 35542154102, on a commit that touched nothing in this area:

tests/test_diffusion_backend.py:2509: in test_begin_load_rejects_concurrent
    thread.join(timeout = 5)
/opt/hostedtoolcache/Python/3.13.15/x64/lib/python3.13/threading.py:1086: in join
    raise RuntimeError("cannot join thread before it is started")
E   RuntimeError: cannot join thread before it is started

Why

threading.enumerate() lists threads that have called start() but have not begun running yet: CPython keeps them in _limbo until the OS schedules them, and join() on one of those raises. begin_load starts its worker and returns immediately, so the drain at the end of the test can enumerate that worker and be unable to join it at the same instant. On an idle machine the worker is always running by then, which is why this only shows up on a loaded runner.

The assertion itself was never the problem. It was the drain.

Change

The worker now waits on an event the test owns, and the test waits for it to signal from inside load_pipeline before asking for the second load. A thread that has reached its target has started, so the join is always legal.

That also removes a second, quieter timing assumption. The old stub was time.sleep(0.2), so the rejection was being asserted against a load that was only in flight for as long as that sleep lasted. Now it is asserted against a load that is genuinely running and stays running until the test releases it.

Threads left in limbo by other tests are skipped rather than joined. threading.enumerate() is process-global, and those are not this test's to drain.

The claim is unchanged

A second begin_load while one is in flight still has to raise. Removing the RuntimeError from begin_load fails this test with DID NOT RAISE RuntimeError, checked against a green baseline and then restored.

One thing this does not fix

test_mirrored_base_still_trips_the_flux2_shape_guard fails in a full-file run on my machine both with and without this patch, so it is not introduced here and is not addressed here. It is green in CI, so it reads as a local environment difference rather than a defect, but I would rather name it than leave it in a passing summary.

test_begin_load_rejects_concurrent failed on run 35542154102 with

  tests/test_diffusion_backend.py:2509: in test_begin_load_rejects_concurrent
      thread.join(timeout = 5)
  RuntimeError: cannot join thread before it is started

on a commit that touched nothing in this area. threading.enumerate() lists
threads that have called start() but have not begun running yet, because
CPython holds them in _limbo until the OS schedules them, and joining one of
those raises. begin_load starts its worker and returns at once, so the drain at
the end of the test can enumerate that worker and be unable to join it in the
same instant.

The worker now waits on an event this test owns, and the test waits for it to
signal from inside load_pipeline before asking for the second load. A thread
that has reached the target has started, so the join is always legal. It also
makes the rejection an assertion about a load that is genuinely running rather
than one that happens to be inside a 0.2s sleep that has not elapsed.

Threads left in limbo by other tests are skipped rather than joined, since they
are not this test's to drain.

The claim is unchanged: a second begin_load while one is in flight still has to
raise. Removing the RuntimeError from begin_load fails this test with DID NOT
RAISE, checked against a green baseline.

Unrelated to this change, test_mirrored_base_still_trips_the_flux2_shape_guard
fails in a full-file run on this host both 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 20, 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-20T23:10:15.822832Z 956f3b7 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: ff22ee1bde

ℹ️ 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 +2534 to +2535
if thread.ident is not None:
thread.join(timeout = 5)

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 Join only the worker that entered the stub

When any unrelated process-global thread is starting concurrently, thread.ident is not None does not guarantee that join() is legal: CPython assigns the identifier before setting the internal _started event that join() checks, and threading.enumerate() includes threads in that intervening limbo state. The guard can therefore pass and the next line can still raise the same RuntimeError this change is intended to eliminate; capture threading.current_thread() in held and join only that known worker instead of enumerating all new threads.

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 my guard was wrong for exactly the reason you give. CPython sets Thread.ident in _bootstrap_inner before it sets the _started event that join() waits on, so 'has an ident' is not 'is joinable', and since threading.enumerate() is process-global the thread sitting in that window need not even be this test's.

Fixed in 956f3b7 by dropping the enumerate() diff entirely: the stub records threading.current_thread() from inside itself and the drain joins that one thread. A thread running its own target is past the window by definition, so there is no race left and no unrelated thread to mistake for the worker.

Re-checked that removing the RuntimeError from begin_load still fails this test after the change.

Filtering the enumerate() diff on Thread.ident was not enough. CPython assigns
ident in _bootstrap_inner before it sets the _started event that join() waits
on, so a thread can be enumerated, carry an ident, and still raise 'cannot join
thread before it is started'. Since enumerate() is process-global, the thread
in that window need not even belong to this test.

The stub now records threading.current_thread() from inside itself and the
drain joins that one thread. A thread running its own target is past the window
by definition, so there is nothing left to race with and no unrelated thread to
misidentify as this test's worker.

Removing the RuntimeError from begin_load still fails this test, checked again
after the change.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 956f3b7c35

ℹ️ 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 9ba936a into main Sep 20, 2026
43 checks passed
@danielhanchen
danielhanchen deleted the ci/diffusion-concurrent-load-event branch September 20, 2026 23:48
pull Bot pushed a commit to chizee/unsloth that referenced this pull request Sep 21, 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.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…hai#11392)

* Hold the diffusion load worker on an event instead of a sleep

test_begin_load_rejects_concurrent failed on run 35542154102 with

  tests/test_diffusion_backend.py:2509: in test_begin_load_rejects_concurrent
      thread.join(timeout = 5)
  RuntimeError: cannot join thread before it is started

on a commit that touched nothing in this area. threading.enumerate() lists
threads that have called start() but have not begun running yet, because
CPython holds them in _limbo until the OS schedules them, and joining one of
those raises. begin_load starts its worker and returns at once, so the drain at
the end of the test can enumerate that worker and be unable to join it in the
same instant.

The worker now waits on an event this test owns, and the test waits for it to
signal from inside load_pipeline before asking for the second load. A thread
that has reached the target has started, so the join is always legal. It also
makes the rejection an assertion about a load that is genuinely running rather
than one that happens to be inside a 0.2s sleep that has not elapsed.

Threads left in limbo by other tests are skipped rather than joined, since they
are not this test's to drain.

The claim is unchanged: a second begin_load while one is in flight still has to
raise. Removing the RuntimeError from begin_load fails this test with DID NOT
RAISE, checked against a green baseline.

Unrelated to this change, test_mirrored_base_still_trips_the_flux2_shape_guard
fails in a full-file run on this host both with and without the patch, so it is
not introduced here.

* Join the worker by identity, not by diffing the thread table

Filtering the enumerate() diff on Thread.ident was not enough. CPython assigns
ident in _bootstrap_inner before it sets the _started event that join() waits
on, so a thread can be enumerated, carry an ident, and still raise 'cannot join
thread before it is started'. Since enumerate() is process-global, the thread
in that window need not even belong to this test.

The stub now records threading.current_thread() from inside itself and the
drain joins that one thread. A thread running its own target is past the window
by definition, so there is nothing left to race with and no unrelated thread to
misidentify as this test's worker.

Removing the RuntimeError from begin_load still fails this test, checked again
after the change.
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