Skip to content

Stub unsloth in test_safetensors_reasoning_stream so it can run first - #9027

Merged
danielhanchen merged 45 commits into
mainfrom
fix-safetensors-reasoning-stub
Aug 17, 2026
Merged

danielhanchen merged 45 commits into
mainfrom
fix-safetensors-reasoning-stub

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 16, 2026 •

Copy link
Copy Markdown
Member

Three tests in studio/backend/tests/test_safetensors_reasoning_stream.py fail on main today if the file runs first, or on its own, against the dependency set Backend CI installs:

core/inference/inference.py:6: from unsloth import FastLanguageModel, FastVisionModel
unsloth/_gpu_init.py:166: raise ImportError(
E   ImportError: Unsloth: Please install unsloth_zoo via `pip install unsloth_zoo` then retry!

Why they pass today

The backend pytest matrix installs studio.txt plus torch and transformers and deliberately stops there. repo-cpu-tests beside it is the job that installs unsloth_zoo, for the repo-root tests/ tree.

So every test file here that reaches a backend module needing unsloth stubs it first, and test_backend_tests_stub_heavy_imports.py exists to enforce exactly that.

This file never stubbed anything. It reaches core.inference.inference through pytest.importorskip inside the test bodies, and the guard treats a function-scope import as lazy and does not inspect it:

# test_backend_tests_stub_heavy_imports.py
# An import inside a function is lazy already, so it is not an offence.
lazy = "def test_x():\n    from core.training.trainer import UnslothTrainer\n"
assert _first_heavy_import_line(ast.parse(lazy), heavy) is None

So the omission was invisible, and the three tests passed only because an earlier file in the same session had installed the stub and left the imported module in sys.modules for them.

importorskip does not paper over it either. pytest 8.2 narrowed it to skip on ModuleNotFoundError only; this is an ImportError raised by unsloth/_gpu_init.py, so it propagates as a failure rather than the intended skip.

Fix

Install the same stub the sibling files install (test_audio_type_inconclusive.py, test_trainer_stdout_quiet.py), at module scope.

Stubbing rather than switching to try/except ImportError + skipif is deliberate: it keeps the coverage. The module under test is still the real core.inference.inference, and only unsloth itself is faked. Converting to a skip would have made the three tests silently stop running on the backend job, which is the opposite of the point.

Verification

Reproduced the CI shape locally by hiding unsloth_zoo's metadata (the runner's condition, since it is genuinely not installed there):

result
before 3 failed, 10 passed
after 13 passed

The guard test still passes alongside it (17 passed for both files together).

Which PR, and which side is wrong

this file, with no stub from the start #5620 (2026-07-06)
the stub guard #8342 (2026-08-10)

Neither is wrong about its own subject and neither is reverted. #5620's tests are correct; they just relied on another file having stubbed unsloth first. #8342's guard exempts imports inside a function deliberately, because those are lazy and cannot fail COLLECTION, which is the disaster it was written for.

The hole is that pytest.importorskip used to make a lazy import safe and no longer does. #8342's exemption was sound when written and stopped being sound under a pytest it did not choose.

Robustification

A second guard beside #8342's, for modules reached through importorskip at any scope, with its own reason stated rather than folded into the collection guard. Against main's version of this file it says:

1 test module(s) reach a backend module that needs unsloth through pytest.importorskip
without installing the stub ... ['test_safetensors_reasoning_stream.py']

It is pinned in both directions (an unstubbed sample is an offence; a stubbed one, and an importorskip of numpy, are not) so it cannot pass by matching nothing.

I also swept the other five files that importorskip a core.* or unsloth* module without stubbing, to check this was not one of many. Under the no-unsloth_zoo condition all five pass, so this file was the only live case:

file result
test_active_generations.py 84 passed
test_bypass_permissions.py 117 passed
test_diffusion_dataset_clips.py 22 passed
test_mlx_inference_backend.py 80 passed, 10 skipped
test_offline_gguf_cache_fallback.py 202 passed
test_safetensors_reasoning_stream.py 3 failed, 10 passed

Found while measuring whether the backend suite can run under pytest-xdist, where splitting the file across workers makes it fail outright. It is not an xdist bug though, which is why it is here on its own: the file is order-dependent on main as it stands.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…d hole

Three tests in this file fail on main if the file runs first, or on its own,
against the dependency set Backend CI installs:

  ImportError: Unsloth: Please install unsloth_zoo via `pip install unsloth_zoo`

Which PR, and which side is wrong:

  #5620 (2026-07-06) added this file, with no stub, from the start
  #8342 (2026-08-10) added the stub guard, which does not look here

Neither is wrong about its own subject, and neither is reverted. #5620's tests
are correct; they just relied on another file having stubbed unsloth first.
#8342's guard exempts imports inside a function on purpose, because those are
lazy and cannot fail COLLECTION, which is the disaster it was written for.

The hole is that pytest.importorskip USED to make a lazy import safe and no
longer does. Since pytest 8.2 it skips on ModuleNotFoundError only, and
unsloth/_gpu_init.py raises a plain ImportError when unsloth_zoo is missing, so
the call fails instead of skipping. #8342's exemption was sound when written and
stopped being sound under a pytest it did not choose.

Fix: install the same stub the sibling files install, at module scope. Stubbing
rather than skipif keeps the coverage: the module under test is still the real
core.inference.inference, and only unsloth is faked. A skipif would have made
three tests silently stop running on the backend job.

Robustification: a second guard beside #8342's, for modules reached through
pytest.importorskip at any scope, with its own reason stated rather than folded
into the collection guard. Verified against main's version of this file:

  1 test module(s) reach a backend module that needs unsloth through
  pytest.importorskip without installing the stub ... ['test_safetensors_reasoning_stream.py']

It is pinned in both directions (an unstubbed sample is an offence, a stubbed one
and an importorskip of numpy are not) so it cannot pass by matching nothing.

I also swept the other five files that importorskip a core.* or unsloth* module
without stubbing. Under the no-unsloth_zoo condition all five pass, so this file
was the only live case:

  test_active_generations            84 passed
  test_bypass_permissions           117 passed
  test_diffusion_dataset_clips       22 passed
  test_mlx_inference_backend         80 passed, 10 skipped
  test_offline_gguf_cache_fallback  202 passed
  test_safetensors_reasoning_stream   3 FAILED, 10 passed

Verified by hiding unsloth_zoo's metadata to reproduce the CI shape:

  before: 3 failed, 10 passed
  after:  13 passed
The first version of this fix installed the unsloth stub and left it in
sys.modules for the rest of the process. Staging CI caught it on all four
interpreters:

  tests/test_audio_type_inconclusive.py:159: in test_the_stubs_do_not_outlive_this_module
      assert name not in sys.modules, name
  E   AssertionError: unsloth

That test exists precisely to forbid what I did. Every other file installs its
stubs, performs its heavy import, then pops them, and a stub left behind is a
cross-file leak: every other _stub_if_missing returns early when the name is
already present, so its own bookkeeping never runs and its cleanup has nothing
to undo.

Traded this file's order dependency for a worse one, in other words.

Now it follows the same shape as test_audio_type_inconclusive.py: stub, build
core.inference.inference while the stubs are live, drop the stubs. The three
tests reach the module through pytest.importorskip and get it from sys.modules,
so the stubs only need to exist for that one import.

It did not reproduce locally, which is why it reached staging: run the file
alone and the victim's own _STUBBED list is empty, so its loop asserts nothing
and passes vacuously. It takes xdist interleaving the two files on one worker
to put the leak in front of that assertion.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Both reported on the guard added by this PR, both confirmed by construction
against the guard's own helpers.

1. The bare-name form was invisible. "from pytest import importorskip" then a
   bare importorskip("core.inference.inference") is a call on an ast.Name, not
   an attribute, so matching only pytest.importorskip returned no targets:

     bare-name form detected as target: []

   Both call shapes are matched now.

2. A module-scope call was judged by the wrong boundary. The check scanned the
   whole module for a stub, so a file that calls importorskip at module scope
   and installs its stub BELOW that line read as safe:

     late-stub form judged stubbed (scanning whole module): True

   while the call runs during collection and the import has already raised. The
   boundary is now the call's own line at module scope, and the end of the
   module only inside a def, where the call really does run after the body.

The pinning test covers all four shapes and both boundaries, so neither hole
can reopen silently. The guard still names the file this PR fixes when run
against main's version of it.
@danielhanchen
danielhanchen force-pushed the fix-safetensors-reasoning-stub branch from 5f2abf6 to 7025b60 Compare August 17, 2026 02:02
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two more gaps on the guard this PR adds, both verified against its own helpers
before changing anything.

1. Definition-time calls were given the wrong boundary. _runtime_nodes stops at
   every def and class, so a call in a class body, a decorator, an annotation or
   a default expression was treated as lazy and got the end-of-module boundary:

     class body, stub below    calls=[('core.inference.inference', 5)] judged_safe=True
     default arg, stub below   calls=[('core.inference.inference', 5)] judged_safe=True

   All of those run while the module is being imported. Only a function BODY is
   deferred, so the scope walk now keeps class bodies and definition-time
   expressions and excludes just the body.

   No file in this tree does this today; all five class-level importorskip calls
   are inside methods, which really are lazy. Fixed anyway, because a guard that
   is wrong about when Python runs things is not much of a guard.

2. A lazy call was judged only on whether a stub was ever installed, not on
   whether it was still there. A module that installs the stubs, drops them
   again, and then reaches the heavy module lazily passes that check and still
   raises at test time. This PR's own file is safe only because it imports the
   target eagerly while the stubs are live, and nothing made that a requirement,
   so a copy that omitted the eager import would have read as safe.

   Now: a lazy call is an offence when the module drops its stubs and does not
   import the target itself. A module that keeps its stubs installed is fine
   lazily, which is why the removal is part of the condition rather than the
   eager import alone.

The decision is one function used by both the guard and the test that pins it.
My first version of this test reimplemented the logic instead, and a mutation
that deleted the real rule left it green.

  scope walk narrowed back to _runtime_nodes  -> 1 failed
  eager-import rule deleted                   -> 1 failed
  stub-removal condition dropped              -> 1 failed
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Reported on this PR and correct. The guard asked "were the stubs dropped again,
and was the target never imported eagerly" only in the lazy branch, so a module
that installs the stub, pops it, and then calls importorskip at module scope
satisfied the install check and read as safe, while collection still dies: the
stub is gone by the time the call runs and nothing put the target in sys.modules.

Both questions now take the same boundary as the install check. _drops_stubs and
_eagerly_imports stop at that line, so an import-time call is judged on the pops
and imports ABOVE it and a lazy call on the whole module body, which is what the
old lazy-only branch computed. Three cases pinned: stub-pop-call is an offence,
stub-call-pop is not, and stub-import-pop-call is not.

Mutating the branch back to the lazy-only form fails the new pin.
6 passed.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 17, 2026 03:27
All four reported on this PR, all four real, each pinned and each verified by
reverting the fix and watching the pin fail.

1. An eager import only counts if the stubs were live for it. A file that probes
   the target in try/except ImportError before installing the stubs, then stubs,
   pops, and calls importorskip lazily, was read as safe. On the dependency-light
   matrix that probe fails and Python removes the half-initialised module, so the
   later call still reaches the real dependency. The check now asks _stubs_before
   for the statement's own line, so there is one answer to "are the stubs live"
   in this file rather than two that can drift.

2. A drop has to be OUR stubs being dropped. Any x.modules.pop counted, so an
   unrelated sys.modules.pop("routes.foo", None) in a properly stubbed file got
   that file reported as an offender, and a pop on any object with a .modules
   counted as well. The receiver must now be sys.modules and the statement must
   name the required stub the same way an install does, directly or through a
   module-level list it reads, which is how the real files spell it.

3. importorskip(modname = "...") is the documented signature
   (modname, minversion=None, reason=None, *, exc_type=None), and node.args is
   empty for it, so a file written that way walked straight past the guard. The
   keyword is read now.

4. exc_type=ImportError is pytest's own opt-in to skipping on a plain
   ImportError, which is the exact failure this guard is about, so such a call is
   safe unstubbed and flagging it was a false report. Those calls are excluded.
   exc_type=ModuleNotFoundError is the default and stays flagged. Confirmed
   against the pytest reference: exc_type arrived in 8.2, "must be ImportError or
   a subclass", and defaults to ModuleNotFoundError.

  6 passed, and reverting each of the four in turn: 1 failed each time
  test_safetensors_reasoning_stream.py + the guard together: 19 passed
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Three more exemptions that were granted on shape rather than effect.

A handler naming ImportError does not necessarily absorb it: 'except ImportError:
raise', and one raising a replacement, both take collection down while the try
body read as guarded, which hid the import from the guard entirely. Any raise the
handler can reach disqualifies it now. A module-level pytest.skip is a call rather
than a raise, so the skip idiom these files use stays exempt.

A helper that can return before installing has not installed anything, so the scan
stops at an exit rather than reading on to the call below it. Two exits are benign
and both are already in the tree: a return under 'name in sys.modules', and one
under the importlib probe inside an absorbing try. On each of those paths the
module is AVAILABLE, so skipping the stub is the point of the branch. Without that
distinction five correct files became offenders, which is how the shape of the
exemption was found.

And a call was treated as installing a stub because its name contained 'stub',
which counted _remove_stub and _validate_stub. Where the module defines the
callee, what it does decides. The name stays as the fallback for a helper imported
from elsewhere, since a name defined nowhere would raise NameError at import and
never reach collection.

Nine pins, four mutation-checked behaviours.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Python dispatches an exception to the FIRST handler that matches it, so 'except
Exception: raise' followed by 'except ImportError: pass' still propagates. Asking
whether ANY handler absorbs found the second one and exempted a try that does not
guard the import. Only the first handler that would catch it is asked now.

The re-raise check also descended into a def the handler merely DEFINES. That body
does not run while the exception is being handled, so a properly guarded file was
reported as an offender. The traversal stops at deferred bodies now.

And the call-graph closure walked past an unconditional exit, handing a helper
named below one the outer call's import-time boundary although it never ran, which
rejected a stub installed below that call. It stops at such an exit now, checked
AFTER the statement since 'return _inner()' runs its own expression, and only for
an unconditional one: the path that skips a conditional exit still reaches the
calls below it.

Five pins, three mutation-checked behaviours.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… code

Two enclosing functions can each define a helper of the same name. Keeping only
the first dropped the second from the call graph, so its importorskip took the
end-of-module boundary and a stub installed after the enclosing call read as being
in time. All definitions of a name are kept now. Which one a given call names
cannot be told apart here, so all of them take the boundary, which is the strict
answer.

And the general reachability walk did not stop at an unconditional exit, so an
importorskip written after a bare return or raise was reported as an unstubbed
offence. Python cannot execute it, so that is a file failing CI over dead code.
The walk now ends a statement list at a return, raise, break or continue, which
the import-time traversal beside it already did.

Four pins, both mutation-checked.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Separate branches can each import a heavy module, and only one of them needs to be
stubbed for the first to look fine. A file that stubs before the import in the if
and forgets the one in the else dies at collection whenever the else runs, while
reducing the module to a single line reported it safe.

Every import-time heavy import is collected now and each is judged against the
stubs that precede it on its own path. Any single unstubbed one is an offence,
whatever the others do.

Two pins, mutation-checked.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…tallers

The already-imported exemption fired on any sys.modules membership test, so
'if "pytest" not in sys.modules:' decided whether the stubs under it counted.
An unrelated cached package says nothing about unsloth, and the branch is skipped
exactly when that package is present. The key now has to be the required stub or
a heavy backend module. A key this file cannot read gets that latitude only inside
a stub helper deciding about its own argument, which is the idiom
_stub_if_missing opens with, and never at module scope.

And calling an async def builds a coroutine and runs none of its body, so reading
through such a call credited the module with stubs it never installed. Only
synchronous helpers are read through now.

Six pins, three mutation-checked behaviours.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 17, 2026
@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: f58602ebb1

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Thirty-three comments ended in 'Reported on this PR', which says nothing to
anyone reading the file afterwards: once merged there is no this PR. The reasoning
each comment records is what matters and is kept.
@danielhanchen
danielhanchen merged commit 4d1f9c5 into main Aug 17, 2026
33 of 35 checks passed
@danielhanchen
danielhanchen deleted the fix-safetensors-reasoning-stub branch August 17, 2026 09:44
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