Skip to content

Stop three tests stranding a waiting request in a module-level dict - #11287

Merged
danielhanchen merged 3 commits into
mainfrom
fix/auto-switch-waiter-leak
Sep 18, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
fix/auto-switch-waiter-leak

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

routes.inference._auto_switch_waiters is a module-level dict, and three tests in test_openai_auto_switch.py register a waiting request in it and never unregister: they call _note_switch_waiter(key, 1) with no matching -1 to stage a concurrent request. Everything else those tests touch goes through monkeypatch and is restored. This does not.

Found by putting a teardown check over the whole file:

test_concurrent_same_target_requests_load_once
  LEAK: _auto_switch_waiters={('org/b-gguf', 'q8_0'): 1}
test_queued_different_target_does_not_deadlock_current_swap
  LEAK: _auto_switch_waiters={('org/c-gguf', 'q4_k_m'): 1}
test_swap_waits_until_concurrent_request_finishes_resolving
  LEAK: _auto_switch_waiters={('org/b-gguf', 'q8_0'): 1}

Why it is worth fixing

_switch_waiter_count() sums every key rather than reading one:

def _switch_waiter_count() -> int:
    with _auto_switch_waiters_guard:
        return sum(max(0, count) for count in _auto_switch_waiters.values())

so one stranded entry inflates the count for the rest of the xdist worker, and _wait_for_model_switch_idle waits on requests that do not exist.

What this is not

It is not a fix for the 500s in #11241, and I want to be clear about that rather than imply a connection. I staged exactly this residue by hand and ran the three tests that fail in CI:

inf._auto_switch_waiters[("org/b-gguf", "q8_0")] = 1
->  test_chat_withheld_model_named_by_its_advertised_alias: PASSED
    test_chat_withheld_model_does_not_send_the_caller_to_load_it: PASSED
    test_chat_absent_model_with_only_resolver_withheld_checkpoints: PASSED

So this is a separate defect found while looking for that one. It is worth landing on its own terms, and it removes a confounder from the next attempt.

The fixture does two things on purpose

Restoring keeps the next test starting from a known state. Raising fails the test that dirtied the dict, which is the part that matters for this class of bug: the residue surfaces nowhere near its cause, which is exactly why #11241 has been hard to place.

The three tests that stage the condition deliberately carry @pytest.mark.stages_switch_waiter, registered in tests/conftest.py. The marker is checked rather than inferred from a name, so a new leak cannot arrive silently by resembling them.

Verification

before, with an external teardown check:  694 passed, 3 errors
after,  with the same check:              695 passed, 0 errors
after,  check removed:                    694 passed, 1 skipped

Sabotage, to show the guard bites rather than decorating:

remove @pytest.mark.stages_switch_waiter from one staging test
  ->  1 error: "this test left routes.inference._auto_switch_waiters dirty"
restored
  ->  694 passed, 1 skipped

An earlier version of this guard was a plain test asserting the dict was empty. Sabotage showed it passing while the fixture was disabled, because it sits near the top of the file and runs before the three tests that strand an entry. The marker form does not depend on position.

routes.inference._auto_switch_waiters is a module-level dict, and three tests in
test_openai_auto_switch.py register a waiting request in it without
unregistering: they call _note_switch_waiter(key, 1) with no matching -1 to
stage a concurrent request. Everything else those tests touch goes through
monkeypatch and is restored; this does not.

Found with a temporary teardown check over the whole file:

  test_concurrent_same_target_requests_load_once
    LEAK: _auto_switch_waiters={('org/b-gguf', 'q8_0'): 1}
  test_queued_different_target_does_not_deadlock_current_swap
    LEAK: _auto_switch_waiters={('org/c-gguf', 'q4_k_m'): 1}
  test_swap_waits_until_concurrent_request_finishes_resolving
    LEAK: _auto_switch_waiters={('org/b-gguf', 'q8_0'): 1}

It matters beyond tidiness because _switch_waiter_count() sums every key rather
than reading one, so a single stranded entry inflates the count for every later
test in the same xdist worker and _wait_for_model_switch_idle sees waiters that
do not exist.

The autouse fixture restores the dict and fails the test that dirtied it, which
is the part that matters for this class of bug: the residue surfaces nowhere
near its cause. The three tests that stage the condition on purpose carry
@pytest.mark.stages_switch_waiter, checked rather than inferred from a name, so
a new leak cannot arrive silently by resembling them.

Not a fix for the 500s in issue #11241. Staging that exact residue by hand and
running the three failing tests leaves them passing, so this is a separate
defect found while looking for that one, and removing it takes a confounder out
of the way.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 18, 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-18T19:03:03.695265Z d317f58 Manual request
🔒 Security Review ✅ Completed 2026-09-18T18:45:03.444192Z c5c69ff 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: c5c69ffbd6

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

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: c5c69ffbd6

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

