Skip to content

Backend CI (Python 3.13, l-r): a withheld model 500s instead of 404ing, from state a neighbouring test leaves behind #11241

Closed

Description

@danielhanchen

Backend CI / (Python 3.13, l-r) is red on main and reproduces on re-run, so it is not a one-off. Opening this rather than guessing at a fix, because I could not reproduce it outside CI (details at the end).

Symptom

FAILED tests/test_openai_auto_switch.py::test_chat_withheld_model_named_by_its_advertised_alias - assert 500 == 404
FAILED tests/test_openai_auto_switch.py::test_chat_absent_model_with_only_resolver_withheld_checkpoints - assert 500 == 404

Which of the two fails varies between runs: the first run of 9ace1ed45 failed both, the re-run failed only the second. The failure itself is consistent.

What the route actually does

Could not check GGUF files for 'unsloth/B-GGUF' after 3 attempts: [Errno -2] name resolution blocked in tests
Could not read config.json for 'unsloth/B-GGUF' ...
Transformers tier default (5.5.0) selected for unsloth/B-GGUF (no match)
ExportOrchestrator initialized (subprocess mode)
Error loading model: '_B' object has no attribute 'load_model'

Traceback (most recent call last):
  File "studio/backend/routes/inference.py", line 16213, in _load_model_impl
    backend.load_model,
AttributeError: '_B' object has no attribute 'load_model'

A request for a withheld model should be refused with 404 before anything is loaded. Instead the route reaches _load_model_impl, calls load_model on the test's backend double, and the AttributeError surfaces as a 500.

Why this looks like leaked state, not a bug in the test

test_chat_withheld_model_named_by_its_advertised_alias asks for the model "tiny", and its wiring only ever mentions org/A-GGUF and unsloth/whisper-tiny. It never names unsloth/B-GGUF.

But unsloth/B-GGUF appears 266 times in that same file, in the auto-switch and auto-download tests that deliberately drive a load hook. So the model the route tried to load came from a different test, and the probes and the load happened inside the failing test's window (the log lines are in its captured stdout).

That points at module-level state in routes/inference.py surviving from one test into the next, rather than at these two tests. It also explains the varying failing subset, since xdist ordering decides which test inherits it.

Two further details worth keeping:

  • The Hub probes were real network calls, retried five times with backoff (1+2+4+8+8s, twice, about 46s) before falling through. In a suite that blocks egress, the path that reached the Hub was not the stubbed one.
  • Falling back to Transformers tier default (5.5.0) ... (no match) and then attempting a load is the step that converts "I could not determine anything about this model" into a load attempt. Refusing earlier would turn this into the 404 the test expects regardless of the leak.

Where it started