The guard compared the registry before and after each test and raised on any
difference. That is wrong in one direction: several tests here clear
_auto_switch_waiters as part of their own setup, so the moment another file in
the same worker left an entry behind, every one of those tests was blamed for
tidying it up.

Reproduced by staging residue from a second file: 144 errors, all of the shape

  {('someone/else-gguf', 'q4_k_m'): 3} -> {}

which is cleanup, not a leak. Only a count that GREW inflates
_switch_waiter_count() for the tests that follow, so only growth is flagged.
With the same residue staged, the file is now clean again.

Also records which half of the fixture is proven. Removing a marker still fails
that test, so detection is covered. Removing the restore is not observable from
this file, because the growth check is per-test and a carried-over entry only
reaches files that run later in the same worker, which xdist decides at run
time. A cleanliness assertion in a second file would pass vacuously whenever the
two land in different processes, so the restore stays as a defensive measure and
is left explicitly unproven rather than given a test that cannot fail.
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed 849475ae9, which fixes a false positive in the guard I added here. Worth writing down because the guard would have reddened CI rather than protecting it, and the fault was the same class the PR is about: a check that was correct for the case in front of me and wrong about the case beside it.

The fixture compared the registry before and after each test and raised on any difference. Several tests in this file clear _auto_switch_waiters as part of their own setup, so the moment another file in the same xdist worker left an entry behind, every one of those tests was blamed for cleaning it up.

Staged exactly that, with a second file that seeds the registry first:

144 errors, all of the form
  {('someone/else-gguf', 'q4_k_m'): 3} -> {}

which is tidying, not leaking. Only a count that GREW inflates _switch_waiter_count() for the tests that follow, so only growth is flagged now. With the same residue staged: 695 passed, 0 errors.

I had argued the opposite a moment earlier, that per-test before/after diffing made foreign residue harmless. That was wrong, and testing it rather than reasoning about it is what showed the 144.

The PR body's verification section still holds, with the sabotage matrix now reading:

drop @pytest.mark.stages_switch_waiter from a staging test  ->  1 error   (detection works)
foreign residue seeded by another file                      ->  0 errors  (no false positive)
clean run                                                   ->  694 passed, 1 skipped

One half of the fixture is deliberately left unproven, and the docstring now says so: removing the restore is not observable from this file, because the growth check is per-test and a carried-over entry only reaches files that run later in the same worker, which xdist decides at run time. A cleanliness assertion in a second file would pass vacuously whenever the two land in different processes, which is worse than no test, so the restore stays as a defensive measure without one.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 849475ae91

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

try:
yield
finally:
after = dict(inference_route._auto_switch_waiters)

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 Inspect the waiter registry before monkeypatch teardown

For tests using the monkeypatch fixture, this autouse fixture is set up first and torn down last, so monkeypatch restores inference_route._auto_switch_waiters before this line reads it. All three newly marked tests call _wired() → _wire(), which replaces the registry via monkeypatch.setattr; consequently after observes the original dictionary and equals before, meaning the advertised leak check cannot detect those tests' staged entries (removing a marker would not make them fail). Make the guard depend on monkeypatch, or otherwise inspect the temporary registry before its teardown.

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.

The fragility is real and I have taken the remedy, in d317f58ab. The specific mechanism is not what happened, though, and the difference matters for what the fix is for.

You are right that _wire() rebinds the registry:

monkeypatch.setattr(inference_route, "_auto_switch_waiters", {})   # line 281

so a staged entry goes into a temporary dict, and the guard's correctness rests entirely on which fixture tears down first.

Where it differs: the order was already the right one, so the check does detect those tests today. Removing a marker from a staging test:

ERROR at teardown of test_swap_waits_until_concurrent_request_finishes_resolving
AssertionError: ... dirty: {('org/b-gguf', 'q8_0'): 1} (registry went {} -> {('org/b-gguf', 'q8_0'): 1})

{} to the staged entry is the temporary dict being read, not the original. Had monkeypatch torn down first, after would have been the original and equal to before, exactly as you describe. So the guard was not inert, but it was correct by accident, and that is the part worth fixing: this fixture requests monkeypatch now, which makes it set up after and tear down before, so the read lands on the dict the test wrote to by construction rather than by whichever fixture pytest instantiated first.

I checked this by running it rather than reasoning about fixture ordering, having already been wrong once on this PR about what per-test diffing implies.

No behaviour change intended and none observed:

clean run                                        694 passed, 1 skipped
marker removed from a staging test               1 error, naming that test
second file seeding residue before this one      695 passed, 0 errors

_wire() rebinds the registry with monkeypatch.setattr(inference_route,
"_auto_switch_waiters", {}), so a staged entry goes into a temporary dict.
Whichever of the two fixtures tears down second sees the original restored and
nothing amiss, which means the guard's correctness rests entirely on teardown
order.

That order happened to be right already: with the marker removed from a staging
test the guard fires, reporting {} -> {('org/b-gguf', 'q8_0'): 1}, so it was
reading the temporary dict. Working by accident is the problem. Requesting
monkeypatch makes this fixture set up after it and tear down before it, so the
read lands on the dict the test wrote to by construction rather than by
whichever fixture pytest happened to instantiate first.

No behaviour change intended, and none observed: 694 passed either way, the
marker sabotage still produces exactly one error, and a second file seeding
residue still produces none.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: d317f58ab4

ℹ️ 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 df18fa7 into main Sep 18, 2026
32 of 35 checks passed
@danielhanchen
danielhanchen deleted the fix/auto-switch-waiter-leak branch September 18, 2026 19:07
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…nslothai#11287)

* Stop three tests stranding a waiting request in a module-level dict

routes.inference._auto_switch_waiters is a module-level dict, and three tests in
test_openai_auto_switch.py register a waiting request in it without
unregistering: they call _note_switch_waiter(key, 1) with no matching -1 to
stage a concurrent request. Everything else those tests touch goes through
monkeypatch and is restored; this does not.

Found with a temporary teardown check over the whole file:

  test_concurrent_same_target_requests_load_once
    LEAK: _auto_switch_waiters={('org/b-gguf', 'q8_0'): 1}
  test_queued_different_target_does_not_deadlock_current_swap
    LEAK: _auto_switch_waiters={('org/c-gguf', 'q4_k_m'): 1}
  test_swap_waits_until_concurrent_request_finishes_resolving
    LEAK: _auto_switch_waiters={('org/b-gguf', 'q8_0'): 1}

It matters beyond tidiness because _switch_waiter_count() sums every key rather
than reading one, so a single stranded entry inflates the count for every later
test in the same xdist worker and _wait_for_model_switch_idle sees waiters that
do not exist.

The autouse fixture restores the dict and fails the test that dirtied it, which
is the part that matters for this class of bug: the residue surfaces nowhere
near its cause. The three tests that stage the condition on purpose carry
@pytest.mark.stages_switch_waiter, checked rather than inferred from a name, so
a new leak cannot arrive silently by resembling them.

Not a fix for the 500s in issue unslothai#11241. Staging that exact residue by hand and
running the three failing tests leaves them passing, so this is a separate
defect found while looking for that one, and removing it takes a confounder out
of the way.

* Flag only a waiter count that grew, not any change at all

The guard compared the registry before and after each test and raised on any
difference. That is wrong in one direction: several tests here clear
_auto_switch_waiters as part of their own setup, so the moment another file in
the same worker left an entry behind, every one of those tests was blamed for
tidying it up.

Reproduced by staging residue from a second file: 144 errors, all of the shape

  {('someone/else-gguf', 'q4_k_m'): 3} -> {}

which is cleanup, not a leak. Only a count that GREW inflates
_switch_waiter_count() for the tests that follow, so only growth is flagged.
With the same residue staged, the file is now clean again.

Also records which half of the fixture is proven. Removing a marker still fails
that test, so detection is covered. Removing the restore is not observable from
this file, because the growth check is per-test and a carried-over entry only
reaches files that run later in the same worker, which xdist decides at run
time. A cleanliness assertion in a second file would pass vacuously whenever the
two land in different processes, so the restore stays as a defensive measure and
is left explicitly unproven rather than given a test that cannot fail.

* Order the waiter guard against monkeypatch instead of by luck

_wire() rebinds the registry with monkeypatch.setattr(inference_route,
"_auto_switch_waiters", {}), so a staged entry goes into a temporary dict.
Whichever of the two fixtures tears down second sees the original restored and
nothing amiss, which means the guard's correctness rests entirely on teardown
order.

That order happened to be right already: with the marker removed from a staging
test the guard fires, reporting {} -> {('org/b-gguf', 'q8_0'): 1}, so it was
reading the temporary dict. Working by accident is the problem. Requesting
monkeypatch makes this fixture set up after it and tear down before it, so the
read lands on the dict the test wrote to by construction rather than by
whichever fixture pytest happened to instantiate first.

No behaviour change intended, and none observed: 694 passed either way, the
marker sabotage still produces exactly one error, and a second file seeding
residue still produces none.
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