commit Backend CI
448bf6b05 and earlier today failure, but on the unrelated main-reds fixed in #11222
0133c89a5 (#11222) success, including l-r
9ace1ed45 (#11220) failure, this issue, first sighting

#11220 touches only install.ps1, studio/setup.ps1 and tests/studio/, nothing under studio/backend, so it is very unlikely to be the cause; the more probable reading is that it shifted shard timing or ordering enough to expose an existing leak.

What I could not do

I could not reproduce it locally. The file passes alone (694 passed), passes offline with an empty HF_HOME, and a single-process run of the whole l-r selection gives 0 failures on this host. That last run is not equivalent to CI: five files in the selection error at collection here because this environment cannot import unsloth, so they never run and cannot pollute. Reproducing it needs a machine where the whole shard actually executes.

Four hypotheses tested and rejected along the way: the new autouse fixture from #11222 (ruled out by l-r being green on the very commit that added it), HF cache state, offline mode, and the tests in isolation.

Activity

  1. danielhanchen commented on Sep 18, 2026

    @danielhanchen
    MemberAuthor

    Update: this is intermittent, not deterministic, and main is green again.

    • 9ace1ed45 - failed, and failed again on a re-run of the same job
    • 16408b25f - Backend CI success

    The only change between those two commits is #11240, which edits scripts/scan_packages_baseline.json and nothing else, so the l-r shard's test content is byte-identical across the pass and the two failures. That rules out shard content and leaves ordering or timing, which fits the leak reading above: whether the failure appears depends on which tests land on the same xdist worker, and in which order.

    Correcting my own note in the description: I called it deterministic after it failed on re-run. Two failures in a row at one head is not determinism, and a pass at a head with identical test content settles it. It is a flake with a high failure rate, which is worse than a rare one for anyone trying to reproduce it, but it does mean a green run proves nothing.

    One negative result, to save someone the same search. My local reproduction attempt passed only because five files in the selection error at collection in that environment and never run:

    tests/test_mcp_server.py
    tests/test_native_audio.py
    tests/test_native_tool_token_provenance.py
    tests/test_nudge_tool_calls_wiring.py
    tests/test_online_tokenization_wiring.py
    

    They were the obvious candidates for the polluter on that basis. None of them references inference_route at all, so if one of them is involved it is indirectly, through a module it imports, rather than by touching the route's globals itself.

  2. danielhanchen commented on Sep 18, 2026

    @danielhanchen
    MemberAuthor

    Recurred on main at 6803a826e, run 35324333375, same three tests. This time the log carries the cause rather than just the status code:

    Error loading model: '_B' object has no attribute 'load_model'
      File "studio/backend/routes/inference.py", line 16213, in _load_model_impl
        backend.load_model,
    AttributeError: '_B' object has no attribute 'load_model'
    

    That narrows it a lot. _B is not a product class. It is built in the test tree only, by type("_B", (), ...), in exactly two files:

    • studio/backend/tests/test_openai_auto_switch.py:6019, 6073, 6241 - {"active_model_name": ..., "models": {}}, which is precisely a _B with no load_model
    • studio/backend/tests/test_model_memory_settings.py:1371 via _fake_backend()

    Both files are in the l-r shard. So the 500 is a stale get_inference_backend still answering with a neighbour's double when the withheld tests run, and the route reaches the load path instead of the 404.

    What I have ruled out so far, on be95e417b:

    • Not the tests themselves. -k withheld alone: 5 passed. The whole file in declaration order: 694 passed, 1 skipped.
    • Not an obvious unwound patch. Every get_inference_backend patch in both candidate files goes through the monkeypatch fixture, and every bare MonkeyPatch() in the shard (conftest.py:224, conftest.py:622, test_mtp_drafter_companion.py:3956, test_rag_upload_progress.py:409) is paired with an undo().
    • Not a cached backend. _load_model_impl binds it fresh at line 16138, backend = await asyncio.to_thread(get_inference_backend), so it reads the module global at call time.

    So the leak is a route into get_inference_backend that does not go through the fixture, and the _B shape says which double it is. Reproducing it still needs the full l-r selection actually running: 5 files in it cannot import unsloth on this host and error at collection.

  3. danielhanchen commented on Sep 18, 2026

    @danielhanchen
    MemberAuthor

    Recurred on main at 40e94577f, so this is not specific to any branch. Run 35370782742, job 105683967288, (Python 3.13, l-r):

    FAILED tests/test_openai_auto_switch.py::test_chat_withheld_model_named_by_its_advertised_alias      assert 500 == 404
    FAILED tests/test_openai_auto_switch.py::test_chat_withheld_model_does_not_send_the_caller_to_load_it assert 500 == 404
    FAILED tests/test_openai_auto_switch.py::test_chat_absent_model_with_only_resolver_withheld_checkpoints assert 500 == 404
    FAILED tests/test_llama_cpp_wait_for_health.py::TestHealthWaitMeasuresStalls::test_mmap_page_ins_with_flat_resident_memory_count assert False is True
    4 failed, 18745 passed, 236 skipped in 371.32s
    

    with, for each of the three:

    Error loading model: '_B' object has no attribute 'load_model'
      studio/backend/routes/inference.py:16213 in _load_model_impl
        backend.load_model,
    

    What the signature actually means

    _B is the inference-backend double from _wire_unloaded_chat, studio/backend/tests/test_openai_auto_switch.py:6082:

    lambda: type("_B", (), {"active_model_name": None, "models": {}})()

    It is deliberately minimal because these tests expect a 404 before the backend is touched at all. So the double is not wrong and the missing attribute is not the bug: the route reached the auto-load path on a request that should have been refused as withheld. The AttributeError is the first thing that happens afterwards, not the cause.

    Reproduction attempts, all negative

    Everything below on 40e94577f in a clean worktree.

    attempt result
    the three tests alone 5 passed
    tests/test_openai_auto_switch.py whole file, fixed order 694 passed, 1 skipped
    full l-r shard, -n 8, fixed order target tests pass
    full l-r shard with CI's exact flags, -n 4 --dist loadgroup --timeout=330 target tests pass
    test_llama_cpp_wait_for_health.py + test_openai_auto_switch.py in one process 781 passed, 1 skipped

    The fourth row matters: -n 4 --dist loadgroup is what CI runs, taken from the job log rather than assumed, and worker grouping is what decides which tests share an interpreter. It still does not reproduce.

    Why this environment probably cannot reproduce it

    In the same local shard runs, 242 tests fail and 257 error that are green in CI, all in test_rag_*, test_pdf_* and test_mcp_server, from dependencies this host does not have. A test that dies on an import or an early assertion does not execute the code that would leave the state behind. So the neighbour that pollutes routes.inference in CI may be one of the tests that never runs to completion here, and no amount of reordering on this host will surface it.

    That is the blocker worth recording: reproducing this needs an environment where the whole l-r shard genuinely passes, not merely a machine that can run pytest.

    Narrowed, for whoever picks it up

    • The fault is upstream of the AttributeError: find why the withheld branch does not fire, not why _B lacks load_model.
    • It is order-dependent and survives into a worker, so it is process-global state in routes.inference or one of its imports, not fixture state.
    • _wire_unloaded_chat patches _cached_local_catalog, _openai_catalog_objects, get_llama_cpp_backend, get_inference_backend, resolve_local_gguf and describe_local_miss, all through monkeypatch, so they are restored. Whatever leaks is something it does not patch.
    • The neighbouring test_llama_cpp_wait_for_health failure in the same job is likely the same root cause rather than a second bug, and it is a cheaper thing to bisect: one assertion, no HTTP layer.
  4. danielhanchen commented on Sep 18, 2026

    @danielhanchen
    MemberAuthor

    Follow-up: the two failures in this job are almost certainly two different problems, and the title fits only one of them. Recurred again on main at 14b40739a (run 35371407170, job 105686000115), this time as 2 failures rather than 4:

    FAILED tests/test_llama_cpp_wait_for_health.py::TestHealthWaitMeasuresStalls::test_mmap_page_ins_with_flat_resident_memory_count - assert False is True
    FAILED tests/test_openai_auto_switch.py::test_chat_absent_model_with_only_resolver_withheld_checkpoints - assert 500 == 404
    

    The test_mmap_page_ins row has now failed on both consecutive main runs, while which of the test_openai_auto_switch rows fail varies (3 then 1). That difference is the clue: they do not look like one root cause.

    The mmap row is resource contention, not leaked state

    It does not depend on anything a neighbouring test monkeypatches. It depends on the machine.

    The test disables the other two progress signals deliberately, so page faults are the only one left:

    monkeypatch.setattr(LlamaCppBackend, "_STARTUP_PROGRESS_MIN_CPU_FRACTION", 100.0)
    monkeypatch.setattr(LlamaCppBackend, "_STARTUP_PROGRESS_MIN_BYTES", 1 << 40)

    and the worker forces real I/O rather than reading from page cache:

    os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED)   # evict, every iteration
    with mmap.mmap(fd, 16 << 20, access = mmap.ACCESS_READ, offset = offset) as m:
        sum(m[p] for p in range(0, view, mmap.PAGESIZE))  # 4096 page-ins
    time.sleep(0.05)

    Against _STARTUP_PROGRESS_MIN_PAGE_FAULTS = 64, _STARTUP_PROGRESS_SAMPLE_S patched to 0.1, and timeout = 0.6 in _wait_on_child, with assert elapsed >= 2.5.

    So the assertion is: a child process sustains at least 64 page faults in every 0.6s window, continuously for 2.5 seconds, with the page cache dropped each iteration so every read is disk I/O, on a runner that is concurrently executing 18,747 tests across 4 xdist workers. One 0.6s window where that child is not scheduled, or where its I/O is queued behind three other workers, expires the deadline and the wait returns False. _page_faults counts minflt + majflt, so the count is real, but a process that is not running generates neither.

    That is a wall-clock liveness assertion about a starved process. It is expected to be flaky under parallel load, and it will get flakier as the shard grows. Worth separating from this issue and fixing on its own terms: assert the progress rule (_made_startup_progress) against synthetic samples, which the file already does elsewhere in test_resident_memory_regained_after_eviction_is_not_progress and test_answering_health_probes_is_not_progress, rather than racing a real child.

    The 500s are still unexplained, and this host cannot reach them

    Second round of attempts, after installing the deps that were blocking the shard locally (sqlite-vec, fastmcp), which took the local run from 242 failed / 257 errored to 99 failed / 20 errored against CI's 18,745 passed:

    attempt result
    full l-r shard, CI's exact flags (-n 4 --dist loadgroup --timeout=330) targets pass
    same, repeated targets pass
    test_llama_cpp_wait_for_health.py + test_openai_auto_switch.py in one process 781 passed

    The 99 that still fail here are GPU/CUDA-setup dependent (test_mmproj_placement_policy.py alone is 70 of them), so this host still is not CI. Unchanged conclusion: the 500s need an environment where the whole shard genuinely passes.

    The narrowing from before still stands and is where I would start: the fault is upstream of '_B' object has no attribute 'load_model', which is only the first thing that happens once the withheld branch fails to fire.

  5. danielhanchen commented on Sep 18, 2026

    @danielhanchen
    MemberAuthor

    Progress on the two halves.

    The mmap half is solved: #11284

    Reproduced, fixed, and the fix verified. It was resource contention, and the reason it is the only fragile test in its class is an asymmetry in _made_startup_progress: CPU is compared as MIN_CPU_FRACTION * elapsed and scales with the window, while page faults are compared against a flat MIN_PAGE_FAULTS. Starvation lowers the fault count without lowering the bar, and this is the only test that disables the other two signals so faults are the only one left.

    Worth recording how the reproduction went, because the first attempt was misleading. On this 192-core host, 12 busy loops changed nothing: 6 of 6 passed. Pinning the test and the load to the same 2 CPUs is what reproduces the CI shape:

    taskset -c 0,1, 8 competing busy loops
      before:  2 failures in 12 runs, both `assert ok is True` at line 1719
      after:   10 passes in 10 runs, identical contention
    

    Production is unaffected: _wait_for_health defaults to timeout = 120.0 and it is the test that compresses the window to 0.6s.

    The 500s are NOT contention, and one hypothesis is now eliminated

    Same technique, applied to the withheld tests: 8 of 8 passed pinned to 2 CPUs against 8 busy loops. They are pure logic with no timing, so the original framing of this issue was right for this half. It is state.

    I also tried and disproved the most obvious state candidate, a leaked managed account. _downloaded_model_ids() calls account_access.managed_account() and filters the catalog when one is bound, which would empty downloaded and skip the withheld branch. Forcing exactly that:

    monkeypatch.setattr(account_access, "managed_account", lambda: "someone")
    ->  STATUS: 404
        DETAIL: Model not found

    It changes which 404 is returned, not the status. So a leaked account would fail the message assertion, not produce assert 500 == 404. Not the cause.

    Where I would look next

    A 500 means the route never took a miss path at all and reached _load_model_impl. The module-global state in the auto-switch machinery is the strongest remaining candidate, because none of it is reachable by monkeypatch and all of it survives into the next test in the same xdist worker:

    routes/inference.py:7545  _auto_switch_locks        WeakKeyDictionary keyed by event loop
    routes/inference.py:7564  _auto_switch_process_lock threading.Lock, module-global
    routes/inference.py:7580  _auto_switch_waiters      dict[tuple[str, str], int], module-global
    

    _auto_switch_process_lock is acquired non-blocking in a retry loop at 7574. A test that leaves it held, or leaves _auto_switch_waiters populated, changes what the next request decides to do. Note also that each test creates a fresh event loop via asyncio.run, so every test gets a different key in the loop-keyed WeakKeyDictionary while the two plain module globals are shared by all of them.

    That is where I would start, and it is checkable without reproducing the flake: assert those three are pristine at the end of each test in this file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions