Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Condense comments added since the last cleanup: core, CLI and tests (#16111)
Daniel Han2478e74ec78b
diff --git a/tests/conftest.py b/tests/conftest.pyindex f46e8bde06f..41383c8ed68 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -18,12 +18,9 @@ for _up in _iso.parents:_spec.loader.exec_module(_mod) # sets the env vars on importbreak-# --- one CPU share per xdist worker ------------------------------------------------# Also before torch is imported. Each xdist worker otherwise starts a torch / OpenMP pool-# as wide as the machine, so `-n 4` on a 4 vCPU runner runs 16 spinning threads on 4 cores-# and CPU training tests slow down by an order of magnitude: test_decision_model's Clef-# training took >330 s there against ~50 s alone. An explicit thread setting is kept.-# Loaded by path: tests/_shared is put on sys.path only below.+# One CPU share per xdist worker, set before torch is imported: otherwise each worker starts a+# torch/OpenMP pool as wide as the machine, slowing CPU training tests; an explicit thread setting+# is kept; loaded by path because tests/_shared is only put on sys.path below.import os as _os # noqa: E402# The suite predates the CPU training backend: a GPU-less runner must keep refusing `import unsloth`@@ -154,9 +151,8 @@ def _preload_device_type(package: str, prereqs: tuple[str, ...] = ()) -> bool:def _patch_torch_cuda_for_import() -> None:- """Stub the torch.cuda.* probes fired at import time once DEVICE_TYPE is- forced to "cuda"; returning plausible Ampere values lets the import finish- (real-tensor tests still run on CPU)."""+ """Stubs the torch.cuda.* probes that fire at import once DEVICE_TYPE is forced to cuda,+ returning plausible Ampere values so the import finishes; real-tensor tests still run on CPU."""try:import torch.cuda.memory as _cuda_memory # type: ignorediff --git a/tests/fast_inference/test_fast_inference.py b/tests/fast_inference/test_fast_inference.pyindex 9a48bfa9702..1c9e4fe2941 100644--- a/tests/fast_inference/test_fast_inference.py+++ b/tests/fast_inference/test_fast_inference.py@@ -50,9 +50,8 @@ PROMPTS = [def length_reward_func(completions, **kwargs) -> list[float]:- """Reward longer completions. The fractional tie-break keeps rewards distinct- even if the model samples equal-length completions, so GRPO advantages are- never all-zero and the step stays meaningful on any vLLM/GPU combination."""+ """Rewards longer completions; the fractional tie-break keeps rewards distinct even for+ equal-length samples, so GRPO advantages are never all-zero on any vLLM/GPU setup."""n = len(completions)return [float(len(c[0]["content"])) + i / (n + 1) for i, c in enumerate(completions)]diff --git a/tests/kaggle/studio_gpu/run_studio_gpu.py b/tests/kaggle/studio_gpu/run_studio_gpu.pyindex bde4fd6d063..066889104de 100644--- a/tests/kaggle/studio_gpu/run_studio_gpu.py+++ b/tests/kaggle/studio_gpu/run_studio_gpu.py@@ -2334,9 +2334,8 @@ class Payload:failures: list[str] = []detail: dict = {"driver": str(driver)}- # Re-seed: the UI driver needs the forced password change pending, which the API- # already completed.- # start_server() removes $STUDIO_HOME/auth, re-seeding the bootstrap password.+ # Re-seed: the UI driver needs the forced password change pending, which the API already+ # completed; start_server() removes $STUDIO_HOME/auth, re-seeding the bootstrap password.self.stop_server()if not self.start_server():failures.append("Unsloth did not come back after the restart that re-seeds the account")diff --git a/tests/kaggle/test_directive_leg_set.py b/tests/kaggle/test_directive_leg_set.pyindex edfa3498f3b..e138432a044 100644--- a/tests/kaggle/test_directive_leg_set.py+++ b/tests/kaggle/test_directive_leg_set.py@@ -63,9 +63,8 @@ def test_the_expensive_exports_stay_off():def test_at_least_one_wired_leg_still_exports():- """The rule above must not be satisfiable by removing every export. Read- off KERNELS, not off the list here, so dropping the exporting leg from the- wired set fails too."""+ """The rule above must not pass by removing every export, so this reads KERNELS rather than a+ local list; dropping the exporting leg from the wired set fails too."""wired = {name for kernel in legs.KERNELS for name in kernel}exporting = [n for n in wired if "--export-gguf" in legs.LEGS[n].args]assert exporting, (@@ -75,9 +74,8 @@ def test_at_least_one_wired_leg_still_exports():def test_the_grpo_leg_keeps_the_settings_it_was_measured_with():- """0.95 utilisation and sleep mode were asked for and both were measured- passing on Kaggle AND Colab; the flashinfer uninstall stays because- removing it broke the leg. None of the three is a default."""+ """0.95 gpu memory utilisation and sleep mode were measured passing on Kaggle and Colab; the+ flashinfer uninstall stays because removing it broke the leg; none is a default."""grpo = legs.LEGS["grpo"]args = grpo.argsassert "--gpu-memory-utilization" in argsdiff --git a/tests/kaggle/test_fire_and_forget.py b/tests/kaggle/test_fire_and_forget.pyindex 26745f527da..963813d655e 100644--- a/tests/kaggle/test_fire_and_forget.py+++ b/tests/kaggle/test_fire_and_forget.py@@ -80,9 +80,8 @@ def test_the_slug_carries_the_commit_and_the_workflow():def test_the_slug_carries_twelve_hex_characters_and_still_reads_eight():- """Two commits can share eight characters, and the commits API 422s the- ambiguous prefix on every pass, so the status stays pending forever. Twelve- is written; eight is still read, since old kernels outlive the change."""+ """Two commits can share eight characters and the commits API 422s the ambiguous prefix every+ pass, leaving status pending forever; twelve is written, eight is still read for old kernels."""assert launch.SLUG_SHA_LEN == 12name = launch.slug_name("studio", "a" * 40)assert launch.parse_slug(name)["sha"] == "a" * 12@@ -194,9 +193,8 @@ def test_the_gate_still_recognises_a_dispatched_kernel_as_ours():),)def test_a_kernel_that_is_not_ours_is_invisible(foreign):- """The collector enumerates a whole ACCOUNT shared with a human and DELETES- what it collects, so there is deliberately no heuristic: a false positive- deletes somebody's work and looks exactly like a kernel that finished."""+ """The collector enumerates an account shared with a human and deletes what it collects, so+ there is deliberately no heuristic; a false positive deletes someone's work."""assert launch.parse_slug(foreign) is None, f"{foreign!r} was accepted as one of ours"@@ -224,9 +222,8 @@ def test_dispatch_without_a_commit_is_a_usage_error(monkeypatch, capsys):def test_dispatch_does_not_delete_the_kernel_it_pushed():- """The whole point: the kernel is LEFT RUNNING, through the existing- --keep-kernel flag rather than a second condition in release(). Two guards- on one deletion is how one ends up wrong, and this one bills GPU quota."""+ """Dispatch leaves the kernel running via the existing --keep-kernel flag, not a second guard in+ release(), since two guards on one deletion can go wrong and the kernel bills GPU quota."""src = (CI_DIR / "launch.py").read_text(encoding = "utf-8")assert re.search(r"if args\.dispatch:\s*\n\s*args\.keep_kernel = True", src), ("dispatch mode must set keep_kernel, or release() deletes the kernel it "@@ -244,9 +241,8 @@ def test_dispatch_does_not_report_pass():def test_the_dispatch_worst_case_excludes_the_phases_it_never_runs():- """Otherwise the pre-push guard demands two hours of job deadline for a job- that exits in five minutes, and stands runs down for a window they do not- need -- the opposite of what dispatch mode is for."""+ """Otherwise the pre-push guard demands two hours of job deadline for a job that exits in five+ minutes and stands runs down for a window they do not need."""full = launch.worst_case_seconds(5400, 1)quick = launch.worst_case_seconds(5400, 1, dispatch = True)assert quick < full, (quick, full)@@ -439,9 +435,8 @@ def test_a_failed_payload_reaches_github_as_a_failure():def test_the_collector_never_sees_a_github_token():- """A script holding both a Kaggle and a GitHub credential is one bug away- from sending one to the other. It emits statuses as DATA; the workflow- posts them."""+ """A script holding both a Kaggle and a GitHub credential is one bug away from sending one to+ the other, so the collector emits statuses as data for the workflow to post."""src = (CI_DIR / "collect.py").read_text(encoding = "utf-8")for forbidden in ("GH_TOKEN", "GITHUB_TOKEN", "api.github.com"):assert forbidden not in src, f"collect.py references {forbidden}"@@ -639,9 +634,8 @@ def test_an_abbreviated_sha_is_EXPANDED_before_a_status_is_posted(monkeypatch):def test_a_commit_that_no_longer_exists_is_reported_not_silently_dropped(monkeypatch, capsys):- """A force-push can remove the commit a running kernel was dispatched for.- Posting is then impossible, but it must SAY so and release the kernel rather- than retry forever."""+ """A force-push can remove the commit a running kernel was dispatched for; posting is then+ impossible, so it must say so and release the kernel rather than retry forever."""calls = _fake_gh(monkeypatch, resolve_to = None)outcome = post_statuses.post_all([dict(_STATUS)], "unslothai/unsloth")assert outcome["unresolved"] == [_STATUS["slug"]] and outcome["failed"] == []@@ -887,9 +881,8 @@ def test_a_malformed_report_line_is_skipped_by_the_extractor(tmp_path):def test_the_expected_report_count_travels_inside_the_kernel(tmp_path, monkeypatch):- """The scheduled collector has no workflow output to read a payload count- from, and judging a five-payload kernel against one turns a run that lost- four into a pass. The driver's own sentinel is the record."""+ """The scheduled collector has no workflow output to read the payload count from, so the count+ travels in the driver's sentinel record; a default of one would pass a run that lost four."""def _fetch(slug,@@ -940,9 +933,8 @@ def test_the_scheduled_collector_no_longer_guesses_the_payload_count():def test_a_kernel_far_past_the_ceiling_is_still_seen(monkeypatch):- """A pass delayed six hours by an outage still finds the wedge it exists- for; ageing it out of the listing leaves it billing with its commit- pending forever."""+ """A pass delayed six hours by an outage must still find a wedged kernel, since ageing it out of+ the listing would leave it billing with its commit pending forever."""from datetime import datetime, timedeltanow = datetime(2026, 9, 6, 12, 0, 0)@@ -1069,9 +1061,8 @@ def test_a_reaped_kernel_is_not_reported_deleted_before_it_is(tmp_path, monkeypadef test_a_malformed_neighbour_notebook_does_not_hide_a_failing_report(tmp_path, monkeypatch):- """One malformed notebook among several used to make the reader raise, and- the collector then judged the kernel infra, posted success and released it.- The failing report in the well-formed neighbour must survive."""+ """A malformed neighbour notebook must not make the reader raise, since that judged the kernel+ infra and posted success; the failing report must survive."""slug = _ENTRY["slug"]dest = tmp_path / slug.rsplit("/", 1)[-1]dest.mkdir()@@ -1189,9 +1180,8 @@ def test_a_client_that_cannot_import_is_not_reported_as_a_bad_token(tmp_path, modef test_dispatch_refuses_a_ref_that_is_not_a_commit(monkeypatch, capsys):- """`slug_name` falls back to the legacy unattributable form for anything not- hex, so a branch here pushes a kernel that runs, bills and reports to- nobody."""+ """slug_name falls back to the legacy unattributable form for anything not hex, so dispatching a+ branch would push a kernel that runs, bills and reports to nobody."""monkeypatch.setattr(sys,"argv",@@ -1251,9 +1241,8 @@ def test_pending_is_posted_only_for_a_kernel_that_was_actually_dispatched(path):def test_a_lookup_that_could_not_be_made_keeps_the_kernel(monkeypatch, capsys):- """Only GitHub saying the commit is not there releases a kernel: a 5xx or a- dropped connection says nothing, and reading it as "gone" deletes the only- copy of the result."""+ """Only GitHub saying the commit is missing releases a kernel; a 5xx or dropped connection says+ nothing, and reading it as gone would delete the only copy of the result."""calls = _fake_gh(monkeypatch, lookup_error = "gh: HTTP 503 Service Unavailable")outcome = post_statuses.post_all([dict(_STATUS)], "unslothai/unsloth")assert outcome["failed"] == [_STATUS["slug"]]@@ -1314,9 +1303,8 @@ def test_an_unrecognised_kernel_state_is_kept_and_not_judged(tmp_path, monkeypatdef test_a_downloaded_file_that_is_not_a_notebook_does_not_wedge_the_collector(tmp_path, monkeypatch):- """`[]` is valid JSON and not a notebook. The expected-count reader used to- raise on it, and a collector that raises writes no result and stalls on the- same kernel every pass."""+ """An empty JSON list is valid JSON but not a notebook; the expected-count reader must not raise+ on it, since a raising collector writes no result and stalls every pass."""slug = _ENTRY["slug"]dest = tmp_path / slug.rsplit("/", 1)[-1]dest.mkdir()@@ -1335,9 +1323,8 @@ def test_a_downloaded_file_that_is_not_a_notebook_does_not_wedge_the_collector(def test_the_evidence_download_is_clamped_to_the_pass_deadline(tmp_path, monkeypatch):- """A kernel started just inside the pass budget must not get a fresh- five-minute download budget, or the collector overruns the job with the- release step still to come."""+ """A kernel started just inside the pass budget must not get a fresh five-minute download+ budget, or the collector overruns the job before the release step."""seen: list[float] = []def _fetch(@@ -1381,9 +1368,8 @@ def test_collection_runs_before_the_recheck_so_the_recheck_is_last_before_the_pu@pytest.mark.parametrize("path", (NOTEBOOK_WF, STUDIO_WF), ids = ("notebook", "studio"))def test_the_unpack_step_reads_the_tree_a_collected_kernel_lands_in(path):- """A collected kernel lands in kaggle_collected/<slug>, so an unpack step- reading only kaggle_evidence never fires on the run that retrieved the- screenshots."""+ """A collected kernel lands in kaggle_collected/<slug>, so the unpack step must read that tree+ as well as kaggle_evidence or it never fires for collected screenshots."""step = next(s for _j, n, s in _steps(_wf(path)) if n == "Unpack the Playwright evidence")assert "kaggle_collected/**/*_output.ipynb" in step["if"]assert "kaggle_evidence/**/*_output.ipynb" in step["if"]@@ -1494,9 +1480,8 @@ def test_two_commits_that_merely_share_eight_characters_post_two_statuses():def test_the_release_phase_stops_at_its_budget_and_keeps_the_rest(tmp_path, monkeypatch):- """delete_kernel allows three 180-second attempts per kernel, so an- unbounded release could outlive the job and be killed mid-delete. What is- left over is released by the next pass."""+ """delete_kernel allows three 180-second attempts per kernel, so an unbounded release could+ outlive the job; what is left over is released by the next pass."""clock = [1000.0]monkeypatch.setattr(collect.time, "time", lambda: clock[0])@@ -1524,17 +1509,15 @@ def test_the_scheduled_collector_timeout_covers_collection_and_release():def test_nothing_tells_the_reader_to_require_a_sampled_context():- """The gate samples and the workflows path-filter, so a commit the gate- skips never gets a status, and a required context that never arrives blocks- the merge."""+ """The gate samples and the workflows path-filter, so a skipped commit never gets a status and a+ required context that never arrives blocks the merge."""for path in (NOTEBOOK_WF, STUDIO_WF, COLLECT_WF, CI_DIR / "launch.py", CI_DIR / "collect.py"):assert "branch protection must require" not in path.read_text(encoding = "utf-8"), pathdef test_a_delete_is_clamped_to_the_deadline_it_is_handed(monkeypatch):- """Checked only before the call, the deadline did not bound the release:- two deletes of three 180-second attempts outlive a 600-second budget. Every- attempt is clamped to what is left and none starts past it."""+ """The deadline must bound each attempt, not just the call: two deletes of three 180-second+ attempts outlive a 600-second budget, so every attempt is clamped to what is left."""clock = [1000.0]timeouts: list[float] = []@@ -1664,9 +1647,8 @@ def test_two_commits_that_share_eight_characters_resolve_apart_and_post_twice(modef test_a_notebook_kernel_without_its_expected_count_is_never_a_pass(tmp_path, monkeypatch):- """A notebook kernel predating the expected-count record could have lost- four legs and reported one, which against a default of one read as a pass.- With the plan unknown a failure still fails, but a clean set is infra."""+ """A notebook kernel without its expected-count record could have lost four legs yet reported+ one, which a default of one reads as a pass; a clean set must be infra, failures still fail."""monkeypatch.setattr(launch, "fetch_evidence", lambda slug, dest, deadline = None: {})monkeypatch.setattr(launch, "delete_kernel", lambda slug, deadline = None: True)api = _StubApi([], {_ENTRY["slug"]: "COMPLETE"})diff --git a/tests/kaggle/test_gptoss_completions_and_gguf.py b/tests/kaggle/test_gptoss_completions_and_gguf.pyindex 5209c8089f7..abf2c03646a 100644--- a/tests/kaggle/test_gptoss_completions_and_gguf.py+++ b/tests/kaggle/test_gptoss_completions_and_gguf.py@@ -45,9 +45,8 @@ def test_the_rule_is_inert_when_completions_only_was_not_requested():def test_the_leg_asks_for_completions_and_for_mxfp4():- """Asserted through the REGISTRY, because a payload flag nobody passes is- coverage that does nothing. The default is on, so the check is that the leg- does not turn it off."""+ """Asserted through the registry, since a payload flag nobody passes is coverage that does+ nothing; the default is on, so the leg must not pass --no-train-on-completions."""from kaggle_t4_ci.legs import LEGSleg = LEGS["gptoss"]@@ -231,9 +230,8 @@ def test_the_text_leg_exports_once_per_leg_and_not_once_per_cycle():def test_skipping_every_cycle_is_still_a_failure():- """The saving must not be able to become missing coverage. A leg that asked- for an export and produced no file anywhere has to say so, and a per-cycle- excuse that fires on cycle 0 too would be silent."""+ """Skipping the GGUF export per cycle must not become missing coverage: a leg that asked for an+ export and produced no file must fail, and the excuse must not fire on cycle 0."""src = (PAYLOAD / "run_t4_smoke.py").read_text(encoding = "utf-8")assert "every cycle skipped the GGUF export" in srcassert (diff --git a/tests/kaggle/test_grpo_nightly.py b/tests/kaggle/test_grpo_nightly.pyindex 8afeb08cc7b..7e094a2108b 100644--- a/tests/kaggle/test_grpo_nightly.py+++ b/tests/kaggle/test_grpo_nightly.py@@ -85,9 +85,8 @@ def test_every_leg_the_nightly_names_exists():def test_the_nightly_set_fits_in_one_kernel():- """`--legs` builds ONE kernel, and MAX_LEGS_PER_KERNEL is what the driver's- scheduling was measured against. A list longer than that silently packs a- kernel nobody has run."""+ """--legs builds one kernel, and MAX_LEGS_PER_KERNEL is what the driver's scheduling was+ measured against; a longer list silently packs a kernel nobody has run."""assert len(_nightly_legs()) <= legs.MAX_LEGS_PER_KERNEL@@ -102,9 +101,8 @@ def test_no_nightly_leg_is_ALSO_in_the_per_pr_set():def test_a_leg_list_replaces_all_kernels_rather_than_filtering_after_it():- """``--all-kernels`` derives BOTH the kernel plan and the payload count the- launcher waits on. A filter applied afterwards leaves it expecting payloads- that were never built, which times out rather than failing."""+ """--all-kernels derives both the kernel plan and the payload count the launcher waits on; a+ filter applied afterwards leaves it expecting payloads never built, which times out."""assert 'KERNEL_SELECT="--legs $LEG_LIST"' in TEXTassert 'KERNEL_SELECT="--all-kernels"' in TEXTassert "$KERNEL_SELECT \\" in TEXT@@ -241,9 +239,8 @@ def test_the_per_pr_command_line_is_one_the_builder_accepts(tmp_path):def test_studio_rides_the_wired_set_and_only_the_wired_set(tmp_path):- """The pair that was mutually exclusive, asserted in BOTH directions:- dropping Studio from the nightly is only a fix if the per-PR kernel still- carries it, else the payload is covered by nothing."""+ """Studio and the leg list were mutually exclusive, so this asserts both directions: dropping+ Studio from the nightly is only a fix if the per-PR kernel still carries it."""nightly, _, _ = _compose_argv("schedule", tmp_path)assert "--with-studio" not in nightly, ("the nightly still asks for Studio alongside a leg list, which "@@ -257,9 +254,8 @@ def test_studio_rides_the_wired_set_and_only_the_wired_set(tmp_path):def test_studio_concurrent_still_reaches_the_builder_on_the_per_pr_run(tmp_path):- """The flag moved inside the Studio branch. One that stops being passed is- the failure run 32674263571 shipped: the variant of an A/B ran the- control's schedule and nothing was red."""+ """The --studio-concurrent flag moved inside the Studio branch; if it stops being passed, the+ A/B variant runs the control's schedule and nothing turns red, as in run 32674263571."""argv, _, _ = _compose_argv("push", tmp_path)assert "--studio-concurrent" in argv, ("the default per-PR build no longer shares a card, so Studio waits for "diff --git a/tests/kaggle/test_harness_dependencies.py b/tests/kaggle/test_harness_dependencies.pyindex ab3a2fe5368..ad41f6d0609 100644--- a/tests/kaggle/test_harness_dependencies.py+++ b/tests/kaggle/test_harness_dependencies.py@@ -94,9 +94,8 @@ def test_every_unguarded_import_is_installed_by_the_workflow():def test_the_import_scan_finds_something_at_all():- """A scan that silently matched nothing would satisfy the rule above- forever. Two modules the suite genuinely imports are named here, so a- refactor that breaks the walk fails rather than passes."""+ """A scan that silently matches nothing would pass the rule above forever, so the test asserts+ known imports (datasets, torch) are found and a broken walk fails."""found = _imported_third_party()assert "datasets" in found, "the walk no longer sees the vision dataset imports"assert "torch" in founddiff --git a/tests/kaggle/test_kernel_provenance.py b/tests/kaggle/test_kernel_provenance.pyindex 06e8d885555..b01439ae2c2 100644--- a/tests/kaggle/test_kernel_provenance.py+++ b/tests/kaggle/test_kernel_provenance.py@@ -51,9 +51,8 @@ def test_fla_missing_is_a_failure():def test_flash_attention_2_on_turing_is_a_failure():- """The regression that matters. FA2 cannot execute on sm_75, so a stack that- selects it fails at the first forward, and a leg that did not check would- report that as an unexplained crash."""+ """FA2 cannot execute on sm_75, so a stack that selects it fails at the first forward; the check+ must flag it, not report an unexplained crash."""broken = vision_kernel_failures({"fla": VENDORED}, {"config": "flash_attention_2"}, capability = "7.5")@@ -75,9 +74,8 @@ def test_a_missing_attention_record_is_a_failure_not_a_silence():def test_causal_conv1d_absence_is_reported_and_not_asserted():- """Measured absent on this path. The wheel-first machinery in ssm_runtime.py- belongs to Studio's training worker, which the notebook path never calls, so- an assertion here would go red on correct behaviour."""+ """causal_conv1d and mamba_ssm are absent on the notebook path, where ssm_runtime.py's+ wheel-first code never runs, so absence is reported rather than asserted."""kernels = {"fla": VENDORED,"causal_conv1d": {"importable": False, "error": "ModuleNotFoundError"},diff --git a/tests/kaggle/test_known_upstream_breakage.py b/tests/kaggle/test_known_upstream_breakage.pyindex 458f8de85bd..7ba93dd65f4 100644--- a/tests/kaggle/test_known_upstream_breakage.py+++ b/tests/kaggle/test_known_upstream_breakage.py@@ -46,9 +46,8 @@ def test_a_listed_model_does_not_fail_on_the_known_disagreement():def test_a_listed_model_that_starts_AGREEING_fails():- """The strict half, and the reason this is not a mute. Agreement in bf16- means a kernel or the stack changed, and CI says so instead of carrying a- stale expectation."""+ """A listed model that starts agreeing in bf16 means a kernel or the stack changed, so CI must+ fail and say to delete the entry rather than carry a stale expectation."""agreeing = _record(agrees = {"2": True, "4": True, "8": True})broken = batched_generation_failures(agreeing, "unsloth/Qwen3.5-2B")assert broken, "a fixed upstream bug must turn the leg red"@@ -56,9 +55,8 @@ def test_a_listed_model_that_starts_AGREEING_fails():def test_a_listed_model_still_fails_every_other_rule():- """The entry excuses ONE claim. A right-padded batch, an unpadded batch or- an empty output is still a failure, and those are exactly what make the- disagreement meaningful rather than an artefact."""+ """A listed model excuses only the batched-generation disagreement; right-padded, unpadded or+ empty-output batches still fail, keeping that disagreement meaningful."""for over, expect in (({"padding_side_after": "right"}, "padding_side_after"),({"distinct_lengths": 1}, "nothing was ever padded"),diff --git a/tests/kaggle/test_multi_gpu_leg.py b/tests/kaggle/test_multi_gpu_leg.pyindex d0495c9e205..ea0adfe84b8 100644--- a/tests/kaggle/test_multi_gpu_leg.py+++ b/tests/kaggle/test_multi_gpu_leg.py@@ -56,9 +56,8 @@ def test_the_nullcontext_shim_is_the_failure_this_leg_exists_for():def test_one_visible_card_fails_and_says_only_that():- """A pinned run measures the wrong machine, so every rule after the count- is noise. Reporting eight failures about arrays that are correctly sized- for the one card the leg was given sends the reader after the wrong bug."""+ """A pinned run measures the wrong machine, so with one visible card only the count failure is+ reported; later rules would flag arrays sized correctly for that card."""facts = dict(GOOD,device_count = 1,@@ -75,9 +74,8 @@ def test_one_visible_card_fails_and_says_only_that():def test_an_import_before_the_cards_were_visible_is_caught_separately():- """torch can see two cards while unsloth.kernels.utils was imported when- only one was visible -- the bindings are made once, at import. The two are- different failures with different fixes, so they are reported separately."""+ """unsloth.kernels.utils binds its devices once at import, so importing it before both cards+ were visible is a separate failure with its own fix, reported apart."""facts = dict(GOOD, module_device_count = 1)broken = _payload().multi_gpu_failures(facts, expected_cards = 2)assert broken and "imported before the cards were visible" in broken[0]@@ -94,9 +92,8 @@ def test_short_stream_and_buffer_arrays_each_fail():def test_missing_facts_are_a_failure_rather_than_a_silence():- """A cycle that never ran the reading reports null, and null must not read- as "nothing wrong". This is the shape that let a payload be carried and- never executed for two rounds."""+ """A null or empty multi-GPU reading must be a failure, not silence; that gap once let a payload+ be carried without ever executing."""payload = _payload()assert payload.multi_gpu_failures(None, expected_cards = 2)assert payload.multi_gpu_failures({}, expected_cards = 2)@@ -141,9 +138,8 @@ def test_the_reading_is_taken_from_the_module_and_not_recomputed():def test_the_leg_asks_for_two_cards_and_the_BUILT_payload_enforces_it():- """Asserted through the generated notebook, not off the dataclass. A field- nothing emits reads like coverage and does nothing -- which is exactly how- a payload was carried and never run for two rounds."""+ """Assert against the generated notebook, not the dataclass field, because a field nothing emits+ looks like coverage and enforces nothing."""leg = legs.LEGS["multi_gpu"]assert leg.all_cards is Truenotebook = build_kernel.build_payload_notebook(@@ -172,9 +168,8 @@ def test_every_OTHER_leg_still_requires_exactly_one():def test_the_leg_is_small_enough_to_co_tenant():- """The whole cost argument. At a whole card this leg would block gptoss- (12.78 of the 13.0 budget) for its entire life and the kernel would get- longer, which is the one thing this was built not to do."""+ """The leg must stay small enough to co-tenant: at a whole card it would block gptoss for its+ whole life (12.78 of the 13.0 budget in CARD_VRAM_BUDGET_GB) and lengthen the kernel."""leg = legs.LEGS["multi_gpu"]budget = 13.0 # CARD_VRAM_BUDGET_GB in build_kernel.py@@ -254,9 +249,8 @@ def test_it_runs_UNPINNED_or_it_measures_the_single_card_branch():def test_the_reservation_is_all_or_nothing():- """A partial reservation holds a seat on card 0 while waiting for card 1 --- capacity nothing is using, and a deadlock against a big leg waiting for- card 0. The refusal path must not have mutated anything."""+ """A partial reservation can hold card 0 while waiting for card 1, leaving capacity unused and+ deadlocking a big leg that waits for card 0; checks must all run before any card is charged."""source = _driver_source()body = source.split("def _admit_all(name):")[1].split("def _release_all")[0]check, commit = body.split("for g in range(N_GPU):")[1:3]diff --git a/tests/kaggle/test_phase_timers.py b/tests/kaggle/test_phase_timers.pyindex 7ce81148ae8..59f6317c76b 100644--- a/tests/kaggle/test_phase_timers.py+++ b/tests/kaggle/test_phase_timers.py@@ -30,9 +30,8 @@ def hub(monkeypatch):def test_an_unattached_timer_reports_none_not_zero(monkeypatch):- """The finding this whole file exists for. With nothing patched, `seconds`- must be None: a report showing 0.0 is indistinguishable from a warm cache,- and one of those is a measurement while the other is a broken instrument."""+ """An unattached timer must report seconds as None, not 0.0, since 0.0 looks identical to a warm+ cache and would hide a broken instrument."""monkeypatch.setitem(sys.modules, "huggingface_hub", types.ModuleType("huggingface_hub"))monkeypatch.delitem(sys.modules, "transformers.utils.hub", raising = False)timer = FetchTimer().install()diff --git a/tests/kaggle/test_prefetch_covers_the_wired_legs.py b/tests/kaggle/test_prefetch_covers_the_wired_legs.pyindex f3a8f09b865..03040706807 100644--- a/tests/kaggle/test_prefetch_covers_the_wired_legs.py+++ b/tests/kaggle/test_prefetch_covers_the_wired_legs.py@@ -51,9 +51,8 @@ def test_every_wired_leg_loads_a_prefetched_checkpoint():def test_the_model_walk_reads_the_payload_default_and_not_only_the_args():- """Three of the five wired legs carry no --model at all. A rule that read- the args alone would report them as having no checkpoint and pass by- finding nothing, which is the shape of a guard that guards nothing."""+ """Three of the five wired legs pass no --model, so the walk must read the payload default too;+ reading only the args would pass by finding nothing."""assert models_for(legs.LEGS["canary"]) == {"unsloth/Qwen2.5-0.5B-Instruct"}assert "unsloth/gpt-oss-20b-unsloth-bnb-4bit" in models_for(legs.LEGS["gptoss"]), ("the gpt-oss redirect is not being applied, so the prefetch would warm "diff --git a/tests/kaggle/test_studio_api_key.py b/tests/kaggle/test_studio_api_key.pyindex 04436b884eb..854dc5bfcf0 100644--- a/tests/kaggle/test_studio_api_key.py+++ b/tests/kaggle/test_studio_api_key.py@@ -69,9 +69,8 @@ def test_the_raw_key_is_registered_as_a_secret_before_it_is_used():def test_the_session_token_is_restored_even_when_the_call_raises():- """A finally, not a trailing statement: an exception mid-check would- otherwise leave the session authenticated as a corrupted API key and every- later assertion would fail for the wrong reason."""+ """The token restore must sit in a finally: an exception mid-check would otherwise leave the+ session authenticated as a corrupted key and fail later assertions."""tree = ast.parse(_assert_api_key_body())tries = [n for n in ast.walk(tree) if isinstance(n, ast.Try) and n.finalbody]restores = [diff --git a/tests/kaggle/test_studio_cli_run.py b/tests/kaggle/test_studio_cli_run.pyindex b7dc291ba78..50d0b79cf57 100644--- a/tests/kaggle/test_studio_cli_run.py+++ b/tests/kaggle/test_studio_cli_run.py@@ -47,9 +47,8 @@ def test_it_uses_its_own_port():def test_no_public_url_is_ever_opened_from_ci():- """--secure implies a Cloudflare quick tunnel, which publishes this server- to the internet from a CI kernel. --no-cloudflare is explicit rather than- relying on the default, because a default is a thing that changes."""+ """--secure implies a Cloudflare quick tunnel that publishes the server to the internet from CI,+ so --no-cloudflare is passed explicitly rather than trusting a default."""body = "".join(_body().split()) # formatter-proof; see the cloudflare guardsassert '"--no-cloudflare",' in bodyassert '"--secure"' not in body@@ -62,9 +61,8 @@ def test_the_key_comes_from_the_marker_the_cli_itself_prints():def test_the_key_is_registered_as_a_secret_before_anything_reads_the_log():- """The log is packed into the evidence bundle. `redacted()` is what keeps- the key out of it, and it can only redact a secret it has been told about,- so the registration has to happen at the moment the key is parsed."""+ """The log goes into the evidence bundle and redacted() only redacts secrets it has been told+ about, so the key must be registered where it is parsed."""src = _body()parse_at = src.index('text.split("UNSLOTH_START_API_KEY:"')add_at = src.index("self.secrets.add(api_key)")diff --git a/tests/kaggle/test_studio_cloudflare.py b/tests/kaggle/test_studio_cloudflare.pyindex 71210ed1e46..a8977c7ac2f 100644--- a/tests/kaggle/test_studio_cloudflare.py+++ b/tests/kaggle/test_studio_cloudflare.py@@ -86,9 +86,8 @@ def test_an_unauthenticated_request_through_the_tunnel_must_be_refused():def test_the_no_tunnel_excuse_is_narrow():- """Reported-not-failed applies ONLY when nothing was published, because- then there is nothing to have gone wrong with. Once a URL exists, every- rule above is live."""+ """The no-tunnel excuse, reported rather than failed, applies only when no URL was published;+ once a URL exists, every cloudflare rule above is live."""func = _func("assert_cloudflare")excuses = [n for n in ast.walk(func) if isinstance(n, ast.If) and ast.unparse(n.test) == "url is None"diff --git a/tests/kaggle/test_studio_code_execution.py b/tests/kaggle/test_studio_code_execution.pyindex fa6b70a9bb5..3880b2046ef 100644--- a/tests/kaggle/test_studio_code_execution.py+++ b/tests/kaggle/test_studio_code_execution.py@@ -104,9 +104,8 @@ def test_the_verdict_is_read_off_the_filesystem_and_not_off_the_reply():def test_the_search_reads_content_rather_than_only_a_filename():- """A small local model rewording the path is not a Studio defect. What- cannot be faked is the token's BYTES landing on disk, so the content is- what the search is entitled to rely on."""+ """The search checks file content, not only the filename, since a small model may reword the+ path but the token's bytes cannot be faked on disk."""body = _body()assert "read_text" in bodyassert "token in body" in body@@ -119,8 +118,7 @@ def test_it_looks_under_the_studio_home_sandbox_and_not_a_stray_root():def test_the_cpu_fallback_records_the_assertion_rather_than_omitting_it():- """A skipped assertion that leaves no record is indistinguishable from one- that never existed, and the summary would be short by one line rather than- red."""+ """The CPU fallback must record code_execution explicitly, because a skipped assertion with no+ record is indistinguishable from one that never existed."""run = _body("execute")assert '"code_execution",' in run, "the non-GPU branch must record code_execution explicitly"diff --git a/tests/kaggle/test_studio_compaction.py b/tests/kaggle/test_studio_compaction.pyindex 0f153cc6daa..90916a707a5 100644--- a/tests/kaggle/test_studio_compaction.py+++ b/tests/kaggle/test_studio_compaction.py@@ -171,9 +171,8 @@ def test_the_refusal_is_checked_by_CODE_and_not_by_the_status_alone():def test_the_over_length_conversation_is_sent_twice_under_two_policies():- """One request cannot compare two policies. Both calls have to exist, and- they have to send the SAME messages, or the pair compares a policy against- a different conversation."""+ """One request cannot compare two policies; both calls must exist and send identical messages,+ or the pair compares a policy against a different conversation."""func = _func("assert_compaction")calls = [nodediff --git a/tests/kaggle/test_studio_gpu_harness.py b/tests/kaggle/test_studio_gpu_harness.pyindex b19c6c539f4..32a8773cfd1 100644--- a/tests/kaggle/test_studio_gpu_harness.py+++ b/tests/kaggle/test_studio_gpu_harness.py@@ -181,9 +181,8 @@ def _verdict(**kw):def test_no_evidence_at_all_is_a_failure_and_not_a_pass():- """The asymmetry this whole module exists for. A CPU fallback returns- text just like the GPU path, so an unanswerable question has not been- answered in the affirmative."""+ """No evidence at all must fail, not pass: a CPU fallback returns text just like the GPU path,+ so an unanswerable question was never answered in the affirmative."""verdict = _verdict()assert not verdict["passed"]assert any("no probe could show" in f for f in verdict["failures"])@@ -906,9 +905,8 @@ def test_the_reserve_leaves_ci_the_fifty_hours_it_is_allowed():def test_the_budget_hours_flag_covers_the_reaper_window():- """budget-hours is the worst case one invocation can cost. Nothing waits on- the kernel now, so a kernel that ignores its own timeout is left to the- collector's reaper window rather than to the kernel ceiling."""+ """budget-hours is the worst case one invocation can cost and must cover the collector's reaper+ window, since nothing waits on a kernel that ignores --kernel-timeout-sec."""source = WORKFLOW.read_text(encoding = "utf-8")assert "--kernel-timeout-sec 4200" in sourceceiling_hours = 4200 / 3600@@ -1343,9 +1341,8 @@ def test_a_non_cuda_runtime_line_is_not_a_cuda_install():def test_a_future_cuda_major_is_recognised():- """Matching a fixed set of names fails closed on the next CUDA major,- reporting a working install as not-CUDA -- the same failure this fix is- for. The match is on the runtime line's shape instead."""+ """Match the CUDA runtime line's shape, not a fixed list of names: a fixed set fails closed on+ the next CUDA major and reports a working install as not-CUDA."""module = _load_payload()assert module.is_cuda_install("cuda14")assert module.is_cuda_install("app-bX-linux-x64-cuda99-portable.tar.gz")@@ -1550,9 +1547,8 @@ def test_a_nested_executed_notebook_is_read_too(tmp_path):def test_evidence_that_is_json_but_not_a_notebook_does_not_raise(tmp_path):- """`[]`, a string cell, a numeric output: all valid JSON, all seen back from- a kernel. The reader used to raise on the first `.get`, failing the job- after its verdict was already posted."""+ """Evidence that is valid JSON but not a notebook, such as [], a string cell or a numeric+ output, must not raise, since a raise after the verdict was posted fails the job."""evidence = tmp_path / "evidence" / "unsloth-t4-ci-1234"evidence.mkdir(parents = True)(evidence / "a_output.ipynb").write_text("[]", encoding = "utf-8")@@ -1588,9 +1584,8 @@ def test_the_evidence_unpack_is_best_effort_on_the_gpu_job():def test_a_nan_loss_is_not_a_trained_step():- """A T4 has no bf16, so this trains in fp16, and an fp16 run that diverges- logs NaN for every step while still reaching `completed` and still saving- an adapter. Counting mere list occupancy scored that as a full run."""+ """A T4 has no bf16, so training runs in fp16; a diverged fp16 run logs NaN every step yet still+ completes and saves an adapter, so NaN losses are not trained steps."""status = {"metric_history": {"loss": [float("nan")] * 8}}assert studio_client.trained_steps(status) == 0assert len(studio_client.nonfinite_losses(status)) == 8@@ -1609,9 +1604,8 @@ def test_real_losses_still_count():def test_studio_is_launched_from_the_interpreter_running_the_payload(tmp_path, monkeypatch):- """The payload runs under the Unsloth venv, whose bin is NOT on PATH. A- global `unsloth` anywhere on PATH would otherwise win shutil.which() and- the run would measure some other install instead of the checkout."""+ """Studio must be launched from the interpreter running the payload, since the venv bin is not+ on PATH and a global unsloth on PATH would win shutil.which()."""module = _load_payload()venv_bin = tmp_path / "venv" / "bin"venv_bin.mkdir(parents = True)@@ -1650,9 +1644,8 @@ def test_without_a_console_script_the_same_interpreter_runs_the_module(tmp_path,def test_the_payload_never_reads_a_pid_the_status_response_does_not_declare():- """InferenceStatusResponse declares no llama_server_pid and no pid, and- FastAPI drops what the response model does not declare, so that lookup was- always None and the process-level VRAM probe could never fire."""+ """InferenceStatusResponse declares neither llama_server_pid nor pid, and FastAPI drops+ undeclared fields, so reading them was always None and the process VRAM probe never fired."""import remodel_src = (REPO_ROOT / "studio" / "backend" / "models" / "inference.py").read_text(@@ -1855,9 +1848,8 @@ def test_an_export_that_outlives_its_http_request_is_still_polled(tmp_path, monkdef test_the_capped_bundle_still_carries_the_logs(tmp_path, monkeypatch):- """The fallback used to rebuild with the report ALONE while its message- said it was shipping logs, discarding studio.log and the driver log in- exactly the failing runs that need them."""+ """The size-capped fallback bundle must still carry studio.log and the driver log, not just the+ report, since those logs matter most in failing runs."""module = _load_payload()session = _session(module, tmp_path)session.outdir = tmp_path / "out"@@ -1885,9 +1877,8 @@ def test_the_capped_bundle_still_carries_the_logs(tmp_path, monkeypatch):def test_a_crash_while_packaging_the_evidence_does_not_publish_a_pass(tmp_path, monkeypatch):- """extract_reports keeps the FIRST report per label|model, so printing a- pass and then crashing published the pass and left the correction- unread."""+ """extract_reports keeps the first report per label|model, so a pass printed before a crash+ would be published while the later correction goes unread."""module = _load_payload()session = _session(module,@@ -2137,9 +2128,8 @@ def test_the_opt_in_label_can_actually_start_the_workflow():def test_an_unrelated_label_cannot_start_a_seventy_minute_kaggle_run():- """GitHub has no per-label event filter, so `labeled` fires for every label- added -- and the gate reads the whole label list, so once the opt-in label- sits on the pull request it would call every one of those events forced."""+ """GitHub has no per-label event filter, so labeled fires for every label while the gate reads+ the whole label list; the job if must screen out unrelated labels."""condition = " ".join(_workflow()["jobs"]["gate"]["if"].split())assert "github.event.action != 'labeled'" in conditionassert "github.event.label.name == 'kaggle-studio-gpu-ci'" in condition@@ -2193,9 +2183,8 @@ def test_load_model_does_not_inherit_the_previous_loads_offload_line(tmp_path, mdef test_a_box_without_nvidia_smi_reports_no_gpu_rather_than_crashing(tmp_path, monkeypatch):- """environment() runs inside finish(), on every path including the- preflight one, so a FileNotFoundError there ended the run with a traceback- and no report at all."""+ """environment() runs inside finish() on every path, so a missing nvidia-smi (FileNotFoundError)+ must read as no GPU, not end the run with no report at all."""module = _load_payload()monkeypatch.setenv("PATH", str(tmp_path))assert module.gpu_inventory() == []@@ -2358,9 +2347,8 @@ class TestTheListingNamesItsPids:assert gpu_assert.listed_pids("pid, used_gpu_memory\n\nnotapid, 5\n333, 10\n") == {333}def test_the_sample_is_taken_once(self):- """Two nvidia-smi calls would describe two different moments, so the attributed- mapping and the listed pids could disagree about which processes exist.- """+ """The compute-apps listing is sampled once: two nvidia-smi calls would describe two+ moments, so the attributed mapping and listed pids could disagree."""body = (PAYLOAD_DIR / "run_studio_gpu.py").read_text(encoding = "utf-8")assert body.count("nvidia_compute_apps_listing()") >= 3assert "apps_before = attributed_apps(_listing_before)" in bodydiff --git a/tests/kaggle/test_studio_image_generation.py b/tests/kaggle/test_studio_image_generation.pyindex 651616d3ead..1b084d10958 100644--- a/tests/kaggle/test_studio_image_generation.py+++ b/tests/kaggle/test_studio_image_generation.py@@ -66,9 +66,8 @@ def test_the_size_is_read_from_the_file_and_not_from_the_record():def test_the_ihdr_offsets_are_right():- """Executed against a PNG built here, because an off-by-four in a- fixed-offset parse reads a plausible number out of the wrong bytes and- every other rule still passes."""+ """The IHDR width and height offsets are checked against a PNG built in the test, since an+ off-by-four would read a plausible number and still pass other rules."""blob = _png(256, 256, zlib.compress(b"\x00" * 16))assert int.from_bytes(blob[16:20], "big") == 256assert int.from_bytes(blob[20:24], "big") == 256@@ -78,9 +77,8 @@ def test_the_ihdr_offsets_are_right():def test_a_flat_image_is_a_failure():- """A pipeline whose weights never loaded returns a uniform frame, and a- uniform frame is a valid PNG of exactly the right size. Every other rule- here passes on it."""+ """A pipeline whose weights never loaded returns a uniform frame that is a valid PNG of the+ right size and passes every other rule, so a flat image must fail."""func = _func("assert_image_generation")assert any(isinstance(n, ast.If) and ast.unparse(n.test) == "flat" for n in ast.walk(func)@@ -104,9 +102,8 @@ def test_the_bytes_are_fetched_raw_rather_than_through_the_json_client():def test_the_pipeline_is_unloaded_in_a_finally():- """A diffusion pipeline is the largest single thing this payload puts on a- T4. Left resident, it takes the card from whatever runs next and that- failure lands on the wrong assertion."""+ """The diffusion pipeline is the largest thing the payload puts on a T4; it must be unloaded in+ a finally, or it takes the card from whatever runs next."""func = _func("assert_image_generation")finals = "\n".join(ast.unparse(n) for t in ast.walk(func) if isinstance(t, ast.Try) for n in t.finalbody@@ -151,9 +148,8 @@ def test_the_load_is_WAITED_ON_rather_than_assumed_synchronous():def test_a_load_that_never_finishes_fails_rather_than_generating_anyway():- """The refusal branch. Falling through to `generate` after the deadline- reports a 409 under the generation's name, which sends the reader after the- wrong component -- which is exactly what happened."""+ """The refusal branch: falling through to generate after the deadline reports a 409 under the+ generation's name and sends the reader after the wrong component."""func = _func("assert_image_generation")src = ast.get_source_segment(SRC, func) or ""marker = "never reported loaded within"diff --git a/tests/kaggle/test_studio_password_path.py b/tests/kaggle/test_studio_password_path.pyindex 0fd4d88a4a2..928a5e1f490 100644--- a/tests/kaggle/test_studio_password_path.py+++ b/tests/kaggle/test_studio_password_path.py@@ -22,9 +22,8 @@ def test_login_uses_the_password_that_was_passed():def test_there_is_no_fallback_to_the_bootstrap_password():- """The whole assertion. If --password were ignored, Studio would seed a- bootstrap password instead and the login would fail; a fallback would then- quietly succeed and report a pass for a flag that did nothing."""+ """If --password were ignored, Studio would seed a bootstrap password and login would fail; a+ fallback would quietly pass for a flag that did nothing."""tree = ast.parse(SRC)func = next(node@@ -47,9 +46,8 @@ def test_there_is_no_fallback_to_the_bootstrap_password():def test_the_generated_password_is_registered_as_a_secret_before_use():- """Registered in __init__, which runs before the server starts and before- anything writes a log. Registering it later would scrub the logs written- after that point and not the banner."""+ """Register the generated password in __init__, before the server starts and any log is written;+ registering later would scrub later logs but not the banner."""tree = ast.parse(SRC)init = next(nodediff --git a/tests/kaggle/test_studio_server_flags.py b/tests/kaggle/test_studio_server_flags.pyindex 306713d03ef..0093418b38a 100644--- a/tests/kaggle/test_studio_server_flags.py+++ b/tests/kaggle/test_studio_server_flags.py@@ -94,17 +94,15 @@ def test_the_cache_rules_append_a_failure_on_both_paths():def test_the_context_pin_is_checked_against_the_requested_value():- """llama-server admits a prompt on n_ctx alone, so a server at the model- default behaves differently from one at 2048 and the difference does not- show in a chat response."""+ """llama-server admits prompts on n_ctx alone, so a server at the model default differs from one+ at 2048 without showing in a chat response."""body = _body()assert "int(ctx) > self.args.studio_ctx" in bodydef test_gpu_residency_is_confirmed_after_the_split():- """A tensor_split that fell back to CPU reports a healthy server and proves- nothing about either card. Checked structurally: the threshold comparison- must exist, not merely the message about it."""+ """A tensor_split that fell back to CPU still reports a healthy server and proves nothing about+ either card, so the threshold comparison itself must exist."""tree = ast.parse(_body())compares = [ast.unparse(node) for node in ast.walk(tree) if isinstance(node, ast.Compare)]assert any(@@ -135,9 +133,8 @@ def test_it_is_skipped_rather_than_passed_when_the_model_is_not_on_the_gpu():def test_it_runs_between_gpu_inference_and_training():- """It reloads the chat model with different flags. Earlier would change the- model the inference checks measured; later would put a reload between the- adapter and the export."""+ """Server flags reload the chat model: earlier would change the model that inference measured,+ later would put a reload between the adapter and export."""infer_at = SRC.index("gpu_ok = self.assert_gpu_inference()")flags_at = SRC.index("self.assert_server_flags()")train_at = SRC.index("trained = self.assert_training()")@@ -197,9 +194,8 @@ def test_a_pinned_payload_does_not_see_both_cards(monkeypatch):def test_an_unpinned_payload_still_sees_every_card(monkeypatch):- """The other direction, and it is the one the two-card claim depends on: a- leg that is deliberately NOT pinned must still report both cards, or real- multi-GPU coverage would be reported as single-card."""+ """An unpinned leg must still report every GPU, or real multi-GPU coverage would be reported as+ single-card; the two-card claim depends on it."""module = _payload_module()_with_smi(module, monkeypatch, TWO_ROWS, None)assert len(module.gpu_inventory()) == 2diff --git a/tests/kaggle/test_studio_tabs.py b/tests/kaggle/test_studio_tabs.pyindex 291378196c3..ab2aac02bbf 100644--- a/tests/kaggle/test_studio_tabs.py+++ b/tests/kaggle/test_studio_tabs.py@@ -63,9 +63,8 @@ def test_the_assertion_exists_and_is_driven_from_the_run():def test_every_endpoint_resolves_to_a_route_that_exists():- """The rule that turns a list of strings into a check. A typo'd path 404s- exactly like a missing router, so the payload would go red naming a tab- that is perfectly fine."""+ """Each endpoint must resolve to a declared route, since a typo'd path 404s just like a missing+ router and would wrongly fail a healthy tab."""prefixes = _mounted_prefixes()declared = _declared_get_paths()unresolved = []diff --git a/tests/kaggle/test_studio_web_search.py b/tests/kaggle/test_studio_web_search.pyindex 145299fda4f..ae11b8e5143 100644--- a/tests/kaggle/test_studio_web_search.py+++ b/tests/kaggle/test_studio_web_search.py@@ -33,9 +33,8 @@ def test_the_assertion_exists_and_is_driven_from_the_run():def test_only_the_web_search_tool_is_offered():- """With `enabled_tools` omitted the loop may reach for python instead, and- a run that executed python would satisfy a looser log check while saying- nothing about search."""+ """With enabled_tools omitted the loop may reach for python, and a run that executed python+ would satisfy a looser log check while saying nothing about search."""body = _body()assert "enable_tools = True" in bodyassert 'enabled_tools = ["web_search"]' in body@@ -50,9 +49,8 @@ def test_the_evidence_is_the_execution_line_and_not_a_selection_one():def test_it_counts_only_what_this_request_wrote():- """The payload drives several tool assertions against one server. A grep- over the whole log would let an earlier assertion's tool call stand in for- this one, which is a green tick for a search that never happened."""+ """Several assertions share one server, so count only the log slice this request wrote; a+ whole-log grep would let an earlier tool call pass for this search."""body = _body()assert "before = self.server_log.read_text" in body# Whitespace-insensitive: the formatter rewrites the slice spacing.@@ -61,9 +59,8 @@ def test_it_counts_only_what_this_request_wrote():def test_an_empty_result_set_is_reported_and_not_failed():- """Deliberately narrow. ddgs runs with no API key, so a provider throttling- a Kaggle egress IP is a fact about the day; failing on it would be a red- nobody can act on. The execution is the claim; the results are context."""+ """ddgs needs no API key, so provider throttling of a Kaggle egress IP is not actionable; the+ test asserts execution, and results are only context."""func = _func("assert_web_search")for node in ast.walk(func):if not isinstance(node, ast.If):diff --git a/tests/kaggle/test_t4_ci_transport.py b/tests/kaggle/test_t4_ci_transport.pyindex eb9297323d5..5db32ded943 100644--- a/tests/kaggle/test_t4_ci_transport.py+++ b/tests/kaggle/test_t4_ci_transport.py@@ -2323,13 +2323,8 @@ def test_gptoss_never_shares_a_card(tmp_path):def test_two_small_legs_do_share_a_card(tmp_path):- """The feature, asserted positively.-- Every other guard here is a bound -- never over budget, never more than two- -- and every one of them is satisfied by a scheduler that co-schedules- NOTHING. Without this the whole change could silently do no work at all and- the suite would stay green.- """+ """Asserts that small legs actually share a card, since the other guards are bounds that a+ scheduler co-scheduling nothing would also satisfy."""durations = {f"t4_{n}.ipynb": 0.4 for n in ALL_LEGS}driven = _drive_packed(tmp_path, ALL_LEGS, gpus = 2, durations = durations)assert driven[diff --git a/tests/kaggle/test_t4_payload_assertions.py b/tests/kaggle/test_t4_payload_assertions.pyindex 008cd130a89..6576370347b 100644--- a/tests/kaggle/test_t4_payload_assertions.py+++ b/tests/kaggle/test_t4_payload_assertions.py@@ -92,11 +92,8 @@ def test_matching_step_coordinates_are_not_reported_as_a_difference():def test_two_runs_that_both_overflowed_on_the_same_step_agree():- """An fp16 overflow logs infinity as readily as NaN, and abs(inf-inf) is NaN.-- NaN != 0.0, so the subtraction reported two identical traces as- nondeterministic, with a max_abs_diff of 0.0 to show for it.- """+ """fp16 overflow logs infinity and abs(inf-inf) is NaN, which is never 0.0, so identical+ overflowing traces were reported as nondeterministic."""from determinism import compare_metricsa = [{"step": 1, "loss": 10.0, "grad_norm": INF}, {"step": 2, "loss": 9.0, "grad_norm": 4.0}]@@ -803,11 +800,8 @@ def test_a_reference_with_no_recorded_revision_does_not_refuse(tmp_path):def test_a_pin_the_run_could_not_read_is_recorded_as_unchecked(tmp_path):- """The other direction: the reference names a commit and the run does not.-- Skipping that silently is a checkpoint pin that stopped running with- nothing to say so.- """+ """When the reference names a commit but the run cannot read one, the pin must be recorded as+ unchecked, not silently skipped."""check_reference, ref = _shared_setup_3(tmp_path)payload = json.loads(ref.read_text())payload["resolved_revision"] = "10413c288cb9629acdf60b3e0229f3ba75efe413"@@ -1928,9 +1922,8 @@ def test_the_length_reward_still_discriminates_at_the_lengths_the_model_emits():def test_the_length_reward_is_strictly_increasing_and_never_saturates():- """The property that makes the test above hold for lengths nobody has seen- yet. A cap is a length at which this stops being true, which is exactly how- the previous version passed review."""+ """Strict monotonicity must hold for lengths nobody has seen; a cap is a length where it stops+ being true, which is how the previous version passed review."""from run_grpo_t4 import reward_lengthlengths = [0, 1, 50, 200, 1000, 3000, 10000, 100000]@@ -1940,9 +1933,8 @@ def test_the_length_reward_is_strictly_increasing_and_never_saturates():def test_two_identical_completions_still_tie_because_that_is_real():- """Guard against overcorrecting. A group whose completions are genuinely- identical SHOULD tie -- that is degenerate generation and the leg is right- to fail on it. The bug was ties between DIFFERENT completions."""+ """Identical completions should tie, since that is degenerate generation the leg should fail on;+ the bug was ties between different completions."""from run_grpo_t4 import reward_lengthscores = reward_length(_completions(2534, 2534))@@ -2178,9 +2170,8 @@ def test_every_option_the_child_needs_actually_reaches_the_child():def test_the_export_flag_is_forwarded_as_a_bare_flag():- """store_true options cannot ride the (flag, value) loop -- `--export-gguf- True` is not a thing -- so they need their own append, and that is the line- that was missing."""+ """store_true options cannot ride the (flag, value) loop, since --export-gguf True is not valid,+ so they need their own append line."""block = _child_command_block()assert 'cmd.append("--export-gguf")' in blockassert "if args.export_gguf:" in blockdiff --git a/tests/kaggle/test_t4_smoke_harness.py b/tests/kaggle/test_t4_smoke_harness.pyindex 9d4f9d6a5db..6853b10f919 100644--- a/tests/kaggle/test_t4_smoke_harness.py+++ b/tests/kaggle/test_t4_smoke_harness.py@@ -1145,9 +1145,8 @@ def test_a_moved_scaler_skip_pattern_is_out_of_band(tmp_path, swap):def test_matching_infinite_grad_norms_are_within_band(tmp_path):- """An fp16 overflow logs infinity as readily as NaN, and the same sign on- both sides is the unchanged case. abs(inf - inf) is NaN, so this has to be- decided before the division rather than by it."""+ """Matching infinite grad norms (same sign) must be decided before the division, since abs(inf -+ inf) is NaN after an fp16 overflow."""from run_t4_smoke import check_referenceinf = float("inf")@@ -1549,9 +1548,8 @@ def test_every_registered_leg_is_either_carried_or_explicitly_unwired():def test_an_unwired_leg_still_builds():- """It is unwired because its INSTALL does not work on the image, not because- the payload rots: a leg that stopped building would be rediscovered only by- whoever next tries to switch it on."""+ """An unwired leg is unwired because its INSTALL fails on the image, not because the payload+ rots, so it must still build when someone switches it on."""from legs import UNWIREDfor name in UNWIRED:assert name in LEG_NAMES, (@@ -1922,9 +1920,8 @@ def test_the_grpo_vllm_pin_does_not_replace_the_images_torch():def test_the_grpo_leg_shares_the_image_now_that_it_keeps_the_images_torch():- """The isolated venv existed only to survive replacing torch. Probe 3 spent- about an hour of quota resolving a CUDA stack from scratch and never- produced payload output; with nothing to replace, nothing to isolate."""+ """The grpo leg shares system site-packages and keeps the image torch, so nothing needs+ replacing and no isolated venv is needed."""from legs import LEGSassert LEGS["grpo"].system_site_packages is True@@ -2071,9 +2068,8 @@ def test_the_grpo_leg_keeps_the_config_that_actually_fit():def test_the_grpo_leg_still_pins_the_vllm_that_matches_the_image():- """The pin is chosen to match the image's torch to the patch, not to be- old. Any other release replaces torch, which is what killed three probe- sessions."""+ """The vLLM pin must match the image's torch to the patch release rather than be old; any other+ release replaces torch, which killed three probe sessions."""from legs import LEGSinstall = " ".join(part for group in LEGS["grpo"].install for part in group)@@ -2218,12 +2214,9 @@ def test_a_dispatched_ref_is_resolved_to_one_commit():@pytest.mark.skipif(shutil.which("bash") is None, reason = "the step is a bash script")def test_the_resolve_step_pins_every_shape_of_ref_it_can_be_given(tmp_path):- """EXECUTE the step, with git stubbed, rather than reading it.-- Pattern-matching a shell script passes on one that runs and writes the wrong- thing, and this one has four branches: no input, a mutable branch or tag, a- commit needing no resolution, and a ref that resolves to nothing.- """+ """Executes the resolve step with git stubbed, since pattern matching passes a script that+ writes the wrong thing; its four branches are no input, a mutable branch or tag, a commit,+ and a ref resolving to nothing."""steps = _workflow()["jobs"]["gate"]["steps"]script = next(s for s in steps if s.get("id") == "ref")["run"]@@ -3354,9 +3347,8 @@ def test_the_log_fallback_reads_kaggles_own_json_record_shape(tmp_path):def test_a_report_split_across_log_records_is_still_read(tmp_path):- """Kaggle chunks stdout by write, not by line, so the prefix and its- payload can land in different records. Flattening has to join them back- before any line splitting happens."""+ """Kaggle chunks stdout by write, not by line, so the prefix and payload can land in different+ records; flattening must join them before splitting lines."""import launchrecords = [@@ -3369,8 +3361,7 @@ def test_a_report_split_across_log_records_is_still_read(tmp_path):def test_a_kernel_that_could_not_be_pushed_does_not_lose_the_other(tmp_path):- """Half a run is a warning, not a failure: half a comparison is not- evidence of a regression."""+ """Half a run is a warning, not a failure, since half a comparison is not evidence of a regression."""sys.path.insert(0, str(CI_DIR))evidence = tmp_path / "evidence"evidence.mkdir()diff --git a/tests/kaggle/test_two_account_selection.py b/tests/kaggle/test_two_account_selection.pyindex 35b8be7d252..dc216862477 100644--- a/tests/kaggle/test_two_account_selection.py+++ b/tests/kaggle/test_two_account_selection.py@@ -232,9 +232,8 @@ def test_every_run_of_one_commit_lands_on_the_same_account():def test_an_account_with_no_readable_quota_gets_no_weight_but_keeps_its_turn():- """Unknown is not zero-sized and it is not disqualified either: the account- loses its share of the traffic, because a share is what its plan says and we- did not get to hear it, and keeps its place as a fallback."""+ """An account with unknown quota gets no weight, since a share comes from its plan, but it is+ not disqualified and keeps its place as a fallback."""chosen, _ = gate.weighted_pick("5", {"1": 60.0})assert chosen == "1"chosen, _ = gate.weighted_pick("5", {})@@ -258,9 +257,8 @@ def test_an_unknown_plan_size_leaves_the_reserve_alone():def test_a_sweep_leaves_the_other_account_s_kernels_filed(tmp_path, monkeypatch):- """This token cannot delete that kernel. Trying turns a real leak into a- log line that reads exactly like a kernel already gone -- and DROPS the- record, which is the only thing that still knows the kernel exists."""+ """This token cannot delete that kernel; trying would turn a real leak into a log line that+ reads like an already-gone kernel and drop the only record of it."""registry = tmp_path / "inflight.json"registry.write_text(json.dumps(@@ -385,9 +383,8 @@ def test_neither_token_name_can_reach_the_kernel():def test_a_kernel_already_running_this_commit_on_any_account_stands_the_run_down():- """A handover lands a retry on the other account, whose GPU job collects- with only its own token and sees nothing in flight. So the gate asks every- account it surveys before it picks one."""+ """A handover lands a retry on another account whose GPU job sees only its own kernels, so the+ gate surveys every account before picking one."""sha = "abcdef0123456789" + "0" * 24own = ["danielhanchen/unsloth-t4-ci-sabcdef012345-1111 (RUNNING)", # studio, this commit@@ -524,9 +521,8 @@ def _other(sha: str) -> tuple[str, str]:def test_the_gate_stands_down_when_the_other_account_already_runs_this_commit(monkeypatch, tmp_path):- """The sampled account is FREE and the other holds a kernel for this commit,- which is what a retry after a handover looks like. A gate that only asks the- account it is about to pick finds it clear and dispatches a duplicate."""+ """The sampled account is free but the other holds a kernel for this commit, as on a retry after+ a handover; checking only the sampled account would dispatch a duplicate."""_sampled, other = _other("abcdef0123456789" + "0" * 24)code, outputs, asked, _sha = _drive_gate(monkeypatch, tmp_path, holder = other)assert code == 0@@ -539,9 +535,8 @@ def test_the_gate_stands_down_when_the_other_account_already_runs_this_commit(def test_an_account_that_cannot_launch_is_still_asked_whether_it_runs_this_commit(monkeypatch, tmp_path):- """The account that dispatched this commit is the one likely to be short of- quota now. Skipping it in the sweep hands the retry to the other account,- which dispatches the same commit again."""+ """The dispatching account is likely short of quota now; skipping it in the sweep hands the+ retry to the other account, which dispatches the same commit again."""_sampled, other = _other("abcdef0123456789" + "0" * 24)for outcome in ("insufficient_quota", "quota_unreadable"):code, outputs, asked, _sha = _drive_gate(@@ -553,9 +548,8 @@ def test_an_account_that_cannot_launch_is_still_asked_whether_it_runs_this_commidef test_the_second_slot_is_not_a_duplicate_but_its_own_retry_is(monkeypatch, tmp_path):- """`slot: 2` is a second session on the same ref beside slot 1, so a slot-1- kernel must not stand it down, while a retry of the slot-2 run itself must.- The slot in the slug tells the two apart."""+ """A slot-2 session on the same ref is not a duplicate of a slot-1 kernel, but a retry of the+ slot-2 run is; the slot in the kernel slug tells the two apart."""sampled, _unused = _other("abcdef0123456789" + "0" * 24)# Slot 1 kernel up, slot 2 asked for: runs._c, outputs, _a, _s = _drive_gate(@@ -600,9 +594,8 @@ def test_the_surveys_share_one_budget(monkeypatch, tmp_path):def test_the_gate_is_keyed_on_the_commit_the_gpu_job_will_test():- """A dispatch naming `unsloth_ref` tests that ref, not github.sha. Keyed on- github.sha the gate looks for the wrong kernel, and once the default branch- moves two runs of one ref can land on different accounts."""+ """A dispatch naming unsloth_ref tests that ref, not github.sha; keyed on github.sha the gate+ finds the wrong kernel, and after the default branch moves one ref can split across accounts."""for path in (NOTEBOOK_WF, STUDIO_WF):gate_job = _wf(path)["jobs"]["gate"]steps = {s.get("id"): s for s in gate_job["steps"] if s.get("id")}diff --git a/tests/kaggle/test_venv_interpreter_and_overlay_path.py b/tests/kaggle/test_venv_interpreter_and_overlay_path.pyindex ce689557a64..c68cf481d2e 100644--- a/tests/kaggle/test_venv_interpreter_and_overlay_path.py+++ b/tests/kaggle/test_venv_interpreter_and_overlay_path.py@@ -115,9 +115,8 @@ def test_the_mutation_this_rule_exists_for_is_actually_caught():def test_the_path_is_not_merely_a_string_containing_site_packages():- """`site-packages` has to be the directory packages are installed INTO, not- a decoration further up the path, or pip lays the tree somewhere dill still- reads by value."""+ """The overlay --target must end in site-packages, the directory pip installs into; otherwise+ pip lays the tree where dill still reads modules by value."""ov = _overlay_dir_from_generated_source()assert ov.name == "site-packages", (f"the overlay --target is {ov}, whose last component is {ov.name!r}; "diff --git a/tests/kaggle/test_vision_run.py b/tests/kaggle/test_vision_run.pyindex 7fffb89baab..0b27924f6c4 100644--- a/tests/kaggle/test_vision_run.py+++ b/tests/kaggle/test_vision_run.py@@ -223,9 +223,8 @@ def test_a_marker_that_matched_nothing_is_refused_rather_than_answered_no():def test_adapter_sum_finds_the_capital_b_peft_names():- """Drives the REAL function, because every rule above is fed a dict written- by hand and none of them execute the code that produces it. That is exactly- how the capital-B bug reached hardware."""+ """Drives the real adapter_sum, since the other rules feed hand-written dicts; that gap is how+ the capital-B PEFT name bug reached hardware."""import torchfrom run_vision_t4 import adapter_sum@@ -266,9 +265,8 @@ def test_the_leg_actually_DRIVES_the_vision_run():def test_the_parent_spawns_the_vision_run_after_the_cycles():- """Two 4bit models resident at once on a 14.56GB card is how a leg becomes- an OOM blamed on the thing it was testing. It is also what keeps a vision- failure from reading as a text-training one."""+ """The vision run is spawned after the text cycles so two 4bit models are never resident on the+ 14.56GB T4, which avoids an OOM and keeps vision failures separate."""src = (PAYLOAD / "run_t4_smoke.py").read_text(encoding = "utf-8")assert '"run_vision_t4.py"' in srccycles_at = src.index("runs.append(json.loads(report_file.read_text")@@ -285,9 +283,8 @@ def test_a_vision_run_that_wrote_no_report_is_a_failure_not_a_silence():def test_the_vision_step_count_is_pinned_low_rather_than_inherited():- """A vision step on a T4 is ~100s (317.9s for three, measured on- unsloth-probe-vision-train-r3). Inheriting the text side's --max-steps- would quietly add half an hour to the leg."""+ """The vision step count is pinned low rather than inherited from the text --max-steps, which+ would quietly add about half an hour to the T4 leg."""src = (PAYLOAD / "run_t4_smoke.py").read_text(encoding = "utf-8")spawn = src[src.index('"run_vision_t4.py"') :]spawn = spawn[: spawn.index("subprocess.run(vision_cmd)")]diff --git a/tests/notebooks/test_colab_oracle_drift.py b/tests/notebooks/test_colab_oracle_drift.pyindex f1d02ad2b00..99d68cfa162 100644--- a/tests/notebooks/test_colab_oracle_drift.py+++ b/tests/notebooks/test_colab_oracle_drift.py@@ -123,9 +123,8 @@ def test_full_lists_every_drifted_entry(oracle, capsys):def test_strict_oracle_is_the_one_lint_pins_against(oracle):- """--colab-pin is fed COLAB_FALLBACK_FILE, and that is the snapshot whose- drift is fatal. If these ever diverge the tripwire is guarding the wrong- file again."""+ """--colab-pin is fed COLAB_FALLBACK_FILE, the snapshot whose drift is fatal; the strict oracle+ must stay that same file or the tripwire guards the wrong one."""assert nv.COLAB_ORACLE_FILES[nv.COLAB_STRICT_ORACLE] == nv.COLAB_FALLBACK_FILE.name@@ -218,9 +217,8 @@ def test_refresh_all_writes_nothing_into_a_fresh_dir_on_failure(oracle, tmp_pathdef test_cron_lint_survives_a_strict_drift_failure():- """The strict step exits 1 on a Colab rotation, which is exactly when the- live-PyPI pass is worth having. Without `if: always()` on the steps after- it, the job would only ever lint on the days nothing drifted."""+ """The strict step exits 1 on a Colab rotation, so steps after it need if: always() to keep the+ live-PyPI lint running on drift days."""wf = (REPO_ROOT / ".github/workflows/notebooks-ci.yml").read_text(encoding = "utf-8")rest = wf.split("\n static-with-pypi:", 1)[1]nxt = re.search(r"^ [A-Za-z0-9_-]+:$", rest, re.M)@@ -343,9 +341,8 @@ def test_a_rule_bearing_oracle_that_will_not_fetch_still_fails_the_refresh(oracldef test_a_refresh_never_acknowledges_a_payload_the_rules_cannot_read(oracle, tmp_path, name, payload):- """Writing it would leave upstream and snapshot equally empty of the key, and colab-diff- compares the two parses, so the strict tripwire would go quiet on the very rotation it- exists to catch."""+ """A refresh must not acknowledge a payload the rules cannot read: upstream and snapshot would+ both lack the key and colab-diff would go quiet on that rotation."""upstream, _ = oracleupstream[name] = payloadout_dir = tmp_path / "rotated"diff --git a/tests/notebooks/test_notebook_validator_shell_parsing.py b/tests/notebooks/test_notebook_validator_shell_parsing.pyindex 0d755e8e1c1..c163213a1df 100644--- a/tests/notebooks/test_notebook_validator_shell_parsing.py+++ b/tests/notebooks/test_notebook_validator_shell_parsing.py@@ -1916,9 +1916,8 @@ def test_a_conditional_only_cell_does_not_replay_the_bare_oracle(tmp_path):def test_python_version_drift_in_the_os_oracle_fails_strict():- """_marker_environment reads the Python line out of os-info, so that key is rule-bearing- even though the rest is human context: with only the pip freeze strict, an interpreter- bump behind an unchanged package set left the cron green and the Python stale."""+ """_marker_environment reads the Python version from os-info, so that key is rule-bearing; an+ interpreter bump with unchanged packages must fail strict, not stay green."""nv = _load_notebook_validator_module()assert nv.COLAB_STRICT_ORACLE == "pip-freeze.gpu.txt"@@ -4448,10 +4447,8 @@ def test_a_project_name_is_canonicalized_the_way_pep_503_says():def test_a_for_list_is_read_across_any_shell_whitespace():- """`for x\tin\ta` is the same loop to bash as the spaced form.-- Partitioning on the literal `" in "` found no list, so a body that certainly runs was marked- conditional and its install dropped out of the replay."""+ """A for loop with tabs around in is the same loop to bash; partitioning on literal spaces found+ no list, so a body that certainly runs was marked conditional."""nv = _load_notebook_validator_module()assert ("!pip install torch==2.11", False) in nv._split_chained(diff --git a/tests/python/test_compiler_watch_temp_scan.py b/tests/python/test_compiler_watch_temp_scan.pyindex 7178596b7a9..03cae398b3d 100644--- a/tests/python/test_compiler_watch_temp_scan.py+++ b/tests/python/test_compiler_watch_temp_scan.py@@ -227,13 +227,8 @@ def test_an_unreadable_directory_is_reported_and_not_just_skipped(tmp_path: pathreason = "POSIX permissions only; see the walk control above.",)def test_a_directory_that_vanished_is_not_reported_as_unread(tmp_path: pathlib.Path) -> None:- """A path that is gone is not a hole in the measurement, and must not void a run.-- This is the transient case the whole change exists for. A directory that no longer- exists cannot contribute a file to a later listing of itself, so there is nothing for- the caller to withhold and nothing to declare void. Only a directory that is still- there and still unreadable is a real gap.- """+ """A vanished directory is not a gap in the measurement and must not void a run; only a+ directory that is still present but unreadable counts as unread."""scan = _scan(tmp_path / "never-existed")assert scan["files"] == [], scanassert scan["unread"] == [], (diff --git a/tests/python/test_cross_platform_parity.py b/tests/python/test_cross_platform_parity.pyindex 3d6b155ff20..90ae158f92d 100644--- a/tests/python/test_cross_platform_parity.py+++ b/tests/python/test_cross_platform_parity.py@@ -610,9 +610,8 @@ class TestPinnedIndexClearsUvEnvParity:assert var in text, f"install_python_stack.py must clear {var} for pinned installs"def test_all_installers_clear_uv_torch_backend(self):- """uv's torch backend redirects torch resolution to its own per-backend- index even against an explicit pin, so every installer's pinned-install- scrub must clear UV_TORCH_BACKEND too."""+ """uv's torch backend redirects torch to its own per-backend index even against an explicit+ pin, so every pinned-install scrub must clear UV_TORCH_BACKEND."""sh = INSTALL_SH.read_text(encoding = "utf-8")assert "-u UV_TORCH_BACKEND" in sh, "install.sh pinned scrub must clear UV_TORCH_BACKEND"for path in (INSTALL_PS1, SETUP_PS1):diff --git a/tests/python/test_docker_cpu_fallback.py b/tests/python/test_docker_cpu_fallback.pyindex 63566e1cd81..ef563e90649 100644--- a/tests/python/test_docker_cpu_fallback.py+++ b/tests/python/test_docker_cpu_fallback.py@@ -182,11 +182,9 @@ def _studio_mounts(argv):@_posix_shellclass TestRunShMountsTheStudioVolume:- """Studio's accounts, chats and trained models live under /opt/unsloth-studio.- The image links its own code in there at every start, so a named volume keeps- the data across `docker rm` without pinning the first image's code. The helper- has to mount it, or the quick start in DOCKERHUB.md keeps data and the helper- does not."""+ """Studio data lives under /opt/unsloth-studio and the image relinks its code there on each+ start, so a named volume keeps data across docker rm; run.sh must mount it, or it would+ diverge from the DOCKERHUB.md quick start, which keeps data."""def test_the_default_is_a_named_volume(self, tmp_path):argv, _ = _invoke_run_sh(tmp_path, nvidia = True, amd = False)diff --git a/tests/python/test_docker_nb_compat_pre_run_cell.py b/tests/python/test_docker_nb_compat_pre_run_cell.pyindex da0cd1a5429..4c73c73fc5d 100644--- a/tests/python/test_docker_nb_compat_pre_run_cell.py+++ b/tests/python/test_docker_nb_compat_pre_run_cell.py@@ -220,9 +220,8 @@ def test_every_spelling_the_shim_drops_is_a_pin(compat, spec):def test_the_shim_and_the_scanner_agree_on_the_name(compat):- """The two halves this item found apart. Read the shim's own canonicaliser rather- than restating its rule here, so a change on that side fails this instead of- drifting silently."""+ """The shim and the scanner must agree on the canonical name; the test reads the shim's own+ canonicaliser rather than restating its rule, so a change fails loudly."""shim_path = REPO_ROOT / "docker" / "unsloth_pip_shim.py"spec = importlib.util.spec_from_file_location("unsloth_pip_shim_names", shim_path)shim = importlib.util.module_from_spec(spec)diff --git a/tests/python/test_docker_nb_install_cell_sig.py b/tests/python/test_docker_nb_install_cell_sig.pyindex f17f1db3b8a..40e2f0ec3e6 100644--- a/tests/python/test_docker_nb_install_cell_sig.py+++ b/tests/python/test_docker_nb_install_cell_sig.py@@ -340,9 +340,8 @@ def test_a_real_shell_invocation_still_counts(sig, line):def test_the_whole_shipped_corpus_is_unaffected(sig):- """Blast radius, measured rather than asserted: all 1064 marker lines inside the- 152 `%%bash` cells of the 561 shipped notebooks open a command, so the narrowing- changes no digest today. It only removes the tail this item found."""+ """All marker lines inside the shipped %%bash notebook cells open a command, so narrowing the+ marker changes no digest; only the review-found tail is removed."""for line in ("pip install -q unsloth","apt install -y git",diff --git a/tests/python/test_docker_nb_populate_retry.py b/tests/python/test_docker_nb_populate_retry.pyindex e6c007d157a..cee4fa1788e 100644--- a/tests/python/test_docker_nb_populate_retry.py+++ b/tests/python/test_docker_nb_populate_retry.py@@ -282,10 +282,9 @@ def test_a_stale_unwritable_state_temp_is_not_published_as_our_state(tmp_path: P@behaviouraldef test_an_unstageable_state_leaves_the_marker_off_instead_of_copying(tmp_path: Path):- """Fail CLOSED when the staging path cannot be cleared either, exactly as the- refresh child does: notebooks we cannot record read as user edits on the next run,- which is `kept`, not `failed`, so the marker would be stamped over them for good.- A DIRECTORY at the staging path is unlinkable and untruncatable for root too."""+ """Fail closed when the staging path cannot be cleared: unrecorded notebooks read as kept user+ edits, so the marker would be stamped over them; a directory there cannot be unlinked or+ truncated even by root."""template = _template(tmp_path)dest = tmp_path / "dest"dest.mkdir()@@ -393,9 +392,8 @@ _ACCOUNTED = (def _exempt_lines(lines):- """record_state() is dead code (no caller anywhere; the companion test below- keeps it that way), and record_tmpstate() is the shared helper whose whole job is- to perform the append and report the status its CALLERS must handle."""+ """record_state() is dead code kept dead by a companion test, while record_tmpstate() is the+ shared append helper whose callers must handle the status it reports."""out = set()for name in ("record_state() {", "record_tmpstate() {"):start = next(i for i, l in enumerate(lines) if l.startswith(name))@@ -465,9 +463,8 @@ def test_the_marker_advance_is_gated_on_the_failure_counters():def test_record_state_is_still_uncalled():- """The exemption above depends on it. A call site makes its unchecked append live,- and it has a second problem waiting: its loop is a PIPELINE, so a failure counter- set inside would not survive the subshell."""+ """Any call site would make the unchecked append live, and its loop is a pipeline, so a failure+ counter set inside would be lost in the subshell; the exemption depends on this."""body = SYNC.read_text(encoding = "utf-8")calls = [ln.strip()diff --git a/tests/python/test_docker_nb_refresh_state_durability.py b/tests/python/test_docker_nb_refresh_state_durability.pyindex 3c6d256f8f5..23da2a83874 100644--- a/tests/python/test_docker_nb_refresh_state_durability.py+++ b/tests/python/test_docker_nb_refresh_state_durability.py@@ -231,15 +231,8 @@ def _commit_upstream_change(up: Path):@needs_gitdef test_a_user_edited_notebook_is_never_rolled_back(tmp_path: Path):- """The rollback removes OUR copy so a lost record is recoverable. It must never- touch a notebook the user changed.-- Every SECOND notebook is edited, not every twenty-fifth. The cap bites near the- end of the walk, so a sparse edited set can miss the failing range entirely and- the rollback is then never asked about a user edit -- which is how the first- version of this test passed without executing the code it named. The assertion- that some pristine notebook WAS removed is what keeps it honest.- """+ """The rollback must never touch a user-edited notebook; every second file is edited since a+ sparse set can miss the failing range, and a pristine one must still be removed."""dest, tpl, up = _shared_setup_1(tmp_path)assert len(_published(dest)) == NOTEBOOKS@@ -266,9 +259,8 @@ def test_a_user_edited_notebook_is_never_rolled_back(tmp_path: Path):def _json_upstream(tmp_path: Path, count: int) -> Path:- """Valid notebook JSON, so the body-aware comparison can report SAME and the- `unchanged` branch is reachable. With one-byte files it never is, which is why- the rollback below had no coverage."""+ """Writes valid notebook JSON so the body-aware comparison can report SAME and the unchanged+ branch is reachable; one-byte files never reach it."""import jsonup = tmp_path / "up"@@ -330,12 +322,8 @@ def test_the_refresh_child_never_republishes_an_unreadable_state_as_empty(tmp_pa@needs_gitdef test_a_failed_record_on_an_unchanged_notebook_rolls_it_back(tmp_path: Path):- """drop_unrecordable's removal, which nothing exercised before.-- Its other call sites either hand it a user-edited file (hash gate declines) or a- missing one (early return), so the suite could call it seven times and roll back- zero. The `unchanged` branch is the reachable one that must actually remove.- """+ """Exercises drop_unrecordable's removal, reachable only through the unchanged branch; its other+ call sites decline user edits or return early on missing files."""# Own build: only JSON notebooks can reach the body-aware `unchanged` branch.tpl, dest = _template(tmp_path), tmp_path / "dest"up = _json_upstream(tmp_path, NOTEBOOKS)@@ -388,14 +376,8 @@ def test_keeping_a_removed_notebook_keeps_its_record_too(tmp_path: Path):@needs_gitdef test_an_unrecorded_notebook_identical_to_upstream_is_adopted(tmp_path: Path):- """When the publish rollback cannot unlink -- a single-FILE bind mount gives- EBUSY there, the same case the rename at line 562 already works around -- the- published bytes stay on disk with no record, and no further append is possible in- that run. Rolling the bytes back instead would not help, because the file is- still unrecorded and so still read as a user edit, and discarding the staged- state would strand every notebook the run DID record. The only repair is for a- later refresh to notice that a file identical to the clone was never a user edit- and take it back under management."""+ """If the rollback cannot unlink a published file (EBUSY on a single-file bind mount), its bytes+ stay unrecorded, so a later refresh must adopt a file identical to the clone."""dest, tpl, up = _shared_setup_1(tmp_path)orphan = f"nb{7:09d}.ipynb"@@ -420,9 +402,8 @@ def test_an_unrecorded_notebook_identical_to_upstream_is_adopted(tmp_path: Path)@needs_gitdef test_a_genuinely_edited_unrecorded_notebook_is_still_left_alone(tmp_path: Path):- """The adoption above must key on the content matching the clone EXACTLY. An- unrecorded file whose bytes differ is the real user-edit case and must keep its- hands-off treatment."""+ """Adoption must key on the content matching the clone exactly; an unrecorded file whose bytes+ differ is a real user edit and must be left alone."""dest, tpl, up = _shared_setup_1(tmp_path)orphan = f"nb{7:09d}.ipynb"@@ -510,18 +491,14 @@ def _big_template(tmp_path: Path, count: int) -> Path:@needs_gitdef test_an_abandoned_restore_puts_the_tree_back(tmp_path: Path):- """Section 1b restores notebooks that are missing, then rewrites the state. When- that rewrite is abandoned the old state is kept, and it describes the tree as it- was BEFORE the restores -- so the restored files have to go back too. Leaving them- means the next refresh sees baked content where the state holds post-refresh- hashes and reads every one as a user edit."""+ """When the state rewrite after the section 1b restores is abandoned, the old state describes+ the pre-restore tree, so restored files must go back too, or every one reads as a user edit."""dest, tpl, up = _shared_big_synced(tmp_path)before = _recorded(dest)assert len(before) == NOTEBOOKS- # The last 50 records straddle the point where appends start failing. Taken in the- # state's own order: the script records `find` order, which is directory order, so on- # ext4 the 50 highest names can all sit before the cap and every one gets restored.+ # The last 50 records straddle where appends start failing; the script records find order+ # (directory order), so on ext4 the 50 highest names can all precede the cap.order = [line.partition(" ")[2]for line in (dest / ".unsloth_sync_state").read_text(encoding = "utf-8").splitlines()@@ -559,11 +536,8 @@ def test_an_abandoned_restore_puts_the_tree_back(tmp_path: Path):@needs_gitdef test_a_lost_merge_record_does_not_publish_the_short_state(tmp_path: Path):- """The merge loop is the only source of records for notebooks that exist upstream- but not in the baked template. Nothing can re-derive them, so a lost one must- abandon the staged state rather than publish it and merely withhold the marker.- A failed COPY is different and still publishes, because the next boot re-walks the- template."""+ """A lost merge record must abandon the staged state, since nothing can re-derive upstream-only+ notebooks; a failed copy still publishes because the next boot re-walks the template."""dest, tpl, up = _shared_big_synced(tmp_path)state = dest / ".unsloth_sync_state"diff --git a/tests/python/test_docker_nb_strip_colab_race.py b/tests/python/test_docker_nb_strip_colab_race.pyindex 17f75e6699c..4203c39b25c 100644--- a/tests/python/test_docker_nb_strip_colab_race.py+++ b/tests/python/test_docker_nb_strip_colab_race.py@@ -180,9 +180,8 @@ def test_the_recorded_hash_is_the_cleaned_copy_when_nobody_races(strip, tmp_pathdef test_cleanup_keeps_the_notebooks_owner_and_mode(strip, tmp_path: Path):- """A bind-mounted notebook matching the baked template is managed WITHOUT being- copied, so the host user keeps owning it -- and os.replace swaps the directory- entry, so a root-written staging file would hand it back root-owned."""+ """A bind-mounted notebook matching the template is managed without a copy, keeping the host+ owner; os.replace swaps the entry, so a root-written stage would hand back root ownership."""import osimport stat as _statdiff --git a/tests/python/test_docker_nb_sync_publish_ownership.py b/tests/python/test_docker_nb_sync_publish_ownership.pyindex 558487ef15a..73523f593c3 100644--- a/tests/python/test_docker_nb_sync_publish_ownership.py+++ b/tests/python/test_docker_nb_sync_publish_ownership.py@@ -191,11 +191,8 @@ def test_a_failed_publish_does_not_claim_the_commit_is_synced(tmp_path: Path):reason = "needs POSIX mode bits, and root holds CAP_DAC_OVERRIDE, so a read-only marker does not stop the write",)def test_a_marker_the_user_cannot_truncate_is_still_advanced(tmp_path: Path):- """A root boot leaves the marker root-owned 0644 inside a directory the host user- owns. A later --user boot renames the state into place fine but `> marker` fails- on the truncate, so the refresh reported success while the marker stayed behind- and every start after that re-synced every notebook. Modelled here with a- read-only marker, which fails the same open(O_TRUNC)."""+ """A root-owned marker that a --user boot cannot truncate must still be advanced, or every start+ re-syncs every notebook; modelled with a read-only marker, which fails open(O_TRUNC)."""template, dest, remote = _world(tmp_path)synced = dest / ".unsloth_sync_commit"synced.write_text("stale\n", encoding = "utf-8")@@ -387,9 +384,8 @@ def test_an_existing_notebook_still_inherits_from_the_file_not_the_directory(tmpdef test_both_template_copies_hand_the_file_to_the_host_user():- """The sibling guard: populate and restore both `cp -a` from the template,- which preserves its root:root 0644, so each needs the ownership fix. Fixing- the publish path alone is how this class of bug keeps coming back."""+ """Populate and restore both cp -a from the template, preserving its root:root 0644, so each+ needs the ownership fix; fixing only the publish path lets this bug recur."""source = SYNC_SH.read_text(encoding = "utf-8")copies = [idiff --git a/tests/python/test_docker_nb_sync_upstream_removal.py b/tests/python/test_docker_nb_sync_upstream_removal.pyindex 326bb4f45ef..234b787fff5 100644--- a/tests/python/test_docker_nb_sync_upstream_removal.py+++ b/tests/python/test_docker_nb_sync_upstream_removal.py@@ -177,9 +177,8 @@ def test_nothing_is_removed_when_upstream_removed_nothing(tmp_path: Path):def _refuse_rm(tmp_path: Path, target: Path) -> Path:- """A `rm` earlier on PATH that fails for one path, the way a writable single-FILE- bind mount fails with EBUSY. The publish above already works around that case for- rename, so it is not hypothetical here."""+ """Stubs rm earlier on PATH to fail for one path, as a writable single-file bind mount does with+ EBUSY; the publish already works around that case for rename."""bindir = tmp_path / "bin"bindir.mkdir(exist_ok = True)stub = bindir / "rm"@@ -197,10 +196,8 @@ def _refuse_rm(tmp_path: Path, target: Path) -> Path:@behaviouraldef test_a_removal_that_cannot_be_unlinked_keeps_its_record_and_retries(tmp_path: Path):- """Ignoring the failure dropped the record while leaving the file, which is the- exact state the removal exists to prevent: the next refresh reads the stale copy as- user-owned and never tries again. It also left `failed` at zero, so the sync marker- was stamped and the next start exited before it looked."""+ """A removal that fails must keep its record and retry: dropping it leaves the stale copy read+ as user-owned forever, and failed stays zero so the sync marker is stamped."""remote, template, dest = _setup(tmp_path)_advance(remote)(dest / "nb" / "edited.ipynb").write_text("MY OWN WORK", encoding = "utf-8")@@ -244,9 +241,8 @@ def test_the_successful_removal_still_stamps_the_commit(tmp_path: Path):def _refuse_mv_to(tmp_path: Path, target: Path) -> Path:- """An `mv` earlier on PATH that fails for one destination, the way a full or- read-only /workspace fails when the state file is published. Every other move,- including the same-dir rename each notebook is published with, passes through."""+ """Stubs mv earlier on PATH to fail for one destination, as a full or read-only /workspace does+ when the state file is published; other moves pass through."""bindir = tmp_path / "bin"bindir.mkdir(exist_ok = True)stub = bindir / "mv"@@ -264,11 +260,8 @@ def _refuse_mv_to(tmp_path: Path, target: Path) -> Path:@behaviouraldef test_a_state_that_cannot_be_published_holds_the_sync_marker(tmp_path: Path):- """Stamping the commit over a failed state publish wedges the tree permanently.- The next boot exits on remote == last, and once upstream moves again the stale- hashes no longer match the notebooks this run wrote, so all of them read as- user-edited and are never updated again. `failed` already holds the marker back- for a notebook that could not be written; the state file has to count too."""+ """Stamping the commit after a failed state publish wedges the tree, as stale hashes read every+ notebook as user-edited; the state failure must hold the marker like failed does."""remote, template, dest = _setup(tmp_path)_advance(remote)before = _state(dest)@@ -287,14 +280,8 @@ def test_a_state_that_cannot_be_published_holds_the_sync_marker(tmp_path: Path):@behaviouraldef test_the_state_temp_file_is_published_by_a_same_directory_rename(tmp_path: Path):- """Holding the marker is not on its own enough, which is why the temp file sits- beside the state file rather than in /tmp. The notebooks are published BEFORE the- state is, so a publish that fails on its own leaves disk ahead of state, and no- marker check undoes that: the next run reads every notebook it just wrote as- user-edited, because they no longer hash to the stale record. A sibling makes the- publish an atomic rename and makes it fail WITH the notebook writes, which already- hold the marker. Asserted on the script text because the failure it removes cannot- be provoked once the rename is atomic."""+ """The state temp file must sit beside the state file so publishing it is an atomic rename;+ notebooks publish first, so a standalone state publish failure leaves disk ahead of state."""source = SYNC.read_text(encoding = "utf-8")assert 'TMPSTATE="$STATE.tmp"' in source, ("the refresh state temp file left $DEST, so publishing it is a cross-device "@@ -322,14 +309,8 @@ def test_a_published_state_still_stamps_the_commit(tmp_path: Path):@behaviouraldef test_an_unwritable_dest_publishes_nothing_and_recovers(tmp_path: Path):- """$DEST unwritable while a notebook subdir still is, which is the container shape:- the image bakes the root and only the subdirs get chowned to the host user.-- Staging the state in /tmp here would publish the new notebook bytes and then be- unable to record them. Run two reads every one of them as a user edit, and a user- edit counts as `kept`, not `failed`, so the marker IS stamped and the whole managed- set is stranded permanently. Nothing is published yet at that point, so the refresh- must bail and leave the tree exactly as it was."""+ """With DEST unwritable but its notebook subdirs writable (the container shape), staging in /tmp+ would publish bytes it cannot record; the refresh must bail before publishing."""remote, template, dest = _setup(tmp_path)_advance(remote)before_state = _state(dest)@@ -360,12 +341,8 @@ def test_an_unwritable_dest_publishes_nothing_and_recovers(tmp_path: Path):@behaviouraldef test_a_stale_state_temp_file_does_not_block_the_refresh_forever(tmp_path: Path):- """The bail above must not become permanent. A run killed between the truncate and- the mv leaves $STATE.tmp behind, and if that run was a different uid (root once,- then --user) the file cannot be truncated even though $DEST is writable. Bailing- then would strand the tree on every future start, which is the failure the bail- exists to prevent. Unlinking needs write on $DEST, which the real bail case does- not have, so clearing it first cannot weaken the guard."""+ """A stale $STATE.tmp left by a run under another uid must not block the refresh forever;+ unlinking it needs write on DEST, which the real bail case lacks, so the guard holds."""remote, template, dest = _setup(tmp_path)_advance(remote)diff --git a/tests/python/test_docker_nvidia_toolkit_install.py b/tests/python/test_docker_nvidia_toolkit_install.pyindex de465ce7924..36fc641fd6c 100644--- a/tests/python/test_docker_nvidia_toolkit_install.py+++ b/tests/python/test_docker_nvidia_toolkit_install.py@@ -536,9 +536,8 @@ def test_docker_desktop_on_macos_says_cpu_only(tmp_path: Path):def test_macos_says_cpu_only_whatever_runs_the_daemon(tmp_path: Path):- """colima and Rancher Desktop keep their socket outside /var/run, which took a Mac- to the endpoint check: it told the user to configure that daemon by hand, for a- toolkit no Mac can use."""+ """On macOS, colima and Rancher Desktop sockets sit outside /var/run, so the endpoint check must+ not ask users to configure a daemon for a toolkit no Mac can use."""_, _, env = _setup(tmp_path, driver = False, uid = 1000)_stub(tmp_path / "bin" / "uname", 'if [ "$1" = -s ]; then echo Darwin; else echo arm64; fi\n')res = _run(env, extra_env = {"DOCKER_HOST": "unix:///Users/u/.colima/default/docker.sock"})@@ -685,8 +684,7 @@ def test_a_mac_never_asks_the_daemon_which_backend_it_is(tmp_path: Path):def test_a_mac_with_an_uninspectable_context_gets_the_error_not_nothing_to_install(tmp_path: Path):- """Same rule as the endpoint check further down: a context lookup failure is an- error, not a local daemon."""+ """As in the endpoint check further down, a context lookup failure is an error, not a local daemon."""_, _, env = _setup(tmp_path, driver = False, uid = 1000)_stub(tmp_path / "bin" / "uname", 'if [ "$1" = -s ]; then echo Darwin; else echo arm64; fi\n')res = _run(env, extra_env = {"DOCKER_CONTEXT": "missing-in-root-config"})diff --git a/tests/python/test_docker_publish_ref_freeze.py b/tests/python/test_docker_publish_ref_freeze.pyindex 18dad4ba0a8..41c9ed9ac33 100644--- a/tests/python/test_docker_publish_ref_freeze.py+++ b/tests/python/test_docker_publish_ref_freeze.py@@ -554,10 +554,8 @@ def test_the_digest_export_refuses_another_runs_manifest(manifest_digest_step: sdef test_the_digest_export_accepts_the_flattened_per_arch_indexes(manifest_digest_step: str, tmp_path: Path):- """The real shape: each build leg pushed an index (image + attestation), and the- merged index carries those CHILDREN, never the per-arch index digests the- artifact files are named after. Runs 33935929946 and 33936467156 published a- correct :core and then failed here, which skipped the Studio build."""+ """The merged index carries the children of each per-arch index, not the index digests the+ artifact files are named after; rejecting that shape skipped the Studio build."""bin_dir = tmp_path / "bin"_docker_stub(bin_dir,diff --git a/tests/python/test_docker_rocm.py b/tests/python/test_docker_rocm.pyindex 6dd5cda6945..c0aef72e2fc 100644--- a/tests/python/test_docker_rocm.py+++ b/tests/python/test_docker_rocm.py@@ -637,9 +637,8 @@ class TestRocmEntrypoint:)def test_dxg_torch_failure_gives_bridge_advice_not_amdgpu_advice(self, tmp_path):- """WSL has no host amdgpu stack, so the rocm-smi / dkms / rebuild-against-the-host- advice is wrong there; the bridge has its own two causes (measured: the libdxcore- mount, and the Windows driver)."""+ """WSL has no host amdgpu stack, so rocm-smi, dkms and rebuild advice is wrong there; the+ librocdxg bridge has its own two causes: the libdxcore mount and the Windows driver."""rc, ran, err = self._dxg_with_torch(tmp_path,["librocprofiler-register.so"],diff --git a/tests/python/test_docker_studio_home_volume.py b/tests/python/test_docker_studio_home_volume.pyindex 65e294763c3..a160d51d92f 100644--- a/tests/python/test_docker_studio_home_volume.py+++ b/tests/python/test_docker_studio_home_volume.py@@ -102,9 +102,8 @@ def test_a_volume_from_an_earlier_image_runs_this_images_code(tmp_path):def test_nothing_in_the_way_is_deleted_it_is_kept_aside(tmp_path):- """What an earlier image left, or what the user put under a code entry's name, is- a rename away, not gone: the old venv, the old source tree with an uncommitted- file, a real file where the lock is, and a link the user pointed elsewhere."""+ """Anything in the way (an old venv, an old source tree with an uncommitted file, a real file+ where the lock is, a user link) is renamed aside, never deleted."""app = _app(tmp_path)home = _legacy_home(tmp_path)(home / "bin").mkdir()@@ -196,11 +195,8 @@ def test_restore_without_a_legacy_dir_or_an_app_dir_says_which_image_to_use(tmp_def test_the_restore_hint_this_file_expects_is_the_one_the_script_prints() -> None:- """Catch a copy edit at the source, not as a mismatch in someone else's run.-- The test above compares against stderr, so when the wording moves it fails with two long- strings and no indication that the fix is one line of shell. This names the file.- """+ """Catches a reworded restore hint at the source: the linker must still print+ RESTORE_NEEDS_APP_HINT, and the failure names the file to update."""assert RESTORE_NEEDS_APP_HINT in LINKER.read_text(encoding = "utf-8"), (f"{LINKER.relative_to(REPO)} no longer prints {RESTORE_NEEDS_APP_HINT!r}. If the wording "f"changed on purpose, update RESTORE_NEEDS_APP_HINT here to match."diff --git a/tests/python/test_docker_studio_launch_view_config.py b/tests/python/test_docker_studio_launch_view_config.pyindex 74dc3813f92..487808b9968 100644--- a/tests/python/test_docker_studio_launch_view_config.py+++ b/tests/python/test_docker_studio_launch_view_config.py@@ -107,12 +107,8 @@ def test_the_generator_does_not_interpolate_the_paths_in_the_shell(generator: st@behaviouraldef test_the_heredoc_form_this_replaced_really_was_broken(tmp_path: Path):- """Pin the premise, so the test above is not guarding a hypothetical.-- Reproduces the previous construct exactly: an unquoted heredoc interpolating- the value into a Python string literal. With a double quote in the path the- generated config does not parse, which is JupyterLab failing to start.- """+ """Pins the premise: the old unquoted heredoc interpolated the path into a Python string+ literal, so a double quote in the path broke JupyterLab startup."""name = 'My "Special" Notebooks'script = tmp_path / "old.sh"script.write_text(diff --git a/tests/python/test_docker_studio_password_banner.py b/tests/python/test_docker_studio_password_banner.pyindex 4fd8a899317..83c3b1808be 100644--- a/tests/python/test_docker_studio_password_banner.py+++ b/tests/python/test_docker_studio_password_banner.py@@ -121,9 +121,8 @@ def test_the_generated_password_is_printed_once_studio_writes_it(tmp_path: Path)@behaviouraldef test_a_stale_file_from_an_interrupted_launch_is_not_printed(tmp_path: Path):- """The CLI writes the bootstrap file before committing the admin row. A launch- interrupted between the two leaves a file whose password the next launch- replaces, so the file is read only once the row exists."""+ """The CLI writes the bootstrap file before committing the admin row, so an interrupted launch+ leaves a stale file; the wrapper reads it only once the row exists."""auth = tmp_path / "auth"auth.mkdir()(auth / ".bootstrap_password").write_bytes(b"stale one\n")@@ -303,9 +302,8 @@ def _run_wrapper(def test_stored_means_an_admin_row_whose_password_was_changed(tmp_path: Path, db: str, stored: bool):- """A bare auth.db from an interrupted first launch, or a seeded row nobody- changed, still accepts an initial password; only must_change_password=0 is- "stored"."""+ """A bare auth.db from an interrupted first launch, or a seeded admin row nobody changed, still+ accepts an initial password; only must_change_password=0 counts as stored."""if db == "empty":_auth_db(tmp_path, must_change = None)elif db == "seeded":@@ -487,9 +485,8 @@ def test_the_image_wires_the_scripts_in():def test_the_summary_is_coloured_unless_no_color_is_set(tmp_path: Path):- """The block is the one thing worth reading in a long startup log; plain text- left it indistinguishable from the supervisord and Jupyter lines around it.- NO_COLOR (no-color.org) is the documented way off, for log collectors."""+ """The summary block is coloured so it stands out in a long startup log beside supervisord and+ Jupyter lines; NO_COLOR is the documented way to turn colour off."""env = {"UNSLOTH_STUDIO_PASSWORD_STATE": "generated"}a, b = tmp_path / "a", tmp_path / "b"a.mkdir()diff --git a/tests/python/test_docker_studio_rocm_jupyter.py b/tests/python/test_docker_studio_rocm_jupyter.pyindex b8208887f84..d8d2e39c219 100644--- a/tests/python/test_docker_studio_rocm_jupyter.py+++ b/tests/python/test_docker_studio_rocm_jupyter.py@@ -293,9 +293,8 @@ def test_the_entrypoint_syncs_the_notebooks_before_every_exec():def test_the_publisher_passes_every_build_arg_the_final_stage_declares():- """Each ARG after the final FROM is a ref a RUN layer is keyed on. One the- publisher leaves at its default bakes a mutable 'main' that docker matches on- the next run, so the published image would carry the first build's bits."""+ """Every ARG after the final FROM keys a RUN layer; one left at its default bakes a mutable main+ ref that docker matches on the next run, so the image would carry old bits."""import yamltext = _read(ROCM_STUDIO)diff --git a/tests/python/test_docker_update_helpers.py b/tests/python/test_docker_update_helpers.pyindex b3973cf5bc1..6bbdcf6479b 100644--- a/tests/python/test_docker_update_helpers.py+++ b/tests/python/test_docker_update_helpers.py@@ -56,9 +56,8 @@ def _studio_env(src_link: bool = False,restart_exit: int = 0,) -> dict:- """A Studio home whose venv python is the real interpreter over a fake `studio`- package, so the script's own import and frontend checks run for real. pip,- supervisorctl, git and the bundled npm are recording stubs."""+ """Builds a Studio home whose venv runs the real interpreter over a fake studio package so+ import and frontend checks run; pip, supervisorctl, git and npm are recording stubs."""home = tmp_path / "studio"site = tmp_path / "site"(site / "studio" / "backend").mkdir(parents = True)@@ -208,9 +207,8 @@ def test_studio_update_restarts_a_studio_that_is_not_running(tmp_path: Path, stadef test_studio_update_fails_when_supervisor_cannot_restart_studio(tmp_path: Path):- """A restart that fails used to leave the new install in place with Studio down and- the previous tree already deleted. The previous tree is kept until the service is- up, so a failed restart puts it back and starts that."""+ """The previous tree is kept until the service is up, so a failed restart puts it back and+ starts that tree again instead of leaving Studio down."""env = _studio_env(tmp_path, restart_exit = 1)res = _run(STUDIO_UPDATE, ["--ref", "main"], env)home = Path(env["UNSLOTH_STUDIO_HOME"])@@ -360,9 +358,8 @@ def test_studio_update_rollback_keeps_the_editable_uri_pip_recorded(tmp_path: Padef test_studio_update_ref_restores_the_tree_when_interrupted_after_the_swap(tmp_path: Path):- """Ctrl-C or `docker stop` between the swap and the checks left the half-installed- tree in place and the previous one beside it as .src-prev.*, which the next- container start links into the Studio home."""+ """An interrupt (Ctrl-C or docker stop) between the swap and the checks left the half-installed+ tree and the old one as .src-prev entries, which the next start links into the Studio home."""env = _studio_env(tmp_path)env["STUB_PIP_INTERRUPT"] = "1"res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)@@ -392,9 +389,8 @@ def test_studio_update_release_restores_the_pins_when_interrupted_during_pip(tmpdef test_studio_update_restores_once_and_leaves_no_temp_files_when_signalled_mid_restore(tmp_path: Path,):- """After a failed tree check the script restores explicitly, then exits; the exit- trap must not restore a second time, and a signal during the restore must not skip- the temp-file cleanup."""+ """After a failed tree check the script restores explicitly, so the exit trap must not restore a+ second time and a signal mid-restore must not skip temp-file cleanup."""env = _studio_env(tmp_path, dist_ok = False)env["STUB_PIP_INTERRUPT_RESTORE"] = "1"tmpd = tmp_path / "tmpd"@@ -509,9 +505,8 @@ def test_studio_update_puts_the_install_back_when_pip_itself_fails(tmp_path: Patdef test_a_signal_during_the_health_wait_puts_the_service_back_too(tmp_path: Path):- """Ctrl-C while waiting for /api/health: the service is already running the new- code, so restoring the files alone would leave it serving a mix of versions.- The cleanup restarts it on the restored install, as back_out does."""+ """A Ctrl-C while waiting for /api/health must restart the service on the restored install, as+ back_out does, since restoring files alone leaves a mix of versions."""env = _studio_env(tmp_path)env["UNSLOTH_STUDIO_UPDATE_HEALTH_WAIT"] = "30"_stub(@@ -615,9 +610,8 @@ def test_studio_update_health_wait_zero_commits_once_the_restart_command_succeeddef test_studio_update_clears_leftovers_of_a_killed_run_before_it_starts(tmp_path: Path):- """`docker stop` ends in SIGKILL, so no trap ran: a previous tree can sit beside src- with a pid-derived name that a later run could reuse (mv would nest into it) and a- staging tree can sit there with its node_modules."""+ """SIGKILL from docker stop runs no trap, so leftover previous and staging trees can sit beside+ src; a pid-derived name could be reused and mv would nest into it."""env = _studio_env(tmp_path)home = Path(env["UNSLOTH_STUDIO_HOME"])(home / ".src-prev.4242" / "junk").mkdir(parents = True)@@ -660,9 +654,8 @@ def test_studio_update_puts_back_a_previous_tree_a_killed_run_never_committed(tmdef test_studio_update_reads_the_install_record_from_the_venv_not_the_cwd(tmp_path: Path):- """`python -` searches the caller's cwd first, so a checkout there with its own- dist-info would answer for the venv's installed unsloth and a rollback would- reinstall the wrong thing."""+ """python - searches the current directory first, so a checkout there with its own dist-info+ would answer for the venv's unsloth and a rollback would reinstall the wrong thing."""env = _studio_env(tmp_path, import_ok = False)site = tmp_path / "site"info = site / "unsloth-2026.9.4.dist-info" # seeded by _studio_env@@ -684,9 +677,8 @@ def test_studio_update_reads_the_install_record_from_the_venv_not_the_cwd(tmp_padef test_studio_update_records_every_packages_target_for_the_rollback(tmp_path: Path):- """--packages can name more than unsloth and unsloth_zoo; a restore that put only- those two back would leave the extra target upgraded, or newly installed, while- reporting the previous install is back."""+ """--packages can name targets beyond unsloth and unsloth_zoo; the rollback must record all of+ them, or an extra target stays upgraded while the restore reports success."""env = _studio_env(tmp_path, import_ok = False)site = tmp_path / "site"info = site / "bar-1.0.dist-info"@@ -715,9 +707,8 @@ def test_studio_update_with_deps_stops_when_the_dependency_snapshot_fails(tmp_padef test_studio_update_finishes_the_package_restore_a_killed_run_left(tmp_path: Path):- """SIGKILL after pip had replaced the packages but before the commit: the record- kept beside the tree says what to put back, and the next run does that before it- records anything as the previous install."""+ """SIGKILL after pip replaced packages but before the commit leaves a rollback record beside the+ tree; the next run finishes that restore before recording a new previous install."""env = _studio_env(tmp_path)home = Path(env["UNSLOTH_STUDIO_HOME"])(home / ".src-update.rollback").write_text("-e file:///opt/prev-src\n# absent: foo\n")@@ -758,9 +749,8 @@ def test_studio_update_recovery_puts_the_service_on_the_restored_install(def test_studio_update_with_deps_rollback_fails_when_pip_cannot_list_packages(tmp_path: Path):- """The list of what the update pulled in comes from a second `pip freeze`; when- that fails, nothing would be removed, so the restore is reported as unfinished- and the record stays."""+ """The packages the update pulled in come from a second pip freeze; if that fails nothing can be+ removed, so the restore is reported unfinished and the record stays."""env = _studio_env(tmp_path, import_ok = False)env["STUB_FREEZE_EXIT_AFTER"] = "1"res = _run(STUDIO_UPDATE, ["--with-deps", "--no-restart"], env)@@ -774,9 +764,8 @@ def test_studio_update_with_deps_rollback_fails_when_pip_cannot_list_packages(tmdef test_recover_finishes_a_killed_update_and_does_nothing_else(tmp_path: Path):- """The container start runs --recover before supervisord starts Studio: a previous- tree beside src goes back over the unverified one, the recorded packages are- reinstalled, and no update is attempted."""+ """The container start runs --recover before supervisord starts Studio: a previous tree goes+ back over the unverified src, recorded packages are reinstalled, and no update runs."""env = _studio_env(tmp_path)home = Path(env["UNSLOTH_STUDIO_HOME"])(home / "src" / "OLD_TREE").unlink()@@ -829,9 +818,8 @@ def test_studio_update_keeps_the_lock_file(tmp_path: Path):def test_studio_update_treats_a_previous_tree_without_a_record_as_scratch(tmp_path: Path):- """The record is unlinked before the previous tree is deleted, so a previous tree- with no record is a committed update that was killed mid-delete, and src is the- tree that passed the health check."""+ """The record is unlinked before the previous tree is deleted, so a previous tree without a+ record is scratch from a committed update killed mid-delete; src is the healthy tree."""env = _studio_env(tmp_path)home = Path(env["UNSLOTH_STUDIO_HOME"])(home / ".src-prev.abc123" / "studio").mkdir(parents = True)@@ -1113,9 +1101,8 @@ def test_fetcher_normalizes_the_base_build_for_the_marker_tag(release_tag, expecdef test_a_failed_studio_update_puts_the_previous_install_back(tmp_path: Path):- """Not restarting protected only the code the running process had already- imported; the venv on disk stayed replaced, so any lazy import or later restart- failed the same way. The update now reinstalls exactly what it started from."""+ """Not restarting protected only already-imported code while the venv stayed replaced, so lazy+ imports and later restarts failed; a failed update now reinstalls its starting set."""env = _studio_env(tmp_path, import_ok = False)res = _run(STUDIO_UPDATE, [], env)assert res.returncode != 0, "a broken update must not report success"diff --git a/tests/python/test_e2e_no_torch_sandbox.py b/tests/python/test_e2e_no_torch_sandbox.pyindex e5f84a195dc..70dc135d7c9 100644--- a/tests/python/test_e2e_no_torch_sandbox.py+++ b/tests/python/test_e2e_no_torch_sandbox.py@@ -730,8 +730,7 @@ class TestInstallShLogic:assert b"ERROR" in r.stderrdef test_python_version_resolution(self):- """Python version defaults to 3.12 on Intel Mac, 3.13 elsewhere.- --python overrides both."""+ """The Python version defaults to 3.12 on Intel Mac and 3.13 elsewhere; --python overrides both."""script = textwrap.dedent("""\MAC_INTEL="$1"_USER_PYTHON="$2"diff --git a/tests/python/test_embed_lm_head_target_modules_redirect.py b/tests/python/test_embed_lm_head_target_modules_redirect.pyindex ec7c0e75673..14d265fd51a 100644--- a/tests/python/test_embed_lm_head_target_modules_redirect.py+++ b/tests/python/test_embed_lm_head_target_modules_redirect.py@@ -218,9 +218,8 @@ def test_flipping_ensure_weight_tying_is_seen_as_a_different_request():@pytest.mark.slowdef test_a_classification_repeat_call_is_not_tripped_by_peft_added_modules():- """PeftModelForSequenceClassification.__init__ extends modules_to_save with- classifier/score unconditionally, so the stored config names modules the caller never- asked for. An unchanged request must still pass through."""+ """PeftModelForSequenceClassification.__init__ adds classifier and score to modules_to_save+ unconditionally, so an unchanged repeat request must still pass through."""from unsloth import FastLanguageModelcore = [m for m in TARGET_MODULES if m not in ("embed_tokens", "lm_head")]diff --git a/tests/python/test_fast_sentence_transformer_embedding_parity.py b/tests/python/test_fast_sentence_transformer_embedding_parity.pyindex 380a83ef7e8..b5f25cb4c2e 100644--- a/tests/python/test_fast_sentence_transformer_embedding_parity.py+++ b/tests/python/test_fast_sentence_transformer_embedding_parity.py@@ -11,9 +11,8 @@ import pytestdef test_transformer_load_signature_supports_unsloth_kwargs():- """Forwards-compat tripwire: a Hub-capable Transformer.load must accept the kwargs- the #6881 fix passes. Legacy ST 3.x/4.x expose load(input_path); the code falls back- to Transformer(...) there, so mirror that gate and skip."""+ """Tripwire: a Hub-capable Transformer.load must accept the kwargs the issue 6881 fix passes;+ legacy ST 3.x/4.x load(input_path) falls back to Transformer(...), so the test skips there."""models = pytest.importorskip("sentence_transformers.models")load = getattr(models.Transformer, "load", None)assert callable(load), (diff --git a/tests/python/test_import_without_bitsandbytes.py b/tests/python/test_import_without_bitsandbytes.pyindex d98709e6246..0e3bd4bad5a 100644--- a/tests/python/test_import_without_bitsandbytes.py+++ b/tests/python/test_import_without_bitsandbytes.py@@ -151,9 +151,8 @@ def test_bitsandbytes_guard_is_not_gated_on_use_exact_model_name():def test_bitsandbytes_guard_drops_a_bnb_quantization_config():- """A BitsAndBytesConfig in kwargs re-sets the flags downstream, so clearing- load_in_4bit/8bit alone still builds the bnb quantizer in Transformers. A- non-bnb config (GPTQ/AWQ/fp8) must not be touched."""+ """A BitsAndBytesConfig in kwargs re-sets the flags downstream, so clearing load_in_4bit and+ load_in_8bit alone still builds the bnb quantizer; GPTQ, AWQ or fp8 configs stay untouched."""_, guards = _bnb_guards()for guard in guards:# ast.unparse normalises quotes, so match on the call shape instead.diff --git a/tests/python/test_install_python_stack.py b/tests/python/test_install_python_stack.pyindex 6697ab402a6..f41a7a724f0 100644--- a/tests/python/test_install_python_stack.py+++ b/tests/python/test_install_python_stack.py@@ -558,9 +558,8 @@ class TestPinnedIndexClearsUvEnv:assert "UV_CONFIG_FILE" not in envdef test_pinned_cmd_disables_pip_config_files(self):- """devnull is the ONLY spelling that reaches a SITE or GLOBAL pip.conf. Measured- on pip 26.2: naming a real file suppresses the per-user file alone, so a- venv-level `no-index` still killed the pin."""+ """Only devnull reaches a SITE or GLOBAL pip.conf; measured on pip 26.2, naming a real file+ suppresses only the per-user file, so a venv-level no-index still killed the pin."""env = ips._install_env_for_cmd(["uv", "pip", "install", "torch", "--index-url", "https://x/cu128"])@@ -727,9 +726,8 @@ class TestHardenedPipConfigRelaxation:assert ips._install_env_for_cmd(["python", "-m", "ensurepip", "--upgrade"]) is Nonedef test_pinned_cmd_clears_hash_mode_only(self):- """Hash enforcement, which our unhashed requirements cannot satisfy, and nothing- else the operator hardened: dropping only-binary would let a compromised mirror- run a source build they had forbidden."""+ """Only hash enforcement is cleared, since unhashed requirements cannot satisfy it; other+ hardening such as only-binary stays, or a compromised mirror could run a source build."""with mock.patch.dict(os.environ, self.HOSTILE):env = ips._install_env_for_cmd(["uv", "pip", "install", "torch", "--index-url", "https://x/cu128"]@@ -959,9 +957,8 @@ class TestHardenedPipConfigRelaxation:@pytest.mark.reads_real_pip_configdef test_a_wedged_pip_costs_the_run_one_budget_not_one_per_command(self, monkeypatch):- """Failures are deliberately not memoised, so a transient miss cannot cost the- operator their cert for the whole run. Unbounded, a HANG paid the timeout once per- pinned command instead of once."""+ """Failures are not memoised, so a transient miss cannot cost the operator their cert; a+ wedged pip must spend one timeout budget for the whole run, not one per pinned command."""attempts = []def always_fails(cmd, **kwargs):@@ -979,9 +976,8 @@ class TestHardenedPipConfigRelaxation:@pytest.mark.reads_real_pip_configdef test_a_cheap_failure_does_not_spend_the_budget(self, monkeypatch):- """A fresh venv has no pip for the first part of the run. That answer is instant,- so budgeting it would mean the operator's cert is lost for the rest of the run the- moment pip does appear."""+ """A fresh venv has no pip at first and that answer is instant, so it must not spend the+ timeout budget, or the cert is lost once pip appears."""calls = []def missing_then_present(cmd, **kwargs):@@ -1293,9 +1289,8 @@ class TestProgressLineNotes:assert "\n\n" not in out, outdef test_uv_fallback_warning_does_not_glue_onto_the_bar(self):- """A real producer, not _note() directly: pip_install() warns on the uv- fallback while the bar for its own step is still open. This path survived- the first pass of the fix, which only converted ' message' call sites."""+ """Uses a real producer, not _note(): pip_install() warns on the uv fallback while its step+ bar is open; the first fix pass only converted ' message' call sites and missed it."""fake = mock.Mock(returncode = 1, stdout = "uv output")with (mock.patch.object(ips, "USE_UV", True),@@ -1475,9 +1470,8 @@ class TestBuildPipCmdUpgradeIntent:class TestDamagedCorePayloadRepair:- """An upgrade of a distribution already at the wanted version installs- nothing: uv audits it, pip calls it satisfied, and both read metadata a- quarantine of the payload leaves intact."""+ """An upgrade of a distribution already at the wanted version installs nothing: uv audits it and+ pip calls it satisfied, both reading metadata a payload quarantine leaves intact."""def test_the_uv_command_targets_only_the_named_package(self):cmd = ips._build_uv_cmd(@@ -1887,9 +1881,8 @@ class TestDuplicateCoreMetadataRepair:assert installs[0][2]["constrain"] is Falsedef test_the_repair_runs_again_before_the_manifest_is_written(self):- """The first pass runs before the core packages are installed, so an- upgrade that leaves a superseded record behind would survive it and- write_manifest would record a null version under a successful exit."""+ """The first repair pass runs before core packages install, so a superseded record left by+ an upgrade would survive it and write_manifest would record a null version."""source = inspect.getsource(ips.install_python_stack)first = source.index("_repair_duplicate_core_metadata")second = source.index("_repair_duplicate_core_metadata", first + 1)@@ -1983,9 +1976,8 @@ class TestDuplicateCoreMetadataRepair:assert calls[0][1]["input"] == b"unsloth-zoo"def test_a_falling_index_aborts_the_repair_rather_than_substituting(self, monkeypatch, capsys):- """uv fails the compile outright when a higher-priority index is unreachable,- which is the behaviour first-index exists to give: a public release must not- stand in for a private one just because the private mirror was down."""+ """uv fails the compile when a higher-priority index is unreachable, as first-index intends;+ a public release must not stand in for a private one just because its mirror is down."""self._uv_only(monkeypatch)monkeypatch.setattr(ips, "USE_UV", True)self._uv_plan(monkeypatch, returncode = 1)@@ -2030,11 +2022,9 @@ class TestDuplicateCoreMetadataRepair:),)def test_a_direct_reference_is_staged_as_written(self, monkeypatch, requirement):- """The overlay paths hand staging a git URL or a checkout, not a bare name.- Such a requirement is its own provenance -- no index chose it -- and uv- appends the resolved commit to what it emits, so asking uv would compare a- bare spec against a pinned one and never match, aborting every local- duplicate-zoo repair before it started."""+ """Overlay direct references (git URL or checkout) are their own provenance; uv appends the+ resolved commit, so asking it would never match and abort every local duplicate-zoo+ repair."""self._uv_only(monkeypatch)monkeypatch.setattr(ips, "USE_UV", True)calls = self._uv_plan(monkeypatch)@@ -2112,9 +2102,8 @@ class TestDuplicateCoreMetadataRepair:assert Path(ips._pip_config_without_sources(str(tmp_path))).read_text() == ""def test_uv_artifact_policy_is_replayed_from_its_configuration(self, monkeypatch):- """A no-binary or only-binary rule would otherwise change the artifact type- during the repair: a wheel downloaded under a no-binary rule, or an sdist- built under an only-binary one."""+ """A no-binary or only-binary rule must be replayed during repair, or the artifact type+ changes: a wheel downloaded under no-binary, or an sdist built under only-binary."""self._uv_only(monkeypatch)self._uv_plan(monkeypatch,@@ -2124,9 +2113,8 @@ class TestDuplicateCoreMetadataRepair:assert options == ["--only-binary", ":all:"]def test_the_env_spelling_of_the_artifact_policy_is_translated(self, monkeypatch):- """Measured on uv 0.10.7: --emit-build-options surfaces the policy from- uv.toml but not the environment-variable spelling, so that half is- translated by hand."""+ """On uv 0.10.7, --emit-build-options surfaces the policy from uv.toml but not the+ UV_ONLY_BINARY spelling, so that half is translated by hand."""self._uv_only(monkeypatch)monkeypatch.setenv("UV_ONLY_BINARY", ":all:")monkeypatch.delenv("PIP_ONLY_BINARY", raising = False)@@ -2217,9 +2205,8 @@ class TestDuplicateCoreMetadataRepair:assert ips._strip_userinfo(url) == baredef test_offline_still_stages_a_local_checkout(self, tmp_path, monkeypatch):- """--local hands the repair a checkout on disk. It needs no network, so- UV_OFFLINE has nothing to say about it, and refusing left the conflict in- place and failed the update for no reason."""+ """A --local checkout needs no network, so UV_OFFLINE does not apply to it; refusing would+ leave the conflict in place and fail the update for no reason."""self._uv_only(monkeypatch)monkeypatch.setattr(ips, "USE_UV", True)monkeypatch.setenv("UV_OFFLINE", "1")@@ -2294,9 +2281,8 @@ class TestDuplicateCoreMetadataRepair:assert "Version: 1.2.3" in writtendef test_a_record_without_a_manifest_fails_closed(self, tmp_path):- """No RECORD means neither pip nor this installer knows which files belong- to the package, so a replacement laid over them would leave whatever the new- release no longer ships behind."""+ """Without a RECORD, neither pip nor this installer knows which files belong to the package,+ so a replacement would leave files the new release drops behind."""record = tmp_path / "realpkg-1.2.3.dist-info"record.mkdir()(record / "METADATA").write_bytes(b"\xff\xfe")@@ -2623,9 +2609,8 @@ class TestDuplicateCoreMetadataRepair:assert "ci_source_overlay=ci_source_overlay" in sourcedef test_the_replacement_is_staged_before_any_record_is_removed(self, monkeypatch):- """The uninstall loop deletes every record, so the replacement has to be- in hand first. Otherwise an index that is unreachable at that moment- leaves the venv with no unsloth and nothing to reinstall from."""+ """The uninstall loop deletes every record, so the replacement must be staged first;+ otherwise an unreachable index leaves the venv with no unsloth to reinstall."""probes = iter((["2026.8.12", "2026.8.15"], ["2026.8.15"], [], ["2026.8.15"]))order = []@@ -2744,9 +2729,8 @@ class TestDuplicateCoreMetadataRepair:assert "Name: unsloth" in (backup / "METADATA").read_text()def test_staging_builds_a_wheel_so_the_offline_install_can_work(self):- """pip download leaves an sdist for a source-only index, and the install- that follows runs --no-index, so its isolated build cannot fetch- setuptools and the package stays uninstalled."""+ """pip download leaves an sdist for a source-only index, and the following --no-index+ install cannot fetch setuptools for its isolated build, so staging must build a wheel."""source = inspect.getsource(ips._stage_replacement).replace(" ", "")assert '"wheel",\n"--no-deps",' in sourceassert '"--wheel-dir",\nstaging,' in source@@ -2754,9 +2738,8 @@ class TestDuplicateCoreMetadataRepair:assert 'glob.glob(os.path.join(staging,"*.whl"))' in sourcedef test_a_git_overlay_is_staged_before_the_uninstall_loop(self, monkeypatch):- """--local pulls unsloth-zoo from git, so an overlay is a network fetch- too. Skipping staging for it meant an unreachable GitHub left the- package uninstalled."""+ """A --local overlay pulls unsloth-zoo from git, a network fetch too; skipping its staging+ meant an unreachable GitHub left the package uninstalled."""probes = {"unsloth-zoo": iter((["old", "new"], ["new"], [], ["new"]))}order = []@@ -2803,9 +2786,8 @@ class TestDuplicateCoreMetadataRepair:assert installs and "--find-links" in installs[0]def test_a_partial_uninstall_restores_the_payload(self, monkeypatch, capsys):- """The first uninstall deletes the package tree. Returning after a later- one fails would leave a dist-info claiming an install whose files are- gone."""+ """The first uninstall deletes the package tree, so a failure on a later one must restore+ the payload rather than leave a dist-info claiming files that are gone."""probes = iter((["a", "b", "c"], ["b", "c"]))uninstalls = iter([True, False])installs = []@@ -2885,11 +2867,9 @@ class TestDesktopBackendVersionConstraint:zoo = None,floors = None,):- """uv pip compile over a fake index: unsloth 2026.10.2..have, unsloth-zoo 2026.10.2..zoo.-- Each unsloth requires unsloth-zoo>=its own version unless *floors* says otherwise; the- zoo floor is only enforced when the probe resolves dependencies.- """+ """uv pip compile over a fake index (unsloth 2026.10.2..have, unsloth-zoo 2026.10.2..zoo);+ each unsloth requires its own zoo unless floors says otherwise; the zoo floor is enforced+ only when the probe resolves dependencies."""from packaging.requirements import Requirementdef releases(top):diff --git a/tests/python/test_installer_conda_path_guard.py b/tests/python/test_installer_conda_path_guard.pyindex ab58d513a3e..fca0fe287bb 100644--- a/tests/python/test_installer_conda_path_guard.py+++ b/tests/python/test_installer_conda_path_guard.py@@ -233,11 +233,8 @@ def _stub_registry(script: str) -> str:@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")@pytest.mark.parametrize("shell", POWERSHELLS)def test_the_session_refresh_keeps_an_active_conda_ahead_of_the_user_path(shell: str):- """The case #5871 is about, in the prompt the user is standing in.-- Without this the message that conda keeps priority is false for the rest of that- session: the registry ordering is right and the live PATH is not.- """+ """The issue 5871 case: an active conda in the user's shell must stay ahead in the live session+ PATH, since the registry ordering can be right while the live PATH is not."""script = _stub_registry(_refresh_preamble(f"{_CONDA_ENTRIES};{MACHINE}"))out = _run(shell,@@ -366,9 +363,8 @@ def test_a_name_only_activation_keeps_the_session_it_already_had(shell: str):@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")@pytest.mark.parametrize("shell", POWERSHELLS)def test_a_prefix_activation_still_takes_the_precise_route(shell: str):- """The whole-PATH fallback is for the case where nothing better can be known, so an- activation that DOES name its prefix must keep the targeted behaviour: only the conda- entries move, and an unrelated directory that happened to be on PATH does not."""+ """The whole-PATH fallback is only for when no prefix is known; an activation that names its+ prefix moves only the conda entries, leaving unrelated PATH directories alone."""previous = f"C:\\tools\\bin;{CONDA_ROOT}\\envs\\ml\\Scripts"script = _stub_registry(_refresh_preamble(previous))out = _run(diff --git a/tests/python/test_installer_differential_comparer.py b/tests/python/test_installer_differential_comparer.pyindex 92eaf927680..2dc47eb7460 100644--- a/tests/python/test_installer_differential_comparer.py+++ b/tests/python/test_installer_differential_comparer.py@@ -596,9 +596,8 @@ def test_a_renamed_launcher_marker_inside_unsloth_cmd_is_reported(tmp_path: Pathdef test_a_version_drift_inside_a_shortcut_is_printed_even_though_it_is_normalised(tmp_path: Path,) -> None:- """normalise_line runs on shortcut fields too, so a launcher retargeted at a different python- is erased in exactly the same way a patch release is. That is the right call and the wrong one- to make silently, so wherever the rule reaches, the drift is said out loud."""+ """normalise_line also erases a shortcut launcher retargeted at another python, just as it+ erases patch releases, so drift the rule reaches must still be printed."""base = _write(tmp_path / "base")retargeted = [dict(diff --git a/tests/python/test_module_entry_point.py b/tests/python/test_module_entry_point.pyindex 90945ff274b..23cee6d3d5b 100644--- a/tests/python/test_module_entry_point.py+++ b/tests/python/test_module_entry_point.py@@ -178,12 +178,9 @@ def test_the_attached_np_short_is_still_canonicalised(monkeypatch):ids = ["module", "trampoline"],)def test_help_matches_the_console_script_under_a_narrow_encoding(argv_builder):- """rich draws box characters cp1252 cannot encode; --help must still agree.-- -X utf8 is dropped for this case on purpose: it would hand the child a utf- stream anyway, which is exactly the situation the stream guard in- unsloth_cli/__init__ does not need to handle.- """+ """rich draws box characters cp1252 cannot encode, so --help must still match; -X utf8 is+ dropped on purpose since it would give the child a utf stream the stream guard in+ unsloth_cli/__init__ does not need to handle."""strip = ("-X", "utf8")argv = [arg for arg in argv_builder("--help") if arg not in strip]env = dict(os.environ)@@ -220,13 +217,9 @@ def test_the_module_entry_source_keeps_its_two_load_bearing_details():@requires_this_checkout_installeddef test_the_advertised_module_route_ignores_a_shadowing_directory(tmp_path):- """`-m` resolves the package before __main__.py runs, so -I is load bearing.-- A shell sitting in a directory that has an `unsloth_cli` folder is not exotic:- it is anyone standing in an unsloth checkout. Without -I that copy wins and the- printed recovery command drives the wrong install, which nothing inside- __main__.py can detect or undo.- """+ """-m resolves the package before __main__.py runs, so -I is load-bearing: without it a+ shadowing unsloth_cli folder in the cwd wins and the printed recovery command drives the+ wrong install."""shadow = tmp_path / "unsloth_cli"shadow.mkdir()(shadow / "__init__.py").write_text("app = None\n", encoding = "utf-8")diff --git a/tests/python/test_posix_only_marks_import_on_windows.py b/tests/python/test_posix_only_marks_import_on_windows.pyindex e6ae397fff6..891fbd08c52 100644--- a/tests/python/test_posix_only_marks_import_on_windows.py+++ b/tests/python/test_posix_only_marks_import_on_windows.py@@ -57,9 +57,8 @@ def _getattr_geteuid(node: ast.AST) -> ast.Call | None:def _lambda_accepts(lam: ast.Lambda, call: ast.Call) -> bool:- """Whether this lambda could take this call's arguments. True when the source does- not say (a `*args` at the call site, say), since a false alarm is worse than a miss- in a scan everybody has to keep green."""+ """Whether this lambda could take the call's arguments; a call with starred or keyword-unpacked+ arguments returns True, since a false alarm is worse than a miss."""if any(isinstance(arg, ast.Starred) for arg in call.args) or any(keyword.arg is None for keyword in call.keywords):@@ -82,9 +81,8 @@ def _lambda_accepts(lam: ast.Lambda, call: ast.Call) -> bool:def _fallback_takes(fallback: ast.AST, call: ast.Call) -> bool:- """Whether getattr's third argument survives being called this way on Windows. A- literal never does. A lambda is checked against the call. Anything else is taken at- its word, since whether a name is callable is not decidable from this file."""+ """Whether getattr's third argument survives this call on Windows: a literal never does, a+ lambda is checked against the call, and other expressions are taken at face value."""if isinstance(fallback, ast.Lambda):return _lambda_accepts(fallback, call)return not isinstance(@@ -480,9 +478,8 @@ def _flagged(source: str) -> list[int]:def test_an_os_name_guard_is_read_for_polarity_not_presence():- """`os.name == "posix" or os.geteuid() == 0` names the same attribute as the real- guard and spares nothing: on Windows the left side is false, so the call is reached.- A scan that matched the words alone would pass exactly this."""+ """os.name == 'posix' or os.geteuid() == 0 names the same attribute but spares nothing: on+ Windows the left side is false and the call is reached; a word-matching scan would accept it."""assert _flagged("import os, pytest\n"'@pytest.mark.skipif(os.name == "posix" or os.geteuid() == 0, reason = "x")\n'@@ -565,9 +562,8 @@ def test_a_statement_level_platform_guard_is_honoured():def test_a_getattr_fallback_has_to_be_callable():- """getattr(os, "geteuid", None)() picks None on Windows and raises TypeError there,- which Linux never shows because the real function is picked. A literal fallback is- no fallback."""+ """getattr(os, 'geteuid', None)() picks None on Windows and raises TypeError there, which Linux+ never shows since the real function is picked; a literal fallback is no fallback."""assert _flagged('import os\nROOT = getattr(os, "geteuid", None)() == 0\n')assert _flagged('import os\nROOT = getattr(os, "geteuid", 1)() == 0\n')assert not _flagged('import os\nROOT = getattr(os, "geteuid", lambda: 1)() == 0\n')@@ -584,8 +580,7 @@ def test_a_direct_import_fails_before_any_decorator_can_skip():def test_a_class_header_is_evaluated_where_the_class_is_written():- """Bases and keywords run at the `class`, exactly as a decorator does, and the body- was already traversed while they were not."""+ """Bases and keywords run at the class line, as a decorator does, so they are checked."""assert _flagged("import os\nclass C(Base if os.geteuid() else Other):\n pass\n")assert _flagged("import os\nclass D(metaclass = meta(os.geteuid())):\n pass\n")assert not _flagged(@@ -631,8 +626,7 @@ def test_a_non_callable_container_fallback_is_no_fallback():def test_an_invoked_fallback_lambda_runs_its_body_on_windows():- """`getattr(os, "geteuid", lambda: os.geteuid())()` picks the fallback there and runs- it, so its body is the one place Windows definitely reaches."""+ """On Windows getattr picks the lambda fallback and runs it, so its body is reached there."""assert _flagged('import os\nROOT = getattr(os, "geteuid", lambda: os.geteuid())() == 0\n')assert not _flagged('import os\nROOT = getattr(os, "geteuid", lambda: 1)() == 0\n')@@ -676,8 +670,7 @@ def test_an_annotation_is_a_string_under_the_future_import():def test_a_lambda_fallback_short_of_a_keyword_only_argument():- """**kwargs does not satisfy a required keyword-only parameter: Python still wants it- by name, so the fallback fails on Windows whatever it collects."""+ """**kwargs cannot fill a required keyword-only parameter; the fallback fails on Windows."""assert _flagged('import os\nROOT = getattr(os, "geteuid", lambda *, required, **kw: 1)() == 0\n')@@ -696,8 +689,7 @@ def test_a_negative_number_is_still_a_literal():def test_starred_unpacking_exhausts_the_generator_here():- """A star says outright that the generator is consumed on the spot, which a call- around it does not."""+ """A star unpacking consumes the generator on the spot, which a call around it does not."""assert _flagged("import os\nROOT = [*(os.geteuid() for _ in range(1))]\n")assert _flagged("import os\nROOT = f(*(os.geteuid() for _ in range(1)))\n")assert not _flagged("import os\nGEN = (os.geteuid() for _ in range(1))\n")@@ -755,8 +747,7 @@ def test_a_relative_import_is_not_the_stdlib_os():def test_an_eager_comprehension_advances_the_generator_it_iterates():- """A list, set or dict comprehension runs on the spot, so a generator it iterates is- advanced there too."""+ """A list, set or dict comprehension advances the generator it iterates on the spot."""assert _flagged("import os\nROOT = [x for x in (os.geteuid() for _ in range(1))]\n")assert _flagged("import os\nROOT = {x for x in (os.geteuid() for _ in range(1))}\n")assert not _flagged("import os\nGEN = (x for x in (os.geteuid() for _ in range(1)))\n")diff --git a/tests/python/test_prebuilt_cuda_wheels.py b/tests/python/test_prebuilt_cuda_wheels.pyindex 6c1633f4bfd..6c29480320f 100644--- a/tests/python/test_prebuilt_cuda_wheels.py+++ b/tests/python/test_prebuilt_cuda_wheels.py@@ -92,8 +92,7 @@ class TestWorkflowAndResolverAgree:assert checked == 6def test_every_url_the_resolver_can_emit_is_a_published_cell(self):- """Whatever the probe reports, a URL names a cell the publish matrix builds and the release- carries: (platform, torch, interpreter, package). Anything else is a 404 in front of the+ """Every URL the resolver emits must be a published cell, or it is a 404 in front of thefallback."""published = set()for platform in prebuilt_wheels.PLATFORMS:@@ -310,8 +309,7 @@ class TestOverrideScope:is None)- # win_amd64, win_arm64 and linux_aarch64 are published too, for fewer cells; the windows and arm- # resolver tests own them.+ # win_amd64, win_arm64 and linux_aarch64 are published too; their own tests cover them.@pytest.mark.parametrize("platform_tag", ["macosx_11_0_arm64", "linux_armv7l"])def test_no_wheel_for_an_unbuilt_platform(self, platform_tag):assert (@@ -680,13 +678,11 @@ def workflow():class TestWorkflow:def test_dispatch_only(self, workflow):- """It signs binaries and writes a release under our identity. A pull_request or push- trigger would put both behind whatever a fork can propose."""+ """Signs and releases as us, so pull_request or push triggers would let forks reach it."""assert set(triggers(workflow)) == {"workflow_dispatch"}def test_publishing_is_opt_in(self, workflow):- """A run that only builds, smoke tests and signs is the default, so the expensive and- irreversible half has to be asked for."""+ """Publishing is opt-in, since the expensive, irreversible half must be asked for."""inputs = triggers(workflow)["workflow_dispatch"]["inputs"]assert inputs["publish"]["default"] is Falseassert inputs["gpu_smoke"]["default"] is False@@ -721,8 +717,7 @@ class TestWorkflow:assert "pip install" not in bodydef test_it_never_becomes_the_latest_release(self, workflow):- """The repository's latest release is what the installers and the README resolve to.- A wheelhouse tag must not take it."""+ """Installers resolve the latest release, which a wheelhouse tag must not take."""body = json.dumps(workflow["jobs"]["publish"]["steps"])assert body.count("--latest=false") == 3assert "gh release create" in body@@ -742,8 +737,7 @@ class TestWorkflow:assert any(u.startswith("actions/attest-build-provenance@") for u in uses)def test_the_signature_is_verified_in_the_same_job(self, workflow):- """A bundle nobody checked is a bundle nobody can rely on, and it must verify against- the identity the release notes tell people to use."""+ """The bundle must verify against the identity the release notes tell people to use."""step = next(stepfor step in workflow["jobs"]["sign"]["steps"]@@ -806,8 +800,7 @@ class TestWorkflow:assert tuple(workflow["jobs"]["gpu-smoke"]["runs-on"]) in existingdef test_the_build_cannot_outlive_githubs_job_limit(self, workflow):- """A job that hits the 6 h cap is reported as cancelled with no logs. Both the step's- own timeout and the job's have to sit below it."""+ """A job at the 6 h cap is reported cancelled with no logs, so keep timeouts below it."""assert workflow["jobs"]["build"]["timeout-minutes"] < 360for spec in prebuilt_wheels.SPECS.values():minutes = int(spec["build_timeout"].removesuffix("m"))diff --git a/tests/python/test_pwsh_runner_encoding.py b/tests/python/test_pwsh_runner_encoding.pyindex 98fa0eccec7..e9862bede8b 100644--- a/tests/python/test_pwsh_runner_encoding.py+++ b/tests/python/test_pwsh_runner_encoding.py@@ -32,9 +32,7 @@ SAMPLES = {@pytest.mark.parametrize("shell", POWERSHELLS)@pytest.mark.parametrize("name", sorted(SAMPLES), ids = sorted(SAMPLES))def test_a_non_ascii_string_survives_the_round_trip(shell: str, name: str):- """The whole point. Built from code points inside PowerShell so the script itself stays- ASCII: a script that carried the character would be testing how the -Command argument is- encoded, which is a different pipe."""+ """Built from code points so the script stays ASCII, else it would test -Command encoding instead."""text = SAMPLES[name]literal = " + ".join(f"[char]::ConvertFromUtf32({ord(c)})" for c in text)done = run_pwsh(@@ -57,8 +55,7 @@ def test_a_non_ascii_string_survives_the_round_trip(shell: str, name: str):@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")@pytest.mark.parametrize("shell", POWERSHELLS)def test_the_prologue_adds_no_bom(shell: str):- """[Text.Encoding]::UTF8 carries a preamble; the one we set must not, or every caller's- first assertion sees a U+FEFF it did not print."""+ """The UTF-8 encoding we set must have no BOM, or every caller sees a stray U+FEFF first."""done = run_pwsh([shell, "-NoProfile", "-NonInteractive", "-Command", "Write-Output 'plain'"],check = True,@@ -72,9 +69,8 @@ def test_the_prologue_adds_no_bom(shell: str):@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")@pytest.mark.parametrize("shell", POWERSHELLS)def test_without_the_fix_the_same_string_does_not_survive(shell: str):- """The control. Same script, run the old way, on this host. It is allowed to pass -- a- box whose console is already UTF-8 was never broken -- so this asserts the two agree- when it does, and that the fixed one is right when they do not."""+ """Control runs the old invocation; a UTF-8 console may pass, so the two must agree then, and+ the fixed one must be right when they do not"""script = "Write-Output ('<' + [char]::ConvertFromUtf32(0x00e4) + '>')"argv = [shell, "-NoProfile", "-NonInteractive", "-Command", script]# pwsh_env, not run_pwsh: the control must call pwsh as call sites did before the prologue.@@ -145,8 +141,7 @@ def test_errors_alone_does_not_count_as_choosing_an_encoding():ids = ["-File", "no-command", "trailing-command"],)def test_an_invocation_with_no_script_string_still_gets_the_decode_half(argv):- """-File names a path, so there is nothing to prepend to. Decoding UTF-8 is still right- for pwsh 7, and is the only half available here."""+ """With -File there is no string to prepend to; only the UTF-8 decode half applies."""kwargs = {"text": True}assert _agree_on_utf8(list(argv), kwargs) == argvassert kwargs["encoding"] == "utf-8"diff --git a/tests/python/test_revision_forwarding.py b/tests/python/test_revision_forwarding.pyindex 59be51bd2de..c355b91f78a 100644--- a/tests/python/test_revision_forwarding.py+++ b/tests/python/test_revision_forwarding.py@@ -99,8 +99,7 @@ def test_llama_loads_forward_revision(callee, minimum):def test_llama_does_not_pass_revision_to_load_vllm():- """load_vllm has no `revision` parameter and load_vllm_kwargs is not filtered,- so putting one in that dict is an unconditional TypeError on the vLLM path."""+ """load_vllm takes no revision and kwargs are not filtered, so the key raises TypeError."""function = _function(_tree(LLAMA), "from_pretrained", "FastLlamaModel")dicts = [node.value@@ -385,8 +384,7 @@ def test_the_vllm_drop_only_fires_when_vllm_owns_the_weights():def test_the_tokenizer_revision_is_resolved_by_the_loader():- """The tokenizer repo is not always the base model's: a PEFT load whose- tokenizer_name is the adapter keeps the caller's ref, which the base model cannot."""+ """The tokenizer repo can be the PEFT adapter, so the caller's ref is kept for it."""tree = _tree(LOADER)helper = _function(tree, "_revision_for_tokenizer_repo")assert helper, "the loader must resolve the tokenizer repo's revision"@@ -454,16 +452,14 @@ def test_an_adapter_ref_never_reaches_the_base_tokenizer():def test_an_adapter_hosted_tokenizer_keeps_the_callers_ref():- """An adapter is a separate repo with its own history, so the caller's ref still- names it even though the base model it sits on cannot answer to it."""+ """An adapter is its own repo with its own history, so the caller's ref still names it."""gate = _load_tokenizer_gate()assert gate("org/adapter", "org/base", "org/adapter", "v2", None, True) == "v2"def test_a_remapped_plain_load_drops_the_tokenizer_pin_too():- """Naming the requested repo as tokenizer_name must not smuggle the ref back in: the- weights now come off a mirror's default branch, and a pinned tokenizer beside them is- the ref mismatch the gate exists to prevent. Only a PEFT adapter is a separate repo."""+ """A remapped plain load drops the tokenizer pin even when tokenizer_name is the requested repo,+ since its weights come off a default branch; only a PEFT adapter is a separate repo"""gate = _load_tokenizer_gate()assert gate("org/model", "unsloth/model-bnb-4bit", "org/model", "v2", None) is None@@ -537,8 +533,7 @@ def test_a_direct_llama_call_still_pins_its_tokenizer():],)def test_the_vllm_drop_clears_the_tokenizer_pin_too(path, cls, name):- """Clearing only the model pin left vLLM on the default branch while the tokenizer- stayed on the requested ref."""+ """Clearing only the model pin left vLLM on the default branch; the tokenizer kept the ref."""function = _function(ast.parse(path.read_text(encoding = "utf-8")), "from_pretrained", cls)clears = [n@@ -678,8 +673,7 @@ def test_the_fp8_quantizer_takes_the_requested_revision():def test_the_fp8_cache_name_is_revision_specific():- """A shared temp dir keyed only on the repo name would serve one ref's artifact to- another, and the artifact outlives the process that built it."""+ """A temp dir keyed only on the repo name would serve one ref's artifact to another ref."""function = _function(_tree(LOADER_UTILS), "_offline_quantize_to_fp8")writes = [n@@ -712,9 +706,7 @@ def test_both_loaders_hand_the_fp8_quantizer_the_revision():def test_the_vllm_drop_happens_before_the_config_probe():- """model_types, auto_model and the text-only decision all come off the probed config.- Reading it at a ref vLLM will not fetch picks the dispatch for a different model, so- the pin has to be gone before the probe, not just before the dispatch."""+ """Config probe must run unpinned: reading it at a ref vLLM will not fetch picks the wrong dispatch."""function = _function(_tree(LOADER), "from_pretrained", "FastModel")drops = [n@@ -765,9 +757,8 @@ def test_the_fp8_cache_key_survives_a_lossy_sanitization():def test_the_peft_probe_keeps_the_adapter_ref_under_vllm():- """The vLLM drop runs before is_peft is known. An adapter is loaded in-process by peft,- so zeroing its probe would read the default branch and either miss PEFT entirely or- resolve a different base model before attaching the pinned adapter."""+ """The vLLM drop runs before is_peft is known, so the PEFT probe keeps the adapter ref; zeroing+ it reads the default branch and may miss PEFT or resolve the wrong base model"""tree = _tree(LOADER)for class_name in ("FastLanguageModel", "FastModel"):function = _function(tree, "from_pretrained", class_name)@@ -786,8 +777,7 @@ def test_the_peft_probe_keeps_the_adapter_ref_under_vllm():def test_both_loaders_drop_the_vllm_pin_before_the_probe():- """model_types picks the architecture class off the probed config, so reading it at a- ref vLLM will not fetch dispatches the wrong one."""+ """The vLLM pin must go before the probe, or model_types picks the wrong architecture."""tree = _tree(LOADER)for class_name in ("FastLanguageModel", "FastModel"):function = _function(tree, "from_pretrained", class_name)diff --git a/tests/python/test_rl_config_pickling.py b/tests/python/test_rl_config_pickling.pyindex ee97ca6008b..dc41471b3d7 100644--- a/tests/python/test_rl_config_pickling.py+++ b/tests/python/test_rl_config_pickling.py@@ -79,8 +79,7 @@ def test_torch_save_load_round_trip(patched, tmp_path, use_pristine):def test_checkpoint_loads_without_unsloth(patched, tmp_path):- """The whole point of pickling under the TRL name: a checkpoint written here- has to open on a machine that only has transformers and TRL."""+ """Checkpoints pickled under the TRL name must open where only transformers and TRL exist."""torch = pytest.importorskip("torch")path = tmp_path / "training_args.bin"@@ -179,8 +178,7 @@ def test_every_patched_config_pickles_portably(tmp_path):def _assert_the_patch_applied(patched):- """Names the patcher on failure: a failed patch leaves trl.SFTConfig pristine and the tests- misreport."""+ """Fails with the cause when the patch fell back, so tests do not describe TRL's own class."""assert getattr(patched, "_unsloth_patched_rl_config", False), (f"trl.SFTConfig is {patched.__name__!r} from {patched.__module__!r} but carries ""no _unsloth_patched_rl_config, so Unsloth's RL patch fell back and these tests "@@ -190,8 +188,7 @@ def _assert_the_patch_applied(patched):def test_patched_config_still_subclasses_the_pristine_one(patched):- """The generated class is renamed onto TRL's name, which must not tempt a- later patching pass into making it its own base."""+ """The patched class takes TRL's name, so a later patch pass must not make it its own base."""_assert_the_patch_applied(patched)base = patched.__mro__[1]assert base is not patched@@ -247,8 +244,7 @@ def test_a_displaced_sibling_wrapper_is_covered(patched, tmp_path):def test_an_unrelated_class_is_not_reduced_through_the_patched_one(patched):- """Unrelated classes must not be rebuilt as the patched class, which would silently drop their- fields."""+ """Unrelated classes must not be rebuilt as the patched one, or their fields silently drop."""import copyregfrom unsloth.models.rl import _register_config_pickle_fallbackdiff --git a/tests/python/test_rocm_aotriton_gate.py b/tests/python/test_rocm_aotriton_gate.pyindex a47a058737e..acf1374f7a7 100644--- a/tests/python/test_rocm_aotriton_gate.py+++ b/tests/python/test_rocm_aotriton_gate.py@@ -31,8 +31,7 @@ def _gate_statement(path):def _open_gate(path, modules, environ):- """Exec the statement against a synthetic `sys.modules` / environ; running it rather than- grepping the source keeps a re-added guard visible."""+ """Runs the statement against fake sys.modules and environ, so a re-added guard is caught."""scope = {"os": types.SimpleNamespace(environ = environ),"sys": types.SimpleNamespace(modules = modules),diff --git a/tests/python/test_sign_wheel_binaries.py b/tests/python/test_sign_wheel_binaries.pyindex fbea3932ca8..7094c2b6698 100644--- a/tests/python/test_sign_wheel_binaries.py+++ b/tests/python/test_sign_wheel_binaries.py@@ -136,8 +136,7 @@ class TestSigningAWheel:assert mod.is_signed(z.read(name)), namedef test_an_already_signed_binary_is_left_alone(self, mod, tmp_path, fake_signer):- """delvewheel vendors Microsoft's redistributables into pyarrow already signed by- Microsoft. Re-signing one replaces their signature with ours."""+ """Vendored Microsoft DLLs arrive signed; re-signing would replace their signature."""original = _pe(signed = True)wheel = _wheel(tmp_path / "demo-1.0-cp313-cp313-win_arm64.whl",@@ -238,8 +237,7 @@ class TestTheRecordIsRegenerated:), "the fixture did not really change the bytes, so this proves nothing"def test_record_names_itself_without_a_digest(self, mod, tmp_path, fake_signer):- """PEP 376: RECORD cannot hash itself, and a tool that writes one anyway makes the- file self-contradictory."""+ """RECORD cannot hash itself (PEP 376); a digest makes the file contradict itself."""wheel = _wheel(tmp_path / "demo-1.0-cp313-cp313-win_arm64.whl",{@@ -292,8 +290,7 @@ class TestItRefusesRatherThanShipSomethingWrong:mod.sign_wheel(wheel, tmp_path / "out", failing)def test_a_signer_that_silently_does_nothing_fails_the_run(self, mod, tmp_path):- """Exit 0 with the file untouched is the dangerous case: it would publish an unsigned- wheel while every log line says it was signed."""+ """A signer that exits 0 but leaves the file untouched would publish an unsigned wheel."""wheel = _wheel(tmp_path / "demo-1.0-cp313-cp313-win_arm64.whl",{diff --git a/tests/python/test_ssm_kernels_install_python_stack.py b/tests/python/test_ssm_kernels_install_python_stack.pyindex ed1a687c66a..4b614c8c47b 100644--- a/tests/python/test_ssm_kernels_install_python_stack.py+++ b/tests/python/test_ssm_kernels_install_python_stack.py@@ -160,8 +160,7 @@ def test_no_torch_or_macos_skips_the_check(monkeypatch):@pytest.mark.parametrize("torch_imports", [False, None])def test_a_torch_that_does_not_import_keeps_every_kernel(monkeypatch, torch_imports):- # A half-finished repair or a transient failure in torch says nothing about the kernels, and an- # offline machine could not reinstall them.+ # A torch that fails to import says nothing about the kernels, so none are removed.host = _Kernels({"causal-conv1d": False, "mamba-ssm": False}, torch_imports = torch_imports)warnings = _run_stale_check(monkeypatch, host)assert host.removed == []diff --git a/tests/python/test_tokenizers_and_torch_constraint.py b/tests/python/test_tokenizers_and_torch_constraint.pyindex 6d2b771cc9b..68ded39a443 100644--- a/tests/python/test_tokenizers_and_torch_constraint.py+++ b/tests/python/test_tokenizers_and_torch_constraint.py@@ -97,8 +97,7 @@ class TestStructuralTorchConstraint:), f"{literal} hardcoded on a pip install line: {ln.strip()!r}"def test_gfx906_reroute_caps_below_211(self):- """The gfx906 / MI50 reroute must keep its literal sub-2.11 cap: the- rocm6.3 index it routes to serves no torch 2.11 wheel."""+ """gfx906 reroute keeps a literal sub-2.11 cap; rocm6.3 index has no torch 2.11 wheel."""assert self._sh.count('TORCH_CONSTRAINT="torch>=2.4,<2.11.0"') == 1def test_tightening_guarded_by_skip_torch(self):diff --git a/tests/python/test_torchcodec_torch_compat.py b/tests/python/test_torchcodec_torch_compat.pyindex 1aef3d2fe74..ae0bb157b41 100644--- a/tests/python/test_torchcodec_torch_compat.py+++ b/tests/python/test_torchcodec_torch_compat.py@@ -169,8 +169,7 @@ def _load_install_python_stack():def _reload_install_python_stack():- """A private instance: _PYTORCH_WHL_BASE is read from the environment at import, so the- cached module answers with whatever was set on first import."""+ """A fresh private module, since _PYTORCH_WHL_BASE is read from the environment at import."""import importlib.utilspec = importlib.util.spec_from_file_location(@@ -350,9 +349,8 @@ _INDEX_INVENTORY = {def test_torchcodec_index_follows_the_resident_torch_build():- """torchcodec ships one wheel per accelerator, so the right version from the wrong index- is a codec that cannot dlopen. Upstream's install docs say to pass --index-url and match- it to the torch build; docker/Dockerfile pins cu128 by hand for exactly this reason."""+ """torchcodec has one wheel per accelerator, so a version from the wrong index fails to dlopen;+ the index must match the torch build."""ips = _load_install_python_stack()base = "https://download.pytorch.org/whl/"assert ips._torchcodec_index_url("2.11.0+cu128") == base + "cu128"@@ -393,8 +391,7 @@ def _starved_index_cells():def test_pinning_the_index_starves_only_where_the_retry_covers_it():- """Pinning the index starves only cells the unpinned retry covers; a new starved cell fails this- test."""+ """Only cells the unpinned retry covers may starve from the pin; a new starved cell fails."""starved = {(tag, minor) for tag, minor, _ in _starved_index_cells()}assert starved == {("cu129", 9)}, sorted(starved)@@ -580,8 +577,7 @@ def test_compat_matrix_matches_the_published_upstream_table():def test_installer_never_selects_a_torchcodec_built_against_another_torch():- """Pip's window must exclude torchcodec releases built for another torch, since pip takes the- highest."""+ """Pip's window must skip torchcodec builds for other torch, since pip takes the highest."""from packaging.specifiers import SpecifierSetips = _load_install_python_stack()@@ -774,8 +770,7 @@ def test_the_installer_never_selects_a_spec_with_no_wheel_here(monkeypatch):)-# Hand-written answers; the sweep only checks against the history table.-# (host, python, torch minor, must the gate install?)+# Hand-written; the sweep checks only the history table. Columns: host, python, minor, install._WHEEL_GATE_ANCHORS = [("linux-aarch64", (3, 12), 11, True),("linux-aarch64", (3, 12), 10, False),@@ -829,8 +824,7 @@ def test_the_torchcodec_step_cannot_end_the_install():def test_the_runtime_hint_pins_the_index_it_tells_you_to_install_from(monkeypatch):- """The installer pins the torch index for torchcodec, so a remedy that omits it hands- back the wrong accelerator build and audio stays broken."""+ """The remedy must pin the torch index, or it hands back the wrong accelerator build."""import importlib.metadatafixes = _load_import_fixes_module()@@ -858,9 +852,8 @@ def test_the_runtime_hint_pins_the_index_it_tells_you_to_install_from(monkeypatcdef test_the_remedy_drops_the_extra_when_an_index_pin_is_needed(monkeypatch):- """An extra cannot carry an index: the marker picks the version, and putting- --index-url on the whole command would resolve unsloth itself from the torch index. On a- tagged venv the extra would hand back the same unloadable wheel the warning is about."""+ """An extra cannot carry an index, and --index-url on the whole command would resolve unsloth+ from the torch index; on a tagged venv the extra gives the unloadable wheel"""import importlib.metadatafixes = _load_import_fixes_module()@@ -1043,8 +1036,7 @@ def test_the_provenance_hint_does_not_assert_a_cause_it_has_not_established(monkdef test_the_remedy_uses_the_shell_of_the_host_it_prints_on(monkeypatch):- """PowerShell is Studio's supported Windows shell and does not expand `$NAME`, so the- POSIX spelling pasted there produced an empty `--index-url`."""+ """PowerShell does not expand `$NAME`, so the pasted POSIX form left --index-url empty."""import importlib.metadatafixes = _load_import_fixes_module()@@ -1070,9 +1062,8 @@ def test_the_remedy_uses_the_shell_of_the_host_it_prints_on(monkeypatch):def test_the_provenance_remedy_pins_the_compatible_window(monkeypatch):- """The accelerator indexes carry the whole codec line, so a bare `torchcodec` on a torch- 2.9 host installs the newest release there and trades a wrong-accelerator build for a- wrong-version one, leaving audio just as disabled."""+ """The accelerator indexes carry the whole codec line, so a bare `torchcodec` on torch 2.9 gets+ a wrong-version wheel and audio stays off; pin the compatible window."""import sysimport types@@ -1256,8 +1247,7 @@ def test_an_untagged_torch_without_an_explicit_index_stays_unpinned(monkeypatch)def test_the_installed_codec_reports_the_cuda_major_it_actually_links(monkeypatch, tmp_path):- """torchcodec 0.16.0 links libcudart.so.13 on PyPI and .12 on the cu126 leaf, so the NPP- choice reads the wheel rather than the torch tag."""+ """0.16.0 links libcudart.so.13 on PyPI, .12 on cu126; read the wheel, not the torch tag."""mod = _load_install_python_stack()class _Dist:@@ -1305,9 +1295,8 @@ def test_the_remedy_spells_the_variable_for_the_shell_it_will_be_pasted_into(mondef test_a_query_authenticated_mirror_is_not_pinned_at_all(monkeypatch):- """No URL shape pins a query-auth index, and building a broken one is worse than- declining: --index-url makes _install_env_for_cmd strip pip.conf and ~/.netrc, the only- channel that can carry that credential."""+ """No URL shape pins a query-auth index; declining beats a broken one, since --index-url makes+ _install_env_for_cmd strip pip.conf and ~/.netrc, the only credential channel."""for base in ("https://mirror.example/whl?token=abc", "https://mirror.example/whl#tok"):monkeypatch.setenv("UNSLOTH_PYTORCH_MIRROR", base)mod = _reload_install_python_stack()@@ -1515,9 +1504,8 @@ def test_every_pytorch_mirror_leaf_goes_through_the_guarded_helper():def test_an_explicit_family_is_honoured_when_torch_carries_no_tag(monkeypatch):- """As explicit as the full URL, and needed by the same host: a mirror that rebuilds torch- bare. _explicit_unknown_family_torch_index_url treats a custom leaf as authoritative, so a- None here is never corrected later."""+ """A mirror that rebuilds torch bare needs the explicit family; a None here is never corrected,+ since a custom leaf is authoritative."""monkeypatch.setenv("UNSLOTH_PYTORCH_MIRROR", "https://mirror.example/whl")monkeypatch.setenv("UNSLOTH_TORCH_INDEX_FAMILY", "current")mod = _reload_install_python_stack()diff --git a/tests/python/test_unsloth_pip_shim.py b/tests/python/test_unsloth_pip_shim.pyindex a0e206771e9..f3c674947dc 100644--- a/tests/python/test_unsloth_pip_shim.py+++ b/tests/python/test_unsloth_pip_shim.py@@ -450,9 +450,8 @@ class _FakeDist:def _fake_distributions(monkeypatch, *pairs):- """Pin what _protected_constraints_file sees as INSTALLED, else the assertions- depend on the ambient venv. The shim imports it inside the function, so patch- it at its source."""+ """Pin what _protected_constraints_file sees as installed, else assertions depend on the ambient+ venv; the shim imports it inside the function, so patch at its source."""monkeypatch.setattr("importlib.metadata.distributions",lambda **kw: [_FakeDist(n, v) for n, v in pairs],@@ -1051,8 +1050,7 @@ def test_protected_pins_ignore_a_sidecar_on_pythonpath(shim, tmp_path, monkeypatdef test_base_site_packages_never_returns_a_pythonpath_entry(shim, tmp_path, monkeypatch):- """sys.prefix cannot be influenced by PYTHONPATH, which is the property the pin- scoping relies on. A sidecar on sys.path must not appear in the scope."""+ """PYTHONPATH cannot change sys.prefix, which pin scoping needs; sidecars must not appear."""sidecar = _sidecar_dir(tmp_path / "sc", "5.5.0")monkeypatch.syspath_prepend(str(sidecar))scope = shim._base_site_packages()@@ -1252,8 +1250,7 @@ def test_a_separated_alias_value_is_not_read_as_a_target(shim, monkeypatch, argvdef test_an_alias_value_does_not_hide_uv_pip_sync(shim, monkeypatch):- """The sync refusal is found by the same positional walk, so a mis-parsed global- hid it too."""+ """The sync refusal uses the same positional walk, so a mis-parsed global hid it too."""_fake_distributions(monkeypatch, ("torch", "2.11.0"))with pytest.raises(SystemExit) as exc:_full_argv(shim, ["uv", "--python-preference", "system", "pip", "sync", "r.txt"])@@ -1323,8 +1320,7 @@ def test_the_uv_working_dir_env_moves_the_file_too(shim, monkeypatch, tmp_path):def test_the_directory_flag_wins_over_the_working_dir_env(shim, monkeypatch, tmp_path):- """uv gives the flag precedence, so honouring the variable instead would filter- and record the wrong file."""+ """uv gives the flag precedence, so honouring the variable would filter the wrong file."""_fake_distributions(monkeypatch, ("transformers", "4.57.6"))here, there = _working_dir_case(tmp_path)other = tmp_path / "other"@@ -1340,8 +1336,7 @@ def test_the_directory_flag_wins_over_the_working_dir_env(shim, monkeypatch, tmpdef test_a_nested_include_follows_uvs_working_directory(shim, monkeypatch, tmp_path):- """A nested `-r` is relative to the file that NAMES it, and that file now lives- in uv's directory rather than ours."""+ """Nested `-r` paths resolve against the naming file, which now sits in uv's directory."""_fake_distributions(monkeypatch, ("transformers", "4.57.6"))here, there = _working_dir_case(tmp_path)(there / "requirements.txt").write_text("-r nested.txt\nsnac\n", encoding = "utf-8")@@ -1413,8 +1408,7 @@ def test_the_working_dir_env_also_finds_a_local_protected_project(shim, monkeypadef test_a_local_project_relative_to_the_cwd_is_still_classified(shim, monkeypatch, tmp_path):- """The ordinary no-directory case must keep working: pip never changes directory- and uv without --directory resolves from the cwd exactly as we do."""+ """Without --directory, uv resolves from the cwd as we do; local projects still classify."""_fake_distributions(monkeypatch, ("unsloth", "2026.6.9"))here = tmp_path / "here"here.mkdir()@@ -1428,8 +1422,7 @@ def test_a_local_project_relative_to_the_cwd_is_still_classified(shim, monkeypatdef test_an_unrelated_local_project_still_reaches_the_real_tool(shim, monkeypatch, tmp_path):- """Resolving from uv's directory must not start dropping things: a local project- that is not protected still has to be installed."""+ """Unprotected local projects must still install when resolving from uv's directory."""_fake_distributions(monkeypatch, ("unsloth", "2026.6.9"))here, there = tmp_path / "here", tmp_path / "there"here.mkdir()@@ -1449,9 +1442,8 @@ def test_an_unrelated_local_project_still_reaches_the_real_tool(shim, monkeypatcids = ["subdirectory", "unknown-fragment"],)def test_a_fragment_does_not_hide_a_local_protected_project(shim, monkeypatch, tmp_path, spec):- """The stat has to happen on the path alone. `#egg=` is recognised earlier, but- any other fragment reaches the directory lookup still attached, and leaving it on- makes the stat miss and forwards the project for replacement."""+ """Stat the bare path: the egg fragment is stripped earlier, but other fragments stay attached+ and make the stat miss, forwarding a protected project for replacement"""there = _shared_setup_1(monkeypatch, tmp_path)ran = _full_argv(shim, ["uv", "pip", "--directory", str(there), "install", "-e", spec])@@ -1511,8 +1503,7 @@ def test_an_install_aimed_elsewhere_keeps_the_packages_it_asked_for(shim, monkey],)def test_a_destination_environment_variable_redirects_too(shim, monkeypatch, var, value):- """pip honours PIP_<OPTION> for every option and uv documents --python as- [env: UV_PYTHON=], so the destination moves with nothing on the command line."""+ """pip reads PIP_<OPTION> and uv reads UV_PYTHON, so the destination moves without a flag."""_fake_distributions(monkeypatch, ("torch", "2.9.1+cu128"))monkeypatch.setenv(var, value)tool = "uv" if var.startswith("UV_") else "pip"@@ -1527,9 +1518,8 @@ def test_a_destination_environment_variable_redirects_too(shim, monkeypatch, vardef test_a_sync_aimed_elsewhere_is_not_refused(shim, monkeypatch):- """The sync refusal exists because sync UNINSTALLS everything missing from the- file, stripping the baked stack. Pointed at another environment there is no baked- stack for it to strip."""+ """The sync refusal exists because sync uninstalls everything missing from the file, stripping+ the baked stack; aimed elsewhere there is no stack to strip."""_fake_distributions(monkeypatch, ("torch", "2.9.1+cu128"))ran = _full_argv(shim, ["uv", "pip", "sync", "--python", "/tmp/venv/bin/python", "r.txt"])assert ran is not None and "r.txt" in ran, f"a sync aimed elsewhere was refused: {ran}"@@ -1786,9 +1776,8 @@ def test_an_uninspectable_target_source_is_refused(shim, monkeypatch, argv):def test_a_group_install_aimed_elsewhere_is_not_refused(shim, monkeypatch):- """Guard: the destination bypass runs first on purpose. A group installed into- another environment cannot touch the baked stack, so refusing it would break a- command that was never a threat."""+ """The destination bypass runs first on purpose: a group installed into another environment+ cannot touch the baked stack, so refusing it would block a harmless command."""_fake_distributions(monkeypatch, ("unsloth", "2026.6.9"))ran = _full_argv(shim, ["pip", "install", "--target", "/tmp/lib", "--group", "dev"])assert ran is not None and "--group" in ran, f"a harmless group install was refused: {ran}"diff --git a/tests/python/test_virustotal_scan.py b/tests/python/test_virustotal_scan.pyindex 55cb4d0abea..1cc4cd5ea1c 100644--- a/tests/python/test_virustotal_scan.py+++ b/tests/python/test_virustotal_scan.py@@ -349,9 +349,8 @@ class TestSingleUseUploadUrl:class TestDeadlineEnforcement:- """One attempt can block for the full socket timeout, so the deadline has to be- checked BEFORE a request, not after, or the step timeout kills the process- before any summary is written."""+ """One attempt can block for the full socket timeout, so the deadline must be checked before+ each request, or the step timeout kills the process before any summary is written."""def test_request_checks_deadline_before_issuing(self):calls = []@@ -733,9 +732,8 @@ class TestMarkdownEscaping:class TestAnnotationEscaping:- """Engine names, detection labels and error strings are third-party data.- Actions truncates an annotation at the first newline, which would drop the- engine list exactly when the scan is trying to alert a maintainer."""+ """Engine names, detection labels and error strings are third-party data; Actions truncates an+ annotation at its first newline, dropping the engine list."""def test_percent_is_escaped_before_the_newlines(self):# Escaping % last would double-encode %0A into %250A.@@ -847,8 +845,7 @@ class TestWorkflowOrdering:@staticmethoddef _runner_temp(path):- """Maps the spellings of the runner temp dir to one token, since `with:` and `run:` use- different ones."""+ """Maps the runner temp dir spellings to one token, since `with:` and `run:` use different ones."""normalised = " ".join(str(path).split())for spelling in ("${{ runner.temp }}", "${RUNNER_TEMP}", "$RUNNER_TEMP"):normalised = normalised.replace(spelling, "<RUNNER_TEMP>")diff --git a/tests/python/test_windows_arm64_requirement_markers.py b/tests/python/test_windows_arm64_requirement_markers.pyindex 8f33960d1e1..d9d2d62d538 100644--- a/tests/python/test_windows_arm64_requirement_markers.py+++ b/tests/python/test_windows_arm64_requirement_markers.py@@ -226,10 +226,8 @@ def _lowest_allowed(req) -> str:@per_sourcedef test_a_selected_row_is_installable_on_the_python_it_was_selected_for(label, reqs):- """Splitting on platform is not enough on its own: a row can be live for an interpreter- that no release in its range supports, which is not a resolution failure anyone reads- as a marker bug -- pip just reports that no version matches.- """+ """Splitting on platform is not enough: a row can be live for an interpreter no release in its+ range supports, and pip reports that as no matching version rather than a marker bug."""for plat, py, env in ENVS:for req in _live(reqs, env):for spec, floor in PACKAGE_PYTHON_FLOORS.get(req.name.lower(), ()):@@ -298,12 +296,8 @@ def test_a_skipped_package_is_not_left_live_in_an_extra(extra):@per_extradef test_dropping_a_package_on_woa_drops_it_nowhere_else(extra):- """A negative ARM64 marker is a scalpel: every other platform keeps the row.-- Checked as an outcome rather than a spelling, over the same platform table the rest of- this file uses, so a marker that reads correctly but excludes (say) Windows x86 as well- is still caught.- """+ """A negative ARM64 marker must drop the row only on ARM64; checked as an outcome over the+ platform table, so a marker also excluding Windows x86 is caught."""for req in _pyproject_extras()[extra]:if IPS._canonical_dist_name(req.name) not in WOA_SKIPPED or req.marker is None:continuediff --git a/tests/python/test_windows_arm64_wheelhouse_tags.py b/tests/python/test_windows_arm64_wheelhouse_tags.pyindex 6764babe202..11d494e547b 100644--- a/tests/python/test_windows_arm64_wheelhouse_tags.py+++ b/tests/python/test_windows_arm64_wheelhouse_tags.py@@ -123,9 +123,8 @@ def native_cp314(ips, monkeypatch):@pytest.fixturedef soxr_published(ips, monkeypatch):- """Answer the index for soxr, which publishes no win_arm64 wheel in any release, so it- alone would decide tests that are about something else. test_librosa_still_needs_soxr- covers soxr itself."""+ """Answers the index for soxr, which publishes no win_arm64 wheel in any release, so it would+ otherwise decide unrelated tests; test_librosa_still_needs_soxr covers soxr itself."""real = ips._public_index_win_arm64_versionsmonkeypatch.setattr(ips,@@ -640,9 +639,8 @@ class TestDuplicateRequirementRowsAreSplitByMarker:class TestAPrereleaseWheelDoesNotSatisfyAFinalPin:- """A wheelhouse holding 0.13.0rc1 must not unskip a package pinned to ==0.13.0: the- numeric comparison reduced both to (0, 13, 0), so the skip was dropped and uv -- which- applies PEP 440 properly -- fell to the ARM64 sdist the skip list exists to avoid."""+ """A 0.13.0rc1 wheel must not unskip a package pinned to ==0.13.0: numeric comparison reduced+ both to (0, 13, 0), so uv (which applies PEP 440) fell to the ARM64 sdist."""@pytest.mark.parametrize("version, specifier, expected, why",@@ -773,9 +771,8 @@ class TestAnExplicitPinIsNotOverriddenByThePreservationShortcut:class TestThePublicIndexUnblocksWhatItAlreadyPublishes:- """The skip list was decided from the local wheelhouse alone, so a native CPython 3.14- ARM64 host -- where llvmlite and numba both publish a win_arm64 wheel, cp314 being the- only tag either publishes one for -- had librosa dropped with its chain resolvable."""+ """The skip list used only the local wheelhouse, so a native CPython 3.14 ARM64 host dropped+ librosa with its chain resolvable, as llvmlite and numba publish cp314 win_arm64 wheels."""def test_the_recorded_versions_clear_the_blocker_floors(self, ips):"""A recorded version below the floor would unblock nothing but this table."""@@ -827,9 +824,8 @@ class TestThePublicIndexUnblocksWhatItAlreadyPublishes:class TestThePublicIndexClaimNeedsTheIndex:- """What PyPI publishes is only availability if the resolve will look at PyPI: offline, or- pointed at an exclusive corporate index, unblocking librosa drops the skip and then fails- the whole extras pass on a numba chain nothing serves."""+ """What PyPI publishes counts only if the resolve reaches PyPI; offline or on an exclusive+ index, unblocking librosa fails on a numba chain nothing serves."""@pytest.fixture(autouse = True)def _native(self, ips, monkeypatch, native_cp314):@@ -1295,9 +1291,8 @@ class TestInstallPs1HandsOverWhatPyPIProvides:class TestAHostedTorchcodecIsInstalledByItsStep:- """The requirement filter kept a hosted torchcodec's row, but no requirements file has one,- and the dedicated step skipped every platform without a published wheel. Hosting the wheel- therefore re-enabled nothing, against what the drop list in install.ps1 promises."""+ """Hosting torchcodec re-enabled nothing, against install.ps1's drop list: no requirements file+ has its row, and the dedicated step skips platforms without a published wheel."""@pytest.fixturedef native(self, ips, monkeypatch, wheelhouse):diff --git a/tests/python/test_windows_installer_concurrency_guard.py b/tests/python/test_windows_installer_concurrency_guard.pyindex 9ad963b6264..dd944983333 100644--- a/tests/python/test_windows_installer_concurrency_guard.py+++ b/tests/python/test_windows_installer_concurrency_guard.py@@ -1161,9 +1161,8 @@ def test_tauri_start_install_rejects_backend_conflicts_before_spawn():ids = ["mutex", "process", "final-path"],)def test_the_extracted_helpers_can_call_everything_they_call(helpers):- """Every installer function these harnesses reach must be in the harness: the scripts run under- -ErrorActionPreference Stop, so a missing one fails the test for an unrelated reason. Runs on- every platform, unlike the scripts themselves."""+ """Every installer function the harnesses reach must be in the harness, since a missing one+ fails under -ErrorActionPreference Stop; this runs on every platform."""source = INSTALL_PS1.read_text(encoding = "utf-8")extracted = helpers(source)installer_functions = set(re.findall(r"^ function ([\w-]+) \{", source, flags = re.M))diff --git a/tests/python/test_windows_installer_resolver_fallback.py b/tests/python/test_windows_installer_resolver_fallback.pyindex 46672d58978..86080dc8ea7 100644--- a/tests/python/test_windows_installer_resolver_fallback.py+++ b/tests/python/test_windows_installer_resolver_fallback.py@@ -157,13 +157,8 @@ def _lines(result: subprocess.CompletedProcess, prefix: str) -> list[str]:@requires_pwshdef test_install_lock_is_acquired_when_the_native_helper_is_unavailable(tmp_path: Path):- """The bug from #9140, at the rung it lives on now.-- It was a throwing Add-Type then, then a host that could not define a type at all,- and it is a host with no interpreter to ask now. All three are the same thing to- every caller: no exact answer. The lock must still be acquired, and the reason- said once.- """+ """Regression for issue 9140: with the native helper unavailable (throwing Add-Type, no type+ support, or no interpreter), the install lock is still taken and the reason printed once."""studio_home = tmp_path / "studio"studio_home.mkdir()result = _run_powershell(@@ -197,9 +192,8 @@ def _fresh_install_statement() -> str:def test_the_first_install_verdict_is_taken_before_anything_is_created() -> None:- """Read where $VenvDir is first computed, before the install lock and before any path is- resolved: read any later and this run's own venv would make every install look like an- update, and the warning would come back on exactly the run it was silenced for."""+ """Read the fresh-install verdict where $VenvDir is first computed, before the install lock and+ path resolution; read later, this run's own venv makes every install look like an update."""source = INSTALL_PS1.read_text(encoding = "utf-8")verdict = source.index(_fresh_install_statement())assert source.index(' $VenvDir = Join-Path $StudioHome "unsloth_studio"') < verdict@@ -221,11 +215,8 @@ def test_the_first_install_verdict_is_taken_before_anything_is_created() -> Nonedef test_a_python_less_first_install_prints_no_degraded_warning(tmp_path: Path, existing: str | None, warns: bool):- """main resolved paths in process, so a normal first install on a host with no Python- printed nothing. The interpreter rung has nothing to run there, and the five-line yellow- block it printed instead was the first thing a new user (Desktop's first run included)- saw. It stays for an existing install, where two spellings of it escaping one another's- lock is the thing the operator is being told about. The lock is the same in every row."""+ """A first install with no Python prints no degraded warning, as the interpreter rung has+ nothing to run; existing installs keep it, since two spellings can escape one another's lock."""studio_home = tmp_path / "studio"studio_home.mkdir()profile = tmp_path / "profile"@@ -278,13 +269,9 @@ Exit-StudioInstallMutex -Mutex $mutex@requires_pwshdef test_a_dead_compiler_is_not_something_the_installer_can_notice(tmp_path: Path):- """The other half, and the reason the file is named for a fallback it no longer needs.-- install.ps1 reaches no compiler, so replacing Add-Type with one that always throws- has to change nothing at all: the lock is taken, the path resolves exactly through- the child interpreter, and no degraded warning is printed. A failure here means a- compile came back.- """+ """install.ps1 reaches no compiler, so an Add-Type that always throws must change nothing: the+ lock is taken, the path resolves exactly, no warning prints; a failure means a compile came+ back."""studio_home = tmp_path / "studio"studio_home.mkdir()result = _run_powershell(@@ -307,9 +294,8 @@ Write-Output "EXACT:$((Resolve-StudioFinalPathInfo -Path '{studio_home}').Exact)@requires_pwshdef test_the_compiler_is_never_called_however_many_paths_are_resolved(tmp_path: Path):- """Zero, not "few". The count used to be two, one attempt and one retry under a- private %TEMP%, and both of those launched csc.exe, which is the chain behavioural- antivirus blocked."""+ """The compiler must never be called (zero, not few): the old attempt and private-%TEMP% retry+ both launched csc.exe, which behavioural antivirus blocked."""result = _run_powershell(_script(f"""@@ -330,18 +316,8 @@ Write-Output "CALLS:$global:AddTypeCalls"@requires_pwshdef test_the_interpreter_is_looked_for_once_however_many_paths_are_resolved(tmp_path: Path):- """The caching the retry count used to stand in for, at the rung that has it now.-- Finding an interpreter means running a probe against every candidate on PATH until- one answers, and that search is latched. Resolving a path still costs one child, so- five resolutions cost five children plus the ONE search: six calls, not ten. Without- the latch every resolution pays the search again, and on a host whose first few- candidates are slow or broken that is the expensive half.-- Five DIFFERENT paths. The same path five times is served by the per-path answer cache- after the first child, which would make this count two and hide whether the search is- latched at all.- """+ """The interpreter search is latched: five different paths cost five child probes plus one+ search, six calls not ten; repeating one path would hit the per-path answer cache."""paths = []for i in range(5):(tmp_path / f"p{i}").mkdir()@@ -372,15 +348,9 @@ Write-Output "PROBES:$global:Probes"@requires_pwshdef test_a_path_still_resolves_with_no_usable_temp_at_all(tmp_path: Path):- """What replaced the private-%TEMP% retry: a ladder that cannot be ended by %TEMP%.-- The retry existed because compiling wrote a source file there, and a %TEMP% that- could not hold one failed the install outright (#9140). The rungs left do use %TEMP%- -- the child interpreter is handed its script through a file -- so an unusable one- can still cost the EXACT answer. What it may no longer cost is the install: the- ladder drops to the lexical rung, says so, and hands the caller's broken variables- back exactly as they arrived rather than repairing them behind its back.- """+ """An unusable %TEMP% may still cost the exact answer, since the child gets its script via a+ file, but never the install: the ladder falls to the lexical rung, says so, and returns the+ caller's broken variables unrepaired (issue 9140)."""blocker = tmp_path / "blocker"blocker.write_text("not a directory", encoding = "utf-8")dead = str(blocker / "temp")@@ -463,11 +433,8 @@ Write-Output "PATH:$(Get-StudioFinalPath -Path '{left}')"@requires_pwshdef test_unequal_paths_are_unknown_rather_than_different_when_inexact(tmp_path: Path):- """NO_NATIVE, not the Add-Type sabotage: the installer no longer calls Add-Type, so on a real- Windows host the emit succeeds, the answer is exact, and two different directories compare- $false. The case this test is about is the one with no exact answer, and the only way to that- case now is the capability gate.- """+ """Uses NO_NATIVE rather than sabotaging Add-Type, which the installer no longer calls; the+ capability gate is now the only route to an inexact answer, where unequal paths are unknown."""left = tmp_path / "left"right = tmp_path / "right"left.mkdir()@@ -488,12 +455,8 @@ Write-Output "NULL:$($null -eq $answer)"@requires_pwshdef test_a_directory_that_will_not_give_a_file_back_is_not_usable(tmp_path: Path):- """Create and read are not enough. csc.exe also has to clean up after itself.-- A directory that accepts a file and then refuses to delete it (a denied- Delete ACE, a scanner sitting on the handle) is the shape that produced the- reported failure, and it passes a create-and-read probe unchanged.- """+ """A temp directory must also allow deleting a file, not just create and read one: a denied+ Delete ACE passes a create-and-read probe yet broke csc.exe cleanup."""good = tmp_path / "good"good.mkdir()result = _run_powershell(@@ -746,12 +709,9 @@ def test_a_drive_less_rooted_target_lands_on_the_link_own_root(tmp_path: Path):def test_a_whitespace_only_tmp_is_set_as_far_as_windows_is_concerned(tmp_path: Path, tmp: str | None, expect_override: bool):- """GetTempPath takes the first of TMP/TEMP that is merely NON-empty.-- So a whitespace-only TMP is the one Windows and every child process will use.- Reading it as "unset" probes a healthy TEMP, changes nothing, and leaves the- compile and every later download pointed at a path that cannot exist.- """+ """GetTempPath uses the first non-empty of TMP/TEMP, so a whitespace-only TMP is what Windows+ and child processes use; treating it as unset probes a healthy TEMP and leaves every later+ step pointed at a path that cannot exist."""good = tmp_path / "good"good.mkdir()local_app_data = tmp_path / "localappdata"@@ -878,15 +838,9 @@ def test_the_installer_and_the_runtime_gate_normalize_alike(resolved: str, expecids = ["drive-root", "bare-drive", "lowercase-letter", "unmapped-drive"],)def test_a_subst_drive_folds_onto_its_target(path: str, expected: str):- """The Python runtime gate resolves a SUBST drive; Path.resolve does that.-- Left unresolved here, one directory reached under two spellings produces two- different install mutexes, and an Unsloth running from the physical spelling is- invisible to the in-use scan. Measured on windows-latest: subst.exe is the- only source available without a compiler -- Get-PSDrive.DisplayRoot,- Win32_LogicalDisk.ProviderName, GetFullPath and Resolve-Path all reveal- nothing about the mapping.- """+ """The runtime gate resolves SUBST drives (Path.resolve does this), so one directory under two+ spellings gets one mutex; subst.exe is the only compiler-free source; Get-PSDrive,+ Win32_LogicalDisk, GetFullPath and Resolve-Path reveal nothing."""result = _run_powershell("\n".join([@@ -907,12 +861,8 @@ def test_a_subst_drive_folds_onto_its_target(path: str, expected: str):@requires_pwshdef test_the_recorded_owner_outranks_the_name(tmp_path: Path):- """The PID in the name is the INSTALLER's, and it exits.-- The process that keeps using the directory is the Unsloth the installer- autostarted, which is what owner.pid records. Reading only the name would- clear a live Unsloth's %TEMP% on the next run.- """+ """The PID in the name is the installer's and exits; the live user is the Unsloth it+ autostarted, which owner.pid records, so the name alone must not clear its %TEMP%."""root = tmp_path / "root"root.mkdir()keep = root / f"ust-{_DEAD_PID}-000000aa"@@ -933,12 +883,9 @@ def test_the_recorded_owner_outranks_the_name(tmp_path: Path):@requires_pwshdef test_the_sweep_keeps_a_directory_whose_owner_is_still_running(tmp_path: Path):- """An Unsloth autostarted by an earlier install owns one of these as its %TEMP%.-- It can outlive the one-day cutoff without ever writing to the directory, and- the sweep runs before the runtime mutex is taken, so age alone must not be- read as proof that nothing is using it.- """+ """An Unsloth autostarted by an earlier install owns one of these as its %TEMP% and can outlive+ the one-day cutoff unwritten; the sweep runs before the runtime mutex is taken, so age alone+ must not prove it unused."""root = tmp_path / "root"root.mkdir()live = root / f"ust-{os.getpid()}-01d01d01"@@ -959,12 +906,8 @@ def test_the_sweep_keeps_a_directory_whose_owner_is_still_running(tmp_path: Path@requires_pwshdef test_a_healthy_temp_still_sweeps_what_an_earlier_degraded_run_left(tmp_path: Path):- """The allocator is the only thing that sweeps, and a healthy host skips it.-- Once the host's own temp is fixed (an ACL correction, a cleaned environment)- no further run allocates a private directory, so whatever the degraded runs- left would age in place until an uninstall.- """+ """Only the allocator sweeps and a healthy host skips it, so leftovers of degraded runs would+ age in place; a healthy temp must still sweep them."""good = tmp_path / "good"good.mkdir()local_app_data = tmp_path / "localappdata"@@ -1000,12 +943,8 @@ Write-Output "OVERRIDE:$($null -ne $script:StudioTempOverride)"@requires_pwshdef test_probing_the_host_temp_never_creates_it(tmp_path: Path):- """An inherited TMP that names nothing is unusable, not an instruction.-- New-Item -Force builds the whole parent chain, so treating the host's own- TMP as creatable would have the installer materialize a tree at a path- nobody chose, on a stale or mistyped value, and then trust it as temp.- """+ """An inherited TMP naming nothing is unusable: New-Item -Force builds the whole parent chain,+ so probing the host temp must never create it, even on a stale or mistyped value."""ghost = tmp_path / "ghost" / "deeper"result = _run_powershell(_script(@@ -1036,12 +975,8 @@ Write-Output "EXISTS:$(Test-Path -LiteralPath '{ghost}')"@requires_pwshdef test_an_undeletable_probe_file_is_reclaimed_next_time(tmp_path: Path):- """The probe cannot clean up after itself when deletion is what failed.-- Without a sweep every such run leaves one more file in the host's own- temp, forever, since nothing else knows the name. Aged, so a probe running- concurrently in another process is never touched.- """+ """A probe whose deletion failed is reclaimed by a later sweep, else each run leaves one more+ file in the host temp; only aged probes go, sparing concurrent ones."""good = tmp_path / "good"good.mkdir()stale = good / "unsloth-probe-deadbeef.tmp"@@ -1164,16 +1099,8 @@ def test_the_sweep_only_takes_directories_the_allocator_could_have_made(tmp_path@requires_pwshdef test_a_resolver_that_runs_and_fails_says_so_once(tmp_path: Path):- """An interpreter that answers nothing is not the same as no interpreter.-- The install proceeds on the lexical answer either way, and Exact = $false already- makes the runtime lock fail closed, but for a long time nothing said so: the- degraded warning fired only where the exact rung was known to be unavailable. That- left an operator with a silently inexact identity on a host that looks perfectly- healthy. A child that starts, runs and returns nothing -- a sandboxed interpreter, a- symlink loop under the requested path, an AV hook that kills it -- has to reach the- same warning.- """+ """A resolver child that runs but returns nothing (sandbox, symlink loop, AV kill) must print+ the degraded warning; Exact = $false already fails the lock closed but was silent."""studio = tmp_path / "studio"studio.mkdir()result = _run_powershell(@@ -1342,14 +1269,9 @@ def test_the_private_temp_directory_is_somewhere_uninstall_reclaims():@requires_pwshdef test_the_uninstall_sweep_leaves_a_live_owner_and_never_follows_a_link(tmp_path: Path):- """An uninstall stops the Unsloth instances under the roots it knows about, not others.-- An Unsloth from another install root, or another user, can be alive on one of- these directories as its %TEMP%; install.ps1's own sweep preserves it and so- must this one. And a temp directory that is itself a link must not be walked:- the target's children carry no ReparsePoint attribute, so a recursive delete- would take an unrelated tree.- """+ """The uninstall sweep preserves live owners from other roots or users, as install.ps1 does, and+ never walks a temp link: the target's children lack ReparsePoint, so recursion would hit an+ unrelated tree."""block, preamble, uninstall = _shared_setup_2()temp = tmp_path / "Unsloth Studio" / "temp"@@ -1406,13 +1328,8 @@ def test_the_uninstall_sweep_leaves_a_live_owner_and_never_follows_a_link(tmp_pa@requires_pwshdef test_a_live_owner_survives_the_data_directory_removal(tmp_path: Path):- """Preserving a directory is worth nothing if the next line deletes its parent.-- The primary private temp directory sits inside the data directory, and the- data directory is removed wholesale. An Unsloth from another install root can- be alive on that temp directory as its %TEMP%, so the sweep has to run first- and the removal has to be told what the sweep kept.- """+ """The sweep must run before the data directory is removed wholesale, and the removal must skip+ what the sweep kept, since a live Unsloth from another root may use that temp."""uninstall = (REPO_ROOT / "scripts" / "uninstall.ps1").read_text(encoding = "utf-8")body = uninstall[uninstall.index("function Uninstall-UnslothStudio") :]@@ -1592,14 +1509,9 @@ Write-Output "PRIVATE:$(New-StudioPrivateTempDirectory)"@requires_pwshdef test_the_uninstall_sweep_needs_a_recorded_owner_outside_its_own_profile(tmp_path: Path):- """The alternate LocalAppData spelling can be another user's profile.-- install.ps1 reads a missing owner.pid as unknown rather than abandoned,- because an installer killed before writing it leaves a live Unsloth holding- the directory. Deleting that out of somebody else's profile is not this- uninstall's business. Under our own profile the shape is enough, since that- is what is being removed.- """+ """The alternate LocalAppData may be another user's profile, so its sweep needs a recorded+ owner.pid (a missing one reads as unknown, not abandoned); our own profile needs only the+ shape."""block, preamble, uninstall = _shared_setup_2()mine = tmp_path / "mine" / "Unsloth Studio" / "temp"@@ -1628,14 +1540,8 @@ def test_the_uninstall_sweep_needs_a_recorded_owner_outside_its_own_profile(tmp_@requires_pwshdef test_the_uninstaller_reclaims_the_temp_tree_at_both_spellings(tmp_path: Path):- """A set-but-unusable LOCALAPPDATA is the case that produced two roots.-- install.ps1 skips such a path and places its private temp under the known- folder instead, so an uninstaller that stops at the first non-blank- candidate leaves the real tree behind. What the second root must NOT get is- the recursive, sentinel-free data-dir delete: the two spellings differ- mainly when one of them names a DIFFERENT USER's profile.- """+ """A set but unusable LOCALAPPDATA produces two roots, so the uninstaller must reach both; the+ second gets no recursive sentinel-free delete, since it may name another user's profile."""uninstall = (REPO_ROOT / "scripts" / "uninstall.ps1").read_text(encoding = "utf-8")block = _extract(r" # The SECOND LocalAppData spelling.*?\n \}\n", uninstall)@@ -1662,11 +1568,8 @@ def test_the_uninstaller_reclaims_the_temp_tree_at_both_spellings(tmp_path: Path@requires_pwshdef test_the_private_temp_removal_only_takes_what_it_created(tmp_path: Path):- """Narrow on purpose: this runs against a root that may be another user's.-- Only ust-<pid>-<hex> directories go, matched by shape rather than prefix,- and the temp directory and its parent only when they are left empty.- """+ """Deliberately narrow, as the root may belong to another user: only ust-<pid>-<hex> directories+ are removed, matched by shape, and parents only when left empty."""uninstall = (REPO_ROOT / "scripts" / "uninstall.ps1").read_text(encoding = "utf-8")block = _extract(r" function _RemoveStudioPrivateTempTrees \{.*?\n \}\n", uninstall)@@ -1749,14 +1652,9 @@ def test_the_lock_chain_defines_everything_it_reaches() -> None:@requires_pwshdef test_an_elevated_run_declines_a_user_writable_interpreter(tmp_path: Path):- """The other side of the stub above, so neither half is an assumption.-- Whatever this ladder settles on is launched WITH THE ADMINISTRATOR TOKEN when the install is- elevated, so an interpreter in a directory the same user's medium-integrity token can write- is a way to have arbitrary code run elevated. This host's own interpreter is exactly that, so- the rung has to decline, the answer stops being exact, and the reason is printed rather than- the degradation being silent.- """+ """An elevated run launches the resolved interpreter with the administrator token, so a+ user-writable interpreter must be declined: the answer goes inexact and the reason is+ printed."""studio_home = tmp_path / "studio"studio_home.mkdir()result = _run_powershell(diff --git a/tests/python/test_windows_on_arm_python_arch.py b/tests/python/test_windows_on_arm_python_arch.pyindex d5929dabacc..35538f27ab0 100644--- a/tests/python/test_windows_on_arm_python_arch.py+++ b/tests/python/test_windows_on_arm_python_arch.py@@ -47,11 +47,9 @@ def _run(return result.stdout.strip()-# The shared preamble: the two host helpers the functions under test call, stubbed so the-# decision is driven by the case rather than by the machine running the suite. Neither stub-# stands in for logic under test here: Get-HostMachineArch is exercised against real-# hardware on the windows-11-arm leg, and Get-PythonPlatformTag asks an interpreter for-# sysconfig.get_platform(), which needs a Windows interpreter to answer win-arm64.+# Stubs the two host helpers so each case, not the test machine, drives the decision;+# Get-HostMachineArch runs on real windows-11-arm hardware, and Get-PythonPlatformTag needs a+# Windows interpreter for sysconfig.get_platform() to return win-arm64.def _preamble(host_arch: str, venv_tag: str) -> str:# Verbatim from install.ps1, not a stub: both the fresh-selection path and the venv# re-check call it, so a change to what the opt-out accepts has to move these cases too.@@ -119,13 +117,8 @@ Write-Host ("MISMATCH=" + $mismatch)def test_the_opt_out_also_protects_an_existing_arm64_environment(tmp_path: Path, shell: str, value: str):- """The opt-out has to be read HERE, not only where a fresh interpreter is chosen.-- Resolve-WindowsOnArmX64Python never runs when the ordinary probe already found x64, so- on an ARM64 box with both interpreters the variable was never consulted and this branch- moved aside the very environment the user asked to keep. The rebuild is not a migration:- nothing installed into the old venv carries over.- """+ """The opt-out is read here too, since Resolve-WindowsOnArmX64Python is skipped when x64 is+ already found; a rebuild carries nothing over from the old venv."""venv_python = tmp_path / "python.exe"venv_python.write_text("", encoding = "utf-8")selected = '@{ Version = "3.13"; Path = "C:\\p\\python.exe"; Arch = "x86_64" }'@@ -165,9 +158,8 @@ Write-Host ("MISMATCH=" + $mismatch)def test_both_arm64_opt_out_readers_go_through_one_helper():- """Two spellings of the same question drift. The fresh-selection path and the reuse- re-check must read it the same way, or an accepted value works in one and not the- other."""+ """The fresh-selection path and the reuse re-check must read the opt-out the same way, or an+ accepted value works in one and not the other."""source = INSTALL_PS1.read_text(encoding = "utf-8")assert source.count("function Test-Arm64PythonOptOut") == 1assert (@@ -274,11 +266,8 @@ Write-Host ("PRESERVE=" + $script:StudioVenvRollbackPreserve)@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")@pytest.mark.parametrize("shell", POWERSHELLS)def test_an_ordinary_rollback_is_still_deleted_on_success(tmp_path: Path, shell: str):- """The preserve flag is opt-in, and every other rollback keeps the old behaviour.-- Without this the fix trades one bug for a slow leak: a full environment left behind by- every reinstall, on the machine of every user who never asked for one.- """+ """The preserve flag is opt-in and other rollbacks keep deleting; otherwise every reinstall+ would leak a full environment for users who never asked to keep one."""home = tmp_path / "studio"backup = home / "unsloth_studio.rollback.20260101000000.4242"backup.mkdir(parents = True)diff --git a/tests/python/test_windows_python_venv_hardening.py b/tests/python/test_windows_python_venv_hardening.pyindex 7814c784220..fe3a4997dcd 100644--- a/tests/python/test_windows_python_venv_hardening.py+++ b/tests/python/test_windows_python_venv_hardening.py@@ -121,11 +121,8 @@ def _uv_cache_functions(source: str) -> str:@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")@pytest.mark.parametrize("shell", POWERSHELLS)def test_arch_probe_ignores_startup_output(tmp_path: Path, shell: str):- """Startup output must not reach the arch tag.-- The caller compares the tag with -eq "win-amd64", so a contaminated answer reads- as "unknown" and Windows on ARM silently settles for a native ARM64 interpreter.- """+ """Startup output must not reach the arch tag: the caller compares it with -eq win-amd64, so+ contaminated output silently settles for a native ARM64 interpreter."""source = INSTALL_PS1.read_text(encoding = "utf-8")probe = _extract(r" function Get-PythonPlatformTag \{.*?\n \}\n", source)(tmp_path / "sitecustomize.py").write_text('print("STARTUP_BANNER")\n', encoding = "utf-8")@@ -223,14 +220,8 @@ Write-Output ("dir=" + [string]$script:StudioVenvRollbackDir)@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")@pytest.mark.parametrize("shell", POWERSHELLS)def test_restoring_a_split_move_never_deletes_the_half_left_behind(tmp_path: Path, shell: str):- """Restoration must merge the two halves, not clear the destination first.-- After a partway move the target holds the entries the move never got to -- not- an incomplete *new* environment. The committed-replacement path removes the- target before moving the backup back, which for a split tree deletes files that- exist nowhere else. Keeping the rollback active is only safe if restoration- takes a merge path, so this pins the file that never moved to being still there.- """+ """Restoring a split move must merge into the destination, not clear it first, since clearing+ deletes files that exist nowhere else; the half that never moved must still be there."""source = INSTALL_PS1.read_text(encoding = "utf-8")blocks = "".join(_extract(rf" function {name} \{{.*?\n \}}\n", source)@@ -278,14 +269,8 @@ Write-Output ("active=" + $script:StudioVenvRollbackActive)@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")@pytest.mark.parametrize("shell", POWERSHELLS)def test_merging_a_split_move_keeps_every_sibling_at_its_own_path(tmp_path: Path, shell: str):- """Each entry must land at its own path, not nested under the previous one.-- PowerShell variable names are case-insensitive, so a per-entry $destination- reassigns the $Destination parameter. Only the first sibling at a level then- lands correctly and the rest are appended to its path, so a restored venv comes- back with pyvenv.cfg buried inside Lib. One entry per level hides it, so this- uses several.- """+ """Each sibling must land at its own path: PowerShell names are case-insensitive, so a per-entry+ $destination reassigns $Destination and buries pyvenv.cfg inside Lib."""source = INSTALL_PS1.read_text(encoding = "utf-8")blocks = "".join(_extract(rf" function {name} \{{.*?\n \}}\n", source)@@ -348,12 +333,8 @@ Write-Output ("active=" + $script:StudioVenvRollbackActive)@pytest.mark.parametrize("shell", POWERSHELLS)@pytest.mark.parametrize("side", ["destination", "source"])def test_merging_a_split_move_never_walks_through_a_link(tmp_path: Path, shell: str, side: str):- """A junction on either side is a leaf, not a subtree to recurse into.-- Recursing through one moves venv files to wherever the link points, outside- $StudioHome, and replaces the link with a real directory. Either half can carry- the link, so both directions are pinned here.- """+ """A junction on either side is a leaf: recursing through one moves venv files outside+ $StudioHome and replaces the link with a real directory, so both sides are pinned."""source = INSTALL_PS1.read_text(encoding = "utf-8")blocks = "".join(_extract(rf" function {name} \{{.*?\n \}}\n", source)@@ -804,9 +785,8 @@ foreach ($root in @($env:TEST_STUDIO_HOME_ONE, $env:TEST_STUDIO_HOME_TWO)) {{@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")@pytest.mark.parametrize("shell", POWERSHELLS)def test_a_non_ascii_marker_survives_the_rollback(tmp_path: Path, shell: str):- """The update writes this file BOM-less UTF-8, and Windows PowerShell 5.1 reads a- BOM-less file with the active ANSI code page, so a non-ASCII path came back as- mojibake and the rollback wrote that back over a marker that had been correct."""+ """The marker is written BOM-less UTF-8, which Windows PowerShell 5.1 reads as ANSI, so a+ non-ASCII path became mojibake and the rollback wrote that over a correct marker."""source = INSTALL_PS1.read_text(encoding = "utf-8")functions = "".join(_extract(rf" function {name} \{{.*?\n \}}\n", source)@@ -850,9 +830,8 @@ Restore-StudioUvCacheMarker -StudioRoot $env:TEST_STUDIO_HOMEdef test_a_rolled_back_install_restores_the_previous_uv_cache_marker(tmp_path: Path, shell: str, preexisting: bool):- """The marker describes the environment, so it goes back when the environment does:- install.ps1 restores the previous venv on failure, and a marker for an install that- never happened would outlive it."""+ """The marker describes the environment, so it is restored with the previous venv on failure;+ otherwise a marker for an install that never happened would outlive it."""source = INSTALL_PS1.read_text(encoding = "utf-8")functions = "".join(_extract(rf" function {name} \{{.*?\n \}}\n", source)diff --git a/tests/python/test_windows_uv_cache_selection.py b/tests/python/test_windows_uv_cache_selection.pyindex d03e3a6104b..c3d541f1f19 100644--- a/tests/python/test_windows_uv_cache_selection.py+++ b/tests/python/test_windows_uv_cache_selection.py@@ -164,11 +164,8 @@ def test_isolation_wins_over_a_warm_default(tmp_path):@requires_pwsh@pytest.mark.parametrize("isolated", [False, True])def test_uv_no_cache_records_nothing_even_when_the_directory_is_decided(tmp_path, isolated):- """uv leaves the chosen directory completely empty under --no-cache.-- Both branches that pick a directory without probing returned before the no-cache check, so- the marker named a cache this install never filled and the next repair could prefer it.- """+ """uv leaves the chosen directory empty under --no-cache, so no marker may be recorded even when+ the directory is decided without probing, or it names an unfilled cache."""root = tmp_path / "studio"env = {"UV_NO_CACHE": "1"}if not isolated:@@ -248,11 +245,8 @@ def test_a_bucket_lookalike_is_not_warmth(tmp_path, name):@requires_pwshdef test_a_studio_cache_with_an_unusable_bucket_is_not_a_fallback(tmp_path):- """The root can be writable while a bucket uv renames into is not.-- A file where a bucket belongs is an existing path to the create uv makes, so uv refuses it.- Selecting that cache anyway turns an install that reported success into a uv error.- """+ """The root can be writable while a bucket uv renames into is not; a file where a bucket belongs+ makes uv refuse it, so selecting that cache would turn a success into a uv error."""root = tmp_path / "studio"(root / "cache" / "uv").mkdir(parents = True)(root / "cache" / "uv" / "archive-v0").write_text("not a directory")@@ -422,10 +416,8 @@ def test_a_read_only_managed_python_bucket_still_condemns_the_cache(tmp_path):@requires_pwshdef test_a_differently_cased_bucket_follows_the_filesystem(tmp_path):- """Where the directory folds, `Python-V0` IS uv's python-v0 and an unwritable one has to- condemn the cache. Where it does not, as on a case-sensitive NTFS directory or the Linux- filesystem this runs on, it is a directory uv never opens and must not condemn anything.- Measured the same way the selector measures it rather than assumed from the platform."""+ """An unwritable Python-V0 condemns the cache only where the filesystem folds case, as the+ selector's own probe measures it, not the platform; elsewhere uv never opens it."""default = _warm(tmp_path / "uvdefault")(default / "Python-V0").mkdir()folds = (default / "python-v0").exists()@@ -449,14 +441,9 @@ def test_a_bucket_that_is_not_a_directory_is_refused(tmp_path):@requires_pwshdef test_an_unmarked_warm_studio_cache_is_kept_when_the_default_is_cold(tmp_path):- """An install from before the marker can hold gigabytes of Torch and CUDA in the Studio- cache with nothing recording it, and abandoning that costs the downloads again.-- It is the LAST candidate though, behind uv's default: the marker arrived in b66d2a4c8 and- the installer's early UV_CACHE_DIR block only in e12963071 the day after, so an install- with no marker is old enough that `shared` was reachable, and there the launch repoint- leaves backend wheels in the Studio cache while the real bytes sit in the default.- """+ """An unmarked warm Studio cache ranks last behind uv's default: unmarked installs predate+ marker b66d2a4c8 and UV_CACHE_DIR block e12963071, so the real bytes sit in the default and a+ repoint would leave wheels in the Studio cache."""root = tmp_path / "studio"studio_cache = _warm(root / "cache" / "uv")cold = tmp_path / "colddefault"@@ -496,9 +483,8 @@ def test_an_unmarked_cold_studio_cache_does_not_block_the_shared_one(tmp_path):reason = "root reads through the mode bits",)def test_a_marker_we_cannot_even_stat_does_not_cost_us_uvs_default(tmp_path):- """Test-Path throws inside an ACL-denied directory under ErrorActionPreference = Stop, and- the selector wraps the whole candidate loop, so an unreachable marker used to take uv's- default down with it -- a first run elevated, a second one not."""+ """Test-Path throws in an ACL-denied directory under ErrorActionPreference Stop, and the+ selector's candidate loop wrapped it, so an unreachable marker must not cost uv's default."""locked = tmp_path / "locked"(locked / "uv").mkdir(parents = True)locked.chmod(0o000)@@ -607,14 +593,9 @@ def test_a_writable_studio_cache_still_wins_over_a_refused_one(tmp_path):],)def test_the_harness_hands_powershell_the_path_it_was_given(value):- """A path handed to pwsh must arrive byte-identical.-- json.dumps looked right and was not: a JSON string is double-quoted, and PowerShell does- not read `\\` in a double-quoted string as an escape, so every Windows path arrived with- DOUBLED separators and every assertion in this file compared a doubled path against a real- one. It passed anyway on Linux and macOS, where paths have no backslashes to double, so- only a Windows runner could see it. This case is the Windows runner, in one line.- """+ """A path handed to pwsh must arrive byte-identical: json.dumps escapes backslashes that+ PowerShell double-quoted strings do not unescape, doubling every Windows separator; only+ Windows CI sees it."""result = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", f"Write-Output {_ps_literal(value)}"],check = True,diff --git a/tests/python/test_windows_xformers_installer.py b/tests/python/test_windows_xformers_installer.pyindex da2bfa176ce..26f787d7621 100644--- a/tests/python/test_windows_xformers_installer.py+++ b/tests/python/test_windows_xformers_installer.py@@ -178,9 +178,8 @@ def test_the_index_fallback_hides_the_machine_level_indexes():@pytest.mark.skipif(shutil.which("pwsh") is None, reason = "PowerShell is unavailable")def test_the_url_join_keeps_a_tokenized_mirrors_query():- """Executed, not read: a private mirror may authenticate by query string, and appending- after the query put the wheel path inside the token value -- request path still /whl,- token unusable. Same rule as the Python side's join_wheel_url."""+ """Executed, not read: a mirror may authenticate by query string, and appending the wheel path+ after it put the path inside the token; same rule as join_wheel_url on the Python side."""joiner = _extract(r"^ function Join-UrlPath \{.*?^ \}", _source())out = _run_pwsh(f"{joiner}\n"@@ -196,9 +195,8 @@ def test_the_url_join_keeps_a_tokenized_mirrors_query():def test_installer_never_installs_an_unpinned_xformers():- """A bare `xformers` resolves to whatever the index serves newest, which is not- necessarily built for the CUDA family the resident torch came from. The installer- picks the exact version for (torch, cuda) instead, so every spec must be pinned."""+ """A bare xformers resolves to the newest build the index serves, which may not match the CUDA+ family of the resident torch; every spec must be pinned to the exact (torch, cuda) version."""source = _source()# The WoA drop list names packages to REMOVE, so a bare name must match the requirement line exactly.drop_list = re.search(r"\$WoaDropCandidates = @\(.*?\n\s*\)\n", source, re.DOTALL)@@ -284,10 +282,9 @@ def test_both_selectors_agree_outside_the_exact_tables(torch_version, cuda_versi@pytest.mark.skipif(shutil.which("pwsh") is None, reason = "PowerShell is unavailable")def test_the_already_installed_check_uses_the_wheels_own_build_target():- """A resident 0.0.35 records the torch it was COMPILED against (the stable-ABI floor),- not the torch it is running under. Comparing against the resident torch made every- correct install look mismatched, so each run force-reinstalled a good wheel -- and- warned about a failed xFormers install whenever the index was unreachable."""+ """A resident 0.0.35 records the torch it was compiled against (the stable-ABI floor), not the+ torch it runs under; comparing to the resident torch forced reinstalls and a false failure+ warning when the index was unreachable."""out = _run_pwsh(f"{_selector_harness()}\n""Write-Output \"[$(Get-XformersExpectedTorchBuild -Version '0.0.35' "diff --git a/tests/saving/test_fix_sentencepiece_tokenizer_guard.py b/tests/saving/test_fix_sentencepiece_tokenizer_guard.pyindex b97dc82f70c..73bdca0b342 100644--- a/tests/saving/test_fix_sentencepiece_tokenizer_guard.py+++ b/tests/saving/test_fix_sentencepiece_tokenizer_guard.py@@ -168,9 +168,8 @@ def test_each_call_uses_a_fresh_isolated_subdirectory(tmp_path, monkeypatch):def test_sentencepiece_scratch_dir_is_reclaimed_once_the_tokenizer_is_gone(tmp_path, monkeypatch):- """The scratch dir must live as long as the returned tokenizer (its vocab_file- points there), then be reclaimed when the tokenizer is garbage collected.- """+ """The scratch dir must outlive the returned tokenizer, whose vocab_file points into it, and be+ reclaimed once the tokenizer is garbage collected."""loaded = _stub_auto_tokenizer(monkeypatch)old, new = _tokenizers()location = str(tmp_path / "_unsloth_sentencepiece_temp")@@ -240,9 +239,8 @@ def test_source_vocab_outside_the_work_directory_is_not_disturbed(tmp_path, monkdef test_swap_mapping_swaps_both_pieces_without_duplicating(tmp_path, monkeypatch):- """When the caller swaps eos and stop_word in the fast JSON it must pass both- directions here; a one-way mapping would leave two stop_word pieces and no eos.- """+ """A swap of eos and stop_word in the fast JSON must map both directions; a one-way mapping+ would leave two stop_word pieces and no eos."""loaded = _stub_auto_tokenizer(monkeypatch)location = str(tmp_path / "_unsloth_sentencepiece_temp")@@ -282,9 +280,8 @@ def test_only_applied_mappings_are_patched(tmp_path, monkeypatch):def test_a_scratch_directory_created_by_another_process_is_reused(tmp_path, monkeypatch):- """Two processes sharing a working directory both see the scratch dir missing; the- second makedirs must not raise. Simulated by reporting the directory absent after- another process has already created it."""+ """Two processes sharing a working directory can both see the scratch dir missing, so the second+ makedirs must not raise; simulated by reporting it absent after creation."""import unsloth.tokenizer_utils as tokenizer_utils_stub_auto_tokenizer(monkeypatch)diff --git a/tests/saving/test_save_subprocess_utf8_encoding.py b/tests/saving/test_save_subprocess_utf8_encoding.pyindex 84fb7077a57..36a4687af2d 100644--- a/tests/saving/test_save_subprocess_utf8_encoding.py+++ b/tests/saving/test_save_subprocess_utf8_encoding.py@@ -89,9 +89,8 @@ def test_save_subprocess_text_calls_declare_utf8_encoding():def test_utf8_replace_decodes_non_cp1252_subprocess_output():- """Reproduce the bug and fix with a real subprocess: the child emits U+201D- (UTF-8 E2 80 9D, byte 0x9D undefined in cp1252) so cp1252 decode raises while- the fix's utf-8/replace kwargs read it cleanly."""+ """A real subprocess reproduces the bug: the child emits U+201D (UTF-8 E2 80 9D, where 0x9D is+ undefined in cp1252), so cp1252 decoding raises while utf-8 with replace reads it."""# All-ASCII argv; the child builds the non-ASCII char so it is locale-independent.child = ("import sys; "diff --git a/tests/security/test_lockfile_supply_chain_audit.py b/tests/security/test_lockfile_supply_chain_audit.pyindex 5fbb8bade46..a35825a4f07 100644--- a/tests/security/test_lockfile_supply_chain_audit.py+++ b/tests/security/test_lockfile_supply_chain_audit.py@@ -402,9 +402,8 @@ def test_skip_env_warning_escapes_workflow_command_injection(tmp_path):fixture = FIXTURES / "clean_lockfile.json"def _physical_lines_starting_with_double_colon(stderr: str) -> list[str]:- # GH Actions parses workflow commands per physical line.- # Only lines that START with `::` after any leading whitespace count as a new annotation.- # Any such line BEYOND the first warning is an injected command.+ # GitHub Actions parses workflow commands per physical line; only lines starting with ::+ # after leading whitespace count as annotations, so any extra one is injected.return [ln for ln in stderr.splitlines() if ln.lstrip().startswith("::")]injected_bad = "%inject\n::error::bad"diff --git a/tests/security/test_mapper_probe_no_exec.py b/tests/security/test_mapper_probe_no_exec.pyindex ac9cf4609b6..5162593a153 100644--- a/tests/security/test_mapper_probe_no_exec.py+++ b/tests/security/test_mapper_probe_no_exec.py@@ -275,9 +275,8 @@ def test_a_deferred_lambda_body_is_not_read(monkeypatch):def test_an_alias_added_inside_the_builder_is_read(monkeypatch):- """`build_mappers` is called at import, so its body runs. The aliases that cannot- be derived from the source table live in there, and the installed builder cannot- know one a newer mapper.py adds."""+ """build_mappers is called at import, so its body runs: aliases not derivable from the source+ table live there, and the installed builder cannot know ones a newer mapper.py adds."""lines = REAL_MAPPER.splitlines(True)for index, line in enumerate(lines):if line.startswith("def build_mappers("):diff --git a/tests/sh/test_get_torch_index_url.sh b/tests/sh/test_get_torch_index_url.shindex b8890abfcd4..3ab010f772a 100755--- a/tests/sh/test_get_torch_index_url.sh+++ b/tests/sh/test_get_torch_index_url.sh@@ -161,11 +161,9 @@ MOCKecho "$_dir"}-# amd-smi above emits ONE gfx token, which is not the shape a real host produces:-# _probe_amd_gfx_arch greps every match out of rocminfo, and rocminfo names each-# agent twice (Name: and the ISA Name:), so one card reads as two identical lines.-# Any gfx comparison that matters has to be exercised against this shape.-# $1 ROCm version, $2 gfx arch, $3 GPU agent count (default 1).+# The amd-smi mock above emits ONE gfx token, unlike a real host where rocminfo names each agent+# twice (Name and ISA Name); gfx checks must be tested with that shape; $1 ROCm version, $2 gfx+# arch, $3 agent count (default 1).make_mock_rocminfo() {_dir=$(make_mock_amd_smi "$1" "$2")_rocm_gfx="$2"diff --git a/tests/studio/_ts_deps.py b/tests/studio/_ts_deps.pyindex 04e89ba98a9..a4b4dabee9f 100644--- a/tests/studio/_ts_deps.py+++ b/tests/studio/_ts_deps.py@@ -531,12 +531,9 @@ def resolve_dependencies(for reference in home.references(harness_source):pull(reference, source)- # A declaration evaluated at import time cannot be left half-resolved: `const A = [B]` with `B` refused crashes the- # whole harness on load, which is worse than the lazy ReferenceError it replaced. Drop those to a fixed point- # instead. Functions and types are lazy or erased, so an unfollowed reference in one costs nothing until it is- # called, and so is a `const` bound to an arrow or function expression. A fixture the harness defines does not- # rescue one either: the fixtures sit BELOW this block, so reading- # one from here is a TDZ error rather than a resolution.+ # Eager declarations (const, let, var, class) that reference a refused helper crash the harness+ # on load, so drop them to a fixed point; functions, types and arrow consts are lazy and cost+ # nothing; fixtures sit below this block, so reading one here is a TDZ error.eager = {"const", "let", "var", "class"}while True:# Any reference to a half-resolved lazy helper dooms an eager declaration: whether it is called on load isdiff --git a/tests/studio/install/test_amd_fastpath_probe.py b/tests/studio/install/test_amd_fastpath_probe.pyindex 2374ab365a5..d6b9b5ca6c1 100644--- a/tests/studio/install/test_amd_fastpath_probe.py+++ b/tests/studio/install/test_amd_fastpath_probe.py@@ -730,9 +730,8 @@ def test_a_rocm_pin_is_not_asked_a_hardware_question(monkeypatch):def test_a_stale_family_no_index_can_repair_keeps_the_fast_path(monkeypatch):- """The preflight must not promise a repair the repair declines. gfx1010 has no AMD leaf- and no generic kernels, so _ensure_rocm_torch refuses on the same routability question,- and answering True here buys a dependency pass per update and never a working torch."""+ """The preflight must not promise a repair that _ensure_rocm_torch declines: gfx1010 has no AMD+ leaf or generic kernels, so answering True buys a pass per update and never a working torch."""_rocm_torch(monkeypatch, family = "gfx110x-all", gfx = ("gfx1010",))assert _needs_pass() is False# Datacentre parts have no leaf but are served by the generic index.@@ -782,8 +781,7 @@ def test_a_sole_gfx906_above_its_legacy_tag_forces_the_pass(monkeypatch):def test_a_repin_to_another_per_arch_leaf_forces_the_pass(monkeypatch):"""Both leaves are torch 2.11 with a three-part +rocm7.13.0 tag, so the pin arm's version- comparison sees no change and would keep the fast path over an edited pin -- the update- that was supposed to move the card onto its own wheels."""+ comparison sees no change and would keep the fast path over an edited pin."""_rocm_torch(monkeypatch,family = "gfx110x-all",diff --git a/tests/studio/install/test_amd_hybrid_igpu_routing_11143.py b/tests/studio/install/test_amd_hybrid_igpu_routing_11143.pyindex 3af11b12a28..899bf3dafed 100644--- a/tests/studio/install/test_amd_hybrid_igpu_routing_11143.py+++ b/tests/studio/install/test_amd_hybrid_igpu_routing_11143.py@@ -202,9 +202,8 @@ def _linux_host() -> "ILP.HostInfo":def test_only_a_flagged_marker_may_disagree_with_its_own_backend():- """_marker_backend_fits_host reads the pair as self-consistency evidence. A- disagreement the installer recorded on purpose is consistent; one with no flag is- still a marker this installer did not write, and keeps taking the full path."""+ """_marker_backend_fits_host reads the pair as self-consistency evidence: a flagged disagreement+ is deliberate, while an unflagged one is a marker not written here and takes the full path."""host = _linux_host()honest = {"backend_request": "vulkan", "backend": "vulkan"}unflagged = {"backend_request": "vulkan", "backend": "rocm"}diff --git a/tests/studio/install/test_cuda_repair.py b/tests/studio/install/test_cuda_repair.pyindex 09424f2eb1f..1d1dd92e96a 100644--- a/tests/studio/install/test_cuda_repair.py+++ b/tests/studio/install/test_cuda_repair.py@@ -57,9 +57,8 @@ def _make_run(smi_rc = 0,compute_caps = ("8.6",),):- """subprocess.run side_effect: the shared torch probe (sys.executable, text- stdout) vs the nvidia-smi version / compute-capability probes (smi path,- text=True), keyed on the executable."""+ """subprocess.run side_effect: the shared torch probe runs sys.executable with text stdout,+ while the nvidia-smi probes use the smi path with text=True, keyed on the executable."""def _run(cmd, *args, **kwargs):result = MagicMock()@@ -958,9 +957,8 @@ class TestExpectedTorchFlavorSkips:@pytest.mark.parametrize("backend", ["rocm", "xpu"])def test_a_gpu_backend_that_disagrees_with_the_handover_is_a_no_op(self, backend):- """An explicit ROCm/XPU pin against a cu124 handover. The pin is the newer and- more specific instruction; the handover only describes what the install arm- above it happened to do, so the pin wins and this pass stays out of it."""+ """An explicit ROCm or XPU pin beats a cu124 handover, which only records what the install+ arm happened to do, so this pass stays out of it."""ok, mock_pip = _run_flavor_invariant(backend = backend, expected_env = "cu124")assert ok is Truemock_pip.assert_not_called()diff --git a/tests/studio/install/test_denied_llama_cpp_preflight.py b/tests/studio/install/test_denied_llama_cpp_preflight.pyindex 2af38a4e1ab..7a12d386786 100644--- a/tests/studio/install/test_denied_llama_cpp_preflight.py+++ b/tests/studio/install/test_denied_llama_cpp_preflight.py@@ -341,9 +341,8 @@ def test_setup_sh_reports_a_denied_default_home_cache() -> None:def test_the_denial_detail_survives_a_directory_it_cannot_open() -> None:- """Get-Item returns nothing for a directory whose ACL denies read, which is the- one case this detail exists for, so the attributes have to come through an API- that needs only FILE_READ_ATTRIBUTES."""+ """Get-Item returns nothing for a directory whose ACL denies read, so attributes must come+ through an API needing only FILE_READ_ATTRIBUTES, such as [System.IO.File]::GetAttributes."""for text in (INSTALL_PS1, SETUP_PS1):body = _function_source(text, "Get-PathDenialDetail")assert "[System.IO.File]::GetAttributes($Path)" in bodydiff --git a/tests/studio/install/test_dependency_pass_skips.py b/tests/studio/install/test_dependency_pass_skips.pyindex 6cc8d7ec7a3..c9d99da17fa 100644--- a/tests/studio/install/test_dependency_pass_skips.py+++ b/tests/studio/install/test_dependency_pass_skips.py@@ -361,9 +361,8 @@ def test_pip_install_and_the_gate_share_one_filter() -> None:def test_a_git_requirement_is_matched_by_ref_not_version(monkeypatch, tmp_path) -> None:- """The same version is published from every branch, so a release/3.6.x pin is- satisfied on paper by a build from main. direct_url.json is the only place the ref- survives the install."""+ """The same version is published from every branch, so a release/3.6.x pin is satisfied on paper+ by a main build; direct_url.json is the only place the ref survives install."""req = tmp_path / "triton-kernels.txt"req.write_text("# comment\n"@@ -687,9 +686,8 @@ def test_no_closure_record_is_kept_under_a_callers_uv_override(monkeypatch, gatedef test_a_caller_supplied_uv_override_forces_a_full_pass(monkeypatch, manifest) -> None:- """uv applies UV_OVERRIDE to every step and its versions replace requirements- outright; the gate digests only the bundled macOS file, so a caller's own file is- an input the evidence cannot see."""+ """uv applies UV_OVERRIDE to every step and its versions replace requirements outright; the gate+ digests only the bundled macOS file, so a caller's own file is invisible."""payload, req_root = manifestmonkeypatch.setattr(stack.install_manifest, "read_manifest", lambda *a, **k: dict(payload))foreign = req_root / "my-overrides.txt"@@ -1005,9 +1003,8 @@ def test_the_mlx_pins_match_the_runtime_repair() -> None:],)def test_a_resident_codec_inside_the_window_needs_no_install(spec, installed, expected) -> None:- """The local tag is ignored here on purpose: provenance is the caller's separate- question, and a +cu130 suffix puts the version outside a PyPI-shaped specifier it- in fact satisfies."""+ """The local tag is ignored on purpose, since provenance is the caller's separate question, and+ a +cu130 suffix would put a version outside a PyPI-shaped specifier it satisfies."""assert stack._codec_spec_is_satisfied(spec, installed) is expected@@ -1080,9 +1077,8 @@ _PIP_REFUSED = "Cannot uninstall ghost 1.0, RECORD file not found: no RECORD fildef test_purging_a_half_written_record_counts_as_an_install_action(counting, tmp_path) -> None:- """It rmtree's a dist-info pip was reading a moment ago. Nothing else on that path- touches the counter, so a constraint answer cached before it would survive it and- let a gated step skip on evidence about an environment that no longer exists."""+ """Purging a dist-info pip was reading must count as an install action, or a constraint answer+ cached before it would let a gated step skip on stale evidence."""_site_with_recordless_dist(counting, tmp_path)assert stack._purge_recordless_distributions(_PIP_REFUSED) == ["ghost-1.0.dist-info"]assert stack._INSTALL_ACTIONS == 1@@ -1090,9 +1086,8 @@ def test_purging_a_half_written_record_counts_as_an_install_action(counting, tmpdef test_a_purge_that_deletes_nothing_leaves_the_cache_alone(counting, tmp_path) -> None:- """The other direction, and the reason this is counted at the rmtree rather than at- the top of the function: `pip check` is gated on the same counter, so a spurious- increment buys a full metadata resolve of the venv on every no-op update."""+ """The count sits at the rmtree, not the top of the function, because pip check is gated on the+ same counter and a spurious increment forces a full metadata resolve on every no-op update."""site = _site_with_recordless_dist(counting, tmp_path)assert stack._purge_recordless_distributions("") == []assert stack._purge_recordless_distributions("some unrelated pip failure") == []@@ -1478,9 +1473,8 @@ def test_the_verdict_is_recorded_after_the_manifest_is_written() -> None:def test_the_escape_hatch_reaches_the_pip_bootstrap_skip() -> None:- """UNSLOTH_STUDIO_FULL_DEPS is what a user is told to set when the install is- behaving oddly. A step it cannot turn off is a step they cannot work around, and the- pip bootstrap skip is not gated on the manifest, so nothing else would reach it."""+ """UNSLOTH_STUDIO_FULL_DEPS is the escape hatch users set when the install misbehaves, and the+ pip bootstrap skip is not gated on the manifest, so it must honour the flag."""source = STACK_PATH.read_text(encoding = "utf-8")assert "if not _full_deps_requested() and _venv_pip_is_usable():" in source@@ -1628,9 +1622,8 @@ def test_an_unreadable_requirements_file_is_never_skipped(tmp_path) -> None:def test_a_carried_known_unmet_record_drops_what_is_met_again(monkeypatch, gated) -> None:- """A skipped step carries its record, narrowed to what the closure still lacks: an- entry satisfied since it was recorded was no conflict, and keeping it would let a- later loss of that package pass as intentional."""+ """A skipped step carries its record narrowed to what the closure still lacks, since keeping an+ entry satisfied since recording would let a later loss pass as intentional."""_payload, req_root = gatedmonkeypatch.setattr(stack, "_AUDITED_STEPS", {"studio.txt": req_root / "studio.txt"})monkeypatch.setattr(stack, "_STEP_RESULTS", {"studio.txt": "skipped"})@@ -1662,9 +1655,8 @@ def test_the_closure_walk_follows_extras_and_survives_cycles(tmp_path) -> None:def test_an_extra_named_before_pep_685_is_still_followed(tmp_path) -> None:- """A wheel built before extras were normalised in the marker still says- extra == "all_files", and matching only the canonical spelling would drop that- extra's whole subtree without a word."""+ """A wheel built before PEP 685 still says extra == "all_files" in its marker, and matching only+ the canonical spelling would silently drop that extra's subtree."""req = tmp_path / "studio.txt"req.write_text("alpha[all_files]\n", encoding = "utf-8")index = _closure_index(alpha = ("1.0", ['beta ; extra == "all_files"']))@@ -1688,9 +1680,8 @@ def test_an_inapplicable_marker_is_not_a_missing_dependency(tmp_path) -> None:],)def test_the_closure_audit_fails_closed(tmp_path, line, reason) -> None:- """Every answer that is not a proven-complete closure has to install. A flag line- can hide requirements from the walk entirely, and guessing the other way would let- a step skip on evidence nobody gathered."""+ """Every answer that is not a proven-complete closure must install, since a flag line can hide+ requirements from the walk and guessing would skip on ungathered evidence."""req = tmp_path / "studio.txt"req.write_text(f"{line}\n", encoding = "utf-8")assert stack.install_manifest.unsatisfied_closure_requirement(req, {}) == reason@@ -1774,9 +1765,8 @@ def test_every_gated_step_states_whether_it_installs_with_deps() -> None:@pytest.mark.parametrize("value", ["1", "true", "YES", " on "])def test_the_escape_hatch_reaches_the_pin_shaped_steps(monkeypatch, value) -> None:- """torchao, MLX and torchcodec compare against the installed distribution rather- than a recorded digest, so a satisfied pin read as "nothing to do" even on the pass- that was asked to do everything."""+ """torchao, MLX and torchcodec compare against the installed distribution rather than a recorded+ digest, so a satisfied pin read as nothing to do even on a full pass."""monkeypatch.setattr(stack, "_PASS_EVIDENCE", {"pass_inputs": {}, "step_results": {}})assert stack._may_skip_on_evidence() is Truemonkeypatch.setenv(stack._FULL_DEPS_ENV, value)@@ -1828,9 +1818,8 @@ def test_the_mlx_and_codec_skips_ask_for_the_evidence_too() -> None:def test_the_npp_repair_is_not_conditional_on_reinstalling_the_codec() -> None:- """NPP is a separate distribution with its own failure modes. While the repair was- gated on the codec step having run, a codec the skip accepted meant a missing NPP- was never looked at again, and torchcodec's CUDA build cannot import without it."""+ """NPP is a separate distribution, so its repair must not depend on the codec step: a skipped+ codec would hide a missing NPP that torchcodec's CUDA build needs."""source = STACK_PATH.read_text(encoding = "utf-8")assert " elif _codec_index:\n" in sourceassert source.count('_STEP_RESULTS.get("torchcodec") == "ran"') == 1@@ -1958,9 +1947,8 @@ def test_the_mlx_payload_check_walks_each_records_files(monkeypatch, tmp_path) -def test_the_parked_manifest_goes_right_after_the_live_one_is_removed(monkeypatch, tmp_path):- """remove_manifest parks the live copy for setup.ps1's ordering. On the path that- read the live manifest itself, the parked copy would otherwise outlive a pass killed- part-way and be read by the next run as evidence of a completed pass."""+ """remove_manifest parks the live copy for setup.ps1's ordering; a parked copy that outlived a+ killed pass would later be read as evidence of a completed pass."""manifest = stack.install_manifestlive = tmp_path / manifest.MANIFEST_NAMEparked = tmp_path / manifest.PREVIOUS_MANIFEST_NAME@@ -1978,9 +1966,8 @@ def test_the_parked_manifest_goes_right_after_the_live_one_is_removed(monkeypatcdef test_an_input_missing_from_the_record_or_unreadable_now_is_changed(monkeypatch, tmp_path):- """pass_input_digests leaves out a file it could not read and digest_file answers None- for one it cannot read now; compared with .get, the two Nones were equal and an- unreadable requirements file counted as unchanged."""+ """Pass input digests must not be compared with .get: a file missing from the record and one+ unreadable now both yield None and would wrongly read as unchanged."""monkeypatch.setattr(stack, "REQ_ROOT", tmp_path)monkeypatch.setattr(stack, "_PASS_EVIDENCE", {"pass_inputs": {"studio.txt": "abc"}})digests = {"studio.txt": "abc"}@@ -2051,9 +2038,8 @@ def audited(monkeypatch, tmp_path):def test_a_requirements_file_the_update_replaced_still_lets_the_manifest_be_written(audited,) -> None:- """The failure this guards is the worst shape available: every package installed, the- pass then dies with a traceback, and the venv is left with no manifest at all -- which- every reader takes for a half-built install."""+ """A requirements file the update replaced must not stop the manifest being written: otherwise+ every package installs, the pass dies, and the missing manifest looks half-built."""(audited / "studio.txt").unlink()assert isinstance(stack._closure_record(), dict)diff --git a/tests/studio/install/test_desktop_capability_llama_runtime.py b/tests/studio/install/test_desktop_capability_llama_runtime.pyindex 6f88110c5aa..fc47fd4f78d 100644--- a/tests/studio/install/test_desktop_capability_llama_runtime.py+++ b/tests/studio/install/test_desktop_capability_llama_runtime.py@@ -256,12 +256,8 @@ def test_the_human_readable_form_still_prints_every_key(tmp_path):@NEEDS_VENVdef test_the_probe_stays_off_the_critical_path_budget(tmp_path):- """The command runs at every launch under a desktop timeout, so its cost is a product- constraint. Measured as the import plus the call, which is all the try block does.-- The bound is loose (half a second against a measured ~30ms), so it catches a probe that- grew a network call or a GPU detection rather than CI jitter.- """+ """The command runs at every launch under a desktop timeout; the loose half-second bound on+ import plus call catches a network or GPU probe, not CI jitter."""assert VENV_PYTHON is not Noneroot = tmp_path / "llama.cpp"_complete_tree(root)@@ -340,9 +336,8 @@ def test_an_unimportable_probe_leaves_the_verdict_null(tmp_path):def test_the_command_emits_exactly_the_pre_pr_keys_plus_the_two_new_ones():- """Read off the source, so it holds without the venv. A key added without a matching- Option<T> in managed.rs is invisible to the desktop; a key removed breaks it.- """+ """Read off the source so it holds without the venv: a key added without a matching Option<T> in+ managed.rs is invisible to the desktop, and a removed key breaks it."""source = (PACKAGE_ROOT / "unsloth_cli" / "commands" / "studio.py").read_text(encoding = "utf-8")body = source.split("def desktop_capabilities(", 1)[1]body = body.split("if json_output:", 1)[0]@@ -353,10 +348,8 @@ def test_the_command_emits_exactly_the_pre_pr_keys_plus_the_two_new_ones():@NEEDS_VENVdef test_dropping_the_new_keys_yields_the_pre_pr_payload(tmp_path):- """Additive, proven by subtraction: strip the two keys and what is left is a payload the- pre-PR desktop already accepted. Neither version constant may move, since bumping one- tells a desktop to treat the CLI as stale.- """+ """Additive, proven by subtraction: without the two new keys the payload is what the pre-PR+ desktop accepts; neither version constant may move or the CLI reads as stale."""root = tmp_path / "llama.cpp"_complete_tree(root)rc, out = _capabilities(root, tmp_path)@@ -368,10 +361,8 @@ def test_dropping_the_new_keys_yields_the_pre_pr_payload(tmp_path):def test_the_desktop_reads_every_emitted_key_as_optional():- """A desktop built from this tree must survive a pre-PR CLI sending neither new key.- serde fills an absent Option with None and managed.rs only treats Some(false) as broken,- so absent is safe only while every field stays an Option.- """+ """A desktop must survive a pre-PR CLI sending neither new key: serde maps an absent field to+ None and managed.rs only flags Some(false), so every field must stay an Option."""source = MANAGED_RS.read_text(encoding = "utf-8")struct_body = source.split("struct DesktopCapability {", 1)[1].split("\n}", 1)[0]fields = dict(re.findall(r"^\s+([a-z_]+):\s*(.+),$", struct_body, flags = re.MULTILINE))diff --git a/tests/studio/install/test_gpu_detection_followups.py b/tests/studio/install/test_gpu_detection_followups.pyindex b5930f58ca1..0d4207e1424 100644--- a/tests/studio/install/test_gpu_detection_followups.py+++ b/tests/studio/install/test_gpu_detection_followups.py@@ -452,9 +452,8 @@ class TestHiddenCvdNotUsable:class TestSetupShPhysicalNvidiaSurvivesTheMask:- """The nvcc source-build search is gated on this probe, so it has to answer true under- a mask that makes the usable probe answer false. Gated on usable, a masked host- compiled a CPU-only binary and activated it over the tree permanently."""+ """The nvcc source-build search must gate on the physical NVIDIA probe, which stays true under+ any mask; gating on usable let a masked host activate a CPU-only binary."""@pytest.mark.parametrize("cvd", [None, "", "-1", "0"])def test_the_physical_probe_ignores_every_mask(self, tmp_path, cvd):diff --git a/tests/studio/install/test_install_llama_prebuilt_logic.py b/tests/studio/install/test_install_llama_prebuilt_logic.pyindex 75fab012bbd..43ec618e243 100644--- a/tests/studio/install/test_install_llama_prebuilt_logic.py+++ b/tests/studio/install/test_install_llama_prebuilt_logic.py@@ -959,9 +959,8 @@ def _fail_activation_then_restore_rename(def test_activate_install_tree_reports_a_recovery_disk_full_as_out_of_space(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, make_copy_error):- """The copy back is the first step here that needs free space -- everything before- it renames or deletes -- so a full disk shows up there and nowhere else. Dropping- it would start a source build needing far more room than the copy that failed."""+ """The copy back is the first step that needs free space, so a full disk shows up only there;+ dropping it would start a source build needing far more room than the failed copy."""install_dir, staging_dir = _fail_activation_then_restore_rename(tmp_path, monkeypatch, make_copy_error())@@ -2735,9 +2734,8 @@ def test_arch_fields_do_not_change_the_install_fingerprint(tmp_path: Path):def test_non_rocm_bundles_record_no_mapped_targets(tmp_path: Path):- """CPU/CUDA/Vulkan/macOS choices never populate the arch fields (#7624): only- published_rocm_choice_for_host sets them, so the marker records [] and the runtime- gate fails open on a non-ROCm bundle."""+ """Only published_rocm_choice_for_host sets the arch fields (issue 7624), so CPU, CUDA, Vulkan+ and macOS bundles record an empty list and the runtime gate fails open."""checksums = release_checksums()for kind, asset in (("linux-cpu", "app-b9001-linux-x64-cpu.tar.gz"),@@ -3417,16 +3415,8 @@ def test_install_prebuilt_skips_when_older_release_fallback_matches_existing_ins@pytest.mark.skipif(os.name == "nt", reason = "the root wrapper is written on POSIX only")@pytest.mark.parametrize("name", ["llama-server", "llama-quantize"])def test_a_damaged_root_entrypoint_stops_the_release_being_reused(tmp_path: Path, name: str):- """Codex 3973890098, P1. The keep decision graded only build/bin, so an online repair- took the shortcut, replaced nothing, and every later launch offered the same repair- again. Both read _damaged_entrypoint now.-- Codex 4056336250, P2 narrowed what the LAUNCH side of it may reject: the resolver- returns the first usable candidate, so it walks past a root wrapper with no execute- bit and runs build/bin, and marking that tree stale repairs a runtime that works. The- keep decision is deliberately left strict, since replacing a rotten wrapper is exactly- what a reinstall is for, and that direction is safe: the launch verdict is never- stricter than the repair that answers it."""+ """Keep decisions read _damaged_entrypoint so a rotten root wrapper forces repair; the launch+ check must not mark stale a tree the resolver can still run via build/bin."""install_dir = tmp_path / "llama.cpp"install_dir.mkdir()write_linux_install_shape(install_dir)@@ -6081,9 +6071,8 @@ def test_supported_sms_stays_out_of_the_install_fingerprint():[("linux-vulkan", "vulkan"), ("linux-cpu", "cpu"), ("linux-rocm", "rocm")],)def test_a_non_cuda_bundle_declares_no_supported_sms(tmp_path: Path, install_kind, runtime_line):- """The runtime gate has no is_vulkan_backend guard; it stays inert there- only because a non-CUDA bundle records an empty list, which reads as unknown- coverage. Pin that at the writing end."""+ """The runtime gate has no is_vulkan_backend guard and stays inert only because a non-CUDA+ bundle records an empty supported_sms list, which reads as unknown coverage."""install_dir = tmp_path / "llama.cpp"install_dir.mkdir()choice = _cuda_choice(install_kind = install_kind, runtime_line = runtime_line, supported_sms = None)@@ -6500,9 +6489,8 @@ def test_a_custom_repo_is_answered_the_way_the_selector_orders_it(tmp_path, monkdef test_a_release_payload_this_run_already_has_overrides_the_latest_pointer(tmp_path, monkeypatch):- """/releases/latest resolves by make_latest/created_at; the macOS path orders by- published_at. When a payload already in hand disagrees with the pointer, the- published_at answer wins -- for free, because it costs no request."""+ """/releases/latest resolves by make_latest and created_at but macOS orders by published_at; a+ payload in hand that disagrees with the pointer wins at no request cost."""install_dir = _current_install(tmp_path, monkeypatch)monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_download_host_latest_release_tag", lambda _repo: "release-1"@@ -6561,9 +6549,8 @@ def test_a_pinned_release_tag_needs_no_lookup_at_all(tmp_path, monkeypatch):def test_an_upstream_pin_is_answered_by_the_recorded_upstream_tag(tmp_path, monkeypatch):- """The marker must record the pinned build, and the release installed must be the- fork's newest packaging of it (the fork can republish a build); /releases/latest- has nothing to say about a pin."""+ """The marker records the pinned upstream build, and the release installed is the fork's newest+ packaging of it since the fork can republish; /releases/latest says nothing of pins."""install_dir = _current_install(tmp_path, monkeypatch)marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text(encoding = "utf-8"))@@ -6636,9 +6623,8 @@ def test_a_gpu_removed_since_the_install_is_not_current(tmp_path, monkeypatch):def test_a_new_gpu_outside_the_recorded_coverage_is_not_current(tmp_path, monkeypatch):- """A bundle carries kernels for a fixed set of SMs (supported_sms). Swapping the- card for one outside that set leaves an install that starts and then cannot run a- model, which is worse than a reinstall."""+ """A bundle carries kernels only for its supported_sms; a card outside that set leaves an+ install that starts but cannot run a model, which is worse than a reinstall."""install_dir = _current_install(tmp_path, monkeypatch, install_host = linux_host(**_CUDA_HOST_FIELDS))@@ -6693,9 +6679,8 @@ def test_a_marker_naming_a_backend_this_platform_cannot_hold_is_not_current(tmp_def test_a_marker_whose_request_and_backend_disagree_is_not_current(tmp_path, monkeypatch):- """A concrete request must name the bundle's own backend, or say outright that it is- a request the install could not honour (the test below). A bare disagreement with no- such flag was not written by this installer."""+ """A concrete backend request must name the bundle's own backend unless the marker flags it+ unsatisfied; a bare disagreement was not written by this installer."""install_dir = _current_install(tmp_path, monkeypatch, backend_request = "vulkan")assert _check(install_dir, backend_request = "vulkan") is False@@ -6715,9 +6700,8 @@ def test_an_unsatisfied_choice_read_off_the_marker_does_not_reinstall_every_updadef test_an_unsatisfied_choice_named_by_this_run_is_re_asserted(tmp_path, monkeypatch):- """--llama-backend vulkan (or Settings, which passes it) is someone asking again by- hand: take the full path, where the request is re-asserted and, if it still cannot be- served, fails loudly instead of silently keeping the bundle it did not ask for."""+ """An explicit --llama-backend vulkan (or Settings) takes the full path, re-asserting the+ request and failing loudly rather than silently keeping an unrequested bundle."""install_dir = _current_install(tmp_path, monkeypatch, **_UNSATISFIED)assert _check(install_dir, backend_request = "vulkan", backend_request_mandatory = True) is False@@ -6743,9 +6727,8 @@ def test_an_old_marker_is_read_as_a_satisfied_choice(tmp_path, monkeypatch):def test_a_truncated_shared_library_is_not_current(tmp_path, monkeypatch):- """The payload scan only globs for existence, so a half-written libggml-*.so keeps- its name and passes it. Most of a CUDA bundle's bytes live in those libraries, and a- full disk or an interrupted extract leaves exactly this shape."""+ """The payload scan only checks that files exist, so a half-written libggml shared library+ passes; most CUDA bundle bytes live there and a full disk leaves exactly this shape."""install_dir = _current_install(tmp_path, monkeypatch)library = install_dir / "build" / "bin" / "libggml-cpu-x64.so.0"assert library.is_file()@@ -6776,9 +6759,8 @@ def test_the_payload_records_cover_the_bundles_own_allowlist(tmp_path, monkeypatdef test_the_reuse_path_backfills_what_the_no_network_check_needs(tmp_path, monkeypatch):- """An install made before this PR carries none of the new evidence, so it would take- the slow path on EVERY update. The reuse path is the only place that sees the bundle- again without reinstalling it, so it is where the record gets caught up -- once."""+ """Installs from before the new evidence existed would take the slow path on every update, so+ the reuse path, the only place that sees them, backfills the record once."""install_dir = _current_install(tmp_path,monkeypatch,@@ -6801,9 +6783,8 @@ def test_the_reuse_path_backfills_what_the_no_network_check_needs(tmp_path, monkdef test_an_empty_runtime_record_is_backfilled_like_an_absent_one(tmp_path, monkeypatch):- """runtime_file_records answers {} when a binary could not be read; a marker that- persisted it would fail the no-network check closed forever unless the reuse path- treats it as missing and records it again once the bytes can be read."""+ """runtime_file_records answers {} for an unreadable binary; a persisted empty record would fail+ the no-network check closed forever, so reuse must backfill it."""install_dir = _current_install(tmp_path, monkeypatch, runtime_files = {})assert _check(install_dir) is Falsesync_marker_selection(@@ -6974,9 +6955,8 @@ def test_a_route_the_caller_already_made_is_not_recomputed(tmp_path, monkeypatchdef test_the_profile_sees_an_nvidia_adapter_that_is_present_but_not_usable():- """The Intel and ROCm-less AMD routes go to Vulkan only when there is NO NVIDIA- adapter at all, so an adapter that appears or goes without ever becoming usable- changes the selection while has_usable_nvidia and every other field stay equal."""+ """Intel and ROCm-less AMD routes go to Vulkan only when no NVIDIA adapter is present at all, so+ the profile must track has_physical_nvidia apart from has_usable_nvidia."""host = linux_host(has_intel_gpu = True)assert host_profile(host)["has_physical_nvidia"] is Falsewith_adapter = dataclasses.replace(host, has_physical_nvidia = True)@@ -7057,9 +7037,8 @@ def test_latest_on_an_older_mac_expects_the_pinned_upstream_fallback(monkeypatchdef test_a_pinned_upstream_build_expects_the_newest_fork_packaging_of_it(monkeypatch):- """The fork can republish a build (b9596-mix-aaa, then b9596-mix-bbb) and the selector- installs the newest packaging; the marker check asks the same question instead of- reading the recorded release as current forever."""+ """The fork can republish a build (b9596-mix-aaa, then b9596-mix-bbb) and the selector installs+ the newest packaging, so the marker check must ask the same question."""M = INSTALL_LLAMA_PREBUILTreleases = [{"tag_name": "b9600-mix-ccc", "published_at": "2026-03-01T00:00:00Z", "id": 3},@@ -7198,9 +7177,8 @@ def test_a_moved_torch_cuda_preference_declines_the_marker_fast_path(monkeypatchdef test_the_host_profile_carries_the_cuda_runtimes_on_disk(monkeypatch):- """The CUDA selectors order the bundles by the runtimes on disk as well as by torch's- preference; a runtime that appeared since the install changes the selection with the- GPU and driver unchanged, so it has to move the profile the marker check compares."""+ """CUDA selectors order bundles by the runtimes on disk too; a runtime that appeared since+ install changes selection with GPU and driver unchanged, so the profile must carry it."""M = INSTALL_LLAMA_PREBUILThost = linux_host(compute_caps = ["8.9"], has_physical_nvidia = True, has_usable_nvidia = True)monkeypatch.setattr(M, "detected_linux_runtime_lines", lambda: (["cuda12"], {}))diff --git a/tests/studio/install/test_install_manifest_pass_evidence.py b/tests/studio/install/test_install_manifest_pass_evidence.pyindex bc2268c72d2..e13e0770aa9 100644--- a/tests/studio/install/test_install_manifest_pass_evidence.py+++ b/tests/studio/install/test_install_manifest_pass_evidence.py@@ -263,9 +263,8 @@ def test_a_symlink_on_the_lock_name_is_not_followed(tmp_path: pathlib.Path) -> Ndef test_a_filesystem_without_locking_is_not_waited_out(tmp_path: pathlib.Path, monkeypatch) -> None:- """Some NFS and SMB mounts answer immediately that they do not implement locking. Only- contention is worth waiting out; retrying that answer would cost the whole deadline on- every manifest write."""+ """Some NFS and SMB mounts answer at once that locking is unsupported; only contention is worth+ waiting out, since retrying would cost the whole deadline on every write."""fcntl = pytest.importorskip("fcntl")monkeypatch.setattr(im, "LOCK_WAIT_SECONDS", 5.0)@@ -367,9 +366,8 @@ def test_remove_manifest_keeps_the_live_one_when_the_parked_name_cannot_be_cleardef test_remove_manifest_refuses_an_unclearable_parked_copy_with_no_live_manifest(tmp_path: pathlib.Path,) -> None:- """An interrupted run already took the live manifest. Nothing is parked by this call, so- a surviving copy is that dead run's, and answering True would send setup.ps1 into its- pip/torch mutations ahead of the refusal the pass makes on exactly that path."""+ """With no live manifest, a surviving parked copy belongs to a dead run, so remove_manifest must+ return False; True would send setup.ps1 into pip/torch mutations."""blocked = tmp_path / im.PREVIOUS_MANIFEST_NAMEblocked.mkdir()(blocked / "keep.txt").write_text("x", encoding = "utf-8")@@ -401,9 +399,8 @@ def test_remove_manifest_parks_over_a_stale_copy_it_can_clear(tmp_path: pathlib.@pytest.mark.skipif(os.name == "nt", reason = "POSIX file modes")def test_the_manifest_keeps_the_mode_it_had(tmp_path: pathlib.Path) -> None:- """It used to be written through Path.write_text, so it carried the umask default and- anything else on the machine could read it. mkstemp creates at 0600, and silently- narrowing a file other tooling may read is a change nobody asked for."""+ """The manifest must keep its umask-default mode: mkstemp creates 0600, and silently narrowing a+ file other tooling may read is a change nobody asked for."""previous = os.umask(0o022)try:im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")@@ -442,9 +439,8 @@ def test_two_writers_do_not_share_a_temp_file(tmp_path: pathlib.Path) -> None:def test_update_manifest_does_not_recreate_one_removed_while_it_worked(tmp_path: pathlib.Path, monkeypatch) -> None:- """A peer running an older build of this module removes the manifest without taking the- lock. Writing it back would put a completion marker over the venv that peer is part-way- through rebuilding."""+ """An older peer build removes the manifest without taking the lock; writing it back would mark+ a venv still being rebuilt as complete, so it must not be recreated."""im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")live = tmp_path / im.MANIFEST_NAMEreal_read = im.read_manifest@@ -810,9 +806,8 @@ def test_a_console_script_alone_does_not_prove_the_payload_arrived(sidecar: pathdef test_a_distribution_with_no_record_at_all_is_not_current(sidecar: pathlib.Path) -> None:- """No directory and no RECORD to fall back to leaves nothing that says the files- landed, and the answer has to be the one that repairs rather than the one that- ships a sidecar the worker cannot import."""+ """With no package directory and no RECORD there is no evidence the files landed, so the answer+ must be not current, which repairs rather than ships an unimportable sidecar."""dist_info = sidecar / "ghost-1.0.dist-info"dist_info.mkdir()(dist_info / "METADATA").write_text(@@ -823,9 +818,8 @@ def test_a_distribution_with_no_record_at_all_is_not_current(sidecar: pathlib.Padef test_a_pinned_sidecar_package_with_no_record_is_rebuilt(sidecar: pathlib.Path) -> None:- """An absent RECORD used to say nothing about damage, since the answer costs a- several-hundred-MB refetch; but pip and uv write RECORD last, so a pinned package- without one is an interrupted install whose payload the size check cannot see."""+ """A pinned package without RECORD is rebuilt: pip and uv write RECORD last, so its absence+ marks an interrupted install that the size check cannot see."""(sidecar / "transformers-5.3.0.dist-info" / "RECORD").unlink()ok, reason = im.sidecar_is_current(sidecar, PINS)assert ok is Falsediff --git a/tests/studio/install/test_install_node_prebuilt_logic.py b/tests/studio/install/test_install_node_prebuilt_logic.pyindex 7183498e26f..3c9461d19dc 100644--- a/tests/studio/install/test_install_node_prebuilt_logic.py+++ b/tests/studio/install/test_install_node_prebuilt_logic.py@@ -1131,9 +1131,8 @@ def _real_node_tree(root: Path, host) -> None:def test_a_verified_install_is_not_re_probed(tmp_path: Path, monkeypatch):- """`node -v` is an interpreter start of a 110 MB runtime, run on every install and- every update to re-derive an answer that cannot have changed while the binary has- not."""+ """A verified node install is not re-probed: running node -v on a 110 MB runtime on every+ install re-derives an answer that cannot change while the binary is unchanged."""host = _host("linux", "x64")_real_node_tree(tmp_path, host)M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")@@ -1176,11 +1175,9 @@ def _runnable_node_tree(def test_a_node_that_no_longer_runs_is_caught_even_at_the_recorded_size_and_mtime(tmp_path: Path, monkeypatch):- """The record compares size and mtime_ns, not the digest, so a rewrite that preserves- both is invisible TO THE RECORD. It is not invisible to the check: npm-cli.js is run BY- the node binary, and that probe is never skipped, so a node that cannot run is still- rejected and repaired. This pins the reason the digest is affordable to skip.- """+ """The record compares size and mtime_ns, not the digest; a rewrite that preserves both is still+ caught when the node can no longer run, because the node and npm-cli.js spawn probes are+ never skipped."""host = _host("linux", "x64")node = _runnable_node_tree(tmp_path, host)M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")@@ -1295,12 +1292,8 @@ _EXECUTE_BIT_IS_ENFORCED = os.name != "nt" and getattr(os, "geteuid", lambda: 0)reason = "needs an unprivileged POSIX user: root and Windows both ignore the execute bit",)def test_a_node_that_lost_its_execute_bit_is_not_a_match(tmp_path: Path, monkeypatch):- """Dropping the execute bit is invisible to the record: it moves ctime, and nothing else.-- Size and mtime_ns both survive it, so the file record still matches a node that can no- longer be started. The spawn the record stands in for would have failed here and the- install would have been repaired, which is the outcome that has to be kept.- """+ """Dropping the execute bit moves only ctime, so the size and mtime_ns record still matches; the+ spawn it stands in for would fail, and the install must be repaired."""host = _host("linux", "x64")_real_node_tree(tmp_path, host)M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")diff --git a/tests/studio/install/test_install_whisper_prebuilt_logic.py b/tests/studio/install/test_install_whisper_prebuilt_logic.pyindex c5e7f69a38c..e6affcdd6a1 100644--- a/tests/studio/install/test_install_whisper_prebuilt_logic.py+++ b/tests/studio/install/test_install_whisper_prebuilt_logic.py@@ -2492,9 +2492,8 @@ def test_the_whisper_reuse_path_backfills_the_paired_ggml_tree(tmp_path, monkeypdef test_the_whisper_backfill_never_rewrites_a_recorded_tree(tmp_path, monkeypatch):- """Added, never corrected: a marker that already names a tree was written by the run- that installed against it, and a llama runtime that moved since is exactly what the- pre-check is supposed to notice."""+ """The whisper backfill adds a missing pairing record but never rewrites one: a recorded tree+ was written against its llama runtime, which the pre-check must notice if it moved."""install_dir, _host, _ = _installed_cpu_tree(tmp_path, monkeypatch)_slim_marker(install_dir)monkeypatch.setattr(M, "installed_llama_ggml_tree", lambda: "ggml-def")@@ -2635,9 +2634,8 @@ def test_a_raw_network_error_from_the_release_fetch_still_keeps_the_install(reason = "os.access(X_OK) is always true on Windows, so the unusable-tree half is POSIX only",)def test_an_unreachable_lookup_still_fails_on_a_broken_install(tmp_path, monkeypatch, capsys):- """Fail-open is the right answer for a tree that cannot serve dictation, and the- message that says so sends the user to browser and Transformers STT. Only the- evidence a previous run left behind may replace it."""+ """Fail-open is the right answer for a tree that cannot serve dictation, with a message pointing+ to browser and Transformers STT; only evidence a previous run left may replace it."""install_dir, host, _ = _installed_cpu_tree(tmp_path, monkeypatch)marker_path = install_dir / M.METADATA_FILENAMErecorded = marker_path.read_bytes()@@ -2689,9 +2687,8 @@ def test_the_kept_path_refuses_a_mismatched_ggml_pairing(tmp_path, monkeypatch,def test_a_pairing_gap_still_reports_itself(tmp_path, monkeypatch, capsys):- """The one lookup failure that ANSWERED. Exit 2 is how setup learns to print the- installed-versus-required tags and tell the user to publish the paired releases; a- keep would replace a release skew nobody would then fix with a soothing warning."""+ """The one lookup failure that answered: exit 2 makes setup print installed versus required tags+ and ask for paired releases; keeping the install would hide the skew."""install_dir, _host, _ = _installed_cpu_tree(tmp_path, monkeypatch)_no_network(monkeypatch)rc, output = _cli_install(capsys, install_dir)@@ -2745,9 +2742,8 @@ def test_both_setup_scripts_report_the_kept_install_as_kept():def test_whisper_a_release_pin_does_not_excuse_a_wrong_upstream_pin(tmp_path, monkeypatch):- """The full path refuses a pinned release whose bundle targets another upstream- version, so the shortcut checks the upstream pin whether or not the release is- pinned too."""+ """The full path refuses a pinned release whose bundle targets another upstream version, so the+ shortcut checks the upstream pin even when the release is pinned too."""install_dir, host, _ = _installed_cpu_tree(tmp_path, monkeypatch)monkeypatch.setattr(M.llama,@@ -2825,9 +2821,8 @@ def test_whisper_an_upstream_pin_without_the_v_prefix_is_the_same_pin(tmp_path,def test_whisper_a_bundle_needing_a_newer_macos_is_not_intact(tmp_path, monkeypatch):- """An install restored onto an older same-architecture Mac has the right platform- tokens and the execute bit; the marker's recorded min_os is what the selector- would refuse it on, so the intact check refuses it too."""+ """A restore onto an older same-architecture Mac keeps the platform tokens and execute bit, but+ the recorded min_os makes the intact check refuse it, as the selector would."""install_dir, host, _ = _installed_cpu_tree(tmp_path, monkeypatch)marker_path = install_dir / M.METADATA_FILENAMEmarker = json.loads(marker_path.read_text(encoding = "utf-8"))@@ -3012,9 +3007,8 @@ def _plan_on_macos(published_repo: str = "unslothai/whisper.cpp"):def test_macos_does_not_walk_back_when_llama_is_ahead_of_every_whisper_release(monkeypatch):- """llama.cpp b10080 is out and its paired whisper.cpp release is not yet: no older release can- pair with a newer llama.cpp, so listing and fetching all of them (two requests each, on every- update) found nothing. Seen in CI as ~50 GitHub requests in a no-op macOS update."""+ """macOS does not walk back when llama.cpp is ahead of every whisper.cpp release, since no older+ release pairs with a newer llama.cpp; listing and fetching them finds nothing."""listed = _macos_pairing_gap(monkeypatch, "b10080-mix-0000000")with pytest.raises(M.LlamaPairingGapError, match = SLIM_LLAMA_TAG):_plan_on_macos()diff --git a/tests/studio/install/test_installed_release_backend_line.py b/tests/studio/install/test_installed_release_backend_line.pyindex 23743c67c53..7321a2a6768 100644--- a/tests/studio/install/test_installed_release_backend_line.py+++ b/tests/studio/install/test_installed_release_backend_line.py@@ -310,9 +310,8 @@ def test_ps1_printer(marker_dir, strict_mode, case_id, raw, expected):@requires_pwsh@pytest.mark.parametrize("strict_mode", ["2.0", "3.0", "Latest"])def test_a_legacy_marker_does_not_abort_under_strict_mode(marker_dir, strict_mode):- """The discriminating case: markers between #4562 and #8520 have no backend key, and- the function's only try/catch wraps ConvertFrom-Json, so the read escapes it.- """+ """The discriminating case: markers between issues 4562 and 8520 lack a backend key, and the+ only try/catch wraps ConvertFrom-Json, so the read escapes it."""install_dir = marker_dir(_drop_backend_key())proc = _run_ps1_printer(install_dir, strict_mode)assert "PropertyNotFound" not in proc.stderr, proc.stderr@@ -636,9 +635,8 @@ def test_the_sh_printer_only_accepts_a_string():@requires_pwsh@requires_bashdef test_the_upstream_source_branch_is_a_known_pre_existing_divergence(marker_dir, tmp_path):- """Recorded, not fixed: teaching setup.ps1 this branch changes what Windows prints- for upstream bundles, which is a separate change from naming the backend.- """+ """A known pre-existing divergence, recorded not fixed: teaching setup.ps1 this branch would+ change what Windows prints for upstream bundles, a separate change."""raw = json.dumps({"published_repo": "unslothai/unsloth",diff --git a/tests/studio/install/test_installed_runtime_health.py b/tests/studio/install/test_installed_runtime_health.pyindex 685660dc447..4f433b26a60 100644--- a/tests/studio/install/test_installed_runtime_health.py+++ b/tests/studio/install/test_installed_runtime_health.py@@ -501,11 +501,9 @@ def test_a_complete_macos_payload_is_healthy(tmp_path):["libllama-common", "libllama", "libggml", "libggml-base", "libggml-cpu", "libmtmd"],)def test_each_essential_macos_dylib_is_required_on_its_own(tmp_path, stem):- """Codex 3958908349, P1. The groups used to be three broad alternatives, so- libggml*.dylib stayed satisfied by libggml-base, libggml-blas, libggml-cpu, libggml-metal- and libggml-rpc after the one the loader needs was quarantined, and the tree reported- healthy while llama-server died in dyld. The dot in each pattern is what keeps it off its- siblings."""+ """Each essential macOS dylib is required on its own: a broad libggml glob stayed satisfied by+ sibling libraries after the loader's one was quarantined, so llama-server died in dyld while+ the tree reported healthy; the dot keeps each pattern off its siblings."""root = _macos_tree(tmp_path)runtime_dir = root / "build" / "bin"for path in [p for p in runtime_dir.iterdir() if p.name.split(".")[0] == stem]:@@ -565,9 +563,8 @@ def test_losing_the_macos_install_name_link_is_caught(tmp_path):@pytest.mark.skipif(os.name == "nt", reason = "the fixture needs POSIX symlinks")def test_a_bare_versionless_macos_dylib_still_satisfies_its_group(tmp_path):- """The other direction, so the rule above cannot become a reinstall loop: a bundle that- ships libfoo.dylib with no chain at all is a name the loader can resolve and must stay- healthy."""+ """A bare versionless libfoo.dylib with no symlink chain is a name the loader can resolve, so it+ must stay healthy or it would become a reinstall loop."""root = _macos_tree(tmp_path)runtime_dir = root / "build" / "bin"for path in [p for p in runtime_dir.iterdir() if p.name.split(".")[0] == "libggml"]:diff --git a/tests/studio/install/test_installed_runtime_health_matrix.py b/tests/studio/install/test_installed_runtime_health_matrix.pyindex c23bf52abfd..6d0fa3a21d1 100644--- a/tests/studio/install/test_installed_runtime_health_matrix.py+++ b/tests/studio/install/test_installed_runtime_health_matrix.py@@ -693,9 +693,8 @@ def test_a_very_deep_install_path_is_judged_normally(tmp_path):def test_the_probe_never_executes_anything_it_finds(tmp_path, monkeypatch):- """Preflight runs at every launch and the setup scripts own the exec probes, so this looks- and does not run. Also why the invariant is one-directional: this call can only be as- strict as, or looser than, the keep path."""+ """Preflight runs every launch, so it only looks and never executes what it finds (setup scripts+ own the exec probes); it is at most as strict as the keep path."""root = build_tree(tmp_path / "llama.cpp", host = LINUX, marker = S12, backend = "cuda")def refuse(*args, **kwargs):diff --git a/tests/studio/install/test_keep_install_backcompat_9979.py b/tests/studio/install/test_keep_install_backcompat_9979.pyindex 772fa71fa22..3a2b9c3f0e7 100644--- a/tests/studio/install/test_keep_install_backcompat_9979.py+++ b/tests/studio/install/test_keep_install_backcompat_9979.py@@ -671,9 +671,8 @@ def test_a_gutted_install_is_refused_in_every_os_and_accelerator_cell(def test_an_accelerator_install_missing_its_own_backend_library_is_refused(tmp_path, cell, host, backend):- """The shared payload alone must not be enough for a CUDA/ROCm/Vulkan tree. The partial- extraction case: everything generic is present and only the accelerator library is gone, so- the binaries start and fail once a model loads."""+ """The shared payload alone is not enough for CUDA, ROCm or Vulkan trees: with only the+ accelerator library missing, the binaries start and then fail once a model loads."""marker = {**S12, "backend": backend, "asset": f"app-b1-{cell}.tar.gz"}install_dir = build_install(tmp_path,@@ -775,9 +774,8 @@ def test_a_transient_failure_keeps_each_shipped_shape_and_returns_exit_zero(tmp_def test_a_transient_failure_still_falls_back_when_the_tree_is_not_runnable(tmp_path, monkeypatch):- """The other half: a broken tree must still reach the source-build fallback. Exit 2 is what- tells setup.sh it may build from source; swallowing it would leave a user with a- half-deleted install told everything was fine."""+ """A broken tree must still reach the source-build fallback: exit 2 tells setup.sh it may build+ from source, and swallowing it would report a half-deleted install as fine."""_transient_listing_failure(monkeypatch)install_dir = build_install(tmp_path, marker = S12, payload_backend = None)with pytest.raises(SystemExit) as caught:diff --git a/tests/studio/install/test_llama_runtime_install_history.py b/tests/studio/install/test_llama_runtime_install_history.pyindex 51cadb6a146..d1c185c0b61 100644--- a/tests/studio/install/test_llama_runtime_install_history.py+++ b/tests/studio/install/test_llama_runtime_install_history.py@@ -241,9 +241,8 @@ def _managed_copy(tmp_path: Path) -> Path:def test_the_managed_install_on_this_machine_is_healthy():- """Read-only, against the install itself rather than a copy: the only sample available of- what the probe is actually asked about at launch.- """+ """Read-only, runs against the real managed install rather than a copy, the only sample of what+ the launch probe is asked; skipped when none is installed."""root = _managed_install()if root is None:pytest.skip("no managed llama.cpp install on this machine")diff --git a/tests/studio/install/test_llama_runtime_repair_convergence.py b/tests/studio/install/test_llama_runtime_repair_convergence.pyindex 6fc439ee5ce..89b717fce0e 100644--- a/tests/studio/install/test_llama_runtime_repair_convergence.py+++ b/tests/studio/install/test_llama_runtime_repair_convergence.py@@ -325,9 +325,8 @@ def build_damaged(def test_the_online_repair_reaches_a_fixed_point_from_every_damaged_tree(tmp_path, cell, host, backend, shape):- """Reachable listing: one reinstall, and its result is a fixed point. A second cycle would- mean the installer writes a tree its own probe rejects, a permanent loop for every user.- """+ """One reinstall must reach a fixed point; a second cycle would mean the installer writes a tree+ its own probe rejects, looping for every user."""marker = MF.shape_with_backend(shape, backend)for label, damage in damage_modes(host, backend, marker):root = build_damaged(tmp_path / label, host, backend, marker, damage)@@ -460,9 +459,8 @@ def test_no_damaged_tree_survives_the_shell_rebuild_skip(@pytest.mark.parametrize(("host_id", "host"), HOSTS, ids = [h[0] for h in HOSTS])def test_a_runtime_quarantined_again_after_every_repair_is_not_a_code_loop(tmp_path, host_id, host):- """Antivirus that re-quarantines after each repair never converges, and must not read as- the bug above. The distinguisher is progress, not convergence: every repair here replaces- the tree, whereas the shell shortcut returned an identical one."""+ """Antivirus that re-quarantines after each repair never converges and is not a code loop:+ progress, not convergence, distinguishes them, as each repair replaces the tree."""backend = "cuda"root = tmp_path / "quarantined"install_fresh_prebuilt(root, host, backend)@@ -558,9 +556,8 @@ def test_grading_an_unparseable_marker_still_terminates_on_every_cell(def test_the_freshly_installed_tree_is_a_fixed_point_on_every_cell(tmp_path):- """The base case the whole argument rests on: whatever the repair installs is accepted. If- this failed for any cell, every cycle above would be infinite whichever branch ran.- """+ """Base case: whatever a fresh prebuilt install produces is accepted on every host and backend;+ if not, every repair cycle would loop forever."""for host_id, host in HOSTS:for backend in BACKENDS:prebuilt = tmp_path / f"{host_id}-{backend}-prebuilt"diff --git a/tests/studio/install/test_macos_loader_probe_record.py b/tests/studio/install/test_macos_loader_probe_record.pyindex 5ac44fea99c..eb19066bb3c 100644--- a/tests/studio/install/test_macos_loader_probe_record.py+++ b/tests/studio/install/test_macos_loader_probe_record.py@@ -454,11 +454,8 @@ def test_the_reuse_fast_paths_do_not_record_a_pass(tmp_path: Path, monkeypatch):@POSIX_ONLYdef test_a_broken_root_wrapper_is_not_blessed_into_the_record(tmp_path: Path, monkeypatch):- """The root entrypoint can be its own file, and it is started AFTER the dyld probe.-- Recording between the two would hash the broken wrapper into the digest record, and- the next run would read that record as current and never start the wrapper again.- """+ """The root entrypoint is started after the dyld probe; recording between the two would hash a+ broken wrapper into the digest record, so later runs never start it."""host = macos_host()install_dir = build_install(tmp_path, host, load_probe_passed = False)marker = marker_of(install_dir)diff --git a/tests/studio/install/test_macos_version_compat.py b/tests/studio/install/test_macos_version_compat.pyindex 39cc40a5a75..500d917d8ee 100644--- a/tests/studio/install/test_macos_version_compat.py+++ b/tests/studio/install/test_macos_version_compat.py@@ -277,9 +277,8 @@ class TestMacosDyldLoadProbe:ILP.preflight_macos_installed_binaries(binaries, install_dir, make_macos_host((15, 5)))def test_the_referencing_dylib_survives_into_the_message(self, tmp_path):- """dyld names the library AND the dylib that asked for it. The second half- is what says libggml-rpc rather than llama-server is at fault, so keep- enough of the tail to carry it."""+ """dyld names the missing library and the dylib that asked for it; that second half shows+ libggml-rpc, not llama-server, is at fault, so keep the tail."""real = ("dyld[41694]: Library not loaded: /usr/lib/librdma.dylib\\n"" Referenced from: /Users/r/.unsloth/llama.cpp/build/bin/libggml-rpc.0.dylib\\n"diff --git a/tests/studio/install/test_missing_kernel_arch_routing_9396.py b/tests/studio/install/test_missing_kernel_arch_routing_9396.pyindex 3e9cc511d5d..64963abd24c 100644--- a/tests/studio/install/test_missing_kernel_arch_routing_9396.py+++ b/tests/studio/install/test_missing_kernel_arch_routing_9396.py@@ -191,9 +191,8 @@ def test_the_reroute_is_not_gated_on_the_rocm_version_floor():def test_the_companion_pins_carry_the_211_floor_on_a_grouped_mm_leaf():- """gfx110X-all joined the torch 2.11 allowlist with unslothai/unsloth#11814 (its 2.10 build- access-violates in _grouped_mm), so the reroute installs the floored trio; every companion- stays bounded above, so none can drift to a different torch major."""+ """gfx110X-all joined the torch 2.11 allowlist (unslothai/unsloth issue 11814; 2.10+ access-violates in _grouped_mm); companions stay bounded above, against major drift."""calls = _run_install(gfx_devices = ("gfx1103",))for spec in stack_mod._ROCM_TORCH_PKG_SPECS["rocm7.2"]:assert spec in calls, (spec, calls)@@ -297,9 +296,8 @@ def _detect_over_amd_smi(arches, dedup = False):def test_amd_smi_keeps_one_entry_per_device():- """dedup=False indexes DEVICES, and amd-smi names no agent: without its GPU: N- header the output is flat, so two cards of one arch collapse into one entry and- every device ordinal past them addresses the wrong card."""+ """dedup=False indexes devices; amd-smi names no agent without its GPU: N header, so two cards+ of one arch would collapse and shift every later ordinal."""assert _detect_over_amd_smi(("gfx1200", "gfx1200", "gfx1032")) == ["gfx1200","gfx1200",@@ -482,9 +480,8 @@ def test_a_stale_runtime_beside_a_non_rocm_torch_does_not_veto_the_repair():def test_a_leaf_that_needs_torch_211_keeps_its_floor():- """An unreadable ROCm version reads as 0.0, which is below the Strix floor, so a- gfx1152 host lands on this branch instead. Its leaf is one of the four whose <2.11- builds carry the _grouped_mm bug, and the generic branch already floors those."""+ """An unreadable ROCm version reads as 0.0, below the Strix floor, so gfx1152 lands here; its+ sub-2.11 builds carry the _grouped_mm bug the generic branch already floors."""calls = _run_install(gfx_devices = ("gfx1152",), inferred = "gfx1152", rocm_version = None)assert f"{_AMD}/gfx1152/" in calls, callsassert "torch>=2.11.0,<2.12.0" in calls, calls@@ -547,9 +544,8 @@ def test_the_strix_banner_redacts_mirror_credentials():@pytest.mark.parametrize("apu", ["gfx1103", "gfx1036", "gfx1035", "gfx1033"])def test_a_leading_integrated_gpu_does_not_pick_the_family(apu):- """Enumeration order alone puts the APU first on a Ryzen box with a Radeon card. The- family is chosen for ONE arch, so letting the APU decide strands the discrete card the- generic index was serving. _SHADOWING_INTEGRATED_GFX is the existing policy (#7776)."""+ """Enumeration order puts an APU first on a Ryzen box with a Radeon card; the family serves ONE+ arch, so the APU must not strand the dGPU (_SHADOWING_INTEGRATED_GFX, ref 7776)."""calls = _run_install(gfx_devices = (apu, "gfx1100"))assert _GENERIC in calls, callsassert _AMD not in calls, calls@@ -751,9 +747,8 @@ def test_a_gfx906_dgpu_never_deposes_a_routable_apu():def test_a_sub_211_build_of_the_right_family_is_still_repaired():- """A matching family is the right SHAPE, not a working build: on the 2.11-floor leaves a- sub-2.11 wheel carries the _grouped_mm bug. An unreadable ROCm version routes gfx1152- through the missing-kernel branch, so this is the only floor such a host meets."""+ """A matching family is the right shape, not a working build: a sub-2.11 wheel on a 2.11-floor+ leaf has the _grouped_mm bug; with an unreadable ROCm version this is the only floor met."""calls = _run_install(gfx_devices = ("gfx1152",),inferred = "gfx1152",@@ -779,9 +774,8 @@ def test_at_the_floor_the_matching_family_is_still_skipped():def test_a_stale_family_is_repaired_when_no_generic_tag_resolves():- """Demoting hands the job to the generic fallback, which resolves no tag at all when the- ROCm version is unreadable -- the shape of a bundled-runtime host. The branch announced a- reinstall, installed nothing, and kept the family it just called incompatible."""+ """Demoting hands off to a generic fallback that resolves no tag when the ROCm version is+ unreadable, so the stale family must be repaired, not kept."""calls = _run_install(gfx_devices = ("gfx1200",),inferred = "gfx1200",@@ -794,9 +788,8 @@ def test_a_stale_family_is_repaired_when_no_generic_tag_resolves():@pytest.mark.parametrize("probe", [(), ("gfx1103",)])def test_an_unreadable_rocm_version_still_routes_a_missing_kernel_arch(probe):- """A bundled-runtime host has no /opt/rocm version to read, and the missing-kernel- reroute has no version floor anyway: whichever index a version would pick ships no kernels- for these arches. Returning early leaves the GPU on a wheel that faults."""+ """No index a version would pick ships kernels for these arches, and a bundled-runtime host has+ no /opt/rocm version to read, so returning early leaves a faulting wheel."""calls = _run_install(gfx_devices = probe,kfd = ("gfx1103",),@@ -808,9 +801,8 @@ def test_an_unreadable_rocm_version_still_routes_a_missing_kernel_arch(probe):@pytest.mark.parametrize("mask", ["", "-1"])def test_an_empty_rocr_mask_under_a_named_hip_mask_still_selects_no_gpu(mask):- """ROCr filters BENEATH HIP, so the masks intersect: HIP naming device 0 over a ROCr mask- exposing nothing leaves nothing to target. Checking only the first mask that is set- reinstalls a multi-GB stack for a GPU the user hid."""+ """ROCr filters beneath HIP, so the masks intersect: an empty ROCr mask under a named HIP mask+ selects nothing; checking only the first mask set reinstalls for a hidden GPU."""calls = _run_install(gfx_devices = ("gfx1103",),env = {"HIP_VISIBLE_DEVICES": "0", "ROCR_VISIBLE_DEVICES": mask},@@ -824,9 +816,8 @@ def test_an_empty_rocr_mask_under_a_named_hip_mask_still_selects_no_gpu(mask):def test_keeping_the_matching_wheels_also_clears_a_confirmed_spoof():- """Keeping the wheels is not keeping the status quo. They carry the PHYSICAL arch alone,- so a confirmed spoof left set has ROCr keep naming the one arch they have no code for- (#7331). The reinstall arm clears it for that reason; the skip arm needs it as much."""+ """Keeping matching wheels still needs the spoof cleared: they carry the PHYSICAL arch alone,+ and a leftover spoof makes ROCr name an arch they have no code for (ref 7331)."""calls = _run_install(gfx_devices = ("gfx1100",),inferred = "gfx1152",@@ -853,9 +844,8 @@ def test_the_rocr_layer_is_applied_before_the_hip_index_on_an_unfiltered_list():def test_a_rocr_filtered_probe_is_not_filtered_a_second_time():- """rocminfo is the one probe ROCr renumbers, and it is renumbered whenever the mask is- set -- not only when it happens to be the first mask set. Applying the mask again to a- list it already shaped would index the survivors by a position in the original."""+ """rocminfo is the one probe ROCr renumbers, whenever any mask is set; applying the mask again+ would index survivors by a position in the original list."""with (patch.object(stack_mod, "_detect_amd_gfx_codes", return_value = ["gfx1103"]),patch.object(stack_mod, "_kfd_gfx_targets", return_value = [], create = True),@@ -881,9 +871,8 @@ def test_a_uuid_rocr_mask_on_one_architecture_still_routes():def test_an_unmappable_uuid_declines_the_reroute_on_a_mixed_host():- """On a mixed host the UUID decides everything and nothing here can read it. The reroute- installs wheels for ONE arch, so picking the first entry may serve the GPU the mask hid- and leave the selected card with no kernels at all."""+ """On a mixed host a ROCR_VISIBLE_DEVICES UUID that cannot be mapped decides everything;+ guessing the first entry could serve a hidden GPU and strand the selected one."""calls = _run_install(gfx_devices = ("gfx1103", "gfx1200"),env = {"ROCR_VISIBLE_DEVICES": "GPU-8d1f2e3a4b5c6d7e"},@@ -898,9 +887,8 @@ def test_an_unmappable_uuid_declines_the_reroute_on_a_mixed_host():def test_a_stale_per_arch_family_is_repaired_even_when_the_rocm_version_is_unreadable():- """A per-arch install outlives the GPU it was made for: swap a gfx1200 card into a box on- gfx110X-all wheels and the generic index would serve it, so the unreadable-version exit- stands and the stale-family repair never runs on wheels with no gfx1200 kernels."""+ """A per-arch install outlives its GPU: a gfx1200 card in a box on gfx110X-all wheels needs the+ stale-family repair even when the ROCm version is unreadable."""calls = _run_install(gfx_devices = ("gfx1200",),inferred = None,@@ -972,9 +960,8 @@ def test_amd_smi_discovery_order_is_not_indexed_as_hip_order():def test_kfd_order_resolves_a_mask_amd_smi_order_cannot():- """KFD nodes ARE the order the masks index, which is why the fallback above reads them- when no userland probe answers. Declining an ordering this file already solves leaves a- Ryzen APU-plus-dGPU box -- the reported shape -- on a wheel it has no kernels for."""+ """KFD nodes are the order the masks index, so the fallback reads them when no userland probe+ answers; declining that ordering strands a Ryzen APU-plus-dGPU box."""assert (_target(["gfx1200", "gfx1103"],@@ -1007,9 +994,8 @@ def test_kfd_order_resolves_a_mask_amd_smi_order_cannot():def test_an_explicit_arch_is_authoritative_for_the_repair_gate_too():- """Stacked masks can leave a device list the override is not in: ROCr keeps the gfx1200,- the user names the gfx1103. The caller reads that set to decide which arch lacks kernels,- so a target missing from it is selected and then never repaired."""+ """Stacked masks can leave the device list without the override target (ROCr keeps gfx1200, user+ names gfx1103); the caller reads that list to pick the arch to repair."""calls = _run_install(gfx_devices = ("gfx1200", "gfx1103"),probe_source = "amd-smi",@@ -1023,9 +1009,8 @@ def test_an_explicit_arch_is_authoritative_for_the_repair_gate_too():def test_a_generic_wheel_is_judged_by_its_own_rocm_tag():- """Which arches a generic wheel carries belongs to THAT wheel. Pin rocm6.3 once, or- upgrade /opt/rocm afterwards, and a gfx1200 box runs a 2.9.1+rocm6.3 build with no kernels- for it while the host reads 7.2 -- judged by the host, it looks healthy forever."""+ """Which arches a generic wheel carries belongs to that wheel's own rocm tag; judged by the+ host's 7.2 instead of a 2.9.1+rocm6.3 build, a gfx1200 box looks healthy forever."""calls = _run_install(gfx_devices = ("gfx1200",),rocm_version = (7, 2),@@ -1064,9 +1049,8 @@ def test_a_named_arch_resolves_an_ordering_no_probe_can():],)def test_the_torch_floor_applies_to_the_family_not_to_the_missing_kernel_gate(gfx, leaf):- """Several floor leaves serve GPUs the generic wheel DOES carry kernels for, so gating the- 2.11 floor on missing kernels never reaches them: the preflight forces the dependency pass- and this branch then declines it, and the _grouped_mm bug survives every update."""+ """Several floor leaves serve GPUs the generic wheel does carry kernels for, so gating the 2.11+ floor on missing kernels never reaches them; the _grouped_mm bug survives."""calls = _run_install(gfx_devices = (gfx,),inferred = None,@@ -1087,9 +1071,8 @@ def test_the_torch_floor_applies_to_the_family_not_to_the_missing_kernel_gate(gf@pytest.mark.parametrize("gfx", ["gfx942", "gfx950"])def test_a_generic_only_replacement_gpu_still_gets_a_wheel(gfx):- """The datacentre parts live only on the generic index, so a stale per-arch install that- outlives its GPU has no AMD leaf to be repaired onto. With no readable host version there- is no tag either, so the branch announced the reinstall and installed nothing."""+ """Datacentre parts (gfx942, gfx950) live only on the generic index, so a stale per-arch install+ has no AMD leaf to repair onto; without a readable version no tag resolves."""calls = _run_install(gfx_devices = (gfx,),inferred = None,@@ -1136,9 +1119,8 @@ def test_a_target_no_index_can_serve_is_not_worth_a_reinstall():[((6, 0), True), ((6, 2), True), ((6, 3), False), ((7, 1), False)],)def test_generic_kernel_support_is_keyed_by_the_tag_the_version_selects(rocm_version, rerouted):- """Which arches the generic wheel carries belongs to the wheel a version resolves to, not- the index as a whole. gfx1102 first ships in rocm6.3, so a stale /opt/rocm gets an older- wheel with no kernels while a gfx110X-all leaf exists."""+ """Generic kernel support belongs to the wheel a version resolves to, not the index as a whole:+ gfx1102 first ships in rocm6.3, so a stale /opt/rocm gets an older wheel without it."""calls = _run_install(gfx_devices = ("gfx1102",), rocm_version = rocm_version)if rerouted:assert f"{_AMD}/gfx110X-all/" in calls, calls@@ -1211,9 +1193,8 @@ def test_a_masked_gfx906_on_a_mixed_host_is_not_demoted_to_another_dead_wheel():],)def test_an_ordinal_past_an_inferred_arch_resolves_nothing(env):- """One guess about the machine is not a device list, so an ordinal past its only entry- indexes nothing: the mask names a GPU the guess cannot account for, and the out-of-range- rule would answer with the guess anyway, then reinstall per-arch wheels for it."""+ """One inferred arch is not a device list, so an ordinal past its only entry resolves nothing;+ the out-of-range rule must not answer with the guess and reinstall per-arch wheels."""calls = _run_install(gfx_devices = (),kfd = (),@@ -1280,9 +1261,8 @@ def test_a_masked_gfx906_is_judged_by_the_host_the_legacy_route_probes(env):@pytest.mark.parametrize("gfx", ["gfx1150", "gfx1151"])def test_a_strix_host_with_no_readable_version_still_gets_rocm_torch(gfx):- """An unreadable version reads as 0.0, so the Strix arm sat out and the missing-kernel- fallback declined too (these arches are in the generic list). The generic branch had no- tag either, so a visible Strix host was left on CPU torch permanently."""+ """An unreadable version reads as 0.0, so the Strix arm and the missing-kernel fallback both+ declined; with no generic tag either, a Strix host stayed on CPU torch permanently."""calls = _run_install(gfx_devices = (gfx,),rocm_version = None,@@ -1320,18 +1300,16 @@ def test_an_explicit_arch_keeps_its_feature_suffix_out_of_the_target():def test_a_version_below_every_index_is_not_read_as_support():- """A ROCm older than the oldest tag this installer maps resolves no tag at all, and a- wheel older than every tag predates the arches those tags were measured to add. Reading- "no tag" as "carries it" preserves exactly the build that cannot run."""+ """A ROCm version below every mapped tag resolves no tag, which must not read as support: such a+ wheel predates the arches those tags were measured to add."""assert stack_mod._generic_rocm_wheel_lacks_kernels("gfx1200", (5, 7))assert stack_mod._generic_rocm_wheel_lacks_kernels("gfx1200", (6, 3))assert not stack_mod._generic_rocm_wheel_lacks_kernels("gfx1200", (6, 4))def test_a_stale_host_version_does_not_pick_a_generic_tag_without_the_target():- """gfx950 (MI350X) lives only on the generic index, so the repair picks a TAG rather than- an index -- and a stale /opt/rocm beside a current kernel offers rocm6.3, which predates- the part. The reinstall would download multiple GB and land on a wheel with no kernels."""+ """gfx950 (MI350X) lives only on the generic index, so the repair picks a tag; a stale /opt/rocm+ offering rocm6.3 would predate the part and land on a wheel with no kernels."""calls = _run_install(gfx_devices = ("gfx950",),rocm_version = (6, 3),@@ -1382,9 +1360,8 @@ def test_an_explicit_arch_still_reconciles_a_contradicting_spoof():def test_an_explicit_arch_reconciles_the_spoof_on_the_reroute_path_too():- """The same host with ROCm torch installed takes the Strix reroute instead, reaching the- clear through _runtime_gfx_target's third return value. Both paths install gfx1151-only- wheels, so both have to answer the override."""+ """With ROCm torch installed the host takes the Strix reroute instead, reaching the clear via+ _runtime_gfx_target's third return value; both paths need the override answered."""calls = _run_install(gfx_devices = (),kfd = ("gfx1151",),@@ -1500,9 +1477,8 @@ def test_matching_per_arch_wheels_clear_a_confirmed_spoof_with_nothing_to_reroutdef test_a_spoof_survives_wheels_that_are_not_the_targets_family():- """The clear above is owned by a family read back positively from a torch that owns it.- Generic wheels, or another family's, are the paths where the override may be the only- source of usable kernels, so it must stay set there."""+ """The clear applies only when a torch that owns rocm reports the target's family; generic or+ other-family wheels may need the override as their only kernel source, so it stays set."""_run_install(gfx_devices = ("gfx1100",),rocm_version = (7, 2),@@ -1539,9 +1515,8 @@ def test_a_rocr_masked_mi50_beside_a_dgpu_keeps_the_generic_wheels():def test_a_generic_only_target_on_a_stale_tag_is_repaired_on_update_too():- """gfx950 has no per-arch leaf, so _generic_rocm_wheel_lacks_kernels answers False for it- by design and the preflight read a rocm6.3 build as healthy. The install path applies a- floor those wheels fail, so the card was repaired once and never from `studio update`."""+ """gfx950 has no per-arch leaf, so _generic_rocm_wheel_lacks_kernels answers False for it; the+ install path's floor fails those wheels, so studio update must repair them too."""for _tag, _hip, _repair in (("2.9.1+rocm6.3", "6.3.0", True),("2.11.0+rocm7.2", "7.2.0", False),@@ -1588,9 +1563,8 @@ def test_a_generic_only_target_installs_when_the_rocm_version_is_unreadable():def test_a_generic_only_target_pinned_to_a_stale_tag_is_reinstalled():- """An automatically selected generic +rocm6.3 build is below the bitsandbytes floor, so a- gfx1100 host on ROCm7.2 is repaired to the generic rocm7.2 family. Compatible generic- builds still remain untouched, including the generic-only gfx950 controls above."""+ """An auto-selected generic +rocm6.3 build is below the bitsandbytes floor and is repaired to+ the rocm7.2 family; compatible generic builds stay untouched, gfx950 controls included."""for _ver in ((7, 2), None):assert f"{_GENERIC}7.2" in _run_install(gfx_devices = ("gfx950",),diff --git a/tests/studio/install/test_mlx_install.py b/tests/studio/install/test_mlx_install.pyindex f4b783b3337..780f5e88f0f 100644--- a/tests/studio/install/test_mlx_install.py+++ b/tests/studio/install/test_mlx_install.py@@ -446,9 +446,8 @@ def _zoo_spec_sequence(monkeypatch, specs):def test_the_core_phase_upgrading_the_zoo_re_resolves_mlx(monkeypatch):- """The MLX step runs before the core phase, so it honours the OLD zoo's range. Without the- re-resolve an update that moves the zoo leaves the machine on the narrower mlx-vlm for good:- the startup self-heal will not correct it, since 0.6.x satisfies _MLX_MIN_VERSIONS."""+ """The MLX step runs before the core phase and honours the old zoo's range; without a re-resolve+ the narrower mlx-vlm stays for good, since 0.6.x satisfies _MLX_MIN_VERSIONS."""narrow = f"{stack._MLX_VLM_SPEC},<0.7.0"# Twice for the install step, then the widened answer after the core phase._zoo_spec_sequence(monkeypatch, [narrow, narrow, stack._MLX_VLM_SPEC])diff --git a/tests/studio/install/test_pr10648_host_matrix.py b/tests/studio/install/test_pr10648_host_matrix.pyindex a1c43389cf1..3a80d2d2cf4 100644--- a/tests/studio/install/test_pr10648_host_matrix.py+++ b/tests/studio/install/test_pr10648_host_matrix.py@@ -370,9 +370,8 @@ def assert_reinstall_forced(monkeypatch, install_dir: Path) -> None:@pytest.mark.parametrize(("row", "column"), MATRIX, ids = MATRIX_IDS)def test_every_cell_of_the_matrix_is_reachable_or_explicitly_impossible(row, column):- """The user population this fast path runs for: every OS crossed with every- accelerator. A cell that does not exist is skipped with the reason, so a column- quietly losing a platform shows up as a skip rather than as absence."""+ """Every OS crossed with every accelerator; a nonexistent cell is skipped with its reason, so a+ platform quietly dropped shows as a skip, not as absence."""reason = _skip_reason(row, column)if reason is not None:pytest.skip(reason)@@ -384,9 +383,8 @@ def test_every_cell_of_the_matrix_is_reachable_or_explicitly_impossible(row, col@pytest.mark.parametrize(("row", "column"), REACHABLE, ids = REACHABLE_IDS)def test_an_unchanged_box_keeps_its_install_in_every_cell(tmp_path, probe, row, column):- """Nothing happened to the user's machine since the install: no download, no listing,- no re-validation. This is the half the fast path exists for, and every rejection test- below is only meaningful because this one passes with the same fixtures."""+ """Nothing changed on the box since install (no download, listing or re-validation); the fast+ path exists for this, and rejection tests mean something only if this passes."""cell = _cell(row, column)install_dir = install_cell(tmp_path, probe, cell)assert check(install_dir) is True, cell.cell_id@@ -395,9 +393,8 @@ def test_an_unchanged_box_keeps_its_install_in_every_cell(tmp_path, probe, row,@pytest.mark.parametrize(("row", "column"), REACHABLE, ids = REACHABLE_IDS)def test_a_second_update_on_the_same_box_is_still_current(tmp_path, probe, row, column):- """Updates are not one-shot: the user runs setup again next week with nothing changed.- A profile that failed to compare equal to itself would be a silent permanent- regression -- every update back to the full path, forever, with no error to report."""+ """Updates are not one-shot: a profile that fails to equal itself would silently send every+ later update down the full path, forever, with no error."""cell = _cell(row, column)install_dir = install_cell(tmp_path, probe, cell)assert check(install_dir) is True, cell.cell_id@@ -411,9 +408,8 @@ def _cpu_cell(row: str) -> Cell:@pytest.mark.parametrize("row", GPU_ROWS)def test_a_gpu_added_to_a_cpu_only_box_is_not_current(tmp_path, probe, monkeypatch, row):- """The user drops an NVIDIA card into a CPU-only machine and re-runs setup. The- request recorded is "auto" and the release tag has not moved, so only the host- profile can notice; without it the box keeps its CPU bundle and stays slow."""+ """With the request recorded as auto and the release tag unchanged, only the host profile can+ notice an added NVIDIA card; without it the CPU bundle is kept."""cell = _cpu_cell(row)after = make_host(**ROWS[row], **NVIDIA_CUDA12)install_dir = moved(tmp_path, probe, cell, after, cuda_lines = ("cuda12",), torch_line = None)@@ -432,9 +428,8 @@ def test_a_gpu_removed_since_the_install_is_not_current(tmp_path, probe, monkeyp@pytest.mark.parametrize("row", GPU_ROWS)def test_a_cuda_12_to_cuda_13_move_is_not_current(tmp_path, probe, monkeypatch, row):- """The user upgrades the NVIDIA driver and the CUDA toolkit. The card is the same and- the release tag has not moved; what moved is the driver's CUDA version and the CUDA- runtimes on disk, which are what orders the CUDA bundles."""+ """A driver and CUDA toolkit upgrade with the same card and tag still changes the driver's CUDA+ version and on-disk runtimes, which order the CUDA bundles."""cell = _cell(row, "nvidia-cuda12")after = make_host(**ROWS[row], **NVIDIA_CUDA13)install_dir = moved(@@ -480,9 +475,8 @@ def test_swapping_an_amd_card_for_an_nvidia_one_is_not_current(tmp_path, probe,@pytest.mark.parametrize("row", GPU_ROWS)def test_a_rocm_runtime_version_bump_is_not_current(tmp_path, probe, monkeypatch, row):- """The user upgrades ROCm 6.2 to 6.4 with the same card. Upstream ROCm assets are- chosen by the runtime's major.minor, which no GPU field carries -- so the bundle this- run would pick has moved even though every other hardware fact is identical."""+ """Upstream ROCm assets are chosen by the runtime's major.minor, which no GPU field carries, so+ a ROCm 6.2 to 6.4 bump moves the bundle with identical hardware."""cell = _cell(row, "amd-rocm")install_dir = moved(tmp_path, probe, cell, cell.host, rocm_runtime = (6, 4))assert_reinstall_forced(monkeypatch, install_dir)@@ -490,9 +484,8 @@ def test_a_rocm_runtime_version_bump_is_not_current(tmp_path, probe, monkeypatch@pytest.mark.parametrize("row", GPU_ROWS)def test_a_rocm_gfx_target_change_is_not_current(tmp_path, probe, monkeypatch, row):- """A different AMD card: gfx1100 out, gfx1030 in. A HIP bundle carries kernels for the- archs it was built for and nothing else, so the install starts and then cannot run a- model."""+ """A HIP bundle carries kernels only for the archs it was built for, so swapping gfx1100 for+ gfx1030 starts the install but cannot run a model."""cell = _cell(row, "amd-rocm")after = make_host(**ROWS[row],@@ -523,9 +516,8 @@ def test_a_second_amd_card_the_bundle_has_no_kernels_for_is_not_current(@pytest.mark.parametrize("row", GPU_ROWS)def test_an_intel_gpu_that_appeared_is_not_current(tmp_path, probe, monkeypatch, row):- """The user enables the integrated Intel GPU (a BIOS change, or a new machine restored- from the same home directory). An Intel GPU with no NVIDIA and no ROCm is the whole- purpose of the has_intel_gpu probe: it routes the install to Vulkan."""+ """An Intel GPU with no NVIDIA or ROCm is the whole purpose of the has_intel_gpu probe, which+ routes the install to Vulkan; it must be noticed when it appears."""cell = _cpu_cell(row)after = make_host(**ROWS[row], **INTEL)install_dir = moved(tmp_path, probe, cell, after)@@ -573,9 +565,8 @@ def test_a_physical_nvidia_disappearing_behind_an_intel_gpu_is_not_current(def test_a_home_directory_carried_to_another_cpu_architecture_is_not_current(tmp_path, probe, monkeypatch, row):- """A home directory rsynced from an x86_64 box onto an arm64 one (or opened under- Rosetta). Every GPU field is equal and the release tag is the same; only machine- differs, and the bundle on disk cannot be executed at all."""+ """A home directory moved from x86_64 to arm64 (or opened under Rosetta) keeps every GPU field+ and the tag equal, but machine differs and the bundle cannot run at all."""cell = _cpu_cell(row)arm = "ARM64" if row == "windows" else "aarch64"after = make_host(**{**ROWS[row], "machine": arm})@@ -585,9 +576,8 @@ def test_a_home_directory_carried_to_another_cpu_architecture_is_not_current(@pytest.mark.parametrize("row", GPU_ROWS)def test_a_new_card_with_a_different_sm_is_not_current(tmp_path, probe, monkeypatch, row):- """An RTX 4090 (sm_89) swapped for a Blackwell part (sm_120), same driver. A bundle- carries kernels for a fixed supported_sms set, so an install outside it starts and- then fails on the first model load."""+ """An RTX 4090 (sm_89) swapped for a Blackwell sm_120 part with the same driver: a bundle only+ has kernels for its supported_sms set and fails on first model load."""cell = _cell(row, "nvidia-cuda12")after = make_host(**ROWS[row], **{**NVIDIA_CUDA12, "compute_caps": ["12.0"]})install_dir = moved(@@ -598,9 +588,8 @@ def test_a_new_card_with_a_different_sm_is_not_current(tmp_path, probe, monkeypa@pytest.mark.parametrize("row", GPU_ROWS)def test_the_same_cards_reported_in_another_order_is_not_a_hardware_change(tmp_path, probe, row):- """The other direction, and the reason compute_caps is sorted and de-duplicated: two- identical cards enumerated in either order, with whitespace, are the same box. Calling- that a change would send every multi-GPU user down the full path on every update."""+ """compute_caps is sorted and de-duplicated, so identical cards enumerated in any order or with+ whitespace are the same box, not a change sending multi-GPU users down the full path."""cell = _cell(row, "nvidia-cuda12")after = make_host(**ROWS[row], **{**NVIDIA_CUDA12, "compute_caps": [" 8.9 ", "8.9"]})install_dir = moved(@@ -614,9 +603,8 @@ MACOS_ROWS = ("macos-arm64", "macos-x86_64")@pytest.mark.parametrize("row", MACOS_ROWS)def test_a_macos_upgrade_across_the_min_os_floor_is_not_current(tmp_path, probe, monkeypatch, row):- """The user upgrades macOS past the floor the newest bundle needs. The bundle the- planner would pick changes with the OS version (walk-back), so the recorded profile- has to carry macos_version or a Mac would keep a walked-back release forever."""+ """The planner's bundle changes with the macOS version (walk-back), so the recorded profile must+ carry macos_version or a Mac keeps a walked-back release forever."""cell = _cell(row, "metal")before = cell.host.macos_versionassert before is not None and before < ILP._PINNED_MACOS_LATEST_FLOOR@@ -676,9 +664,8 @@ def _assert_everything_but_the_host_still_matches(install_dir: Path, after: Hostdef test_adding_a_gpu_is_rejected_by_the_host_profile_and_nothing_else(tmp_path, probe, monkeypatch, row):- """The CPU-to-NVIDIA case again, but proving WHICH guard rejected it. Same release,- same fingerprint, intact tree -- and with the profile comparison neutralised the fast- path keeps the CPU bundle, which is the bug the guard exists to prevent."""+ """Shows the host profile alone rejects a CPU-to-NVIDIA change: with release, fingerprint and+ tree intact, neutralising it keeps the CPU bundle, the bug the guard prevents."""cell = _cpu_cell(row)after = make_host(**ROWS[row], **NVIDIA_CUDA12)install_dir = moved(tmp_path, probe, cell, after, cuda_lines = ("cuda12",), torch_line = None)@@ -694,9 +681,8 @@ def test_adding_a_gpu_is_rejected_by_the_host_profile_and_nothing_else(def test_a_cuda_line_move_is_rejected_by_the_host_profile_and_nothing_else(tmp_path, probe, monkeypatch, row):- """The cuda12-to-cuda13 case, same proof. The release did not move, the marker is- whole and the bundle is intact, so the profile is the only thing that can say the- installed CUDA bundle is no longer the one this run would pick."""+ """Same proof for cuda12 to cuda13: with release, marker and bundle intact, only the host+ profile can say the installed CUDA bundle is no longer the one picked."""cell = _cell(row, "nvidia-cuda12")after = make_host(**ROWS[row], **NVIDIA_CUDA13)install_dir = moved(@@ -737,9 +723,8 @@ def test_a_profile_written_to_a_marker_reads_back_equal_to_a_fresh_one(@pytest.mark.parametrize(("row", "column"), REACHABLE, ids = REACHABLE_IDS)def test_every_profile_field_is_present_in_every_cell(tmp_path, probe, row, column):- """Absent and null are different answers to the comparison. Every field the routing- branches on must be written in every cell, or two different boxes could record the- same profile."""+ """Absent and null are different answers to the comparison; every field the routing branches on+ must be written in every cell, or two boxes could record one profile."""cell = _cell(row, column)probe.set_from(cell)profile = host_profile(route_for(cell.host).host)diff --git a/tests/studio/install/test_pr10648_integrity_and_fs.py b/tests/studio/install/test_pr10648_integrity_and_fs.pyindex e1c4e676472..1727bba5583 100644--- a/tests/studio/install/test_pr10648_integrity_and_fs.py+++ b/tests/studio/install/test_pr10648_integrity_and_fs.py@@ -339,9 +339,8 @@ def test_the_execute_bit_is_checked_on_every_entrypoint(@pytest.mark.parametrize("relative", SIZE_TIER)@pytest.mark.parametrize("corruption", ("truncate_half", "truncate_zero", "delete"))def test_a_truncated_payload_library_is_rejected(tmp_path, monkeypatch, relative, corruption):- """The size tier's whole purpose: _runtime_payload_has globs for EXISTENCE, so before- the record a half-written libggml.so -- what a full disk leaves -- passed the payload- scan. A stat is enough to catch it."""+ """_runtime_payload_has only checks existence, so a half-written libggml.so from a full disk+ passed; a stat against the recorded size catches it."""install_dir = _install(tmp_path, monkeypatch)assert _fast_path(install_dir) is True_CORRUPTIONS[corruption](install_dir / relative)@@ -692,10 +691,8 @@ def test_a_rewritten_marker_is_valid_json_and_keeps_the_keys_the_ui_reads(tmp_pa@pytest.mark.parametrize("mode", (0o600, 0o644, 0o664, 0o444))@pytest.mark.parametrize("writer", WRITERS, ids = _WRITER_IDS)def test_a_rewritten_marker_keeps_its_mode(tmp_path, writer, mode):- """NamedTemporaryFile is 0600 and os.replace keeps the SOURCE file's mode, so without- the restore a refresh silently makes a group-shared install's marker private. 0o444- is the read-only case the temp-and-replace shape exists to support: a plain write- would need the file writable, not the directory."""+ """NamedTemporaryFile is 0600 and os.replace keeps the source mode, so the mode must be+ restored; 0o444 works since replace needs the directory writable, not the file."""path = _live_marker(tmp_path, writer, mode = mode)writer.rewrite(tmp_path, _LIVE_PAYLOAD)assert stat.S_IMODE(path.stat().st_mode) == mode@@ -733,17 +730,9 @@ def test_a_group_shared_marker_keeps_its_group(tmp_path, writer):def test_every_marker_writer_asks_for_the_owner_then_falls_back_to_the_group(tmp_path, writer, monkeypatch):- """All three ask for owner AND group first, then group alone, and that uniformity is- the point.-- Neither half is sufficient on its own. Owner+group alone is EPERM for a non-root member- of a group-shared install -- chown is all-or-nothing -- so the group is silently lost,- which is what e8d128d24 fixed in core and node. Group alone is wrong under root, which- is exactly when the owner CAN be restored: it leaves the marker owned by root, and an- 0600 marker stops being readable by the user who owns the install. The two calls in- this order give each caller the best it is permitted. This pins the call shape so the- three writers cannot drift apart again.- """+ """All three writers chown owner and group first, then group alone: owner plus group is EPERM+ for a non-root member and loses the group (fixed in core and node by e8d128d24); group alone+ under root leaves a root-owned 0600 marker unreadable by its owner."""path = _live_marker(tmp_path, writer)original = path.stat()calls: list = []@@ -790,15 +779,9 @@ def test_a_permitted_writer_restores_the_owner_and_asks_no_further(tmp_path, wri@NOT_ROOT@pytest.mark.parametrize("writer", WRITERS, ids = _WRITER_IDS)def test_a_marker_owned_by_another_user_still_keeps_its_group(tmp_path, writer, monkeypatch):- """The case uid -1 exists for, on the install it matters for.-- A group-shared install whose marker is owned by the admin who ran setup, refreshed by- a member of the group: chown(uid, gid) is EPERM outright there (you may not give a- file away) while chown(-1, gid) succeeds, and since the failure is swallowed the- difference is not an error but a marker that quietly changes group -- on an 0640- marker, the mode restore beside it undone. The kernel rule is simulated, since a test- cannot own a file as another user; the simulation refuses exactly what POSIX refuses.- """+ """A group member refreshing a marker owned by another user needs chown(-1, gid): chown(uid,+ gid) is EPERM and the swallowed failure silently changes the group, undoing the mode restore;+ the test simulates the kernel rule."""path = _live_marker(tmp_path, writer, mode = 0o640)other_uid = os.geteuid() + 1shared_gid = os.getegid() + 1@@ -840,9 +823,8 @@ class _StatWithOwner:@NEEDS_CHOWN@pytest.mark.parametrize("writer", WRITERS, ids = _WRITER_IDS)def test_a_chown_that_is_refused_does_not_abort_the_write(tmp_path, writer, monkeypatch):- """Ownership is best effort; the refreshed marker is not. Declining to write because- the group could not be restored would leave the field the refresh exists to record- (a deliberate --force-cpu, a re-probed version) unrecorded."""+ """Ownership is best effort but the refreshed marker is not: refusing the write because the+ group could not be restored would leave --force-cpu or a re-probed version unrecorded."""path = _live_marker(tmp_path, writer, mode = 0o640)def refuse(*_a, **_k):@@ -941,17 +923,9 @@ def test_the_llama_marker_survives_a_rewrite_and_the_fast_path_still_accepts_it(@NOT_ROOT@pytest.mark.parametrize("relative", ("llama-server", "llama-quantize"))def test_a_damaged_root_entrypoint_is_not_kept_by_the_shortcut(tmp_path, monkeypatch, relative):- """The update has to repair what the launch check calls broken, or the two loop.-- installed_runtime_health rejects a root llama-server that lost its execute bit, so the- desktop marks the install stale and offers a repair. This shortcut returns before- reinstalling anything, and it used to check X_OK under build/bin ONLY -- so the repair- ran, changed nothing, and the next launch was stale again. Measured before the fix:- launch health llama_runtime_binaries_missing, shortcut True, full re-validation False.-- _damaged_entrypoint owns the question for all three now, which is what its own docstring- asks for.- """+ """The update shortcut must reject a root llama-server or llama-quantize that lost its execute+ bit, as installed_runtime_health does; checking only build/bin left the repair a no-op;+ _damaged_entrypoint now decides for all three."""install_dir = _install(tmp_path, monkeypatch)assert _fast_path(install_dir) is True, "the shortcut must accept a healthy install here"(install_dir / relative).chmod(0o644)diff --git a/tests/studio/install/test_pr10648_offline_and_status.py b/tests/studio/install/test_pr10648_offline_and_status.pyindex a272c8d7dee..27eaeedbf07 100644--- a/tests/studio/install/test_pr10648_offline_and_status.py+++ b/tests/studio/install/test_pr10648_offline_and_status.py@@ -787,12 +787,8 @@ def test_setup_ps1_status_labels(tmp_path, name, status, output, label):"name, status, output", FAILURE_CASES, ids = [case[0] for case in FAILURE_CASES])def test_setup_sh_never_reports_success_for_a_non_zero_exit(tmp_path, name, status, output):- """Success TEXT on a failed run must not become a success LABEL.-- The installer writes its progress log and its error to the same stream, so a run that- got as far as printing either token and then died is exactly the shape that would turn- a broken dictation runtime into a green line if the grep ran before the exit check.- """+ """Success text printed before a non-zero exit must not become a success label; progress and+ errors share one stream, so the exit check must come before the grep."""result = _run_bash(_sh_whisper_script(tmp_path, status, output))assert result.returncode == 0, resultlabel = _steps(result.stdout).get("whisper.cpp")@@ -822,11 +818,8 @@ def test_setup_ps1_never_reports_success_for_a_non_zero_exit(tmp_path, name, sta"name, status, output, label", STATUS_CASES, ids = [case[0] for case in STATUS_CASES])def test_both_shells_agree_on_the_label(tmp_path, name, status, output, label):- """Windows and POSIX must tell the user the same thing.-- Asserting each side against a constant leaves them free to drift apart via the- constant; comparing the two measured labels is what makes "mirrored" a measurement.- """+ """Windows and POSIX must show the same label; comparing the two shells' labels directly, not+ each against a constant, stops them drifting apart."""sh = _run_bash(_sh_whisper_script(tmp_path, status, output))ps = _run_ps1(tmp_path, _ps1_whisper_script(tmp_path, status, output))assert sh.returncode == 0 and ps.returncode == 0, (sh, ps.stdout, ps.stderr)@@ -917,12 +910,8 @@ _LLAMA_KEEP_LOG = (@requires_bashdef test_setup_sh_reports_each_component_separately(tmp_path):- """llama keeps its install while whisper's update fails: two labels, no cross-talk.-- Both blocks read from their own log file and their own status variable, and llama's- keep arm must not leak into whisper's line (or the reverse) just because the same- token appears in the same setup run.- """+ """llama's keep arm and whisper's failure must yield two separate labels; each block reads its+ own log file and status variable, so there is no cross-talk."""llama_log = tmp_path / "prebuilt.log"llama_log.write_text(_LLAMA_KEEP_LOG + "\n", encoding = "utf-8")whisper_log = tmp_path / "whisper.log"@@ -983,12 +972,8 @@ def test_setup_ps1_reports_each_component_separately(tmp_path):@requires_bashdef test_the_installer_emits_exactly_the_substrings_the_scripts_grep(tmp_path, monkeypatch, capsys):- """End to end: the real installer log, fed to the real setup.sh block.-- Every other test in this file asserts one half. This one runs the installer offline over- an intact install, takes whatever it printed, and hands it to the shipped shell block --- so a reworded log line shows up as the wrong user-facing label, not as a passing test.- """+ """Runs the installer offline and feeds its real log to the shipped setup.sh block, so a+ reworded log line shows up as a wrong label, not a pass."""host = _host("linux", "x64")install_dir = _seed_install(tmp_path, host)_inject(monkeypatch, "offline")diff --git a/tests/studio/install/test_pr10648_review_fixes.py b/tests/studio/install/test_pr10648_review_fixes.pyindex d83037cf212..87256965318 100644--- a/tests/studio/install/test_pr10648_review_fixes.py+++ b/tests/studio/install/test_pr10648_review_fixes.py@@ -43,15 +43,9 @@ def _node_tree(root: Path, host) -> None:def test_a_live_marker_rewrite_falls_back_to_the_group_when_the_owner_is_refused(tmp_path, monkeypatch, writer_name):- """Both marker rewriters must ask for owner AND group, then for the group alone.-- Neither half is sufficient. A shared install's marker is owned by whoever installed it,- and chown(2) refuses the WHOLE call when an unprivileged caller names another owner, so- asking only for the owner loses the group too and the next reader in that group cannot- read the marker. Asking only for the group is wrong the other way: under root, the one- caller that CAN restore the owner, it leaves the marker owned by root, and an 0600- marker stops being readable by the user who owns the install.- """+ """Rewriters ask for owner and group, then group alone: an unprivileged owner change fails the+ whole chown(2) call and drops the group, while group-only under root leaves a 0600 marker+ unreadable to its owner."""marker = tmp_path / "MARKER.json"marker.write_text('{"release_tag": "b10840"}\n', encoding = "utf-8")original = marker.stat()@@ -78,11 +72,8 @@ def test_a_live_marker_rewrite_falls_back_to_the_group_when_the_owner_is_refused@requires_chowndef test_the_group_survives_a_rewrite_the_owner_cannot_be_granted(tmp_path, monkeypatch):- """The end state, not just the argument: a refused owner must not cost the group.-- os.chown is emulated with the kernel's own rule -- an unprivileged caller may not change- the owner, and chown is all-or-nothing -- so this fails for any writer that names one.- """+ """A refused owner must not cost the group: os.chown is emulated with the kernel rule that an+ unprivileged caller cannot change the owner, and chown is all-or-nothing."""marker = tmp_path / "MARKER.json"marker.write_text('{"release_tag": "b10840"}\n', encoding = "utf-8")shared_gid = marker.stat().st_gid@@ -100,10 +91,8 @@ def test_the_group_survives_a_rewrite_the_owner_cannot_be_granted(tmp_path, monk@requires_chowndef test_a_marker_rewrite_keeps_the_keys_the_about_tab_renders(tmp_path, monkeypatch):- """release_tag and tag reach the user through /api/system/hardware and the About tab.-- A rewrite that drops them changes what Studio displays, so pin that they survive.- """+ """release_tag and tag reach the user via /api/system/hardware and the About tab, so a marker+ rewrite must keep both keys."""marker = tmp_path / "MARKER.json"marker.write_text('{"release_tag": "b10840", "tag": "b10840"}\n', encoding = "utf-8")monkeypatch.setattr(LLAMA.os, "chown", lambda path, uid, gid: None)diff --git a/tests/studio/install/test_pr10648_whisper_payload_digests.py b/tests/studio/install/test_pr10648_whisper_payload_digests.pyindex 1e71dd13bae..3e46bd96fd2 100644--- a/tests/studio/install/test_pr10648_whisper_payload_digests.py+++ b/tests/studio/install/test_pr10648_whisper_payload_digests.py@@ -223,9 +223,8 @@ def test_a_same_size_flip_in_a_ggml_library_is_deliberately_not_caught(tmp_path,def test_a_marker_whose_record_is_unusable_fails_closed(tmp_path, monkeypatch):- """Present but unreadable is not the same as absent. The record is the evidence that- replaces starting the binary, so an empty or malformed one proves nothing -- and it- cannot have come from the writer, which omits the key rather than writing {}."""+ """A present but unusable runtime record is not the same as an absent one: it proves nothing,+ and the writer never emits one since it omits the key rather than writing an empty record."""install_dir = _install(tmp_path, monkeypatch)for damaged in ({}, [], "runtime", {_server_key(install_dir): "not-a-record"}):marker = _marker(install_dir)@@ -306,9 +305,8 @@ def test_the_backfill_records_the_live_bytes_of_a_slim_tree(tmp_path, monkeypatcdef test_the_backfill_never_rewrites_a_record_it_did_not_take(tmp_path, monkeypatch):- """Added, never corrected. Overwriting a present record with whatever is on disk now- would re-bless bytes no run ever hashed -- it would turn the guard into a rubber- stamp the first time an update ran over a corrupt tree."""+ """The backfill only adds missing records and never overwrites one, since re-blessing bytes no+ run hashed would turn the guard into a rubber stamp."""install_dir = _install(tmp_path, monkeypatch)recorded = _marker(install_dir)["runtime_files"]WHISPER.installed_server_path(install_dir, LINUX).write_bytes(b"replaced-behind-our-back")@@ -411,9 +409,8 @@ def test_an_upgrade_does_not_re_download_and_settles_under_the_lock(tmp_path, modef test_a_backfill_that_cannot_hash_writes_nothing(tmp_path, monkeypatch):- """A scanner holding whisper-server open, or a tree half-owned by root. An empty- record is not evidence, and writing one would fail closed on every later update --- which is the re-download loop this whole part exists to prevent."""+ """A backfill that cannot hash (a scanner holding whisper-server open, or a tree half-owned by+ root) must write nothing; an empty record would fail closed on every later update."""install_dir = _install(tmp_path, monkeypatch)_legacy(install_dir)fired = {"n": 0}@@ -444,9 +441,8 @@ def test_a_changed_mtime_alone_does_not_reject(tmp_path, monkeypatch):def test_an_unrecorded_file_appearing_beside_the_payload_does_not_reject(tmp_path, monkeypatch):- """A user's own notes, an antivirus quarantine stub, a .bak from a support session.- A file that appeared since is not evidence against the install; only a RECORDED file- that moved is."""+ """A file that appeared beside the payload, such as user notes or an antivirus stub, is not+ evidence against the install; only a recorded file that moved is."""install_dir = _install(tmp_path, monkeypatch)(WHISPER.runtime_bin_dir(install_dir, LINUX) / "notes.txt").write_text("hello")assert _intact(install_dir) is True@@ -672,9 +668,8 @@ def test_an_unchanged_llama_install_still_takes_the_fast_path(tmp_path, monkeypadef test_a_marker_predating_the_key_is_backfilled_not_re_downloaded(tmp_path, monkeypatch):- """An older marker cannot say which bundle it was paired against, so a swap that ALREADY- happened is unanswerable from it. Reinstalling to find out would re-download the bundle- for every existing user; recording the current pairing makes the NEXT swap detectable."""+ """A marker predating paired_llama_runtime_id cannot say which bundle it paired with;+ backfilling the current pairing avoids re-downloads and makes the next swap detectable."""install_dir, _ = _slim_with_live_llama(tmp_path, monkeypatch)assert WHISPER.kept_install_needs_settling(install_dir) is Trueassert _reuse(install_dir, slim = True, tmp_path = tmp_path) is Truediff --git a/tests/studio/install/test_prebuilt_core.py b/tests/studio/install/test_prebuilt_core.pyindex a11cba07202..dd54e4e3b1b 100644--- a/tests/studio/install/test_prebuilt_core.py+++ b/tests/studio/install/test_prebuilt_core.py@@ -1096,11 +1096,9 @@ def test_a_kept_install_that_changes_under_the_lock_is_re_validated(tmp_path):@pytest.mark.skipif(not hasattr(core.os, "chown"), reason = "os.chown is POSIX only")def test_a_live_marker_rewrite_keeps_the_group_when_the_owner_is_refused(tmp_path, monkeypatch):- """A non-root member of a group-shared install can hand the temp file to the- marker's group, but not to its owner; asking for both refuses the call before the- group is applied and os.replace installs the member's primary group instead. So the- combined call is tried first, for the root case that can honour it, and the group-only- call is the fallback."""+ """Non-root members can set the group but not the owner; the combined chown is tried first for+ root, and group-only is the fallback, since a refused combined call would leave the primary+ group."""marker = tmp_path / "MARKER.json"marker.write_text('{"a": 1}', encoding = "utf-8")original = marker.stat()@@ -1119,9 +1117,8 @@ def test_a_live_marker_rewrite_keeps_the_group_when_the_owner_is_refused(tmp_patdef test_a_walk_back_is_recorded_with_the_host_version_that_decided_it():- """prebuilt_core.WalkBack: the marker-only re-check may hold an install on a Mac- below the newest release's floor current only while the newest release is the one- skipped AND the host is the macOS version that skipped it."""+ """prebuilt_core WalkBack: a marker-only re-check keeps a Mac below the newest release's floor+ current only if the newest release was skipped on the same macOS version."""mac = SimpleNamespace(is_macos = True, macos_version = (14, 7))assert core.macos_version_label(mac) == "14.7"assert core.macos_version_label(SimpleNamespace(is_macos = True, macos_version = None)) is Nonediff --git a/tests/studio/install/test_rdna1_unsupported_message_8529.py b/tests/studio/install/test_rdna1_unsupported_message_8529.pyindex 37aa56b0774..f8fd3a1a037 100644--- a/tests/studio/install/test_rdna1_unsupported_message_8529.py+++ b/tests/studio/install/test_rdna1_unsupported_message_8529.py@@ -536,9 +536,8 @@ class TestAdviceIsNotEmittedForRdna1:ids = [f"{p.name}:{c[:34]}" for p, c, _g in _HIPSDK_ARMS],)def test_the_hip_sdk_arm_does_not_outrank_the_unsupported_arm(self, path, condition, guard):- """Stated as a ban on the UNGUARDED condition, not as a search for the guarded- one: asserting only that the guarded text exists stays green if someone adds a- second, unguarded copy of the arm, and both spellings would then be present."""+ """Stated as a ban on the unguarded condition, since checking only that the guarded text+ exists stays green when an unguarded copy of the arm is added."""src = _normalised(path)assert condition + guard in src, (f"{path.name}: the {condition!r} arm has lost its unsupported-arch guard, so an "@@ -669,10 +668,8 @@ _KFD_NAVI31 = [@pytest.mark.skipif(os.name == "nt", reason = "POSIX shell only")class TestSetupShKfdOnlyHost:- """The KFD sysfs fallback marks the host AMD without rocminfo or amd-smi, so it- leaves _setup_mkt empty -- and a host with no ROCm userspace is exactly the one- #8529 and #8458 describe. Handed "", the lookup used to fall through to the plain- "AMD ROCm" report on a machine that has no ROCm."""+ """The KFD sysfs fallback leaves _setup_mkt empty without rocminfo or amd-smi; the lookup must+ not fall through to a plain AMD ROCm report there (issues 8529 and 8458)."""def test_the_kfd_host_is_diagnosed_from_lspci(self, tmp_path):assert _run_setup_kfd_lookup("", _KFD_NAVI10, tmp_path) == "gfx1010"@@ -708,9 +705,8 @@ class TestSetupShKfdOnlyHost:), "studio/setup.sh: the gpu report no longer goes through the lspci-aware lookup"def test_the_lspci_name_never_reaches_the_routing_table(self):- """Routing must stay byte-identical. The supported inference table keys on- _setup_mkt, which feeds --rocm-gfx into the prebuilt and whisper commands, so- the lspci read must not be written back into it."""+ """Routing must stay byte-identical: the supported inference table keys on _setup_mkt, which+ feeds --rocm-gfx into the prebuilt and whisper commands, so no lspci read goes there."""src = _normalised(_SETUP_SH)assigns = re.findall(r"^\s*_setup_mkt=(.*)$", src, re.MULTILINE)assert assigns, "studio/setup.sh: no _setup_mkt assignment found"@@ -838,9 +834,8 @@ def test_no_advice_arm_speaks_for_the_whole_host(source_path):@pytest.mark.parametrize("name,claims", sorted(_SCOPED_CLAIMS.items()))def test_the_scoped_wording_is_the_one_that_ships(name, claims):- """The other half: dropping the sentence entirely would also pass the ban above,- and would take the answer with it. Each arm still has to say ROCm cannot reach- the card it just named."""+ """Each arm must still say ROCm cannot reach the card it just named; dropping the sentence+ entirely would also pass the ban above and lose the answer."""source_path = next(p for p in _ALL_SOURCES if p.name == name)src = _normalised(source_path)emitted = [ln for ln in src.split("\n") if not ln.lstrip().startswith("#")]@@ -1060,17 +1055,15 @@ class TestVulkanAdvice:@pytest.mark.parametrize("needle,what", _REQUIRED, ids = lambda v: v if " " not in v else None)def test_the_vulkan_advice_is_reached_by_the_rdna1_wmi_path(self, needle, what):- """Source-text assertions cannot tell a live branch from a dead one, and the- Python copy's message is not readable line by line. Drive the real Windows- path and read what it actually printed."""+ """Source-text assertions cannot tell a live branch from a dead one, and the Python message+ is not readable line by line; drive the Windows path and read its output."""arch, out = _wmi_detect(["AMD Radeon RX 580"])assert arch is None, "routing must be unchanged; this is a wording fix"assert needle in out, f"the printed advice is missing {what} ({needle!r})"def test_the_printed_advice_uses_powershell_syntax(self):- """This branch is Windows-only, so its setter has to be pasteable into- PowerShell. Read the live output, not the source: the message is built from- implicitly-joined fragments and no single source line carries it."""+ """The Windows-only branch's setter must paste into PowerShell; read the live output, since+ the message is built from implicitly joined fragments no source line carries."""_arch, out = _wmi_detect(["AMD Radeon RX 580"])assert _PWSH_SETTER in out, f"the printed advice is not pasteable into PowerShell:\n{out}"assert (diff --git a/tests/studio/install/test_rocm_arch_table_parity.py b/tests/studio/install/test_rocm_arch_table_parity.pyindex d83ae8c7974..0409fae4ed4 100644--- a/tests/studio/install/test_rocm_arch_table_parity.py+++ b/tests/studio/install/test_rocm_arch_table_parity.py@@ -37,9 +37,8 @@ stack_mod = _load_stack_module()def _sh_function_body(source: str, name: str) -> str:- """Return a POSIX-shell function body by brace matching (same idea as- _extract_sh_function_body in test_rocm_support.py, kept local so this file- stands alone)."""+ """Return a POSIX-shell function body by brace matching; a local copy of+ _extract_sh_function_body so this file stands alone."""needle = f"{name}() {{"start = source.find(needle)assert start != -1, f"{name}() not found"@@ -225,9 +224,8 @@ def _match_sh(rows: list[tuple[list[str], str]], gpu_name: str) -> str | None:def _match_ps(rows: list[tuple[str, str]], gpu_name: str) -> str | None:- """Evaluate a PowerShell -match table: first arm whose regex matches wins.- -match is case-insensitive; .NET and Python agree on these patterns- (alternation plus one negative lookahead)."""+ """First arm whose regex matches wins; PowerShell -match is case-insensitive, and .NET and+ Python agree on these patterns (alternation plus one negative lookahead)."""for pattern, arch in rows:if re.search(pattern, gpu_name, re.IGNORECASE):return arch@@ -372,9 +370,8 @@ class TestGpuNameArchParity:@pytest.mark.parametrize("gpu_name", [name for name, _ in _GPU_NAME_LEAF_CASES])def test_all_copies_return_the_same_arch(self, gpu_name):- """The drift guard proper: no expected value, just agreement. This is what- catches a table edited in one installer and not the other three, and it- stays honest even where the shipped gfx id is itself wrong."""+ """Drift guard with no expected value, only agreement: catches a table edited in one+ installer but not the others, and stays honest even where the shipped gfx id is wrong."""answers = {where: _resolve(where, rows, gpu_name) for where, rows in _name_tables().items()}distinct = set(answers.values())assert len(distinct) == 1, f"{gpu_name!r} resolves inconsistently: {answers}"@@ -474,9 +471,8 @@ class TestSpoofFixtureParity:), f"{where}: spoof says {gfx} is {gpu_name!r}, installer says {got!r}"def test_divergences_are_real_and_still_diverging(self):- """Keeps the exception list from going stale: if the installers are- corrected later, this fails and the entry has to be removed rather than- quietly suppressing a check that now passes."""+ """Keeps the divergence exception list honest: once installers are corrected this fails so+ the entry is removed, not silently suppressing a passing check."""tables = _name_tables()profiles = _spoof_profiles()for gfx in _SPOOF_DIVERGENCES:@@ -541,9 +537,8 @@ def _files_carrying_a_name_arch_table(root: Path = PACKAGE_ROOT) -> dict[str, inclass TestNoUnregisteredArchTable:- """The failure this whole file exists for is a copy of the table that nobody- knew about. Enumerating the copies by hand is the same manual step that let- them drift, so this rediscovers them from the source tree."""+ """Guards against an unknown copy of the arch table; enumerating copies by hand is what let them+ drift, so the source tree is scanned instead."""def test_scan_still_finds_the_known_copies(self):"""Guards the guard: if the heuristic stops matching (patterns reformatteddiff --git a/tests/studio/install/test_rocm_gfx_spoof_7331.py b/tests/studio/install/test_rocm_gfx_spoof_7331.pyindex a49a3d4afeb..7eb0f1fc7ec 100644--- a/tests/studio/install/test_rocm_gfx_spoof_7331.py+++ b/tests/studio/install/test_rocm_gfx_spoof_7331.py@@ -132,9 +132,8 @@ class TestSpoofedStrixHaloRouting:assert "rocm6.3" not in calls, callsdef test_repair_over_the_broken_rocm63_torch(self):- """`studio update` on the host as the reporter left it: torch is already- 2.9.1+rocm6.3, so has_hip_torch is True and only the Strix reroute can fire. It- must, or the repair is a no-op and the segfault survives."""+ """studio update on a host with torch 2.9.1+rocm6.3 (has_hip_torch True) must still fire the+ Strix reroute, or the repair is a no-op and the segfault survives."""calls = _run_install(torch_probe_stdout = _ROCM63_TORCH, reprobe_devices = ["gfx1151"])assert "repo.amd.com/rocm/whl/gfx1151/" in calls, callsassert "torch>=2.11.0,<2.12.0" in calls, calls@@ -163,9 +162,8 @@ class TestPrecedenceStillHolds:assert "rocm7.1" in calls, callsdef test_kernel_showing_a_second_gpu_vetoes_the_correction(self):- """The mixed host seen through the kernel: the spoofed probe collapsed a Strix- APU and a gfx1100 dGPU into one apparent gfx1100, so the single-device premise- held. KFD sysfs sees both and withdraws it, so the correction must decline."""+ """The spoofed probe collapses a Strix APU and a gfx1100 dGPU into one apparent gfx1100; KFD+ sysfs sees both and withdraws the single-device premise, so the correction must decline."""calls = _run_install(kfd_targets = ["gfx1151", "gfx1100"],rocm_version = (7, 1),@@ -220,9 +218,8 @@ class TestPrecedenceStillHolds:assert "rocm7.1" in calls, callsdef test_deliberate_rdna2_override_is_not_a_strix_spoof(self):- """10.3.0 on an RX 6800 is the documented and CORRECT setting for that card. The- chassis is still a Ryzen AI Max, so the name still infers gfx1151 and the probe- still disagrees, but that does not make gfx1030 a spoof."""+ """10.3.0 is the documented correct override for an RX 6800; even in a Ryzen AI Max chassis+ that name-infers gfx1151, gfx1030 is not a spoof."""calls = _run_install(gfx_devices = ("gfx1030",),reprobe_devices = ["gfx1030"],@@ -233,9 +230,8 @@ class TestPrecedenceStillHolds:assert "gfx1151" not in calls, callsdef test_override_naming_a_third_arch_is_never_a_spoof(self):- """ROCr can only rename an agent to the target the variable names, so 10.3.0- alongside a gfx1100 reading means gfx1100 came from the silicon. No spoof to- undo, even if the kernel is silent and the re-probe agrees."""+ """ROCr only renames an agent to the target the variable names, so 10.3.0 beside a gfx1100+ reading came from the silicon, so no spoof to undo even if the kernel is silent."""calls = _run_install(env = {"HSA_OVERRIDE_GFX_VERSION": "10.3.0"},reprobe_devices = ["gfx1151"],@@ -296,9 +292,8 @@ class TestHsaOverrideArch:class TestKfdGfxTargets:- """amdkfd encodes gfx_target_version as major*10000 + minor*100 + stepping, the- stepping in hex. gfx1151 is 110501; the 110511 circulating online decodes to a- nonexistent part, so it is pinned here. Reads a fabricated sysfs tree."""+ """amdkfd encodes gfx_target_version as major*10000 + minor*100 + hex stepping; gfx1151 is+ 110501 and the circulating 110511 decodes to no real part."""def _nodes(self, tmp_path, monkeypatch, nodes):root = tmp_path / "nodes"@@ -694,9 +689,8 @@ class TestRandomizedParity:@pytest.mark.parametrize("seed", [0])def test_never_corrects_without_corroboration(self, seed, fake_rocminfo):- """The safety invariant over the same random matrix: a verdict is only returned- when a source the override cannot reach (the kernel, or rocminfo re-probed- without it) named that exact arch and nothing else."""+ """Safety invariant over the random matrix: a verdict is returned only when the kernel, or+ rocminfo re-probed without the override, named that exact arch and nothing else."""for shape in _shapes(seed, 100):env = {"FAKE_KFD": "\n".join(shape["kfd"]),@@ -835,9 +829,8 @@ class TestConfirmedSpoofIsClearedBeforeLaunch:assert probe["HSA_OVERRIDE_GFX_VERSION"] is None, probedef test_declined_spoof_keeps_the_users_override(self):- """A real gfx1100 dGPU in a Ryzen AI Max chassis keeps generic wheels, where the- override is the user's own business. Nothing was disproved, so nothing is taken- away."""+ """A real gfx1100 dGPU in a Ryzen AI Max chassis keeps generic wheels and the user's own HSA+ override, since nothing was disproved and nothing is removed."""probe = {}calls = _run_install(kfd_targets = ["gfx1100"],diff --git a/tests/studio/install/test_rocm_native_linux_lib_dirs.py b/tests/studio/install/test_rocm_native_linux_lib_dirs.pyindex 2aa5650b3ef..c44f9f13d04 100644--- a/tests/studio/install/test_rocm_native_linux_lib_dirs.py+++ b/tests/studio/install/test_rocm_native_linux_lib_dirs.py@@ -253,9 +253,8 @@ class TestNativeLinuxRootResolution:], wheredef test_lib64_host_still_finds_llvm_under_lib(self, bundle_dir):- """ROCm puts LLVM under <root>/lib/llvm even where HSA lives in lib64, so- deriving the llvm dir from the HSA dir alone would miss it and leave- libamd_comgr binding to the bundle's libLLVM."""+ """ROCm puts LLVM under <root>/lib/llvm even where HSA lives in lib64; deriving it from the+ HSA dir alone would miss it and bind libamd_comgr to the bundle's libLLVM."""present = {"/dev/kfd","/opt/rocm/lib64/libhsa-runtime64.so",diff --git a/tests/studio/install/test_rocm_support.py b/tests/studio/install/test_rocm_support.pyindex bf6981aea9d..a8ad52912d1 100644--- a/tests/studio/install/test_rocm_support.py+++ b/tests/studio/install/test_rocm_support.py@@ -915,9 +915,8 @@ class TestEnsureRocmTorch:assert "download.pytorch.org" not in torch_calldef test_cuda_torch_on_amd_host_reinstalls(self):- """A CUDA-only torch build is unusable on an AMD-only host, so it must be- reinstalled to ROCm (has_hip_torch is driven by the empty HIP marker, not- by treating the CUDA version string as a HIP marker)."""+ """A CUDA-only torch is unusable on an AMD-only host so it must reinstall to ROCm;+ has_hip_torch keys off the empty HIP marker, not the CUDA version string."""mock_pip, _ = run_ensure_rocm_torch("2.10.0+cu126||", _has_rocm_gpu = True, _detect_rocm_version = (7, 1))@@ -1380,11 +1379,9 @@ GPU: 2def test_explicit_gfx_index_honored_and_skips_strix_reroute(self, mock_ver, mock_gpu, mock_nvidia, mock_pip, mock_pip_try, mock_machine):- """An explicit gfx wheel-index pin is authoritative: install from it verbatim- with torch 2.11, and the pin must not be second-guessed (host ROCm 6.4 would- otherwise pick the rocm6.4 wheel / trigger the Strix re-route). The gfx probe- may run for the bnb-skip flag, but returning a Strix arch must not reroute the- pinned torch index."""+ """An explicit gfx wheel-index pin is authoritative: installed verbatim with torch 2.11, not+ re-picked from host ROCm 6.4 or rerouted for Strix; the gfx probe may still run for the+ bnb skip."""mock_probe = MagicMock()mock_probe.returncode = 0mock_probe.stdout = "\n" # cpu torch -> reinstall@@ -1542,9 +1539,8 @@ GPU: 2def test_non211_gfx_pin_over_210_rocm_no_reinstall(self, mock_ver, mock_gpu, mock_nvidia, mock_pip, mock_pip_try):- """A gfx90a pin (NOT in the 2.11 allowlist) over a correct 2.10+rocm- wheel must NOT be flagged stale -- the install path uses the default <2.11- specs for that arch, so re-flagging would reinstall-loop on every update."""+ """A gfx90a pin, not in the 2.11 allowlist, over a correct 2.10+rocm wheel must not be+ flagged stale; default <2.11 specs apply, so re-flagging would reinstall every update."""mock_probe = MagicMock()mock_probe.returncode = 0mock_probe.stdout = _MARK + "2.10.0+rocm6.4|6.4.12345|\n"@@ -1569,9 +1565,8 @@ GPU: 2def test_gfx_pin_over_generic_rocm211_reinstalls(self, mock_ver, mock_gpu, mock_nvidia, mock_pip, mock_pip_try, mock_machine):- """A gfx1151 pin over a GENERIC (two-part +rocm7.2) 2.11 wheel must reinstall- the AMD per-arch wheel -- even though both are torch 2.11, the generic wheel- is not the per-arch build the user pinned (Strix stays off the generic wheel)."""+ """A gfx1151 pin over a generic two-part +rocm7.2 torch 2.11 wheel must reinstall the+ per-arch AMD wheel, since the generic build is not the one pinned."""mock_probe = MagicMock()mock_probe.returncode = 0mock_probe.stdout = _MARK + "2.11.0+rocm7.2|7.2.12345|\n"@@ -1814,9 +1809,8 @@ class TestGfx906LegacyReroute:mock_pip_try.assert_not_called()def test_mixed_host_gfx906_not_sole_arch_skips_reroute(self, monkeypatch):- """Mixed host (gfx906 + dGPU) with no explicit override: gfx906 is not the- sole arch, so the generic index is kept (Codex #3: never downgrade a- de-dup-ambiguous mixed host)."""+ """Mixed gfx906 plus dGPU host with no explicit override keeps the generic index, since+ gfx906 is not the sole arch (Codex finding 3: never downgrade an ambiguous mixed host)."""monkeypatch.delenv("UNSLOTH_ROCM_GFX_ARCH", raising = False)mock_pip, _ = self._reroute(["gfx1100", "gfx906"])torch_call = str(mock_pip.call_args_list[0])@@ -1833,9 +1827,8 @@ class TestGfx906LegacyReroute:assert "rocm7.2" not in torch_calldef test_gfx906_bnb_skipped_even_when_index_pinned(self, monkeypatch):- """A gfx906 user who pins the ROCm index AND sets the arch override still- skips the generic bnb wheel: the pin suppresses the torch reroute, not the- gfx906 runtime flag used for the bnb skip."""+ """A gfx906 user who pins the ROCm index and sets the arch override still skips the generic+ bnb wheel; the pin suppresses only the torch reroute, not the bnb skip flag."""monkeypatch.setenv("UNSLOTH_ROCM_GFX_ARCH", "gfx906")monkeypatch.setenv("UNSLOTH_TORCH_INDEX_URL", "https://download.pytorch.org/whl/rocm6.3")mock_pip, mock_pip_try = self._reroute(["gfx906"])@@ -4942,9 +4935,8 @@ $adapters = @(class TestSetupPs1ShadowingParity:- """setup.ps1 resolves the arch and builds $ROCmIndexUrl itself, before the Python- stack installer ever runs, so both halves of the #7776 preference have to exist in- the PowerShell mirror too or a fresh Windows install still picks the iGPU."""+ """setup.ps1 builds $ROCmIndexUrl itself before the Python installer runs, so both halves of+ #7776 must exist in its PowerShell copy or fresh Windows installs pick the iGPU."""@staticmethoddef _setup_ps1() -> str:@@ -5213,8 +5205,7 @@ class TestInstallBnbWindowsRocm:assert stack_mod._BNB_ROCM_PYPI_FALLBACK in mock_pip.call_args_list[1].argsdef test_returns_false_only_when_both_paths_fail(self):- """Both the pre-release wheel and the PyPI fallback must fail before the- helper reports failure."""+ """Both the pre-release wheel and the PyPI fallback must fail before the helper reports failure."""with patch.dict(os.environ, {}, clear = False):os.environ.pop("BNB_ROCM_VERSION", None)with patch.object(stack_mod, "pip_install_try", return_value = False) as mock_pip:@@ -5674,9 +5665,8 @@ class TestWindowsRocmTorchaoGuard:class TestProgressStepCountMatchesTotal:- """The progress bar must reach exactly _TOTAL: every _progress() step is counted in- base_total. Regression for a repair step added without incrementing base_total,- which pushed _STEP past _TOTAL (Codex P2)."""+ """Progress must reach exactly _TOTAL, so every _progress() step must be counted in base_total;+ a repair step once overran _STEP past _TOTAL (Codex P2)."""def _run_stack(self,@@ -5904,9 +5894,8 @@ class TestWorkerWindowsRocmPatches:assert "install_torchao_windows_rocm_real_or_stub()" in sourcedef test_embedder_calls_shared_torchao_stub(self):- """embeddings.py must install the stub before importing sentence-transformers:- it runs in the main process (not a stubbed worker), so otherwise transformers- -> torchao crashes on Windows ROCm and the embedder drops to llama-server."""+ """embeddings.py must install the stub before importing sentence-transformers in the main+ process, or torchao crashes on Windows ROCm and the embedder drops to llama-server."""source = _EMBEDDINGS_PATH.read_text(encoding = "utf-8")assert "install_torchao_windows_rocm_stub()" in source@@ -6437,9 +6426,8 @@ class TestStrixRocm71Override:assert m._linux_amd_gfx_from_lspci() == expected, stdoutdef test_install_sh_lspci_scan_covers_all_display_controllers(self):- """install.sh mirror of the scan-all behaviour, executed with a shimmed- lspci: Intel-first still finds the AMD dGPU, NVIDIA-only maps nothing- (860M collision), a domain-prefixed AMD line still maps."""+ """install.sh mirrors the scan-all lspci behaviour: Intel-first still finds the AMD dGPU,+ NVIDIA-only maps nothing (860M collision), and domain-prefixed AMD lines still map."""shell = shutil.which("bash")if not shell:pytest.skip("bash needed to execute the probe block")@@ -7279,9 +7267,8 @@ class TestRocmGfxForwarding:@staticmethoddef _resolve_setup_ps1_repo():- """Run setup.ps1's $HelperReleaseRepo assignment under pwsh and return the- resolved repo. The assignment is unconditional now, so there are no host- inputs to vary."""+ """Run setup.ps1's $HelperReleaseRepo assignment under pwsh and return the resolved repo; it+ is unconditional, so no host inputs vary."""import shutilpwsh = shutil.which("pwsh")@@ -7529,9 +7516,8 @@ class TestLlamaCppRuntimeWslOrdering:class TestRocmWslSupplyChainPins:- """The ROCm-on-WSL bootstrap runs unattended and installs with sudo, so every piece of- code it fetches must come from an immutable ref: a moving branch would turn any rewrite- of that branch into root code execution on affected WSL hosts."""+ """The ROCm-on-WSL bootstrap runs unattended with sudo, so every fetched piece of code must come+ from an immutable ref, since a moving branch means root code execution."""def test_helper_is_fetched_from_a_pinned_commit_not_a_branch(self):source = _INSTALL_SH_PATH.read_text(encoding = "utf-8")diff --git a/tests/studio/install/test_selection_logic.py b/tests/studio/install/test_selection_logic.pyindex a012f0588ae..18faac8d279 100644--- a/tests/studio/install/test_selection_logic.py+++ b/tests/studio/install/test_selection_logic.py@@ -1724,9 +1724,8 @@ class TestResolveInstallAttempts:assert approved.release_tag == "llama-prebuilt-latest"def test_windows_cuda_fork_never_falls_back_to_upstream_assets(self, monkeypatch):- # The fork's checksums once approved an upstream ggml-org Windows CUDA zip by name;- # prebuilts now come only from the fork, so a release without a covering published- # bundle raises (older release / source build) and never lists ggml-org's assets.+ # Fork checksums must never approve an upstream ggml-org zip by name, so a release lacking a+ # covering bundle raises and never lists ggml-org assets.host = make_host(system = "Windows", machine = "AMD64")host.driver_cuda_version = (12, 4)mock_windows_runtime(monkeypatch, ["cuda12"])@@ -2392,9 +2391,8 @@ class TestWindowsCudaAttemptCoversBlackwell:class TestDirectUpstreamWindowsAmdTakesVulkan:- """The direct/upstream planner is reached when the caller pins --published-repo, so the- Windows Vulkan gate there has to match the published one. Left Intel-only, a Windows AMD- host with no usable ROCm took the CPU attempt even with win-vulkan in the release."""+ """The direct/upstream planner runs when --published-repo is pinned, so its Windows Vulkan gate+ must match the published one; Intel-only left Windows AMD hosts with no usable ROCm on CPU"""TAG = "b9365"@@ -2838,8 +2836,7 @@ class TestLinuxPublishedAttemptsNvidiaCpuGate:return make_host(**base)def test_amd_without_rocm_gets_the_published_vulkan_bundle(self):- """Published attempts must prefer Vulkan in _linux_published_attempts for AMD without ROCm,- not CPU."""+ """_linux_published_attempts must prefer the Vulkan bundle over CPU for AMD hosts without ROCm."""host = self._gpu_host(has_amd_gpu_without_rocm = True)attempts = INSTALL_LLAMA_PREBUILT._linux_published_attempts(host, self._vulkan_and_cpu_bundle()@@ -2935,9 +2932,8 @@ class TestPublishedWindowsCudaAttemptsDynamicMajor:class TestPublishedLegacyNamedArm64BundlesAreOrdered:- """The legacy-minor ordering synthesised -x64.zip names and called windows_cuda_attempts- without the arch, so an approved llama-<tag>-bin-win-cuda-13.1-arm64.zip produced no- runtime line and was skipped for the unchecksummed upstream fallback."""+ """Legacy-minor ordering synthesised -x64.zip names and dropped the arch passed to+ windows_cuda_attempts, so approved arm64 bundles fell back to unchecksummed upstream."""TAG = "b8508"@@ -2986,9 +2982,8 @@ class TestPublishedLegacyNamedArm64BundlesAreOrdered:assert all(not a.name.endswith("13.3-arm64.zip") for a in result)def test_the_artifact_gate_reads_the_arm64_name(self, monkeypatch):- """Two legacy minors on one line, the higher one ranked first: the line survives on- the lower minor, and the per-artifact gate must parse the -arm64 name to drop the- higher one; an x64 spelling never matches, and the preferred 13.3 build slips through."""+ """With two legacy minors on one line, the per-artifact gate must parse the -arm64 name to+ drop the higher minor; an x64 spelling never matches."""mock_windows_runtime(monkeypatch, ["cuda13"])release = self._release([("13.3", "cuda13"), ("13.1", "cuda13")], ranks = {"13.3": 10})result = published_windows_cuda_attempts(self._host((13, 1)), release, None, arch = "arm64")diff --git a/tests/studio/install/test_setup_denied_install_tree.py b/tests/studio/install/test_setup_denied_install_tree.pyindex daf56c6ec6c..eb5cbcbfc0b 100644--- a/tests/studio/install/test_setup_denied_install_tree.py+++ b/tests/studio/install/test_setup_denied_install_tree.py@@ -46,9 +46,8 @@ def test_prebuilt_metadata_probe_cannot_terminate_setup():def test_every_denial_route_reports_instead_of_proceeding():- """An unreadable parent dir, metadata file, .git checkout, or ownership root- must all stop. Treating any of them as absent lets the caller replace or- delete a tree it cannot read."""+ """An unreadable parent dir, metadata file, .git checkout or ownership root must stop setup;+ treating any of them as absent lets the caller replace or delete a tree it cannot read."""assert "$llamaDirState = Get-LlamaCppInstallReadState -Path $LlamaCppDir" in SETUP_PS1assert '$llamaDirState -eq "Denied"' in SETUP_PS1assert '$llamaGitState = Get-PathState -Path (Join-Path $LlamaCppDir ".git")' in SETUP_PS1@@ -148,9 +147,8 @@ def test_whisper_phase_stays_non_fatal_on_a_denied_llama_tree():def test_reporting_helpers_tolerate_an_empty_path():- """These run while a failure is being reported. A mandatory [string] rejects- null and empty, so without these attributes the reporter would throw a- binding exception instead of printing the actionable message."""+ """These run while a failure is reported; a mandatory [string] rejects null and empty, so+ without these attributes (such as [AllowNull()]) the reporter throws a binding exception."""for name in ("Get-PathDenialDetail", "Exit-PathAccessDenied"):body = SETUP_PS1.split(f"function {name}", 1)[1].split("\nfunction ", 1)[0]head = body.split("$Path", 1)[0]@@ -174,9 +172,8 @@ def test_local_llama_dir_probes_are_three_state():def test_phase_1b_git_scan_is_guarded_too():- """The git prerequisite scan probes the same candidate binaries in Phase 1b,- thousands of lines before the Phase 4 guards, and under "Stop". A denial- there reproduced the original raw termination."""+ """The git prerequisite scan in Phase 1b probes the same candidate binaries under Stop,+ thousands of lines before the Phase 4 guards; a denial there reproduced the raw termination."""scan = SETUP_PS1.split("$_localLlamaBuilt = $false", 1)[1].split("if (-not $_localLlamaBuilt) {", 1)[0]@@ -188,9 +185,8 @@ def test_phase_1b_git_scan_is_guarded_too():def test_adoption_markers_keep_their_denial():- """A denied prebuilt marker is not evidence of absence. Collapsing it made the- ownership guard call an Unsloth tree an unrelated directory and tell the user- to move it aside, hiding a permissions problem."""+ """A denied prebuilt marker is not evidence of absence; collapsing it made the ownership guard+ call an Unsloth tree unrelated and advise moving it aside, hiding a permissions problem."""assert "function Get-StudioAdoptableState" in SETUP_PS1state = SETUP_PS1.split("function Get-StudioAdoptableState", 1)[1].split("\nfunction ", 1)[0]assert "Get-PathState -Path (Join-Path $Path $marker) -PathType Leaf" in state@@ -254,9 +250,8 @@ def test_the_reparse_point_unlink_reports_a_denied_delete():def test_the_temp_dir_swap_checks_both_of_its_destructive_steps():- """Remove-Item and Move-Item are both non-terminating here, and Move-Item- onto a surviving directory nests the build inside it rather than replacing- it, so setup would report a build it never installed."""+ """Remove-Item and Move-Item are both non-terminating here, and Move-Item onto a surviving+ directory nests the build instead of replacing it, so both steps must be checked."""swap = SETUP_PS1.split("# Swap temp build dir into final location", 1)[1]swap = swap.split("} elseif (-not $BuildOk", 1)[0]assert "$swapState = Get-PathState -Path $OriginalLlamaCppDir" in swap, swap@@ -317,9 +312,8 @@ def _slice(start: str, end: str) -> str:def _whisper_phase() -> str:- """The whisper phase body. Both anchors are asserted so a phase renumbering- fails as an assertion instead of an IndexError, and cannot silently widen- the window to end-of-file."""+ """Returns the whisper phase body; both anchors are asserted so a phase renumbering fails as an+ assertion, not an IndexError, and cannot widen to end-of-file."""return _slice("Install the whisper.cpp prebuilt", "PHASE 3.5")diff --git a/tests/studio/install/test_setup_fast_path_guard.py b/tests/studio/install/test_setup_fast_path_guard.pyindex 6df8b1d195d..3c534291548 100644--- a/tests/studio/install/test_setup_fast_path_guard.py+++ b/tests/studio/install/test_setup_fast_path_guard.py@@ -121,9 +121,8 @@ def test_the_installer_reports_duplicate_metadata_on_every_platform(script: pathdef test_the_sidecar_predicate_asks_the_shim_on_colab_too():- """No venv interpreter on Colab; the shim is stdlib-only and the installer's own- `python` asks it. The version grep alone read a sidecar interrupted after- transformers landed as current on every later run."""+ """On Colab there is no venv interpreter, so the stdlib-only shim is asked via python; a version+ grep alone reads a sidecar interrupted after transformers as current."""text = SETUP_SH.read_text(encoding = "utf-8")start = text.index("_sidecar_current() {")body = text[start : text.index("\n}\n", start)]@@ -170,9 +169,8 @@ def test_the_ps1_sidecar_installs_are_isolated_from_uv_override():def test_the_tiktoken_top_up_checks_the_payload_not_the_dist_info_alone():- """An interrupted install leaves tiktoken-*.dist-info with no package beside it; the- sidecar predicate accepts that sidecar (tiktoken is optional), so the top-up is the- only repair left, and a dist-info-only check would skip it forever."""+ """An interrupted install can leave tiktoken dist-info without its package; the predicate+ accepts it (tiktoken is optional), so the top-up must check the payload itself."""sh = SETUP_SH.read_text(encoding = "utf-8")start = sh.index("_sidecar_top_up_tiktoken() {")assert '"$_stt_dir/tiktoken/__init__.py"' in sh[start : sh.index("\n}\n", start)]diff --git a/tests/studio/install/test_torch_probe_classification_parity.py b/tests/studio/install/test_torch_probe_classification_parity.pyindex 35a281805ea..b1ac9b45a78 100644--- a/tests/studio/install/test_torch_probe_classification_parity.py+++ b/tests/studio/install/test_torch_probe_classification_parity.py@@ -164,9 +164,8 @@ class TestClassificationIsAFaithfulTranslation:assert env["_is_gpu_build"] == _old_cpu_is_gpu(ver, hip, cuda)def test_the_xpu_runtime_marker_is_the_one_deliberate_divergence(self, ver, hip, cuda):- """An untagged source, conda or private-index XPU wheel carries its runtime only- in torch.version.xpu. The old predicate read it as CPU and declined to reinstall,- which is the whole reason the marker was added."""+ """An untagged source, conda or private-index XPU wheel carries its runtime only in+ torch.version.xpu; the old predicate read it as CPU and declined to reinstall."""env = {"re": re,"_version": ver,diff --git a/tests/studio/install/test_transformers_tokenizers_pair.py b/tests/studio/install/test_transformers_tokenizers_pair.pyindex 94ee28ccbed..2a64746e708 100644--- a/tests/studio/install/test_transformers_tokenizers_pair.py+++ b/tests/studio/install/test_transformers_tokenizers_pair.py@@ -116,9 +116,8 @@ def test_the_tokenizers_bound_matches_the_pinned_transformers_release():def test_the_tokenizers_line_covers_both_python_branches():- """The transformers pins split on python_version; the tokenizers line must not, unless- it splits the same way. An unconditional line is correct only while both pinned- releases declare the same window, which the test above is what enforces."""+ """The transformers pins split on python_version, so the tokenizers line must split the same+ way; an unconditional line is only correct while both releases declare the same window."""for path in _installing_files():reqs = _requirements(path)if not _pinned_versions(reqs, "transformers"):diff --git a/tests/studio/install/test_unsupported_arch_routing_guards_8529.py b/tests/studio/install/test_unsupported_arch_routing_guards_8529.pyindex 3ec7359562b..b8cb9d58439 100644--- a/tests/studio/install/test_unsupported_arch_routing_guards_8529.py+++ b/tests/studio/install/test_unsupported_arch_routing_guards_8529.py@@ -60,9 +60,8 @@ _ROUTABLE_ARCHES = [("gfx1030", "gfx103X-all"), ("gfx1100", "gfx110X-all")]@pytest.fixture(autouse = True)def _no_index_mirror():- """Both resolvers honour a mirror override, and a host that has one set would- answer with its URL instead of repo.amd.com. Clear them so the assertions below- are about the arch tables and not about the environment running the suite."""+ """Both resolvers honour a mirror override that would return its URL, not repo.amd.com; clear+ UNSLOTH_AMD_ROCM_MIRROR and UNSLOTH_ROCM_WINDOWS_MIRROR so tests check arch tables only."""with patch.dict(os.environ, {}, clear = False):for _v in ("UNSLOTH_AMD_ROCM_MIRROR", "UNSLOTH_ROCM_WINDOWS_MIRROR"):os.environ.pop(_v, None)@@ -165,9 +164,8 @@ class TestRdna1RoutesOnWindowsOnly:def _sh_function_body(source: str, name: str) -> str:- """Same extraction as test_rdna1_unsupported_message_8529.py: take the function- verbatim from the installer so the shell evaluates the shipped text, not a- Python re-implementation of it."""+ """Same extraction as test_rdna1_unsupported_message_8529.py: take the function verbatim from+ the installer so the shell evaluates the shipped text, not a Python copy."""needle = f"{name}() {{"start = source.find(needle)assert start != -1, f"{name}() not found"@@ -328,9 +326,8 @@ class TestInstallShIndexSelectorRuns:), f"{arch} reaches the per-arch handoff, which reroutes to repo.amd.com"def test_the_selector_still_reaches_its_amd_branch(self):- """Second positive control: on the same stubbed host with a readable ROCm- version the selector returns a ROCm index, which it can only do by running the- AMD branch the test above depends on."""+ """Second positive control: with a readable ROCm version on the same stubbed host the+ selector returns a ROCm index, which requires the AMD branch the tests above rely on."""url, _err = _run_sh_get_torch_index_url("gfx1030", rocm_tag = "rocm6.4")assert url.endswith("/rocm6.4"), f"the AMD branch was not reached: {url!r}"@@ -734,9 +731,8 @@ class TestSetupShReportBlamesTheRightCard:ids = ["kfd-no-name", "generic-name", "vendor-only"],)def test_an_unmapped_market_name_still_reaches_the_lspci_scan(self, tmp_path, mkt):- """rocminfo can hand back a nonempty name that maps to nothing. Returning that- failure ended the lookup, so the lspci scan never ran and the report fell back to- the plain "AMD ROCm" line this change exists to replace."""+ """rocminfo can return a nonempty name that maps to nothing; returning that failure ended+ the lookup before the lspci scan, falling back to the plain AMD ROCm line."""assert _run_setup_report(tmp_path, [_RX_5700], mkt).startswith("UNCOVERED"), f"an unmapped market name ({mkt!r}) hides an uncovered card lspci can see"@@ -768,9 +764,8 @@ class TestSetupShReportBlamesTheRightCard:ids = ["5700-first", "7900-first"],)def test_a_named_hit_is_guarded_by_the_peers_too(self, tmp_path, lines):- """amd-smi reports ONE market name, the first device's, so on a mixed host the- name itself is the uncovered card. Accepting it before the peer scan put the- false verdict back through the other door."""+ """amd-smi reports ONE market name, the first device's, so on a mixed host that name may be+ the uncovered card; accepting it before the peer scan reintroduces the false verdict."""verdict = _run_setup_report(tmp_path, lines, "AMD Radeon RX 5700 XT")assert verdict == "GENERIC", f"a named hit skipped the covered-peer guard: {verdict!r}"@@ -941,11 +936,8 @@ def _ps_unsupported(path: Path, names):@pytest.mark.skipif(os.name == "nt", reason = "POSIX shell only")@pytest.mark.skipif(shutil.which("sh") is None, reason = "no POSIX sh on this host")def test_the_five_unsupported_tables_agree_on_every_name():- """Five hand-kept copies of one table is the standing risk in this area, and the- supported tables are already pinned to each other. The unsupported ones were not:- a row added to a single file (RX 540 -> gfx803 in one of the five) passed the whole- suite. Compare by EVALUATION, in each source's own language, so a copy that spells- the same rule differently still counts as agreeing."""+ """Five hand-kept copies of the unsupported-arch table; compare by evaluation in each source's+ language, so a row added to one copy is caught (RX 540 -> gfx803)."""names = _PARITY_NAMESanswers = {"install_python_stack.py": _py_unsupported(names),diff --git a/tests/studio/install/test_update_idempotency.py b/tests/studio/install/test_update_idempotency.pyindex cccddd558a5..b4c9af07f43 100644--- a/tests/studio/install/test_update_idempotency.py+++ b/tests/studio/install/test_update_idempotency.py@@ -80,15 +80,13 @@ WHISPER_UNPAIRED = re.compile(r"whisper\.cpp\s+no compatible prebuilt \(")AUDIO_CPP_STEP = re.compile(r"^\s*audio\.cpp\s+\S", re.MULTILINE)# A warm-cache rebuild talks to no forbidden host, so the log line is the only witness.FRONTEND_CURRENT_MARKER = re.compile(r"frontend\s+up to date")-# What setup.sh / setup.ps1 print when the version check found a newer release, and when-# it could not ask PyPI at all (the pass runs on purpose in both cases).+# setup.sh/setup.ps1 messages for a newer release or unreachable PyPI; the pass runs anyway.UPGRADE_MARKER = "available, updating..."UPTODATE_MARKER = re.compile(r"python\s+\S+ \S+ is up to date")PYPI_UNREACHABLE_MARKER = "could not reach PyPI, updating to be safe..."# What --local installs from the checkout on every pass, so its RECORD moving is expected.LOCAL_CORE = frozenset({"unsloth", "unsloth-zoo", "unsloth_zoo"})-# Full passes reinstall these at the same version: seed plugins, and click (sqlfluff<4 vs-# huggingface-hub 1.23+, recorded known_unmet).+# Full passes reinstall seed plugins and click unchanged (sqlfluff<4 vs huggingface-hub 1.23+).FULL_PASS_CHURN = LOCAL_CORE | frozenset({"data-designer-github-repo-seed", "data-designer-unstructured-seed", "click"})@@ -285,9 +283,8 @@ def _wait_until(timeout: float = 5.0,interval: float = 0.05,) -> bool:- """Poll until `predicate` holds or the deadline passes. A monotonic deadline rather- than a fixed sleep: the wait is for something the proxy is already doing, and a sleep- long enough to be safe on a loaded CI box is wasted on every ordinary run."""+ """Poll until `predicate` holds or the monotonic deadline passes; a fixed sleep would waste time+ on every ordinary run."""deadline = time.monotonic() + timeoutwhile True:if predicate():@@ -458,8 +455,7 @@ def _digest(path: pathlib.Path) -> str | None:def _tree_state(root: pathlib.Path) -> dict | None:- """File count and newest mtime. Cheap enough for a sidecar of 4000 files, and it- moves the moment anything in the tree is rewritten."""+ """File count and newest mtime; cheap for 4000 files and moves when anything is rewritten."""if not root.is_dir():return Nonecount = 0@@ -561,8 +557,7 @@ def expected_prebuilt_answers(log: str) -> int:@pytest.fixture(scope = "session")def settled(install, tmp_path_factory):- """One update, so whatever the install left half-decided is decided. Everything- below measures the update AFTER this one."""+ """A settling update, so anything the install left half-decided is decided first."""directory = tmp_path_factory.mktemp("idempotency")run = run_update(directory, "run1-settle")assert run.rc == 0, f"the first update failed:\n{run.log[-8000:]}"@@ -586,8 +581,7 @@ def test_a_second_update_changes_nothing_on_disk(install, settled):def test_a_second_update_downloads_no_payload(install, settled):- """The measurement the timings cannot make: a fast run and a run that refetched- three release manifests look the same on a warm cache."""+ """Timings miss refetches: on a warm cache, refetching three manifests still looks fast."""directory, _ = settledrun = run_update(directory, "run3-network")assert run.rc == 0, run.log[-8000:]@@ -702,9 +696,8 @@ def test_a_truncated_sidecar_file_rebuilds_only_that_sidecar(install, settled):def test_a_deleted_manifest_re_runs_the_pass_and_changes_nothing(install, settled):- """The manifest is the only record of what the last pass did. Without it every step- must run -- and every step must then find its work already done, so the venv comes- out identical."""+ """The manifest is the only record of the last pass; without it every step re-runs and must find+ its work done, leaving the venv identical."""directory, _ = settledmanifest = install.parent.parent / "unsloth_install_manifest.json"saved = manifest.read_bytes()@@ -849,9 +842,8 @@ def test_full_deps_forces_every_step_and_still_changes_nothing(install, settled)def test_the_install_is_left_working(install, settled):- """Runs last. The fault cases legitimately move mtimes -- a rebuilt sidecar is a- rebuilt sidecar -- so this asserts what has to be true anyway: the same packages are- installed, and the install reports itself complete."""+ """Runs last; fault cases legitimately move mtimes, so this checks only that the same packages+ are installed and the install reports complete."""_directory, before = settled_assert_install_working(install, before)diff --git a/tests/studio/install/test_uv_boolish_parity.py b/tests/studio/install/test_uv_boolish_parity.pyindex 37d20cea047..bdce5259e2e 100644--- a/tests/studio/install/test_uv_boolish_parity.py+++ b/tests/studio/install/test_uv_boolish_parity.py@@ -211,12 +211,8 @@ def test_an_unset_variable_answers_rather_than_aborts_under_a_callers_strict_mod@pytest.mark.parametrize("variable", ["UV_OFFLINE", "UV_NO_CONFIG", "UV_NO_INDEX"])@pytest.mark.parametrize(("value", "expected"), BOOLISH_TABLE, ids = TABLE_IDS)def test_every_uv_variable_gets_the_same_table(variable, value, expected):- """One function, so the variable cannot change the answer.-- Asserted rather than assumed: the bug being fixed was three sites reading three- variables through three inline copies of one idiom, and a later site added the same- way would read differently again.- """+ """One shared function so the variable cannot change the answer; the bug was three inline copies+ of one idiom that could drift."""assert _ps_flag(SETUP_PS1, "Test-UvEnvFlag", variable, value) is expected@@ -252,9 +248,8 @@ def test_pips_rule_is_checked_against_pip_itself():def test_the_pip_reader_is_a_separate_function_from_the_uv_one():- """Not a style point. PIP_NO_INDEX is pip's variable and uv never reads it, so a single- shared function would mean a correction to uv's parsing silently changing what the pip- fallback does with an index."""+ """Not style: PIP_NO_INDEX is pip's variable and uv never reads it, so one shared function would+ let a uv parsing fix silently change the pip fallback."""for source, uv_name, pip_name in ((INSTALL_SRC, "Test-UvEnvFlag", "Test-PipEnvFlag"),(SETUP_SRC, "Test-UvEnvFlag", "Test-PipEnvFlag"),@@ -278,8 +273,7 @@ PS1_FILES = sorted(# Matched as text so a new site written the old way fails.OLD_IDIOM = '-notin @("", "0", "false")'-# (Get-Item Env:X).Value throws PropertyNotFoundException under Set-StrictMode 2+ when X is unset;-# -ErrorAction SilentlyContinue does not cover the property access.+# (Get-Item Env:X).Value throws under Set-StrictMode 2+ if unset; -ErrorAction does not help._STRICT_UNSAFE_ENV_READ = re.compile(r"\(\s*Get-Item\s+[\"']?Env:[^)]*\)\s*\.Value")diff --git a/tests/studio/install/test_windows_torch_flavor_invariant.py b/tests/studio/install/test_windows_torch_flavor_invariant.pyindex 7aaf5eaf50f..66cec7e2b18 100644--- a/tests/studio/install/test_windows_torch_flavor_invariant.py+++ b/tests/studio/install/test_windows_torch_flavor_invariant.py@@ -111,8 +111,7 @@ class TestSetupPs1PublishesTheFlavor:assert "if (-not $NoTorchMode) {" in _publication_block()def test_unsetting_does_not_depend_on_the_powershell_version(self):- """Unset with Remove-Item: empty assignment keeps the name on PowerShell 7.5 and deletes it- on 5.1."""+ """Remove-Item unsets; an empty value keeps the name on PS 7.5 but deletes it on 5.1."""block = _publication_block()for name in ("UNSLOTH_EXPECTED_TORCH_TAG",@@ -289,10 +288,9 @@ def _base_total(**flags) -> int:class TestStepTotals:def test_windows_totals_include_torchcodec(self):- # Both carry the Windows-only accelerate repair (8c), which ignores NO_TORCH; the- # no-torch case also gets the runtime-deps slot an update announces separately. Both also- # carry the diffusers main slot (11c), which is spent on every path including opting out.- # causal-conv1d and mamba-ssm have no slot: they install when a model needs them.+ # Both carry the Windows-only accelerate repair (8c), which ignores NO_TORCH; the no-torch+ # case also gets the runtime-deps slot; both carry diffusers main (11c), spent even when+ # opting out; causal-conv1d and mamba-ssm have no slot.assert _base_total(IS_WINDOWS = True) == 18assert _base_total(IS_WINDOWS = True, NO_TORCH = True) == 16@@ -502,9 +500,8 @@ class TestTheProvenanceMarkerSurvivesAResolution:class TestAnUnknownMirrorPinNamesNoFlavor:- """The wheel came from a mirror whose leaf names no family, so nothing downstream can- name one for this venv: not the manifest, which describes the install the mirror- replaced, and not the CUDA probe, which reads the mirror's own leaf back as a flavor."""+ """A mirror whose leaf names no family leaves nothing to name the flavor; the manifest describes+ the replaced install and the CUDA probe reads the leaf as a flavor."""def test_the_expectation_stops_before_the_stale_manifest(self):body = _STACK_SRC[_STACK_SRC.index("def _expected_torch_flavor_tag(") :]diff --git a/tests/studio/install/test_woa_wheelhouse_guard_behaviour.py b/tests/studio/install/test_woa_wheelhouse_guard_behaviour.pyindex 19af8325412..f2d0923d1ba 100644--- a/tests/studio/install/test_woa_wheelhouse_guard_behaviour.py+++ b/tests/studio/install/test_woa_wheelhouse_guard_behaviour.py@@ -224,8 +224,7 @@ def test_a_wheel_taken_from_pypi_is_not_then_excluded_on_arm64():[("0.0.20", True), ("0.0.30", False)],)def test_a_pypi_version_below_a_floor_keeps_the_drop(version, still_dropped):- """xformers carries a floor because the released metadata does, so a PyPI version below- it is not a usable answer and the drop has to stay."""+ """xformers floor mirrors released metadata; a PyPI version below it must stay dropped."""dropped = _dropped_names(f'@{{ "xformers" = @("{version}") }}')assert ("xformers" in dropped) is still_droppeddiff --git a/tests/studio/install/test_woa_wheelhouse_prefers_pypi.py b/tests/studio/install/test_woa_wheelhouse_prefers_pypi.pyindex e4c5d9ce32b..af5035cd1f4 100644--- a/tests/studio/install/test_woa_wheelhouse_prefers_pypi.py+++ b/tests/studio/install/test_woa_wheelhouse_prefers_pypi.py@@ -60,8 +60,7 @@ def test_both_staging_branches_skip_what_pypi_publishes(source):def test_the_guard_is_version_aware(source):- """Published is not enough: upstream behind the wheelhouse means dropping ours- downgrades the install, so the floor is the staged wheel's own version."""+ """Floor PyPI at the staged version; if it lags, dropping ours would downgrade the install."""body = _function_body(source, "Test-WoaWheelhouseWheelIsRedundant")assert "-Floor $fields[1]" in body, "the guard must floor PyPI at the staged version"probe = _function_body(source, "Test-WoaPyPIWheel")@@ -75,8 +74,7 @@ def test_the_guard_only_judges_wheels_this_venv_could_use(source):def test_interpreter_agnostic_wheels_still_count(source):- """hf_transfer ships cp38-abi3 and sqlite_vec py3-none, both usable on cp313: an- exact-tag test would call them foreign and go on shipping ours forever."""+ """abi3/none wheels (hf_transfer, sqlite_vec) are usable; exact-tag tests would miss them."""body = _function_body(source, "Test-WoaWheelTagsUsable")assert '"abi3"' in body and '"none"' in bodyassert '$AbiTag -like "*t"' in body@@ -119,9 +117,8 @@ def test_the_default_is_a_release_download_url_on_this_repo(source):def test_the_release_tag_is_the_one_the_workflow_publishes(source):- """Two places name the tag and nothing joins them: the workflow that uploads the assets- and the installer that downloads them. A rename on one side is a 404 on the other, and- the installer reads that as 'no wheelhouse' and falls back to the emulated x64 stack."""+ """The workflow that uploads the assets and the installer that downloads them name the tag+ separately; a rename is a 404 the installer reads as no wheelhouse."""workflow = (REPO_ROOT / ".github" / "workflows" / "woa-wheelhouse.yml").read_text(encoding = "utf-8")diff --git a/tests/studio/install/woa_ps_harness.py b/tests/studio/install/woa_ps_harness.pyindex 8f6b2f8a760..3c44e5e53f8 100644--- a/tests/studio/install/woa_ps_harness.py+++ b/tests/studio/install/woa_ps_harness.py@@ -49,8 +49,7 @@ def _ps(timeout = 120,**kwargs,):- """Use run_pwsh, not subprocess.run: xdist workers would share one PowerShell startup cache and- crash."""+ """Use run_pwsh, not subprocess.run: xdist workers would share one PowerShell startup cache and crash"""return run_pwsh([PWSH, "-NoProfile", "-NonInteractive", "-Command", script],capture_output = True,diff --git a/tests/studio/playwright_chat_ime_i18n.py b/tests/studio/playwright_chat_ime_i18n.pyindex 6f6f6e414cc..dbd33548921 100644--- a/tests/studio/playwright_chat_ime_i18n.py+++ b/tests/studio/playwright_chat_ime_i18n.py@@ -154,8 +154,7 @@ with sync_playwright() as p:returndef _resolve_deferred_404s() -> None:- """Resolved once at the end because the response event and console error can arrive in- either order."""+ """Runs last: the response event and console error can arrive in either order."""for text, url in deferred_404_console:remaining = unspent_get_404s.get(url, 0)if remaining > 0:diff --git a/tests/studio/playwright_chat_ui.py b/tests/studio/playwright_chat_ui.pyindex d3ee3ae08be..649f6b5409e 100644--- a/tests/studio/playwright_chat_ui.py+++ b/tests/studio/playwright_chat_ui.py@@ -56,8 +56,7 @@ PERMISSION_ONLY = os.environ.get("STUDIO_UI_PERMISSION_ONLY", "0") == "1"PLAYWRIGHT_BROWSER = os.environ.get("STUDIO_PLAYWRIGHT_BROWSER", "chromium").lower()PLAYWRIGHT_CHANNEL = os.environ.get("STUDIO_PLAYWRIGHT_CHANNEL") or None-# Emulates 4 vCPU user boxes; the rapid-submit bug only reproduces at 4x/8x.-# Off unless set, Chromium only.+# Emulates 4 vCPU boxes (rapid-submit bug needs 4x/8x); off unless set, Chromium only.CPU_THROTTLE = float(os.environ.get("STUDIO_UI_CPU_THROTTLE", "0") or 0)FETCH_TIMEOUT_MS = int(os.environ.get("STUDIO_UI_FETCH_TIMEOUT_MS", "30000"))@@ -225,15 +224,9 @@ def wait_for_settled_shell(fallback_budget_s = 30.0,missing_pill_s = 5.0,):- """Return once the composer and its permission pill have stayed up together for settle_s.-- The textarea showing once is not the shell settling. On the Windows lane the shell has been seen to drop to the- full-page route fallback right after the composer painted, while the backend stalled ~5 s warming torch, and stay- there past the next step's 5 s expect. The pill and the textarea render in the same commit, so seeing both once- proves nothing either: they have to stay up. A fallback is waited out for up to fallback_budget_s and then raised- as a boot failure (the caller re-navigates once). A booted shell, composer up and no fallback, that goes- missing_pill_s without the pill raises ShellMissingControl, which the caller must not retry.- """+ """Waits for the composer and pill to stay up together for settle_s; a route fallback is waited+ out up to fallback_budget_s, then raises a boot failure; a booted shell missing the pill for+ missing_pill_s raises ShellMissingControl, which callers must not retry."""pill = page.locator(PERMISSION_PILL).firstfallback = page.get_by_text(ROUTE_FALLBACK_TEXT, exact = True)deadline = time.monotonic() + fallback_budget_s@@ -369,8 +362,7 @@ def exercise_permission_mode_controls(page, shoot):else:route.continue_()- # Wait for the pill, not networkidle: with this page.route networkidle can hang past the watchdog.- # One extra reload only when the app shell never booted.+ # Wait for the pill, not networkidle (it hangs); reload once only if the shell never boots.def _boot_state():try:return page.evaluate(@@ -663,8 +655,7 @@ def open_recent_thread_with_our_prompts()def landed(thread_id, before, before_thread):- """Returns ours, other or None; turns identical to before are stale unless the row was- already open."""+ """Ours, other or None; a turn identical to before is stale unless its row was open."""try:handle = page.wait_for_function("""([threadId, wanted, before, beforeThread]) => {@@ -826,8 +817,7 @@ def exercise_floating_monitor_geometry(page):and box["y"] + box["height"] <= surface["height"] - inset + tolerance)- # Wait for /api/system: until then the panel shows a zero-filled DEFAULT_SYSTEM with no GPU, and- # the VRAM row later adds ~59px, breaking the height baseline.+ # Wait for /api/system; before it, zero-filled defaults, and VRAM later adds ~59px.try:page.wait_for_function(r"""() => {@@ -1771,8 +1761,7 @@ with sync_playwright() as p:info(f"this run's chat: {our_thread_id or 'no thread id on the page'}")# ─────────────────────────────────────────────────────- # 7. Composer toggle buttons. Each aria-label flips between- # "Disable X" / "Enable X" with state (shared-composer.tsx).+ # Toggle aria-labels flip Disable X / Enable X with state (shared-composer.tsx).# ─────────────────────────────────────────────────────step("composer toggle buttons (Thinking / Web search / Tools)")for feature in ("thinking", "web search", "tools"):@@ -2417,16 +2406,9 @@ with sync_playwright() as p:# 17. Persisted monitor auth boundary, then shutdown. Own step: page.evaluate has no timeout here.step("persisted monitor: reset the browser session and open a fresh page")- # Start fresh after the CLI rotation invalidates this browser session.- # Stay in the SAME context: it keeps the init script and costs nothing to reuse.- #- # Nothing here runs script in the OLD page. It is CPU-throttled and its auth was- # just revoked, so the app can be busy retrying, and page.evaluate waits for its- # event loop with no timeout of its own: this step wedged for its whole budget on- # Windows and on the Kaggle T4 runner with no line printed. Closing a page and- # clearing cookies are browser-side calls, and the storage writes go through the- # fresh page parked on a same-origin JSON endpoint where no app code runs. Each call- # announces itself first, so a wedge that remains names the call it sits in.+ # Fresh page after CLI rotation, in the SAME context (keeps the init script); nothing runs in+ # the stale page, whose evaluate can wedge with no timeout; storage writes go via a parked+ # same-origin page; each call announces itself firststale_pages.add(page)info("closing the stale page")try:diff --git a/tests/studio/playwright_data_settings.py b/tests/studio/playwright_data_settings.pyindex 13d8ada5d5c..ac7ac8e2dd6 100644--- a/tests/studio/playwright_data_settings.py+++ b/tests/studio/playwright_data_settings.py@@ -938,10 +938,8 @@ def main():browser = getattr(p, engine).launch(**options)page = browser.new_page(viewport = {"width": 1280, "height": 1000})page.add_init_script(FIXTURE)- # The first load runs Vite's dependency optimizer and transforms the whole module graph- # from a cold cache, and on Windows CI two of these drivers do that at once. Module- # scripts run before DOMContentLoaded, so the default 30s has timed out there on a page- # that then loads fine; allow the same 120s the mount wait below already does.+ # The first load runs Vite's optimizer on a cold cache, two drivers at once on Windows+ # CI, so allow 120s; the default 30s timed out there.page.goto(url, wait_until = "domcontentloaded", timeout = 120_000)page.wait_for_function("!!window.__settingsSmoke", timeout = 120000)output.parent.mkdir(parents = True, exist_ok = True)diff --git a/tests/studio/playwright_declared_polls.py b/tests/studio/playwright_declared_polls.pyindex d789baaae62..8660fdbbc4f 100644--- a/tests/studio/playwright_declared_polls.py+++ b/tests/studio/playwright_declared_polls.py@@ -68,19 +68,14 @@ def api(def normalize(url: str) -> str:- """Path only. The query string is part of the dedup identity in the middleware, but a- poll declares a PATH, and a cursor or cache-buster would otherwise make every hit look- unique and hide the poll entirely."""+ """Path only: the query string is part of the middleware dedup identity, but a poll declares a+ PATH, and a cursor or cache-buster would make every hit look unique, hiding the poll."""return urlsplit(url).pathdef studio_path(url: str, base: str) -> str | None:- """The path of a request this Studio serves, or None for any other origin.-- The budget is about lines in this server's log. The Hub calls huggingface.co straight from- the browser (@huggingface/hub listModels / modelInfo), and Hugging Face's own /api/models- shares a path with nothing here; counted by path alone it read as an undeclared Studio poll.- """+ """Path of a request to this Studio, else None; huggingface.co calls go straight from the+ browser, and counting their /api/models by path read as an undeclared poll."""request, studio = urlsplit(url), urlsplit(base)if (request.scheme, request.netloc) != (studio.scheme, studio.netloc):return Nonediff --git a/tests/studio/playwright_extra_ui.py b/tests/studio/playwright_extra_ui.pyindex 065b88297f9..d9c1847cb44 100644--- a/tests/studio/playwright_extra_ui.py+++ b/tests/studio/playwright_extra_ui.py@@ -699,8 +699,7 @@ with sync_playwright() as p:next_rows_ms = float(WHEEL_ROWS_TIMEOUT_MS)def search_abort_extension() -> tuple:- """Re-bases the search budget onto the in-flight request, counting only requests- made after typing."""+ """Budget rebased onto in-flight search; only requests after typing count."""live = [(at, req) for req, at in hf_inflight.items() if at >= query_typed_at]if not live:return None, 0.0diff --git a/tests/studio/playwright_find_in_page.py b/tests/studio/playwright_find_in_page.pyindex dccb560bb6a..34492b112b1 100644--- a/tests/studio/playwright_find_in_page.py+++ b/tests/studio/playwright_find_in_page.py@@ -127,10 +127,8 @@ COUNTER_MOVED = "prev => { const c = window.__findSmoke.counter(); return !!c &&def settled_counter(page) -> str | None:- """Wait for the typed query to settle and paint, then read its counter.-- The first settled render can still show the previous query's results (the search runs in an- effect after it), so give that effect two more frames to land before reading."""+ """Wait for the query to settle and paint; the first settled render can show the previous+ results, so two more frames let the search effect land."""settle(page, COUNTED)frames(page)frames(page)@@ -1062,8 +1060,7 @@ def run_entry_chunk_delay(browser, engine: str) -> None:loading.wait_for(state = "visible", timeout = 5000)field = loading.locator("input")field.dispatch_event("compositionstart", {"data": "u"})- # Observation window, not a readiness guess: the composition has to hold the loading input- # mounted for the whole entry delay, so the wait spans it.+ # Observation window, not readiness: the input must stay mounted across the entry delay.page.wait_for_timeout(ENTRY_DELAY_MS + 500)check(engine,diff --git a/tests/studio/playwright_heavy_thread.py b/tests/studio/playwright_heavy_thread.pyindex 239c2238f8c..3c3c40df2e8 100644--- a/tests/studio/playwright_heavy_thread.py+++ b/tests/studio/playwright_heavy_thread.py@@ -456,9 +456,8 @@ async (timeoutMs) => {}"""-# Delete is a button on the reply's action bar again since #13615 (#12735 had moved it into the More-# menu). The button is found before the clock starts, so the window holds only what Delete costs: the-# message leaving the thread.+# Delete is an action-bar button again since 13615 (12735 had moved it to the More menu); it is+# found before the clock starts, so the window holds only the message leaving.DELETE_JS = """async (timeoutMs) => {const api = window.__heavyThread;@@ -907,8 +906,7 @@ def run() -> dict:return results-# Every recorded metric must appear here; test_heavy_thread_harness_contract.py enforces it.-# CHROMIUM-ONLY rows say so in their name so `-` does not read as zero.+# CHROMIUM-ONLY rows name it so `-` never reads as zero; all metrics must be listed here.def _action(action: str, key: str):return lambda r: r["actions"][action][key]@@ -1240,8 +1238,7 @@ def print_growth(results: dict, report: dict) -> None:)-# Declared double-rAF count vs what the action reports paying; a lower bound, since extra waits on a-# progressive mount are real application commits.+# Declared double-rAF floor vs reported waits; a lower bound, as extra waits are real commits.FLOOR_COUNTERS = {"reopen ms": ("reopen", "paintWaits")}@@ -1286,8 +1283,7 @@ def floor_declaration_problems(results: dict) -> list[str]:def harness_failures(results: dict, report: dict) -> list[str]:- """Only the ways this harness can be measuring nothing. No performance budgets: see the- module docstring."""+ """Only ways this harness can measure nothing; no performance budgets here."""failures: list[str] = list(floor_declaration_problems(results))for engine in results["engines"]:for size in results["sizes"]:@@ -1340,8 +1336,7 @@ def harness_failures(results: dict, report: dict) -> list[str]:f"{where} rendered {counts['messages']} of {plan['messages']} messages; the ""seed did not land")- # The renderer silently drops some content (e.g. non-PNG/JPEG/GIF/WebP data URLs), so check every- # kind against the per-cycle expectation.+ # Renderer silently drops some data URLs (non-PNG/JPEG/GIF/WebP); check every kind.for key, per_cycle in plan["expectedPerCycle"].items():want = per_cycle * plan["cycles"]if counts.get(key, 0) < want:diff --git a/tests/studio/playwright_image_text_encoder.py b/tests/studio/playwright_image_text_encoder.pyindex 8dd4f430636..f0040c3a66a 100644--- a/tests/studio/playwright_image_text_encoder.py+++ b/tests/studio/playwright_image_text_encoder.py@@ -58,9 +58,8 @@ def main():base_repo = "black-forest-labs/FLUX.2-klein-4B",family = "flux.2-klein",model_kind = "gguf",- # The real status echoes the loaded checkpoint file. Reapply reloads the page's last pick- # only while it still matches what status reports (engine-choice.ts reapplyTarget, #14232),- # so without it nothing reloads.+ # Status echoes the loaded checkpoint; reapplyTarget (engine-choice.ts, 14232)+ # reloads the last pick only while it matches status.gguf_filename = loads[-1].get("gguf_filename"),dtype = "bfloat16",text_encoder_quant = value,diff --git a/tests/studio/playwright_loaded_models_indicator.py b/tests/studio/playwright_loaded_models_indicator.pyindex 194e964c063..e4a6ed3e86a 100644--- a/tests/studio/playwright_loaded_models_indicator.py+++ b/tests/studio/playwright_loaded_models_indicator.py@@ -150,8 +150,7 @@ def chat(**overrides) -> dict:class Runtime:- """Mutable stub state, so a scenario can change what a runtime holds- between polls without tearing the routes down."""+ """Mutable stub state: scenarios change runtime contents between polls without re-routing."""def __init__(self) -> None:self.reset()diff --git a/tests/studio/playwright_mac_tab_capabilities.py b/tests/studio/playwright_mac_tab_capabilities.pyindex 6459c24a2aa..b4a12b3c30a 100644--- a/tests/studio/playwright_mac_tab_capabilities.py+++ b/tests/studio/playwright_mac_tab_capabilities.py@@ -93,8 +93,7 @@ def fail(m: str) -> None:def _transport_kind(err: object) -> str:- """Only ECONNREFUSED proves nothing is bound; any other failure is a stalled listener, not a- dead one."""+ """Only ECONNREFUSED proves nothing is bound; any other failure means a stalled listener."""if isinstance(err, ConnectionRefusedError):return "refused"return "timeout"diff --git a/tests/studio/playwright_memory_estimate.py b/tests/studio/playwright_memory_estimate.pyindex f4e924c1c01..69b37492614 100644--- a/tests/studio/playwright_memory_estimate.py+++ b/tests/studio/playwright_memory_estimate.py@@ -37,8 +37,7 @@ GGUF_REPO = os.environ.get("GGUF_REPO", "unsloth/gemma-3-270m-it-GGUF")GGUF_VARIANT = os.environ.get("GGUF_VARIANT", "UD-Q4_K_XL")# From GGUF_REPO: a family-name hint can match a non-GGUF sibling first, which has no memory row.MODEL_HINT = os.environ.get("STUDIO_MODEL_HINT") or GGUF_REPO.rsplit("/", 1)[-1]-# Typing the value already displayed commits no onChange and no re-price, so choose a value that-# differs from the box at typing time.+# Retyping the shown value fires no onChange or re-price, so pick a different value.CTX_CANDIDATES = [int(part)for part in os.environ.get("STUDIO_CTX_CANDIDATES", "6144,5120,4096,3072,2048,1536").split(",")@@ -438,8 +437,7 @@ with sync_playwright() as p:passdef reveal_on_device_row(popover, hint):- """Bring the row into view without clicking it: a single-quant row loads its- quant on click and closes the picker, taking the gear with it."""+ """Reveal the row unclicked; clicking a single-quant row closes the picker and gear."""od = page.get_by_role("tab", name = "On Device").firstif _count(od):od.click()@@ -570,8 +568,7 @@ with sync_playwright() as p:return Nonedef estimate_button():- """Finds the toggle by role first, which proves a screen reader can reach it; markup is a- fallback."""+ """Role lookup first, proving screen-reader reach; markup text is a fallback."""found = _first_visible(page.get_by_role("button", name = ESTIMATE_LABEL), "role=button")if found is not None:return found@@ -632,8 +629,7 @@ with sync_playwright() as p:since: int,timeout_ms: int = ESTIMATE_WAIT_MS,):- """Reads the recorded transcript rather than expect_request, since the gates check what was- asked."""+ """Reads the recorded transcript, not expect_request, as gates check what was asked."""deadline = time.monotonic() + timeout_ms / 1000while time.monotonic() < deadline:for record in exchanges[since:]:diff --git a/tests/studio/playwright_model_config.py b/tests/studio/playwright_model_config.pyindex 5d09cc85519..be7d5afd8db 100644--- a/tests/studio/playwright_model_config.py+++ b/tests/studio/playwright_model_config.py@@ -134,9 +134,8 @@ def _count(loc) -> int:def _as_int(value) -> int | None:- """Parse an input value to int, tolerating commas/whitespace. Comparisons- must be numeric, never substring: '40960' (a model's native default) would- spuriously "contain" '4096'."""+ """Parses to int, tolerating commas and spaces; comparisons must be numeric, since '40960' would+ spuriously contain '4096'."""if value is None:return Nonetry:@@ -259,8 +258,7 @@ with sync_playwright() as p:# A Load/Reload click is answered only by its /load; a flow stopping short goes quiet for 3 s.label = " ".join((btn.text_content() or "").split())expects_load = label in ("Load model", "Reload model")- # Snapshot after a Playwright call: request events only arrive during one, so a restore /load- # already sent would otherwise count as this click's.+ # Snapshot before clicking, since requests are only seen during Playwright calls.started = _commits["started"]loads_before = len(_commits["loads"])clicked_at = time.monotonic()@@ -362,8 +360,7 @@ with sync_playwright() as p:return [v for v in cfg.values() if isinstance(v, dict)]def entries_for_model(cfg: dict) -> list[dict]:- """Only entries keyed to this model and quant; all entries only if no key has the versioned- shape."""+ """Entries keyed to this model and quant; all entries only if no key is versioned."""want = (_normalize_model_identity(GGUF_REPO), GGUF_VARIANT.strip().lower())recognised = [k for k in cfg if re.match(r"^v\d+:\[", str(k))]if not recognised:@@ -518,8 +515,7 @@ with sync_playwright() as p:GEAR_ANY = 'button[aria-label^="Inference settings for" i]'def diagnose(name, selector):- """Capture a screenshot and JSON state on a miss, since a log line alone hides what was on- screen."""+ """Screenshot and JSON state on a miss, since a log line hides what was on screen."""rows = []try:opts = page.locator("[data-model-picker-option]")@@ -979,8 +975,7 @@ with sync_playwright() as p:_seed_marks = [0]def seed_legacy_for_next_document(seed: dict, *, wipe_migrated: bool) -> None:- """Seed via an init script on the next document; seeding the live page races its server- write-back."""+ """Seed via init script on the next document; seeding live races the server write-back."""_seed_marks[0] += 1mark = f"__ui_modelcfg_seed_{_seed_marks[0]}"page.add_init_script(@@ -1001,8 +996,7 @@ with sync_playwright() as p:)def clear_server_overrides_for_model() -> None:- """Also delete the server override rows: opening the panel writes them back over the- migrated value."""+ """Also clear server overrides, else the panel writes them over the migrated value."""# Normalise model and quant separately: normalizeModelIdentity keeps a POSIX path's case.want_model = _normalize_model_identity(GGUF_REPO)want_quant = GGUF_VARIANT.strip().lower()@@ -1017,8 +1011,7 @@ with sync_playwright() as p:)def rows_for_model() -> list[str] | None:- """Override rows for this model, or None when the read failed; a failed fetch is not an- empty list."""+ """Override rows for this model; None on a failed read, never an empty list."""resp = evaluate_fetch(page,f"{BASE}/api/settings/openai-auto-switch/overrides",@@ -1188,8 +1181,7 @@ with sync_playwright() as p:soft_fail(f"migration idempotency check errored: {e}")# ─────────────────────────────────────────────────────- # 6. Hub Run keeps its run settings on a page loaded at /hub (HARD).- # Run mounts Chat there, and the new composer's autofocus used to dismiss them.+ # Hub Run settings must survive on a /hub page; composer autofocus once dismissed them.# ─────────────────────────────────────────────────────step("Hub Run opens run settings on a page loaded at /hub")try:diff --git a/tests/studio/playwright_nonmodal_menus.py b/tests/studio/playwright_nonmodal_menus.pyindex 26e05971fee..afd836d37c9 100644--- a/tests/studio/playwright_nonmodal_menus.py+++ b/tests/studio/playwright_nonmodal_menus.py@@ -74,9 +74,8 @@ def until(arg = None,timeout: int = 5000,) -> None:- """Wait until `condition` holds, without failing here: a broken build spends the timeout and- then fails on the SAME check below with the same message. Replaces flat sleeps, which asserted- the runner's speed along with the behaviour."""+ """Wait until `condition` holds without failing here, since a broken build then fails the same+ check below; replaces flat sleeps that also asserted runner speed."""try:page.wait_for_function(condition, arg = arg, timeout = timeout)except PlaywrightTimeout:@@ -359,9 +358,8 @@ def check_keyboard(page, checks: Checks) -> None:page.get_by_label("Row options 2", exact = True).focus()frames(page)page.keyboard.press("Enter")- # Kept as a flat wait on purpose: a keyboard-opened menu drops an ArrowDown pressed right- # after it opens, even with its first item focused and its open animation finished (measured;- # no DOM state marks when it starts taking arrows), so there is no event to wait on here.+ # Flat wait on purpose: a keyboard-opened menu drops an ArrowDown pressed right after opening,+ # even when focused and animated; no DOM state marks readiness.page.wait_for_timeout(300)checks.record("Enter opens the menu", menus_open(page) >= 1)page.keyboard.press("ArrowDown")@@ -435,8 +433,7 @@ def check_lifetime(page, checks: Checks) -> None:" l.scrollTop = 8 * 40 - l.clientHeight + 20; }")frames(page)- # Press the sliver the scroller leaves visible. Not click_forced: that scrolls the- # trigger into view first, which is the one thing this case must not do.+ # Press the visible sliver; not click_forced, which scrolls the trigger into view.trigger = page.get_by_label("Row options 8", exact = True).bounding_box()clip = page.locator("#list").bounding_box()top = max(trigger["y"], clip["y"])diff --git a/tests/studio/playwright_pinned_chat_persistence.py b/tests/studio/playwright_pinned_chat_persistence.pyindex d3558fc5077..f1af1060ade 100644--- a/tests/studio/playwright_pinned_chat_persistence.py+++ b/tests/studio/playwright_pinned_chat_persistence.py@@ -87,8 +87,7 @@ window.ready = true;def settings_client(home: Path):- # Import the actual route file without importing routes/__init__.py, whose- # application-wide registry eagerly loads unrelated training dependencies.+ # Import the route file, not routes/__init__.py, which eagerly loads training deps.os.environ["UNSLOTH_STUDIO_HOME"] = str(home)os.environ["UNSLOTH_STUDIO_DISABLE_DEVICE_PROBE"] = "1"sys.path.insert(0, str(BACKEND))@@ -206,8 +205,7 @@ async def exercise_browser(url: str, client) -> list[str]:await page.route("**/api/chat/settings**", serve)await page.route("**/api/chat/pins**", serve)page.on("pageerror", lambda error: errors.append(str(error)))- # Supported older WebKit versions lack these static helpers.- # Keep every lifecycle scenario on that API feature floor.+ # Older WebKit lacks these helpers; lifecycle scenarios stay at that API floor.await page.add_init_script("""Object.defineProperty(AbortSignal, 'any', {value: undefined, configurable: true});Object.defineProperty(AbortSignal, 'timeout', {value: undefined, configurable: true});@@ -286,8 +284,7 @@ async def exercise_browser(url: str, client) -> list[str]:assert server_pins() == expectedpassed.append("queued pin and unpin survive reload")- # A component cleanup is not itself a session change (StrictMode- # and remounts also run it), so an unconfirmed edit must survive.+ # Unmount cleanup is not a session change; unconfirmed edits must survive remounts.await delay_focus_read(page, state)await page.evaluate("window.pins.usePinnedChatsStore.getState().togglePin('survives-remount'); window.unmountSync()"@@ -326,8 +323,7 @@ async def exercise_browser(url: str, client) -> list[str]:)passed.append("focus refresh synchronizes isolated browser clients")- # Same-origin session changes use storage events instead of the- # in-document auth events emitted by clearAuthTokens.+ # Same-origin changes use storage events, not clearAuthTokens' in-document events.sibling = await context.new_page()await sibling.goto(url)await sibling.wait_for_function("window.ready === true")@@ -345,8 +341,7 @@ async def exercise_browser(url: str, client) -> list[str]:)passed.append("cross-tab session changes reset and rehydrate pins")- # A supported old backend initially preserves local pins. Once it- # is upgraded, the open page must resume shared persistence.+ # Old backend keeps local pins; after an upgrade the page must resume shared sync._, compatible, compatibility = await new_client(legacy = ["local-before-upgrade"], old_backend = True, missing_route_status = 405)@@ -361,9 +356,8 @@ async def exercise_browser(url: str, client) -> list[str]:assert "after-server-upgrade" in server_pins()passed.append("old-server fallback resumes synchronization after upgrade")- # Downgrading after reading server pins must preserve that baseline.- # Keep explicit local changes across reload, then replay against the- # upgraded server's newer list without replacing another client edit.+ # Downgrade after reading server pins must preserve that baseline; local changes survive+ # reload and replay onto the newer list without replacing other edits.save_server_pins(["downgrade-a", "downgrade-b"])_, downgraded, downgrade = await new_client()await mount(downgraded)@@ -392,9 +386,8 @@ async def exercise_browser(url: str, client) -> list[str]:"downgrade preserves server pins and reload replays ordered offline changes after upgrade")- # Browser pin migration can beat the independent legacy thread- # import. Retry the original IDs after import, while tombstones keep- # an explicit unpin from being undone by later refreshes or reloads.+ # Browser pin migration can beat the legacy thread import; retry original IDs after+ # import, and tombstones keep an explicit unpin from being undone.save_server_pins([])_, delayed_import, _ = await new_client(legacy = ["legacy-imported-later"])await mount(delayed_import)@@ -430,9 +423,8 @@ async def exercise_browser(url: str, client) -> list[str]:"legacy pins migrate after delayed thread import and explicit unpins do not resurrect")- # Pre-session-mark auth storage must gain a stable scope before a- # durable intent is saved. Hourly token rotation preserves that- # scope, including while navigation interrupts a pending request.+ # Auth storage needs a stable scope before a durable intent is saved; hourly token+ # rotation keeps it._, old_auth, old_auth_state = await new_client()await old_auth.evaluate("localStorage.removeItem('unsloth_auth_session_mark')")await mount(old_auth)diff --git a/tests/studio/playwright_research_freeze.py b/tests/studio/playwright_research_freeze.pyindex 977ecac4d5b..8f3944ae6e9 100644--- a/tests/studio/playwright_research_freeze.py+++ b/tests/studio/playwright_research_freeze.py@@ -310,8 +310,7 @@ def run() -> dict:"click_after_close": clicks_after_close > clicks_after_approve,}- # 5. Detaching: a still-pending follow step used to reconcile isAtBottom back to true after a- # small upward flick.+ # A pending follow step must not flip isAtBottom to true after a small upward flick.page.evaluate("window.__research.openPanel()")until(page, f"() => Boolean(document.querySelector('{SCROLLER}'))")frames(page)diff --git a/tests/studio/playwright_settings_tabs.py b/tests/studio/playwright_settings_tabs.pyindex 446f6c4f5e4..fead9d9859f 100644--- a/tests/studio/playwright_settings_tabs.py+++ b/tests/studio/playwright_settings_tabs.py@@ -458,9 +458,7 @@ def run_keystroke_search(page) -> None:toggle = page.locator(f"{PANEL} button[aria-pressed]")click_forced(toggle, timeout = 15000)until(page, "el => el?.getAttribute('aria-pressed') === 'true'", arg = toggle.element_handle())- # Mod is Cmd on macOS and Ctrl everywhere else, and bindingFromEvent drops a Meta- # chord off macOS outright, so a hardcoded Meta would record nothing on the Linux- # runner. Same read as isMacPlatform(), which is what the app itself goes by.+ # bindingFromEvent drops Meta chords off macOS, so a hardcoded Meta records nothing on Linux.mac = page.evaluate("() => /mac|iphone|ipad|ipod/i.test(`${navigator.platform} ${navigator.userAgent}`)")diff --git a/tests/studio/playwright_thread_weight.py b/tests/studio/playwright_thread_weight.pyindex 0a578f6b9e6..1d0a9166538 100644--- a/tests/studio/playwright_thread_weight.py+++ b/tests/studio/playwright_thread_weight.py@@ -238,9 +238,7 @@ async (timeoutMs) => {}"""-# Delete is a button on the reply's action bar again since #13615 (#12735 had moved it into the More-# menu). The button is found before the clock starts, so the window holds only what Delete costs: the-# message leaving the thread.+# Delete is back on the reply action bar (PR/issue 13615); find the button before the clock starts.DELETE_JS = """async (timeoutMs) => {const api = window.__threadWeight;@@ -605,8 +603,7 @@ GROWTH_AXES = (def harness_failures(results: dict) -> list[str]:- """Only the ways this harness can be measuring nothing. No performance budgets: see the- module docstring."""+ """Ways this harness can measure nothing; no performance budgets (see module docstring)."""failures: list[str] = []layers = set()for size in results["sizes"]:diff --git a/tests/studio/playwright_tool_activity.py b/tests/studio/playwright_tool_activity.pyindex 69cdc475f5e..bff53a54179 100644--- a/tests/studio/playwright_tool_activity.py+++ b/tests/studio/playwright_tool_activity.py@@ -314,8 +314,7 @@ def run(base_url: str, pw) -> dict:if scene["uncontrolled"]["aria_expanded"] != "false":p.append("11: the uncontrolled card did not converge after 40 preference flips")- # --- 12 storage denied -------------------------------------------------- # Safari private browsing and blocked cookies make localStorage throw.+ # Storage denied: Safari private browsing and blocked cookies make localStorage throw.denied = browser.new_context(viewport = {"width": 1200, "height": 900})denied.add_init_script("""() => {diff --git a/tests/studio/playwright_update_banner_layout.py b/tests/studio/playwright_update_banner_layout.pyindex ec515a8737e..00fe09fb7c9 100644--- a/tests/studio/playwright_update_banner_layout.py+++ b/tests/studio/playwright_update_banner_layout.py@@ -376,8 +376,7 @@ RESTORE_CYCLES = [((320, 400), (1920, 1080)), ((320, 400), (900, 600))]SCOPE = os.environ.get("STUDIO_UI_BANNER_SCOPE", "full").lower()SPOT = SCOPE == "spot"-# At the 20px font size below 384px the action row wraps; 320x480 has a rail cap between the two-# card heights, which is what clipped Copy command.+# At 20px font below 384px the action row wraps; the 320x480 rail cap clipped Copy command.FONT_SCALE_VIEWPORTS = [(921, 534), (390, 500), (320, 480)]# Mirrors appearance-custom-store.ts; kept in step by test_update_release_notes.py.UI_FONT_SIZE_MAX = 20@@ -1148,8 +1147,7 @@ def main() -> int:# add_init_script takes raw source, not a function to call.seed_js = ("(() => {"- # Shortens the 5s update-check timer only in this page, but keeps it a timer so the late-mount- # reflow is still exercised.+ # Shortens update timer here only; still a timer, so the late-mount reflow runs.f" window.{E2E_DELAY_GLOBAL} = {E2E_DELAY_MS};"f" localStorage.setItem('unsloth_auth_token', {json.dumps(session['access_token'])});"f" localStorage.setItem('unsloth_refresh_token', {json.dumps(session.get('refresh_token', ''))});"diff --git a/tests/studio/probe_dismiss_guard.py b/tests/studio/probe_dismiss_guard.pyindex e1d3415c75b..90f898b4bd7 100644--- a/tests/studio/probe_dismiss_guard.py+++ b/tests/studio/probe_dismiss_guard.py@@ -246,8 +246,7 @@ async def one_case() -> dict:"""Open the menu, attack the Copy button one way, report whether the click reached it."""await hover_last_assistant(page)- # Positive control: a direct click with no menu open must be counted, or a zero below would- # mean only that the counter cannot see clicks.+ # Control: a click with no menu open must register, else zero means a blind counter.control = await page.evaluate(FACTS_JS)if not control["targetRect"]:return {"case": case, "error": "no Copy button"}@@ -349,10 +348,8 @@ async def one_case(before_space = await page.evaluate(FOCUS_FACTS_JS)await page.keyboard.press("Space")elif case == "dismiss_on_composer":- # Dismissing into the composer must preserve its caret. The click has to land on the- # composer itself: since #13615 the shorter More menu can open over the composer's middle,- # and a click there is a click IN the menu, which rightly does not dismiss it. So the spot- # is the first point across the composer's midline that hit-tests to the composer.+ # Dismissing into the composer must preserve its caret; the click must land on the composer,+ # not the menu, since PR/issue 13615 the menu can open over its middle.spot = await page.evaluate("""() => {const c = window.__heavyThread.composer();@@ -554,10 +551,8 @@ async def one_case(else:return {"case": case, "error": f"unknown case {case}"}- # Wait for the menu's exit rather than a flat 1500 ms: same bound, but it returns as soon as- # the menu is gone. A case that leaves it open on purpose (Space reopening it) still waits the- # whole bound. Then a short observation window, because the verdict is mostly "no click- # reached Copy", and a click a touch gesture synthesizes can land after the menu has closed.+ # Wait for the menu to close (1500 ms bound), then 300 ms: a touch click can land after it+ # closes.await until(page, MENU_CLOSED, 1500)await page.wait_for_timeout(300)after = await page.evaluate(FACTS_JS)diff --git a/tests/studio/reasoning-codex-checks.js b/tests/studio/reasoning-codex-checks.jsindex 11cae04d41e..97b7d0a64bd 100644--- a/tests/studio/reasoning-codex-checks.js+++ b/tests/studio/reasoning-codex-checks.js@@ -19,8 +19,7 @@ async (page) => {await page.setViewportSize({ width: 1280, height: 900 });await page.waitForFunction(() => window.__reasoning);await page.evaluate(() => window.__reasoning.run({ size: 250000, kind: "code", chunk: 512, gap: 12 }));- // The options are the THIRD argument; in second place they are the page function's arg and the- // 60 s timeout was silently ignored (default 30 s).+ // Options are the THIRD arg; in second place the 60 s timeout is silently ignored.await page.waitForFunction(() => window.__reasoning.stats().done, null, { timeout: 60000 });await page.waitForTimeout(400);const streaming = await page.evaluate(() => ({ ...window.__reasoning.stats(), transfers: window.__fenceTransfers }));diff --git a/tests/studio/studiobench/__main__.py b/tests/studio/studiobench/__main__.pyindex 4858a767b98..8af378e1ce7 100644--- a/tests/studio/studiobench/__main__.py+++ b/tests/studio/studiobench/__main__.py@@ -665,8 +665,7 @@ def _run_holding_out_dir(args, ab_ref, specs, arm_labels, windowed, paths, out_ltime.sleep(1.0)procs = new_roots(os.getpid(), procs_before)- # Init scripts carry the access token and re-run on every navigation, so the seed script defers- # to the later `exp` after a re-mint.+ # Init scripts carry the token and re-run per navigation; seed defers to later `exp`.for side in sides:side["auth"].on_rotate = lambda auth_now, side = side: bundle.context.add_init_script(side["seed_script"](auth_now)diff --git a/tests/studio/studiobench/analysis/__init__.py b/tests/studio/studiobench/analysis/__init__.pyindex dda64d73744..8ea8d322960 100644--- a/tests/studio/studiobench/analysis/__init__.py+++ b/tests/studio/studiobench/analysis/__init__.py@@ -22,8 +22,7 @@ __all__ = [class CellFailure(RuntimeError):- """Raised, never downgraded to a smaller number, since a truncated trace reads as the thing- never ran."""+ """Raised, never downgraded: a truncated trace reads as if the thing never ran."""def __init__(self, gate: str, detail: str) -> None:super().__init__(f"{gate}: {detail}")@@ -40,8 +39,7 @@ def measured(key: str, value: Any) -> dict:def unmeasured(key: str, reason: str) -> dict:- """Emits None, never 0; the required reason tells a missing mechanism apart from a missing- instrument."""+ """Emits None, never 0; the reason tells a missing mechanism from a missing instrument."""if not reason:raise ValueError(f"unmeasured({key!r}) requires a reason")return {key: None, f"{key}_attempted": False, f"{key}_reason": reason}diff --git a/tests/studio/studiobench/analysis/cpuprofile.py b/tests/studio/studiobench/analysis/cpuprofile.pyindex 0ed10997f66..75f80360169 100644--- a/tests/studio/studiobench/analysis/cpuprofile.py+++ b/tests/studio/studiobench/analysis/cpuprofile.py@@ -31,8 +31,7 @@ class CallFrame:@propertydef key(self) -> tuple[str, str, int, int]:- """Keyed on script id and source position, not name, which is often empty or collides when- minified."""+ """Keyed by script id and position: names are often empty or collide once minified."""return (self.function_name, self.script_id, self.line, self.column)@property@@ -79,16 +78,14 @@ class CpuProfile:return self.start_time - self.declared_start_timedef stack_for_sample_trace_id(self, sample_trace_id: int | str) -> list[CallFrame]:- """Exact stack of a tagged event via sampleTraceId, with none of the sampling error of short- windows."""+ """Exact stack of a sampleTraceId-tagged event: no sampling error of short windows."""node = self.trace_ids.get(str(sample_trace_id))if node is None:return []return self.stack(node)def stack(self, node_id: int) -> list[CallFrame]:- """Stops at a repeated node: a corrupt trace can hold a cyclic parent chain that hangs the- analysis."""+ """Stops at a repeated node; a corrupt trace's cyclic parent chain would hang it."""out: list[CallFrame] = []seen: set[int] = set()cur: int | None = node_id@@ -151,8 +148,7 @@ class CpuProfile:return Nonedef assert_deltas_match_wall(self, tolerance: float = DELTA_WALL_TOLERANCE) -> dict[str, Any]:- """Deltas must sum to the profiled wall span; if not, every self time is off by an unknown- factor."""+ """Deltas must sum to the wall span, or every self time is off by an unknown factor."""if not self.samples:raise CellFailure("cpuprofile_empty", "profile contained no samples")delta_sum = sum(s.delta for s in self.samples)diff --git a/tests/studio/studiobench/analysis/parity.py b/tests/studio/studiobench/analysis/parity.pyindex 5836bc306ff..890b7c20510 100644--- a/tests/studio/studiobench/analysis/parity.py+++ b/tests/studio/studiobench/analysis/parity.py@@ -8,8 +8,7 @@ from __future__ import annotationsimport collectionsfrom typing import Any, Iterable, Optional-# The digest walks the thread only, so MATCH means no thread-structure change was detected, not-# that the UI is unchanged.+# The digest walks only the thread: MATCH means no structure change, not an unchanged UI.MATCH = "match"DIFFER = "differ"NOT_COMPARABLE = "not_comparable"@@ -52,8 +51,7 @@ UNSTABLE_ACTIONS: dict[str, str] = {}-# Actions whose ability to run is a race, keyed on the not_run reason: a treatment that removes a-# control must still be caught.+# Racy actions key on the not_run reason; a treatment removing a control must still be caught.RACY_EXECUTION: dict[str, tuple[str, tuple[str, ...]]] = {"stop_generation": ("needs a live stream to stop, and returns not_run when nothing was generating and a new "@@ -678,8 +676,7 @@ def derive_unstable(def cross_check(derived: dict[str, dict], declared: Iterable[str]) -> dict[str, list[str]]:- """Reports both directions of mismatch between derived and declared unstable lists; each is a- finding."""+ """Reports mismatches both ways, derived vs declared unstable lists; each is a finding."""declared = set(declared)unstable = {a for a, r in derived.items() if r["unstable"]}undetermined = {a for a, r in derived.items() if r["undetermined"]}@@ -694,8 +691,7 @@ def cross_check(derived: dict[str, dict], declared: Iterable[str]) -> dict[str,def mutation_detected(before: dict, after: dict) -> dict:- """Uses the same compare() as production, so the mutation check tests the real comparison, not a- copy."""+ """Uses production compare(), so the mutation check tests the real comparison, not a copy."""result = compare(before, after)result["detected"] = result["verdict"] == DIFFERreturn resultdiff --git a/tests/studio/studiobench/analysis/selftest/test_studiobench_scroll_bounds.py b/tests/studio/studiobench/analysis/selftest/test_studiobench_scroll_bounds.pyindex 43db31d1811..dc68d140258 100644--- a/tests/studio/studiobench/analysis/selftest/test_studiobench_scroll_bounds.py+++ b/tests/studio/studiobench/analysis/selftest/test_studiobench_scroll_bounds.py@@ -108,9 +108,7 @@ def test_the_extent_is_reconstructed_so_both_checks_answer_about_one_scrollbar()def test_a_payload_with_no_client_height_falls_back_and_says_so():- """A row from a checkout that predates the field, or one whose census failed. It compares- `bottom` as before rather than refusing, and the detail names which of the two it compared so- the tighter effective allowance is not silent."""+ """No client height (old checkout or failed census): compares `bottom`, and the detail says so."""base = _scroll_row(18, bottom = 9_200)treat = _scroll_row(6, bottom = 9_100)checks = {c["invariant"]: c for c in B.compare_behaviour(base, treat)["checks"]}@@ -222,9 +220,7 @@ def test_the_ceiling_and_the_extent_check_enforce_one_tolerance_on_one_quantity(def test_an_arm_with_no_extent_does_not_borrow_its_partners_ceiling():- """The degradation stays a degradation. Bounding an arm this check has always left unbounded- above is the one direction that could INVENT a red rather than retire one, so an arm carrying- no extent of its own still gets the lower bound alone and says so."""+ """An arm with no extent gets the lower bound alone and says so; a ceiling could INVENT a red."""base = _scroll_row(18, fraction = 1.0, bottom = 9_200, client = 800)treat = _scroll_row(6, fraction = 2.0, bottom = None, client = 800)treat["census"]["viewport_scroll_height"] = None@@ -243,8 +239,7 @@ def test_the_lower_bound_still_catches_a_gesture_that_was_snapped_back():def test_a_row_with_no_extent_gets_the_lower_bound_and_no_ceiling():- """Degrades to no ceiling rather than to a guess. A ceiling of zero would fail every correct- arm; the row says which of the two it applied."""+ """Degrades to no ceiling, not a guess: a zero ceiling would fail every correct arm."""base = _scroll_row(18, fraction = 1.0, bottom = 9_200, client = 800)treat = _scroll_row(6, fraction = 2.0, bottom = 9_200, client = 800)del treat["expect"]["bottom"]diff --git a/tests/studio/studiobench/analysis/selftest/test_studiobench_visible_parity.py b/tests/studio/studiobench/analysis/selftest/test_studiobench_visible_parity.pyindex f13e850a083..1fbcb8e263c 100644--- a/tests/studio/studiobench/analysis/selftest/test_studiobench_visible_parity.py+++ b/tests/studio/studiobench/analysis/selftest/test_studiobench_visible_parity.py@@ -48,18 +48,14 @@ def test_a_difference_inside_the_viewport_still_fails():def test_showing_different_messages_is_itself_a_visible_difference():- """Two arms whose viewports held different parts of the conversation did not show the user the- same thing, whatever the digests of the overlap say. This is the case a naive intersection- would silently skip by comparing only the ordinals both arms happen to have."""+ """Different messages on screen differ visibly even when overlap digests match."""got = P.compare_visible(_cap({14: "a", 15: "b"}), _cap({15: "b", 16: "c"}))assert got["verdict"] == P.DIFFERassert "DIFFERENT MESSAGES on screen" in got["reason"]def test_a_windowed_arm_and_a_full_arm_are_compared_by_thread_position():- """The reason this mode works where the digest does not. The base has the whole thread mounted- and the treatment has a window of it, so mounted INDEX 0 is a different message on the two- arms. Keyed by thread ordinal, the messages that were actually on screen line up."""+ """Keyed by thread ordinal, not mounted index, so a windowed and a full arm line up on screen."""base = _cap({16: "p", 17: "q", 18: "r"})treat = _cap({16: "p", 17: "q", 18: "r"})assert P.compare_visible(base, treat)["verdict"] == P.MATCH@@ -88,8 +84,7 @@ def test_a_missing_capture_is_refused_rather_than_assumed_empty():def test_a_message_seen_mid_action_but_unmounted_by_capture_is_not_counted_as_agreement():- """A message seen mid-action but unmounted by capture is not agreement; the verdict is NOT- COMPARABLE."""+ """Mid-action messages unmounted at capture are not agreement; verdict is NOT COMPARABLE."""base = _cap({14: "a"}, ever = [3, 14])treat = _cap({14: "a"}, ever = [3, 14])got = P.compare_visible(base, treat)@@ -101,9 +96,7 @@ def test_a_message_seen_mid_action_but_unmounted_by_capture_is_not_counted_as_agdef test_the_messages_that_could_be_digested_agreeing_is_not_the_claim_this_mode_makes():- """The residue is one ordinal out of six, so five messages were compared and all five agreed.- That is a real observation and it is not the printed claim, which is about every message the- viewport showed. The reason says which ordinal went uncompared so the reader can decide."""+ """Five of six messages agreed is a real observation, not the claim about every message shown."""seen = {10: "a", 11: "b", 12: "c", 13: "d", 14: "e"}got = P.compare_visible(_cap(seen, ever = [3, *seen]), _cap(seen, ever = [3, *seen]))assert got["verdict"] == P.NOT_COMPARABLE, gotdiff --git a/tests/studio/studiobench/analysis/symbols.py b/tests/studio/studiobench/analysis/symbols.pyindex 4765d02e922..80975c5dd65 100644--- a/tests/studio/studiobench/analysis/symbols.py+++ b/tests/studio/studiobench/analysis/symbols.py@@ -20,8 +20,7 @@ NOT_BUILT = "not_built"# Low-count functions collide with everything; excluded and reported.MIN_INFORMATIVE_COUNT = 2-# Some identity is expected (React leaves scheduler entry points unminified): ~0.1 for a real-# pair against 1.0 for a same-build pair.+# React leaves scheduler entry points unminified: ~0.1 for a real pair vs 1.0 for same-build.MAX_IDENTITY_MAPPING_FRACTION = 0.5# Function-name length cannot detect a development build (medians were equal); checks are structural.diff --git a/tests/studio/studiobench/analysis/traceparse.py b/tests/studio/studiobench/analysis/traceparse.pyindex 09c77151e52..7c94f736c69 100644--- a/tests/studio/studiobench/analysis/traceparse.py+++ b/tests/studio/studiobench/analysis/traceparse.py@@ -44,8 +44,7 @@ class Task:@propertydef self_dur(self) -> int:- """Clamped at zero: a child longer than its parent in a malformed trace would make self time- negative."""+ """Clamped at zero so a malformed trace, child longer than parent, cannot go negative."""return max(0, self.dur - sum(c.dur for c in self.children))def walk(self) -> Iterator["Task"]:@@ -102,8 +101,7 @@ class Trace:@classmethoddef from_json_text(cls, text: str) -> "Trace":- """Tracing emits an object with traceEvents; DevTools-saved traces are bare arrays, so both- parse."""+ """Accepts a traceEvents object or a bare array (DevTools-saved traces)."""text = text.strip()if not text:raise CellFailure("trace_empty", "trace stream contained no bytes")diff --git a/tests/studio/studiobench/arms/content_visibility_probe.js b/tests/studio/studiobench/arms/content_visibility_probe.jsindex d1d11751ddf..774210baafa 100644--- a/tests/studio/studiobench/arms/content_visibility_probe.js+++ b/tests/studio/studiobench/arms/content_visibility_probe.js@@ -228,8 +228,7 @@var r = rect(el);if (r) {heights.push(Math.round(r.height));- /* Mutually exclusive buckets; the fallback wins ties so a root behaving as declared- * is not charged to the trap. */+ /* Exclusive buckets; ties go to fallback, so a root as declared is not the trap. *//* Only while skipped: size containment applies only then. */var px = ROLE_PX[roleOf(el)];if (cv === "auto" && px && skippedState(el) === true) {diff --git a/tests/studio/studiobench/arms/manifest.py b/tests/studio/studiobench/arms/manifest.pyindex 28b01261f29..6a5b3c7acbf 100644--- a/tests/studio/studiobench/arms/manifest.py+++ b/tests/studio/studiobench/arms/manifest.py@@ -139,8 +139,7 @@ class ArmOutcome:return self.status in (ArmStatus.QUOTED, ArmStatus.BOUND)def quote(self) -> str:- """DOM-changing arms print as a bound, since their cost includes whatever else the change- altered."""+ """DOM-changing arms print a bound: cost includes whatever else the change altered."""if self.status is ArmStatus.QUOTED:return self.cost.display()diff --git a/tests/studio/studiobench/arms/selftest/test_studiobench_probe_hooks.py b/tests/studio/studiobench/arms/selftest/test_studiobench_probe_hooks.pyindex 04ccc5d0fe5..219b87a5761 100644--- a/tests/studio/studiobench/arms/selftest/test_studiobench_probe_hooks.py+++ b/tests/studio/studiobench/arms/selftest/test_studiobench_probe_hooks.py@@ -63,8 +63,7 @@ def test_the_probe_path_is_validated_before_anything_is_started(main_src: str):assert read_at < main_src.index("_probe_init_scripts(extra_init, extra_init_source)")assert "except (OSError, UnicodeDecodeError) as exc:" in main_srcassert main_src.count("Path(extra_init).read_text") == 1- # Also ahead of the archive, which moves the payload aside; behaviour is pinned in- # runtime/selftest/test_studiobench_run_acquisition.py.+ # Also ahead of the archive; see runtime/selftest/test_studiobench_run_acquisition.py.assert read_at < main_src.index("prepare_payload(")diff --git a/tests/studio/studiobench/attribution/vite.studiobench.config.ts b/tests/studio/studiobench/attribution/vite.studiobench.config.tsindex b3fbdcb4a28..0c0329c6d39 100644--- a/tests/studio/studiobench/attribution/vite.studiobench.config.ts+++ b/tests/studio/studiobench/attribution/vite.studiobench.config.ts@@ -10,8 +10,7 @@ import { previewRuntime } from "../../../../studio/frontend/vite-preview-runtimeconst FRONTEND_ROOT = path.resolve(__dirname, "../../../../studio/frontend");-// Resolve plugins from the frontend package: Vite loads this config from its own dir,-// where no node_modules exists up the tree.+// Plugins resolve from the frontend package; Vite's config dir has no node_modules above it.const requireFromFrontend = createRequire(path.join(FRONTEND_ROOT, "package.json"));const tailwindcss = requireFromFrontend("@tailwindcss/vite").default;const react = requireFromFrontend("@vitejs/plugin-react").default;@@ -20,8 +19,7 @@ const { defineConfig } = requireFromFrontend("vite");export default defineConfig({root: FRONTEND_ROOT,plugins: [react(), tailwindcss(), previewRuntime()],- // Keep an unrelated PostCSS config in an ancestor directory from leaking into Unsloth installs.- // Tailwind is provided by its dedicated Vite plugin.+ // Blocks an ancestor PostCSS config from leaking in; Tailwind uses its own Vite plugin.css: {postcss: {plugins: [],diff --git a/tests/studio/studiobench/fixture/corpus.py b/tests/studio/studiobench/fixture/corpus.pyindex 4760c098c8c..e1e79e8698e 100644--- a/tests/studio/studiobench/fixture/corpus.py+++ b/tests/studio/studiobench/fixture/corpus.py@@ -202,8 +202,7 @@ class Unit:}def clipped_to(self, chars: int) -> "Unit":- """Clips on block boundaries so no fence is left unclosed, which would take a different- render path."""+ """Clip on block boundaries: an unclosed fence would take a different render path."""if chars >= self.chars:return self@@ -734,12 +733,7 @@ def dollarise(text: str, salt: str) -> str:def _too_small(rung: str, chars_per_token: float, last_index: int, what: str) -> ValueError:- """The one message for every way a rung can outgrow the frozen corpus.-- Deliberately an ERROR and not a clamp. The clamp it replaces is how a 1M rung came to stream- the same unit three times and report the cheapest per-character cost on the ladder, and a- benchmark that quietly measures something smaller than it says is worse than one that stops.- """+ """Every rung outgrowing the frozen corpus raises this error, not a clamp that measures less quietly."""return ValueError(f"the frozen corpus is too small for the {rung} rung at {chars_per_token} chars per "f"token: {what} runs past the manifest, which ends at index {last_index}. Re-freeze with "diff --git a/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_streamed.py b/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_streamed.pyindex 02de344b73c..e1c97d80d83 100644--- a/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_streamed.py+++ b/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_streamed.py@@ -451,8 +451,7 @@ def test_a_message_that_vanished_is_never_excused_by_being_in_flight():def test_a_running_reply_the_probe_could_not_place_refuses_the_pair():- """A running reply the probe cannot place refuses the pair, rather than reading as no reply in- flight."""+ """An unplaceable running reply refuses the pair rather than reading as idle."""a = streaming_arm(24)blind = dict(streaming_arm(24), in_flight = [], in_flight_unplaced = True)got = P.compare(a, blind)@@ -536,9 +535,7 @@ def test_the_blind_scaffold_rule_needs_run_state_evidence_the_composer_cannot_fodef test_the_blind_scaffold_rule_still_withholds_a_corroborated_run_state_difference():- """THE CONTROL. When the run state independently says one arm was generating and the other was- not, the composer differs BECAUSE of that, and quoting it would manufacture the wall-clock- false alarm this file exists to remove. The refusal is right there and must survive."""+ """Control: a corroborated run-state difference explains the composer, so the refusal must survive."""base = dict(_blind_arm(24), composer_control = "Stop generating", streaming = True)treat = dict(_blind_arm(24),diff --git a/tests/studio/studiobench/fixture/selftest/test_studiobench_tail_deliverable.py b/tests/studio/studiobench/fixture/selftest/test_studiobench_tail_deliverable.pyindex 5b9f99d379f..40bb4ceecb4 100644--- a/tests/studio/studiobench/fixture/selftest/test_studiobench_tail_deliverable.py+++ b/tests/studio/studiobench/fixture/selftest/test_studiobench_tail_deliverable.py@@ -51,11 +51,7 @@ MATRIX: list[tuple[str, int, bool]] = [def test_every_requested_tail_is_delivered_or_refused(corpus: Corpus, rung: str, tail: int, deliverable: bool):- """The whole property, over the whole matrix: no third outcome.-- The two assertions are the reply-axis test's own, applied to every pair rather than to two of- them. Where the corpus cannot answer, the requirement is a refusal and not a smaller number.- """+ """Every requested tail is delivered or refused across the whole matrix, with no third outcome."""if not deliverable:with pytest.raises(ValueError, match = "cannot deliver"):plan_rung(corpus, rung, stream_tail_chars = tail)diff --git a/tests/studio/studiobench/instruments/coverage.py b/tests/studio/studiobench/instruments/coverage.pyindex ac8b23b4eb0..3bc4f6254b8 100644--- a/tests/studio/studiobench/instruments/coverage.py+++ b/tests/studio/studiobench/instruments/coverage.py@@ -25,8 +25,7 @@ class FunctionCount:@propertydef key(self) -> tuple[str, int, int]:- """Keyed on script and byte offsets, since minified code reuses names and a name key merges- functions."""+ """Keyed by script and byte offsets; minified names repeat and would merge functions."""return (self.script_id, self.start_offset, self.end_offset)def label(self) -> str:@@ -223,8 +222,7 @@ def ambiguity(snapshot: CoverageSnapshot, name: str) -> int:return len(snapshot.find(name))-# Harness adapter (INTERFACES.md section 3)-# Precise coverage disables TurboFan/Maglev, so timings in this cell are void (`timings_void`).+# INTERFACES.md section 3 adapter; precise coverage disables TurboFan/Maglev, so timings_void.import time # noqa: E402diff --git a/tests/studio/studiobench/instruments/cpuprofile.py b/tests/studio/studiobench/instruments/cpuprofile.pyindex b340586ed3a..0e737015c38 100644--- a/tests/studio/studiobench/instruments/cpuprofile.py+++ b/tests/studio/studiobench/instruments/cpuprofile.py@@ -176,8 +176,7 @@ def compare_with_trace_profile(}-# Harness adapter (INTERFACES.md section 3)-# V8 has one CpuProfiler, so this is only meaningful at level 1; at level 2+ it stands down.+# INTERFACES.md section 3 adapter; V8 has one CpuProfiler, so only level 1 is meaningful.import time # noqa: E402diff --git a/tests/studio/studiobench/instruments/frames.js b/tests/studio/studiobench/instruments/frames.jsindex 82573e98b05..c928b0b01fc 100644--- a/tests/studio/studiobench/instruments/frames.js+++ b/tests/studio/studiobench/instruments/frames.js@@ -159,8 +159,7 @@gaps.length === 0 ? null : Math.round((over33 / gaps.length) * 1000) / 10,p50_frame_ms: quantile(gaps, 0.5),p95_frame_ms: quantile(gaps, 0.95),- // Raw deltas for the jank metrics. gaps is sorted ascending, so over the cap emit null- // rather than a head slice that drops exactly the janky frames.+ // Sorted gaps: over the cap emit null, since a head slice drops the janky frames.frame_gaps_ms:gaps.length > GAPS_CAP ? null : gaps.map((g) => Math.round(g * 10) / 10),frame_gaps_truncated: gaps.length > GAPS_CAP,diff --git a/tests/studio/studiobench/instruments/heap.py b/tests/studio/studiobench/instruments/heap.pyindex 5c4f5962424..e9df98b51a7 100644--- a/tests/studio/studiobench/instruments/heap.py+++ b/tests/studio/studiobench/instruments/heap.py@@ -153,8 +153,7 @@ class SamplingHeapProfiler:return profiledef peek(self) -> HeapProfile:- """Reads the profile without stopping; the profiler keeps accumulating, so this is non-- destructive."""+ """Reads without stopping: the profiler keeps accumulating, so it is non-destructive."""if not self._running:raise RuntimeError("SamplingHeapProfiler.peek without start")return self._parse(self.cdp.send("HeapProfiler.getSamplingProfile"))@@ -206,8 +205,7 @@ def survival_ratio(}-# Level 3: samples include GC-collected objects so per-render churn is visible.-# The survivors arm is a separate Layer 3 ablation run.+# Level 3 keeps GC-collected samples so per-render churn shows; survivors is a separate run.import time # noqa: E402diff --git a/tests/studio/studiobench/instruments/layoutcost.js b/tests/studio/studiobench/instruments/layoutcost.jsindex 263f340e468..b03a59dbb4a 100644--- a/tests/studio/studiobench/instruments/layoutcost.js+++ b/tests/studio/studiobench/instruments/layoutcost.js@@ -2,12 +2,9 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0/*- * Counts and times DOM operations suspected of forcing synchronous layout during streaming.- * Off by default (perturbing); zero counts are distinguishable from patches that never installed.- * Counts how often the app asks for layout, not layout time; scrollY, getBoundingClientRect,- * offsetHeight and getComputedStyle are deliberately not wrapped (not in the suspected path).- * selfCostEstimate() times wrapped vs original-descriptor reads on a detached element to give- * per-call wrapper overhead. maxMs 0 means below clockGranularityMs, not free.+ * Counts forced-layout requests while streaming, not layout time; off by default as it perturbs;+ * zero counts must be distinguishable from never-installed patches; maxMs 0 means below+ * clockGranularityMs, not free.*/(function () {diff --git a/tests/studio/studiobench/instruments/pagejs.py b/tests/studio/studiobench/instruments/pagejs.pyindex 01e9b4e3636..0943eb2085b 100644--- a/tests/studio/studiobench/instruments/pagejs.py+++ b/tests/studio/studiobench/instruments/pagejs.py@@ -83,9 +83,8 @@ class FramesInstrument(_PageInstrument):self._arm_screencast()def _arm_screencast(self) -> None:- """CDP presented frames: the only one of the three clocks that is not the page's own- opinion of itself. A page whose main thread is wedged reports nothing from rAF and nothing- from a timer; the compositor still presents, or visibly does not."""+ """CDP frames, the only clock not the page's opinion; a wedged thread reports nothing via+ rAF/timers."""ctx = self.ctxif ctx is None or ctx.cdp is None:return@@ -118,8 +117,7 @@ class FramesInstrument(_PageInstrument):self._screencast_on = Falsedef calibrate(self, idle_ms: int = 1200) -> dict:- """Calibrate only in an enforced idle window: a loaded page's load would be read as the- timer floor."""+ """Calibrate only in an enforced idle window; page load would read as the timer floor."""if self.page is None:self.clamp = {"clampMs": None, "reason": "no page"}return self.clamp@@ -154,8 +152,7 @@ class FramesInstrument(_PageInstrument):return outdef _clock_agreement(self, out: dict, presented: int, elapsed_ms: float) -> dict:- """Screencast is liveness only, as it emits on visual change; agreement is rAF against the- 1ms timer."""+ """Screencast is liveness only; agreement is rAF against the 1ms timer."""raf = out.get("frames")lag_ticks = out.get("lag_ticks")clamp = out.get("clamp_ms")diff --git a/tests/studio/studiobench/instruments/rss.py b/tests/studio/studiobench/instruments/rss.pyindex da98b4052c8..686f00ea9c4 100644--- a/tests/studio/studiobench/instruments/rss.py+++ b/tests/studio/studiobench/instruments/rss.py@@ -65,9 +65,7 @@ def tree_rss_mb(roots: list) -> Optional[float]:class RssSampler:- """Samples on a THREAD, because the driver is blocked inside Playwright's sync API for the- whole run and cannot sample anything itself. Touches no Playwright object, only psutil, so it- is safe alongside the sync API's greenlet."""+ """Samples on a thread since the sync API blocks the driver; touches only psutil, so it is safe."""def __init__(self,@@ -114,9 +112,8 @@ class RssSampler:return usable[-1] if usable else Nonedef growth_mb(self) -> Optional[float]:- """Peak minus the FIRST reading of this run, not minus zero. A browser that is already up- carries a base footprint that has nothing to do with the thread, and the run before this- one in the same browser leaves its own. What is claimed is what this run ADDED."""+ """Peak minus this run's first reading, not zero: a pre-warmed browser's base footprint is+ excluded."""usable = [v for _, v in self.samples if v is not None]if len(usable) < 2:return Nonediff --git a/tests/studio/studiobench/instruments/selfcheck.py b/tests/studio/studiobench/instruments/selfcheck.pyindex a31867d0c90..c9119c2ade8 100644--- a/tests/studio/studiobench/instruments/selfcheck.py+++ b/tests/studio/studiobench/instruments/selfcheck.py@@ -533,8 +533,7 @@ def run_gates(injected_stall_ms: float = INJECTED_STALL_MS,injected_input_delay_ms: float = INJECTED_INPUT_DELAY_MS,) -> SelfCheckReport:- """Judges already-collected readings without driving the browser, so failing cases can be unit-- tested."""+ """Judges collected readings without a browser, so failing cases can be unit-tested."""report = SelfCheckReport()report.gates.append(evaluate_stall_gate(stall_observed_ms, injected_ms = injected_stall_ms))diff --git a/tests/studio/studiobench/instruments/selftest/test_studiobench_input_coverage.py b/tests/studio/studiobench/instruments/selftest/test_studiobench_input_coverage.pyindex b542db02e3e..abd35309ad4 100644--- a/tests/studio/studiobench/instruments/selftest/test_studiobench_input_coverage.py+++ b/tests/studio/studiobench/instruments/selftest/test_studiobench_input_coverage.py@@ -217,9 +217,7 @@ def test_a_healthy_reading_still_passes():def test_a_jammed_page_that_coalesced_most_of_its_keystrokes_still_passes():- """A LOW SAMPLE COUNT IS NOT A FAULT, it is the finding. On a jammed page most keystrokes- arrive behind a paint that has not finished, and the slow paint that swallowed them IS- measured. What matters is that every input is accounted for."""+ """A low sample count is the finding, not a fault: every input must still be accounted for."""result = _run_keystroke(_Instrument(_reading(samples = 3, coalesced = 9, p95_ms = 480.0)))@@ -238,8 +236,7 @@ def test_a_reading_with_a_keystroke_still_unpainted_is_not_quotable():def test_a_keystroke_that_never_reached_the_instrument_is_not_quotable():- """`grew_by` is satisfied by a textarea whose value is right; it says nothing about which- keystrokes were measured on the way in."""+ """`grew_by` is met by the textarea value alone; keystrokes must reach the instrument."""result = _run_keystroke(_Instrument(_reading(samples = 8, inputs_seen = 8, coalesced = 0)))diff --git a/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost.py b/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost.pyindex 897aafcfb1c..23c34b15abd 100644--- a/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost.py+++ b/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost.py@@ -251,8 +251,7 @@ MAX_SSE_CHUNK_CHARS = 65536def test_a_batched_sse_read_above_the_decoder_scan_bound_is_still_detected():- """Batched SSE reads above MAX_SSE_CHUNK_CHARS must still be detected, since stalls make them- largest."""+ """Batched SSE reads over MAX_SSE_CHUNK_CHARS are detected; stalls make them largest."""out = one_decoded_batch("batch-over", BURST_CHAIN_MS)assert out["decoded_chars"] > MAX_SSE_CHUNK_CHARS, out@@ -388,8 +387,7 @@ def test_the_close_side_drain_does_not_disturb_the_window_s_own_reading():def test_a_half_open_window_does_not_leak_its_open_reading_into_the_next_cell():- """`_chars_open` is per window; a cell that died between open and close must not seed the next- cell's first window with a stale character count."""+ """`_chars_open` is per window: a cell that died mid-window must not seed the next window."""inst = StreamCostInstrument()inst.start_cell(_FakeCell())inst._chars_open = 12345diff --git a/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_bias.py b/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_bias.pyindex 372244b927c..668b4458068 100644--- a/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_bias.py+++ b/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_bias.py@@ -151,9 +151,7 @@ def test_the_wire_denominator_is_the_same_price_on_a_windowed_document(browser,def test_the_wire_count_is_identical_on_both_documents_for_identical_traffic(browser):- """The denominator itself, not just its cost. Both arms are fed by the SAME pacer, so the- counter has to be a function of the bytes and of nothing else -- least of all of how much of- the thread the arm chose to mount."""+ """The denominator itself: both arms share one pacer, so the wire count depends only on bytes."""full, _ = _page(browser, FULL_ELEMENTS)win, _ = _page(browser, WINDOWED_ELEMENTS)try:@@ -169,9 +167,8 @@ def test_the_wire_count_is_identical_on_both_documents_for_identical_traffic(brodef test_the_counter_survives_a_frame_split_across_two_decode_calls(browser):- """A decode() call is a slice of the socket, not an SSE frame. A counter that assumed frame- alignment would silently under-count exactly when the renderer is jammed and the chunks arrive- ragged, which is the condition the whole instrument exists to measure."""+ """A decode() call is a socket slice, not an SSE frame; assuming alignment under-counts ragged+ chunks."""page, _ = _page(browser, WINDOWED_ELEMENTS)try:before = page.evaluate("() => window.__sb.streamcost.wireStats()")diff --git a/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_integrity.py b/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_integrity.pyindex d6eda472b9b..a49066b36c9 100644--- a/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_integrity.py+++ b/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_integrity.py@@ -84,8 +84,7 @@ def _frame(content: str) -> str:def test_a_clean_stream_is_scoreable_and_counts_every_character(page):- """The control. Without this the failure tests below could pass on an instrument that marks- everything unscoreable and counts nothing."""+ """Control: the failure tests below could also pass on an instrument that counts nothing."""page.evaluate("() => window.__sb.streamcost.reset()")_feed(page, _frame("hello") + _frame(" world"))assert page.evaluate("() => window.__sb.streamcost.replyChars()") == len("hello world")@@ -159,8 +158,7 @@ def test_a_window_ending_mid_frame_is_marked_unscoreable(page):def test_a_clean_window_stays_scoreable(page):- """The fix must not mark everything unscoreable; a check that never passes is as useless as one- that never fails."""+ """The fix must not mark everything unscoreable; a check that never passes is useless."""inst = _instrument(page)page.evaluate("() => window.__sb.streamcost.reset()")inst.open(_Window())@@ -179,8 +177,7 @@ def _halves(text: str, at: int) -> tuple:def test_the_counter_survives_a_split_inside_the_data_prefix(page):- """THE DEFECT. Two chunks, neither of which contains `data:`, and one whole frame between- them."""+ """The defect: a split inside the `data:` prefix, with neither chunk containing `data:`."""page.evaluate("() => window.__sb.streamcost.reset()")head, tail = _halves(_frame("split marker"), 2)assert "data:" not in head and "data:" not in tail, (head, tail)@@ -237,9 +234,7 @@ def test_unrelated_text_ending_in_a_marker_letter_does_not_corrupt_the_next_framdef test_the_speculative_buffer_cannot_grow_with_unrelated_traffic(page):- """The memory bound, asserted rather than argued. A fix that buffered every chunk in the page- on the chance that one of them was an SSE frame would be worse than the bug it fixes: a tail- short enough to be a partial `data:` is at most four characters."""+ """Memory bound asserted: a partial `data:` tail is at most four characters; no unbounded buffer."""page.evaluate("() => window.__sb.streamcost.reset()")for i in range(50):_feed(page, f"chunk {i} of unrelated traffic, ending in data")diff --git a/tests/studio/studiobench/instruments/selftest/test_studiobench_tracing_window.py b/tests/studio/studiobench/instruments/selftest/test_studiobench_tracing_window.pyindex 1b4d4f9c536..44ca7f0fc5f 100644--- a/tests/studio/studiobench/instruments/selftest/test_studiobench_tracing_window.py+++ b/tests/studio/studiobench/instruments/selftest/test_studiobench_tracing_window.py@@ -116,8 +116,7 @@ def test_the_first_window_is_still_traced_and_only_loses_the_cross_check():def test_no_tracing_session_is_left_running_in_the_browser():- """The leak itself. A capture nothing holds is a capture nothing can stop, and it keeps- recording underneath every measurement taken after it."""+ """An unheld capture cannot be stopped and keeps recording under later measurements."""cdp = _Cdp(metrics_fail = True)inst = _instrument(cdp)diff --git a/tests/studio/studiobench/instruments/streamcost.js b/tests/studio/studiobench/instruments/streamcost.jsindex 87ccd52985e..142cd1797b0 100644--- a/tests/studio/studiobench/instruments/streamcost.js+++ b/tests/studio/studiobench/instruments/streamcost.js@@ -63,8 +63,7 @@}return st;};- // The decoder that last delivered SSE, i.e. the measured stream. Built by newState() so a window- // opening before the first stream reads zero, not undefined.+ // Last decoder to deliver SSE, the measured stream; newState() keeps early windows at zero.let active = newState();// Marker fragment holder; reported even before its decoder is identified as the stream.let markerHold = null;diff --git a/tests/studio/studiobench/instruments/tracing.py b/tests/studio/studiobench/instruments/tracing.pyindex 4d600e88973..7d5bfd43824 100644--- a/tests/studio/studiobench/instruments/tracing.py+++ b/tests/studio/studiobench/instruments/tracing.py@@ -295,8 +295,7 @@ class TraceCapture:)def _drain(self, handle: str, compression: str) -> tuple[str, int]:- """Never read by offset (it counts pre-base64 bytes); append the final chunk before the EOF- check."""+ """No offset reads (pre-base64 count); append the last chunk before the EOF check."""parts: list[str] = []binary = Falsechunks = 0@@ -351,8 +350,7 @@ class OverheadLedger:return outdef disqualified_levels(self, rung_order: Sequence[str]) -> dict[str, str]:- """rung_order must run smallest first; rungs lacking L0 or the level are skipped, narrowing- the claim."""+ """rung_order must be smallest first; skipped rungs (no L0 or level) narrow the claim."""out: dict[str, str] = {}for level in (L1, L2, L3):series = [@@ -413,8 +411,7 @@ def cross_check_with_metrics(class MetricsWindow:- """Take getMetrics strictly inside the trace window; a wider metrics window causes false- disagreement."""+ """Read metrics inside the trace window only; a wider window causes false disagreement."""def __init__(self, cdp: Any) -> None:self.cdp = cdp@@ -440,8 +437,7 @@ class MetricsWindow:def read_metrics(cdp: Any) -> dict[str, float]:- """getMetrics on a disabled Performance domain errors; swallowing that error silently skips the- check."""+ """A disabled Performance domain makes getMetrics error; swallowing it skips the check."""res = cdp.send("Performance.getMetrics")return {m["name"]: m["value"] for m in res.get("metrics", [])}diff --git a/tests/studio/studiobench/pacer.py b/tests/studio/studiobench/pacer.pyindex 56aa648a8f7..3f13e45bfde 100644--- a/tests/studio/studiobench/pacer.py+++ b/tests/studio/studiobench/pacer.py@@ -483,8 +483,7 @@ class Pacer:def check_planned_streams(streams: list[dict], planned: list[dict]) -> dict:- """Matches by tag, first unmatched stream wins; cancelled throwaway streams go to extra, not- failures."""+ """By tag, first unmatched wins; cancelled throwaway streams count as extra, not failures."""remaining = list(streams)turns: list[dict] = []ok = Truediff --git a/tests/studio/studiobench/report/selftest/test_studiobench_cli_contracts.py b/tests/studio/studiobench/report/selftest/test_studiobench_cli_contracts.pyindex d714314b57e..3d54ef5d6be 100644--- a/tests/studio/studiobench/report/selftest/test_studiobench_cli_contracts.py+++ b/tests/studio/studiobench/report/selftest/test_studiobench_cli_contracts.py@@ -132,9 +132,7 @@ def test_one_origin_spelled_two_ways_is_still_one_origin(attach, attach_b):def test_the_predicate_and_the_refusal_read_the_same_origin():- """The two halves of this guard are in different files and only agree by construction. If- `origin_scoped` gated on the URL as typed while `arm_origins` canonicalised, a pair that got- past the refusal could still be gated onto a document that does not exist."""+ """origin_scoped (typed URL) and arm_origins (canonicalised) must agree or a pair gates onto nothing."""from studiobench.__main__ import arm_originsfrom studiobench.runtime.ab import origin_scopeddiff --git a/tests/studio/studiobench/report/selftest/test_studiobench_payload_ab_plan.py b/tests/studio/studiobench/report/selftest/test_studiobench_payload_ab_plan.pyindex 0b1e5037bab..e8ca5e06d56 100644--- a/tests/studio/studiobench/report/selftest/test_studiobench_payload_ab_plan.py+++ b/tests/studio/studiobench/report/selftest/test_studiobench_payload_ab_plan.py@@ -154,9 +154,8 @@ def test_a_retry_that_never_reached_its_cell_row_still_owns_the_cell():def test_a_plan_balanced_as_written_is_unbalanced_if_only_its_first_half_ran():- """A `--reps 2` interrupted after rep 0 planned base, treatment, treatment, base and ran- base, treatment, so base led every pair that happened and drift lands on treatment instead- of cancelling. That pair is scored, so the plan's `True` describes an order nothing ran."""+ """Interrupted --reps 2 run plans base,treatment,treatment,base but runs only the first half, so+ balanced must be False, not True."""rows = [ROWS[0], _plan("s1", LADDER, balanced = True), *_cells("s1", *PAIR)]assert _assemble(rows)["ab_plan"]["balanced"] is Falsewhole = [ROWS[0], _plan("s1", LADDER, balanced = True), *_cells("s1", *LADDER)]diff --git a/tests/studio/studiobench/report/selftest/test_studiobench_report.py b/tests/studio/studiobench/report/selftest/test_studiobench_report.pyindex ddc0f67f142..37a41c8e727 100644--- a/tests/studio/studiobench/report/selftest/test_studiobench_report.py+++ b/tests/studio/studiobench/report/selftest/test_studiobench_report.py@@ -238,8 +238,7 @@ def _gated_cell_rows(def test_a_cell_that_lost_its_thread_is_scored_incomplete_rather_than_green():- """A cell that lost its thread must score INCOMPLETE, not green; there is no second arm to- compare it to."""+ """A cell that lost its thread scores INCOMPLETE, not green; no second arm to compare."""from studiobench.report.build import _completion_by_runggot = _completion_by_rung(_gated_cell_rows("thread_complete", False))@@ -299,8 +298,7 @@ def test_a_retry_that_passed_is_not_marked_incomplete_by_the_dead_attempt():def test_the_floor_table_drops_a_gate_failed_cell():- """The other scorer that admits a cell on `completed` alone. It builds the floor a result is- then judged against, and scores the result too."""+ """The floor table also admits on `completed` alone, so it must drop gate-failed cells."""from studiobench.sweep.floor_table import cell_metricsrows = _gated_cell_rows("thread_complete", False) + [@@ -345,9 +343,8 @@ def test_a_measured_stream_follow_failure_is_still_fatal():def test_a_bounded_ratio_is_marked_rather_than_printed_as_a_measurement():- """An arm under its instrument floor contributes the floor, so the ratio understates the true- magnitude. Printed bare it invites `4900% worse` being quoted as a measurement; the marker- goes in the ratio cell rather than a footnote for the same reason the void path gives."""+ """An arm under its floor reports the floor, understating the ratio; mark the ratio cell, not a+ footnote, so 4900% worse is not quoted as a measurement."""identity = RunIdentity("studiobench/1", "c", "r", "w", "s1")smooth = Measure.read(0.0, "%", floor = 0.1)@@ -382,8 +379,7 @@ def test_an_ordinary_ratio_is_still_printed_bare():def test_a_missing_viewport_is_not_waived_as_an_absent_instrument():- """A missing thread viewport is a defect in the arm, so it must not be waived as an absent- instrument."""+ """A missing thread viewport is a defect in the arm, not an absent instrument to waive."""from studiobench.report.build import _completion_by_rungrows = _gated_cell_rows("thread_complete", False)diff --git a/tests/studio/studiobench/runtime/ab.py b/tests/studio/studiobench/runtime/ab.pyindex 9e0eba02b02..175bb9f438b 100644--- a/tests/studio/studiobench/runtime/ab.py+++ b/tests/studio/studiobench/runtime/ab.py@@ -153,8 +153,7 @@ def unmeasured_planned_cells(planned: Sequence[str],session_id: Optional[str] = None,) -> list[str]:- """An incomplete plan must void the table: a failed cell also drops its healthy partner from the- pair."""+ """An incomplete plan voids the table; a failed cell also drops its healthy partner."""from ..scoring.from_payload import latest_attempt_rows# Apply the same two filters as readings_by_arm, so gate-failed cells also void the plan.diff --git a/tests/studio/studiobench/runtime/lifecycle.py b/tests/studio/studiobench/runtime/lifecycle.pyindex e626ac9958c..a05d2e64e0c 100644--- a/tests/studio/studiobench/runtime/lifecycle.py+++ b/tests/studio/studiobench/runtime/lifecycle.py@@ -92,8 +92,7 @@ class StudioAuth:return self.access_tokendef rotate(self) -> str:- """Refresh is skipped for a token already inside the margin, or clock skew would re-login- per request."""+ """Skip refresh inside the margin, or clock skew would re-login per request."""fresh = login(self.base_url, self.username, self.password)self.access_token = fresh.access_tokenself.refresh_token = fresh.refresh_token or self.refresh_token@@ -117,8 +116,7 @@ def auth_request_json(body: Optional[dict] = None,timeout: float = 30.0,) -> Any:- """Retries a 401 once after a fresh login; the login stays outside the try, so its 401 is not- retried."""+ """A 401 is retried once after fresh login; that login is outside the try, so not retried."""bearer = auth.token()try:return request_json(url, method = method, body = body, token = bearer, timeout = timeout)diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_home_collision.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_home_collision.pyindex 377232dec63..0914ec6bf5d 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_home_collision.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_home_collision.py@@ -24,8 +24,7 @@ def test_a_shared_home_under_ab_is_refused_rather_than_warned():def test_the_refusal_says_what_to_do_instead():- """A refusal a reader cannot act on gets worked around. Naming the replacement is the- difference between a guard and an obstacle."""+ """A refusal must name what to do instead, or it becomes an obstacle people work around."""source = _source()guard = source[source.index("--home cannot be used with --ab") :][:700]assert "Drop --home" in guard@@ -33,8 +32,7 @@ def test_the_refusal_says_what_to_do_instead():def test_the_guard_sits_before_any_install_runs():- """Refusing AFTER the first install has already run costs the caller the slow half of the- mistake and leaves a half-built home behind."""+ """The guard must sit before any install, or a refusal leaves a half-built home behind."""source = _source()assert source.index("if not args.attach and args.home:") < source.index("side_install = install_studio(ref, home)"@@ -56,9 +54,7 @@ def test_the_guard_sits_before_the_payload_is_archived():def test_a_single_arm_run_still_accepts_home():- """`--home` is legitimate on its own: there is only one build to install, so there is no- collision. The guard is on the COMBINATION, and narrowing it wrongly would break the- single-arm path that people use to pin an install."""+ """`--home` alone is legitimate (one build, no collision); the guard covers only the combination."""source = _source()guard_line = next(line for line in source.split("\n") if "if not args.attach and args.home:" in linediff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_completeness_gate_rows.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_completeness_gate_rows.pyindex a9154afc89b..6b3c216ab7d 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_completeness_gate_rows.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_completeness_gate_rows.py@@ -77,9 +77,8 @@ def test_a_cell_that_lost_messages_is_excluded_as_itself_and_not_as_the_run(tmp_def test_coverage_that_does_not_apply_does_not_fail_the_cell(tmp_path):- """A fully mounted arm publishes no `aria-posinset` anywhere, so there are no ordinals to- cover and none missing. The question does not arise, and failing a cell on a question that was- never asked of it would fail the shipped build's own completeness gate on every cell."""+ """Fully mounted arms publish no aria-posinset, so coverage does not apply and must not fail the+ cell."""rows, passed = _rows(tmp_path,{diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_copy_from_store_live.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_copy_from_store_live.pyindex f3b6a827499..122f2f83331 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_copy_from_store_live.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_copy_from_store_live.py@@ -122,8 +122,7 @@ def test_a_full_mount_copies_the_whole_thread(context):def test_a_windowed_thread_without_the_handler_loses_most_of_the_conversation(context):- """THE REGRESSION, REPRODUCED. Not described, not inferred from the mounted count: the- clipboard is read back and most of the conversation is not in it."""+ """Regression reproduced: the read-back clipboard lacks most of the conversation."""page = _page(context, "windowed", copy_from_store = False)try:got = _select_all_copy(page)diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_ladder_ratio_identity.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_ladder_ratio_identity.pyindex 454b45fa478..8b2d98af443 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_ladder_ratio_identity.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_ladder_ratio_identity.py@@ -99,12 +99,9 @@ def _problems(paths: Paths, measured: float) -> list:def test_a_resume_that_sizes_the_ladder_differently_is_refused(tmp_path):- """The bug, as the numbers it produced.-- The recorded run had no tokeniser and planned 1K at 4,000 characters; this one reads the corpus- at 3.336 and would plan 100K at 333,600 rather than 400,000. `_resume_set` skips the first two- rungs regardless, because the ratio is nowhere in a cell id.- """+ """The recorded run had no tokeniser and planned 1K at 4,000 characters; this one reads the+ corpus at 3.336 and would plan 100K at 333,600 rather than 400,000; _resume_set skips the+ first two rungs regardless since the ratio is nowhere in a cell id."""paths = _payload(tmp_path,diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_launch_cleanup.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_launch_cleanup.pyindex 0189e470eb8..8902e8192d4 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_launch_cleanup.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_launch_cleanup.py@@ -68,8 +68,7 @@ def test_a_studio_that_never_answers_healthz_is_terminated(launched):def test_a_studio_that_never_started_at_all_still_raises(launched):- """The control for the discovery itself: nothing to find is not a reason to crash on the way- to reporting the timeout."""+ """Control: finding nothing must not crash on the way to reporting the timeout."""launched["healthy"] = Falselaunched["pgrep_finds"] = False@@ -121,8 +120,7 @@ def test_a_port_that_is_already_serving_is_refused_before_anything_is_launched(ldef test_the_occupied_port_does_not_come_back_as_a_healthy_studio(launched):- """The consequence, stated as the caller sees it: no `StudioInstall` is returned at all, so- nothing records a ref against a build it never installed."""+ """Occupied port yields no StudioInstall, so no ref is recorded against an unbuilt build."""launched["port_busy"] = Truelaunched["healthy"] = Truediff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_live_marker_race.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_live_marker_race.pyindex 7d1dc6423a1..2fc1e5ae680 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_live_marker_race.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_live_marker_race.py@@ -156,9 +156,8 @@ def _stalled_holder(write_after_s: float,session: str = "realsession",):- """A holder that takes the lock and only then publishes itself, which is the required order:- the write is what makes the marker say anything, and writing before the lock would let a LOSER- publish itself as the holder."""+ """The holder must take the lock before publishing itself: the write is what makes the marker+ say anything, and writing first lets a loser publish as holder."""code = ("import os,fcntl,time,sys\n""fd=os.open(sys.argv[1],os.O_CREAT|os.O_RDWR,0o644)\n"diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.pyindex 6253dc35b55..2619fec79bf 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py@@ -241,8 +241,7 @@ def test_resuming_with_more_reps_and_another_rung_is_still_a_resume(tmp_path):def test_a_payload_that_never_recorded_an_axis_still_resumes(tmp_path):- """The legacy control. An older payload carries only the required `run_meta` keys, and an axis- it never declared cannot be a difference."""+ """An older payload has only the required run_meta keys; an undeclared axis cannot differ."""paths = Paths.under(tmp_path / "out")legacy = {@@ -382,12 +381,8 @@ def test_resuming_a_single_build_payload_as_an_ab_is_refused(tmp_path):def test_a_session_that_died_before_its_first_cell_declares_no_mode(tmp_path):- """The control for the refusal above: it may not fire on a run that measured nothing.-- `run_meta` is written after both installs and `ab_plan` after the corpus and the gates, so an- A/B killed in between leaves a header and no cells. There is nothing there for a later report- to keep in preference to this one's readings, so resuming it is a resume.- """+ """Control for the refusal above: run_meta is written before ab_plan, so a run killed between+ them leaves a header with no cells, which must still resume."""paths = Paths.under(tmp_path / "out")_record(paths, "sess-1", [_run_meta("standard", "main", ["10K"])])@@ -488,8 +483,7 @@ def test_resuming_under_a_changed_dollar_setting_is_refused(tmp_path):def test_a_payload_that_already_holds_two_fixtures_is_refused_either_way(tmp_path):- """Two sessions, two films, one file: whichever of them you ask for, the other one is still- in there and its cells would still be skipped."""+ """Two sessions in one file: the other session's cells would still be skipped on resume."""paths = _fixture_payload(tmp_path, "mixed", "sess-1", stream_tail_chars = 6_000)_record(@@ -653,8 +647,7 @@ def test_resuming_after_toggling_the_click_probe_is_refused(tmp_path):def test_a_payload_from_before_the_probe_flag_is_refused_under_a_probed_resume(tmp_path):- """Absence proves the default here too. A payload with no `click_probe` key was written when- there was no way to ask for the probe, so it ran without it."""+ """A payload with no click_probe key predates the flag, so it ran without the probe."""paths = _fixture_payload(tmp_path, "legacy-probe", "sess-old")assert "click_probe" not in paths.payload_jsonl.read_text(encoding = "utf-8")@@ -673,8 +666,7 @@ def test_a_payload_from_before_the_probe_flag_is_refused_under_a_probed_resume(tdef test_an_unchanged_probe_setting_resumes_and_returns_its_completed_cells(tmp_path):- """The control. The axis may not swallow a resume that is asking for the run it already has,- on either setting."""+ """The axis must not block a resume asking for the run it already has, on either setting."""probed = _fixture_payload(tmp_path, "probed-same", "sess-probed", click_probe = True)assert (@@ -710,9 +702,8 @@ def test_the_probe_flag_reaches_the_identity_this_invocation_asks_for():def test_the_skip_rule_still_holds_for_an_axis_that_really_did_decline_to_say(tmp_path):- """The other axes keep the general rule: `run_meta` has always carried them, so a payload that- omits one omitted it for its own reasons and this check has nothing to say about it. Only the- axes that arrived with a flag of their own read absence as a value."""+ """Other axes keep the general rule: run_meta has always carried them, so this check says+ nothing about an omitted key; only axes that came with a flag read absence as a value."""paths = Paths.under(tmp_path / "quiet")_record(@@ -921,9 +912,8 @@ def test_resuming_a_finished_uninjected_run_with_the_injection_on_is_refused(tmpdef test_resuming_an_injected_run_without_the_injection_is_refused(tmp_path):- """The other direction, and the likelier one: an injected A/B dies part way up the ladder and- the retry is typed without the flag. The rungs already done stay injected, the rungs still to- come are not, and the ladder the recovery fraction is computed from is half of each."""+ """The likelier case: an injected A/B dies partway up the ladder and is retried without the+ flag, so the ladder the recovery fraction uses is half injected and half not."""paths = _injected_payload(tmp_path, "injected", "sess-1", inject_stream_cost_ms = 3.0)@@ -938,8 +928,7 @@ def test_resuming_an_injected_run_without_the_injection_is_refused(tmp_path):def test_resuming_under_a_changed_injection_amount_is_refused(tmp_path):- """The amount is the measurement. A ladder half of which burned 3 ms per chunk and half 40 ms- has no recovery fraction at all."""+ """The amount is the measurement; mixing 3 ms and 40 ms chunks leaves no recovery fraction."""paths = _injected_payload(tmp_path, "amount", "sess-1", inject_stream_cost_ms = 3.0)@@ -1080,9 +1069,8 @@ def test_a_payload_from_before_the_probe_hook_resumes_under_the_default(tmp_pathdef test_an_unchanged_probe_resumes(tmp_path, monkeypatch):- """THE SECOND CONTROL. A probe ladder that died is meant to be resumable AS a probe ladder.- The payload is not scorable either way, but a potency run is a run, and refusing every value- would make the axis useless rather than safe."""+ """A probe ladder that died should resume as a probe ladder; the payload is not scorable either+ way, but refusing every value would make the axis useless, not safe."""paths = _fixture_payload(tmp_path, "same", "sess-probed", probe_init_script = PROBE)monkeypatch.setenv("SBENCH_EXTRA_INIT_SCRIPT", PROBE)diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_probe_survives_failure.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_probe_survives_failure.pyindex a7a8e185b89..ef93303c37e 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_probe_survives_failure.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_probe_survives_failure.py@@ -208,8 +208,7 @@ def test_the_attribution_of_one_cell_never_lands_on_the_next(tmp_path):def test_a_cell_that_never_asked_for_the_probe_reports_none(tmp_path):- """CONTROL. Without `--click-probe` there is nothing to preserve, and the failed cell says so- by carrying no attribution at all rather than an empty one."""+ """Without --click-probe a failed cell has no attribution to preserve, so it carries none."""runner, paths, recorder = _runner(tmp_path, click_probe = False)runner.run(_cell(), _plan())diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_readiness_live.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_readiness_live.pyindex 0630d11b898..1b8496508bf 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_readiness_live.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_readiness_live.py@@ -557,11 +557,8 @@ def _windowed_probe(**changes) -> dict:def test_evaluate_refuses_ordinals_that_are_not_positions():- """The three malformed shapes, on the decision function itself.-- The live tests above put each of these in a real browser; this pins the rule they are being- judged by, including which of the two conditions each one trips.- """+ """Pins the decision function on the three malformed shapes the live browser tests cover,+ including which of the two conditions each trips."""good = _windowed_probe()assert evaluate(good, good, 18, MODE_WINDOWED)["posinset_ordinals_valid"] is Truezeros = _windowed_probe(posinset_distinct = 1, min_posinset = 0, max_posinset = 0)@@ -645,8 +642,7 @@ def test_ordinal_coverage_reports_a_hole_inside_one_mounted_window_whatever_the_def test_ordinal_coverage_is_unmeasured_when_the_traversal_never_reached_the_top():- """Even a completely covered union proves nothing if the gesture stopped short: the rows it- did not reach are rows it did not look at."""+ """Full coverage proves nothing if the gesture stopped short; unreached rows went unseen."""stopped = {"reached_target": False,"ordinals_seen": list(range(1, 19)),diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_resume_commit.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_resume_commit.pyindex 50d019f820c..51c6c234687 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_resume_commit.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_resume_commit.py@@ -182,8 +182,7 @@ def test_a_resume_after_the_treatment_moved_is_refused(studio):def test_the_same_commit_still_resumes(studio):- """The control that matters: a resume of the build the payload was recorded on is the whole- point of `--resume` and must still skip its cells and exit 0."""+ """Resuming the same build must still skip its cells and exit 0 with --resume."""assert sb.run(_args(studio, "--branch", "main")) == 0assert sb.run(_args(studio, "--branch", "main", "--resume")) == 0@@ -207,8 +206,7 @@ def test_a_payload_recorded_before_commits_were_written_still_resumes(studio):def test_an_attached_resume_is_not_refused_for_having_no_commit(studio):- """The other control: attaching cannot start failing against its own payload just because- this run has no commit to offer either."""+ """An attached resume is not refused for having no commit to offer; it still returns 0."""assert sb.run(_args(studio, "--attach", "http://127.0.0.1:5310")) == 0assert sb.run(_args(studio, "--attach", "http://127.0.0.1:5310", "--resume")) == 0diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_run_acquisition.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_run_acquisition.pyindex 5c451363b44..6c60f569594 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_run_acquisition.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_run_acquisition.py@@ -579,8 +579,7 @@ def test_a_probe_run_invents_no_ab_table_where_there_was_none(studio, monkeypatcdef test_a_probe_run_invents_no_summary_where_there_was_none(studio, monkeypatch, tmp_path):- """The control. The refusal replaces a stale report; it does not create a report-shaped file- in a directory whose reader was never given one to misread."""+ """The refusal replaces a stale report and must not invent a report where none existed."""script = tmp_path / "paint_counter.js"script.write_text("window.__probe_ticks = 0;\n", encoding = "utf-8")diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_drain.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_drain.pyindex 3b3b85ce0b8..1928f5b7890 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_drain.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_drain.py@@ -29,8 +29,7 @@ CENSUS = {class _Clock:- """A monotonic clock the page's own waits advance, so the real drain loop runs to its real- deadline without this test sleeping through it."""+ """A monotonic clock the page's waits advance, so the drain loop reaches its deadline."""def __init__(self) -> None:self.t = 0.0diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_stats.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_stats.pyindex 27deb5e5680..1ad371c93d2 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_stats.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_stats.py@@ -62,8 +62,7 @@ def _consume(pacer: Pacer, *, stop_after_bytes: int | None = None) -> None:class _Page:- """Just enough page for `send_turn`: a composer, a keyboard, and an `isRunning` that is true- for as long as the follow-up's client is draining the stream."""+ """Minimal page for `send_turn`: `isRunning` stays true while the follow-up is draining."""def __init__(self, pacer: Pacer) -> None:self.pacer = pacer@@ -259,8 +258,7 @@ class _CellPage:class _RecordedPacer:- """A pacer whose streams are dictated by the test, so the cell path can be driven over both- outcomes without a socket."""+ """Pacer whose streams the test dictates, so both cell outcomes run without a socket."""def __init__(self, streams: list[dict]) -> None:self.streams = streams@@ -491,9 +489,8 @@ def test_a_follow_up_that_was_sent_but_never_streamed_fails_the_cell(cell_runnerdef test_a_follow_up_that_streamed_but_never_joined_the_thread_fails_the_cell(cell_runner, monkeypatch):- """The other half. The pacer served every byte, so the stream check alone passes; the thread- did not grow, so every later action, the peak census and the equivalence mirror still read a- thread one turn short."""+ """The other half: the pacer served every byte, so the stream check passes; the thread never+ grew, so later actions and the census read one turn short."""monkeypatch.setattr(session_mod, "SceneRunner", _scene_with([SEND_TURN_THAT_FAILED]))runner = cell_runner(@@ -562,9 +559,8 @@ def test_an_ordinary_action_whose_assertion_failed_does_not_fail_the_cell(cell_rdef test_a_send_turn_that_did_not_run_is_not_demanded_of_the_pacer(cell_runner, monkeypatch):- """The other control, and the reason the planned list is built from the ACTION rows. At the- small rungs the queue is empty and `send_turn` reports NOT RUN; nothing was streamed for it and- nothing must be required of it."""+ """The other control: the planned list is built from ACTION rows, so a `send_turn` that reports+ NOT RUN on small rungs (empty queue) is not required of the pacer."""class _NoTurn(_SceneRunner):def run(self, scene, t0) -> list:@@ -652,8 +648,7 @@ class _WirePage:class _RealSendTurnScene:- """The film, reduced to the two `send_turn` slots that matter here, running the SHIPPED action- against the shipped base_args the session builds."""+ """Film cut to two `send_turn` slots, running the shipped action on the shipped base_args."""def __init__(self, **kwargs) -> None:self.kwargs = kwargs@@ -685,9 +680,8 @@ class _RealSendTurnScene:def test_a_healthy_multi_turn_cell_passes_the_check_over_real_wire_bytes(monkeypatch, tmp_path):- """The control the fix most needs: a cell that streamed everything it planned, with the pacer,- the action and the check all real, must still complete. The dictated-stream tests above prove- the failure path; this proves the ordinary path was not broken to get it."""+ """Control for the fix: a cell that streams everything it planned, with real pacer, action and+ check, must still complete; the ordinary path was not broken."""from studiobench.runtime.session import CellRunner, Sessionfrom studiobench.runtime.types import BenchContext, Paths, Recorderdiff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_token_refresh.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_token_refresh.pyindex 7a682745bc2..e4767ff81f4 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_token_refresh.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_token_refresh.py@@ -187,9 +187,8 @@ def test_the_token_is_replaced_before_it_expires_not_after_it_fails(studio, monkdef test_a_401_that_arrives_anyway_is_recovered(studio):- """The reactive half. A token this process believes is fresh can still be refused: a clock- offset against the server, or an Unsloth restarted underneath the run. One retry, then the- refusal is real and is raised."""+ """Reactive half: a token believed fresh can still be refused (clock offset, or Unsloth+ restarted under the run); one retry, then the refusal is real and raised."""base_url, state = studioauth = authenticate(base_url, "bench", PASSWORD, new_password = PASSWORD)auth.expires_at = time.time() + 10_000@@ -243,9 +242,8 @@ def test_a_clock_that_makes_every_token_look_stale_stops_the_proactive_half(studdef test_a_failing_rotation_hook_does_not_fail_the_request(studio):- """`on_rotate` re-seeds a Playwright context, which can throw for reasons that have nothing to- do with authentication -- a closed context, a page that crashed. The token has already been- replaced by then and the request has to go out."""+ """`on_rotate` re-seeds a Playwright context and can throw for reasons unrelated to+ authentication; the token is already replaced, so the request must go out."""monkeypatch_error = RuntimeError("Target page, context or browser has been closed")base_url, _state = studioauth = authenticate(base_url, "bench", PASSWORD, new_password = PASSWORD)diff --git a/tests/studio/studiobench/runtime/session.py b/tests/studio/studiobench/runtime/session.pyindex 6dd67ad1bf2..7c3a90ee02b 100644--- a/tests/studio/studiobench/runtime/session.py+++ b/tests/studio/studiobench/runtime/session.py@@ -157,8 +157,7 @@ class Session:self.ctx.recorder.emit(w.row())def each_instrument(self, method: str, *args) -> dict:- """Iterate a snapshot: _safe may drop a failing instrument, which would skip its neighbour's- hook."""+ """Iterate a snapshot: _safe can drop a failing one, skipping its neighbour's hook."""out: dict = {}for inst in list(self.instruments):got = self._safe(inst, method, *args)@@ -633,8 +632,7 @@ class CellRunner:@staticmethoddef _streamed_follow_ups(plan: RungPlan, row: dict) -> list:- """Counts every follow-up that streamed, from the action rows, so the mirror seeds only what- landed."""+ """Counts streamed follow-ups from action rows, so the mirror seeds only what landed."""streamed = 0for action in row.get("actions") or []:if action.get("action") != "send_turn":@@ -725,8 +723,7 @@ class CellRunner:page.wait_for_timeout(250)def settled(fn) -> float:- """Times fn plus a round trip into the page, since the call can return before the page- processes it."""+ """Times fn and a page round trip, since fn returns before the page processes it."""started = time.monotonic()fn()page.evaluate("() => document.body.offsetHeight")diff --git a/tests/studio/studiobench/runtime/types.py b/tests/studio/studiobench/runtime/types.pyindex 74d779ab794..85522a4e443 100644--- a/tests/studio/studiobench/runtime/types.py+++ b/tests/studio/studiobench/runtime/types.py@@ -394,8 +394,7 @@ class OutDirLock:path: Path,budget_s: float = 0.5,) -> "Optional[tuple[str, int]]":- """The holder locks before it writes, so wait out the empty marker; a single read would name- no one."""+ """Holder locks before writing, so wait out an empty marker; one read names no one."""deadline = time.monotonic() + budget_swhile True:got = cls._read_marker(path)@@ -434,8 +433,7 @@ class OutDirLock:class Recorder:- """Append-only JSONL. Every line is flushed and fsynced, so a renderer crash at rung 4 still- ships rungs 1 to 3 plus the crash record."""+ """Append-only JSONL, each line fsynced, so a crash at rung 4 keeps rungs 1 to 3."""def __init__(self,@@ -488,8 +486,7 @@ class Recorder:detail: Optional[dict] = None,cell_id: Optional[str] = None,) -> None:- """Pass cell_id whenever the verdict is about a cell; without it the failure is attributed- to run."""+ """Pass cell_id for a cell's verdict; without it the failure is attributed to the run."""row = {"row_type": "gate", "name": name, "passed": bool(passed), "detail": detail or {}}if cell_id is not None:row["cell_id"] = cell_iddiff --git a/tests/studio/studiobench/scene/actions.py b/tests/studio/studiobench/scene/actions.pyindex f80e8f855ba..cecc9a56d4d 100644--- a/tests/studio/studiobench/scene/actions.py+++ b/tests/studio/studiobench/scene/actions.py@@ -1506,9 +1506,8 @@ def image_upload(ctx: ActionContext) -> ActionResult:try:plus.click(timeout = max(500, min(ctx.budget_ms // 3, 5000)))except Exception as exc: # noqa: BLE001- # Radix opens the menu on pointerdown, so the click can time out on the modal open after it- # took effect (that open grows with DOM size). The menu this attempt opened is the click's- # effect: carry on with it.+ # Radix opens the menu on pointerdown, so the click can time out after its open took effect+ # (the open grows with DOM size); an open menu is the click's effect, so carry on.if _ev(ctx, _NEW_MENU_OPEN_JS) is True:click_overran = Trueelse:diff --git a/tests/studio/studiobench/scene/dom.js b/tests/studio/studiobench/scene/dom.jsindex 5c353e8c99a..4d512f8cd1e 100644--- a/tests/studio/studiobench/scene/dom.js+++ b/tests/studio/studiobench/scene/dom.js@@ -32,8 +32,7 @@"Send message",];- // Progress hooks: data-status on text parts and aria-busy on reasoning content, named once so- // the streaming scan and its control cannot drift apart.+ // Progress hooks named once so the streaming scan and its control cannot drift apart.const STATUS_HOOK = '[data-status], [data-slot="reasoning-content"][aria-busy]';const byName = (sel, name, root) =>@@ -96,8 +95,7 @@(m) => m.querySelector('[data-status="running"], [aria-busy="true"]') !== null,);},- // Tells a renamed data-status hook (blind probe) apart from an unmounted row or a row with no- // parts yet. data-status is rendered for complete parts too.+ // Tells a renamed hook from unmounted or empty rows; data-status marks complete parts too.statusHookPresent() {return D.assistantMessages().some((m) => m.querySelector(STATUS_HOOK) !== null);},@@ -111,8 +109,7 @@messageCount() {return qa("[data-role]").length;},- // Thread length, not mounted count: differs once an arm windows. Read from aria-setsize, where- // WAI-ARIA requires a windowed list to publish it.+ // Thread length, not mounted count: a windowed list must publish it as aria-setsize.threadTotal() {// The ordinal may sit on the message or on the virtualizer's row wrapper (same walk as readiness.py).const first = q("[data-role]");@@ -134,8 +131,7 @@return all.length ? all[all.length - 1] : null;},- // Hidden with `invisible` when the app's autoscroll considers itself at the bottom, so the- // harness and the app cannot disagree about pinning.+ // Hidden (`invisible`) when the app is at bottom, so harness and app agree on pinning.jumpToBottomButton() {return q(".aui-thread-scroll-to-bottom");},@@ -159,8 +155,7 @@reasoningOpenCount() {return qa('[data-slot="reasoning-root"][data-state="open"]').length;},- // Collapsed content stays mounted until animationend/transitionend, so a collapse is settled- // only once the content is gone.+ // Collapsed content stays mounted until its transition ends, so a collapse settles late.reasoningContentMounted() {return qa('[data-slot="reasoning-content"]').filter((el) => !el.hasAttribute("hidden")).length;@@ -227,8 +222,7 @@const menu = D.openMenu();return menu ? byName(".aui-action-bar-more-item", name, menu) : null;},- // Radix opens on pointerdown, so click() leaves the menu shut. The portaled menu is looked up- // only when body's children change, not per paint.+ // Radix opens on pointerdown, not click; the portal is searched only on body changes.async openMenuAndFind(trigger, name, waitMs) {const pointer = { bubbles: true, cancelable: true, composed: true, button: 0,pointerId: 1, pointerType: "mouse", isPrimary: true };@@ -458,8 +452,7 @@suspend() { suspended += 1; detached = true; detachedAtRun = runSeq; },resume() {suspended = Math.max(0, suspended - 1);- // Re-attach if the gesture ended at the bottom; only checked on gesture exit, so the app pulling- // the viewport down on its own still counts as a yank.+ // Re-attach on exit if the gesture ended at bottom; app-driven scrolls count as yanks.if (suspended === 0 && detached) {const app = D.appSaysAtBottom();const distance = D.distanceFromBottom();diff --git a/tests/studio/studiobench/scene/parity.js b/tests/studio/studiobench/scene/parity.jsindex 51727334ac2..86e16ed94cb 100644--- a/tests/studio/studiobench/scene/parity.js+++ b/tests/studio/studiobench/scene/parity.js@@ -276,9 +276,8 @@return position;};- // The fallback ordinal is the row's DOM position at observe time, not a lifetime counter:- // thread_reopen rebuilds rows in one document. The index is built at most once per mutation- // batch and only when needed, keeping O(document) work off the per-mutation path.+ // Fallback ordinal is DOM position at observe time, not a lifetime counter, since thread_reopen+ // rebuilds rows; the index is built at most once per mutation batch, only when needed.const positionIndex = () => {if (VIS.index) return VIS.index;const nodes = (D().messages && D().messages()) || [];diff --git a/tests/studio/studiobench/scene/schedule.py b/tests/studio/studiobench/scene/schedule.pyindex a19fd2cec91..a2140f8f232 100644--- a/tests/studio/studiobench/scene/schedule.py+++ b/tests/studio/studiobench/scene/schedule.py@@ -24,8 +24,7 @@ class Scene:return max((s.t_start_ms + s.budget_ms for s in self.slots), default = 0)def scaled(self, factor: float) -> "Scene":- """Stretches the same film over a longer duration, keeping action order and spacing, for big- rungs."""+ """Stretches the film over a longer duration for big rungs, keeping order and spacing."""return Scene(name = self.name,slots = [@@ -52,8 +51,7 @@ def _slots(spec: list[tuple[str, int, Optional[int]]]) -> list[Slot]:]-# Ordered: during-generation actions first, then settled-reply ones, destructive last.-# Timings are offsets from the send button press.+# During-generation first, settled-reply next, destructive last; offsets from the send press.STANDARD = Scene(name = "standard",slots = _slots(@@ -87,8 +85,7 @@ QUICK = Scene(name = "quick",slots = _slots([- # Budgets are ~2.5x measured action cost at 100K. The 12s to 20s gap is the stream drain- # constraint, not slack.+ # Budgets ~2.5x action cost at 100K; 12s to 20s gap is stream drain, not slack.("scroll_during_generation", 1_500, 2_500),("keystroke", 5_000, 3_000),("scroll_during_generation", 9_500, 2_500),@@ -197,8 +194,7 @@ class SceneRunner:return {"visible_attempted": False, "reason": f"{type(exc).__name__}: {exc}"}def _parity(self) -> dict:- """Taken with the census at the window's close, so digest and occupancy come from one DOM- reading."""+ """Taken with the census at window close, so digest and occupancy share one DOM read."""want_raw = bool(self.base_args.get("parity_raw"))try:return self.page.evaluate("(raw) => window.__sb.parity.capture({ raw })", want_raw)diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_copy_confirmed_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_copy_confirmed_live.pyindex d8ebda0f276..a4e07ffb6e5 100644--- a/tests/studio/studiobench/scene/selftest/test_studiobench_copy_confirmed_live.py+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_copy_confirmed_live.py@@ -93,14 +93,12 @@ def _ctx(page, log = None) -> ActionContext:def _swallow_the_copy(page) -> None:- """An engine that does not copy, reproduced faithfully: the keystroke is delivered, a `copy`- event fires, and nothing reaches the clipboard."""+ """A non-copying engine: the copy event fires, yet nothing reaches the clipboard."""page.evaluate("() => document.addEventListener('copy', (e) => { e.preventDefault(); }, true)")def test_a_real_copy_is_still_measured(page):- """THE CONTROL. Without it the guard could refuse everything and the tests below would pass on- an action that never reports a timing at all."""+ """Control: a real copy must still be measured, or the guard could refuse everything."""got = A.select_all_copy(_ctx(page))assert got.ran is True, got.reasonassert got.timings.get("copy_ms") is not None@@ -108,8 +106,7 @@ def test_a_real_copy_is_still_measured(page):def test_an_engine_that_does_not_copy_is_NOT_RUN_rather_than_a_timing(page):- """THE DEFECT. The keystroke is sent, 250ms passes, and before this the action returned that- 250ms as `copy_ms` -- stable, plausible, and about nothing."""+ """A non-copying engine must be NOT RUN, never the 250ms settle returned as `copy_ms`."""_swallow_the_copy(page)got = A.select_all_copy(_ctx(page))assert got.ran is False, got@@ -119,8 +116,7 @@ def test_an_engine_that_does_not_copy_is_NOT_RUN_rather_than_a_timing(page):def test_the_refusal_says_the_number_would_have_been_the_harness_own_settle(page):- """The reason has to name the failure, or the next person reads NOT RUN as a flaky run and adds- the action to an allow-list."""+ """The reason must name the failure, or NOT RUN is read as flakiness and allow-listed."""_swallow_the_copy(page)said: list[str] = []got = A.select_all_copy(_ctx(page, said.append))@@ -153,9 +149,8 @@ def test_a_failed_sentinel_write_does_not_re_admit_the_unchanged_clipboard(page)def test_a_real_copy_is_still_measured_when_the_sentinel_could_not_be_written(page):- """THE CONTROL FOR THE ABOVE. The fallback must not turn a missing write permission into a dead- action: a copy that really happened is still a measurement, and the row says which pre-copy- value it was confirmed against."""+ """Control for the fallback: a missing write permission must not kill the action; a real copy is+ still measured, and the row names the pre-copy value it was confirmed against."""page.evaluate("async () => await navigator.clipboard.writeText('stale')")_refuse_the_sentinel_write(page)got = A.select_all_copy(_ctx(page))diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_delete_on_the_action_bar.py b/tests/studio/studiobench/scene/selftest/test_studiobench_delete_on_the_action_bar.pyindex e0666932b66..1b8d851c4b6 100644--- a/tests/studio/studiobench/scene/selftest/test_studiobench_delete_on_the_action_bar.py+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_delete_on_the_action_bar.py@@ -190,8 +190,7 @@ def _assistant_bar_source(tsx: str) -> str:def test_every_control_the_scene_asks_for_is_still_rendered():- """Bar buttons by their tooltip, menu items by their text, read out of what the assistant- message's action bar renders in thread.tsx."""+ """Buttons by tooltip, menu items by text, from the assistant action bar in thread.tsx."""tsx = _assistant_bar_source(THREAD_TSX.read_text(encoding = "utf-8"))buttons, items = _names_the_scene_asks_for()assert {diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_follow_coverage_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_follow_coverage_live.pyindex b396d652b0c..98cfdc89cb0 100644--- a/tests/studio/studiobench/scene/selftest/test_studiobench_follow_coverage_live.py+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_follow_coverage_live.py@@ -121,9 +121,8 @@ def test_the_sampler_scores_a_pinned_stream(page):def test_returning_to_the_end_reattaches_so_the_rest_of_the_stream_is_still_scored(page):- """THE DEFECT. A deliberate scroll used to detach the sampler permanently, so every sample for- the remainder of the stream -- and for every later stream in the cell -- was scored against the- second half of the contract and contributed nothing to the verdict."""+ """Returning to the end must reattach the sampler; a deliberate scroll must not detach it for+ good, or later samples go unscored."""_start_at_bottom(page)_settle(page)before = _read(page)["running_samples"]@@ -191,8 +190,7 @@ def test_the_coverage_travels_with_the_verdict(page):)-# The film's gesture never ends at the bottom, so re-attachment comes from a new run the user-# started, not from resume().+# The gesture never ends at the bottom; re-attach comes from a new user run, not resume().def _end_run(page) -> None:diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_hover_reveal_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_hover_reveal_live.pyindex 4785e8a67ff..5a35e516dac 100644--- a/tests/studio/studiobench/scene/selftest/test_studiobench_hover_reveal_live.py+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_hover_reveal_live.py@@ -99,8 +99,7 @@ def _ctx(page, log = None) -> ActionContext:def test_the_control_really_is_unreachable_until_it_is_hovered(page):- """WITHOUT THIS THE REST PROVES NOTHING. If the fixture's button were hit-testable at rest,- every assertion below would pass with or without the fix."""+ """If the button were hit-testable at rest, every assertion passes either way."""box = page.eval_on_selector(SELECTOR, "(el) => el.getBoundingClientRect().toJSON()")assert round(box["width"]) == 20 and round(box["height"]) == 20, "the fixture lost its geometry"style = page.eval_on_selector(@@ -125,8 +124,7 @@ def test_hovering_reveals_the_control_and_returns_a_point_on_it(page):def test_the_action_clicks_the_control_instead_of_substituting_a_navigation(page):- """The action clicks the control rather than substituting page.goto, which thread_reopen would- refuse."""+ """The action clicks the control rather than page.goto, which thread_reopen would refuse."""got = A._click_or_navigate(_ctx(page), SELECTOR, FALLBACK_URL)assert got.path == "click", got.reasonassert got.navigated is False@@ -134,8 +132,7 @@ def test_the_action_clicks_the_control_instead_of_substituting_a_navigation(pagedef test_the_hover_is_reported_so_the_gesture_is_not_silent(page):- """A harness that quietly does something extra to make a control work is how the last defect- got in. The reveal is logged."""+ """Quiet extra steps that make a control work hid the last defect; the reveal is logged."""said: list[str] = []A._click_or_navigate(_ctx(page, said.append), SELECTOR, FALLBACK_URL)assert any("hover-revealed" in m for m in said), said@@ -159,9 +156,8 @@ def test_an_ordinary_control_is_not_hovered_first(page):def test_a_genuinely_unreachable_control_is_still_reported_unreachable(page):- """The fix must not become a way of clicking things a user cannot click. A control covered by- a real overlay stays unreachable after hovering, and the navigation fallback is taken with the- reason saying so."""+ """The fix must not click what a user cannot: a control under a real overlay stays unreachable+ after hovering, and the navigation fallback is taken with the reason saying so."""page.evaluate("() => { const d = document.createElement('div');"" d.style.cssText = 'position:fixed;inset:0;z-index:9;background:#000';"diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_observation_cost.py b/tests/studio/studiobench/scene/selftest/test_studiobench_observation_cost.pyindex 5d8807aa333..322d12cced3 100644--- a/tests/studio/studiobench/scene/selftest/test_studiobench_observation_cost.py+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_observation_cost.py@@ -228,8 +228,7 @@ def test_it_waits_for_a_generating_reply_instead_of_reporting_no_menu():def test_a_reply_that_never_lands_is_reported_honestly_rather_than_waited_on_forever():- """The wait is bounded by the slot's own budget: a reply that never finishes must not swallow- the rest of the film."""+ """Waits capped by the slot budget; a reply that never lands must not swallow the film."""page = _RunningPage(runs_for = 10_000)assert A._wait_for_the_reply_to_land(_running_ctx(page, budget_ms = 200)) is Falsediff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.pyindex 8dfa2b96d6f..21fd8bcbd69 100644--- a/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.py+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.py@@ -462,9 +462,8 @@ def test_a_composer_regression_between_two_settled_arms_is_reported(page):def test_a_finished_against_a_running_arm_is_still_refused_after_that(page):- """And the suppression this must not cost: `streaming` disagrees, so the run state itself says- the two arms were at different points in one turn and the composer is not evidence of a- change."""+ """The suppression must not cost this case: streaming disagrees, so the arms were at different+ points of one turn and the composer is not evidence of a change."""base = _capture_html(page, _page(tail = "arrived at last", **_finished()))treat = _capture_html(page, _page(tail = "arr", **_writing()))assert base["streaming"] is False and treat["streaming"] is True@@ -493,9 +492,8 @@ def test_a_dispatched_queue_wait_is_a_run_state_not_a_rendering_difference(page)def test_the_queued_idle_arm_against_a_settled_one_is_still_refused(page):- """The other legitimate suppression: `isRunning()` cannot separate queued-idle from settled, so- `queued_idle` is what carries this pair. Without it the Queue button would read as a- regression."""+ """`isRunning()` cannot tell queued-idle from settled, so the `queued_idle` flag carries this+ pair; without it the Queue button would read as a regression."""base = _capture_html(page, _page(tail = "same", **QUEUED_IDLE))treat = _capture_html(page,@@ -561,9 +559,8 @@ def test_a_queue_control_missing_from_the_selector_list_is_not_a_css_regression(def test_a_real_style_regression_between_two_arms_in_one_run_state_is_still_reported(page):- """THE COVERAGE THIS MUST NOT COST. Same control on both arms, and the treatment hides the- viewport from CSS alone -- no structural trace whatever, which is the only thing this probe- exists to see."""+ """Coverage must not cost: same control on both arms; treatment hides the viewport via CSS alone+ with no structural trace, which is what this probe exists to see."""base = _capture_html_raw(page, _page(tail = "same", **_finished()))treat = _capture_html_raw(page,@@ -577,9 +574,8 @@ def test_a_real_style_regression_between_two_arms_in_one_run_state_is_still_repodef test_a_composer_that_lost_its_control_is_still_a_style_finding(page):- """AND THE SUPPRESSION IS NOT KEYED ON THE COMPOSER TOKEN ALONE. The treatment simply has no- Send button: the token differs, the probe matches one element fewer, and the run state agrees- on both independent readings -- so this is a rendering regression and it is reported."""+ """Suppression is not keyed on the composer token alone: a missing Send button changes the token+ and probe count, but agreeing run states still report it as a regression."""base = _capture_html_raw(page, _page(tail = "same", **_finished()))treat = _capture_html_raw(page,diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_settle_js.py b/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_settle_js.pyindex 4767ae73cff..adf306e3526 100644--- a/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_settle_js.py+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_settle_js.py@@ -226,8 +226,7 @@ def test_losing_the_state_restarts_the_streak():def test_the_timing_includes_the_click_dispatch_it_names():- """open_ms must include the click dispatch as well as the settle wait, or slower handlers look- faster."""+ """open_ms includes the click dispatch and settle wait, or slower handlers look faster."""out = run_settle(flip_frame = 2, mount_done_frame = 3, spans_static = True, click_ms = 40.0)dispatch = PANES * 40.0assert out["openDispatchMs"] == dispatchdiff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_settling.py b/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_settling.pyindex d24eeb50ead..63862058cf2 100644--- a/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_settling.py+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_settling.py@@ -13,8 +13,7 @@ from tests.studio.studiobench.scene.actions import reasoning_toggle@dataclassclass _Page:- """Stub page returning a canned reply; accepts both the old timeoutMs and the new pair argument- shape."""+ """Stub page with a canned reply; accepts old timeoutMs and new pair argument shapes."""reply: dictlast_arg: Any = Nonediff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_stop_slot_budget.py b/tests/studio/studiobench/scene/selftest/test_studiobench_stop_slot_budget.pyindex d94b051e935..b760a3767d1 100644--- a/tests/studio/studiobench/scene/selftest/test_studiobench_stop_slot_budget.py+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_stop_slot_budget.py@@ -397,9 +397,8 @@ def test_no_moment_the_turn_can_start_lets_the_action_spend_the_next_slot(@pytest.mark.parametrize("scene", [FAST, QUICK, STANDARD], ids = lambda s: s.name)def test_a_reply_that_drains_early_still_gets_its_throwaway_turn(monkeypatch, scene):- """THE CONTROL. The reserve must not turn the wait into a refusal: a marginally slow drain is- what it was written for, and the fast film opens this slot only 400 ms after the worst-case- drain on the ladder. A reply that finishes 500 ms in must still be stopped and measured."""+ """The reserve must not refuse a marginally slow drain: this slot opens 400 ms after the+ worst-case drain, so a reply that finishes 500 ms in must still be stopped and measured."""stop, _nxt, _slack = _stop_slot(scene)result, page = _run(monkeypatch, budget_ms = stop.budget_ms, drain_after_ms = 500)@@ -413,9 +412,8 @@ def test_a_reply_that_drains_early_still_gets_its_throwaway_turn(monkeypatch, sc@pytest.mark.parametrize("scene", [FAST, QUICK, STANDARD], ids = lambda s: s.name)def test_nothing_running_at_the_slot_still_gets_its_throwaway_turn(monkeypatch, scene):- """THE SECOND CONTROL, and the path every unmodified run takes: with the pinned tail the reply- is long finished when this slot opens, the drain wait is never entered, and the turn has the- whole budget. It must still be sent, stopped and cleaned up on every film."""+ """Second control: unmodified runs skip the drain wait, since the pinned tail has finished; the+ turn still gets sent, stopped and cleaned up on every film."""stop, _nxt, _slack = _stop_slot(scene)clock = _Clock()diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_thread_reopen_gate.py b/tests/studio/studiobench/scene/selftest/test_studiobench_thread_reopen_gate.pyindex c59d9eb73e0..034827a5d21 100644--- a/tests/studio/studiobench/scene/selftest/test_studiobench_thread_reopen_gate.py+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_thread_reopen_gate.py@@ -90,8 +90,7 @@ class _ThreadPage:return {"thread": self.mounted, "gone": 0}.get(self.phase, self.frame.mounted)def _probe(self) -> dict:- """Mounted rows are numbered as a window anchored at the end, setsize - mounted + 1 through- setsize."""+ """Mounted rows: ordinals setsize - mounted + 1 through setsize, anchored at the end."""self.probes += 1f = self.framemounted = self.message_count()@@ -234,9 +233,8 @@ def test_refusing_the_substitute_does_not_refuse_the_click():def test_the_default_still_navigates_for_every_other_caller():- """The signature gained a keyword and must not have changed what anyone else gets. The reopen- half of `thread_reopen` depends on this: from an empty new chat the navigation is what puts the- thread back for the slots that follow."""+ """The new keyword must leave the default unchanged for other callers; thread_reopen depends on+ it, since from an empty new chat navigation is what puts the thread back."""page = _ThreadPage(unclickable = {NEW_CHAT})got = A._click_or_navigate(_ctx(page), NEW_CHAT, NEW_CHAT_URL)@@ -297,9 +295,8 @@ def test_the_row_carries_the_gate_the_timing_was_taken_against():def test_a_thread_that_declares_its_total_and_never_rebuilds_gets_no_timing(monkeypatch):- """The old condition's worst case, and the one that made the defect invisible: the store- publishes eighteen, three rows mount, nothing else ever arrives. That was scored as a fast- re-open. It is now a run with no timing and the outstanding condition named."""+ """The old worst case: the store declares eighteen, three rows mount, nothing else arrives; that+ was scored as fast, now it gets no timing and names the outstanding condition."""monkeypatch.setattr(A, "_REOPEN_READY_CEILING_S", 0.4)page = _ThreadPage(frames = STALLED)result = A.thread_reopen(_ctx(page))@@ -315,9 +312,8 @@ def test_a_thread_that_declares_its_total_and_never_rebuilds_gets_no_timing(monkdef test_a_windowed_arm_is_held_to_the_windowed_gate_and_not_to_a_full_mount():- """The other way this fix could have been wrong. A windowed arm never mounts every message, so- waiting for a full mount would time out on the arm the whole comparison exists to score. The- mode is read from the mount the action LEFT, exactly as the cell's opening gate read it."""+ """A windowed arm never mounts every message, so a full-mount wait would time out; the mode is+ read from the mount the action left, as the cell's opening gate reads it."""page = _ThreadPage(frames = WINDOWED, mounted = 6, total = TOTAL)result = A.thread_reopen(_ctx(page))diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_visible_blind_probe_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_visible_blind_probe_live.pyindex e7d46aec265..0ca2012110c 100644--- a/tests/studio/studiobench/scene/selftest/test_studiobench_visible_blind_probe_live.py+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_visible_blind_probe_live.py@@ -193,8 +193,7 @@ def test_a_lost_conversation_is_still_a_finding_while_a_reply_runs(browser):assert "DIFFERENT MESSAGES on screen" in got["reason"]-# User rows and rows whose role changed do not depend on stream progress, so they must still-# be reported instead of being swallowed by the blind-probe refusal.+# User rows and role changes ignore stream progress, so the blind refusal must not hide them.def test_a_changed_user_row_survives_the_blind_refusal(browser):@@ -253,17 +252,15 @@ def test_a_windowed_arm_that_unmounted_the_live_row_is_not_read_as_blind(browserdef test_a_windowed_arm_is_still_caught_when_the_hook_itself_is_gone(browser):- """The narrowing is not a hole. A missing ROW explains a quiet scan; a missing ATTRIBUTE does- not, because the settled rows would still be publishing it."""+ """No hole: a missing row explains a quiet scan; settled rows still publish the attribute."""cap = _capture(browser, **dict(_BLIND_ATTR, drop_tail = True))assert cap["status_hook_present"] is Falseassert cap["in_flight_unplaced"] is True, capdef test_a_full_mount_is_still_caught_when_only_the_STATUS_VALUE_changed(browser):- """And the reverse: on a full mount the row cannot be missing, so a quiet scan is blindness- even though the attribute is still there. This is the case a hook-presence test alone would- have lost, and it is the likelier build change of the two."""+ """On a full mount no row can be missing, so a quiet scan is blindness even with the attribute+ present; a hook-presence test alone would miss this likelier change."""cap = _capture(browser, **_BLIND)assert cap["status_hook_present"] is Trueassert cap["in_flight_unplaced"] is True, capdiff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_visible_capture_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_visible_capture_live.pyindex 53642d70bd5..c330ea58811 100644--- a/tests/studio/studiobench/scene/selftest/test_studiobench_visible_capture_live.py+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_visible_capture_live.py@@ -110,8 +110,7 @@ def test_it_reports_only_what_the_viewport_showed(page):def test_a_partly_visible_message_counts_as_visible(page):- """One pixel of message 2 inside the viewport. A threshold that rounded this away would exempt- real differences at the top and bottom of the screen."""+ """One pixel of message 2 counts; rounding away would exempt top and bottom differences."""_watch(page)page.evaluate("() => { document.getElementById('vp').scrollTop = 101; }")got = _capture(page)@@ -119,8 +118,7 @@ def test_a_partly_visible_message_counts_as_visible(page):def test_the_compared_set_is_the_union_across_the_whole_action(page):- """The scroll passes over messages 1 to 8 and lands showing 7 and 8. A single sample at the- close would report two; the user saw eight."""+ """A scroll over messages 1 to 8 must count all eight, not the two visible at the close."""_watch(page)for top in (0, 700, 1400, 2100, 2800, 3200):page.evaluate(f"() => {{ document.getElementById('vp').scrollTop = {top}; }}")@@ -132,9 +130,8 @@ def test_the_compared_set_is_the_union_across_the_whole_action(page):def test_a_message_mounted_mid_action_is_observed_too(page):- """A windowed list mounts rows as it scrolls. Rows that appear after the observer was installed- have to be picked up, or a windowed arm reports only what it happened to have mounted at the- start and the comparison silently shrinks to nothing."""+ """A windowed list mounts rows as it scrolls; rows appearing after the observer is installed+ must be picked up, or the comparison silently shrinks to the start-time rows."""page.evaluate("() => window.__build(2)")_watch(page)page.evaluate("() => window.__build(20)")@@ -247,8 +244,7 @@ def test_a_row_mounted_during_the_action_is_still_picked_up_cheaply(page):assert 3 in got["ever_visible"], got["ever_visible"]-# Readiness accepts ordinals on the message or an ancestor row, so the digest must ignore where-# they are published or such arms differ on every message.+# Digest must ignore where ordinals sit, on the message or an ancestor, or all rows differ.def _arm_html(ordinals: str, suffix: str = "") -> str:@@ -332,8 +328,7 @@ def test_ordinals_on_the_message_do_not_make_every_message_differ(browser):def test_ordinals_on_the_row_wrapper_are_unaffected_as_they_always_were(browser):- """The other permitted placement, which was never inside the message's subtree and so was never- part of the defect. It must stay comparable."""+ """Ordinals on the row wrapper were never part of the defect and must stay comparable."""from studiobench.analysis import parity as Passert (P.compare_visible(_capture_arm(browser, "nowhere"), _capture_arm(browser, "on_the_row"))[@@ -465,9 +460,8 @@ def test_placing_a_batch_of_rebuilt_rows_costs_ONE_document_read_for_the_batch(bdef test_a_row_that_publishes_its_ordinal_costs_no_document_read_at_all(browser):- """A windowed arm mounts rows continuously as it scrolls, and it is the arm that would pay- most for a document read per batch. It publishes `aria-posinset`, which is read first and- answers the question outright, so it never reaches the position index."""+ """A windowed arm mounts rows continuously and would pay most for a document read per batch;+ rows publishing `aria-posinset` are read first and never reach the position index."""pg = browser.new_page(viewport = {"width": 800, "height": 600})pg.set_content(FIXTURE)pg.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))@@ -506,8 +500,7 @@ def test_the_structural_digest_still_sees_the_ordinals(browser):assert all(numbered[i] != plain[i] for i in numbered), (numbered, plain)-#: `__churn` mounts and unmounts a row in one task so it is observed detached; `__remount` reuses-#: the same node, as a recycling virtualizer does.+# `__churn` mounts and unmounts a row in one task, observed detached; `__remount` reuses it.RECYCLE_FIXTURE = """<!doctype html><meta charset="utf-8">diff --git a/tests/studio/studiobench/scene/surface_sweep.py b/tests/studio/studiobench/scene/surface_sweep.pyindex 5d3d3b0919e..df1a8f78ad3 100644--- a/tests/studio/studiobench/scene/surface_sweep.py+++ b/tests/studio/studiobench/scene/surface_sweep.py@@ -23,8 +23,7 @@ def _log_noop(_msg: str) -> None:class _Driver:- """The step interpreter. One place that touches the browser, so the registry stays declarative- and the unit tests can read it with no browser installed."""+ """Step interpreter, the only browser-touching code, so the registry stays declarative."""def __init__(self, page: Any, base_url: str, log: Callable[[str], None]) -> None:self.page = pagediff --git a/tests/studio/studiobench/scene/surfaces.py b/tests/studio/studiobench/scene/surfaces.pyindex 861ef066eea..df83c9dd95d 100644--- a/tests/studio/studiobench/scene/surfaces.py+++ b/tests/studio/studiobench/scene/surfaces.py@@ -411,8 +411,7 @@ _SURFACES: list[Surface] = [group = "chat",title = "Composer holding text",reach = (("fill", COMPOSER, "studiobench surface sweep"), ("wait", 400)),- # With text in the box Stop is replaced by Queue.- # Must be one expression: the evaluator wraps it in `return (...)`.+ # With text in the box, Stop becomes Queue; must be one expression (wrapped in return).settle = {"js": "(document.querySelector(""'textarea[aria-label=\"Message input\"]') || {}).value ? true : false"diff --git a/tests/studio/studiobench/scoring/ab.py b/tests/studio/studiobench/scoring/ab.pyindex c8e6354a7b8..3433306c217 100644--- a/tests/studio/studiobench/scoring/ab.py+++ b/tests/studio/studiobench/scoring/ab.py@@ -73,8 +73,7 @@ class Pair:@staticmethoddef _divisible(measure: Measure) -> float | None:- """A measured zero is a reading; a sub-floor value uses the floor, giving a bound rather- than infinity."""+ """A zero is a reading; a sub-floor value uses the floor, a bound rather than infinity."""if not measure.has_reading:return Nonevalue = float(measure.value)@@ -264,8 +263,7 @@ def compare(is_null_control: bool = False,bootstrap_seed: int = 0,) -> AbResult:- """Raises on identity mismatch; returns a VOID result, not an error, when data cannot support a- claim."""+ """Identity mismatch raises; unsupported data yields a VOID result, not an error."""assert_comparable(identity_base, identity_treatment)diff --git a/tests/studio/studiobench/scoring/from_payload.py b/tests/studio/studiobench/scoring/from_payload.pyindex df16d5f0b14..f8e1eda19b8 100644--- a/tests/studio/studiobench/scoring/from_payload.py+++ b/tests/studio/studiobench/scoring/from_payload.py@@ -405,8 +405,7 @@ def measures_from_records(and str(w.get("kind") or "") not in UNSCORED_WINDOW_KINDS]frames = _frame_measures(windows)- # Not in METRIC_BY_KEY on purpose: anchors are hashed into `weights_id`, so adding one would- # make every existing run incomparable.+ # Anchors hash into `weights_id`; one added to METRIC_BY_KEY makes runs incomparable.stream = _stream_measures(windows)readings: dict[str, Measure] = {}diff --git a/tests/studio/studiobench/scoring/schema.py b/tests/studio/studiobench/scoring/schema.pyindex 344b9e7d9e6..017ce9c0397 100644--- a/tests/studio/studiobench/scoring/schema.py+++ b/tests/studio/studiobench/scoring/schema.py@@ -17,8 +17,7 @@ ZERO_OK_KEYS = frozenset("index",# parity.js numbers message rows from `i: 0`."i",- # Only the counters, not the `visible`/`wire` subtrees: a zero-char signature or zero- # `wireChars` must stay loud.+ # Only counters are exempt, not `visible`/`wire` subtrees; zero `wireChars` must fail."wire_parse_failures","wire_pending_chars","wire_parse_failures_in_window",@@ -192,8 +191,7 @@ class Measure:unit: str = "ms",floor: float | None = None,) -> "Measure":- """Reads the harness's flat <key>_attempted and <key>_reason siblings, so the bare-zero ban- holds."""+ """Reads flat <key>_attempted and <key>_reason siblings, so the bare-zero ban holds."""value = row.get(key)reason = row.get(f"{key}_reason")diff --git a/tests/studio/studiobench/scoring/score.py b/tests/studio/studiobench/scoring/score.pyindex 083243d4a27..ee707982fc9 100644--- a/tests/studio/studiobench/scoring/score.py+++ b/tests/studio/studiobench/scoring/score.py@@ -46,8 +46,7 @@ class MetricScore:def score_metric(anchor: MetricAnchor, measure: Measure) -> MetricScore:- """A missing reading is neither 0 nor 100, but is excluded from the mean and counted against- coverage."""+ """A missing reading is neither 0 nor 100: left out of the mean, counted against coverage."""if not measure.has_reading:reason = measure.note or ("not attempted" if not measure.attempted else "no reading")@@ -224,8 +223,7 @@ class LadderScore:def score_ladder(rungs: Sequence[RungScore]) -> LadderScore:- """Every declared rung must be passed in, complete or not, or a crash-beats-limp ladder slips- through."""+ """Pass every declared rung, complete or not, or a crash-beats-limp ladder slips through."""ordered = sorted(rungs, key = lambda r: r.tokens)weights = log_rung_weights([r.tokens for r in ordered])diff --git a/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.py b/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.pyindex b9f267bc678..7dda0adc79a 100644--- a/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.py+++ b/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.py@@ -278,9 +278,7 @@ def test_measures_by_cell_does_not_mix_readings_between_cells():def test_the_wire_integrity_counters_may_be_zero():- """Zero here is the GOOD outcome and the one that makes the denominator trustworthy: no SSE- frame failed to parse, and no unterminated frame was left buffered at the window's close. A- clean run tripped the bare-zero ban and no report could be built from it at all."""+ """Zero wire-integrity counters are the good outcome; a clean run must not trip the bare-zero ban."""validate_payload({"excluded_cells": [],@@ -295,9 +293,8 @@ def test_the_wire_integrity_counters_may_be_zero():def test_a_wire_character_count_of_zero_is_still_a_failure():- """The exemption is deliberately the counters and not the count. `wireChars` at zero means- nothing was ever counted, which is a broken instrument rather than a clean stream, and it must- stay loud."""+ """Exempt counters only, not the count: wireChars at zero means nothing was counted, a broken+ instrument that must stay loud."""with pytest.raises(PayloadSchemaError):validate_payload({"excluded_cells": [], "blk": {"wire_chars": 0}})@@ -401,8 +398,7 @@ def test_a_probe_payload_with_legitimate_zeros_still_validates():def test_the_same_probe_payload_without_the_attestation_is_still_refused():- """The exemption must come from the flag, not from the key names: an unattested zero is the- thing the walk exists to catch."""+ """Exemption comes from the flag, not the key names: an unattested zero is still refused."""cell = _cell()cell["click_attribution"] = {"code_token_spans": 0}with pytest.raises(PayloadSchemaError, match = "code_token_spans"):diff --git a/tests/studio/studiobench/scoring/selftest/test_studiobench_payload_rules.py b/tests/studio/studiobench/scoring/selftest/test_studiobench_payload_rules.pyindex a69cf2d38b0..b6ced7d30d7 100644--- a/tests/studio/studiobench/scoring/selftest/test_studiobench_payload_rules.py+++ b/tests/studio/studiobench/scoring/selftest/test_studiobench_payload_rules.py@@ -11,8 +11,7 @@ from tests.studio.studiobench.scoring import payload_rulesdef _ladder_payload() -> list[dict]:- """Fixture of the withdrawn headline run: 100K completes on both arms; the 1M treatment cell- does not."""+ """Withdrawn headline run: 100K completes on both arms; the 1M treatment cell does not."""rows: list[dict] = []for cell_id, n_windows, completed in (("r100K.base.rep0", 17, True),diff --git a/tests/studio/studiobench/scoring/selftest/test_studiobench_scoring.py b/tests/studio/studiobench/scoring/selftest/test_studiobench_scoring.pyindex babfc7c425e..32f38bb7e1a 100644--- a/tests/studio/studiobench/scoring/selftest/test_studiobench_scoring.py+++ b/tests/studio/studiobench/scoring/selftest/test_studiobench_scoring.py@@ -606,8 +606,7 @@ def test_an_improvement_to_zero_jank_is_bounded_the_other_way():def test_two_arms_below_the_floor_are_not_a_difference():- """score.py's reason, at the ratio layer: instrument noise on a fast machine must not invent- a difference between two perfect builds."""+ """Readings below the floor are not a difference: instrument noise must not invent one."""pair = _jank_pair(SMOOTH, Measure.read(0.02, "%", floor = JANK_FLOOR))@@ -618,8 +617,7 @@ def test_two_arms_below_the_floor_are_not_a_difference():def test_a_reading_that_was_never_taken_is_still_not_a_zero():- """THE LINE THIS MUST NOT CROSS. Both of these carry `value is None`, which is a different- thing from a measured zero, and neither may enter a ratio."""+ """Unmeasured and failed readings carry `value is None`, never a zero, and enter no ratio."""never = Measure.not_attempted("%", "no window had the frame recorder installed")failed = Measure.failed("%", "the recorder ran but exported no per-frame deltas")@@ -649,9 +647,7 @@ def test_a_zero_with_no_declared_floor_stays_unusable():def test_a_null_control_voids_on_jank_it_introduced_over_a_zero_base():- """The coupling. The null control decides whether this machine can tell two identical builds- apart; blind to the jank transition, it passed and published a floor derived from what was- left."""+ """A null control blind to the jank it introduced over a zero base passed and published a floor."""result = compare("null control: main vs itself",diff --git a/tests/studio/studiobench/scoring/selftest/test_studiobench_stream_metrics.py b/tests/studio/studiobench/scoring/selftest/test_studiobench_stream_metrics.pyindex 928414771e0..30489473ad8 100644--- a/tests/studio/studiobench/scoring/selftest/test_studiobench_stream_metrics.py+++ b/tests/studio/studiobench/scoring/selftest/test_studiobench_stream_metrics.py@@ -219,9 +219,7 @@ def test_an_unscoreable_window_does_not_reach_the_cost_per_character():def test_a_payload_recorded_before_the_flag_existed_is_scored_exactly_as_before():- """`is False`, not falsiness. Rows written before the instrument published the flag carry no- key at all, and voiding them would retro-actively delete every streaming metric this project- has already recorded."""+ """Missing flag means scored: check `is False`, not falsiness, so pre-flag rows are not voided."""w = _window("stream:gap1")assert "reply_chars_scoreable" not in w["instruments"]["stream_cost"]picked, rejected = _stream_windows([w])diff --git a/tests/studio/studiobench/sweep/floor_table.py b/tests/studio/studiobench/sweep/floor_table.pyindex 47252645882..3a082d74418 100644--- a/tests/studio/studiobench/sweep/floor_table.py+++ b/tests/studio/studiobench/sweep/floor_table.py@@ -63,8 +63,7 @@ def sessions_in(records: list[dict]) -> set[str]:def refuse_collisions(records: list[dict]) -> None:- """Refuse payloads where one cell completed under two sessions; pooling them averages contending- runs."""+ """Refuse cells completed in two sessions: pooling them averages contending runs."""collided = collided_cells(records)if not collided:return@@ -169,15 +168,12 @@ def concurrent_sessions(def cell_metrics(records: list[dict], session: str | None = None) -> dict[str, dict[str, float]]:- """Completed-cell metrics for one session; without one named, refuses cells completed in two- sessions."""+ """Refuses cells completed in two sessions unless a session is named (the escape hatch)."""if session is None:refuse_collisions(records)- # Drop superseded attempts (last attempt that wrote anything wins), except when `session=` is- # named, which is the escape hatch for concurrent sessions.+ # Last attempt that wrote anything wins; `session=` skips it for concurrent sessions.records = list(latest_attempt_rows(records))- # A cell that failed an invalidating gate is not a reading: those gates are advisory upstream,- # so such cells arrive completed with misleadingly cheap timings.+ # Gate-failed cells are not readings: upstream gates are advisory, so timings mislead.gate_failures = failed_invalidating_gates(records)out: dict[str, dict[str, float]] = {}@@ -357,8 +353,7 @@ def summarise(paths: list[Path]) -> dict[str, dict[str, float]]:if metric in DIFFERENCE_METRICS:# Same gates in the metric's own unit, so delta and spread are percentage points.diffs = [t - b for b, t in rows]- # A zero difference is a tie, not a disagreement: direction means no pair went the other way- # and at least one moved.+ # Zero difference is a tie: direction needs one moved pair and no reversed pair.nonzero = [d for d in diffs if d != 0.0]out[metric] = {"n": len(rows),diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_null_audit.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_null_audit.pyindex 2b10670a641..7ce3ae7b368 100644--- a/tests/studio/studiobench/sweep/selftest/test_studiobench_null_audit.py+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_null_audit.py@@ -585,8 +585,7 @@ def missed_slot_payload(tmp_path: Path, name: str, action: str, reps: tuple[str,def test_one_arm_missing_a_slot_in_every_repetition_is_still_not_a_build_difference(tmp_path):- # Slot misses are correlated through the runner, so corroboration cannot separate them from a- # build difference; `slot_missed` can.+ # Slot misses are correlated, so corroboration cannot separate them; `slot_missed` can.path = missed_slot_payload(tmp_path, "slow", "settings", ("rep0", "rep1"))assert U.report([path], "t", frozenset(), min_reps = 2, min_compared = 16) == 0@@ -1103,8 +1102,7 @@ def test_a_missing_composer_is_not_exempt_just_because_send_turn_can_be_queued(tassert U.report([gone], "t", U.UNSTABLE_ACTIONS, min_reps = 2, min_compared = 16) == 1-# In-flight pairs are NOT_COMPARABLE; `SETTLED_MATCH` counts them as observations only once-# scaffold, overlays, message set and every settled row agree.+# In-flight pairs are NOT_COMPARABLE; `SETTLED_MATCH` counts them only once all parts agree.def streaming_pair_rows(diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_parity_shots.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_parity_shots.pyindex e8dcd5ce655..258a841a5db 100644--- a/tests/studio/studiobench/sweep/selftest/test_studiobench_parity_shots.py+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_parity_shots.py@@ -309,8 +309,7 @@ def test_a_one_arm_miss_in_one_repetition_of_two_is_not_illustrated(tmp_path):def test_a_superseded_attempts_screenshot_is_not_shown_for_the_retrys_verdict(tmp_path):- # `--resume` re-runs a pair under the same cell id, so a raw scan could pair the retry's verdict- # with the dead attempt's shot.+ # `--resume` reuses the cell id, so a raw scan pairs a retry's verdict with the old shot.shots = tmp_path / "shots"png(shots / "old.png", 200, 120, (10, 60, 10))png(shots / "base.png", 200, 120, (10, 60, 10))@@ -461,8 +460,7 @@ def test_two_shards_do_not_share_one_screenshot_identity(tmp_path):assert before.read_bytes() == (shots / f"{shard}_base_{rep}.png").read_bytes()-# First-party imports of a measured route deliberately not gated on, with reasons. Every-# import must be either in the workflow or here.+# Imports not gated on, each with a reason; every import must be in the workflow or here.NOT_GATED: dict[str, str] = {"studio/backend/auth/authentication.py": "session plumbing shared by every route in the app; ""routes/auth.py already gates the endpoints studiobench actually calls",diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.pyindex 2b57988924b..a552151f896 100644--- a/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py@@ -769,8 +769,7 @@ def test_instability_measured_at_a_rung_still_silences_that_rung(tmp_path):def test_a_declared_unstable_action_still_holds_at_every_rung(tmp_path):- # Declared entries are action properties, not rung-scoped.- # Exit 2, not 1: the only pair was filed as expected variation, so no verdict was produced.+ # Declared actions hold at every rung. Exit 2, not 1: the only pair is expected variation.rows = [{"row_type": "run_meta", "tier": "standard"}]rows.append(parity_action("r1K.base.rep0", "stop_generation", "A"))rows.append(parity_action("r1K.treatment.rep0", "stop_generation", "B"))@@ -801,8 +800,7 @@ def resumed_parity(tmp_path: Path, name: str, retry_session: str) -> Path:def test_a_resumed_arm_is_not_paired_with_its_partner_from_the_old_session(tmp_path):- # A resumed dead arm runs under a new session id, so session-scoped volatiles look like arm- # differences.+ # Resumed arms get a new session id, so session-scoped volatiles look like differences.null = resumed_parity(tmp_path, "null_resumed", "s2")unstable, _derived, _checks = U.unstable_set([null])assert ("r100K", "settings") not in unstable@@ -1026,13 +1024,8 @@ def probe_payload(tmp_path: Path, name: str, script: str | None) -> Path:def test_a_payload_recorded_with_a_probe_installed_is_refused(tmp_path):- """The instrument was in the shot. There is no flag to override it.-- A probe samples the DOM on its own schedule and forces layout to do it, so the timings are a- measurement of the page AND the instrument. Without this the run looks entirely ordinary: it- records the same cells and renders the same A/B table, and only the caller's memory stops the- numbers being quoted.- """+ """A probe installed while recording is refused, with no override flag: the timings measure the+ probe as well as the page."""path = probe_payload(tmp_path, "probed", "arms/content_visibility_probe.js")with pytest.raises(SystemExit) as excinfo:F.load([path])@@ -1235,8 +1228,7 @@ def test_the_documented_loop_asserts_liveness_before_it_reads_any_timing():def test_floor_table_prints_a_clean_verdict_from_a_run_that_liveness_voids(tmp_path, capsys):- # `paired` matches only metrics both arms recorded, so a missed slot leaves only a smaller `n`- # and the survivors look like a clean win.+ # A missed slot leaves `paired` a smaller `n`, so the survivors look like a clean win.mine = liveness_payload(tmp_path, "mine", [(1000.0, 900.0), (1000.0, 900.0), (1000.0, 900.0), (1000.0, None)])diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_windowed_parity.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_windowed_parity.pyindex a72a612e610..19250b63c62 100644--- a/tests/studio/studiobench/sweep/selftest/test_studiobench_windowed_parity.py+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_windowed_parity.py@@ -74,8 +74,7 @@ def test_not_applicable_is_not_folded_into_a_pass_or_a_fail():def test_two_full_mounts_are_still_compared_exactly_as_before():- """The refusal must not leak into a normal pair. Same digest is still MATCH, different is- still DIFFER, and the windowed machinery is invisible to both."""+ """Two full mounts compare exactly as before: same digest is MATCH, different is DIFFER."""same = P.compare(_capture(18, 18, "x"), _capture(18, 18, "x"))assert same["verdict"] == P.MATCHdiffer = P.compare(_capture(18, 18, "x"), _capture(18, 18, "y"))@@ -109,8 +108,7 @@ def test_the_scroll_extent_invariant_passes_a_virtualizer_that_sizes_its_spacersdef test_the_scroll_extent_invariant_fails_a_virtualizer_that_simply_drops_rows():- """A scrollbar that says the thread is a third of its real length is a user-visible defect,- and it is the failure mode a windowed mount invites first."""+ """A scrollbar too short for its thread is a user-visible defect that windowing invites."""base = _row("select_text", _capture(18, 18), selected_chars = 100, visible_chars = 100)treat = _row("select_text", _capture(6, 18), selected_chars = 100, visible_chars = 100)treat["census"]["viewport_scroll_height"] = 3_300@@ -319,9 +317,7 @@ def test_a_timed_out_rebuild_leaves_the_behavioural_run_with_no_verdict(tmp_pathdef test_an_action_with_no_declared_invariant_is_unchecked_and_not_a_pass():- """The scroll extent is a property of the THREAD and holds identically on all eighteen- actions. Letting it carry an action to a pass would report `model_change` as verified on a- windowed arm when nothing about `model_change` was looked at."""+ """Scroll extent is a property of the thread, so it must not carry an undeclared action to a pass."""base = _row("model_change", _capture(18, 18))treat = _row("model_change", _capture(6, 18))got = B.compare_behaviour(base, treat)@@ -352,8 +348,7 @@ def test_an_action_that_did_not_run_is_not_scored_at_all():def test_every_named_first_to_break_action_has_an_invariant():- """The five the brief names as the ones that break first. An entry silently missing from the- table would make that action UNCHECKED, which reads as clean."""+ """Each first-to-break action needs an invariant; a missing one reads as clean."""for action in ("select_all_copy","select_text",@@ -494,8 +489,7 @@ def test_a_style_probe_that_matched_no_elements_does_not_report_a_match():def test_one_arm_scanning_nothing_is_also_not_a_difference_to_report():- """It is a broken probe, not a finding about the build, and saying DIFFER here would send- somebody looking for a UI change that nobody has evidence for."""+ """One arm scanning nothing is a broken probe, not a build difference: NOT_COMPARABLE."""verdict, _reason = P.compare_styles(_styled(0), _styled(12))assert verdict == P.NOT_COMPARABLE@@ -551,9 +545,7 @@ def test_markdown_source_against_rendered_text_is_not_treated_as_a_difference():def test_without_a_fully_mounted_arm_there_is_no_reference_and_no_verdict():- """The reference is the thread's visible text as measured by an arm that has all of it. If- neither arm mounts everything, nobody in this payload knows how long the conversation is, and- that is reported rather than guessed."""+ """With no fully mounted arm there is no reference, so no verdict; the gap is reported, not guessed."""base = _copy_row(_capture(9, 18), clipboard = 190_000, selected = 118_000, mounted = 9)treat = _copy_row(_capture(9, 18), clipboard = 190_000, selected = 118_000, mounted = 9)got = B.compare_behaviour(base, treat)@@ -620,8 +612,7 @@ def test_an_action_that_differs_against_an_identical_build_is_not_counted_againsdef test_a_real_visible_difference_outside_the_floor_still_fails(tmp_path):- """The floor must not become a way of passing anything. An action the null never saw differ is- still a failure."""+ """The floor must not pass everything: an action the null never saw differ still fails."""from studiobench.sweep import ui_parity as Unull = _visible_shard(tmp_path, "null2", differ_actions = {"b"})@@ -815,8 +806,7 @@ def test_a_visible_message_that_could_not_be_digested_is_printed_and_not_counteddef test_a_run_where_nothing_could_be_digested_carries_no_visible_verdict(tmp_path, capsys):- """Every pair carrying a residue means every pair was refused, and a mode that refused- everything has no verdict to report. 2, not 0."""+ """If every pair carries a residue, none was digested: no verdict, exit 2, not 0."""from studiobench.sweep import ui_parity as Urows = [@@ -1080,9 +1070,7 @@ def _one_sided_shard(def test_a_declared_windowed_arm_with_no_row_is_not_scored_structurally(tmp_path):- """THE ONE-SIDED HOLE. The declaration fallback was read off the rows the pair HAS, so an arm- that failed before emitting an action row was never asked about: the loop saw the base row,- found no declaration for the base arm, and classified the pair structural."""+ """A declared arm that emitted no action row must still be checked, not classed structural."""from studiobench.sweep import ui_parity as Ushard = _one_sided_shard(tmp_path, "one_sided")@@ -1113,9 +1101,7 @@ def test_a_windowed_cell_row_declares_the_arm_even_when_that_arm_has_no_action_rdef test_a_missing_windowed_arm_does_not_exit_zero_on_the_strength_of_the_other_rung(tmp_path, capsys):- """THE CONSEQUENCE. The fully mounted 1K pair supplies `matched > 0`, the 100K pair is filed as- structurally NOT COMPARABLE, and the command exits 0 -- having never run a windowed report for- the rung whose treatment arm produced nothing at all."""+ """A missing windowed arm must not exit 0 on the strength of another rung's matches."""from studiobench.sweep import ui_parity as U_one_sided_shard(tmp_path, "one_sided_main")@@ -1221,8 +1207,7 @@ def _held_invariant_pair(cell_suffix = "rep0"):def test_a_cell_that_lost_messages_gets_no_behavioural_pass_either(tmp_path, capsys):- """The behavioural invariants are what REPLACE the digest on a windowed arm, so a pass here is- the whole UI verdict for that pair."""+ """A cell that lost messages gets no behavioural pass; invariants replace the digest."""from studiobench.sweep import ui_parity as Urows = [_completeness_gate("r100K.treatment.rep0", False)] + _held_invariant_pair()@@ -1286,8 +1271,7 @@ def test_a_complete_cell_still_earns_its_behavioural_pass(tmp_path, capsys):def test_a_cell_whose_completeness_gate_PASSED_is_scored_exactly_as_before(tmp_path, capsys):- """The positive control. A refusal that fires on every cell measures nothing, and the shipped- build passes this gate on every cell it runs."""+ """A passing completeness gate must still score: a refusal on every cell measures nothing."""from studiobench.sweep import ui_parity as Urows = [_completeness_gate("r100K.treatment.rep0", True)] + _matching_pair()@@ -1572,8 +1556,7 @@ def test_a_successful_resume_clears_the_dead_attempts_completeness_failure(tmp_pdef test_a_resume_that_failed_again_is_still_refused(tmp_path):- """The positive control: scoping the gate to the surviving attempt must not lose a real- refusal when the retry failed too."""+ """A resume whose retry also failed is still refused when scoped to the surviving attempt."""from studiobench.sweep import ui_parity as Ushard = _resumed_completeness_shard(tmp_path, "resumed_bad", retry_passes = False)@@ -1668,9 +1651,7 @@ def test_the_coverage_floor_applies_to_a_run_with_no_fully_mounted_pair(tmp_pathdef test_the_coverage_floor_passes_a_windowed_run_that_compared_enough(tmp_path, capsys):- """THE POSITIVE CONTROL, and it is the half that matters most here: a floor that fires on- everything is not a floor. The same shape as above with the floor set beneath what the run- actually compared has to come out 0, or the test above would pass against a `return 3`."""+ """Positive control: a floor set beneath what the run compared must give 0, or `return 3` passes."""from studiobench.sweep import ui_parity as U_windowed_only_shard(tmp_path, "winenough", pairs = 4)@@ -1742,9 +1723,8 @@ def test_the_coverage_floor_is_checked_per_payload_pattern(tmp_path, capsys):def test_a_floor_each_film_clears_on_its_own_still_passes(tmp_path, capsys):- """THE POSITIVE CONTROL for the one above: per-pattern must not mean every multi-payload run- fails. Two films of 2 pairs each against a floor of 2 is 0, or the test above would pass- against an unconditional `return 3`."""+ """Per-pattern floors must not fail every multi-payload run: two 2-pair films each clear a floor+ of 2."""from studiobench.sweep import ui_parity as U_windowed_only_shard(tmp_path, "filmA", pairs = 2)diff --git a/tests/studio/studiobench/sweep/ui_parity.py b/tests/studio/studiobench/sweep/ui_parity.pyindex f6855658519..7cf34b838af 100644--- a/tests/studio/studiobench/sweep/ui_parity.py+++ b/tests/studio/studiobench/sweep/ui_parity.py@@ -73,8 +73,7 @@ MODE_WINDOWED = "windowed"#: Written by `record_completeness_gate` when the arm may have lost messages.COMPLETENESS_GATE = "thread_complete"-#: Written when the thread did not stay pinned through the stream; an unmounted reply costs-#: nothing to render.+# Written when the thread lost its pin through the stream; unmounted replies render nothing.FOLLOW_GATE = "follows_the_stream"#: A gate that only qualifies one column (`timer_clamp`) is deliberately NOT here.@@ -1509,8 +1508,7 @@ def corroborated(entries: list[tuple], min_reps: int) -> tuple[list[tuple], listby_action[(entry[0], rung_of_cell(entry[2]), direction)].append(entry)firm, weak = [], []for group in by_action.values():- # Distinct repetitions, deliberately not keyed on shard: a film recorded twice in two shards- # would otherwise let one flake corroborate itself.+ # Keyed by repetition, not shard, so one film in two shards cannot corroborate itself.reps = {e[2] for e in group}(firm if len(reps) >= min_reps else weak).extend(group)return firm, weak@@ -1589,8 +1587,7 @@ def swapped_between_arms(results: list[tuple], min_reps: int) -> frozenset[int]:if base is None or treat is None or base == treat:continuegroups[(action, rung_of_cell(cell))].append((i, cell, base, treat))- # One-to-one by repetition: each reversed rep excuses one rep in the other direction, and a rep- # recorded in both directions is ambiguous and never excused.+ # One-to-one by repetition; a rep recorded in both directions is ambiguous, never excused.out: set[int] = set()for group in groups.values():by_cell: dict[str, dict[tuple[str, str], list[int]]] = collections.defaultdict(@@ -1880,9 +1877,8 @@ def report(print("\n (reported, not counted) actions that vary between runs of any build:")for action, shard, cell, moved in unstable_bad[:8]:print(f" {action:<26} {shard} {cell}: {', '.join(moved[:3])}")- # A one-sided action is a failure on the same footing as a differing digest: the two builds- # behaved differently and the difference leaves no digest to compare.- # `expect_bad` is collected ahead of the verdict branches.+ # A one-sided action fails like a differing digest, since it leaves no digest to compare;+ # expect_bad is collected before the verdict branches.if one_sided or expect_bad or (stable_bad and not declared_ui_change):return Outcome(1, frozenset(compared), _keys(results))if stable_bad:@@ -1891,10 +1887,9 @@ def report("rendering differences above are reported, not failed. Behaviour differences still fail.")- # 2, the same code the empty-payload path uses: the tool was asked a question it could not- # answer, and exiting 0 would let CI go green on a run structurally incapable of firing.- # `decided`, not `matched`. AFTER the failure return, since "it failed" is more specific.- # A declared difference was decided too: a wrapper change can differ on every pair.+ # Outcome 2 is the empty-payload code: a run structurally unable to decide must not exit 0 and+ # turn CI green. Checked after the failure return, on decided not matched; declared differences+ # count too, since a wrapper change can differ on every pair.if decided == 0 and not stable_bad:return Outcome(2, frozenset(compared), _keys(results))return Outcome(0, frozenset(compared), _keys(results))diff --git a/tests/studio/test_autoscroll_harness_contract.py b/tests/studio/test_autoscroll_harness_contract.pyindex af902f978b3..c0a0cc105e2 100644--- a/tests/studio/test_autoscroll_harness_contract.py+++ b/tests/studio/test_autoscroll_harness_contract.py@@ -234,9 +234,8 @@ def test_thread_weight_records_the_four_actions() -> None:def test_thread_weight_row_shapes_stay_distinct() -> None:- """TABLE_ROWS is (label, pick) and GROWTH_AXES is (label, pick, floored). They read almost- identically, so a bulk edit to one lands in the other and print_table dies at the end of a- forty-minute run, after every measurement is taken and before any of it is shown."""+ """TABLE_ROWS is (label, pick) and GROWTH_AXES is (label, pick, floored); a bulk edit that lands+ in the wrong one makes print_table die after a forty-minute run, before anything is shown."""import importlibimport sysdiff --git a/tests/studio/test_backend_ci_matrix.py b/tests/studio/test_backend_ci_matrix.pyindex 16d65f0df94..767fa90c9b5 100644--- a/tests/studio/test_backend_ci_matrix.py+++ b/tests/studio/test_backend_ci_matrix.py@@ -63,14 +63,9 @@ def test_the_full_suite_runs_on_the_ceiling():def test_the_pre_312_branches_are_still_executed_somewhere():- """What the dropped legs actually took away, and where it went.-- Seven backend files carry a sys.version_info branch. The 3.10 ones were never- straddled even by the old matrix, whose oldest leg was 3.10, so every leg took the- same side of them. 3.14 is above every leg there has ever been. The pre-3.12 side is- the only thing a 3.13-only matrix stops executing, so it keeps a leg of its own,- running those files and nothing else.- """+ """Seven backend files carry sys.version_info branches; the 3.10 ones were never straddled, and+ a 3.13-only matrix stops running the pre-3.12 side, so the floor-spot-check leg runs those+ files alone."""legs = _legs()spot = legs.get("floor-spot-check")assert spot, (diff --git a/tests/studio/test_browser_simulations_retry_once.py b/tests/studio/test_browser_simulations_retry_once.pyindex 586f6d97485..7dc7aa4f20f 100644--- a/tests/studio/test_browser_simulations_retry_once.py+++ b/tests/studio/test_browser_simulations_retry_once.py@@ -96,11 +96,9 @@ def test_the_retry_is_bounded_at_one():def test_the_retry_records_the_browser_process():- """A second TargetClosedError should say why the browser went away.-- Only the retry carries DEBUG=pw:browser: a first-attempt pass stays quiet, and the- attempt that decides the leg logs the browser's launch, stderr and exit.- """+ """Only the retry sets DEBUG=pw:browser, so a second TargetClosedError says why the browser went+ away while a first-attempt pass stays quiet; the deciding attempt logs the browser's launch,+ stderr and exit."""step = _step()helper = step[step.index("run_driver()") : step.index("for browser in")]first, second = [line.strip() for line in helper.splitlines() if '"$@"' in line]diff --git a/tests/studio/test_cache_budget_discipline.py b/tests/studio/test_cache_budget_discipline.pyindex 4a833637261..eca7dd15e0e 100644--- a/tests/studio/test_cache_budget_discipline.py+++ b/tests/studio/test_cache_budget_discipline.py@@ -115,10 +115,9 @@ _MAIN_ONLY = re.compile(r"github\.ref\s*==\s*['\"]refs/heads/main['\"]")_LEAF_MAIN = re.compile(r"github\.ref\s*==\s*['\"]refs/heads/main['\"]|['\"]refs/heads/main['\"]\s*==\s*github\.ref")-# Staging repos (scripts/pr_review/staging_ci.py) open PRs against `upstream-main` and never-# push their own main, so their dependency caches are seeded by a run dispatched on that branch.-# The equality counts as restricted ONLY next to an AND-ed guard that excludes this repository:-# a branch ref is never a PR ref, but here upstream-main has no business saving anything.+# Staging repos (scripts/pr_review/staging_ci.py) open PRs against upstream-main and never push+# their own main, so a run on that branch seeds their caches; the equality counts only beside an+# AND-ed guard that excludes this repository, since upstream-main should save nothing._LEAF_SEED = re.compile(r"github\.ref\s*==\s*['\"]refs/heads/upstream-main['\"]"r"|['\"]refs/heads/upstream-main['\"]\s*==\s*github\.ref"diff --git a/tests/studio/test_chat_autoload_failure_gate.py b/tests/studio/test_chat_autoload_failure_gate.pyindex cf870856e46..be251947fe7 100644--- a/tests/studio/test_chat_autoload_failure_gate.py+++ b/tests/studio/test_chat_autoload_failure_gate.py@@ -1271,8 +1271,7 @@ def test_a_local_model_wins_over_the_default_even_when_the_cache_is_empty():def test_the_smallest_on_device_model_wins_across_inventories():- """Cached and local rows compete in one size-ordered cascade, not one list- then the other."""+ """Cached and local rows compete in one size-ordered cascade, not one list and then the other."""out = _run("scenario({ ggufRepos: [GEMMA], variants: { [GEMMA.repo_id]: GEMMA_VARIANTS },"" localModels: [LOCAL_GGUF] })"@@ -1297,9 +1296,8 @@ def test_an_inventory_failure_never_reads_as_an_empty_device(inventory):@pytest.mark.parametrize("broken", ["ggufRepos", "modelRepos", "localModels"])def test_one_broken_inventory_still_loads_a_model_another_one_found(broken):- """A failure is one unknown source, not a verdict on the other two.- Promise.all rejected the batch, discarding lists that had already arrived,- so a broken local scan left a loadable model unused."""+ """A failure is one unknown source, not a verdict on the other two; Promise.all rejected the+ whole batch and discarded lists already received, leaving a loadable model unused."""holder = "localModels" if broken != "localModels" else "ggufRepos"rows = "[LOCAL_GGUF]" if holder == "localModels" else "[GEMMA]"extra = "" if holder == "localModels" else ", variants: { [GEMMA.repo_id]: GEMMA_VARIANTS }"@@ -1408,9 +1406,8 @@ def test_a_mac_chat_only_install_still_auto_loads_a_local_mlx_model():def test_an_image_generation_row_is_never_auto_loaded_for_chat():- """Diffusion rows carry an image/video task while can_chat stays true on- file format alone. The picker routes them to the Images page on click; a- background load has no routing step, so it has to skip them."""+ """Diffusion rows carry an image or video task while can_chat stays true on file format alone;+ the picker routes them to Images on click, so a background load must skip them."""for task in ("text-to-image", "text-to-video", "image-diffusion-unsupported"):rows = (f"{{ ...LOCAL_GGUF, id: 'img', load_id: 'img', path: 'img', task: '{task}',"@@ -1596,8 +1593,7 @@ def test_a_download_that_survives_a_failed_cancel_is_not_loaded():def test_a_failed_cancel_does_not_latch_the_toast_action_off():- """The retry latch must clear once the request settles, or every later- Cancel click is swallowed."""+ """The retry latch must clear once the request settles, or every later Cancel click is swallowed."""src = (WORKDIR / "studio/frontend/src/features/chat/api/chat-adapter.ts").read_text(encoding = "utf-8")@@ -1808,9 +1804,8 @@ def test_a_deferred_verdict_with_only_gguf_cached_does_not_detect_hardware():def test_a_cached_adapter_repo_is_never_auto_loaded():- """A cached LoRA has no weights of its own: /load fetches the base from the- Hub when it is not cached, which is why the local twin is dropped too.- Adapters are tiny, so the size order puts one first."""+ """A cached LoRA has no weights of its own: /load fetches the base from the Hub when uncached,+ which is why the local twin is dropped too; the size order would put it first."""out = _run("scenario({ modelRepos: [{ repo_id: 'org/lora', load_id: 'org/lora',"" size_bytes: 40000000, model_format: 'adapter',"@@ -1854,9 +1849,8 @@ def test_an_hf_cache_row_stays_excluded_when_both_lookups_answer():def test_an_admitted_hf_cache_row_is_not_attempted_twice():- """The surviving cached list may name the same model as the admitted- hf_cache row, so the load-target dedupe has to collapse them or the pair- spends two of the three attempts on one model."""+ """The surviving cached list may name the same model as the admitted hf_cache row, so the+ load-target dedupe must collapse them or the pair spends two of three attempts on one model."""row = ("{ ...LOCAL_GGUF, source: 'hf_cache', load_id: 'org/dup', path: 'org/dup', id: 'org/dup' }")diff --git a/tests/studio/test_chat_ui_persisted_monitor_reset.py b/tests/studio/test_chat_ui_persisted_monitor_reset.pyindex 5cc8759bb7b..9d3e9c1f31a 100644--- a/tests/studio/test_chat_ui_persisted_monitor_reset.py+++ b/tests/studio/test_chat_ui_persisted_monitor_reset.py@@ -75,12 +75,9 @@ def test_every_blocking_call_announces_itself_first():def test_the_stale_page_is_closed_without_waiting_on_its_renderer():- """page.close() has no timeout and has sat out the step's whole budget on Windows.-- The step closes through close_page_without_waiting (browser-side Target.closeTarget on- Chromium), and marks the page stale first, so a request it sends while the browser tears- it down is not counted as the fresh page's /api/system poll.- """+ """page.close() has no timeout and has sat out the whole step budget on Windows, so the step+ uses close_page_without_waiting (Target.closeTarget on Chromium) and marks the page stale+ first; a request sent during teardown is not counted as the fresh page's /api/system poll."""body = _step_body()handoff = body.index("page = _fresh_page")assert "page.close()" not in body[:handoff], "the reset waits on the stale renderer again"diff --git a/tests/studio/test_ci_shell_suite_coverage.py b/tests/studio/test_ci_shell_suite_coverage.pyindex ac143449008..07f212c00cb 100644--- a/tests/studio/test_ci_shell_suite_coverage.py+++ b/tests/studio/test_ci_shell_suite_coverage.py@@ -55,9 +55,8 @@ def _skip_list(source: str) -> set[str]:class TestBackendCiRunsEveryShellTest:def test_step_discovers_the_directory_instead_of_listing_files(self):- """Matched against the parsed step script, and on the glob rather than a- verbatim line, so reformatting the loop does not turn CI red -- only- going back to a hardcoded list does."""+ """Matches the glob in the parsed step script rather than a verbatim line, so reformatting+ the loop keeps CI green; only a hardcoded list turns it red."""script = _shell_step_script()assert re.search(r"for\s+\w+\s+in\s+tests/sh/test_\*\.sh", script), ("Backend CI must glob tests/sh; a hardcoded list is how the ROCm WSL "@@ -210,8 +209,7 @@ def _workflows_running_powershell_tests():class TestGithubPathMatcher:- """The guard below is only as good as this matcher; a wrong one would pass- everything silently."""+ """The guard below is only as good as this matcher, since a wrong one would pass everything silently."""@pytest.mark.parametrize("pattern,path,expected",diff --git a/tests/studio/test_cli_studio_stop_windows.py b/tests/studio/test_cli_studio_stop_windows.pyindex 5f774d99b88..8f7419215cd 100644--- a/tests/studio/test_cli_studio_stop_windows.py+++ b/tests/studio/test_cli_studio_stop_windows.py@@ -29,8 +29,7 @@ def _func_source(name: str) -> str:def _load_pid_alive(platform: str, fake_run = None):- """Exec just `_pid_alive` with injectable sys/subprocess, so the win32 branch runs- on any host."""+ """Execs only _pid_alive with injectable sys and subprocess, so the win32 branch runs on any host."""src = _func_source("_pid_alive")fake_sys = types.SimpleNamespace(platform = platform)fake_sub = types.SimpleNamespace(run = fake_run) if fake_run is not None else subprocessdiff --git a/tests/studio/test_code_block_flicker_contract.py b/tests/studio/test_code_block_flicker_contract.pyindex c99fb2df5c4..806aafadf78 100644--- a/tests/studio/test_code_block_flicker_contract.py+++ b/tests/studio/test_code_block_flicker_contract.py@@ -245,9 +245,8 @@ def test_the_fixture_offers_the_state_the_override_was_added_for() -> None:def test_the_variant_stylesheets_are_checked_to_have_won_the_cascade() -> None:- """A variant that loses to the tree measures the tree under another name. That happened: every- variant computed identically, all reported zero collapses, and the run read as "nothing to- fix"."""+ """A variant that loses to the tree measures the tree under another name; a past run had every+ variant compute identically and read as nothing to fix."""source = harness_source()settled = module_assignment(source, "EXPECTED_COMPUTED")running = module_assignment(source, "EXPECTED_COMPUTED_RUNNING")diff --git a/tests/studio/test_core_setup_zoo_revision_notice.py b/tests/studio/test_core_setup_zoo_revision_notice.pyindex 556eb0d0195..d7404120848 100644--- a/tests/studio/test_core_setup_zoo_revision_notice.py+++ b/tests/studio/test_core_setup_zoo_revision_notice.py@@ -191,9 +191,8 @@ def test_a_hanging_remote_lookup_does_not_hold_the_step(tmp_path):def test_the_warning_does_not_prescribe_a_remedy_that_cannot_work(tmp_path):- """A pinned dispatch, a moving main and a stale re-run are indistinguishable by the- time the action sees a sha, and re-running is the remedy for only the last. So the- message has to hold for all three rather than assert one."""+ """A pinned dispatch, a moving main and a stale re-run look identical by the time the action+ sees a sha, and re-running only remedies the last, so the warning must hold for all three."""proc = _run_notice(tmp_path,git_exit = 0,diff --git a/tests/studio/test_deep_research_frontend_contract.py b/tests/studio/test_deep_research_frontend_contract.pyindex 19c385923bc..8dd68a729fd 100644--- a/tests/studio/test_deep_research_frontend_contract.py+++ b/tests/studio/test_deep_research_frontend_contract.py@@ -180,10 +180,8 @@ def test_research_presentation_is_integrated() -> None:assert "<ResearchMessage />" in threadassert "if (researchRunId) return null" in threadassert "!researchRunId &&" in thread- # A research message has no Delete. The hook reports `hidden` for research messages, and every- # component that renders Delete from it renders nothing when hidden. That component has been a- # bar button, a More-menu item (#12735) and a bar button again (#13615), so it is found by the- # hook it calls rather than by its name.+ # Research messages have no Delete, so the hook reports hidden; the Delete component moved+ # between bar, More-menu (ref 12735) and bar (ref 13615), so it is found via its hook.delete_hook = thread.split("function useDeleteMessage()", 1)[1].split("\n}\n", 1)[0]assert re.search(r"hidden:\s*Boolean\(\s*researchRunId\s*\|\|\s*ownsResearchMessage\s*\)", delete_hook@@ -279,12 +277,9 @@ def test_research_presentation_is_integrated() -> None:1].split("setActiveThreadId:", 1)[0]assert "saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY" not in checkpoint_update- # #8686 put a chat-scoped override in front of the global read here, so the literal `const permissionMode =- # loadPermissionMode();` this used to pin is gone. The read itself is the contract, and it is still per call:- # toggling deep research re-resolves the permission level, taking the chat's own level when it has one and the- # persisted global otherwise, rather than reusing a stale value. Scoped to the setter, because over the whole file- # this would also match the initial-state constant, which is a different property and would keep passing if this- # read were dropped.+ # Since ref 8686 a chat-scoped override precedes the global read, so the read must stay per+ # call: toggling deep research re-resolves permission from the chat or the persisted global;+ # scoped to the setter because a whole-file match would hit the initial-state constant.deep_research_update = store.split("setDeepResearchEnabled: (deepResearchEnabled) =>", 1)[1].split("setResearchWebsitePolicy:", 1)[0]diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.pyindex 4dd6d148d14..3a37f38192d 100644--- a/tests/studio/test_desktop_reliability_frontend_contract.py+++ b/tests/studio/test_desktop_reliability_frontend_contract.py@@ -1655,10 +1655,8 @@ def test_chat_sidebar_row_actions_visible_on_coarse_pointers():builder_end = indexbreakassert builder_end is not None, "unbalanced `const buttonClass = cn(` in the sidebar"- # On the row button itself, not merely somewhere in the function. The row also renders a- # pin, and handing buttonClass to it or another element while the button- # went without would leave every padding check below describing classes that reach nothing- # the gutters are measured against.+ # The row also renders a pin, so buttonClass must reach the row button itself: if the button+ # went without it, padding checks would measure classes that reach nothing.carriers = [tagfor tag in _opening_jsx_tags(applied, "<SidebarMenuButton")@@ -2255,9 +2253,8 @@ def test_a_stopped_repair_update_is_recorded_as_canceled_not_failed():assert '"failed"' not in call-# `_ui_source` hides whether a length still scales, so the scaling is asserted here, per-# variant (`h-[...]` and `hover:h-[...]` differ).-# Images, Audio and Video line their model picker up with Chat: same left inset, same control height.+# _ui_source hides whether a length still scales, so scaling is asserted per variant (h-[...] and+# hover:h-[...] differ); Images, Audio and Video match Chat's picker inset and height._MEDIA_PICKER_CLASS = ('className="ml-1.5 max-w-full overflow-hidden !pl-2.5 !pr-1.5 ''!h-[var(--studio-chat-control-height,34px)]"'@@ -2273,18 +2270,14 @@ _LENGTHS_THAT_MUST_KEEP_THE_SCALE = ((AUDIO_PAGE, "@[50rem]:", "pt", "60px", 2),(DIFFUSION_TRAIN_PANEL, "@[50rem]:", "pt", "42px", 1),(DIFFUSION_TRAIN_PANEL, "", "pt", "42px", 1),- # The sidebar row: its height, the gap it sets when pinned, and the indent a project row- # takes. These are hand-set one-off lengths, which is exactly the spacing that used to- # stay put while the labels grew, so the row clips its own text at a larger setting.- # Seven rows: #11589 added the drop-cue row, #12016 a second section header for the- # custom sidebar sections, and #12927 the pinned-pages label; #13575 dropped the inline- # rename input (one 30px height, one 39px indent).+ # Hand-set sidebar lengths stay put as labels grow, so rows clip their text; seven 30px rows+ # (ref 11589 drop-cue row, ref 12016 second section header, ref 12927 pinned-pages label) and+ # ref 13575 removed the inline rename input (one 30px, one 39px indent).(APP_SIDEBAR, "", "h", "30px", 7),(APP_SIDEBAR, "", "gap", "8.5px", 6),(APP_SIDEBAR, "", "pl", "39px", 1),- # The 34px pill controls in the media headers, in all three spellings the pages use. The- # band around them scales and so does their own text, so a control left fixed is the one- # thing in that row that does not move, and it crowds out its label.+ # The 34px pill controls in the media headers are checked in all three spellings, since a+ # control left fixed would not scale with the band and would crowd its label.(IMAGES_PAGE, "!", "h", "34px", 1),(IMAGES_PAGE, "", "h", "34px", 1),(IMAGES_PAGE, "[&>button]:", "h", "34px", 1),diff --git a/tests/studio/test_diffusion_gpu_layers_contract.py b/tests/studio/test_diffusion_gpu_layers_contract.pyindex 45da9a53951..dc70a65200b 100644--- a/tests/studio/test_diffusion_gpu_layers_contract.py+++ b/tests/studio/test_diffusion_gpu_layers_contract.py@@ -99,9 +99,8 @@ def test_diffusion_server_forwards_ngl_and_gates_it_on_shim_support():def test_zero_layers_masks_the_child_devices(llama_cpp):- """gpu_layers=0 must CUDA-mask the child, else _gpu_offload_active=False lies to the- training VRAM coordinator and a GPU-resident runner survives into a training run.- Behavioural, not a source-text match: what matters is the token the child gets."""+ """gpu_layers=0 must CUDA-mask the child, else _gpu_offload_active=False misleads the training+ VRAM coordinator and a GPU-resident runner survives into training."""arg = llama_cpp.LlamaCppBackend._diffusion_gpu_argassert arg([3, 1], force_cpu = True) == ""assert arg(None, force_cpu = True) == ""@@ -193,9 +192,8 @@ def test_backend_dedup_compares_the_requested_split(def test_the_dedupe_compares_the_requested_split_through_the_paravirtual_rewrite():- """The single comparator now lives on the backend, so the diffusion split has to be- judged on the normalized intent: a virtualised Metal device launches the CPU-pinned- rewrite, and comparing the raw ask against it would reload a healthy server forever."""+ """The split dedupe compares the normalized intent, since a virtualised Metal device launches+ the CPU-pinned rewrite and comparing the raw ask would reload a healthy server forever."""bodies = {node.name: (ast.get_source_segment(SRC, node) or "")for node in ast.walk(TREE)diff --git a/tests/studio/test_freeze_report_verdicts.py b/tests/studio/test_freeze_report_verdicts.pyindex d0e5f9f1c36..1d96c881b33 100644--- a/tests/studio/test_freeze_report_verdicts.py+++ b/tests/studio/test_freeze_report_verdicts.py@@ -74,9 +74,8 @@ def test_a_real_stall_after_warmup_is_still_caught():def test_both_loops_going_quiet_is_not_healthy():- """Backend gone at 120s, shell still up. Both counters freeze together, so no- comparison between them can fail, and the totals from the first half are large enough- that every other branch declines: this used to fall through to OK."""+ """With the backend gone at 120s and the shell still up, both counters freeze together, so no+ comparison fails and every other branch declines; it must not fall through to OK."""samples, mon, live = [], 0, 0for t in range(15, 241, 15):if t <= 120:@@ -110,9 +109,8 @@ def test_clean_exit_late_in_the_window_is_not_a_single_instance_handoff():def test_candidate_env_drops_an_inherited_workaround():- """The reporter has already been told to try these by hand, so one is very likely- still exported. Overlaying on top of it runs the control through the workaround and- the report then says the control was fine."""+ """The reporter was told to try workarounds by hand, so one is likely still exported; overlaying+ on it would run the control through the workaround and misreport it as fine."""base = {"GDK_BACKEND": "x11", "PATH": "/usr/bin", "DISPLAY": ":0"}control = freeze.candidate_env(base, {})assert "GDK_BACKEND" not in control@@ -269,9 +267,8 @@ def test_bare_relative_executable_is_resolved_before_launch(tmp_path, monkeypatcdef test_candidate_rationale_survives_a_no_signal_result():- """The reason a candidate was tried is a field of the report. A no-signal run used to- overwrite it with the measurement-failure explanation, so the one result that most- needs context lost it."""+ """The reason a candidate was tried is a report field that a no-signal run must not overwrite+ with the measurement-failure explanation."""import inspectsource = inspect.getsource(freeze.run_candidate)@@ -367,9 +364,8 @@ def test_exactly_three_silent_intervals_is_already_stale():def test_a_non_executable_appimage_is_refused_with_the_command_that_fixes_it(monkeypatch, tmp_path, capsys):- """An AppImage downloaded through a browser has no execute bit. Popen raises- PermissionError on it and nothing between run_candidate() and the candidate loop- catches it, so the run ended in a traceback with nothing measured and no report."""+ """A browser-downloaded AppImage has no execute bit; Popen raises PermissionError, nothing up to+ the candidate loop catches it, so the run ends in a traceback with no report."""app = tmp_path / "Unsloth-Desktop.AppImage"app.write_text("#!/bin/sh\n")app.chmod(0o644)diff --git a/tests/studio/test_frontend_dist_cache.py b/tests/studio/test_frontend_dist_cache.pyindex 1402bb83dc6..d929d39bdf5 100644--- a/tests/studio/test_frontend_dist_cache.py+++ b/tests/studio/test_frontend_dist_cache.py@@ -149,12 +149,8 @@ def test_the_key_covers_every_path_the_rebuild_check_reads(reader) -> None:def test_the_two_installers_agree_on_what_makes_a_dist_stale() -> None:- """One key serves both, so the two checks reading different paths would be a bug.-- Neither script alone can reveal that. setup.sh could gain a path group, the key- could gain it too, both Linux tests would pass, and Windows would keep hitting a key- that no longer describes what setup.ps1 reads.- """+ """studio/setup.sh and studio/setup.ps1 share one dist cache key, so they must read the same+ staleness inputs or Windows keeps hitting a key that no longer describes its reads."""assert _staleness_inputs_sh() == _staleness_inputs_ps1(), (f"studio/setup.sh checks {sorted(_staleness_inputs_sh())} but studio/setup.ps1 "f"checks {sorted(_staleness_inputs_ps1())}. They share one cache key, so the "diff --git a/tests/studio/test_heavy_thread_measurement_integrity.py b/tests/studio/test_heavy_thread_measurement_integrity.pyindex 5f6219b1904..acc97eb99ce 100644--- a/tests/studio/test_heavy_thread_measurement_integrity.py+++ b/tests/studio/test_heavy_thread_measurement_integrity.py@@ -707,9 +707,7 @@ def test_a_multi_commit_reopen_is_not_a_mis_declared_floor() -> None:def test_subtracting_a_floor_the_reopen_never_paid_is_a_failure() -> None:- """The other side of the lower bound. Equality is no longer required, so the check has to- still catch the direction that invents time: a cell whose reopen resolved without waiting a- paint at all, while the axis removes one."""+ """Subtracting a floor the reopen never waited out must still fail, since that invents time."""problems = HARNESS.floor_declaration_problems(floor_row(0))assert len(problems) == 1 and "never waited out" in problems[0], problems@@ -1010,9 +1008,8 @@ def test_a_counter_is_still_judged_as_a_counter() -> None:def test_the_counter_set_is_stated_and_non_empty() -> None:- """Inferring which axes are counts is what produced the defect. If a rename ever empties this- set, every counter silently becomes a timing and the liveness verdict loses its only- zero-based axis, so the set is pinned against the axis list itself."""+ """Inferring counts from axis names caused the defect; if a rename empties this set, counters+ silently become timings and the liveness verdict loses its zero-based axis."""assert HARNESS.COUNTER_AXES, "no axis is classified as a counter any more"names = {name for name, _pick, _floored in HARNESS.GROWTH_AXES}assert (@@ -1089,9 +1086,8 @@ def wall_cells_for_report(paint_waits: int) -> dict:def test_a_fractional_median_wait_count_is_not_truncated() -> None:- """`summarise` medians the wait count across repetitions, so an even-repetition run whose- repetitions paid 1 and 2 reports 1.5. Truncating that to 1 left half a vsync floor in the- wall axis, and the documented two-repetition configurations are the ones that produce it."""+ """summarise medians wait counts, so an even repetition count can give 1.5; truncating that to 1+ left half a vsync floor in the wall axis, as two-repetition configs do."""assert (HARNESS.resolve_floor(HARNESS._floor_from("menu", "paint_waits"), {"actions": {"menu": {"paint_waits": 1.5}}}diff --git a/tests/studio/test_installer_av_shapes.py b/tests/studio/test_installer_av_shapes.pyindex e84c9d571a7..a164565478d 100644--- a/tests/studio/test_installer_av_shapes.py+++ b/tests/studio/test_installer_av_shapes.py@@ -734,9 +734,8 @@ def test_a_compiler_started_by_a_compiler_is_one_compile_not_two(@pytest.mark.skipif(shutil.which("pwsh") is None, reason = "needs PowerShell")def test_a_record_with_no_parent_field_is_still_scored(tmp_path) -> None:- """The whole chain is reported when the schema does not carry ParentProcessName. An- absent field reads as empty, and empty must not be mistaken for a compiler parent, or a- log that predates the field would report nothing at all."""+ """The whole chain is still reported when ParentProcessName is absent, since empty must not be+ read as a compiler parent or old logs would report nothing."""script = tmp_path / "probe.ps1"script.write_text("\n".join(@@ -866,13 +865,8 @@ def test_the_watcher_sees_intermediates_the_compiler_cleaned_up(tmp_path) -> Non@pytest.mark.skipif(shutil.which("pwsh") is None, reason = "needs PowerShell")def test_the_watcher_still_reports_intermediates_that_were_left_behind(tmp_path) -> None:- """The listing half must keep working; the watcher is added to it, not swapped for it.-- A compile that was NOT cleaned up, so the response file is still next to the assembly.- This asserted a bare ``leftover.dll`` before, which read as "any DLL under TEMP is a- compiler artefact"; that is the rule the job died on, and it is not what this test is- for. The vehicle changed, the listing half it checks did not.- """+ """The listing still reports an uncleaned compile's leftovers, such as a response file beside+ the assembly; a bare DLL under TEMP is not evidence, since that rule killed the job."""action = ('$dir = Join-Path $env:TEMP "leftover"; '"New-Item -ItemType Directory -Force -Path $dir | Out-Null; "@@ -928,11 +922,8 @@ def test_a_compile_beside_an_unpacked_archive_is_still_caught(tmp_path) -> None:@pytest.mark.skipif(shutil.which("pwsh") is None, reason = "needs PowerShell")def test_an_action_that_compiles_nothing_reports_nothing(tmp_path) -> None:- """Otherwise the real measurement, which requires neither detector to fire, can never pass.-- A text file is written so the action is not a no-op: the watcher sees the creation and- must still discard it, because the extension is not one a compiler writes.- """+ """An action that compiles nothing must report nothing, or the real measurement (which needs+ neither detector to fire) can never pass; a .txt write must still be discarded."""action = ('Set-Content -LiteralPath (Join-Path $env:TEMP "notes.txt") -Value "hello"; '"Start-Sleep -Milliseconds 400"@@ -963,9 +954,8 @@ def test_the_compiler_window_is_cut_to_size_by_timecreated() -> None:def test_the_path_resolver_still_has_a_lexical_fallback() -> None:- """The point of the change is the acquisition, not the ladder: a host that cannot reach the- exact rung must degrade exactly as one that could not compile already did.- """+ """The path resolver keeps its lexical fallback: a host that cannot reach the exact rung must+ degrade exactly as a host that could not compile already did."""text = _text("install.ps1")assert "Write-StudioFinalPathDegraded" in textassert "Get-StudioLexicalPath" in textdiff --git a/tests/studio/test_legacy_chat_title_repair.py b/tests/studio/test_legacy_chat_title_repair.pyindex 9222373bdbf..9c27572d4bc 100644--- a/tests/studio/test_legacy_chat_title_repair.py+++ b/tests/studio/test_legacy_chat_title_repair.py@@ -21,9 +21,8 @@ def _read(path: Path) -> str:def test_the_repair_reads_its_own_messages_as_late_as_it_can():- """Not the sidebar's map. That map takes its empty-backend entries from- listStoredChatMessages, which merges Dexie rows the backend has pruned, and- it is fetched at load time rather than at write time."""+ """The repair reads its own messages as late as it can, not the sidebar map: that map merges+ pruned Dexie rows via listStoredChatMessages and is fetched at load time."""hook = _read(HOOK)assert "void repairLegacyChatTitles(threads).catch(() => undefined);" in hook@@ -47,9 +46,8 @@ def test_the_repair_reads_only_stored_messages():def test_an_emptied_chat_is_not_retried_for_the_session():- """A chat the user deleted every message from reads back the same as one- still importing. Retrying it would re-read it on every refresh, since its- title stays clipped and keeps matching the pre-filter."""+ """An emptied chat must not be retried for the session: it reads back like one still importing,+ and its clipped title keeps matching the pre-filter on every refresh."""repair = _read(REPAIR)assert "const withoutMessages = threadsMissingMessages(ids, messages);" in repairassert "if (withoutMessages.length > 0) {" in repair@@ -61,9 +59,8 @@ def test_an_emptied_chat_is_not_retried_for_the_session():def test_the_repair_never_creates_anything():- """updateStoredChatThread ensures the thread first, which re-imports one- deleted on another client from the Dexie rows still sitting here. A- migration patching a row that is gone has to 404, not resurrect it."""+ """The repair must never create threads: updateStoredChatThread ensures the thread first and+ would re-import one deleted elsewhere, so a patch to a gone row must 404."""repair = _read(REPAIR)assert 'from "./chat-history-storage"' not in repairassert "await updateChatThread( repair.threadId, { title: repair.title }," in repair@@ -88,9 +85,8 @@ def test_only_one_repair_pass_runs_at_a_time():def test_a_rename_is_left_to_the_backend_guard():- """The pass only runs where the guard is enforced, so re-listing the whole- history per page to check titles client side was both redundant and- quadratic: every page of 100 pulled every thread the account has."""+ """Renames are left to the backend guard: the pass runs only where it is enforced, and+ re-listing all threads per page client side would be redundant and quadratic."""repair = _read(REPAIR)assert "listChatThreads" not in repairassert "repairsStillValid" not in repairdiff --git a/tests/studio/test_mac_tab_capability_warm_window.py b/tests/studio/test_mac_tab_capability_warm_window.pyindex 48beac18d07..44e8dc66996 100644--- a/tests/studio/test_mac_tab_capability_warm_window.py+++ b/tests/studio/test_mac_tab_capability_warm_window.py@@ -203,9 +203,8 @@ def _health(mod, bodies):def test_greyed_row_fails_even_though_the_warm_window_already_shut(tmp_path, monkeypatch):- """The vacuous-pass case. Health has settled, so the real-warm sampler observes- nothing and breaks on its first iteration; the row is blacked out exactly as it was- in the field. Before the forced-verdict check this run went green."""+ """A greyed row fails even when the warm window already shut: health has settled so the sampler+ observes nothing, and without the forced-verdict check this run went green."""mod = _load(tmp_path, monkeypatch)_health(mod, [SETTLED])page = FakePage({TRAIN: GREYED})@@ -244,9 +243,8 @@ def test_absent_row_fails_instead_of_skipping(tmp_path, monkeypatch):def test_spinning_row_passes_and_the_route_is_lifted(tmp_path, monkeypatch):- """The green case, and the only one there should be: the row spins on a forced- unmeasured verdict, and the interception is taken back off so the tab walk that- follows sees the real backend."""+ """The only green case: a spinning row passes on a forced unmeasured verdict, and the route+ interception is lifted so the tab walk that follows sees the real backend."""mod = _load(tmp_path, monkeypatch)_health(mod, [SETTLED])page = FakePage({TRAIN: SPINNING})@@ -260,9 +258,8 @@ def test_spinning_row_passes_and_the_route_is_lifted(tmp_path, monkeypatch):def test_forced_body_is_a_real_reply_with_the_measurement_removed(tmp_path, monkeypatch):- """What the browser is served has to be provisional by env.ts's rules: hardware- detecting, no device_type, and not the deferred marker (which env.ts reads as- settled and would grey the row out legitimately)."""+ """The forced body must stay provisional under env.ts rules: hardware detecting, no device_type,+ and not the deferred marker, which env.ts reads as settled and would grey rows out."""mod = _load(tmp_path, monkeypatch)_health(mod, [{**SETTLED, "hardware_detection_deferred": True, "studio_root_id": "abc"}])page = FakePage({TRAIN: SPINNING})@@ -312,9 +309,8 @@ def test_sampler_that_cannot_read_the_page_at_all_fails(tmp_path, monkeypatch):def test_a_navigation_in_flight_on_the_first_read_is_not_a_failure(tmp_path, monkeypatch):- """The forced password change navigates the app itself, which can abort the post-login- goto and leave a navigation in flight: the first evaluate then loses its context. macOS- job 108389456188 failed on exactly that; the next read would have worked."""+ """A navigation in flight on the first read is not a failure: the forced password change can+ abort the post-login goto and drop the first evaluate's context."""mod = _load(tmp_path, monkeypatch)_health(mod, [UNMEASURED, SETTLED])page = FakePage({TRAIN: SPINNING})@@ -360,9 +356,8 @@ def test_drive_tabs_fails_when_the_pinned_rows_never_render(tmp_path, monkeypatcdef test_drive_tabs_waits_out_the_boot_screen_before_judging_the_rows(tmp_path, monkeypatch):- """A full navigation boots the app again, and a slow macOS runner can still show the- "Loading..." screen after the fixed settle wait (Library, twice on 2026-10-29). The rows- are judged once the sidebar has mounted, not while nothing has rendered yet."""+ """Rows are judged once the sidebar has mounted: a full navigation reboots the app, and a slow+ macOS runner can still show the Loading screen past the fixed settle wait."""mod = _load(tmp_path, monkeypatch)_health(mod, [SETTLED])page = FakePage({}, mounts_after_wait = {rid: SETTLED_ENABLED for rid in mod.INLINE_ROW_IDS})@@ -388,9 +383,8 @@ def test_a_row_missing_from_a_mounted_sidebar_still_fails(tmp_path, monkeypatch)def test_drive_tabs_does_not_fail_on_the_rows_that_live_under_more(tmp_path, monkeypatch):- """Video and Export render inside the More dropdown, which mounts no data-testid at- all. Their absence is the documented shape, not a miss -- asserting on it would be- asserting on something that can never be true."""+ """Video and Export live under the More dropdown, which mounts no data-testid at all, so their+ absence is the documented shape and not a miss; do not assert on it."""mod = _load(tmp_path, monkeypatch)_health(mod, [SETTLED])page = FakePage({rid: SETTLED_ENABLED for rid in mod.INLINE_ROW_IDS})@@ -460,9 +454,8 @@ def test_every_stand_in_names_a_pinned_row_and_a_section_the_sidebar_renders():def test_inline_row_ids_match_the_frontends_default_pinned_set():- """If a row is unpinned in the store, it stops rendering a data-testid and every- assertion pinned to it silently becomes unobservable. That is how the Video half of- this script came to check nothing, and it must not happen again unnoticed."""+ """INLINE_ROW_IDS must match the frontend default pinned set: an unpinned row stops rendering+ its data-testid, silently making its assertions unobservable."""src = APPEARANCE_STORE.read_text(encoding = "utf-8")block = re.search(r"SIDEBAR_NAV_DEFAULT_PINNED[^{]*\{(.*?)\n\};",@@ -623,17 +616,15 @@ def test_a_stall_the_backend_recovers_from_is_not_a_failure(tmp_path, monkeypatcdef test_even_a_long_stall_passes_if_the_backend_comes_back(tmp_path, monkeypatch):- """No threshold shorter than the launcher's most generous path is decidable in the- 120s this phase gets, so there is deliberately no threshold at all. A stall far past- anything the old replay would have killed on still passes once the backend answers."""+ """No stall threshold is used: none shorter than the launcher's most generous path is decidable+ in the 120s this phase gets, so a long stall still passes once the backend answers."""mod = _load(tmp_path, monkeypatch)assert _verdict(mod, _timeline(220, stalls = [(30, 150)])) == []def test_a_backend_that_never_answers_again_fails(tmp_path, monkeypatch):- """The terminal stall. This is what the poller exists to catch and it needs no- watchdog arithmetic: the backend stopped answering and was still not answering when- the run ended, confirmed by the final probe."""+ """A terminal stall fails: the backend stopped answering and was still silent when the run+ ended, as confirmed by the final probe; no watchdog arithmetic is needed."""mod = _load(tmp_path, monkeypatch)failed = _verdict(mod, _timeline(150, stalls = [(60, 9999)]), final_kind = "timeout", final_status = 0@@ -643,9 +634,8 @@ def test_a_backend_that_never_answers_again_fails(tmp_path, monkeypatch):def test_a_trailing_stall_the_final_probe_clears_is_not_a_failure(tmp_path, monkeypatch):- """A stall still in progress when sampling stopped is not a terminal one if the- backend answers the final probe. Without that probe this would be indistinguishable- from death, which is why report() takes it rather than guessing from the samples."""+ """A stall still open when sampling stopped is not terminal if the final probe is answered;+ report() takes that probe because the samples alone cannot tell it from death."""mod = _load(tmp_path, monkeypatch)samples = _timeline(150, stalls = [(60, 9999)])assert samples[-1]["kind"] == "timeout", "fixture no longer ends mid-stall"@@ -795,9 +785,8 @@ def test_an_answered_non_200_does_not_get_the_recovery_window(tmp_path, monkeypadef test_the_recovery_window_clears_the_stalls_actually_seen():- """Sized from evidence, not from a round number. Run 32862298967 produced stalls of- 10.03s, 25.1s, 27.75s and 33.2s on one runner, so the window has to clear 33.2s with- room to spare or it decides "never ended" about stalls this job has already seen."""+ """RECOVERY_WINDOW_S must exceed twice the longest stall seen on one runner (33.2s), or a stall+ this job has already seen would be judged never ended."""longest_observed_s = 33.2assert _module_constant("RECOVERY_WINDOW_S") > 2 * longest_observed_s@@ -874,9 +863,8 @@ def _serve(def test_a_trickling_response_cannot_outlive_the_probe_budget(tmp_path, monkeypatch):- """urllib's timeout is per socket operation, so a peer that dribbles bytes resets it- forever and read() never returns. That would outlive the script's wall watchdog and- hang the job, which reports nothing at all. The read carries its own deadline."""+ """urllib's timeout is per socket operation, so a peer that dribbles bytes can hang read() past+ the wall watchdog; the read carries its own deadline."""mod = _load(tmp_path, monkeypatch)base, state, shutdown = _serve(b"{}", trickle = True)monkeypatch.setattr(mod, "BASE", base)@@ -908,9 +896,8 @@ def test_an_oversized_body_does_not_get_read_to_the_end(tmp_path, monkeypatch):def test_immediate_failures_are_paced_during_recovery(tmp_path, monkeypatch):- """_transport_kind calls a reset a stall on purpose, and a reset returns in about a- millisecond, so an unpaced window becomes thousands of connections against a backend- that is already in trouble. Pacing is bounded by the window, never past it."""+ """Recovery probes are paced, bounded by the window: _transport_kind counts a reset as a stall+ and it returns in about 1 ms, so unpaced retries would flood a sick backend."""mod = _load(tmp_path, monkeypatch)calls = _scripted_probes(mod, ["timeout"])began = time.monotonic()@@ -969,9 +956,8 @@ def test_the_wall_watchdog_stays_armed_through_recovery_and_reporting():def test_the_warning_counts_the_post_run_wait(tmp_path, monkeypatch, capsys):- """Sampling stops at an arbitrary moment. If it stops mid-stall, the span ends at the- last timed-out sample, so the reported length leaves out every second of the watch- that actually saw the stall clear. A warning nobody can trust is worse than none."""+ """The warning counts the post-run wait, since sampling can stop mid-stall and a span ending at+ the last timeout would hide the watch seconds that saw it clear."""mod = _load(tmp_path, monkeypatch)samples = _timeline(150, stalls = [(140, 9999)])assert samples[-1]["kind"] == "timeout", "fixture no longer ends mid-stall"@@ -1128,9 +1114,8 @@ def test_trickling_response_headers_cannot_outlive_the_probe_budget(tmp_path, modef test_the_deadline_covers_the_whole_request_not_one_layer():- """Stated so the next reader does not swap it back for a per-layer bound. Each layer- bounded on its own just moves the hole: the body cap left headers open, and a header- cap would leave the redirect chain or the handshake."""+ """The deadline covers the whole request, not one layer: a per-layer cap just moves the hole, as+ a body cap leaves headers open and a header cap leaves redirects or the handshake."""source = SCRIPT.read_text(encoding = "utf-8")assert "WHOLE-REQUEST deadline" in sourceassert "worker.join(timeout)" in sourcediff --git a/tests/studio/test_main_runs_survive_merge_bursts.py b/tests/studio/test_main_runs_survive_merge_bursts.pyindex df07da13a33..f2bc1fe9605 100644--- a/tests/studio/test_main_runs_survive_merge_bursts.py+++ b/tests/studio/test_main_runs_survive_merge_bursts.py@@ -46,9 +46,8 @@ QUOTA_BOUND = frozenset({"kaggle-t4-notebook-ci.yml", "kaggle-t4-studio-gpu-ci.y# the one entry, and it no longer runs on pushes to main.PER_COMMIT_ALLOWED = frozenset()-# Phrasings that assert a main run is never cancelled or that main is grouped per commit.-# Either is false for a workflow sharing one group across main commits: its PENDING run is-# replaced by the next push.+# Phrasings claiming main runs are never cancelled or are grouped per commit; both are false for a+# shared-group workflow, whose PENDING run the next push replaces.CLAIMS_PROTECTION = re.compile(r"never on main|never cancelled on main|not cancelled on main|never cancels on main"r"|unique per commit on main|grouped per commit on main|one group per commit on main",@@ -171,11 +170,8 @@ def _coalescing() -> dict[str, dict]:def test_every_workflow_that_runs_on_main_coalesces_a_merge_burst():- """Two main commits share one group, so a burst runs the executing commit plus the tip.-- A group per commit runs every workflow on every main commit, which is the load that- queued the whole org for hours. Checked across all of them rather than a named few.- """+ """Every main workflow must coalesce merge bursts: a shared group runs the executing commit plus+ the tip, while a per-commit group queued the whole org for hours."""offenders = sorted(name for name, document in _coalescing().items() if _is_per_commit_on_main(_group(document)))@@ -291,12 +287,8 @@ def test_every_group_expression_is_understood():def test_the_evaluator_reads_which_branch_supplies_the_sha():- """The per-commit predicate is only worth its assertions if this holds.-- Each of these contains ``github.sha`` in its source text, and a substring test would- call all four per-commit. Only the first and the last are, so a grep cannot tell a- coalescing group from a per-commit one; rendering can.- """+ """The per-commit evaluator must read which branch supplies github.sha, since a substring grep+ cannot tell a coalescing group from a per-commit one; rendering can."""gated = "${{ github.ref }}-${{ github.ref == 'refs/heads/main' && github.sha || '' }}"reversed_ = "${{ github.ref }}-${{ github.ref != 'refs/heads/main' && github.sha || '' }}"wrong_branch = "${{ github.ref }}-${{ github.ref == 'refs/heads/main' && '' || github.sha }}"@@ -317,11 +309,8 @@ def test_the_evaluator_reads_which_branch_supplies_the_sha():def test_no_workflow_claims_a_main_protection_it_does_not_have():- """A comment promising per-commit or never-cancelled main runs must match the group.-- Read from the raw text rather than the parsed document, because a comment is exactly what- YAML throws away, and the comment is what people act on.- """+ """No workflow comment may claim a main protection its group lacks; the check reads raw text,+ since YAML parsing discards comments and comments are what people act on."""offenders = []for path in sorted(WORKFLOWS.glob("*.y*ml")):text = path.read_text(encoding = "utf-8")diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex b876e5bfec6..0501280d7eb 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -196,9 +196,8 @@ def _braced_block(text: str, declaration: str) -> str:def _override_lookup_candidates(*args, **kwargs) -> list[str]:- """The real override-key ladder, imported rather than grepped out of inference.py: #8702 moved- it to another module unchanged and took four contract tests red with it. The module is- import-cheap (stdlib only at import time)."""+ """Imports the real override-key ladder rather than grepping inference.py: issue 8702 moved it+ unchanged and took four contract tests red; the module is stdlib-only at import."""import sysbackend = str(WORKDIR / "studio" / "backend")@@ -235,9 +234,8 @@ def _override_load_kwargs(*args, **kwargs) -> dict:def test_models_api_sends_token_via_header_not_query():- """getModelConfig / checkVisionModel / checkEmbeddingModel must pass the HF- token through hubTokenHeader, never as a ?hf_token= query param (which leaks- the credential into server/proxy access logs)."""+ """getModelConfig, checkVisionModel and checkEmbeddingModel pass the HF token via+ hubTokenHeader, never as a ?hf_token= query param, which leaks it into access logs."""src = _read("features/training/api/models-api.ts")assert src.count("hubTokenHeader(") >= 3assert "hf_token=" not in src@@ -251,9 +249,8 @@ def test_model_metadata_probe_never_puts_token_in_query():def test_model_config_page_floors_the_context_ceiling():- """The model's native max-context must be FLOORED to the step grid, never- rounded up (rounding up can offer/persist a length above the model's real- ceiling and break loading)."""+ """The native max context must be floored to the step grid, never rounded up, since rounding up+ can offer or persist a length above the real ceiling and break loading."""src = _read("features/model-picker/components/model-config-page.tsx")assert re.search(r"floorMaxSeqLength\(\s*targetIsNpu\s*\? target\.meta\.contextLength\s*"@@ -296,18 +293,16 @@ def test_auto_offload_context_is_not_below_the_fit_floor():def test_compare_load_clears_stale_native_lease():- """A compare-pane load never comes from the desktop file picker, so it must- clear any prior picked file's lease token + expiry, otherwise a reload can- send a stale lease for the now-active model."""+ """A compare-pane load must clear any prior picked file's lease token and expiry, since it never+ comes from the file picker and a reload could send a stale lease."""src = _read("features/chat/shared-composer.tsx")assert "activeNativePathToken: null" in srcassert "activeNativePathExpiresAtMs: null" in srcdef test_autoload_records_backend_loaded_model_identity():- """An inactive-cache inventory row loads by local path, so startup autoload- must key both the active checkpoint and its summary by the backend's loaded- model identity instead of the catalog repo id."""+ """Startup autoload keys the active checkpoint and its summary by the backend's loaded model+ identity, not the catalog repo id, since inactive-cache rows load by local path."""src = _read("features/chat/api/chat-adapter.ts")autoload = src.split("async function loadAutoLoadCandidate", 1)[1]autoload = autoload.split("\n try {", 1)[0]@@ -404,9 +399,8 @@ def test_recipe_model_load_toast_is_persistent_and_dismissible():def test_rollback_restores_native_lease_expiry_with_token():- """A failed model switch that rolls back to a previously loaded picked GGUF- must restore the lease expiry paired with the token, never the token alone- (which would look non-expiring and skip the expiry guard)."""+ """A rollback to a previously picked GGUF must restore the lease expiry with its token, never+ the token alone, which would look non-expiring and skip the expiry guard."""src = _read("features/chat/hooks/use-chat-model-runtime.ts")assert "previousActiveNativePathExpiresAtMs" in srcassert re.search(@@ -415,9 +409,8 @@ def test_rollback_restores_native_lease_expiry_with_token():def test_default_caches_keyed_on_inventory_version():- """The chat-template and max-position caches must key on the inventory- version so a model update in the same session invalidates the cached value- instead of showing the stale revision."""+ """The chat-template and max-position caches key on the inventory version, so a model update in+ the same session invalidates them instead of showing a stale revision."""src = _read("features/model-picker/hooks/use-model-defaults.ts")assert src.count("${inventoryVersion}") >= 2@@ -432,9 +425,8 @@ def test_hidden_infra_model_needles_present():def test_hidden_models_dynamic_exact_ids_wired():- """The configured embedder arrives from /api/hub/hidden-models as exact- repo ids; a substring needle would let a generic basename like "model"- hide unrelated chat models."""+ """The configured embedder arrives from /api/hub/hidden-models as exact repo ids and must match+ exactly, since a substring needle like model would hide unrelated chat models."""src = _read("features/hub/lib/hidden-models.ts")assert "toLowerStrings(data.exact_ids)" in srcassert "dynamicExactIds.includes(lower)" in src@@ -448,9 +440,8 @@ def test_hidden_model_matchers_refresh_with_inventory_version():def test_diffusion_capability_labeled_image_video_gen():- """The diffusion capability detects image and video GENERATORS (FLUX, SDXL,- LTX, Wan, text-to-image tags); labeling it "Image to text" showed generators- when users asked for captioning models."""+ """The diffusion capability detects image and video generators, so it must not be labeled Image+ to text, which showed generators to users looking for captioning models."""for rel in ("features/hub/lib/model-capabilities.ts","features/hub/lib/model-type-filter.ts",@@ -463,9 +454,8 @@ def test_diffusion_capability_labeled_image_video_gen():assert '{ value: "video-gen", label: "Video gen" }' in hub# The badge on a model carries the same two names.assert '"Video gen" : "Image gen"' in _read("features/hub/lib/model-capabilities.ts")- # Since #14083 the On Device list takes Discover's picks and matcher instead of- # keeping its own option list, so the names above are the only ones it shows.- # Should it grow its own list again, the diffusion entry must still name generators.+ # Since issue 14083 the On Device list reuses Discover's picks and matcher, so the names above+ # are the only ones shown; a list of its own must still name diffusion generators.on_device = _read("features/hub/lib/model-type-filter.ts")if 'value: "diffusion"' in on_device:assert '{ value: "diffusion", label: "Image/video gen" }' in on_device@@ -631,9 +621,8 @@ def test_model_default_hooks_do_not_reset_state_in_effect():def test_variant_expander_refreshes_after_delete():- """Deleting a downloaded quant from an expanded repo that still has other- cached quants must bump the expander refresh key, or the deleted quant stays- shown as downloaded and clickable and tries to reload the removed file."""+ """Deleting a quant from an expanded repo that still has cached quants must bump the refresh+ key, or the deleted quant stays clickable as downloaded and reloads a removed file."""src = _read("features/model-picker/components/model-selector/pickers.tsx")del_confirm = re.search(r"await onDeleteVariant\(v\.quant, v\.cache_ref \?\? v\.cache_path\);.*?setRefreshKey\(\(key\) => key \+ 1\)",@@ -676,9 +665,8 @@ def test_local_picker_rows_require_chat_capability():def test_a_pinned_cached_row_loads_from_the_id_the_backend_pinned():- """The cached listing pins a snapshot when the repo's default ref reaches no copy- that loads, and it is the load that has to follow the pin. The id stays the repo- id everywhere it is shown, deduped or stored, so only model_path changes."""+ """A pinned cached row loads from the snapshot the cached listing pins when the default ref has+ no loadable copy; the id stays the repo id, so only model_path changes."""inventory = _read("features/model-picker/inventory/use-chat-picker-inventory.ts")for mapper in ("toCachedGgufRepo", "toCachedModelRepo"):body = re.search(rf"function {mapper}\(.*?\n}}", inventory, re.S)@@ -759,9 +747,8 @@ def test_a_pinned_cached_row_loads_from_the_id_the_backend_pinned():def test_a_local_quant_short_a_shard_is_not_selectable():- """The variants endpoint now reports a local folder's torn quant as partial. A folder has no- download to resume, so the row has to say so and refuse the pick rather than send validate and- load at files that are not on disk."""+ """A local folder has no download to resume, so a torn quant reported as partial must be+ disabled and refused rather than sent to validate and load."""picker = _read("features/model-picker/components/model-selector/pickers.tsx")assert "const unusableLocal = isLocalPath && v.partial === true;" in pickerassert "disabled={unusableLocal}" in picker@@ -872,9 +859,8 @@ def _menu_guard_truth(src):def test_partial_safetensors_download_keeps_delete_menu():- """A stopped partial safetensors download must keep its options menu (the Delete- affordance) like the GGUF card does, or partial downloads can only be cleaned up by- finishing or leaving them."""+ """A stopped partial safetensors download keeps its options menu with Delete, as the GGUF card+ does, or partials can only be finished or left."""src = _read("features/hub/catalog/safetensors-download-card.tsx")names, shows_menu = _menu_guard_truth(src)for required in ("isDownloaded", "isPartial", "downloading", "localPath"):@@ -945,9 +931,8 @@ def test_cache_location_update_invalidates_frontend_inventory():def test_downloaded_list_offsets_virtual_rows():- """The On Device virtualized list sits below the Pinned block in the same- scroll element, so it must pass its measured offset as scrollMargin or rows- past the overscan render blank."""+ """The On Device virtual list sits below the Pinned block in the same scroll element, so it must+ pass its measured offset as scrollMargin or rows past overscan render blank."""src = _read("features/hub/catalog/models-catalog-lists.tsx")assert "scrollMargin={scrollMargin}" in src@@ -1012,9 +997,8 @@ def test_local_mtp_warning_uses_backend_source_metadata():def test_fixed_layer_gguf_pins_displayed_context():- """An already-loaded auto-fit GGUF saved with Manual fixed GPU layers must- pin the shown context, so a later fresh load keeps the fitted placement- instead of sending native/0 and recreating the OOM."""+ """A loaded auto-fit GGUF saved with Manual fixed GPU layers must pin its shown context, else a+ fresh load sends native/0 and recreates the OOM."""src = _read("features/model-picker/components/model-config-page.tsx")assert "const pinFixedLayerContext =" in srcassert 'loadableConfig.gpuMemoryMode === "manual"' in src@@ -1057,18 +1041,16 @@ def test_auto_defaults_not_persisted_as_overrides():def test_compare_pane_context_from_own_config_only():- """A compare pane's context comes from its own config only (a saved pin, else- null for Auto/native); it must not inherit the active model's shared snapshot,- which resolveFitMaxSeqLength would treat as an explicit pin (VRAM/OOM)."""+ """A compare pane takes its context only from its own config (saved pin, else null), since+ resolveFitMaxSeqLength would read the shared snapshot as an explicit pin (OOM)."""src = _read("features/chat/shared-composer.tsx")assert "const effectiveCustomContextLength = ownConfig.customContextLength;" in srcassert "compareLoadKnobs.customContextLength" not in srcdef test_reset_max_seq_length_falls_back_to_app_default():- """After Reset clears maxSeqLength (null), a non-GGUF active model's shown- max sequence length must fall back to the app default, never the loaded- runtime snapshot, or a remembered/active override can never be cleared."""+ """After Reset clears maxSeqLength, a non-GGUF model must fall back to the app default, not the+ loaded runtime snapshot, or an override can never be cleared."""src = _read("features/model-picker/components/model-config-page.tsx")assert "clampMaxSeqLength(DEFAULT_MAX_SEQ_LENGTH, nativeMaxSeqLength)" in srcassert "clampMaxSeqLength(initialMaxSeqLength" not in src@@ -1169,9 +1151,8 @@ def test_reset_enabled_for_explicit_context_pin_at_native():def test_compare_pane_non_gguf_falls_back_to_app_default():- """A non-GGUF compare pane with no saved maxSeqLength must fall back to the- shared app default, not the active model's runtime snapshot; otherwise an- unconfigured pane inherits a saved 128K neighbor's context and can OOM."""+ """A non-GGUF compare pane with no saved maxSeqLength falls back to the shared app default+ (4096), not the runtime snapshot, or it inherits a saved neighbor's 128K context and can OOM."""per_model = _read("features/model-picker/model-config/per-model-config.ts")assert "export const DEFAULT_MAX_SEQ_LENGTH = 4096;" in per_modelbarrel = _read("features/model-picker/index.ts")@@ -1373,9 +1354,8 @@ def test_chat_load_prepares_hf_token_before_gguf_metadata_preflight():def test_chat_autoload_prepares_hf_token_before_gguf_metadata_preflight():- """Background autoload performs the same GGUF classification probe as the- interactive paths, so a stale saved token must take the same recovery path.- """+ """Background autoload runs the same GGUF classification probe as interactive paths, so it+ prepares the HF token first and a stale saved token recovers the same way."""adapter = _read("features/chat/api/chat-adapter.ts")autoload = adapter.split("async function loadAutoLoadCandidate", 1)[1]autoload = autoload.split("async function autoLoadSmallestModel", 1)[0]@@ -1466,9 +1446,8 @@ def test_the_run_settings_footer_does_not_reflow_under_the_pointer():blur-committed draft mounted Save, so the click was never dispatched (#10216)."""src = " ".join(_read("features/model-picker/components/model-config-page.tsx").split())before = src.split("<RunSettingsPicker ", 1)[0]- # Opening tags of the divs enclosing the settings dropdown, nearest first. The footer column is the one- # under the rule. A wrapper just outside it (the picker's sticky pin) may vary by variant, but- # only in placement: it must not make the footer wrap either.+ # Opening div tags enclosing the settings dropdown, nearest first; the footer column is under+ # the rule, and the sticky pin wrapper may vary but must not make the footer wrap.attr = r"""(?:[^>"'{]|"[^"]*"|'[^']*'|\{(?:[^{}]|\{[^{}]*\})*\})*"""stack = []for match in re.finditer(r"<div\b(" + attr + r")>|</div>", before):@@ -1528,9 +1507,8 @@ def test_legacy_migration_is_idempotent_and_non_destructive():def test_variant_expander_forwards_the_gguf_filename():- """A quant pick must carry the exact .gguf filename. The diffusion pages load- by filename and cannot map a quant label back to one, so without it every hub- GGUF pick on Images/Video fell through to a silent return and nothing loaded."""+ """A quant pick must carry the exact .gguf filename, since diffusion pages load by filename and+ cannot map a quant label back; without it hub GGUF picks silently did nothing."""src = _read("features/model-picker/components/model-selector/pickers.tsx")assert "ggufFilename: filename," in _variant_select_meta(src)# Matched structurally, since prettier wraps the call once it grows.@@ -1589,9 +1567,8 @@ def test_a_routed_curated_pick_uses_the_same_load_spec_as_a_direct_one():def test_a_quantized_load_drops_a_lora_selection_it_cannot_bake():- """int8/fp8 builds take adapters only at load time. Switching artifact inside one family- keeps the selection (same family, no clear) while the load did not bake it, so Generate- would 400 with the picker still showing the adapter as active."""+ """int8/fp8 builds take adapters only at load time; a same-family artifact switch must not keep+ a LoRA selection the load did not bake, or Generate would 400."""src = _read("features/images/images-page.tsx")assert "bakedLorasOnLoad.current = bakeLoras.length > 0;" in srcguard = re.search(@@ -1607,9 +1584,8 @@ def test_a_quantized_load_drops_a_lora_selection_it_cannot_bake():def test_diffusion_pages_never_drop_a_gguf_pick_silently():- """The fallback branch splits a local path, so a repo pick reaching it has no- filename. It used to error; it now resolves the repo's own .gguf. Either way the- branch must act: returning with no request and no toast drops the pick."""+ """The fallback branch must always act on a GGUF pick, since returning with no request and no+ toast silently drops it; a repo pick with no filename resolves its own .gguf."""for rel in ("features/images/images-page.tsx", "features/video/video-page.tsx"):src = _read(rel)branch = re.search(@@ -1623,9 +1599,8 @@ def test_diffusion_pages_never_drop_a_gguf_pick_silently():def test_diffusion_pages_stage_downloads_through_the_manager():- """Images/Video must not download inside the load: a Hub pick with missing files goes- to the download manager first, so it shares progress, cancel/resume, disk preflight,- and manifest verification with every other model."""+ """Images and Video must stage missing Hub files through the download manager rather than inside+ the load, so they share progress, cancel/resume, disk preflight and manifest verification."""for rel in ("features/images/images-page.tsx", "features/video/video-page.tsx"):src = _read(rel)assert "useStagedDownload" in src, f"{rel}: not wired to the download manager"@@ -1645,9 +1620,8 @@ def test_diffusion_pages_stage_downloads_through_the_manager():def test_every_diffusion_planner_filters_the_cache_before_staging():- """Planning every Hub pick is only safe on a planner that skips files already on disk;- without that an unchanged, fully cached model stages its whole footprint again. The two- move together, so pin them together rather than leaving it to a comment."""+ """Planning every Hub pick is only safe if each planner skips files already on disk, else a+ fully cached model re-stages its whole footprint; the test pins both together."""root = WORKDIR / "studio" / "backend" / "core" / "inference"for name in ("diffusion.py", "sd_cpp_backend.py", "video.py"):src = (root / name).read_text(encoding = "utf-8")@@ -1660,9 +1634,8 @@ def test_every_diffusion_planner_filters_the_cache_before_staging():def test_image_load_fallback_names_requirements_instead_of_only_the_model():- """If planning fails and the backend has to fetch files inside the load, its toast must- not call companion text encoders and VAEs the selected model. The normal path stages- them through Downloads; this wording keeps the defensive fallback honest too."""+ """If planning fails and the backend fetches inside the load, the toast must name the+ requirements, not just the model, since companion text encoders and VAEs are also fetched."""src = _read("features/images/images-page.tsx")assert '"Downloading model requirements…"' in srcassert '"Downloading model…"' not in src@@ -1670,9 +1643,8 @@ def test_image_load_fallback_names_requirements_instead_of_only_the_model():def test_a_hidden_diffusion_page_does_not_load_when_its_download_lands():- """Images and Video stay mounted behind the router, and a load evicts whoever holds the- GPU. A multi-GB staged download finishing while the user is on another page must not take- the model out from under them; the pick waits for its page to be visible again."""+ """Images and Video stay mounted behind the router and a load evicts whoever holds the GPU, so a+ staged download landing while the page is hidden must wait until visible again."""for rel in ("features/images/images-page.tsx", "features/video/video-page.tsx"):src = _read(rel)ready = re.search(r"onReady: \(\) => \{.*?\n \},", src, re.S)@@ -2074,9 +2046,8 @@ def test_on_device_rows_carry_the_task_the_pickers_filter_on():def test_local_diffusion_routing_is_keyed_by_the_id_the_row_selects():- """A local row's click passes m.id (a filesystem load id), while m.model_id is its HF-style- name. Keying the routing map on one alone let the lookup miss, so the pick fell through to the- chat loader instead of navigating to Images or Video."""+ """A local row's click passes m.id (a filesystem load id), while m.model_id is an HF-style name,+ so the diffusion routing map must be keyed by the id the row selects."""src = _read("features/model-picker/components/model-selector/pickers.tsx")block = re.search(r"const diffusionTaskById = useMemo\(.*?\n \}, \[", src, re.S)assert block, "diffusionTaskById not found"@@ -2300,9 +2271,8 @@ def test_parallel_slots_are_never_recorded_for_a_diffusion_load():def test_hydration_restores_a_remembered_slot_override():- """The control is never seeded from the status echo, so a model running on a remembered- override shows a BLANK slot control after a browser reload or a tab move to another- GGUF."""+ """Hydration must restore a remembered slot override via resolveResidentInitialConfig, since the+ control is never seeded from the status echo and would show blank after a reload."""src = _read("features/chat/lib/apply-inference-status-to-store.ts")status = " ".join(src.split())assert (@@ -2641,9 +2611,8 @@ def test_only_gguf_configs_are_mirrored_to_the_server():def test_a_native_leased_gguf_is_not_mirrored_to_the_server():- """A dropped or file-picked GGUF loads through a signed native-path lease, and- /api/inference/status reports model_identifier as null for it, so the checkpoint the- browser keys settings by is the bare file name the backend echoes back."""+ """A GGUF loaded via a signed native-path lease is not mirrored to the server;+ /api/inference/status reports model_identifier as null, so the echoed file name is the key."""page = " ".join(_read("features/model-picker/components/model-config-page.tsx").split())assert "&& !nativePathToken ) { syncModelOverride(" in pageassert (@@ -2801,9 +2770,8 @@ def test_backfill_includes_a_standalone_gguf_with_no_variant():def test_monitor_overlay_does_not_pull_in_the_lazy_page():- """The overlay is mounted from __root.tsx, so a static import of the page for two label- helpers drags the whole 900-line page and its dependency graph into the eagerly- loaded bundle and undoes the route's lazyRouteComponent."""+ """The overlay is mounted from __root.tsx, so it takes label helpers from lifecycle; importing+ the page would pull it into the eager bundle and undo lazyRouteComponent."""overlay = _read("features/api-monitor/api-monitor-overlay.tsx")assert 'from "./lifecycle"' in overlayassert "api-monitor-page" not in overlay, "the overlay must not reach the page"@@ -2813,9 +2781,8 @@ def test_monitor_overlay_does_not_pull_in_the_lazy_page():def test_override_writes_are_ordered_per_model():- """Two saves for one model, or a save racing the one-time backfill, started independent- requests with no sequencing, so the older response could commit last and resurrect- the entry the newer one meant to replace."""+ """Override writes are ordered per model with one in-flight promise per key, so an older save+ response cannot commit last and resurrect an entry a newer save replaced."""src = " ".join(_read("features/model-picker/api/model-overrides.ts").split())# One in-flight promise per key is the ordering; what it resolves to is not.assert (@@ -2841,9 +2808,8 @@ def test_backfill_skips_future_schema_local_records():def test_a_failed_detail_fetch_is_retried():- """A terminal row's updated_at never advances and selectedIsMissing stays true, so a- fetch that failed had nothing left to re-run the effect and the payload stayed- unavailable until another row was selected."""+ """A failed detail fetch is retried up to DETAIL_FETCH_ATTEMPTS, because a terminal row's+ updated_at never advances and nothing else would re-run the effect."""src = " ".join(_read("features/api-monitor/api-monitor-page.tsx").split())assert "const DETAIL_FETCH_ATTEMPTS = 3;" in srcassert "const detailInFlight = selectedId_ != null && loadingDetails.has(selectedId_);" in src@@ -2959,9 +2925,8 @@ def test_the_chat_picker_marks_ollama_targets_unloadable_by_the_api():def test_the_backfill_fills_in_fields_rather_than_skipping_known_keys():- """The backfill reads the override map once and then writes each model in turn, so a- save by another tab during that pass was overwritten by this browser's older- localStorage copy."""+ """The backfill reads the override map once, so another tab's save during that pass must not be+ overwritten; fillAbsentFields fills what the server lacks, not just by key presence."""backfill = " ".join(_read("features/model-picker/api/migrate-model-overrides.ts").split())assert "{ fillAbsentFields: true }," in backfill# Key presence alone is not "done": what the server lacks decides.@@ -3064,9 +3029,8 @@ def test_the_sidebar_settings_editor_reseeds_when_the_live_config_lands():def test_a_standalone_gguf_has_one_settings_identity_in_the_picker():- """A loose .gguf has no quant to choose between, but llama_cpp falls back to- _extract_quant_label(gguf_path) when a load names no variant, and /status echoes- that as gguf_variant."""+ """A loose .gguf has no quant to choose between, yet llama_cpp falls back to+ _extract_quant_label when a load names no variant, and /status echoes that as gguf_variant."""resident = " ".join(_read("features/model-picker/model-config/model-config-handoff.ts").split())assert ("const settingsGgufVariant = isStandaloneGgufPath(modelId) ? null : ggufVariant;"@@ -3114,9 +3078,8 @@ def test_a_local_quant_folder_lists_its_variants_by_path():def test_a_repo_id_ending_in_gguf_keeps_its_quant():- """Repo ids ending in .gguf are real on the Hub, an iMat repo among them, and- those hold every quant. A suffix-only test reads one as a single file, drops- the variant, and saves Q4 and Q8 under one key."""+ """Hub repo ids may end in .gguf (an iMat repo among them) and hold every quant, so a+ suffix-only test would drop the variant and save Q4 and Q8 under one key."""identity = " ".join(_read("features/hub/lib/model-identity.ts").split())assert "if (modelId == null || !GGUF_SUFFIX_RE.test(modelId)) { return false; }" in identityassert "PUBLIC_ID_PATH_PREFIX_RE.test(modelId) ||" in identity@@ -3188,9 +3151,8 @@ def test_picker_popover_and_trigger_keep_their_tour_hooks():def test_run_settings_gear_label_names_its_model():- """The driver cannot reach the gear through the row -- it is a sibling at 2 of its- render sites and an uncle at the rest -- so it matches on this label, and the model- name in it is what keeps it off another row's gear."""+ """The driver cannot reach the gear through the row (a sibling at two render sites, an uncle at+ the rest), so it matches this label; the model name keeps it off another row's gear."""pickers = _read("features/model-picker/components/model-selector/pickers.tsx")# The expander's own label is the only one naming both repo and quant.assert (@@ -3453,9 +3415,8 @@ def test_cached_inventory_lookups_take_the_run_signal():def test_download_cancel_survives_the_pending_start_window():- """cancel() no-ops on a key with no job, so a click during requestStart's- preflights is replayed once the job exists, and exactly once: cancelling- patches the job and wakes the subscription."""+ """cancel() no-ops on a key with no job, so a cancel clicked during requestStart's preflights is+ replayed exactly once when the job exists, patching it and waking the subscription."""src = _read("features/chat/api/chat-adapter.ts")helper = src.split("async function ensureDefaultModelDownloaded", 1)[1]helper = helper.split("async function autoLoadSmallestModel", 1)[0]@@ -3483,9 +3444,8 @@ def test_a_failed_quant_is_marked_tried_so_the_repo_continues():def test_local_safetensors_chat_capability_is_classified_not_assumed():- """An embedding export is config.json plus model.safetensors, which the- format-only rule marked chat-capable, and it is small enough to be tried- first."""+ """An embedding export (config.json plus model.safetensors) is small enough to be tried first,+ so chat capability must be classified, not assumed from format alone."""src = _read_backend("hub/services/models/common.py")assert "def _local_transformers_can_chat(" in srcassert "can_chat_override" in src@@ -3697,9 +3657,8 @@ def test_the_gguf_footprint_is_resolved_per_dependency_group_not_per_repo():def test_every_footprint_group_gets_its_own_resolve_call():- """One request per distinct key. The ordinary repo has exactly one key, so the- common case stays exactly one request, which is what the representative scheme- exists to protect."""+ """Each distinct footprint dependency key gets its own resolve call; an ordinary repo has one+ key, keeping the common case at one request as the representative scheme requires."""src = _read("features/model-picker/components/model-selector/pickers.tsx")effect = src.split("const [companionBytesByKey, setCompanionBytesByKey]", 1)[1]effect = effect.split("const variantOptionKeys = useMemo(", 1)[0]@@ -3781,9 +3740,8 @@ def test_the_dependency_key_survives_the_variant_validator():def test_the_backend_keys_the_footprint_on_family_and_text_encoders():- """Both sources of variation have to be in the key. Folding in only the family- would give klein-4B and klein-9B the same key inside one repo, which is the- exact case the per-row lookup exists for."""+ """The backend footprint key must include both family and text encoders, since family alone+ would give klein-4B and klein-9B the same key inside one repo."""src = _read_backend("hub/services/models/gguf_variants.py")helper = src.split("def _variant_dependency_key(", 1)[1].split("\ndef ", 1)[0]assert "detect_family_for_pick(repo_id, filename)" in helper@@ -3863,9 +3821,8 @@ def test_a_download_only_pick_does_not_strand_a_staged_load():def test_every_optimistic_pick_hands_its_label_back_under_a_guard():- """`quantRevert` is one slot. A pick that no longer owns the page must not revert over the label- a newer pick has already set, so every `!started` rollback is guarded. Two branches lost that- guard when they moved from `handleLoad` to `loadOrStage`."""+ """quantRevert is one slot: every !started rollback must stay guarded or a stale pick reverts a+ newer label; two branches lost the guard moving to loadOrStage."""src = _read("features/images/images-page.tsx")start = src.index("const handleModelSelect = useCallback(")# handleDeployAdapter rolls back a deploy, not a pick.@@ -3911,9 +3868,8 @@ def test_a_download_only_pick_claims_no_label_rollback():def test_a_routed_download_only_arrival_claims_nothing():- """A ?model= arrival from the chat picker or the Hub takes the page like a direct pick. Under- Download only it must not: claiming there revokes the token of a load that is already staging,- and resumePendingLoad then drops that load once its files have finished arriving."""+ """Under Download only, a ?model= arrival must not claim the page: claiming revokes the token of+ a load already staging, and resumePendingLoad then drops it once its files arrive."""src = _read("features/images/images-page.tsx")body = re.search(r"const handledRouteModel = useRef(.*?)\n \]\);", src, re.S)assert body, "the routed-pick effect was not found; this guard has gone stale"@@ -3939,9 +3895,8 @@ def test_an_unresolvable_download_only_gguf_hands_nothing_back():def test_a_download_only_pick_is_allowed_while_the_page_is_busy():- """The busy guard exists because the backend 409s a second load. A Download only pick submits- no load, and the selector stays interactive during a generation, so refusing it there was a- silent dead click: the user picked a model to download and nothing happened."""+ """The busy guard only exists because the backend 409s a second load; a Download only pick+ submits none, so refusing it while busy was a silent dead click."""src = _read("features/images/images-page.tsx")body = re.search(r"const handleModelSelect = useCallback\(\n(.*?)\n \);", src, re.S)assert body, "handleModelSelect not found"diff --git a/tests/studio/test_overlay_layering.py b/tests/studio/test_overlay_layering.pyindex f1c235b0da5..55ccda026f2 100644--- a/tests/studio/test_overlay_layering.py+++ b/tests/studio/test_overlay_layering.py@@ -65,9 +65,8 @@ def test_the_front_panel_does_not_climb_past_the_layer_above_it():@pytest.mark.parametrize("path", [MONITOR, API_PANEL])def test_both_floating_panels_stack_on_the_shared_layer(path: Path):- """Both containers take their z-index from the order store, not from a class.- Sharing the layer is what lets the one the user touched last come forward,- which is the only way out of a monitor resized over the whole viewport."""+ """Both containers take z-index from the shared order store rather than a class, so the panel+ touched last comes forward; this is the only way out of a monitor resized over the viewport."""container = _container(path, "setConstraintsElement")style_applies_shared_layer = re.search(r"style=\{\{\s*zIndex\s*[,}]", container) or re.search(r"style=\{floatingMonitorConstraintStyle\(\{\s*zIndex,", containerdiff --git a/tests/studio/test_pwsh_calls_use_the_shared_runner.py b/tests/studio/test_pwsh_calls_use_the_shared_runner.pyindex a7b5631ed50..4b787abf349 100644--- a/tests/studio/test_pwsh_calls_use_the_shared_runner.py+++ b/tests/studio/test_pwsh_calls_use_the_shared_runner.py@@ -189,9 +189,8 @@ def scan_tests() -> dict[str, list[tuple[int, str]]]:class TestEveryPwshCallUsesTheSharedRunner:def test_no_test_file_spawns_powershell_directly(self):- """The guard itself. A new direct call site fails here with its own line number,- rather than as an unrelated FileLoadException in someone else's test a month- later."""+ """The guard itself: a new direct call site fails here with its own line number, not as an+ unrelated FileLoadException in another test."""offenders = {rel: callsfor rel, calls in scan_tests().items()diff --git a/tests/studio/test_reveal_file_manager_matrix.py b/tests/studio/test_reveal_file_manager_matrix.pyindex 558abd69e36..64d8df1f094 100644--- a/tests/studio/test_reveal_file_manager_matrix.py+++ b/tests/studio/test_reveal_file_manager_matrix.py@@ -225,9 +225,8 @@ def test_a_broken_symlink_launches_nothing_anywhere(host, spawned, tmp_path, reqclass _VanishesAfterTheGuard:- """There for the existence guard, gone by the branch. The two are separate- stats, and a chat deleted or migrated in between is what the endpoint's own- tests already simulate one layer up."""+ """Present for the existence guard but gone by the branch, since the two are separate stats; a+ chat deleted or migrated in between is simulated one layer up by the endpoint's own tests."""def __init__(self, real: Path) -> None:self._real = real@@ -265,9 +264,8 @@ def test_a_target_that_vanishes_after_the_guard_never_opens_its_parent(class _SwappedForAFile:- """A checked directory replaced by a regular file before the open. A tool- runs inside its own sandbox and can do this, and the file branch names the- parent on every platform."""+ """A checked directory replaced by a regular file before the open; a tool inside its own sandbox+ can do this, and the file branch names the parent on every platform."""def __init__(self, real: Path) -> None:self._real = realdiff --git a/tests/studio/test_studio_gguf_export_script_pin.py b/tests/studio/test_studio_gguf_export_script_pin.pyindex 9ee59b15e86..ba6e81f2c42 100644--- a/tests/studio/test_studio_gguf_export_script_pin.py+++ b/tests/studio/test_studio_gguf_export_script_pin.py@@ -202,9 +202,8 @@ def test_the_pin_is_never_left_in_the_environment():def test_pin_prefers_the_internal_helper():- """unsloth_zoo exempts a user pin from the strict converter scan, so Studio's own- routing has to be marked as internal or the exemption is taken by a converter nobody- reviewed."""+ """unsloth_zoo exempts a user pin from the strict converter scan, so Studio's own routing must+ be marked internal or the exemption goes to an unreviewed converter."""helper = _pin_helper_node(TREE)assert helper is not Noneimported = [diff --git a/tests/studio/test_ui_font_scale_contract.py b/tests/studio/test_ui_font_scale_contract.pyindex b12a55f8f0a..5a04671b0dc 100644--- a/tests/studio/test_ui_font_scale_contract.py+++ b/tests/studio/test_ui_font_scale_contract.py@@ -118,9 +118,8 @@ def test_radix_select_viewport_owns_the_scroll_state():def test_cn_knows_the_ui_typography_tokens():- """Stock tailwind-merge classifies text-ui-* as a text color and deletes- it whenever a real color class follows in the same cn() call, so the- element falls back to the unscaled inherited font size."""+ """Stock tailwind-merge treats the text-ui- prefixed classes as text colors and drops them when+ a real color follows in the same cn() call, falling back to the unscaled font size."""assert "extendTailwindMerge" in UTILSassert '"font-size": [{ text: [isUiToken] }]' in UTILSassert "leading: [{ leading: [isUiToken] }]" in UTILSdiff --git a/tests/studio/test_update_release_notes.py b/tests/studio/test_update_release_notes.pyindex 93f84a5f3bc..44b47c79079 100644--- a/tests/studio/test_update_release_notes.py+++ b/tests/studio/test_update_release_notes.py@@ -712,9 +712,8 @@ def test_every_refusal_records_a_deadline_retry_has_to_wait_out(notes_module):def test_the_page_asked_for_fits_under_the_read_cap(notes_module, serve_releases):- """A release entry carries its whole body, so the page size and the byte cap- are one decision: the endpoint's maximum of 100 is near 4 MiB against a- 2 MiB cap, and the fetch then fails outright."""+ """A release entry carries its whole body, so per_page and the byte cap are one decision: the+ endpoint's maximum of 100 is near 4 MiB against a 2 MiB cap."""import urllib.parsequery = urllib.parse.urlparse(notes_module.RELEASES_API_URL).query@@ -1899,9 +1898,8 @@ def test_an_escaped_mark_makes_an_image_a_link():def test_only_markdown_line_endings_split_the_changelog(notes_module):- """str.splitlines also breaks on U+2028, U+2029, NEL, vertical tab and form- feed, none of which end a CommonMark line: one in prose indexed a release- the renderer never shows and truncated the notes above it."""+ """str.splitlines also breaks on U+2028, U+2029, NEL, vertical tab and form feed, which do not+ end a CommonMark line; one in prose indexed a release the renderer never shows."""text = "## 2.0\n\nnote with a separator ## 9.9.9\n\n## 1.0\n\n- old\n"assert [e.version for e in parse_sections(notes_module, text)] == ["2.0", "1.0"]entry = find_section(notes_module, text, "2.0")@@ -1915,9 +1913,8 @@ def test_only_markdown_line_endings_split_the_changelog(notes_module):def test_link_resolver_reads_comments_before_fences():- """A fence delimiter inside an HTML comment is not a fence: reading it as one- left the fence open, so every link below went unresolved. The order matters- both ways, so a comment opener inside a real fence is not a comment."""+ """A fence delimiter inside an HTML comment is not a fence, and a comment opener inside a real+ fence is not a comment; the read order matters both ways."""links = LINKS.read_text(encoding = "utf-8")# Fence state is read before comments are masked, the order the collapsed preview uses.assert "const fenceSource = inComment\n ? null\n : FENCE.exec(" in links@@ -1942,10 +1939,8 @@ def test_preview_heading_and_quote_markers_follow_the_backend_rule():def test_preview_collects_labels_only_from_real_definitions():- """A definition-shaped line inside indented code or a deep fence is literal,- so recording its label made toPlainText strip brackets the expanded view- keeps. The pre-scan skips the same code the collector pass skips; a real- definition takes at most three spaces, so the indent test cannot reject one."""+ """Definition-shaped lines in indented code or deep fences are literal, so the label pre-scan+ skips the code the collector skips; real definitions indent at most three spaces."""src = PREVIEW.read_text(encoding = "utf-8")scan = src.index("const labels = new Set<string>();")collect = src.index("let deepFence: string | null = null;")@@ -1968,10 +1963,8 @@ def test_an_html_block_to_the_left_of_a_list_item_closes_it(notes_module):def test_the_download_panel_can_shrink_inside_the_capped_stack():- """The stack is capped to the viewport and a flex item defaults to- min-height:auto, so this wrapper could not shrink and the cap was absorbed by- the fixed update card rather than the scrolling download list. Only the- shared-stack branch needs it; standalone is fixed and not a flex item."""+ """The stack is capped to the viewport and a flex item defaults to min-height:auto, so the+ wrapper must set min-h-0 to shrink; only the shared-stack branch needs it."""panel = (FRONTEND / "features/hub/download-manager/download-manager-panel.tsx").read_text(encoding = "utf-8")@@ -1983,11 +1976,9 @@ def test_the_download_panel_can_shrink_inside_the_capped_stack():@pytest.fixture(scope = "module")def run_scanner(tmp_path_factory):- """Run the frontend's markdown scanners under node.-- Their job is to classify a line the way a CommonMark renderer would, which- only a real run can show. The "@/lib" alias resolves through Vite, not node,- so the copies have it rewritten."""+ """Runs the frontend markdown scanners under node, since only a real run shows how a CommonMark+ renderer classifies a line; @/lib resolves through Vite, not node, so the copies are+ rewritten."""node = shutil.which("node")if node is None:pytest.skip("node is needed to run the TypeScript scanners")@@ -2016,10 +2007,8 @@ def preview_leads(preview) -> list[str]:def test_a_link_indented_under_a_bullet_still_resolves(run_scanner):- """CommonMark measures indentation from the container (spec 0.31.2 section- 5.2), so under "- Details:" a four-space line is two columns in: a paragraph- holding a link. Measuring from the margin called it code (section 4.4) and- left the destination relative to Unsloth's own origin."""+ """CommonMark measures indentation from the container (spec 0.31.2 section 5.2); measuring from+ the margin read such a link as code (section 4.4), leaving it relative to Unsloth's origin."""resolved = run_scanner("links", "- Details:\n\n [guide](docs/a.md)\n")assert "https://github.com/unslothai/unsloth/blob/main/docs/a.md" in resolvedcode = run_scanner("links", "- Added.\n\n [guide](docs/a.md)\n")@@ -2070,9 +2059,8 @@ def test_a_fence_inside_a_list_item_ends_with_the_item(notes_module):def test_stripping_comments_stays_linear_in_the_code_spans(notes_module):- """The comment scanner restarted its code-span search per opener, so N spans- cost N squared. A 203 KiB line is well inside the 2 MiB accepted, and notes- are reparsed on every request, so one held a worker for over ten seconds."""+ """The comment scanner restarted its code-span search per opener, so N spans cost N squared;+ notes are reparsed on every request, so the scan must stay linear."""# A quarter of the budget form's size: the big leg is the 16_000 it was checked at.spans = 4_000assert len("`a` <!--x--> " * (spans * 4)) < notes_module.RELEASES_MAX_BYTES@@ -2087,9 +2075,8 @@ def test_stripping_comments_stays_linear_in_the_code_spans(notes_module):def test_the_three_scanners_share_one_list_column_rule():- """The parser and both frontend scanners must classify a line the same way;- drifting on indentation is what put a paragraph link inside a code block.- The frontend pair shares one module, ported from the backend's tracker."""+ """The backend parser and both frontend scanners must classify a line the same way; the frontend+ pair shares one module ported from the backend's _open_lists tracker."""shared = LIST_COLUMNS.read_text(encoding = "utf-8")assert "export function openLists(" in sharedassert "_open_lists" in shared, "the backend function this mirrors"@@ -2122,9 +2109,8 @@ def test_a_failed_fetch_keeps_retry_reachable():def test_an_unclosed_comment_in_prose_cannot_hide_later_links(run_scanner):- """CommonMark opens an HTML block (spec 0.31.2 section 4.6, type 2) only when- the line begins with `<!--`; one mid-sentence is inline and cannot outlive- its block. Carrying the unclosed state on masked every link below it."""+ """CommonMark opens an HTML block (spec 0.31.2 section 4.6, type 2) only when a line begins with+ an HTML comment opener; mid-sentence it is inline and must not hide later links."""repo = "https://github.com/unslothai/unsloth/blob/main/docs/a.md"item = run_scanner("links", "- Type <!-- to begin a comment\n- See [docs](docs/a.md)\n")assert repo in item@@ -2139,9 +2125,8 @@ def test_an_unclosed_comment_in_prose_cannot_hide_later_links(run_scanner):def test_a_bare_level_two_marker_ends_the_release(notes_module, run_scanner):- """An ATX heading's opening sequence may be followed by the end of the line- (spec 0.31.2 section 4.2), so a bare `##` is an empty level-two heading.- Requiring whitespace kept everything below it inside the release above."""+ """A bare ## line is an empty ATX heading (spec 0.31.2 section 4.2) that ends the release;+ requiring whitespace after the marker kept the content below inside it."""text = "## 2.0\n\n- new thing\n\n##\n\n- SECRET: not part of 2.0\n"entry = find_section(notes_module, text, "2.0")assert "new thing" in entry.body@@ -2154,10 +2139,8 @@ def test_a_bare_level_two_marker_ends_the_release(notes_module, run_scanner):def test_a_comment_between_bullets_closes_the_list(notes_module, run_scanner):- """A comment is an HTML block (spec 0.31.2 section 4.6, type 2), so one at- the margin under a bullet closes the list. Blanking the line before list- tracking saw it reads as a blank line, which leaves the item open and made- the release heading below look like nested content."""+ """A comment at the margin is an HTML block (spec 0.31.2 section 4.6, type 2) that closes the+ list; blanking it as a blank line left the item open and the heading looking nested."""text = "## 1.0\n\n- old item\n<!-- separator -->\n ## 2.0\n\n- new item\n"assert [e.version for e in parse_sections(notes_module, text)] == ["1.0", "2.0"]assert "new item" not in find_section(notes_module, text, "1.0").body@@ -2199,9 +2182,8 @@ def test_a_parenthesised_link_destination_still_resolves(run_scanner):def test_a_fence_inside_a_container_still_hides_its_sample(run_scanner):- """A fence is measured from its container (spec 0.31.2 section 4.5), so- `> ~~~` and one under a nested bullet both open a fence. Reading the margin- never saw them, so a link in a code block was rewritten into verbatim text."""+ """A fence is measured from its container (spec 0.31.2 section 4.5), so a fence in a quote or+ under a nested bullet opens; reading only the margin rewrote its links."""quoted = run_scanner("links", "> ~~~\n> [guide](docs/a.md)\n> ~~~\n")assert "[guide](docs/a.md)" in quoted and "github.com" not in quotednested = run_scanner("links", "- a\n - b\n ~~~\n [x](docs/x.md)\n ~~~\n")@@ -2219,9 +2201,8 @@ def test_a_fence_inside_a_container_still_hides_its_sample(run_scanner):def test_an_html_block_inside_a_container_is_literal_too(run_scanner):- """Type 1 and type 6 blocks are measured from their container too, so a- `<details>` under a nested bullet and a `<pre>` in a quote are verbatim.- Missing the opener rewrote the literal examples inside them."""+ """Type 1 and type 6 HTML blocks are measured from their container too, so details and pre+ inside a bullet or quote are verbatim; missing them rewrote the literal examples."""nested = run_scanner("links", "- a\n - b\n <details>\n [x](docs/x.md)\n </details>\n")assert "[x](docs/x.md)" in nested and "github.com" not in nestedquoted = run_scanner("links", "> <pre>\n> [x](docs/x.md)\n> </pre>\n")@@ -2276,10 +2257,8 @@ def test_indented_code_before_an_ordered_marker_still_opens_a_list(notes_module)def test_a_fence_written_as_an_item_first_content_opens_in_that_item(run_scanner):- """A block straight after a marker is the item's own first content, measured- from where that content starts (spec 0.31.2 section 5.2), so "- ```md" opens- a fence. Reading the whole line never saw one, so the sample below was- treated as prose and rewritten, and its info string became a headline."""+ """A block straight after a list marker is the item's first content, measured from where it+ starts (spec 0.31.2 section 5.2), so a fence there opens; reading the whole line missed it."""sample = run_scanner("links", "- ```md\n [example](docs/a.md)\n ```\n")assert "[example](docs/a.md)" in sample and "github.com" not in sampleordered = run_scanner("links", "1. ~~~\n [example](docs/a.md)\n ~~~\n")@@ -2293,9 +2272,8 @@ def test_a_fence_written_as_an_item_first_content_opens_in_that_item(run_scannerdef test_an_html_block_ends_with_the_item_it_was_written_in(notes_module, run_scanner):- """An HTML block takes no lazy continuation line, so one opened on an item's- continuation line ends with the item, as a fence there does. Ending it only- on a blank line let it swallow the next release heading."""+ """An HTML block takes no lazy continuation line, so one opened in an item ends with that item,+ as a fence does; ending it only on a blank line swallowed the next release."""text = "## 1.0\n\n- item\n\n <div>\n## 2.0\n\n- new thing\n"assert [e.version for e in parse_sections(notes_module, text)] == ["1.0", "2.0"]assert "new thing" in find_section(notes_module, text, "2.0").body@@ -2310,10 +2288,8 @@ def test_an_html_block_ends_with_the_item_it_was_written_in(notes_module, run_scdef test_a_comment_may_close_on_a_later_line_of_its_paragraph(run_scanner):- """A comment written mid-sentence belongs to its paragraph, so its `-->` may- arrive on a later line of it and everything between renders as nothing.- Ending it at its own line left a backtick inside pairing with a real one- below, hiding a link, and left the preview quoting hidden text."""+ """A mid-sentence comment belongs to its paragraph, so its closing delimiter may come on a later+ line; ending it at its own line let a backtick pair up and hide a link."""carried = run_scanner("links", "Note <!-- ` open\nstill --> see [d](docs/a.md) and `x`\n")assert "https://github.com/unslothai/unsloth/blob/main/docs/a.md" in carriedinside = run_scanner("links", "Note <!-- see [c](docs/c.md)\nmore --> end\n")@@ -2344,10 +2320,8 @@ def test_only_punctuation_is_escapable_in_a_link_destination(run_scanner):def test_one_definition_does_not_hide_the_next(run_scanner):- """Definitions may run consecutively (spec 0.31.2 section 4.7) and none is- paragraph text, so none opens a paragraph the next cannot interrupt.- Counting one as prose left every definition after the first unresolved.- The backend already reads the line this way."""+ """Consecutive link definitions (spec 0.31.2 section 4.7) are not paragraph text, so counting+ one as prose left the next unresolved; the backend already reads them this way."""text = ("- AMD support is here, see [the AMD guide][amd] and the\n"" [Intel notes][xpu].\n\n"@@ -2365,10 +2339,8 @@ def test_one_definition_does_not_hide_the_next(run_scanner):def test_a_comment_closed_on_its_own_line_still_closes(run_scanner):- """A multiline comment is usually closed by a `-->` on a line of its own, and- a wrapped line may open with emphasis. Reading any leading punctuation as a- new block meant neither continued the paragraph, so the comment never closed- and the popup showed the author's internal note."""+ """A multiline comment is often closed on a line of its own, and a wrapped line may open with+ emphasis; reading that punctuation as a new block left the note visible."""closer = run_scanner("preview","- DoRA training is available in Unsloth. <!-- TODO confirm the exact\n"@@ -2392,10 +2364,8 @@ def test_a_comment_closed_on_its_own_line_still_closes(run_scanner):def test_a_comment_written_as_an_item_first_content_is_a_block(notes_module, run_scanner):- """A comment is an HTML block (spec 0.31.2 section 4.6, type 2), so one- written as an item's first content opens inside that item, as a fence does.- Looking for the opener at the margin let a marker in front of it hide the- block, so the resolver rewrote hidden text and the preview quoted it."""+ """A comment as an item's first content is an HTML block inside that item (spec 0.31.2 section+ 4.6, type 2); finding its opener only at the margin let a marker before it hide the block."""item = run_scanner("links", "- <!-- new --> AMD support, see [the guide](docs/amd.md)\n")assert item == "- <!-- new --> AMD support, see [the guide](docs/amd.md)\n"for text in (@@ -2551,9 +2521,8 @@ def test_a_paragraph_install_block_keeps_its_platform_headings(notes_module):def test_a_platform_heading_opens_an_install_block_on_its_own(notes_module):- """`v0.1.0-beta` and `v0.1.41-beta` head their commands with a bare platform- heading, so requiring an "Updating" above it left them in the popup. All- seven platform headings in the 24 published bodies head an install block."""+ """v0.1.0-beta and v0.1.41-beta head commands with a bare platform heading, so no Updating line+ may be required; all seven platform headings in the bodies open a block."""body = ("Intro.\n\n""#### macOS, Linux, WSL:\n```\ncurl -fsSL https://unsloth.ai/install.sh | sh\n```\n\n"diff --git a/tests/studio/test_usable_sync_api.py b/tests/studio/test_usable_sync_api.pyindex 09900da40f3..b12326312a5 100644--- a/tests/studio/test_usable_sync_api.py+++ b/tests/studio/test_usable_sync_api.py@@ -16,9 +16,8 @@ from _playwright_robust import usable_sync_api # noqa: E402def _sync_api_stub() -> types.ModuleType:- """The shape test_heavy_thread_measurement_integrity.py installs: every name answers with a- callable that raises, dunders do not. Rebuilt here rather than imported, since importing- that module installs its stub and loads its harness as a side effect."""+ """Rebuilds the stub test_heavy_thread_measurement_integrity.py installs, where non-dunder names+ are raising callables; importing that module has side effects."""module = types.ModuleType("playwright.sync_api")def __getattr__(name):diff --git a/tests/studio/test_usage_examples_model_source_contract.py b/tests/studio/test_usage_examples_model_source_contract.pyindex 6cfd4505a3d..ba4264e472c 100644--- a/tests/studio/test_usage_examples_model_source_contract.py+++ b/tests/studio/test_usage_examples_model_source_contract.py@@ -153,9 +153,8 @@ def test_api_monitor_renders_lifecycle_rows():def test_auto_switch_section_sits_below_the_monitor_link():- # #14455 moved the usage examples up, under the key form (api-settings-tab.test.ts pins that), and- # #15467 put them behind ApiExamplesPanel's tab row; the auto-switch section still follows the- # monitor link, whatever props the link takes.+ # Issue 14455 moved the usage examples up under the key form (api-settings-tab.test.ts pins+ # that) and issue 15467 behind ApiExamplesPanel's tab row; auto-switch follows the monitor link.tab = API_KEYS_TAB_TSX.read_text(encoding = "utf-8")def at(pattern):diff --git a/tests/studio/test_version_compat_bundle.py b/tests/studio/test_version_compat_bundle.pyindex 92d486c9003..36a51453eb4 100644--- a/tests/studio/test_version_compat_bundle.py+++ b/tests/studio/test_version_compat_bundle.py@@ -164,9 +164,8 @@ def test_the_install_bearing_jobs_were_not_folded_in() -> None:def test_every_test_file_a_job_runs_triggers_the_workflow() -> None:- """A file only this workflow executes must be in its pull_request paths, or a PR that only- edits (or weakens) that file never runs it. The modules.json trust gate is the case that- prompted this: the CPU repo-test shards skip it, so this workflow is its only runner."""+ """A file only this workflow runs must be in its pull_request paths, or a PR editing it never+ runs it; CPU repo-test shards skip the modules.json trust gate, so this is its only runner."""from fnmatch import fnmatchdoc = _doc()diff --git a/tests/studio/test_wsl_shortcut_script_is_valid_powershell.py b/tests/studio/test_wsl_shortcut_script_is_valid_powershell.pyindex 86b04846c66..f1ad3908ece 100644--- a/tests/studio/test_wsl_shortcut_script_is_valid_powershell.py+++ b/tests/studio/test_wsl_shortcut_script_is_valid_powershell.py@@ -138,11 +138,8 @@ def test_the_icon_refresh_python_notifies_each_shortcut_then_the_shell() -> None@needs_pwshdef test_the_icon_refresh_launch_runs_one_interpreter_with_every_shortcut(tmp_path: Path) -> None:- """The PowerShell half: candidate order, the WindowsApps skip, argv quoting, stop on success.-- The block is lifted from the rendered script as written; only the elevation probe, which has- no answer off Windows, is pinned to "not elevated".- """+ """The PowerShell half checks candidate order, the WindowsApps skip, argv quoting and stop on+ success; only the elevation probe is pinned to not elevated off Windows."""import jsonrendered = _render()diff --git a/tests/studio/test_zoo_suite_parallel_isolation.py b/tests/studio/test_zoo_suite_parallel_isolation.pyindex c482b1b90df..552f3af7a2a 100644--- a/tests/studio/test_zoo_suite_parallel_isolation.py+++ b/tests/studio/test_zoo_suite_parallel_isolation.py@@ -188,9 +188,8 @@ def test_the_mlx_group_runs_serially_and_skips_the_per_file_three() -> None:def test_an_empty_mlx_group_stops_the_step_instead_of_collecting_everything() -> None:- """The group is passed unquoted, so an empty list is not an empty run: with nothing- in ``mlx_group`` the command collects the whole rootdir instead, green and far- slower. The glob only has to stop matching once, upstream renaming the family say."""+ """The mlx group is passed unquoted, so an empty glob makes the command collect the whole+ rootdir, green and far slower; the step must stop when the glob matches nothing."""text = WORKFLOW.read_text(encoding = "utf-8")assert 'if [ -z "$mlx_group" ]' in text, ("nothing checks that the mlx group glob matched anything, so an empty glob "@@ -326,9 +325,8 @@ def test_the_shared_preamble_is_not_also_inlined() -> None:def test_a_skipped_isolated_file_is_named_in_the_log() -> None:- """Exit 5 is tolerated, so the file that produced it has to be identifiable: an- expected module-level skip and a file that stopped collecting for a new reason both- exit 5 and both stay green."""+ """Exit 5 is tolerated, so each isolated file must be named in the log: an expected module-level+ skip and a file that stopped collecting both exit 5 and stay green."""text = WORKFLOW.read_text(encoding = "utf-8")for path, _ in ISOLATED:assert f'_keep "$?" {path}' in text, (diff --git a/tests/test_allow_cpu_import_driverless.py b/tests/test_allow_cpu_import_driverless.pyindex 595d0d508a4..0383f48d4c5 100644--- a/tests/test_allow_cpu_import_driverless.py+++ b/tests/test_allow_cpu_import_driverless.py@@ -134,9 +134,8 @@ def test_no_unsloth_module_probes_a_device_that_is_not_there(_import_attempt_resdef test_the_import_succeeds_on_a_driverless_host(_import_attempt_result):- """End to end. The chain runs through unsloth_zoo as well- (`compiler.py`, `loss_utils.py`), so an unsloth_zoo without those guards- leaves this unprovable rather than failed."""+ """End to end; the chain also runs through unsloth_zoo (compiler.py, loss_utils.py), so an+ unsloth_zoo without those guards leaves this unprovable rather than failed."""out = _import_attempt_resultif out.returncode != 0 and _asked_a_missing_device(out.stderr):import unsloth_zoodiff --git a/tests/test_async_grpo_fast_inference.py b/tests/test_async_grpo_fast_inference.pyindex 352d8ba5d28..3b8dfd78515 100644--- a/tests/test_async_grpo_fast_inference.py+++ b/tests/test_async_grpo_fast_inference.py@@ -207,9 +207,8 @@ def test_unset_fields_take_the_generation_config_defaults_and_set_fields_win(serdef test_concurrent_requests_all_complete(served):- # 256 is well past socketserver's default listen backlog of 5: with that- # backlog a burst this size has connections reset every run, while 32 only- # tripped it now and then on a loaded runner.+ # 256 is well past socketserver's default listen backlog of 5, where a burst this size resets+ # connections every run; 32 only tripped it now and then on a loaded runner.server, _ = servedcount = 256results = [None] * countdiff --git a/tests/test_block_compile.py b/tests/test_block_compile.pyindex 2276824ca07..49983713506 100644--- a/tests/test_block_compile.py+++ b/tests/test_block_compile.py@@ -1684,12 +1684,9 @@ def test_router_hooks_are_not_installed_twice_after_an_eager_capture(request, modef test_router_logits_capture_compiles_one_graph_for_every_layer(monkeypatch):- """A capture hook inside the block appends to an empty scratch list on every call.-- Before: the hook appended to the collector's list and Dynamo guarded on its length (the layer- index), so each of 10 layers compiled its own graph. Now <= 2 graphs (static, then dynamic) across- 10 layers at 10 sequence lengths, and the collected logits match the stock forward in order.- """+ """A capture hook appends to an empty scratch list per call, so Dynamo does not guard on the+ collector's length, which compiled one graph per layer; now at most 2 graphs across 10 layers+ and 10 lengths, with logits matching the stock forward."""output_capturing = pytest.importorskip("transformers.utils.output_capturing")misc = pytest.importorskip("unsloth_zoo.temporary_patches.misc")if not hasattr(misc, "output_capture_scratch"):diff --git a/tests/test_block_cudagraphs_clone.py b/tests/test_block_cudagraphs_clone.pyindex efecb3ccaa4..fd1aa904d7f 100644--- a/tests/test_block_cudagraphs_clone.py+++ b/tests/test_block_cudagraphs_clone.py@@ -451,9 +451,8 @@ def test_no_pool_copies_outside_checkpointing(monkeypatch, trainable_input):"through", ["view", "view_add", "cat", "addmm_input", "addmm_bias", "embedding"])def test_input_viewing_a_trainable_param_copies_its_gradient(monkeypatch, through):- """inputs_embeds = param.view(...): the view's backward passes the pool gradient straight to- AccumulateGrad, so the parameter's first .grad would alias the pool. An embedding lookup writes- a new gradient, so it needs no copy."""+ """inputs_embeds = param.view(...) passes the pool gradient straight to AccumulateGrad, so the+ parameter's first .grad would alias the pool; an embedding lookup needs no copy."""monkeypatch.setattr(torch, "compile", lambda fn, **kwargs: fn)seen = _counting_clones(monkeypatch)A = _linear_layer_class("ViewInputDecoderLayer")diff --git a/tests/test_bnb_checkpoint_skip_modules.py b/tests/test_bnb_checkpoint_skip_modules.pyindex c5c8c750191..9713c713524 100644--- a/tests/test_bnb_checkpoint_skip_modules.py+++ b/tests/test_bnb_checkpoint_skip_modules.py@@ -64,9 +64,8 @@ def test_the_vision_loader_does_not_touch_the_checkpoint_skip_list():def test_the_runtime_skip_list_is_still_built_for_on_the_fly_quantization():- """The other half: a full-precision checkpoint has no config to defer to, so Unsloth's- own list keeps heads, routers and towers in compute dtype. Hence the fix was to remove- a write, not to stop building the list."""+ """A full-precision checkpoint has no config to defer to, so Unsloth's own skip list keeps+ heads, routers and towers in compute dtype; the fix removed a write, not the list build."""source = open(VISION, encoding = "utf-8").read()assert "_skip_modules = SKIP_QUANTIZATION_MODULES.copy()" in sourceassert "llm_int8_skip_modules = _skip_modules" in sourcediff --git a/tests/test_bnb_integration_compile.py b/tests/test_bnb_integration_compile.pyindex c75f9e757ae..3a28bfafdec 100644--- a/tests/test_bnb_integration_compile.py+++ b/tests/test_bnb_integration_compile.py@@ -203,9 +203,8 @@ def test_float_packed_storage(path, storage):def test_side_streams_never_share_the_scratch(path):- """Two streams dequantizing different weights with use_global_buffer at the same time: each- must read its own weight back. Only the default stream owns a scratch, so a program making a- new stream per step cannot pin a weight-sized buffer per stream."""+ """Two streams dequantizing with use_global_buffer must each read back their own weight; only+ the default stream owns a scratch, so a stream per step cannot pin a weight-sized buffer."""(q1, s1), (q2, s2) = (_quantize((4096, 4096), torch.bfloat16, seed = 1),_quantize((4096, 4096), torch.bfloat16, seed = 2),diff --git a/tests/test_broken_torchvision_probe.py b/tests/test_broken_torchvision_probe.pyindex 0f1ddaf075c..95497772d42 100644--- a/tests/test_broken_torchvision_probe.py+++ b/tests/test_broken_torchvision_probe.py@@ -170,9 +170,8 @@ def test_the_skip_variable_still_skips_everything():def test_the_repair_names_the_wheel_for_this_torch_patch():- """`0.22.*` on a torch 2.7.0 host resolves torchvision 0.22.1, which requires- torch 2.7.1, and `--no-deps` then keeps the 2.7.0 that does not match it. The- advertised repair would rebuild the mismatch it is meant to fix."""+ """A 0.22.* pin on torch 2.7.0 resolves torchvision 0.22.1, which needs torch 2.7.1, and+ --no-deps keeps the mismatched torch, so the repair pins the exact patch."""from unsloth.import_fixes import _torchvision_repair_commandassert '"torchvision==0.22.0"' in _torchvision_repair_command((0, 22, 0))diff --git a/tests/test_chunked_mask_block_sequence_ids.py b/tests/test_chunked_mask_block_sequence_ids.pyindex da76f8c7936..0cd5ffe22b4 100644--- a/tests/test_chunked_mask_block_sequence_ids.py+++ b/tests/test_chunked_mask_block_sequence_ids.py@@ -123,9 +123,8 @@ def unpatched(monkeypatch):_point_references_at(monkeypatch, wrappers, original)assert masking_utils.create_chunked_causal_mask is originalyield original- # monkeypatch only restores what existed at setup. A module first imported during the test (the- # tiny Llama-4 imports modeling_llama4) bound the stock function, and the fix may have rewritten- # it to a wrapper made by this test; give it what a normal import would have bound instead.+ # monkeypatch only restores what existed at setup, so a module first imported during the test+ # (e.g. modeling_llama4) must be given what a normal import would bind, not this test's wrapper.for name, namespace in _mask_importer_namespaces().items():if name in already_imported:continuediff --git a/tests/test_ci_repo_cpu_shards.py b/tests/test_ci_repo_cpu_shards.pyindex 826613261aa..8bc5259821f 100644--- a/tests/test_ci_repo_cpu_shards.py+++ b/tests/test_ci_repo_cpu_shards.py@@ -128,9 +128,8 @@ class TestEveryTestFileLandsInExactlyOneShard:class TestEveryGlobRootMatchesAFile:def test_no_shard_hands_pytest_an_unexpanded_pattern(self):- """bash passes a glob that matches nothing through as the literal pattern, and pytest- then fails the whole shard on a path that does not exist. A split that moved the last- file out of one of its globs would break that shard rather than drop the file."""+ """bash passes an unmatched glob through literally and pytest then fails the whole shard on+ the missing path, so a split must not empty any glob."""files = _test_files()empty = [(name, root)diff --git a/tests/test_compressed_tensors_bnb.py b/tests/test_compressed_tensors_bnb.pyindex 4687c3f37ab..bce024e8b8a 100644--- a/tests/test_compressed_tensors_bnb.py+++ b/tests/test_compressed_tensors_bnb.py@@ -486,10 +486,8 @@ def test_arm_declines_a_plan_the_installed_compressed_tensors_cannot_parse(monkenot (HAS_CT and HAS_CONVERTERS), reason = "needs compressed-tensors and the transformers 5 loader")def test_the_planner_pass_does_not_consume_the_plan():- """The device-map planner preprocesses a meta model built from the very config object the- load uses. The plan used to be taken off the config by the first pass, so on a multi-GPU- load the real quantizer found none, added no converters, and every packed expert was- reported missing and quantized from its random initialisation."""+ """The device-map planner's pass must not consume the plan on the shared config; otherwise+ multi-GPU loads add no converters and quantize packed experts from random init."""from transformers import LlamaConfig, LlamaForCausalLMfrom transformers.quantizers import AutoHfQuantizerfrom transformers.utils.quantization_config import BitsAndBytesConfig@@ -888,10 +886,8 @@ def test_classification_load_under_fast_inference_still_requantizes():@pytest.mark.skipif(not HAS_CONVERTERS, reason = "needs the transformers 5 loader")def test_wrapped_many_to_many_op_still_passes_the_converter_type_check():- """transformers' WeightConverter allows a many-to-many mapping only when `operations`- holds an instance of its internal Ernie ops. The adapter that feeds such an op its- original source contract must remain an instance of the op's class, or building the- replacement converter raises before any weight loads."""+ """transformers WeightConverter allows many-to-many only when operations holds an Ernie op+ instance, so the adapter feeding it must stay that class or building the converter raises."""from transformers.core_model_loading import ErnieFuseAndSplitTextVisionExperts, WeightConverterfrom unsloth.models.compressed_tensors_bnb import _WithOriginalSources, _with_original_sources@@ -920,9 +916,8 @@ def test_a_pickled_shard_is_refused_rather_than_read_in_the_model_dtype():def test_load_only_converters_are_dropped_before_save():- """transformers reverses every converter on model._weight_conversions in save_pretrained;- the decompression converters must not be there, or a bitsandbytes model is saved under- the packed names."""+ """transformers reverses every converter in model._weight_conversions on save_pretrained, so+ decompression converters must be dropped or the model saves under the packed names."""from unsloth.models.compressed_tensors_bnb import (_DecompressPackedWeights,drop_load_only_conversions,diff --git a/tests/test_cuda_spoof_supplies_the_raw_stream.py b/tests/test_cuda_spoof_supplies_the_raw_stream.pyindex 4b029aba752..7655eb7af5f 100644--- a/tests/test_cuda_spoof_supplies_the_raw_stream.py+++ b/tests/test_cuda_spoof_supplies_the_raw_stream.py@@ -87,12 +87,9 @@ def test_the_spoof_leaves_a_real_raw_stream_alone():def test_the_spoof_replaces_a_raw_stream_that_has_no_driver_behind_it():- """A CUDA wheel on a GPU-less runner carries the symbol, but calling it raises.-- The notebooks smoke leg for Llama3.1 GRPO installs vLLM, which brings in torch 2.13.0+cu130,- and importing unsloth then died in kernels/utils.py with "CUDA driver version is insufficient- for CUDA runtime version". The spoof has to cover that wheel the same way it covers a CPU one.- """+ """A CUDA wheel on a GPU-less runner has the symbol but raises when called; torch 2.13.0+cu130+ pulled in by vLLM made import die in kernels/utils.py with a driver-insufficient error, so+ the spoof must cover it."""script = textwrap.dedent(f"""import ctypes, sysdiff --git a/tests/test_decision_model.py b/tests/test_decision_model.pyindex 4f2be2d7d16..c1199ae19d1 100644--- a/tests/test_decision_model.py+++ b/tests/test_decision_model.py@@ -738,9 +738,8 @@ def test_clef_backbone_stays_on_one_device_unless_the_caller_places_it(tmp_path,def test_toy_task_beats_the_base_model(checkpoint, tmp_path, monkeypatch):- # On CPU everywhere: the toy task plateaus near loss 0.45 and leaves it by step ~70 on CPU but- # only after ~100 steps on a GPU (same curve otherwise, any precision), so 80 steps is a threshold- # tuned to CPU arithmetic, not a GPU defect.+ # The toy task plateaus near loss 0.45 and leaves it by step ~70 on CPU but only after ~100+ # steps on GPU, so 80 steps is tuned to CPU arithmetic, not a GPU defect.monkeypatch.setattr(decision, "_device", lambda: torch.device("cpu"))# Eager too: a compiled encoder draws the same accuracy from a different 45-decision RNG stream.monkeypatch.setenv("UNSLOTH_DECISION_COMPILE", "0")diff --git a/tests/test_dill_module_by_value_fix.py b/tests/test_dill_module_by_value_fix.pyindex 00f96883aa5..dc9452c73f5 100644--- a/tests/test_dill_module_by_value_fix.py+++ b/tests/test_dill_module_by_value_fix.py@@ -233,9 +233,8 @@ def test_the_env_switch_turns_it_off(tmp_path):def test_an_ordinary_site_packages_install_is_a_no_op():- """dill's behaviour, fingerprints included, has to be identical where it- already works. The gate is what guarantees that, so it is asserted against- the environment this test suite itself runs in."""+ """dill's behaviour, fingerprints included, must be identical where it already works, so the+ gate is asserted against the environment this test suite runs in."""from unsloth.import_fixes import _dill_path_pickles_by_valueassert not _dill_path_pickles_by_value("/usr/lib/python3.12/site-packages/pyarrow/__init__.py")diff --git a/tests/test_fla_autotuner_fast_path.py b/tests/test_fla_autotuner_fast_path.pyindex fde07a9e9d2..e45472d55cf 100644--- a/tests/test_fla_autotuner_fast_path.py+++ b/tests/test_fla_autotuner_fast_path.py@@ -210,9 +210,8 @@ needs_probe = pytest.mark.skipif(CACHE_PROBE is None, reason = "tree without the@needs_probedef test_cache_probe_detects_the_reuse_cache_under_any_name():- """unsloth_zoo defines _ReuseBestCache inside a function, so there is no symbol to import.- The probe must key off behaviour, not the class name, or a rename silently turns the fast- path off."""+ """unsloth_zoo defines _ReuseBestCache inside a function so there is no symbol to import; the+ probe keys off behaviour, since a rename would silently turn the fast path off."""class RenamedTomorrow(_ReuseBestCache):passdiff --git a/tests/test_float32_generate_autocast.py b/tests/test_float32_generate_autocast.pyindex 01a55d60fe8..28e5a741d6c 100644--- a/tests/test_float32_generate_autocast.py+++ b/tests/test_float32_generate_autocast.py@@ -77,9 +77,8 @@ def test_the_gate_by_execution(dtype, expected):@pytest.mark.skipif(not has_real_cuda(), reason = "needs a CUDA device")def test_cuda_really_does_accept_float32_as_an_autocast_dtype():- """The premise. If torch ever starts rejecting or ignoring this, the fix- above is no longer load-bearing and this test says so rather than letting- it rot in place."""+ """The premise: if torch ever rejects or ignores float32 as an autocast dtype, the fix above is+ no longer load-bearing and this test says so."""with torch.autocast(device_type = "cuda", dtype = torch.float32):assert torch.is_autocast_enabled("cuda") is Trueassert torch.get_autocast_dtype("cuda") == torch.float32diff --git a/tests/test_float32_no_fp16_autocast.py b/tests/test_float32_no_fp16_autocast.pyindex 99dbb0ca9b5..cc21c8cfba7 100644--- a/tests/test_float32_no_fp16_autocast.py+++ b/tests/test_float32_no_fp16_autocast.py@@ -269,9 +269,8 @@ def test_the_direct_diffusion_loader_records_it_too():def test_the_request_is_read_from_the_model_not_the_environment():- """A process-global would describe whichever model loaded last, so a- program that loads two before building a trainer would train the first- with the second's precision."""+ """The request is stored on each model, since a process-global would describe whichever model+ loaded last and train the first with the second's precision."""assert "_unsloth_user_float32" in MP_SRCassert "UNSLOTH_USER_FLOAT32" not in MP_SRCdiff --git a/tests/test_float8_training_fsdp2_gloo.py b/tests/test_float8_training_fsdp2_gloo.pyindex 3de8514e900..7d400ca3409 100644--- a/tests/test_float8_training_fsdp2_gloo.py+++ b/tests/test_float8_training_fsdp2_gloo.py@@ -124,9 +124,8 @@ def test_float8_linear_trains_under_native_fsdp2(tmp_path):import torch.multiprocessing as mpfrom test_fsdp2_frozen_dtypes_gloo import _free_port- # The unsharded reference trains in a fresh process too. Computed in the pytest worker it- # inherits whatever earlier tests left there, and in the CPU rest shard that moved its step-4- # loss to 5.603441 while the sharded ranks (and a clean process) give 5.603824.+ # The unsharded reference runs in a fresh process: inside the pytest worker it inherited earlier+ # tests' state and gave step-4 loss 5.603441 instead of 5.603824 from a clean process.ref_out = str(tmp_path / "unsharded_fp8.json")mp.spawn(_reference_worker, args = (ref_out,), nprocs = 1, join = True)reference = json.load(open(ref_out, encoding = "utf-8"))diff --git a/tests/test_formatter_fixed_point.py b/tests/test_formatter_fixed_point.pyindex 9d02cf43d1b..64ed5ae432b 100644--- a/tests/test_formatter_fixed_point.py+++ b/tests/test_formatter_fixed_point.py@@ -422,11 +422,8 @@ def test_a_timeout_in_the_polling_loop_kills_the_running_formatters(tmp_path, mo@pytest.mark.skipif(not _HAS_PROC, reason = "reads Linux /proc")def test_a_pid_reaped_between_the_two_probes_is_not_alive(monkeypatch):- """The signal probe can see a zombie that is reaped before /proc/<pid>/stat is opened.-- That window used to read as alive, so the timeout test above failed on a process that had- already been killed and reaped (Repo tests (CPU, rest) on #12097).- """+ """A pid reaped between the two probes must not read as alive, since the signal probe can see a+ zombie before /proc/<pid>/stat is opened (issue 12097)."""child = subprocess.Popen([sys.executable, "-c", "pass"])child.wait()assert not Path(f"/proc/{child.pid}").exists(), "the child was not reaped"@@ -436,10 +433,8 @@ def test_a_pid_reaped_between_the_two_probes_is_not_alive(monkeypatch):@pytest.mark.skipif(os.name == "nt", reason = "POSIX signal probe")def test_without_proc_a_pid_the_signal_probe_finds_is_alive(monkeypatch):- """Where /proc is not mounted (macOS), a missing /proc entry proves nothing.-- Reading it as death would pass the timeout test above even if the group kill missed.- """+ """Where /proc is not mounted (macOS) a missing /proc entry proves nothing, so reading it as+ death would pass the timeout test even if the group kill missed."""# A pid with no /proc entry, as on macOS, that the signal probe still finds.child = subprocess.Popen([sys.executable, "-c", "pass"])child.wait()diff --git a/tests/test_fsdp2_native_quant_gloo.py b/tests/test_fsdp2_native_quant_gloo.pyindex 71c7c2648de..f8227879352 100644--- a/tests/test_fsdp2_native_quant_gloo.py+++ b/tests/test_fsdp2_native_quant_gloo.py@@ -275,10 +275,9 @@ def test_native_fsdp2_shards_4bit_and_keeps_quant_state():def test_without_native_quant_context_the_gathered_weight_is_not_4bit():- # Control: the same fully_shard calls with no 4-bit handling. bitsandbytes' own Linear4bit forward- # recovers (it re-reads the module's copy of the QuantState), but the all-gathered weight the block- # sees is a plain Parameter without quant_state: what Unsloth's fused LoRA kernels and the zoo MoE- # 4-bit paths read (they take it for a dense weight, or crash).+ # Control with no 4-bit handling: bnb's Linear4bit forward recovers by re-reading the module's+ # own QuantState copy, but the all-gathered weight is a plain Parameter without quant_state,+ # which Unsloth's fused LoRA kernels and zoo MoE 4-bit paths read as dense or crash on.pytest.importorskip("bitsandbytes")# torch < 2.12 cannot shard the uint8 weight at all ("only Tensors of floating point dtype can# require gradients"); later torch shards it but gathers a plain Parameter.diff --git a/tests/test_fsdp2_save_coverage.py b/tests/test_fsdp2_save_coverage.pyindex c1486c64c7e..d0c49a66a27 100644--- a/tests/test_fsdp2_save_coverage.py+++ b/tests/test_fsdp2_save_coverage.py@@ -118,9 +118,8 @@ def test_push_to_hub_gathers(fake_fsdp2):],)def test_whole_model_exports_run_on_rank0_under_fsdp2(monkeypatch, method, call, adapter_only):- """GGUF, torchao, OpenVINO and GGML exports used to be refused (or, for OpenVINO and GGML, ran- on every rank over its own shards). Under FSDP2 they now gather and run on rank 0 alone:- a non-writer rank gets rank 0's answer without running the export."""+ """Under FSDP2 GGUF, torchao, OpenVINO and GGML exports gather and run on rank 0 alone; a+ non-writer rank gets rank 0's answer without running the export."""from peft import LoraConfig, get_peft_modelseen = []diff --git a/tests/test_fsdp2_save_gloo.py b/tests/test_fsdp2_save_gloo.pyindex af93a6fe891..6c59f8073d2 100644--- a/tests/test_fsdp2_save_gloo.py+++ b/tests/test_fsdp2_save_gloo.py@@ -996,11 +996,10 @@ def _legacy_and_mismatched_loads(rank, model, saved, out):def _case_dcp_quant_state_missing(rank, world_size, m):- """A full DCP state dict holding a packed 4-bit weight but none of its QuantState entries loads- only when the bytes are the live ones (older checkpoints of a frozen base); other bytes would be- paired with the live scales and must not load. One without the packed weight still loads.- The broadcast_from_rank0 presence check must not send a CPU tensor through the process group- (NCCL rejects those): with tensor broadcasts of CPU tensors refused, the restore still works."""+ """A full DCP state dict with a packed 4-bit weight but no QuantState entries loads only with+ the live bytes (older frozen-base checkpoints); one without the packed weight still loads;+ the broadcast_from_rank0 presence check must not send CPU tensors through NCCL, which rejects+ them."""from torch.distributed.checkpoint.state_dict import StateDictOptionsimport torch.distributed as distimport torch.distributed.checkpoint.state_dict as dcp@@ -1326,10 +1325,9 @@ def test_merge_offload_keeps_4bit_adapters_after_an_eval_forward():def test_packed_4bit_save_stages_bytes_and_quant_state_on_the_cpu():- """A full save of a sharded NF4 model kept every gathered packed weight on rank 0's accelerator,- so the whole quantized base had to fit on one GPU. Saves that only write the bytes now get them- on the CPU, with a CPU copy of the QuantState; the merge path is unchanged and the written state- dict is byte for byte the same."""+ """A full save of a sharded NF4 model kept all gathered packed weights on rank 0's accelerator;+ bytes-only saves now stage them on the CPU with a CPU copy of the QuantState, and the merge+ path writes a byte-for-byte identical state dict."""pytest.importorskip("bitsandbytes")r0 = _run("gather_4bit_offload")[0]kept, staged = r0[False], r0[True]@@ -1384,11 +1382,9 @@ def test_full_dcp_broadcast_load_restores_quant_state_over_nccl():def test_merged_4bit_save_streams_the_packed_base_one_layer_at_a_time():- """merged_4bit of a sharded NF4 QLoRA kept every gathered packed weight on rank 0's accelerator- until PEFT merged them all, so the whole quantized base had to fit on one GPU next to its shards.- The gather now stages each packed weight on the CPU right after gathering it, and the merge- brings one layer back at a time (restage, merge, restage), writing the same bytes as an unsharded- merge and as the previous placement."""+ """merged_4bit of sharded NF4 QLoRA stages each packed weight on the CPU and merges one layer at+ a time (restage, merge, restage), so the whole base need not fit on one GPU; bytes match an+ unsharded merge."""pytest.importorskip("bitsandbytes")pytest.importorskip("peft")r0 = _run("merged_4bit_streamed")[0]diff --git a/tests/test_gguf_disk_headroom.py b/tests/test_gguf_disk_headroom.pyindex 048fa74b7b4..1f279e97ef0 100644--- a/tests/test_gguf_disk_headroom.py+++ b/tests/test_gguf_disk_headroom.py@@ -437,9 +437,8 @@ def test_a_separate_output_filesystem_is_left_alone(tmp_path, monkeypatch, save_merge_real = os.path.realpath(merge)def stat_on_another_device(path, *args, **kwargs):- """Real `stat_result`, one field changed. `os.path.isdir` goes through the- same `os.stat`, so `st_mode` and the rest have to stay intact or the helper- never reaches the device comparison this test is about."""+ """Returns a real stat_result with one field changed; os.path.isdir uses the same os.stat,+ so st_mode and the other fields must stay intact for the device comparison to be reached."""st = real_stat(path, *args, **kwargs)if os.path.realpath(path) != merge_real:return st@@ -455,9 +454,8 @@ def test_a_separate_output_filesystem_is_left_alone(tmp_path, monkeypatch, save_def test_an_unreadable_merge_directory_declines_rather_than_raising(tmp_path, monkeypatch, save_mod):- """The helper promises never to raise. A directory listing that fails must- end the reclamation, not the export -- llama-quantize does not need that- directory any more and would have succeeded."""+ """The helper never raises: a failing directory listing must end the reclamation, not the+ export, since llama-quantize no longer needs that directory and would have succeeded."""merge, gguf, bases = _layout(tmp_path, merge_gb = 63, base_gb = 60)_with_free(monkeypatch, save_mod, 20)@@ -469,9 +467,8 @@ def test_an_unreadable_merge_directory_declines_rather_than_raising(def test_f32_output_is_counted_as_twice_the_base(tmp_path, monkeypatch, save_mod):- """An f32 output off a bf16 base is four bytes a weight against two, so it- is twice the file it reads. Bounding every pass by the base size would call- a disk roomy that is about to fill."""+ """An f32 output off a bf16 base is four bytes a weight against two, so it is twice the file it+ reads; bounding every pass by the base size would call a filling disk roomy."""merge, gguf, bases = _layout(tmp_path, merge_gb = 63, base_gb = 60)_with_free(monkeypatch, save_mod, 100)assert _reclaim(save_mod, merge, gguf, bases, ["q8_0"], first_conversion = "bf16") == 0@@ -630,9 +627,8 @@ def test_a_malformed_index_falls_back_to_the_naming_convention(tmp_path, monkeypdef test_a_quantized_output_is_priced_below_the_base_it_reads(tmp_path, monkeypatch, save_mod):- """The merge is kept whenever the export already fits, which is the whole- promise. A Q4_K_M off a 60GB BF16 base needs about 21GB, so 30GB free has- the room and charging it a full 60GB copy would delete for nothing."""+ """The merge is kept whenever the export fits: a Q4_K_M off a 60GB BF16 base needs about 21GB,+ so 30GB free has room, and charging a full 60GB copy would delete for nothing."""merge, gguf, bases = _layout(tmp_path, merge_gb = 63, base_gb = 60)_with_free(monkeypatch, save_mod, 30)assert _reclaim(save_mod, merge, gguf, bases) == 0@@ -661,9 +657,8 @@ def test_a_q8_0_base_is_not_priced_as_sixteen_bit(save_mod):def test_the_vlm_projector_is_not_charged_to_every_quant(tmp_path, monkeypatch, save_mod):- """llama-quantize copies the `-mmproj` projector rather than quantizing it,- so it is not part of what a pass writes. Charging it per quant calls a disk- tight that has the room."""+ """llama-quantize copies the -mmproj projector rather than quantizing it, so it is not part of+ what each pass writes; charging it per quant would call a roomy disk tight."""merge, gguf, bases = _layout(tmp_path, merge_gb = 63, base_gb = 30)mmproj = Path(gguf) / "model.BF16-mmproj.gguf"with open(mmproj, "wb") as fh:diff --git a/tests/test_growth_ratio_guard.py b/tests/test_growth_ratio_guard.pyindex 5308b23ab04..390034bc41f 100644--- a/tests/test_growth_ratio_guard.py+++ b/tests/test_growth_ratio_guard.py@@ -23,9 +23,8 @@ class FakeClock:self.now += seconds-#: Seconds per unit of cost. Small enough that a quadratic row stays well under the 60s-#: backstop `assert_linear` applies, so the quadratic rows fail on the RATIO, which is what-#: they are about, rather than on the backstop, which has its own row.+# Seconds per unit of cost, small enough that a quadratic row stays well under the 60s backstop+# assert_linear applies, so quadratic rows fail on the ratio, not the backstop._UNIT = 0.001diff --git a/tests/test_grpo_autocast_disabled.py b/tests/test_grpo_autocast_disabled.pyindex aea431d8236..40de3b60464 100644--- a/tests/test_grpo_autocast_disabled.py+++ b/tests/test_grpo_autocast_disabled.py@@ -51,9 +51,8 @@ class _pretend_cuda:def test_bfloat16_autocast_raises_without_hardware_support():- """Guards everything below: if torch ever downgraded this to a warning,- the bug would be a silent precision change instead of a crash, and these- tests would be asserting the wrong thing."""+ """Guards everything below: if torch ever downgraded this to a warning, the bug would be a+ silent precision change instead of a crash and these tests would assert the wrong thing."""with _pretend_cuda(has_bf16 = False):with pytest.raises(RuntimeError, match = "does not support bfloat16"):with torch.amp.autocast(device_type = "cuda", dtype = torch.bfloat16):@@ -74,8 +73,7 @@ def _prepare_inputs_snippet() -> str:def _autocast_helper_source() -> str:- """Module level helpers the header calls, mirrored into the generated- trainer through RL_PRE_ITEMS."""+ """Module level helpers the header calls, mirrored into the generated trainer through RL_PRE_ITEMS."""parts = [ast.get_source_segment(SRC, node)for node in ast.parse(SRC).body@@ -86,9 +84,8 @@ def _autocast_helper_source() -> str:def _namespace(env):- """What the generated trainer module offers the header. `self` carries no- args here, which is the fallback path; a trainer with args is covered in- test_grpo_autocast_per_trainer.py."""+ """What the generated trainer module offers the header; with self carrying no args this is the+ fallback path, and a trainer with args is covered in test_grpo_autocast_per_trainer.py."""from contextlib import nullcontextnamespace = {diff --git a/tests/test_grpo_image_column_normalisation.py b/tests/test_grpo_image_column_normalisation.pyindex cb06a9bd439..29128a33e0b 100644--- a/tests/test_grpo_image_column_normalisation.py+++ b/tests/test_grpo_image_column_normalisation.py@@ -146,9 +146,8 @@ def test_guard_is_injected_when_no_anchor_matches():def test_guard_is_injected_when_the_legacy_reference_calls_drift():- """Rewriting the cell is half the job. A legacy TRL also has to carry the image counts- into the reference logprob calls; without them the images are sliced by sample index and- all but the first are dropped, which the model reports as a token/feature mismatch."""+ """A legacy TRL must also pass image counts into the reference logprob calls, or images are+ sliced by sample index and dropped, showing as a token/feature mismatch."""source = (" def _generate_and_score_completions(self, inputs):\n"' has_images = "image" in inputs[0]\n'@@ -228,10 +227,8 @@ def _legacy_source(*, with_placeholder_helper):def test_a_trl_that_cannot_size_its_placeholders_refuses_the_multi_image_row():- """The cell rewrite alone would hand the processor two images while the prompt still- carries one placeholder, and nothing else in the batch disagrees, because the prologue- counts the same cells. That surfaces inside the processor naming neither the column nor- the fix, which is exactly what the guard exists to replace."""+ """Without the guard, a TRL that cannot size its placeholders gets two images for one+ placeholder and fails inside the processor, naming neither the column nor the fix."""patched = grpo_trainer__generate_and_score_completions("_generate_and_score_completions", _legacy_source(with_placeholder_helper = False))@@ -277,9 +274,8 @@ def _run_legacy_placeholders(cells):def test_an_empty_cell_takes_no_placeholder_so_a_mixed_batch_stays_in_step():- """One placeholder for a row with no image leaves the prompt a token ahead of the pixels,- which the processor rejects. Measured against a real Gemma 3 processor: this batch fails- with one placeholder for the empty row and succeeds with none."""+ """An image-less row must take no placeholder: one placeholder leaves the prompt a token ahead+ of the pixels, which a real Gemma 3 processor rejects."""a, b = _Img("a"), _Img("b")assert _run_legacy_placeholders([a, []]) == ([[a], []], [1, 0])assert _run_legacy_placeholders([[a, b], []]) == ([[a, b], []], [2, 0])diff --git a/tests/test_grpo_legacy_trl_vision.py b/tests/test_grpo_legacy_trl_vision.pyindex 66d415081cc..2d238b0a4f4 100644--- a/tests/test_grpo_legacy_trl_vision.py+++ b/tests/test_grpo_legacy_trl_vision.py@@ -340,9 +340,8 @@ def _legacy_unsplit_pixel_values_by_grid(batch):def test_a_multi_image_grid_batch_keeps_its_images_with_their_samples():- """0.22.x-0.23.x splits pixel_values by grid row, so with two images on one sample the list- is indexed by image while prompt_ids is indexed by sample. shuffle_sequence_dict then takes- its length from prompt_ids and drops the tail of the list."""+ """TRL 0.22.x-0.23.x splits pixel_values per grid row, so with two images on one sample+ shuffle_sequence_dict, sized by prompt_ids, drops the tail of the image list."""import torchtrl_utils = pytest.importorskip("trl.trainer.utils")@@ -416,9 +415,8 @@ def test_a_grid_batch_trl_1_1_0_already_split_by_sample_is_left_alone():def test_a_legacy_grid_row_with_no_image_still_gets_its_neighbours_images_apart():- """num_images = [0, 2] over two samples makes the image count and the sample count agree- while the axes still differ, so a bare length comparison would leave the list alone and the- shuffle would hand both of the second sample's images to the first."""+ """num_images [0, 2] over two samples matches the lengths but not the axes, so a bare length+ check would skip regrouping and hand both images to the first sample."""import torchfrom unsloth.models.rl_replacements import _unsloth_grpo_split_vision_by_sample@@ -486,9 +484,8 @@ def test_an_image_column_with_no_images_in_it_is_a_text_batch():def test_an_untruncated_token_type_ids_as_wide_as_prompt_plus_completion_is_dropped():- """max_prompt_length runs truncate_with_protected_tokens after the processor, which keeps the- image tokens but MOVES them. A processor copy whose width happens to equal prompt+completion- is still the untruncated one, so its marks sit at the wrong offsets."""+ """truncate_with_protected_tokens runs after the processor and moves image tokens, so a+ processor copy as wide as prompt plus completion is untruncated and its marks are wrong."""import torchprocessor_output, inputs, completion_ids = _grid_batch()diff --git a/tests/test_grpo_move_model_to_vllm_sync.py b/tests/test_grpo_move_model_to_vllm_sync.pyindex f1215b02f64..58100fa9e71 100644--- a/tests/test_grpo_move_model_to_vllm_sync.py+++ b/tests/test_grpo_move_model_to_vllm_sync.py@@ -560,10 +560,8 @@ def _drift_config(kind):@pytest.mark.parametrize("kind", ["dora", "lora_bias", "loha", "lokr", "ia3", "vera"])def test_bf16_non_plain_peft_never_drifts_frozen_base(kind):- # TRL's body merge_adapter()s and unmerge_adapter()s the live bf16 model every sync; those rounded- # in-place edits are not lossless, so the frozen base drifted outside the optimizer. The merge now- # runs on a copy: after 10 syncs every frozen tensor keeps its exact bytes, and each sync pushes- # exactly what PEFT's own merge of the current adapter gives.+ # TRL's in-place merge_adapter and unmerge_adapter on the live bf16 model are lossy and drift+ # the frozen base; merging on a copy keeps frozen tensors bit-exact across syncs.peft = pytest.importorskip("peft")model = peft.get_peft_model(_tiny_llama(torch.bfloat16), _drift_config(kind))frozen = {n: p.detach().clone() for n, p in model.named_parameters() if not p.requires_grad}diff --git a/tests/test_grpo_packed_raw_logits_nograd.py b/tests/test_grpo_packed_raw_logits_nograd.pyindex b90c6aba7a1..57edff512ff 100644--- a/tests/test_grpo_packed_raw_logits_nograd.py+++ b/tests/test_grpo_packed_raw_logits_nograd.py@@ -390,9 +390,8 @@ def test_square_lm_head_double_application_is_actually_detectable():def test_first_use_verify_branch_runs_the_per_row_forwards():- """Without this, the raw-logits test above would never reach the second- call site: a model already inside the trusted envelope takes the shortcut- and the verifier never runs."""+ """Without this the raw-logits test above never reaches the second call site, since a model+ already inside the trusted envelope takes the shortcut and the verifier never runs."""namespace, model, input_ids, _max_left_pad = _run_packed_block(hidden_states = False)assert (diff --git a/tests/test_grpo_routing_replay_trainer_hooks.py b/tests/test_grpo_routing_replay_trainer_hooks.pyindex c4327fd755a..33175fe5036 100644--- a/tests/test_grpo_routing_replay_trainer_hooks.py+++ b/tests/test_grpo_routing_replay_trainer_hooks.py@@ -251,10 +251,9 @@ def _bias_router_model(model_type):@pytest.mark.parametrize("model_type", ["minimax_m2", "hy_v3", "lfm2_moe"])def test_sigmoid_correction_bias_routers_route_naturally_with_a_warning(replay, model_type):- # MiniMax-M2 / HY-V3: TopKRouter.forward(hidden_states, e_score_correction_bias), the bias a- # buffer of the parent MoE block; LFM2-MoE: forward(hidden_states, expert_bias = None). All three- # take sigmoid(logits) top-k weights, which no zoo replay formula reproduces: priming must reach- # the router (no TypeError), then take the hooks off and say so.+ # MiniMax-M2 and HY-V3 (TopKRouter.forward takes e_score_correction_bias) and LFM2-MoE+ # (expert_bias) use sigmoid top-k weights no zoo replay formula reproduces; priming must reach+ # the router, then hooks come off with a warning.model = _bias_router_model(model_type)routers = [m for m in model.modules() if "TopKRouter" in type(m).__name__]if not routers:diff --git a/tests/test_hf_packed_attention.py b/tests/test_hf_packed_attention.pyindex aafc2eea525..da4b876f36f 100644--- a/tests/test_hf_packed_attention.py+++ b/tests/test_hf_packed_attention.py@@ -417,8 +417,7 @@ def _block_flag(@pytest.mark.parametrize("in_block,leaves", [(True, True), (True, None), (False, True)])def test_packed_rows_leave_a_compiled_block_for_the_eager_wrapper(monkeypatch, in_block, leaves):"""Inside an Unsloth compiled block a packed call the predicate sends out runs the wrapper- eagerly (one graph break). A CPU row (real predicate) and a user's own compile (flag off) keep- the wrapped sdpa in the graph."""+ eagerly (one graph break); CPU rows and a user's own compile keep sdpa in the graph."""hpa._ORIG_SDPA[0] = _plain_sdpamonkeypatch.delenv("UNSLOTH_HF_PACKED_VARLEN", raising = False)_block_flag(monkeypatch, in_block, leaves)diff --git a/tests/test_hf_xet_broken_wheel.py b/tests/test_hf_xet_broken_wheel.pyindex 66c11da8304..20b58078af9 100644--- a/tests/test_hf_xet_broken_wheel.py+++ b/tests/test_hf_xet_broken_wheel.py@@ -560,9 +560,8 @@ def test_patches_every_module_that_binds_the_flag(monkeypatch):def test_does_not_invent_the_flag_on_hub_versions_that_never_had_it(monkeypatch):- """Before 0.34 the Hub read os.environ per call, so the variable alone is the whole fix and- creating the attribute would put a value into a namespace upstream does not own.- """+ """Hub versions before 0.34 read os.environ per call, so HF_HUB_DISABLE_XET alone is the fix;+ setting the attribute would invent a flag upstream never had."""monkeypatch.delenv("HF_HUB_DISABLE_XET", raising = False)_fake_host(monkeypatch, "win-arm64")monkeypatch.setattr(IF, "_hf_xet_wheel_platform_tags", lambda: ("win_amd64",))diff --git a/tests/test_high_precision_layernorm_coverage.py b/tests/test_high_precision_layernorm_coverage.pyindex 37c4d23c66c..eb4d21d85d3 100644--- a/tests/test_high_precision_layernorm_coverage.py+++ b/tests/test_high_precision_layernorm_coverage.py@@ -42,8 +42,7 @@ def test_non_norm_modules_are_not_selected():def test_custom_rmsnorm_still_matched_by_name():- """Model-specific RMSNorm classes are not torch.nn types, so the name rule- still has to carry them."""+ """Model-specific RMSNorm classes are not torch.nn types, so the name rule must still match them."""class RMSNorm(nn.Module):def __init__(self):diff --git a/tests/test_import_time_floors.py b/tests/test_import_time_floors.pyindex 1cc0b21345e..48d9ac39ff1 100644--- a/tests/test_import_time_floors.py+++ b/tests/test_import_time_floors.py@@ -210,9 +210,8 @@ def test_a_pypi_torch_gets_no_accelerator_note(patched_torch, monkeypatch, torchdef test_an_unattributable_access_keeps_torchs_own_error(patched_torch, monkeypatch):- """sys._getframe is CPython-only and raises an audit event, so a hardened- interpreter can refuse it. hasattr() swallows only AttributeError, so rethrowing- the frame-lookup failure would break an ordinary feature probe."""+ """sys._getframe is CPython-only and audited, so a hardened interpreter can refuse it; hasattr()+ swallows only AttributeError, so rethrowing would break feature probes."""def _refuse(_depth):raise RuntimeError("frame inspection is not allowed here")@@ -551,8 +550,7 @@ def test_a_public_triton_still_gets_the_plain_reinstall_line(monkeypatch, tmp_padef test_python_313_and_later_do_not_pay_for_the_probe(monkeypatch, tmp_path):- """CPython stopped requiring the macro in 3.13, so the shim is fine there and- the file is never read."""+ """CPython stopped requiring the macro in 3.13, so the shim is fine there and the file is never read."""spec, _ = _fake_triton(tmp_path, _UNGUARDED_SHIM)monkeypatch.setattr(sys, "version_info", (3, 13, 1))@@ -977,9 +975,8 @@ def test_a_rename_leftover_is_settled_by_what_torch_requires(monkeypatch, tmp_padef test_the_declared_requirement_is_read_by_distribution_name(monkeypatch):- """The names are compared PEP 503 normalised, so an underscore spelling in torch's- own metadata still matches the dist-info name, and a non-Triton requirement is not- collected."""+ """Names are compared PEP 503 normalised, so an underscore spelling in torch's own metadata+ still matches the dist-info name; non-Triton requirements are not collected."""import importlib.metadata as metadatamonkeypatch.setattr(diff --git a/tests/test_installer_elevation_report.py b/tests/test_installer_elevation_report.pyindex 148285031c0..17d55732a65 100644--- a/tests/test_installer_elevation_report.py+++ b/tests/test_installer_elevation_report.py@@ -230,9 +230,8 @@ def test_the_early_bail_restores_the_environment_too():def test_both_scripts_resolve_the_warning_root_the_same_way():- """install.ps1 and setup.ps1 each mirror the resolver's precedence for the- message, so a drift in one would send only half the flows to the right- directory."""+ """install.ps1 and setup.ps1 each mirror the resolver's precedence for the warning, so drift in+ one would send only half the flows to the right directory."""install_root = _read(INSTALL_PS1)install_root = install_root[install_root.index("$UnslothRoot =") : install_root.index("-Tauri:$TauriMode")diff --git a/tests/test_installer_interactive_prompts.py b/tests/test_installer_interactive_prompts.pyindex 7c46bd570e1..8048644d817 100644--- a/tests/test_installer_interactive_prompts.py+++ b/tests/test_installer_interactive_prompts.py@@ -222,9 +222,8 @@ def _redirected_loop_bodies(lines: list[str]) -> set[int]:def _outside_docstring(line: str, delimiter: str) -> tuple[str, str]:- """Strip triple-quoted regions from a Python line, returning what is left and the- delimiter still open. A docstring showing an `input()` example documents the- script, it does not prompt."""+ """Strip triple-quoted regions from a Python line, returning the rest and any delimiter still+ open; an input() example inside a docstring documents the script, it does not prompt."""while True:if delimiter:end = line.find(delimiter)diff --git a/tests/test_installer_profile_hardening.py b/tests/test_installer_profile_hardening.pyindex aa04dd6106a..3124a69d74e 100644--- a/tests/test_installer_profile_hardening.py+++ b/tests/test_installer_profile_hardening.py@@ -314,12 +314,9 @@ def _probe_lines(stdout: str) -> list[str]:)@requires_pwshdef test_a_real_profile_reproduces_the_same_state(tmp_path):- """Anchor for the simulation: a profile pwsh actually loads leaves the same state.-- If these ever diverge, every test below is measuring something the installer never meets.- Only the probe lines are compared, so a system-wide profile that prints a banner does not- turn this into a flake.- """+ """Anchor for the simulation: a profile pwsh really loads must leave the same state, or every+ test below measures what the installer never meets; only probe lines are compared, so a+ banner from a system-wide profile cannot flake it."""env = _hostile_env(tmp_path)paths = _profile_paths(env)# Machine-wide profiles load only in the real leg and cannot be redirected, so skip if present.@@ -506,11 +503,9 @@ def test_uv_probe_finds_the_real_uv_behind_a_profile_alias(tmp_path):@requires_pwshdef test_uv_probe_rejects_a_too_old_uv_and_leaves_the_reset_value(tmp_path):- """The version gate still has to fail closed, or a stale uv would be pinned and used.-- PATH is REPLACED, not prepended to: since the gate now walks every candidate, a real uv on- the machine running this would legitimately rescue the run and hide the branch under test.- """+ """The version gate must fail closed, or a stale uv would be pinned and used; PATH is replaced,+ not prepended, since the gate walks every candidate and a real uv on the host would hide the+ branch under test."""fake = _fake_uv(tmp_path / "bin", version = "0.7.0")res = _run_with_profile(tmp_path, _uv_probe_body(), path_override = fake.parent)assert res.returncode == 0, f"stdout={res.stdout!r} stderr={res.stderr!r}"@@ -551,11 +546,8 @@ def test_a_convincing_uv_function_is_not_accepted_as_uv(tmp_path):@requires_pwshdef test_an_alias_to_a_real_uv_is_followed_to_the_executable(tmp_path):- """The legitimate wrapper shape still has to work, and resolve to a PATH, not the alias.-- People do alias uv at a specific build. Refusing that outright would install a second uv- over a working machine, which is the failure this whole function was written to avoid.- """+ """An alias to a real uv build must still resolve to that executable path, not the alias itself;+ refusing it would install a second uv over a working machine."""fake = _fake_uv(tmp_path / "aliased", version = "0.12.4")profile = f"Set-Alias uv {_ps_literal(fake)}\n"body = _uv_probe_body(' "RESOLVED:$(Resolve-UvExecutable)"')@@ -570,12 +562,9 @@ def test_an_alias_to_a_real_uv_is_followed_to_the_executable(tmp_path):def test_no_bare_winget_token_survives_at_a_call_site():- """winget installs uv, so an alias on it owns the same ground.-- Detection used a bare Get-Command and every invocation was a bare token, so the fix applied- to uv left the winget half of the bootstrap exposed to the identical wrapper. (Python itself- no longer comes from winget: the Studio environment is always on a uv-managed Python.)- """+ """winget installs uv, so an alias on it owns the same ground; winget detection must skip+ aliases and functions as uv detection does; Python no longer comes from winget, as Studio is+ always on a uv-managed Python."""src = _install_ps1()assert ("Get-Command winget -CommandType Application -All" in src@@ -599,12 +588,8 @@ def test_module_autoloading_is_restored():@requires_pwsh@pytest.mark.parametrize("script", [INSTALL_PS1, SETUP_PS1], ids = ["install.ps1", "setup.ps1"])def test_the_powershell_entrypoints_parse(script):- """A syntax error here is a total install failure, and neither file is imported by anything.-- setup.ps1 is here for the same reason install.ps1 is, and because the tests that read it- extract single functions: an extraction still parses when the file around it does not, so- nothing else in the suite would notice a broken brace at file scope.- """+ """A syntax error here is a total install failure and neither file is imported; setup.ps1 is+ checked too, since function-level extraction tests would miss a broken brace at file scope."""res = run_pwsh([shutil.which("pwsh") or "pwsh",@@ -808,9 +793,8 @@ def test_a_standalone_update_reconstructs_the_proxy_for_itself():@requires_pwshdef test_the_probe_reads_a_hostile_profile_without_carrying_anything_else(tmp_path):- """Executable, against a profile pwsh genuinely loads: strict mode on, module autoloading- off, a lowercase key and a [uri] value. The probe has to survive all of it and return only- the proxy entries."""+ """The probe must survive a profile pwsh genuinely loads (strict mode on, module autoloading+ off, a lowercase key, a [uri] value) and return only the proxy entries."""src = STUDIO_COMMAND.read_text(encoding = "utf-8")# From the markers: the frame must survive a profile that prints.start = _locate(src, "_PROXY_PROBE_BEGIN = ", "the probe framing")diff --git a/tests/test_installer_shortcut_icons.py b/tests/test_installer_shortcut_icons.pyindex 93ba4da4d86..73d5e571a3f 100644--- a/tests/test_installer_shortcut_icons.py+++ b/tests/test_installer_shortcut_icons.py@@ -141,8 +141,7 @@ def _wsl_packaged_icon_block() -> str:@pytest.mark.skipif(shutil.which("bash") is None, reason = "bash is unavailable")def test_wsl_shortcut_reads_the_packaged_ico_out_of_site_packages(tmp_path):- """A WSL install that found the .ico in site-packages must hand the shortcut script a- Windows path."""+ """A WSL install that finds the .ico in site-packages must hand the shortcut script a Windows path."""dist = (tmp_path / "venv" / "lib" / "python3.12" / "site-packages" / "studio" / "frontend" / "dist")diff --git a/tests/test_installer_system32_guard.py b/tests/test_installer_system32_guard.pyindex e3cb0a2b586..54ef6fdadef 100644--- a/tests/test_installer_system32_guard.py+++ b/tests/test_installer_system32_guard.py@@ -1299,9 +1299,8 @@ def test_cli_guard_goes_back_when_the_move_lands_somewhere_still_refused():def test_cli_guard_restores_the_real_sys_path_when_the_move_fails():- """The console script passes no list, so the guard has to snapshot the real- sys.path before pinning it, or a chdir that then fails leaves the process- carrying import roots it never agreed to."""+ """The console script passes no list, so the guard snapshots the real sys.path before pinning+ it; otherwise a failed chdir leaves import roots it never agreed to."""import sysbefore = list(sys.path)diff --git a/tests/test_kbit_prep_guard.py b/tests/test_kbit_prep_guard.pyindex fbcf968e9a0..340498dc817 100644--- a/tests/test_kbit_prep_guard.py+++ b/tests/test_kbit_prep_guard.py@@ -166,9 +166,8 @@ def test_a_source_checkout_with_no_metadata_is_still_guarded(trl_modules):def test_an_unparseable_version_does_not_patch_an_already_guarded_trl(trl_modules):- """Falling through on an unparseable version is only safe because the- source check is self-guarding: 0.24.0 and above spell the branch with the- clause already in it, so there is nothing for us to match."""+ """Falling through on an unparseable version is safe only because the source check self-guards:+ 0.24.0 and above already include the clause, so nothing matches."""trl_modules.trl.__version__ = "unknown"src = TRL_0_22_2_SOURCE.replace("if is_qlora and not is_sharded_qlora:",diff --git a/tests/test_mamba_dt_proj_eval_parity.py b/tests/test_mamba_dt_proj_eval_parity.pyindex 4d11ecbf714..472ea1dfa12 100644--- a/tests/test_mamba_dt_proj_eval_parity.py+++ b/tests/test_mamba_dt_proj_eval_parity.py@@ -285,9 +285,8 @@ def test_eval_weight_follows_dtype_conversion(monkeypatch, arch):@pytest.mark.parametrize("arch", ARCHS)def test_eval_weight_follows_unversioned_optimizer_step(monkeypatch, arch):- # FlashAdamW's Triton update writes the parameters in place without bumping their version- # counters (as an in-place op through `p.data` does), so eval -> train step -> eval must not- # serve the W + delta of the first eval.+ # FlashAdamW's Triton update writes parameters in place without bumping version counters (as+ # p.data does), so a second eval must not reuse the first eval's W + delta.model = _trained(monkeypatch, arch, ["dt_proj"])ids = _ids()first = _logits(model, ids)diff --git a/tests/test_moe_lora_targets.py b/tests/test_moe_lora_targets.pyindex 1ccf1af181c..2c4902f9ea2 100644--- a/tests/test_moe_lora_targets.py+++ b/tests/test_moe_lora_targets.py@@ -216,9 +216,8 @@ def test_attention_only_list_prefers_original_when_in_scope():def test_unfused_expert_parameters_resolve_both_leaves():- """NemotronH keeps the expert projections unfused as separate 3D Parameters, so- up_proj must resolve alongside down_proj instead of being silently dropped- (unsloth#4476)."""+ """NemotronH keeps expert projections unfused as separate 3D Parameters, so up_proj must resolve+ alongside down_proj rather than be silently dropped (unsloth#4476)."""import torchfrom unsloth.models._utils import get_moe_target_parameters@@ -406,9 +405,8 @@ def test_does_not_warn_when_the_unfused_fallback_resolved_the_experts():def test_does_not_warn_when_an_ordinary_suffix_match_reaches_the_experts():- """transformers 4.x builds Qwen3-MoE experts as per-expert submodules. PEFT attaches- to them by leaf name, so a warning here would be a false alarm on a model that trains- its experts correctly. This is what keeps the fix identical on 4.57.6 and 5.x."""+ """transformers 4.x Qwen3-MoE per-expert submodules get LoRA by leaf name, so a warning there+ would be a false alarm; this keeps the fix identical on 4.57.6 and 5.x."""result, records = _warnings_from(_per_expert_submodule_moe_model(), ALL_MLP_LEAVES)assert result is Noneassert records == []diff --git a/tests/test_new_mapper_no_global_leak.py b/tests/test_new_mapper_no_global_leak.pyindex c844279395c..7ce2eb96a43 100644--- a/tests/test_new_mapper_no_global_leak.py+++ b/tests/test_new_mapper_no_global_leak.py@@ -151,9 +151,8 @@ def test_the_byte_cap_stops_the_read_instead_of_measuring_it_afterwards(monkeypadef test_a_redirect_body_is_bounded_too(monkeypatch):- """`requests` drains an intermediate 3xx body inside `get`, before `stream=True`- hands anything to the caller, so a redirect was a way around the cap and the- deadline. The probe follows redirects itself for that reason; this pins it."""+ """requests drains an intermediate 3xx body inside get, before stream=True hands anything over,+ so a redirect was a way around the cap and deadline; the probe follows redirects itself."""served = []def endless():diff --git a/tests/test_nf4_triton_gemv.py b/tests/test_nf4_triton_gemv.pyindex ef356aa9879..c7f9d4e9194 100644--- a/tests/test_nf4_triton_gemv.py+++ b/tests/test_nf4_triton_gemv.py@@ -660,9 +660,8 @@ def test_rocm_batch_1_decode_takes_the_triton_gemv(monkeypatch, env):@pytest.mark.parametrize("dtype", DTYPES, ids = str)@pytest.mark.parametrize("shape", SHAPES + [(12288, 4096), (256, 256)], ids = str)def test_eager_decode_route_matches_dequantize_matmul(shape, dtype, nested):- """The route eager batch-1 decode takes on this GPU (on ROCm with Triton 3.6+, the Triton- GEMV) against dequantize + fp32 matmul, on the Llama 3 8B / Qwen3 8B decode shapes. Reruns- of a weight's planned launch must give the same result."""+ """Checks the route eager batch-1 decode takes on this GPU (Triton GEMV on ROCm with Triton+ 3.6+) against dequantize + fp32 matmul on Llama 3 8B and Qwen3 8B shapes; reruns must match."""from unsloth.kernels import utilsif torch.version.hip and nf4_gemv._TRITON_VERSION >= nf4_gemv._HIP_EAGER_MIN_TRITON:diff --git a/tests/test_offline_loading_helpers.py b/tests/test_offline_loading_helpers.pyindex 20ad5603f82..b7b511e2df1 100644--- a/tests/test_offline_loading_helpers.py+++ b/tests/test_offline_loading_helpers.py@@ -592,9 +592,8 @@ def test_a_successful_retry_is_unchanged(monkeypatch):def test_the_failed_attempt_is_not_pinned_by_the_error_it_raised(monkeypatch):- """Holding the online error holds its frames, and its frames hold the partial- model. The retry then reallocates alongside it and a large VLM runs out of- memory doing exactly what the retry exists to do."""+ """Holding the online error keeps its frames and the partial model they hold alive, so the retry+ reallocates alongside it and a large VLM can run out of memory."""import gcimport weakref@@ -644,9 +643,8 @@ def test_a_real_retry_failure_is_not_replaced_by_the_network_error(monkeypatch):def test_an_oom_spelled_as_a_bare_runtimeerror_still_surfaces(monkeypatch):- """accelerate re-raises an accelerator OOM as a plain RuntimeError, and XPU has- its own class. Selecting on the empty-cache artifact rather than on a list of- OOM spellings covers both without naming either."""+ """accelerate re-raises an accelerator OOM as a plain RuntimeError and XPU has its own class;+ selecting on the empty-cache artifact covers both without listing OOM spellings."""monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)calls = []@@ -692,9 +690,8 @@ def test_a_network_error_wrapped_in_a_runtimeerror_keeps_its_cause(monkeypatch):def test_a_wrapped_online_error_does_not_pin_the_failed_attempt(monkeypatch):- """Same pinning as above, but through the wrapper path the retry already supports:- the loader re-raises the connection error as its own type, so the partial model is- held by the CAUSE's traceback, not the top-level one."""+ """Same pinning through the wrapper path the retry supports: the loader re-raises the connection+ error as its own type, so the partial model is held by the CAUSE's traceback."""import gcimport weakrefdiff --git a/tests/test_pp_native_gloo.py b/tests/test_pp_native_gloo.pyindex e138060bf55..c24b337d7dc 100644--- a/tests/test_pp_native_gloo.py+++ b/tests/test_pp_native_gloo.py@@ -191,9 +191,8 @@ def _read_adapter(path):def _enable_reentrant_gc(model):- """Reentrant checkpointing only back-propagates into a segment whose input requires grad; with the- embeddings frozen (LoRA) that needs enable_input_require_grads, which transformers 4.x- gradient_checkpointing_enable does not do for a PEFT model (5.x does)."""+ """Reentrant checkpointing needs a grad-requiring input: frozen LoRA embeddings need+ enable_input_require_grads, which transformers 4.x skips for PEFT but 5.x does."""model.gradient_checkpointing_enable(gradient_checkpointing_kwargs = {"use_reentrant": True})model.enable_input_require_grads()diff --git a/tests/test_profile_startup_gate.py b/tests/test_profile_startup_gate.pyindex abb60b20332..3b6420313ad 100644--- a/tests/test_profile_startup_gate.py+++ b/tests/test_profile_startup_gate.py@@ -267,9 +267,8 @@ def test_the_profile_step_passes_the_budget():def test_the_profile_step_sets_pipefail():- """`shell: bash` already implies -o pipefail, so this is belt and braces: the- gate's exit code only reaches the step through the pipe into tee, and it has to- survive that shell key being dropped or changed to `bash {0}`."""+ """shell: bash implies -o pipefail, so set -o pipefail is belt and braces: the gate's exit code+ reaches the step only through the pipe into tee, even if the shell key is dropped or changed."""run = _profile_step()["run"]assert "| tee" in run, "no pipe left; this guard can go"assert "set -o pipefail" in rundiff --git a/tests/test_psutil_apple_cpu_freq.py b/tests/test_psutil_apple_cpu_freq.pyindex e5a8bbe9cd7..9c9b64c2b8f 100644--- a/tests/test_psutil_apple_cpu_freq.py+++ b/tests/test_psutil_apple_cpu_freq.py@@ -363,13 +363,8 @@ class TestPatchApplication:reason = "Apple Silicon only: reads this host's real IORegistry tables",)def _raw_apple_reading():- """This host's own psutil reading, or None when it has none to give.-- psutil gates cpu_freq on a runtime probe on macOS, so on Apple Silicon the- attribute can be missing outright (virtualised runners) or present and- raising (M5, whose tables are not at the indexes psutil hardcodes). Both are- supported hosts, so a test that needs a raw reading skips rather than fails.- """+ """Returns this host's psutil cpu_freq reading or None; on Apple Silicon it can be missing+ (virtualised runners) or raise (M5, tables off psutil's hardcoded indexes), so tests skip."""import psutilreader = getattr(psutil, "cpu_freq", None)diff --git a/tests/test_raw_text.py b/tests/test_raw_text.pyindex ca718fc0e71..d8d55907602 100644--- a/tests/test_raw_text.py+++ b/tests/test_raw_text.py@@ -299,9 +299,8 @@ def test_clean_text_decision_cannot_drift_between_interpreters():def test_smart_chunk_text_single_chunk_no_eos_returns_plain_list():- """smart_chunk_text's single-chunk branch must return a plain list for- input_ids even when the tokenizer has no eos_token_id, matching the- multi-chunk branch's unconditional tolist()/list() conversion."""+ """smart_chunk_text's single-chunk branch must return a plain list for input_ids even without an+ eos_token_id, like the multi-chunk branch's unconditional tolist()/list() conversion."""class MockTensor:def __init__(self, data):@@ -425,9 +424,8 @@ def test_load_from_file_skips_non_object_json_lines():def test_smart_chunk_text_empty_input_returns_no_chunks():- """Empty/whitespace text must yield no chunks. This tokenizer keeps one token- per char (like BPE/SentencePiece keeping spaces), so a len(tokens)==0 check- would miss whitespace; the fix guards on text.strip() before tokenizing."""+ """Empty or whitespace text must yield no chunks; this tokenizer keeps a token per char, so a+ len(tokens)==0 check would miss whitespace, hence the text.strip() guard."""class WhitespacePreservingTokenizer:def __init__(self, eos_token_id):diff --git a/tests/test_remote_moe_shims.py b/tests/test_remote_moe_shims.pyindex 99f0f57591f..ee23ab39385 100644--- a/tests/test_remote_moe_shims.py+++ b/tests/test_remote_moe_shims.py@@ -226,9 +226,8 @@ def test_a_gate_adding_its_bias_in_place_still_backpropagates():def test_shims_reach_a_module_behind_an_accelerate_hook():- """A device_map load wraps forward with an accelerate hook that keeps the original as- `_old_forward`; the class-level shim alone is never called from `module(...)`. Kimi-K2.7-Code- on four GPUs still hit the gate's training assert this way."""+ """A device_map load wraps forward in an accelerate hook keeping the original as _old_forward,+ so a class-level shim is never called; Kimi-K2.7-Code on four GPUs hit the training assert."""from accelerate.hooks import ModelHook, add_hook_to_moduletorch.manual_seed(0)diff --git a/tests/test_rope_cache_current_device.py b/tests/test_rope_cache_current_device.pyindex fb677ab2c57..c527c9c6981 100644--- a/tests/test_rope_cache_current_device.py+++ b/tests/test_rope_cache_current_device.py@@ -406,9 +406,8 @@ def test_model_forward_longrope_under_compile_matches_eager(monkeypatch, start):def test_first_grown_cache_is_computed_on_inv_freq_device():- # A configured max above the 4 * 8192 floor grows the size on the first forward. The eager code then- # rebuilt it on inv_freq's device, so the lazy build must too: on CPU it took 0.3-1.6 s for 128K-1M- # rows and rounded cos/sin differently from every earlier release.+ # The lazy build must run on inv_freq's device, as the eager code did, since a CPU build rounds+ # cos/sin differently from every earlier release.rope = _llama(1 << 17)rope.inv_freq = rope.inv_freq.to("meta")with pytest.raises(NotImplementedError):diff --git a/tests/test_sdpa_fully_masked_rows.py b/tests/test_sdpa_fully_masked_rows.pyindex 4ec7d655bb0..617f821e993 100644--- a/tests/test_sdpa_fully_masked_rows.py+++ b/tests/test_sdpa_fully_masked_rows.py@@ -219,9 +219,8 @@ def test_the_correction_itself_on_every_dtype_it_can_meet():def test_the_correction_is_idempotent_and_self_neutralising():- """Applied twice is applied once, and applied to an already-correct mask it- is the identity in value. That is what makes it safe to leave in place if a- future transformers restores its own guard."""+ """The row unmasking is idempotent and an identity on already-correct masks, so it is safe to+ leave in place if a future transformers restores its own guard."""mask = torch.tensor([[[[False, False], [False, True]]]])once = _unmask_rows_attending_to_nothing(mask)twice = _unmask_rows_attending_to_nothing(once)diff --git a/tests/test_setup_master_root.py b/tests/test_setup_master_root.pyindex b1683e7b11d..27387d5c915 100644--- a/tests/test_setup_master_root.py+++ b/tests/test_setup_master_root.py@@ -583,21 +583,8 @@ def test_the_windows_legacy_root_named_explicitly_is_not_custom(tmp_path):@pytest.mark.skipif(PWSH is None, reason = "needs pwsh")def test_the_windows_uninstaller_only_removes_a_root_that_is_really_empty(tmp_path):- """The master root and its .staging go only when empty, and by an operation that cannot do- anything else.-- Windows asked with Get-ChildItem -ErrorAction SilentlyContinue and then called _RemovePath,- which is Remove-Item -Recurse -Force, in the one directory this branch teaches users to- point at their own files. Two separate calls, so a file arriving between the two was taken- by the -Recurse; and a swallowed enumeration error read as an empty directory.- uninstall.sh uses rmdir for both paths, which is one call that refuses a non-empty- directory, and this file's own %TEMP% prune already asks with -ErrorAction Stop.-- The behavioural halves below are what can be shown on a POSIX host: a recursive delete needs- to enumerate too, so an unlistable directory survives either version here and the ACL shape- that separates DELETE from LIST is Windows-only. What is checked instead is the mechanism,- which is what removes the race as well.- """+ """Master root and .staging go only when empty, removed in one non-recursive call;+ enumerate-then-Remove-Item -Recurse raced with new files and hid errors."""ps = UNINSTALL_PS1.read_text(encoding = "utf-8")assert "function _RemoveDirIfEmpty" in pshelper = _slice(ps, " function _RemoveDirIfEmpty {", "\n # The exact shape")@@ -746,17 +733,9 @@ UNINSTALL_PS1 = REPO_ROOT / "scripts" / "uninstall.ps1"@pytest.mark.skipif(shutil.which("pwsh") is None, reason = "pwsh not available")def test_the_windows_uninstaller_resolves_a_relative_root_like_setup(tmp_path):- """setup.ps1 resolves through PowerShell's own location; uninstall.ps1 used- [IO.Path]::GetFullPath, which anchors at [Environment]::CurrentDirectory.-- PowerShell does not keep those two in step, so after a Set-Location a relative UNSLOTH_HOME- named one install to setup and a different one to the uninstaller. The owner marker does not- save you there: it spares trees that are not Unsloth's, and the wrongly resolved path is- another Unsloth install, marker and all.-- Runs the shipped function rather than matching its text, so a rewrite that keeps the words- and loses the behaviour still fails.- """+ """The uninstaller must resolve a relative UNSLOTH_HOME as setup.ps1 does: GetFullPath anchors+ at CurrentDirectory, which Set-Location leaves out of step; the owner marker cannot catch it+ since the wrong path is another real Unsloth install."""initial = tmp_path / "initial"chosen = tmp_path / "chosen"(chosen / "portable").mkdir(parents = True)diff --git a/tests/test_st_modules_json_trust_gate.py b/tests/test_st_modules_json_trust_gate.pyindex 3a136480ee7..a8ab5ad0bce 100644--- a/tests/test_st_modules_json_trust_gate.py+++ b/tests/test_st_modules_json_trust_gate.py@@ -1411,9 +1411,8 @@ def test_an_unparseable_manifest_is_tolerated_where_upstream_gates_it(tmp_path,def test_a_manifest_that_is_not_a_list_is_not_a_refusal(tmp_path, monkeypatch):- """A modules.json that is not a list names no modules, and the loader iterates it too,- so it cannot build a module from this either. Refusing would only break a load that- upstream fails on its own."""+ """A non-list modules.json names no modules and the loader iterates it too, so the gate cannot+ build a module from it; refusing would only break a load upstream fails on its own."""_simulate_pre_six(monkeypatch)odd = tmp_path / "models--acme--embedder" / "snapshots" / ("c" * 40)diff --git a/tests/test_st_save_merged_signature.py b/tests/test_st_save_merged_signature.pyindex e9c4f687574..b5c08e9cd0c 100644--- a/tests/test_st_save_merged_signature.py+++ b/tests/test_st_save_merged_signature.py@@ -228,8 +228,7 @@ class _Merged:class _FakeST:- """A SentenceTransformer stand-in: a sequence of modules, module 0 of- which wraps the transformer."""+ """A SentenceTransformer stand-in: a sequence of modules, where module 0 wraps the transformer."""def __init__(self, no_modules = False):self.tokenizer = _Tok()@@ -334,11 +333,8 @@ def test_the_forwarding_path_refuses_lora_for_its_own_reason(tmp_path):def test_the_two_lora_refusals_do_not_share_a_message(tmp_path):- """Written because the check above can only see one of the pair at a time.-- If both branches were ever collapsed onto one message, each test would still pass on its- own substring while the distinction that makes the advice actionable was gone.- """+ """Each refusal is checked alone, so this test compares both: collapsing the two LoRA refusals+ onto one message would hide the distinction that makes the advice actionable."""fn, _ = _extract(1)messages = []for no_modules in (True, False):diff --git a/tests/test_st_subfolder_weights_are_fetched.py b/tests/test_st_subfolder_weights_are_fetched.pyindex db980d592b9..3a4bc45a8b1 100644--- a/tests/test_st_subfolder_weights_are_fetched.py+++ b/tests/test_st_subfolder_weights_are_fetched.py@@ -75,9 +75,8 @@ def test_a_root_only_st_model_is_not(modules_json):def test_a_repo_without_modules_json_is_not(modules_json):- """The overwhelming majority. A plain causal LM must keep the old- behaviour exactly, so a fix for one notebook does not enlarge 400 other- downloads."""+ """Plain causal LMs, the overwhelming majority, must keep the old behaviour exactly so a fix for+ one notebook does not enlarge other downloads."""modules_json(None)assert U._repo_has_weighted_st_subfolders("unsloth/Qwen3-0.6B") is False@@ -182,9 +181,8 @@ def test_only_the_subdir_weight_patterns_differ(modules_json, monkeypatch):def test_the_patterns_still_exist(modules_json):- """They are correct for the case they were written for -- an fp16/ or- experimental/ directory a root load never reads. This fix narrows where- they apply, it does not retire them."""+ """The subdir weight ignore patterns are correct for fp16/ or experimental/ directories a root+ load never reads; this fix narrows where they apply and does not retire them."""assert "*/*.safetensors" in U._SUBDIR_WEIGHT_IGNORE_PATTERNSassert "*/*.bin" in U._SUBDIR_WEIGHT_IGNORE_PATTERNSdiff --git a/tests/test_studio_install_workspace_guard.py b/tests/test_studio_install_workspace_guard.pyindex a2a155b5fcb..ca95128d2ae 100644--- a/tests/test_studio_install_workspace_guard.py+++ b/tests/test_studio_install_workspace_guard.py@@ -329,9 +329,8 @@ def test_setup_ps1_direct_update_in_place_route_is_the_last_escape():def test_setup_ps1_stale_sweep_runs_outside_the_rebuild_branch():- """The sweep collects leftovers from an earlier move-aside whose delete a lock cut short. Inside- the rebuild branch it would never run for the install that needs it most: one that renamed a- venv aside, failed to delete the copy, and thereafter always takes an in-place route."""+ """The stale-venv sweep must run outside the rebuild branch, since an install whose move-aside+ delete failed always takes an in-place route and would never reach it."""src = SETUP_PS1.read_text(encoding = "utf-8")sweep = src.index("$_staleShape = ")rebuild = src.index("Stale venv detected ($reason) -- rebuilding")@@ -1205,12 +1204,8 @@ def test_install_sh_rejects_an_id_holding_a_nul_byte(tmp_path):@pytest.mark.skipif(os.name != "posix", reason = "PATH-shadowed cat is a POSIX shape")def test_install_sh_reports_a_failed_read_instead_of_regenerating(tmp_path):- """A read that FAILS is not the same answer as a malformed id.-- `-r` can pass while the read errors, on an NFS or FUSE backed root.- Flattening that into "no id" let the publish path replace a valid- incumbent a running backend still reports.- """+ """A failed read is not a malformed id: -r can pass on NFS or FUSE roots while the read errors,+ and treating that as no id let publish replace a valid incumbent a backend reports."""src = INSTALL_SH.read_text(encoding = "utf-8")assert ('_cvi_id=$({ cat "$1"; } 2>/dev/null) || return 1' in src@@ -1247,11 +1242,8 @@ def test_install_sh_reports_a_failed_read_instead_of_regenerating(tmp_path):reason = "needs POSIX mode bits, and root reads regardless of them",)def test_install_sh_replaces_an_empty_id_even_when_it_cannot_read_it(tmp_path):- """Zero length is an answer stat can give: that file holds no id.-- Refusing would fail an install that pre-validation simply completed. The- protection is for ids we cannot read, and an id is 64 bytes, never zero.- """+ """An empty id file reads as no id, even when unreadable, since refusing would fail an install+ that pre-validation completed; a real id is 64 bytes."""src = INSTALL_SH.read_text(encoding = "utf-8")assert '[ -s "$1" ] || return 0' in src, "an empty id file must read as no id"@@ -1280,12 +1272,8 @@ def test_install_sh_replaces_an_empty_id_even_when_it_cannot_read_it(tmp_path):reason = "needs POSIX mode bits, and root reads regardless of them",)def test_install_sh_refuses_an_unreadable_existing_id(tmp_path):- """An id we cannot READ must not be treated as malformed and replaced.-- In a shared root it can be a good id owned by someone else that a running- backend already reports, so the step refuses, as it did before the id was- validated at all.- """+ """An unreadable id must not be treated as malformed and replaced: in a shared root it may be a+ good id owned by someone else that a running backend reports, so refuse."""src = INSTALL_SH.read_text(encoding = "utf-8")fn_start = src.index('_css_id_dir="$STUDIO_HOME/share"')block = src[fn_start : fn_start + 4200]@@ -1319,11 +1307,8 @@ def test_install_sh_refuses_an_unreadable_existing_id(tmp_path):@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason = "no FIFOs on this platform")def test_install_sh_never_reads_a_non_regular_id_path(tmp_path):- """A FIFO at the id path must not park the installer on the open.-- `cat` blocks until a writer appears, so an unconditional read of a shared- or custom root hangs the install forever.- """+ """A FIFO at the id path must not hang the installer: cat blocks until a writer appears, so+ install.sh reads the id only from a regular file."""src = INSTALL_SH.read_text(encoding = "utf-8")assert '[ -f "$1" ] || return 0' in src, "install.sh must read the id only from a regular file"@@ -1340,11 +1325,9 @@ def test_install_sh_never_reads_a_non_regular_id_path(tmp_path):@pytest.mark.skipif(os.name != "posix", reason = "runs the POSIX installer function")def test_create_studio_shortcuts_end_to_end_never_embeds_a_planted_id(tmp_path):- """The REAL create_studio_shortcuts, not a reconstruction of it.-- Helper-level tests cannot catch a caller that validates then embeds- something else, so this inspects the launcher the shipped function writes.- """+ """Runs the real create_studio_shortcuts, since helper-level tests cannot catch a caller that+ validates an id and then embeds something else; it inspects the launcher that function+ writes."""home = tmp_path / "home"studio_home = tmp_path / "studio"data_dir = tmp_path / "data"diff --git a/tests/test_torchao_subprocess_fix.py b/tests/test_torchao_subprocess_fix.pyindex 48ffe265c5c..a0ba35187e1 100644--- a/tests/test_torchao_subprocess_fix.py+++ b/tests/test_torchao_subprocess_fix.py@@ -61,9 +61,8 @@ def test_it_does_not_overwrite_existing_torch_symbols():def test_the_child_never_imports_unsloth():- """Importing unsloth at the start of every subprocess would pay the full- import cost each time and could recurse back through- propagate_torchao_fix_to_subprocesses, so the logic is inlined."""+ """The child must not import unsloth: that pays the full import cost in every subprocess and+ could recurse through propagate_torchao_fix_to_subprocesses, so logic is inlined."""src = IF._subprocess_sitecustomize_source()assert "import unsloth" not in srcassert "from unsloth" not in src@@ -117,8 +116,7 @@ def _torchao_is_broken_here() -> bool:def test_it_is_a_noop_on_a_healthy_environment():- """Nothing is written and PYTHONPATH is untouched unless the fix is- actually needed."""+ """Nothing is written and PYTHONPATH is left untouched unless the fix is actually needed."""if _torchao_is_broken_here():pytest.skip("this environment genuinely needs the fix")before = os.environ.get("PYTHONPATH")@@ -163,9 +161,8 @@ def test_it_is_idempotent_on_pythonpath():def test_the_directory_is_private_to_this_user():- """The temp dir is shared and everything on PYTHONPATH runs in every- subprocess, so a fixed name there is code execution for whoever creates it- first."""+ """The temp dir is shared and everything on PYTHONPATH runs in every subprocess, so a fixed name+ there gives code execution to whoever creates it first."""directory = IF._subprocess_fix_directory()if hasattr(os, "getuid"):assert directory.endswith("-%d" % os.getuid()), directory@@ -564,9 +561,8 @@ def test_our_own_hook_file_is_trusted(tmp_path):@pytest.mark.parametrize("kind", ["symlink", "group_writable"])def test_a_planted_hook_is_replaced_even_when_it_matches(monkeypatch, tmp_path, kind):- """End to end: a once-world-writable directory already holds a hook whose- contents match ours. Tightening the directory does not revoke write access- to that file, so leaving it is code execution in every subprocess."""+ """A once world-writable directory may hold a hook matching our contents; tightening it does not+ revoke that file's write access, so keeping it would mean code execution in every subprocess."""if not hasattr(os, "getuid"):pytest.skip("POSIX ownership/permissions only")import torch.nn.functional as F@@ -608,9 +604,8 @@ def test_a_planted_hook_is_replaced_even_when_it_matches(monkeypatch, tmp_path,def test_a_pre_created_temporary_symlink_is_not_followed(monkeypatch, tmp_path):- """The other half of a once-world-writable directory: the temporary file- the hook is staged through. A predictable name lets someone leave a- symlink behind, and os.replace would install that link as the hook."""+ """A predictable temp name lets someone leave a symlink behind, and os.replace would install+ that link as the hook, so the staged temp file must not be followed."""if not hasattr(os, "getuid"):pytest.skip("POSIX symlinks only")import stat as _stat@@ -727,9 +722,8 @@ _COUNT_HOOKS = (def test_a_symlink_alias_of_our_own_directory_is_not_chained(staged, tmp_path):- """A string compare treats an alias as somebody else's sitecustomize, so- the two spellings load and execute one another until the stack runs out.- Every unwound level then installs another finder."""+ """A string compare treats a symlink alias of our own directory as another sitecustomize, so the+ two load each other until the stack runs out, and each unwound level installs a finder."""if not hasattr(os, "symlink"):pytest.skip("symlinks only")site, _fake = stageddiff --git a/tests/test_torchao_torch_symbol_skew.py b/tests/test_torchao_torch_symbol_skew.pyindex 69eee41b22e..2c373f3f7d3 100644--- a/tests/test_torchao_torch_symbol_skew.py+++ b/tests/test_torchao_torch_symbol_skew.py@@ -209,9 +209,8 @@ INIT = ROOT / "unsloth" / "__init__.py"def test_the_mlx_path_applies_the_fix_too():- """The MLX branch imports unsloth_zoo directly and never reaches- _gpu_init, so without the fix there Apple Silicon hits the same dead- import."""+ """The MLX branch imports unsloth_zoo directly without reaching _gpu_init, so without the fix+ Apple Silicon hits the same dead import."""lines = INIT.read_text(encoding = "utf-8").splitlines()fix = next(i for i, l in enumerate(lines) if "_fix_torchao()" in l)zoo = next(i for i, l in enumerate(lines) if l.strip() == "import unsloth_zoo")diff --git a/tests/test_tp_env_gloo.py b/tests/test_tp_env_gloo.pyindex 9075d924d64..a0738a46f04 100644--- a/tests/test_tp_env_gloo.py+++ b/tests/test_tp_env_gloo.py@@ -30,11 +30,10 @@ from test_tp_native_gloo import ( # noqa: E402_trainer_args,)-# These arms start the adapters at init_lora_weights = False and compare 3 whole Trainer steps. At AdamW's-# default eps 1e-8, m / (sqrt(v) + eps) turns the fp32 reduction-order noise between tp = 2 and one process-# into 1e-5 grad-norm and 1e-4 weight drift by step 3 while the losses still match exactly; at 1e-4 it stays-# below 1e-6, and a real tp error (a missed all-reduce) still lands at 3.5e-4. Only these runs take it: the-# native Trainer tests (B = 0 adapters) pass at the default eps on the CI runners and fail at 1e-4 there.+# Only these arms use eps 1e-4: at the default 1e-8 AdamW turns tp=2 vs one-process fp32 reduction+# noise into 1e-4 weight drift by step 3; at 1e-4 drift stays below 1e-6 while a real missed+# all-reduce still gives 3.5e-4; B = 0 native Trainer tests pass at default eps on CI but fail at+# 1e-4._ADAM_EPS = 1e-4_ENV_KEYS = (diff --git a/tests/test_tp_native_gloo.py b/tests/test_tp_native_gloo.pyindex 428e787e71f..01dbf243106 100644--- a/tests/test_tp_native_gloo.py+++ b/tests/test_tp_native_gloo.py@@ -1460,10 +1460,9 @@ def test_sharded_loading_refuses_quantized_loads():)-# Per-step grad norms over 3 AdamW steps. phi3's fused qkv / gate_up shards add reduction-order noise that the-# optimizer compounds: on the CI runners its step-3 norm lands 6.9e-5 / 7.7e-5 relative off one process-# (1.5e-6 at step 1), while this host stays inside 1e-5. The step-1 per-gradient check in the test-# (rtol 1e-4, atol 1e-6) is what catches a real tp error such as a missed all-reduce, and it is unchanged.+# phi3 fused qkv / gate_up shards add reduction-order noise the optimizer compounds (step-3 grad+# norm 6.9e-5 / 7.7e-5 off one process on CI); the step-1 per-gradient check (rtol 1e-4, atol 1e-6)+# catches real tp errors like a missed all-reduce._TP_FSDP2_NORM_REL = {"phi3": 2e-4}diff --git a/tests/test_transformers_cap_sites.py b/tests/test_transformers_cap_sites.pyindex 9bfbcdc0f05..43546ec6315 100644--- a/tests/test_transformers_cap_sites.py+++ b/tests/test_transformers_cap_sites.py@@ -341,9 +341,8 @@ def test_no_workflow_lane_sits_below_the_declared_ceiling() -> None:def test_every_exemption_names_a_lane_that_exists_today() -> None:- """A dormant exemption is a pre-authorisation: the day its string returns, the scan finds it and- skips it, which is the failure this file exists to prevent.- """+ """A dormant exemption is a pre-authorisation: once its string reappears the scan finds it and+ skips it, which is the failure this file exists to prevent."""spelled = {(path.name, raw.strip())for path in sorted(WORKFLOWS.glob("*.yml"))@@ -410,9 +409,8 @@ def test_this_file_is_triggered_by_everything_it_scans() -> None:def test_a_stale_range_cap_is_caught_even_in_an_allowlisted_workflow(tmp_path, monkeypatch) -> None:- """NEGATIVE CONTROL: keyed on the filename, one intentional pin exempted every other- transformers requirement in that file, so a range cap could go stale in the scanned workflow.- """+ """Negative control: exemptions keyed on the filename let one intentional pin exempt every other+ transformers requirement in that file, hiding a stale range cap."""workflows = tmp_path / "workflows"workflows.mkdir()(workflows / "version-compat-ci.yml").write_text(@@ -432,9 +430,8 @@ def test_a_stale_range_cap_is_caught_even_in_an_allowlisted_workflow(tmp_path, mdef _matrix_module(urlopen):- """The pinned-symbols module, imported fresh with `urlopen` replaced, under its own name: the- matrix is built at import, so the substitution must precede the module body.- """+ """Imports the pinned-symbols module fresh with urlopen replaced; the matrix is built at import,+ so the substitution must precede the module body."""import importlib.utilimport urllib.request@@ -494,9 +491,8 @@ def test_the_outage_fallback_reaches_the_declared_floor() -> None:def test_an_empty_release_index_keeps_every_load_bearing_tag() -> None:- """NEGATIVE CONTROL: a reachable PyPI yielding no usable release takes a different return- path, which has to merge the anchors too.- """+ """Negative control: a reachable PyPI with no usable release takes a different return path,+ which must also merge the anchors."""import ioimport json as _json@@ -517,9 +513,8 @@ def test_an_empty_release_index_keeps_every_load_bearing_tag() -> None:def test_the_declared_ceiling_stays_in_the_matrix_after_a_patch_release() -> None:- """One tag per minor means a 5.17.1 would evict 5.17.0, the exact maximum the window admits, and- check a version no user can resolve instead. The anchor derives from pyproject's cap.- """+ """One tag per minor would let a 5.17.1 evict 5.17.0, the exact maximum the window admits, and+ check a version no user can resolve; the anchor derives from pyproject's cap."""import ioimport json as _json@@ -551,9 +546,8 @@ def test_the_declared_ceiling_stays_in_the_matrix_after_a_patch_release() -> Nondef test_the_matrix_is_shared_between_xdist_workers(tmp_path, monkeypatch) -> None:- """Each worker resolves the matrix during collection, so one timing out takes the fallback list,- the parameter sets diverge and xdist aborts. With the cache set, the first to resolve publishes.- """+ """Each worker resolves the matrix during collection, so one timing out would take the fallback+ list and diverge the parameter sets, aborting xdist; with the cache set, the first publishes."""import ioimport json as _jsonimport urllib.error@@ -599,9 +593,8 @@ def test_without_the_cache_a_failed_read_still_falls_back(tmp_path, monkeypatch)def test_a_pinned_patch_release_is_not_evicted_by_a_later_one() -> None:- """Notebooks pin 5.10.1; with 5.10.4 published the (5, 10) slot becomes 5.10.4, so a symbol- arriving in a later 5.10 patch would break them while this matrix stayed green.- """+ """Notebooks pin 5.10.1; once 5.10.4 is published the (5, 10) slot becomes 5.10.4, so a symbol+ added in a later 5.10 patch would break the notebooks unseen."""import ioimport json as _json@@ -632,9 +625,8 @@ def test_a_pinned_patch_release_is_not_evicted_by_a_later_one() -> None:def test_an_import_lane_pins_the_declared_ceiling() -> None:- """The `latest` lane is unpinned, so once upstream publishes above the cap it resolves a- combination no user can install. The static symbol suite cannot see import-time breakage.- """+ """The latest lane is unpinned, so once upstream publishes above the cap it resolves a+ combination no user can install; static symbol checks cannot see import-time breakage."""import yamlworkflow = yaml.safe_load((WORKFLOWS / "version-compat-ci.yml").read_text(encoding = "utf-8"))@@ -689,9 +681,8 @@ def test_no_two_import_lanes_mint_the_same_pip_cache_key() -> None:def test_a_published_matrix_still_carries_the_anchors(tmp_path, monkeypatch) -> None:- """The published file can come from another revision or an earlier run, and returning it verbatim- dropped the floor, the old ceiling and the notebook pins while the suite reported green.- """+ """A published matrix may come from another revision or an earlier run; returning it verbatim+ dropped the floor, old ceiling and notebook pins while the suite stayed green."""import json as _jsonimport urllib.error@@ -712,9 +703,8 @@ def test_a_published_matrix_still_carries_the_anchors(tmp_path, monkeypatch) ->def test_the_declared_ceiling_anchor_uses_the_tag_upstream_pushed() -> None:- """NEGATIVE CONTROL: upstream does not always tag a release under its own name, so a ceiling- landing on one must resolve to the tag pushed or every check fails on the fetch.- """+ """Negative control: upstream does not always tag a release under its own name, so a ceiling+ must resolve to the tag actually pushed or every check fails on the fetch."""import importlib.utilpath = (@@ -769,8 +759,7 @@ def _newest_published_zoo_transformers_ceiling(timeout: float = 10.0):def test_the_zoo_deferral_expires_when_the_zoo_release_ships() -> None:"""The gate above skips on a hand-written constant, so this asks PyPI what the newest zoo allows- and fails only on POSITIVE evidence it is obsolete; an offline runner stays skipped.- """+ and fails only on positive evidence the deferral is obsolete; offline stays skipped."""if ZOO_FLOOR_WITH_LIFTED_TRANSFORMERS_CAP is not None:pytest.skip("the floor already names a zoo release carrying the lift, so the deferral is "diff --git a/tests/test_trust_remote_code_native_compile.py b/tests/test_trust_remote_code_native_compile.pyindex 401e55fe42d..4602972236c 100644--- a/tests/test_trust_remote_code_native_compile.py+++ b/tests/test_trust_remote_code_native_compile.py@@ -107,10 +107,8 @@ def _cuda_is_available():@pytest.mark.skipif(not _cuda_is_available(), reason = "needs a GPU to load a 4-bit model")def test_native_model_with_trust_remote_code_keeps_fast_lora(tmp_path, monkeypatch):- """The arm that fails without the fix: PEFT's Linear4bit forward is left in place.-- Skips only on errors meaning the checkpoint cannot be built here (old transformers, no torchvision, offline).- """+ """The arm that fails without the fix keeps PEFT's Linear4bit forward in place; it skips only+ when the checkpoint cannot be built here (old transformers, no torchvision, offline)."""monkeypatch.chdir(tmp_path) # fresh unsloth_compiled_cacheimport torchimport unsloth # noqa: F401diff --git a/tests/test_unsloth_device_map_optin.py b/tests/test_unsloth_device_map_optin.pyindex 3c7004ae5eb..6e74deb8490 100644--- a/tests/test_unsloth_device_map_optin.py+++ b/tests/test_unsloth_device_map_optin.py@@ -394,9 +394,8 @@ def test_an_infeasible_plan_is_still_raised_for_the_balanced_name():def test_the_default_device_map_still_resolves_to_the_plain_sentinel():- """An omitted device_map becomes the planner, and its decline has always been- "sequential" -- which is also what an omitted device_map got before planning existed.- Widening that to "balanced" would change what every single-card caller loads."""+ """An omitted device_map resolves to the planner, whose decline stays sequential as it was+ before planning existed; widening that to balanced would change single-card loads."""ns = _load()assert ns["requested_device_map"](ns["DEFAULT_DEVICE_MAP"]) == "unsloth"@@ -420,9 +419,8 @@ def test_the_plan_is_returned_and_the_model_name_reaches_the_planner():def test_free_memory_is_planned_against_not_total():- """Two 16 GB cards with a CUDA context already resident have far less than 16 GB to- give. Planning against total is what made the notebook's first attempt OOM- (unsloth-zoo#1048)."""+ """Planning against total memory OOMed the notebook's first attempt (unsloth-zoo#1048): a+ resident CUDA context leaves far less than 16 GB free on each 16 GB card."""seen = {}ns = _load(free = {0: 4 * 2**30, 1: 15 * 2**30},diff --git a/tests/test_unsloth_device_map_review_fixes.py b/tests/test_unsloth_device_map_review_fixes.pyindex 17976da6cb8..ef6828917a3 100644--- a/tests/test_unsloth_device_map_review_fixes.py+++ b/tests/test_unsloth_device_map_review_fixes.py@@ -451,9 +451,8 @@ def test_gpus_the_caller_withheld_are_never_probed():def test_a_refusing_card_outside_the_requested_set_does_not_cost_the_plan():- """Dropping to "sequential" because GPU 3 is in Exclusive_Process mode is the wrong- answer when the caller asked for GPUs 0 and 1 -- and "sequential" is the placement that- then OOMs."""+ """A card in Exclusive_Process mode outside the requested set (GPU 3) must not drop the plan to+ sequential, which OOMs when the caller asked for GPUs 0 and 1."""planner = _Recorder(plan = _Plan())ns = _build(devices = 4,diff --git a/tests/test_video_path_validation.py b/tests/test_video_path_validation.pyindex 48ec93a67f2..a55b829a50b 100644--- a/tests/test_video_path_validation.py+++ b/tests/test_video_path_validation.py@@ -348,8 +348,7 @@ def test_file_uri_double_encoded_percent(check_dataset_for_missing_videos, tmp_pdef test_windows_style_absolute_path_not_mistaken_for_scheme(check_dataset_for_missing_videos, tmp_path):- """'C:/...' has no '://' so it is a plain path, even where urlparse- would yield scheme='c'."""+ """The path C:/... has no '://' so it is a plain path, even where urlparse would yield scheme 'c'."""target = tmp_path / "clip.mp4"target.write_bytes(b"x")path = str(target)diff --git a/tests/test_warnings_issued_guard.py b/tests/test_warnings_issued_guard.pyindex a8c8ee024b3..687da31841b 100644--- a/tests/test_warnings_issued_guard.py+++ b/tests/test_warnings_issued_guard.py@@ -71,8 +71,7 @@ def test_each_model_gets_its_own_dict():def test_an_existing_dict_is_left_exactly_as_it_was():- """This is the whole backwards-compatibility claim: on transformers 4.x and- 5.0, where the attribute is already a dict, the guard must be a no-op --+ """On transformers 4.x and 5.0 the attribute is already a dict, so the guard must be a no-op:same object, same contents, nothing rebound."""m = _Bare()original = {"estimate_tokens": True, "other": 1}@@ -107,9 +106,8 @@ def test_running_twice_is_idempotent():@pytest.mark.parametrize("value", [None, "Qwen/Qwen2.5-1.5B", 7, object()])def test_non_modules_are_left_alone_without_raising(value):- """trl accepts a repo id string and builds the model itself. Attaching an- attribute to whatever was passed is not this function's job, and it must- never be the thing that raises."""+ """trl accepts a repo id string and builds the model itself, so the guard must leave non-modules+ alone and never be the thing that raises."""GUARD(value)assert not hasattr(value, "warnings_issued")@@ -259,9 +257,8 @@ def test_trl_still_writes_the_attribute_unconditionally():def test_the_installed_transformers_tells_us_which_side_of_5_1_we_are_on():- """Not an assertion about which version is installed -- a check that the- two possible worlds behave as claimed. 4.x/5.0 ship the attribute and the- guard is a no-op; 5.1+ do not and the guard is what makes trl work."""+ """Checks both possible worlds behave as claimed rather than which version is installed: 4.x/5.0+ ship warnings_issued and 5.1+ do not, where the guard makes trl work."""transformers = pytest.importorskip("transformers")import transformers.modeling_utils as mu@@ -536,9 +533,8 @@ def test_trainer_kwargs_still_go_to_the_trainer(tmp_path):def test_auto_packing_wraps_inside_the_backwards_compatible_wrapper():- """Auto-packing reads `packing` off the config to block VLMs, custom collators- and the blocklist, so it has to wrap first and see the moved value. Wrapped- last it decides on the old one, and the block is undone right after."""+ """Auto-packing reads packing off the config to block VLMs, collators and the blocklist, so it+ must wrap first to see the moved value; wrapped last, the block is undone right after."""for node in ast.walk(ast.parse(SRC)):if isinstance(node, ast.FunctionDef) and node.name == "_patch_trl_trainer":body = ast.get_source_segment(SRC, node)@@ -567,9 +563,8 @@ def test_auto_packing_failure_still_leaves_the_wrapper_installed():def test_a_plain_training_arguments_keeps_the_moved_kwargs(tmp_path):- """The old notebook shape: transformers.TrainingArguments plus SFT kwargs on the trainer. trl- rebuilds a plain TrainingArguments with SFTConfig(**args.to_dict()), which drops anything set- as an attribute, so packing, the text field and the length used to fall back to defaults."""+ """Plain TrainingArguments plus SFT kwargs: trl rebuilds via SFTConfig(**args.to_dict()), which+ drops attributes set on args, so packing, text field and length must survive."""from transformers import TrainingArgumentsTrainer, config_class = _wrapped_recording()diff --git a/tests/test_windows_amd_gpu_scan_fallback.py b/tests/test_windows_amd_gpu_scan_fallback.pyindex 8dd66cf50cc..f150075c82d 100644--- a/tests/test_windows_amd_gpu_scan_fallback.py+++ b/tests/test_windows_amd_gpu_scan_fallback.py@@ -366,10 +366,8 @@ def test_an_empty_handoff_is_ignored(tmp_path):"var", ["HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"])def test_a_mask_suppresses_the_handoff(tmp_path, var):- """The mask selects the unrecognized discrete card, so the inference above deliberately- resolves nothing rather than borrowing the 780M's arch. The installer scans without the mask- and forwards that very arch, and taking it would install for a GPU the mask hides from the- runtime entirely (ROCR filters below HIP, so masked devices never reach enumeration)."""+ """Under a mask, resolve no arch rather than borrow the 780M's: the installer's unmasked arch+ would target a GPU the runtime hides (ROCR filters below HIP)."""# RX 580 (gfx803) has no routed arch; the RX 5700 XT now routes.adapters = [(_R780M, 0), ("AMD Radeon RX 580", 0)]assert _run(tmp_path, adapters, env = {var: "1", HANDOFF: "gfx1103"})["arch"] is None@@ -451,9 +449,8 @@ def _run_installer_scan(@requires_pwshdef test_the_installer_skips_a_disabled_adapter(tmp_path):- """A disabled Radeon listed first used to win here, and a mapped arch installs ROCm wheels- right there, so the dead card got the wheels and the live unsupported one went to nothing.- Setup filters this adapter out, so forwarding its arch also made the two disagree."""+ """Skip disabled adapters as setup does: a dead Radeon listed first would otherwise get the ROCm+ wheels while the live unsupported card gets none."""out = _run_installer_scan(tmp_path, [("AMD Radeon RX 9070 XT", 22), ("AMD Radeon RX 580", 0)])assert out["label"] == "AMD Radeon RX 580"assert out["arch"] is None, "the active card is unsupported, so this host belongs on CPU"@@ -740,9 +737,8 @@ def _run_handoff_lifecycle(def test_the_caller_environment_survives_the_setup_call(tmp_path, arch, inherited, fails, caller_env):- """`irm ... | iex` runs install.ps1 in the caller's own shell, so anything set for the child- has to be put back -- on the failure path too, which is the one that rolls back and retries,- and whether or not the caller had the variable to begin with."""+ """install.ps1 runs in the caller's own shell via irm | iex, so variables set for the child must+ be restored on success and failure, even if unset before."""out = _run_handoff_lifecycle(tmp_path,arch = arch,@@ -932,14 +928,9 @@ def test_a_real_llama_cpp_dir_is_handed_over_and_then_put_back(tmp_path, caller_def test_only_this_runs_arch_is_handed_to_the_child(tmp_path, arch, inherited, expected, caller_env):- """A value inherited from an outer process is not this run's answer, so it is cleared rather- than forwarded as though the scan had produced it.-- Parametrised over the caller patterns, not left on the helper's default. The default is- `all`, which sets every caller variable, and a clear that wrongly keyed itself off some- other variable's $hadPrevious flag would then find that flag true and clear anyway. The- empty-caller case is the one that catches it, and running only the default lost it.- """+ """Inherited values are cleared, not forwarded as this run's answer; parametrise over caller+ patterns, since the default all hides a clear keyed off another $hadPrevious flag, which only+ the empty-caller pattern catches."""out = _run_handoff_lifecycle(tmp_path, arch = arch, inherited = inherited, fails = False, caller_env = caller_env)diff --git a/tests/test_windows_no_sentencepiece.py b/tests/test_windows_no_sentencepiece.pyindex cb304f66a63..808f0790747 100644--- a/tests/test_windows_no_sentencepiece.py+++ b/tests/test_windows_no_sentencepiece.py@@ -158,9 +158,8 @@ def test_calling_it_twice_is_stable(monkeypatch):def test_the_studio_parent_applies_the_same_rule_without_importing_unsloth():- """Studio's parent must not import unsloth: that runs unsloth/__init__.py, whose GPU branch- pulls torch, Triton, transformers and the model stack into a long-lived process built to- stay light, and can open a competing GPU context. So it calls Studio's own copy instead."""+ """Studio's parent must not import unsloth: unsloth/__init__.py's GPU branch pulls torch, Triton+ and transformers into a light process and can open a competing GPU context."""source = MAIN.read_text(encoding = "utf-8")assert "from unsloth.import_fixes import" not in sourceassert "import unsloth\n" not in source@@ -190,9 +189,8 @@ def test_the_studio_parent_applies_the_same_rule_without_importing_unsloth():],)def test_the_two_spellings_agree(platform, env, expect_disabled, monkeypatch):- """The package helper and Studio's copy, driven through the same cases. Compared by- behaviour rather than by source text, which would pass on two implementations that had- quietly stopped agreeing."""+ """Compares the package helper and Studio's copy by behaviour over the same cases; comparing+ source text would pass even if the two had stopped agreeing."""monkeypatch.setattr(sys, "platform", platform)if env is None:monkeypatch.delenv(DISABLE_SENTENCEPIECE_VARIABLE, raising = False)diff --git a/tests/utils/test_attention_masks.py b/tests/utils/test_attention_masks.pyindex c90baf31ab0..90c57c43a90 100644--- a/tests/utils/test_attention_masks.py+++ b/tests/utils/test_attention_masks.py@@ -769,9 +769,8 @@ def test_run_attention_sdpa_ignores_a_zero_window(monkeypatch):def test_the_window_mask_is_built_once_per_shape(monkeypatch):- """Every layer asks for the identical mask, and at 32K that tensor is 1 GiB with two more- alive while it is built. Rebuilding it per layer is how this SDPA fallback OOMs a run that- xFormers or flash would have carried."""+ """Every layer asks for the same mask (1 GiB at 32K, two more alive while built); rebuilding it+ per layer makes the SDPA fallback OOM where xFormers or flash would not."""attention_dispatch._WINDOW_MASK_CACHE.clear()built = []real_arange = torch.arangediff --git a/tests/utils/test_dataset_num_proc.py b/tests/utils/test_dataset_num_proc.pyindex 7775ed099db..e0fd0612624 100644--- a/tests/utils/test_dataset_num_proc.py+++ b/tests/utils/test_dataset_num_proc.py@@ -540,13 +540,8 @@ def test_zoo_sft_prepare_dataset_anchor_has_not_drifted():def test_the_narrow_num_proc_anchor_still_matches_the_installed_zoo():- """The num_proc site has a second, narrower anchor; it needs its own canary.-- The block anchor drifting is survivable precisely because this regex catches- the assignment the block ends on. If the Zoo ever renames or restructures- that line too, both anchors are gone and nothing rewrites the worker count --- so pin it here, in CI, rather than discovering it from a user's Pool(1).- """+ """The narrow num_proc anchor backs up the block anchor; if both break, nothing rewrites the+ worker count, so this canary pins it in CI."""source = _zoo_source_as_anchored()pattern = _narrow_num_proc_pattern()@@ -1396,9 +1391,8 @@ def test_the_unaided_reader_picks_its_own_v1_line_too(monkeypatch, dnp, tmp_pathdef test_the_hatch_wins_on_a_small_split_too(monkeypatch, dnp):- """A split under the threshold is where the resolver would otherwise stand- down, and standing down there would silently discard the count a user set- by hand to get workers on a small dataset."""+ """The env override must win on a split under the threshold too, where the resolver would+ otherwise stand down and silently drop a hand-set worker count."""_force_start_method(monkeypatch, dnp, "fork")_force_stdlib_start_method(monkeypatch, dnp, "fork")monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, "16")diff --git a/tests/utils/test_q_galore.py b/tests/utils/test_q_galore.pyindex 851951f3c73..39d107f5832 100644--- a/tests/utils/test_q_galore.py+++ b/tests/utils/test_q_galore.py@@ -77,12 +77,8 @@ def requires_bnb_optimizer(device):@pytest.mark.skipif(not _adamw_mod._HAS_BNB, reason = "bitsandbytes is required")def test_optimizer_constructs_against_the_installed_bitsandbytes():- """Runs on every version in the CI matrix, unlike the tests that need a step.-- Construction needs no optimizer kernels, so this is the only check the 0.45.x-0.49.x- matrix jobs can actually execute. It has to assert on the bound arguments because the- 0.50.x misbinding left the arity intact and raised nothing.- """+ """Construction needs no kernels, so it also runs in the 0.45.x-0.49.x jobs; it must assert+ bound arguments, since 0.50.x misbinding kept the arity and raised nothing."""signature = inspect.signature(_adamw_mod.Optimizer2State.__init__)captured = {}original = _adamw_mod.Optimizer2State.__init__diff --git a/tests/utils/test_unsloth_optimizer_full_finetune_embedding_lr.py b/tests/utils/test_unsloth_optimizer_full_finetune_embedding_lr.pyindex e4440778486..c859426ffb2 100644--- a/tests/utils/test_unsloth_optimizer_full_finetune_embedding_lr.py+++ b/tests/utils/test_unsloth_optimizer_full_finetune_embedding_lr.py@@ -82,9 +82,8 @@ def test_frozen_embeddings_stay_out_of_the_optimizer():def test_a_checkpoint_from_before_resumes_with_its_own_moments():- # The previous layout put the embeddings in the ordinary decay groups, so the new- # groups differ; every parameter must get its own moments back, and the embeddings- # their own learning rate at the saved point of the schedule.+ # Checkpoints from the old layout put embeddings in the ordinary decay groups, so resume must+ # restore each parameter's moments and the embeddings' own LR at the saved schedule point.torch = pytest.importorskip("torch")from torch.optim.lr_scheduler import LambdaLRfrom unsloth.trainer import _install_legacy_scheduler_resumediff --git a/tests/utils/test_varlen_int32_overflow_guard.py b/tests/utils/test_varlen_int32_overflow_guard.pyindex 428ecab03a2..214b56eb6ca 100644--- a/tests/utils/test_varlen_int32_overflow_guard.py+++ b/tests/utils/test_varlen_int32_overflow_guard.py@@ -205,9 +205,8 @@ def test_forward_only_is_never_downgraded(monkeypatch, backend):@pytest.mark.parametrize("backend", [ad.XFORMERS, ad.FLASH_VARLEN])def test_gradient_checkpointing_picks_the_same_backend_in_both_passes(monkeypatch, backend):- """torch.utils.checkpoint runs its first forward under no_grad and recomputes with grad on.- If the guard keyed only on the tensors, the two passes would take different backends and- the backward would see activations the reported loss never came from."""+ """Checkpoint's no_grad forward and grad-enabled recompute must pick the same backend; keying+ the guard on tensors alone lets the passes differ, so backward sees unreported activations."""def go(grad_enabled):with torch.set_grad_enabled(grad_enabled):diff --git a/tests/version_compat/test_peft_conversion_symbol_backfill.py b/tests/version_compat/test_peft_conversion_symbol_backfill.pyindex f2fba070013..681a40bd1ff 100644--- a/tests/version_compat/test_peft_conversion_symbol_backfill.py+++ b/tests/version_compat/test_peft_conversion_symbol_backfill.py@@ -984,9 +984,8 @@ def test_the_not_fused_list_matches_upstream():def _fetch_conversion_mapping_source():- """The upstream map, over the network, so the canary runs in the job that- installs only pytest -- where `transformers` is absent and every comparison- against the installed copy silently skips."""+ """Fetches the upstream conversion map over the network so the canary also runs in the+ pytest-only job, where transformers is absent and local comparisons skip."""import osimport urllib.errorimport urllib.request@@ -1007,9 +1006,8 @@ def _fetch_conversion_mapping_source():def test_the_fused_snapshot_matches_upstream():- """The other half of the same canary: a fused MoE alias added upstream and- missing here falls through the stand-in silently if its name says nothing- about MoE. Runs off the network, so the dependency-free job exercises it."""+ """A fused MoE alias added upstream but missing from the snapshot falls through the stand-in+ silently if its name lacks MoE; the dependency-free job runs this canary."""src = _fetch_conversion_mapping_source()if src is None:pytest.skip("upstream conversion map unavailable")@@ -1077,9 +1075,8 @@ def test_an_unrelated_absolute_import_is_not_queued():def test_an_import_in_a_module_level_match_case_is_collected():- """The selected case runs at import time, so an import inside one can raise- the startup error this guard exists to catch. `ast.Match` keeps its- statements under `cases`, which the walk did not descend into."""+ """A module-level match case runs at import time, so an import inside one can raise the startup+ error this guard catches; ast.Match keeps its statements under cases."""src = ("import sys\n""match sys.version_info[0]:\n"@@ -1118,18 +1115,16 @@ def test_the_two_base_patterns_are_in_the_snapshot():@pytest.mark.parametrize("model_type", sorted(F._PEFT_MOE_NAMED_NOT_CONVERTED))def test_a_moe_named_type_outside_the_map_is_not_refused(model_type):- """peft answers `None` for a type the map does not hold and skips the target- rewrite, so refusing breaks an ordinary adapter load. `qwen3_vl_moe` and- `lfm2_moe` are both supported models the substring hint was catching."""+ """peft answers None for a type the map does not hold and skips the target rewrite, so refusing+ breaks an ordinary load; the substring hint wrongly refused qwen3_vl_moe and lfm2_moe."""stand_in = F._UnavailableConversionPatternMap()assert stand_in.get(model_type) is Noneassert stand_in.get(model_type, "fallback") == "fallback"def test_the_unconverted_list_is_still_outside_the_upstream_map():- """The canary for the other half. A name that gains a conversion pattern- upstream becomes fused, and answering `None` for it is the silent- mis-conversion the refusal exists to prevent."""+ """A name in the unconverted list that gains a conversion pattern upstream becomes fused, and+ answering None for it silently mis-converts; this canary catches that."""src = _fetch_conversion_mapping_source()if src is None:pytest.skip("upstream conversion map unavailable")diff --git a/tests/version_compat/test_trl_fake_train_cpu.py b/tests/version_compat/test_trl_fake_train_cpu.pyindex 7fce7af7478..ffc6eb532c2 100644--- a/tests/version_compat/test_trl_fake_train_cpu.py+++ b/tests/version_compat/test_trl_fake_train_cpu.py@@ -274,9 +274,8 @@ def test_dpo_trains_on_cpu(tmp_path):from trl.trainer import dpo_trainer- # TRL 1.15 scores DPO through its fused LM head, a Triton kernel with no CPU path, so- # plain TRL cannot train DPO on a CPU either. Only skip when that is what the installed- # TRL does, so an older TRL still has to train here.+ # TRL 1.15 scores DPO through a fused LM head (a Triton kernel with no CPU path); skip only when+ # the installed TRL does this, so older TRL still trains here.if "fused_lm_head=True" in inspect.getsource(dpo_trainer):pytest.skip("this TRL computes DPO log-probs with a Triton GPU kernel only")model, tok = _load_plain()diff --git a/tests/version_compat/test_trl_padding_free_max_length.py b/tests/version_compat/test_trl_padding_free_max_length.pyindex f808eb9e4be..d2d43d1c82f 100644--- a/tests/version_compat/test_trl_padding_free_max_length.py+++ b/tests/version_compat/test_trl_padding_free_max_length.py@@ -771,9 +771,8 @@ def test_a_pretokenized_stream_is_truncated_without_num_proc(tmp_path, trl_has_gdef test_an_unrewritable_stream_is_refused_not_assumed(tmp_path, trl_has_guard):- """A stream the truncation cannot rewrite is unverifiable, not verified: the- prefix scan called the first 1024 fitting rows proof, and nothing downstream- truncates a pre-tokenized row."""+ """A stream the truncation cannot rewrite is unverifiable, not verified: a prefix scan of the+ first 1024 fitting rows is not proof, and nothing downstream truncates a pre-tokenized row."""if not trl_has_guard:pytest.skip("no guard in this TRL: the block under test is not generated at all")tok = _load_plain()[1]@@ -2001,9 +2000,8 @@ def test_probing_a_rewindable_split_hands_it_straight_back():def test_predict_keeps_every_row_it_was_given():- """`predict` returns one prediction per row IN ORDER. Dropping the- unsupervised ones silently shortens and shifts the output relative to the- dataset the caller zipped it back onto."""+ """predict returns one prediction per row, in order; dropping the unsupervised rows silently+ shortens and shifts the output against the dataset the caller zipped it back onto."""from datasets import Datasetids = list(range(8))@@ -2175,9 +2173,8 @@ def test_a_rewindable_stream_is_not_chained():def test_the_completion_only_probe_does_not_eat_a_training_row():- """That probe read the first TRAINING example and chained nothing back, so- a one-shot stream trained from row 2. Columns first, and a row only when- reading one is free."""+ """A probe that read the first training example and chained nothing back made a one-shot stream+ train from row 2; probe the columns first, and a row only when that is free."""block = _padding_free_codegen_block()assert "_unsloth_probe is train_dataset or _unsloth_probe is iter(train_dataset)" in blockassert "next(iter(train_dataset), None)" not in block, "the destructive probe is back"@@ -2330,9 +2327,8 @@ def test_a_transformed_tokenized_split_keeps_its_cap(tmp_path, trl_has_guard):def test_a_transformed_split_within_the_cap_keeps_max_length_and_trains(tmp_path, trl_has_guard):- """The other half: the same shape with nothing overlength must not be cleared- either, and must not raise. This is what shows the raise above is about the- rows and not about the transform."""+ """The other half: the same transformed shape with nothing overlength must keep max_length and+ must not raise, so the earlier raise is about the rows, not the transform."""if not trl_has_guard:pytest.skip("no guard in this TRL: the block under test is not generated at all")trainer = _build(@@ -2619,9 +2615,8 @@ def test_a_one_shot_stream_slices_every_aligned_column():def test_an_unfiltered_map_style_split_is_not_scanned_up_front():- """With no supervision columns every row survives, so building an identity- index read and transformed the whole split before the dataloader could- start -- a second on-access tokenization pass for no information."""+ """With no supervision columns every row survives, so an identity index would read and transform+ the whole split before the dataloader starts: a second tokenization pass for nothing."""from unsloth.models.rl import _CappedRowsreads = []@@ -2664,9 +2659,8 @@ def test_a_filtered_split_still_drops_its_unsupervised_rows():def test_switching_truncation_mode_re_caps_the_same_split():- """The memo keyed on identity, cap and filtering mode but not on the SLICE,- so evaluating with keep_start and then keep_end handed back the cached- prefixes for both."""+ """The memo must key on the slice too: keyed only on identity, cap and filtering mode,+ keep_start then keep_end would get the cached prefixes for both."""_, tok = _load_plain()late = _tokenized_dataset(tok)Stub, seen = _stub_trainer_class()@@ -2888,9 +2882,8 @@ def test_a_later_row_that_cannot_take_the_slice_does_not_raise():def test_a_misaligned_later_row_keeps_its_own_length():- """Same probe, different drift: a column that is aligned in row 0 and a- different width in row 1. Cutting it there would report a mask for tokens- the row never had."""+ """Same probe, different drift: a column aligned in row 0 but a different width in row 1 keeps+ its own length, since cutting it reports a mask for tokens the row never had."""from unsloth.models.rl import _CappedRows# Longer than the tokens, so cutting it is visible.@@ -2902,9 +2895,8 @@ def test_a_misaligned_later_row_keeps_its_own_length():def test_input_ids_comes_first_so_every_column_is_measured():- """`_column_names` returns a SET, and the `map` path reads the width off- `input_ids` as it walks this list. A run that ordered `labels` first sliced- the labels having compared them to nothing at all."""+ """_column_names returns a set, and the map path reads the width off input_ids as it walks the+ list; labels ordered first were sliced with nothing to compare them to."""from unsloth.models.rl import _sliceable_per_tokennames = ("labels", "attention_mask", "input_ids")@@ -2947,9 +2939,8 @@ def test_a_mark_is_not_trusted_after_the_split_is_mutated():def test_an_unfingerprintable_split_is_never_trusted_by_its_mark():- """The memo excludes these on purpose because their rows can change under a- stable identity. The mark has to reach the same conclusion, or it becomes- the way around the memo."""+ """The memo excludes unfingerprintable splits because their rows can change under a stable+ identity; the mark must reach the same conclusion or it becomes a way around the memo."""from unsloth.models import rlclass Plain:@@ -2978,9 +2969,8 @@ def test_our_own_wrapper_is_still_handed_straight_back():def test_the_late_evaluation_memo_is_bounded():- """Every entry pins the original split AND the capped copy for the trainer's- lifetime. A caller building a fresh validation subset each epoch grew this- dictionary without bound until the host ran out of memory."""+ """Each memo entry pins the original split and its capped copy for the trainer's lifetime, so a+ fresh validation subset each epoch grew it until memory ran out; the memo is bounded."""from unsloth.models import rl_, tok = _load_plain()diff --git a/unsloth/_compressed_quantize.py b/unsloth/_compressed_quantize.pyindex 0141a9b34e2..938a4a9ca6e 100644--- a/unsloth/_compressed_quantize.py+++ b/unsloth/_compressed_quantize.py@@ -51,16 +51,10 @@ def _has_mtp(config):def compressed_ignore_patterns(config):- """Modules the compressed recipe refuses to quantize, as llm-compressor `ignore` entries.-- Module level, and reachable without importing anything outside the stdlib, so `save.py`- can size the quantized sibling from the same list the recipe is built from rather than a- second copy of it that drifts. This module is still only ever *executed* by file path.-- Matching is compressed-tensors' `is_match`: a `re:` prefix is `re.match(pattern, name)`- against the module's fully qualified name, anything else is an exact name (or parent- class name) match.- """+ """Modules the compressed recipe refuses to quantize (llm-compressor ignore entries);+ stdlib-only so save.py sizes from the same list, and only ever executed by file path. A re:+ prefix is re.match on the qualified name, else exact name or parent class name+ (compressed-tensors is_match)."""ignore = ["lm_head"]# Skip what RedHatAI/NVIDIA skip for Qwen3.5 / Qwen3-Next: shapes not divisible by group_size.ignore += ["re:.*\\.linear_attn\\..*", "re:.*\\.visual\\..*", "re:.*mtp.*"]diff --git a/unsloth/_gc_passes.py b/unsloth/_gc_passes.pyindex bee14eed883..899a6c22bf7 100644--- a/unsloth/_gc_passes.py+++ b/unsloth/_gc_passes.py@@ -13,12 +13,10 @@ def collect_garbage(before = None,after = None,):- """Up to `passes` full gc.collect() passes, `before` / `after` run around each.-- Stops after a pass that ran and found nothing. Keeps going while gc.callbacks are registered (they- may drop references) or when the gen 2 stats do not show one more empty collection (CPython returns 0- without collecting while another thread is collecting).- """+ """Runs up to passes full gc.collect() passes with before and after around each; stops after a+ pass that finds nothing unless gc.callbacks are registered (they may drop references) or gen+ 2 stats do not show one more empty collection (CPython returns 0 while another thread+ collects)."""for _ in range(passes):if before is not None:before()diff --git a/unsloth/chat_templates.py b/unsloth/chat_templates.pyindex dd899e1a655..877c6462bea 100644--- a/unsloth/chat_templates.py+++ b/unsloth/chat_templates.py@@ -2678,12 +2678,9 @@ def get_chat_template(_mlx_tokenizer_wrapper = tokenizertokenizer = _inner_tokenizer- # Multimodal checkpoints (gemma-4-E2B, Llava, Qwen-VL, ...) load as a processor,- # which carries the text tokenizer in `.tokenizer` -- the same unwrap the save and- # loader paths do. Everything below needs the tokenizer itself: the processor never- # has the Rust backend the vocab edits use, nor, on MLX, a padding_side of its own.- # Match the processor type rather than the attribute: MistralCommonBackend is itself- # a tokenizer but also exposes its non-HF backend as `.tokenizer`.+ # Multimodal processors carry the text tokenizer in .tokenizer, but everything below needs it+ # directly (no Rust backend, and on MLX no padding_side); match the ProcessorMixin type, since+ # MistralCommonBackend is itself a tokenizer that also exposes .tokenizer._processor = Noneif isinstance(tokenizer, ProcessorMixin):_processor = tokenizer@@ -2743,10 +2740,9 @@ def get_chat_template(assert(type(stop_word) is str)- # gemma_chatml / gemma2_chatml build <|im_end|> by renaming <eos> whether or not the caller opts- # out, while the rebuilt tokenizer carries eos_token = stop_word only when the mapping is on, so- # honouring the opt-out lets the class default re-add <eos> past the end of the embeddings. Key on- # the mapping, or a Gemma checkpoint whose eos_token is <end_of_turn> slips through.+ # gemma_chatml and gemma2_chatml build <|im_end|> by renaming <eos> even when opted out;+ # honouring the opt-out lets the class default re-add <eos> past the embeddings. Key on the+ # mapping, or a Gemma checkpoint whose eos_token is <end_of_turn> slips through.if not map_eos_token and yes_map_eos_token and token_mapping is not None:logger.warning_once(f"Unsloth: {type_chat_template} builds {stop_word} by renaming existing "\@@ -2916,10 +2912,9 @@ def get_chat_template(if old_pad_token != new_pad_token: tokenizer.pad_token = old_pad_token- # Hand the processor back, not the tokenizer it was carrying: it renders chat- # templates off its own attribute, and the vocab edits above may have rebuilt the- # tokenizer and remapped eos. The loader mirrors these onto the processor- # (models/vision.py), so refresh them here or that copy goes stale.+ # Hand back the processor, not the tokenizer it carried: it renders chat templates off its own+ # attribute, and vocab edits may have rebuilt the tokenizer and remapped eos; models/vision.py+ # mirrors these onto the processor, so refresh them here or that copy goes stale.if _processor is not None:# GGUF export unwraps the processor before it builds the Ollama Modelfile.tokenizer._ollama_modelfile = ollama_modelfilediff --git a/unsloth/dataprep/raw_text.py b/unsloth/dataprep/raw_text.pyindex 4aee863c6e1..82fd8e5f179 100644--- a/unsloth/dataprep/raw_text.py+++ b/unsloth/dataprep/raw_text.py@@ -130,13 +130,8 @@ class RawTextDataLoader:stride,return_tokenized = True,):- """- Intelligent chunking that:- 1. Respects sentence/paragraph boundaries- 2. Handles various text formats (.txt, .md, .json, etc.)- 3. Maintains context with stride overlap- 4. Returns tokenized chunks directly (more efficient) or text chunks- """+ """Chunks text at sentence or paragraph boundaries with stride overlap, returning tokenized+ chunks (more efficient) or text chunks; handles .txt, .md, .json and other text formats."""if chunk_size <= 0:raise ValueError(f"chunk_size must be positive, got {chunk_size}")if stride < 0:@@ -402,13 +397,8 @@ class TextPreprocessor:dataset,tokenizer = None,):- """- Check for:- - Minimum/maximum sequence lengths- - Character encoding issues- - Repeated content- - Empty chunks- """+ """Checks a dataset for min and max sequence lengths, character encoding issues, repeated+ content and empty chunks."""stats = {"total_samples": len(dataset),"empty_samples": 0,diff --git a/unsloth/dataprep/synthetic.py b/unsloth/dataprep/synthetic.pyindex 11c71b0297c..868b5b10565 100644--- a/unsloth/dataprep/synthetic.py+++ b/unsloth/dataprep/synthetic.py@@ -173,12 +173,8 @@ class PipeCapture:def _deadline(timeout):- """Monotonic instant `timeout` seconds from now, `None` for never.-- `timeout` arrives here untyped from the caller, and the `Event.wait` this- replaced read `None` as an unbounded wait, which is what a first load of a- large model over a slow link needs.- """+ """Monotonic instant timeout seconds from now, or None for never; None must stay unbounded as+ Event.wait treated it, since a first large-model load over a slow link needs that."""return None if timeout is None else time.monotonic() + timeout@@ -395,12 +391,8 @@ class SyntheticDataKit:timeout,poll_interval = 1.0,):- """Block until the server is ready, or raise saying why it is not.-- The readiness event alone cannot notice the child dying, so a server- that failed to import in twenty seconds still burned the whole- `timeout`. Poll readiness, exit status and the closed pipe together.- """+ """Blocks until the server is ready or raises why not; readiness alone cannot see the child+ die and would burn the whole timeout, so also poll exit status and the closed pipe."""deadline = _deadline(timeout)while True:# Cap each wait at the time left so readiness after the deadline is not reported as success.diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.pyindex 367e972cea5..723ab0515ec 100644--- a/unsloth/import_fixes.py+++ b/unsloth/import_fixes.py@@ -11978,10 +11978,9 @@ def disable_torchao_if_torch_too_old():return True-# vLLM inspects architectures in a separate process that imports torchao itself, never sees a-# parent monkey-patch, and fails the same way. sitecustomize is the one hook reaching a process-# we do not launch: site imports it at startup off the inherited PYTHONPATH. A .pth would need-# a real site directory, which a library has no business writing into.+# vLLM's separate process imports torchao itself, never sees a parent monkey-patch and fails the+# same way; sitecustomize is the one hook reaching a process we do not launch (site imports it off+# the inherited PYTHONPATH); a .pth needs a real site directory a library should not write into._SUBPROCESS_FIX_DIRNAME = "unsloth_subprocess_import_fix"diff --git a/unsloth/kernels/bnb_override.py b/unsloth/kernels/bnb_override.pyindex 8b9d5deb646..48df31d8c33 100644--- a/unsloth/kernels/bnb_override.py+++ b/unsloth/kernels/bnb_override.py@@ -178,10 +178,9 @@ def _eligible(self, x, weight, quant_state):def _bnb_fused_takes(self, x, quant_state):- """bitsandbytes >= 0.50 would run its fused 4-bit GEMM here (2..1536 rows, per its own per-GPU- heuristic): keep that. Where it dequantizes + F.linear instead, the override does the same with- the faster Triton dequantize, bit for bit. Eager answers are cached per layer and element count- (_nf4_forward checks that cache first): this runs on every decode call."""+ """Keeps bitsandbytes >= 0.50 fused 4-bit GEMM where it runs (2..1536 rows, per its per-GPU+ heuristic); otherwise Triton dequantize + F.linear, bit for bit; eager answers are cached per+ layer and element count since this runs every decode call."""K = x.shape[-1]n = x.numel()if n <= K or n > _BNB_FUSED_MAX_ROWS * K:diff --git a/unsloth/kernels/fast_lora.py b/unsloth/kernels/fast_lora.pyindex 664d1e116c7..4e66f235541 100644--- a/unsloth/kernels/fast_lora.py+++ b/unsloth/kernels/fast_lora.py@@ -173,10 +173,9 @@ def _active_lora_requires_grad(projs):def _autocast_dtype_mismatch(X):- # Under autocast the fused matmuls return the autocast dtype but the in-place LoRA accumulation runs- # in X's dtype (in-place ops are not autocast), so a different autocast dtype cannot be fused.- # Mode flags only, no tensor work. Eager first asks whether any autocast is on (a private query, so not- # under Dynamo, which traces the public calls below as constants).+ # Under autocast fused matmuls return the autocast dtype but in-place LoRA accumulation keeps+ # X's dtype, so a mismatched autocast dtype cannot be fused; the check reads mode flags only,+ # eager-only since Dynamo would trace the public calls as constants.if (_is_any_autocast_enabled is not Noneand not _is_compiling()diff --git a/unsloth/kernels/fp8.py b/unsloth/kernels/fp8.pyindex e5ce89352c6..6efc964e6b9 100644--- a/unsloth/kernels/fp8.py+++ b/unsloth/kernels/fp8.py@@ -269,11 +269,9 @@ def _has_fbgemm_rowwise():def _scale_mul(x, s, dtype):- # fp16: an fp16 scale goes subnormal below 6.1e-5 and overflows above 65504, zeroing or inf-ing- # the weight, so multiply by the fp32 scale and round once. fp8 values are exact in fp16, and an- # fp16 out= makes TensorIterator compute in fp32 per element without fp32 temporaries. Dynamo- # refuses a strided out=; under compile Inductor fuses the fp32 expression instead (same bits).- # Other dtypes keep their dtype-native expression.+ # fp16 scales go subnormal below 6.1e-5 and overflow above 65504, so multiply by the fp32 scale+ # and round once; an fp16 out= computes fp32 per element (fp8 is exact in fp16), and Dynamo+ # refuses a strided out= so Inductor fuses it under compile.if _scale_dequant_one_pass_ok(x, s, dtype):return _scale_dequant_one_pass(x, s, dtype)if dtype != torch.float16:@@ -1144,16 +1142,9 @@ def _hip_bytes_dequant(device, out_dtype):def _fp8_kernel_unsupported(tensor, kernel_dtype = None):- """True when triton here cannot compile this fp8 dtype, so kernels taking it must be avoided.-- triton adds fp8e4nv only from sm89 on, so compare the full (major, minor): sm89 (4090,- L40S, L4) does support it. ROCm's capability is gfx-derived, so it is gated on the gfx arch- and triton version instead (_rocm_fp8e4nv_kernel_supported).-- kernel_dtype is the fp8 dtype the kernel really handles. It defaults to the tensor's own,- which is right for a dequant, but a forward must pass e4m3fn: act_quant emits e4m3fn- whatever the weight dtype is, so e5m2 weights hit the same unsupported kernel.- """+ """True when triton here cannot compile this fp8 dtype (fp8e4nv from sm89 on, compared as major+ and minor; ROCm uses gfx arch and triton version); forwards pass kernel_dtype e4m3fn since+ act_quant always emits it, even for e5m2 weights."""return (tensor.is_cudaand (tensor.dtype if kernel_dtype is None else kernel_dtype) == torch.float8_e4m3fn@@ -1834,9 +1825,8 @@ def _e4m3fn_bytes_dequant(def _blockwise_weight_dequant_any_shape(weight, weight_scale, block_size, out_dtype):- """Blockwise fp8 weight dequant for any shape: triton when the weight tiles- evenly into block_size and this GPU can compile its fp8 dtype, else a- torch-native per-block scale expansion."""+ """Blockwise fp8 weight dequant for any shape: triton when weight tiles evenly into block_size+ and this GPU can compile the fp8 dtype, else a torch scale expansion."""m, n = weight.shapeif weight_scale.dtype not in (torch.float32, torch.float16, torch.bfloat16):weight_scale = weight_scale.to(torch.float32) # e.g. float8_e8m0fnu scales break tritondiff --git a/unsloth/kernels/large_head_attention.py b/unsloth/kernels/large_head_attention.pyindex a114dd2cf3b..20540906c47 100644--- a/unsloth/kernels/large_head_attention.py+++ b/unsloth/kernels/large_head_attention.py@@ -535,9 +535,8 @@ def _bwd_impl(do, q, k, v, o, lse, lo, hi, scale):return dq, dk, dv-# Opaque custom ops keep torch.compile from tracing into Triton (no graph break, no-# re-emission with fp fusion). The plain autograd.Function is the fallback for torch-# builds without torch.library.custom_op.+# Opaque custom ops keep torch.compile from tracing into Triton (no graph break, no re-emission with+# fp fusion); the plain autograd.Function is the fallback without torch.library.custom_op._HAS_CUSTOM_OP = (hasattr(torch, "library")and hasattr(torch.library, "custom_op")@@ -637,13 +636,10 @@ def intervals_from_mask(S,_rows = 1024,):- """(lo, hi) int32 [B, S] such that query i attends exactly keys lo[i]..hi[i], or None.-- None unless every row of `mask` (bool, or additive float with 0 = keep) allows one- non-empty contiguous key range and both ends are non-decreasing down the rows. One- host sync; the verdict is cached on the mask so every layer sharing it reuses it.- Inference tensors have no version counter, so they are rescanned on every call.- """+ """Returns (lo, hi) int32 [B, S] (query i attends lo[i]..hi[i]) or None unless each mask row+ (bool, or additive float with 0 = keep) is one non-empty contiguous key range with+ non-decreasing ends; one host sync, cached on the mask, but inference tensors are rescanned+ each call."""if not torch.is_tensor(mask) or mask.dim() != 4 or mask.shape[1] != 1:return Noneif mask.shape[-2] != S or mask.shape[-1] != S or mask.shape[0] not in (1, B):@@ -721,13 +717,9 @@ _enabled.cache_clear = lambda: _ENABLED.__setitem__(0, None)def _row_span(x):- """Largest element offset the kernels compute in int32 for a [B, H, S, D] operand.-- Batch and head offsets are int64 in every kernel; the row and column offsets- (offs_m * stride_m + offs_d) are int32, so they are what must stay below 2**31. A strided- view can have a small numel and still reach far past 2**31 elements along S. An operand- whose last stride is not 1 is copied contiguous before launch, so its numel bounds it.- """+ """Largest int32 element offset for a [B, H, S, D] operand (row and column offsets must stay+ below 2^31; batch and head offsets are int64); a strided view can reach past it, but a+ non-unit last stride is copied contiguous first, so numel bounds it."""if x.stride(-1) != 1:return x.numel()return (x.shape[-2] - 1) * x.stride(-2) + (x.shape[-1] - 1)@@ -971,9 +963,8 @@ _PATCHED = [False]def patch_large_head_attention(model = None):- """Route transformers' `sdpa` attention through the large head kernel when a call- qualifies; everything else reaches the previous `sdpa` function unchanged. With a- model, only installs if one of its modules has head_dim > 256."""+ """Routes transformers' sdpa attention through the large head kernel when a call qualifies, else+ the previous sdpa; with a model, installs only if a module has head_dim > 256."""if not _enabled() or not torch.cuda.is_available() or torch.version.hip is not None:return Falseif model is not None:diff --git a/unsloth/kernels/moe/autotune_cache.py b/unsloth/kernels/moe/autotune_cache.pyindex 145fb5f82f9..23ca692999a 100644--- a/unsloth/kernels/moe/autotune_cache.py+++ b/unsloth/kernels/moe/autotune_cache.py@@ -11,9 +11,7 @@# You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <https://www.gnu.org/licenses/>.-"""-Auto-tuning cache system for MoE kernels to ensure tuning runs only once at training start.-"""+"""Auto-tuning cache system for MoE kernels to ensure tuning runs only once at training start."""import hashlibimport json@@ -556,10 +554,9 @@ def _estimate_smem(capability: Tuple[int, int],pipelined_dW: bool = False,) -> int:- """Shared memory (B) per launch; matches compiled metadata.shared (Triton 3.6-3.8, sm_75..120) or exceeds it by <= 1 KiB.-- pipelined_dW: the per-expert dW kernel with unpermuted operands. Its one M loop is software pipelined (the- legacy kernel's nested loop and a gathered load never are), so 16-bit shared memory grows with num_stages."""+ """Shared memory in bytes per launch, matching compiled metadata.shared (Triton 3.6-3.8,+ sm_75..120) or exceeding it by <= 1 KiB; for pipelined_dW (per-expert dW, unpermuted+ operands) 16-bit SMEM grows with num_stages."""M, N, K = config.BLOCK_SIZE_M, config.BLOCK_SIZE_N, config.BLOCK_SIZE_Kstages = max(int(config.num_stages), 1)if kind == "fwd":diff --git a/unsloth/kernels/moe/grouped_gemm/interface.py b/unsloth/kernels/moe/grouped_gemm/interface.pyindex 2e16d20f0ab..dd7cd5bc34a 100644--- a/unsloth/kernels/moe/grouped_gemm/interface.py+++ b/unsloth/kernels/moe/grouped_gemm/interface.py@@ -172,10 +172,9 @@ def _fit_tiles_to_operand_device(def _autotuner_for(kernel, device):- """Triton's autotune key omits the device, so on several GPUs each card runs its own copy. Copies on- the same GPU model share one results cache, so identical cards reuse each other's tuning; a run's- scratch state (nargs) stays per card, since backward runs one autograd thread per device. No lock:- a cached launch never waits on another card's tuning."""+ """Triton's autotune key omits the device, so each card gets a copy; same-model copies share one+ results cache; nargs stays per card (one autograd thread per device); no lock, since a cached+ launch never waits on another card's tuning."""if torch.cuda.device_count() <= 1 or not hasattr(kernel, "cache"):return kernelkey = (id(kernel), _device_index(device))@@ -1144,11 +1143,10 @@ def _dW_accumulate_enabled():def _dW_accumulate_target(ctx, X, autotune):- """The leaf parameter whose existing .grad the dW kernel may add into, else None.-- Any case where AccumulateGrad would do more than `param.grad += dW` falls back to returning dW,- including Node hooks that can rewrite dW: prehooks on W's AccumulateGrad and post hooks on this- GroupedGemmBackward. Post hooks on AccumulateGrad only observe (they see None for this dW)."""+ """Leaf param whose .grad the dW kernel may add into, else None; any case where AccumulateGrad+ would do more than param.grad += dW (e.g. prehooks on W's AccumulateGrad or post hooks on+ this GroupedGemmBackward) falls back to returning dW; AccumulateGrad post hooks only observe,+ seeing None."""if torch.compiler.is_compiling() or _is_tracing(X) or torch.is_grad_enabled():return None# Anomaly mode checks the returned gradients for NaN; an in-place add returns None for W.@@ -1200,10 +1198,9 @@ def _node_hook_probe(*args):def _node_has_python_hooks(register):- """True if the Node behind `register` (register_hook / register_prehook) already holds a Python hook.-- Nodes cannot list their hooks, but every Python hook of one kind shares a single dict, and the- handle of a new registration points at it: register a no-op, count, remove it again."""+ """True if the Node behind register (register_hook or register_prehook) already holds a Python+ hook; Nodes cannot list hooks, so a no-op is registered and its handle's shared dict counted,+ then removed."""try:handle = register(_node_hook_probe)except Exception:diff --git a/unsloth/kernels/moe/tests/moe_utils.py b/unsloth/kernels/moe/tests/moe_utils.pyindex bbc6eca606b..95088a0bb07 100644--- a/unsloth/kernels/moe/tests/moe_utils.py+++ b/unsloth/kernels/moe/tests/moe_utils.py@@ -321,12 +321,9 @@ def run_backward(class Qwen3MoeFusedGroupedGEMMBlock(Qwen3MoeGroupedGEMMBlock):- """Reference MoE block using triton grouped gemm.-- Like Qwen3MoeGroupedGEMMBlock but with triton (not torch-native) grouped gemm.- NOT for production: it saves intermediate results and runs extra checks for- debugging. See grouped_gemm/reference/moe_block.py for a cleaner version.- """+ """Reference MoE block with triton grouped GEMM (the parent Qwen3MoeGroupedGEMMBlock is+ torch-native); not for production since it saves intermediates and runs extra debug checks;+ see grouped_gemm/reference/moe_block.py for a cleaner version."""def __init__(self,diff --git a/unsloth/kernels/nf4.py b/unsloth/kernels/nf4.pyindex ce8e87a8f3a..5450739d184 100644--- a/unsloth/kernels/nf4.py+++ b/unsloth/kernels/nf4.py@@ -386,11 +386,9 @@ def dequantize_nf4(dtype: torch.dtype,out: Optional[torch.Tensor] = None,) -> torch.Tensor:- """Dequantize a bitsandbytes NF4 weight into ``out`` (allocated when None).-- ``code`` is the quant state's fp32 [16] NF4 codebook. ``code2``, ``absmax2`` and the device- tensor ``offset`` are None when the absmax is not double quantized (it is then fp32).- """+ """Dequantize a bitsandbytes NF4 weight into out (allocated when None); code is the fp32 [16]+ NF4 codebook, and code2, absmax2 and offset are None when the absmax is not double quantized+ (it is then fp32)."""if dtype not in (torch.float16, torch.bfloat16, torch.float32):raise TypeError(f"Unsloth: dequantize_nf4 does not support dtype {dtype}")if not _is_pow2(blocksize) or blocksize < 2 or (code2 is not None and not _is_pow2(blocksize2)):diff --git a/unsloth/kernels/nf4_gemv.py b/unsloth/kernels/nf4_gemv.pyindex f2d9d8cf269..0d1c0d96d70 100644--- a/unsloth/kernels/nf4_gemv.py+++ b/unsloth/kernels/nf4_gemv.py@@ -1,11 +1,9 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.-# Batch-1 NF4 GEMV for decoding, out[1, 1, N] = X[1, 1, K] @ dequant(W).T, in one Triton launch-# (nested absmax decode, NF4 lookup and dot product fused) on torch's current stream. Registered-# as unsloth::gemv_nf4 so torch.compile traces it and CUDA graphs capture it. Each quantization-# block is summed before scaling, so it matches bitsandbytes to fp32 accumulation noise, not bitwise.-# Every weight row must start a new quantization block (K % blocksize == 0); callers check.+# Batch-1 NF4 GEMV for decoding, out[1, 1, N] = X @ dequant(W).T in one launch, registered as+# unsloth::gemv_nf4 for torch.compile and CUDA graphs; each block is summed before scaling, matching+# bitsandbytes to fp32 noise, not bitwise; every row must start a quant block (K % blocksize == 0).import functoolsimport os@@ -364,14 +362,10 @@ def gemv_nf4(dtype,out = None,):- """X @ dequant(W).T for a single token; returns (1, 1, shape[0]) in X's dtype.-- ``code2/absmax2/offset`` are None for a quant state without double quantization, and- ``offset`` is bitsandbytes' 0-dim device tensor (read in the kernel, so no host sync).- Eager calls launch the kernel directly: the torch.library dispatcher costs about 20us- per call, as much as the kernel itself at decode sizes. Compiled code goes through- the registered op so Dynamo sees it.- """+ """X @ dequant(W).T for one token, returning (1, 1, shape[0]) in X's dtype; code2, absmax2 and+ offset are None without double quant (offset is a 0-dim device tensor, so no host sync);+ eager calls skip the torch.library dispatcher (costly at decode sizes), compiled code uses+ the registered op."""out_features, in_features = int(shape[0]), int(shape[1])if not X.is_contiguous():X = X.contiguous()diff --git a/unsloth/kernels/rms_layernorm.py b/unsloth/kernels/rms_layernorm.pyindex b52af974ce4..823af45423a 100644--- a/unsloth/kernels/rms_layernorm.py+++ b/unsloth/kernels/rms_layernorm.py@@ -142,12 +142,9 @@ def _rms_layernorm_backward(TRAIN_W: tl.constexpr, # weight grad partialsFROM_Y: tl.constexpr, # recompute normed from saved Y):- """- Fast RMS Layernorm kernel for the backward pass- Inspiration from a Triton tutorial:- https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html- TRAIN_W: per-program fp32 dW partials (fla-org/flash-linear-attention layer_norm_bwd_kernel_row).- """+ """Fast RMS layernorm backward kernel, inspired by the Triton layer-norm tutorial; TRAIN_W+ writes per-program fp32 dW partials, as in fla-org/flash-linear-attention+ layer_norm_bwd_kernel_row."""pid = tl.program_id(0)if LONG_INDEXING:pid = pid.to(tl.int64)diff --git a/unsloth/kernels/rope_embedding.py b/unsloth/kernels/rope_embedding.pyindex 0994aae3856..702ac37e100 100644--- a/unsloth/kernels/rope_embedding.py+++ b/unsloth/kernels/rope_embedding.py@@ -135,12 +135,9 @@ def _rope_qk_program(BLOCK_SIZE: tl.constexpr, # hd // 2 next pow2EVICT_INDICES: tl.constexpr, # evict-first hint on position ids):- """- RoPE is Q * cos + rotate_half(Q) * sin; the backward is the same with -sin.- One program = one (batch, seq) row x a group of HEADS_Q query heads or HEADS_K key heads,- BLOCK_SIZE lanes over half of head_dim, read from any strides and written out of place- (or in place when Q_out is Q).- """+ """RoPE is Q x cos + rotate_half(Q) x sin, with minus sin in the backward; one program handles a+ (batch, seq) row and a group of HEADS_Q or HEADS_K heads over half of head_dim, at any+ strides, out of place or in place when Q_out is Q."""row_position = tl.program_id(0)group = tl.program_id(1)col_offsets = tl.arange(0, BLOCK_SIZE)diff --git a/unsloth/kernels/utils.py b/unsloth/kernels/utils.pyindex e9e66f1c249..708d9d928b5 100644--- a/unsloth/kernels/utils.py+++ b/unsloth/kernels/utils.py@@ -52,9 +52,8 @@ else:torch_amp_custom_fwd = torch.amp.custom_fwd(device_type = "cuda")torch_amp_custom_bwd = torch.amp.custom_bwd(device_type = "cuda")-# DEVICE_COUNT == 0 = no visible accelerator (e.g. CPU-only CI runner). The consumer functions below only index-# these arrays during real GPU work, so empty containers are safe -- they just need to be defined so the module-# imports cleanly.+# DEVICE_COUNT == 0 means no visible accelerator (e.g. a CPU-only CI runner); consumers only index+# these arrays during GPU work, so empty containers only need to exist for the module to import.if DEVICE_TYPE == "xpu":torch_amp_custom_fwd = torch.amp.custom_fwd(device_type = "xpu")torch_amp_custom_bwd = torch.amp.custom_bwd(device_type = "xpu")@@ -178,10 +177,9 @@ HAS_CUDA_STREAM = Falsetry:import bitsandbytes as bnb- # If an earlier `import bitsandbytes` died inside __init__, CPython evicts only the parent from- # sys.modules and keeps its submodules, so this retry re-executes __init__ without rebinding- # bnb.functional. `import x.y as z` reads sys.modules directly and survives that, plain attribute- # access does not.+ # If an earlier import bitsandbytes died in __init__, CPython evicts only the parent from+ # sys.modules, so this retry re-runs __init__ without rebinding bnb.functional; import x.y as z+ # survives that, plain attribute access does not.import bitsandbytes.functional as bnb_functionalexcept Exception:# device_type.py already degrades to 16bit/full finetuning when bnb is missing (gfx906, whose@@ -497,10 +495,9 @@ def _is_packed_state(quant_state):def get_lora_parameters(proj):- """Return (weight, weight quant_state, lora A, lora B, lora scale).- With QAT enabled, also fake-quantizes the base layer and lora weights.- Tensor parallel projections (models/tp_native.py) return local shards of their DTensors.- """+ """Return (weight, weight quant_state, lora A, lora B, lora scale); with QAT the base layer and+ lora weights are also fake-quantized; tensor parallel projections (models/tp_native.py)+ return local shards of their DTensors."""localize = proj.__dict__.get("_unsloth_tp_local")if localize is not None:return localize(proj)@@ -738,12 +735,9 @@ _FSDP2_GATHERED = "_unsloth_fsdp2_gathered"def _gathered_plan_hit(plan, W):- """FSDP2 frees an all-gathered weight's storage after use and re-allocates it for the next- all-gather: the same tensor at a new address, so a plan keyed on the address it was built at- never hits again. The planned launch reads the address of the tensor it was built with at- launch time, so it still applies while that tensor and W (the weight, or a view of it such as- the backward's `W.t()`) are at the same address with the 16 byte alignment it was specialized- on. A tensor given a new storage object instead of a resized one has another address: rebuilt."""+ """FSDP2 re-allocates an all-gathered weight at a new address, so a plan is reused only while+ its tensor and W (or a view like W.t()) keep the address and 16 byte alignment it was built+ for; else rebuilt."""address = W.data_ptr()if plan[6].data_ptr() != address or (address & 15) != (plan[0] & 15):return False@@ -1841,8 +1835,7 @@ def fast_linear_forward(out = torch_matmul(X, W, out = out)if out.dtype != X.dtype:- # torch.matmul under a different autocast dtype returns that dtype; the LoRA update, decode- # buffers and every other branch here work in X.dtype.+ # Matmul under another autocast returns that dtype; LoRA and buffers need X.dtype.out = out.to(X.dtype)if lora_A is not None:diff --git a/unsloth/models/_async_grpo_vllm.py b/unsloth/models/_async_grpo_vllm.pyindex 35c70108dbd..4abf609faea 100644--- a/unsloth/models/_async_grpo_vllm.py+++ b/unsloth/models/_async_grpo_vllm.py@@ -294,9 +294,7 @@ class _Handler(BaseHTTPRequestHandler):class _Server(ThreadingHTTPServer):- # socketserver listens with a backlog of 5. Each in-flight completion is its- # own connection, so a burst of them can overflow the accept queue and have- # connections reset before a handler thread picks them up.+ # Backlog of 5 is too small: each in-flight completion is its own connection, reset on overflow.request_queue_size = 1024daemon_threads = Truediff --git a/unsloth/models/_attn_mask_compat.py b/unsloth/models/_attn_mask_compat.pyindex 6a3ac88ccc8..1cf0a7f0fdf 100644--- a/unsloth/models/_attn_mask_compat.py+++ b/unsloth/models/_attn_mask_compat.py@@ -42,12 +42,7 @@ try:except ImportError:def is_tracing(tensor = None) -> bool: # type: ignore[no-redef]- """Local fallback for transformers < 5.0.0.-- True under ``torch.jit.trace``, ``torch.fx.symbolic_trace`` or Dynamo.- The 5.x helper also detects CUDA stream capture, FakeTensor and JAX via- torchax; 4.x itself detects none of those, so behaviour on 4.x matches.- """+ """Fallback for transformers < 5.0: true under jit trace, fx symbolic trace or Dynamo."""if torch.jit.is_tracing():return Trueif tensor is not None and isinstance(tensor, torch.fx.Proxy):@@ -183,9 +178,8 @@ class AttentionMaskConverter:expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)- # 0-dim tensor, not a Python float: a float literal lowers to an fp32 scalar and breaks ExecuTorch- # edge-dialect export on fp16/bf16 masks. Matches upstream from 4.53.0- # (huggingface/transformers#38637).+ # 0-dim tensor, not a float: a float literal lowers to fp32 and breaks ExecuTorch export on+ # fp16/bf16 masks; matches transformers 4.53.0 upstream (issue 38637)inverted_mask = torch.tensor(1.0, dtype = dtype) - expanded_maskreturn inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)diff --git a/unsloth/models/_block_compile.py b/unsloth/models/_block_compile.pyindex b7047a13098..d76d24c195c 100644--- a/unsloth/models/_block_compile.py+++ b/unsloth/models/_block_compile.py@@ -48,10 +48,9 @@ except ValueError:_CUDAGRAPH_MAX_SHAPES = 2-# Process wide: every block class shares one cudagraph tree (one pool per device).-# off: why graphs went off (None = on); release: None, "done" or "kept"; ours: compile ids of the-# tree functions block calls created; built: compile ids the graphs-on block backend compiled;-# managers: CUDA index -> the tree manager block graphs ran on.+# Process-wide cudagraph state (one tree, one pool per device): off = why graphs went off, None =+# on; release = None, done or kept; ours = compile ids of tree functions block calls made; built =+# compile ids the graphs-on backend compiled; managers = CUDA index to tree managerdef _new_cudagraph_state():return {"off": None,@@ -153,9 +152,7 @@ def _block_backend(options):def _graphed_call(compiled, device, *args, **kwargs):- """Call the graphs-on region; note the compile ids of tree functions it created (forward here,- the backward of the same compile later) that the block backend built, so the release can tell- its pool is only ours."""+ """Records the compile ids of tree functions this block built, so release knows the pool is ours."""managers = _CUDAGRAPH_STATE["managers"]manager = managers.get(device)if manager is None:@@ -293,9 +290,7 @@ def _watch_hidden_states(model):def _pool_outputs_stay_valid(layer, hidden_states):- """A grad-mode call outside backward leaves a forward pending, so cudagraph trees start no new- generation (can_start_new_generation) and its outputs need no copy out of the pool. Checkpointed- calls (no-grad forward, recompute in backward, and the trial standing in for it) may start one."""+ """Grad-mode calls outside backward leave a forward pending, so their outputs stay valid in the pool."""return (not _IN_TRIAL[0]and not _HIDDEN_STATES_EXPOSED[0]@@ -347,8 +342,7 @@ def _input_grad_must_leave_pool(hidden_states):_ADDITIVE_BACKWARD = ("AddmmBackward", "BaddbmmBackward")-# Backward nodes that write their input gradient to new storage (a view, add, clone or cat passes-# on the incoming gradient or a narrowed view of it).+# Backward ops that allocate fresh storage for the input gradient (not a view, add or cat)._ALLOCATING_BACKWARD = ("MmBackward","AddmmBackward",@@ -457,10 +451,7 @@ def _flex_block_mask_call(return False-# Auto mode. Graphs remove launch overhead only: they pay off when the host takes longer to launch a-# block than the GPU takes to run it, and cost a recording per batch shape. Forward passes 1-2 run-# without graphs (compile); pass 3 times a few block calls; graphs start at the next pass when every-# call so far had one batch shape and launching was slower than running by _AUTO_RATIO.+# Auto: graphs start when launch time exceeds GPU time by _AUTO_RATIO and all calls had one shape._AUTO_WARMUP_PASSES = 2_AUTO_MEASURE_CALLS = 4_AUTO_SLEEP_CYCLES = 20_000_000 # ~10-15 ms: the block's launches queue behind it@@ -606,11 +597,8 @@ def _auto_decide(auto, device):def _auto_time(call, device):- """(output, host seconds to launch one block call, GPU seconds to run it). The launches queue- behind a GPU sleep, so the event pair after the sleep sees the block's kernels back to back; if- launching outlasts the sleep the GPU time includes gaps, which can only understate the ratio.- Sleep and events run on the block's device (cuda:1 or a device_map shard need not be current).- Host / GPU are None when timing is unavailable."""+ """Sleep and events run on the block device (cuda:1 or a device_map shard need not be current);+ the sleep lets launches queue behind it; host and GPU are None when timing is unavailable"""try:guard = torch.cuda.device(device)except Exception:@@ -682,11 +670,9 @@ except Exception:def _no_ddp_graph_split():- """Inside DDP.forward dynamo hands a block's graph to DDPOptimizer, which splits it at gradient- bucket boundaries. A checkpoint recompute runs from backward, outside DDP.forward, so a block- graph compiled there is not split and saves a different number of tensors than the forward- (CheckpointError under DDP's non-reentrant checkpointing, DeepSeek-OCR). Each block is its own- region already, so its gradients still reach DDP's buckets block by block."""+ """Stop DDPOptimizer splitting block graphs so checkpoint recomputes save the same tensors as+ the forward (CheckpointError under DDP non-reentrant checkpointing); gradients still reach+ DDP buckets block by block"""try:if _DDP is None or _DDP._get_active_ddp_module() is None or not _ddp_optimizer_mode():return contextlib.nullcontext()@@ -761,11 +747,9 @@ def _writes_globals(code):def _rebind_globals(fn):- """dynamo resolves a function's globals through sys.modules[__globals__["__name__"]]; Unsloth's- generated modules exec code into a dict that module does not own (Gemma-4: `module- 'transformers...modeling_gemma4' has no attribute 'Gemma4RMSNorm_forward'`). Rebuild such a- function on a registered module holding a copy of that dict. A copy cannot follow later- writes, so functions that assign globals are left alone."""+ """Dynamo resolves globals via sys.modules; exec-generated code is rebuilt on a registered+ module holding a copy of its dict; functions that assign globals are left alone since a copy+ cannot follow later writes"""g = getattr(fn, "__globals__", None)if g is None or _writes_globals(fn.__code__):return fn@@ -790,10 +774,9 @@ def _rebind_globals(fn):def _inline_compiled(fn):- """A method that is itself torch.compile'd (zoo's patch_function): inside a block, call the- original so dynamo inlines it. Inlining through the compiled wrapper guards on the wrapper's- closure as if it were the original's (torch 2.13 / 2.14, Gemma-4 fp16 MLP: `Unexpected type- CatchErrorsWrapper`). Outside a block the compiled wrapper runs as before."""+ """Inside a block, call the original of a compiled method so dynamo inlines it: inlining the+ wrapper guards on its closure and hits Unexpected type CatchErrorsWrapper on torch 2.13 and+ 2.14 (Gemma-4 fp16 MLP); outside a block the wrapper runs as before"""original = getattr(fn, "_torchdynamo_orig_callable", None)if (not isinstance(original, types.FunctionType)@@ -924,16 +907,12 @@ def _gdn_chunk_adapter(original):def _route_fla_kernel():- """Point modeling code's references to fla's chunk_gated_delta_rule at the adapter. Callers- reach it through module globals, transformers' hub-kernel wrapper (a closure over it) and- Unsloth's compiled-module copies, so callers are found from the function object (gc- referrers), not by name. Closures are left alone: only namespace entries are swapped."""+ """Repoint namespace refs to fla chunk_gated_delta_rule at the adapter; callers are found by gc+ referrers, not by name (they reach it via globals, closures and compiled copies); closures+ are left alone"""import gc- # gc.get_referrers skips the permanent generation, and Trainer.train() freezes the setup-time- # heap (_gc_train_scope) before the first GatedDeltaNet forward gets here: the walk found no- # caller and the op never engaged. Thaw for the walk; refreezing also freezes what train()- # allocated so far, which train()'s exit unfreezes with the rest.+ # gc.get_referrers skips frozen objects, so thaw before the walk or the op never engages.frozen = gc.get_freeze_count() > 0if frozen:gc.unfreeze()@@ -1192,11 +1171,9 @@ _BAND_CHECK = [None]def _gemma4_router_hook():- """Inside a block, a sliding layer whose mask is a plain causal band no longer than the- window runs is_causal SDPA, as the stock router does; longer bands run masked SDPA. The- router itself is not traced: its engagement counters drive a log-once branch dynamo guards- on, and its banded kernel traced in a checkpointed block recomputes different saved tensors- than its forward (CheckpointError)."""+ """Sliding layers: a plain causal band within the window runs is_causal SDPA, longer bands run+ masked SDPA. Router stays untraced: its counters drive a branch dynamo guards on; traced+ banded kernel breaks checkpoints"""try:from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONSexcept Exception:diff --git a/unsloth/models/_custom_dtype.py b/unsloth/models/_custom_dtype.pyindex 00588531129..f63893cb264 100644--- a/unsloth/models/_custom_dtype.py+++ b/unsloth/models/_custom_dtype.py@@ -110,8 +110,7 @@ def neutralize_inherited_custom_dtype():def trusted_custom_dtype():- """Returns (value, code_is_trusted); False means honour the dtype fields and drop- the two code fields."""+ """Returns (value, code_is_trusted); when False, drop the two code fields."""value = os.environ.get(_ENV_KEY, "")if value == "":return "", Falsediff --git a/unsloth/models/_decision_common.py b/unsloth/models/_decision_common.pyindex 01ba53cfbea..aa977fa1f20 100644--- a/unsloth/models/_decision_common.py+++ b/unsloth/models/_decision_common.py@@ -500,9 +500,8 @@ HEAD_TEMPERATURE_RANGE = (0.05, 20.0)def _calibrate_clef(config: dict, logits, items) -> dict:- # Calibrated against being right (the gold label), not the soft gold distribution: Clef's- # confidence is read as the chance the answer is correct, and soft gold targets left a tuned- # model underconfident (confidence 0.61 at accuracy 0.78 on typed-decisions).+ # Hard gold: Clef's confidence is the chance an answer is right; soft targets made it+ # underconfident.common = _laya().commonhard = [{**item, "target": [float(j == item["label"]) for j in range(len(z))]}diff --git a/unsloth/models/_decision_fast.py b/unsloth/models/_decision_fast.pyindex 776386b09ae..7a067d08f77 100644--- a/unsloth/models/_decision_fast.py+++ b/unsloth/models/_decision_fast.py@@ -152,10 +152,8 @@ def compiled_encoder(amp_dtype = None,max_length: Optional[int] = None,):- """Compile each Laya encoder layer in place for one training run, then go back to eager.-- In place keeps parameter names, saving and LoRA merging unchanged.- """+ """Compile Laya encoder layers in place for one training run, then go back to eager; parameter+ names stay unchanged so saving and LoRA merging work"""layers = _encoder_layers(model)if not (layers and _wants_compile(model, forwards)):layers = []@@ -209,8 +207,7 @@ def compiled_encoder(def pad_length(model, inputs: dict) -> dict:- # Pads a training batch to the static bucket; padded positions are masked keys and never- # gathered, so the loss is unchanged.+ # Padded keys are masked and never gathered, so the loss is unchanged.multiple = model.__dict__.get("_unsloth_pad_multiple", 0)extra = -inputs["input_ids"].shape[1] % multiple if multiple and model.training else 0if extra:diff --git a/unsloth/models/_fused_rl_logprobs.py b/unsloth/models/_fused_rl_logprobs.pyindex 7b1e4155bab..20c56a8627c 100644--- a/unsloth/models/_fused_rl_logprobs.py+++ b/unsloth/models/_fused_rl_logprobs.py@@ -118,9 +118,8 @@ def score_hidden_states(entropy = False,head_info = None,):- """``(logps, entropy | None)`` from ``tensor`` when it is the final hidden states of ``model``, else None (the- forward ignored the flag and ``tensor`` is real logits). Entropy is detached, as every caller logs it under- ``no_grad``; rows outside ``mask`` are 0."""+ """Returns (logps, entropy or None) from the final hidden states, else None; entropy is detached+ since callers log it under no_grad; rows outside mask are 0"""from .rl_replacements import _unsloth_pref_returns_hidden_stateshead, transforms, _ = head_info if head_info is not None else fused_head(model)@@ -285,9 +284,7 @@ def ppo_score(temperature,entropy = False,):- """``(logps, entropy | None)`` for PPO from ``tensor = output.logits[:, context_length - 1 : -1]``, or None when- the route is off or the forward returned real logits (TRL's lines then run on them unchanged). ``model`` is the- PolicyAndValueWrapper (its policy head scores) or a standalone reference policy."""+ """PPO logps and entropy from the hidden states; None when the route is off or real logits came back."""if route is None:return Nonemodel = _ppo_policy(route, model)diff --git a/unsloth/models/_gdn_op.py b/unsloth/models/_gdn_op.pyindex dc7a7435e99..d0bc526579a 100644--- a/unsloth/models/_gdn_op.py+++ b/unsloth/models/_gdn_op.py@@ -12,9 +12,8 @@ from torch.autograd.graph import saved_tensors_hooksdef _causal_depthwise_conv(x, weight):- """F.conv1d(x, weight[:, None], groups = C, padding = K - 1)[..., :T] for x (B, C, T), weight- (C, K), as K shifted multiply-adds accumulated in fp32. Inductor's convolution_backward- lowering guards on the exact sequence length (a recompile per length); this stays dynamic."""+ """Causal depthwise conv as K shifted multiply-adds accumulated in fp32 (not conv1d); Inductor+ conv backward recompiles per exact sequence length, so this stays dynamic"""seq_len, padding = x.shape[-1], weight.shape[-1] - 1xp = F.pad(x, (padding, 0)).float()w = weight.float()diff --git a/unsloth/models/_mamba_lora.py b/unsloth/models/_mamba_lora.pyindex 7d28805bef3..3d6da218905 100644--- a/unsloth/models/_mamba_lora.py+++ b/unsloth/models/_mamba_lora.py@@ -111,10 +111,7 @@ def _merged_weight(allow_multiple = False,names = None,):- """``W + delta`` when that is exactly what the LoRA module computes, else None.-- ``names`` replaces the active adapters (one row of a PEFT mixed-adapter batch).- """+ """W + delta when exactly what the LoRA module computes, else None; names replaces active adapters."""try:from peft.tuners.lora import Linear as LoraLinearexcept Exception:diff --git a/unsloth/models/_remote_code_buffers.py b/unsloth/models/_remote_code_buffers.pyindex 1b668f4e965..068108f1b36 100644--- a/unsloth/models/_remote_code_buffers.py+++ b/unsloth/models/_remote_code_buffers.py@@ -41,8 +41,7 @@ def _is_remote_code_module(module):def _constructor_kwargs(module):- """Arguments to rebuild ``module`` from its own attributes, or None when a required- one cannot be recovered."""+ """Kwargs to rebuild module from its attributes; None if a required one is unrecoverable."""try:signature = inspect.signature(type(module).__init__)except (TypeError, ValueError):@@ -173,16 +172,13 @@ def _fresh_non_persistent_buffers(def restore_remote_code_non_persistent_buffers(model):- """Recompute the non-persistent buffers of remote-code modules that transformers 5- left uninitialised. Returns the number of buffers restored; a no-op on 4.x, where- the model is built with real buffers."""+ """Recomputes non-persistent buffers that transformers 5 leaves uninitialised; a no-op on 4.x."""if model is None or not _transformers_builds_on_meta():return 0dtype = getattr(model, "dtype", None)cache = {}restored = 0- # transformers 5 runs the nearest PreTrainedModel's `_init_weights` on every module after- # building on meta; a buffer it writes already holds the right value.+ # transformers 5 runs `_init_weights` after meta build; buffers it writes are already set.for module, init_weights in _modules_with_init_weights(model):own = getattr(module, "_non_persistent_buffers_set", None)if not own or not _is_remote_code_module(module):diff --git a/unsloth/models/_routing_replay.py b/unsloth/models/_routing_replay.pyindex 5a3b013bc85..7003652bd41 100644--- a/unsloth/models/_routing_replay.py+++ b/unsloth/models/_routing_replay.py@@ -118,10 +118,8 @@ def _active_adapters(model):def _router_extra_args(module, parent):- # Routers such as MiniMax-M2 / HY-V3 (`forward(hidden_states, e_score_correction_bias)`) or- # LFM2-MoE (`forward(hidden_states, expert_bias = None)`) take the parent MoE block's buffer:- # the block calls `self.gate(hidden_states, self.e_score_correction_bias)`. Pass the parent's- # same-named tensor; None when a required argument has none.+ # Routers taking e_score_correction_bias or expert_bias get the same-named tensor from the+ # parent MoE block; None when a required argument has nonetry:params = list(inspect.signature(module.forward).parameters.values())[1:]except (TypeError, ValueError):@@ -145,9 +143,7 @@ def _prime_formula(layers,parent = None,):- """Run the zoo hook once, eagerly, on a synthetic router call whose replay is the natural- routing: it picks and caches module._unsloth_replay_formula exactly as the first real call- would. Returns None when primed, else why it could not be."""+ """Eagerly primes module._unsloth_replay_formula on a synthetic natural-routing call; None if primed."""weight = getattr(module, "weight", None)hidden = getattr(module, "hidden_dim", None) or getattr(module, "in_features", None)if hidden is None and torch.is_tensor(weight) and weight.dim() == 2:@@ -187,9 +183,7 @@ def _prime_formula(return _check_formula(rr, module, x, extra)-# The check also runs with the input scaled so the router logits spread to these standard-# deviations: near-zero logits make every formula give ~1 / k, so the priming input alone can let a-# wrong formula through (sigmoid routing matched by softmax).+# Also checks scaled inputs: near-zero logits make every formula give ~1/k, hiding a wrong one._CHECK_LOGIT_STDS = (1.0, 4.0)@@ -236,12 +230,9 @@ def _remove_hook(module, name, extras, hook_id):def prepare_routing_replay(model, before):- """After install_routing_replay(model, ...): prime the router formulas outside compilation and- detach the replay hooks during `model.disable_adapter()` and while `model.set_adapter()` leaves a- non-policy adapter active (PEFT reference scoring). A router that- cannot be primed loses its replay hook (it keeps its natural routing) with a warning, rather- than reaching the data dependent formula pick inside a compiled graph. Returns the number of- replay hooks left (0 when routing replay installed nothing)."""+ """Primes router formulas outside compilation; detaches replay hooks during disable_adapter and+ non-policy set_adapter (PEFT reference scoring); a router that cannot be primed keeps natural+ routing and loses its replay hook with a warning"""hooks = _new_hooks(model, before)if not hooks:return 0diff --git a/unsloth/models/_sentence_transformer_unpadding.py b/unsloth/models/_sentence_transformer_unpadding.pyindex 24a4f05f7ee..fed7276f794 100644--- a/unsloth/models/_sentence_transformer_unpadding.py+++ b/unsloth/models/_sentence_transformer_unpadding.py@@ -182,12 +182,9 @@ def disable_sentence_transformer_unpadding(model):def enable_sentence_transformer_unpadding(model, auto = False):- """Pack valid tokens through FlashAttention varlen / xFormers during training.-- Returns False (model untouched) unless: Transformers 5, stock BertModel / RobertaModel- with absolute positions and SDPA, a mean-only pooling pipeline, and a bidirectional- varlen backend. ``auto`` skips batches under _MIN_AUTO_TOKENS padded slots.- """+ """Packs valid tokens for FlashAttention varlen or xFormers in training; returns False (model+ untouched) unless transformers 5, stock Bert or Roberta with absolute positions and SDPA,+ mean-only pooling, bidirectional varlen backend"""import transformersif getattr(model, "_unsloth_unpadding_installed", False):@@ -203,8 +200,7 @@ def enable_sentence_transformer_unpadding(model, auto = False):transformer = model[0]base = transformer.auto_model- # Exact types (seen through unsloth_zoo's bf16 autocast subclass): PEFT-wrapped,- # remote-code and compiled models keep the stock path.+ # Exact type check: PEFT, remote-code and compiled models keep the stock path.base_type = getattr(type(base), "_unsloth_autocast_base", type(base))if base_type not in (BertModel, RobertaModel):return Falsediff --git a/unsloth/models/clef.py b/unsloth/models/clef.pyindex 552e92b0db1..9a217c4ecfc 100644--- a/unsloth/models/clef.py+++ b/unsloth/models/clef.py@@ -91,17 +91,15 @@ def _span_mask(starts, ends, begin, end, dtype):def _norm_pool_forward(hidden, weight, bias, memory_weight, starts, ends, eps, chunk, matmul_dtype):- # hidden_norm in fp32 one chunk of tokens at a time: only the [B, L, width] memory and the span- # means are kept, never the [B, L, hidden] fp32 copy. The memory projection runs in- # matmul_dtype, as autocast runs Cloudflare's head.+ # Normalizes hidden in fp32 one token chunk at a time, never keeping a full [B, L, hidden] fp32+ # copy; the memory projection runs in matmul_dtype, as autocast runs the Cloudflare headbatch, length, _ = hidden.shapememory = hidden.new_empty((batch, length, memory_weight.shape[0]), dtype = matmul_dtype)pooled = hidden.new_zeros((batch, starts.shape[1], hidden.shape[-1]), dtype = weight.dtype)projection = memory_weight.to(matmul_dtype).t()for begin in range(0, length, chunk):end = min(length, begin + chunk)- # aten directly, as the backward does: Unsloth patches F.layer_norm into a function that- # compiles itself, which would add a graph inside this opaque op.+ # Calls aten directly: the patched F.layer_norm compiles itself inside the op.normalized = torch.ops.aten.native_layer_norm(hidden[:, begin:end].to(weight.dtype), weight.shape, weight, bias, eps)[0]@@ -477,8 +475,7 @@ def batched_logits(head, hidden_states, output_embedding_weight, layout, checkpoclass JointSchemaHead(ReferenceJointSchemaHead):- # Same parameters and state dict as Cloudflare's head; the forward also takes an fp32 copy of- # the head over 16-bit hidden states.+ # Same state dict as Cloudflare's head; forward uses an fp32 copy of it for 16-bit inputs.def __init__(self,hidden_size: int,diff --git a/unsloth/models/cohere.py b/unsloth/models/cohere.pyindex f5a6ea0a1c4..a5f4c03e692 100644--- a/unsloth/models/cohere.py+++ b/unsloth/models/cohere.py@@ -421,8 +421,7 @@ def CohereAttention_fast_forward_inference(if bsz == 1:Qn *= self.scalar- # (Q * scalar) @ K beats (Q @ K) * scalar for stopping overflows; see ggerganov/llama.cpp#7805- # (comment 2153349963).+ # Scale Q before Q @ K to avoid overflow; see ggerganov/llama.cpp 7805.A = _gqa_decode_scores(Qn, Knn, self.attention[:, :, :, :cached_len])A[:] = torch_nn_functional_softmax(A, dim = -1, dtype = torch.float32)A = _gqa_decode_values(A, Vnn, Qn)diff --git a/unsloth/models/decision.py b/unsloth/models/decision.pyindex 28029b6179c..3e11ea9bb73 100644--- a/unsloth/models/decision.py+++ b/unsloth/models/decision.py@@ -137,8 +137,7 @@ def _lean_lora_forward(self, x, *args, **kwargs):)):return self._unsloth_peft_forward(x, *args, **kwargs)- # PEFT's maths without its per-call checks, its round trip of x through the fp32 adapter- # dtype, and the multiply when scaling is 1.+ # PEFT math without per-call checks, the fp32 round trip of x, and the scale-1 multiply.lora = self.lora_B[adapter](self.lora_A[adapter](x))scaling = self.scaling[adapter]return self.base_layer(x) + (lora if scaling == 1 else lora * scaling)@@ -752,9 +751,8 @@ def _load_clef(if load_in_4bit and not full_finetuning and kwargs.get("quantization_config") is None:kwargs["quantization_config"] = _clef_bnb_config(dtype)_pin_device_map(kwargs)- # A float16 request (or a GPU without bfloat16) puts Qwen3.5 on Unsloth's float32 path:- # float16 linear weights, float32 activations, no autocast (the gated delta net NaNs in pure float16).- # An adapter folder loads its base and the adapters through Unsloth's own PEFT path.+ # float16 or no bfloat16 sends Qwen3.5 to a float32 path (float16 linear weights, float32+ # activations, no autocast): pure float16 NaNs in its gated delta netbackbone, processor = FastModel.from_pretrained(str(folder),max_seq_length = max_len,@@ -886,8 +884,7 @@ def _staging(output: Path):def _fold_temperature(state: dict, temperature: float) -> bool:- # logits / T == prior / T + gate * (joint_scale / T * cosine + residual / T): exact while the- # rescaled log-scales stay under the head's clamp(max = log 100).+ # Folding T is exact while the rescaled log scales stay under the clamp at log 100.cap = math.log(100.0)scales = {}for name in ("prior_logit_scale", "joint_logit_scale"):@@ -934,8 +931,7 @@ def _clef_head_weights(self, exact = False) -> tuple:config["head_temperature"] = temperatureweights = {}for name, value in state.items():- # The logit scales stay float32: a folded temperature moves them, and bfloat16's 8 bit- # mantissa would turn that into a few percent on every logit.+ # Logit scales stay float32: bfloat16 would blur a folded temperature in every logit.value = value.to(torch.float32 if value.dim() == 0 else torch.bfloat16).contiguous()if not torch.isfinite(value).all():raise ValueError(diff --git a/unsloth/models/decision_datasets.py b/unsloth/models/decision_datasets.pyindex a6acf10b011..52b45520d60 100644--- a/unsloth/models/decision_datasets.py+++ b/unsloth/models/decision_datasets.py@@ -675,12 +675,7 @@ def build_decision_mixture(decontaminate_against: Optional[Iterable] = None,token = None,) -> list:- """A shuffled mix of decision rows from several sources.-- `sources`: names from SOURCES, {name: weight}, or {name: [converted rows]} (weights equal).- Each source contributes n_rows * weight / total rows, sampled with replacement only when it- has fewer rows than its share (each repeat gets a fresh augmentation).- """+ """Sources sample with replacement only when short of their share; repeats get fresh augmentation."""rng = random.Random(seed)if isinstance(sources, (list, tuple)):sources = {name: 1.0 for name in sources}diff --git a/unsloth/models/decision_from_lm.py b/unsloth/models/decision_from_lm.pyindex f8a45bbfdaa..803d0e6fb10 100644--- a/unsloth/models/decision_from_lm.py+++ b/unsloth/models/decision_from_lm.py@@ -1,8 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.-# A plain language model plus a fresh joint schema head = a Clef-style decision model that trains,-# evaluates and saves like a Cloudflare Clef checkpoint.+# A plain LM + a fresh joint schema head: a Clef-style model that trains and saves like Clef.__all__ = ["load_lm_as_decision_model",diff --git a/unsloth/models/decision_gguf.py b/unsloth/models/decision_gguf.pyindex fe2ecd699d0..dc40fbcf29a 100644--- a/unsloth/models/decision_gguf.py+++ b/unsloth/models/decision_gguf.py@@ -604,9 +604,7 @@ def export_decision_gguf(source_folder = None,print_output = False,) -> dict:- """Converts a merged decision checkpoint (Clef or Laya layout) to GGUF in output_dir- (default <checkpoint_folder>/gguf): model-<QUANT>.gguf, mmproj-<QUANT>.gguf for a Clef- vision tower, and export.json, written last. Returns export.json's content."""+ """Writes model-<QUANT>.gguf (and mmproj for vision), then export.json last; returns its content."""with _exit_on_sigterm():return _export_decision_gguf(checkpoint_folder, quantization_method, output_dir, source_folder, print_outputdiff --git a/unsloth/models/decision_mlx.py b/unsloth/models/decision_mlx.pyindex c9b574f7068..d71df89f442 100644--- a/unsloth/models/decision_mlx.py+++ b/unsloth/models/decision_mlx.py@@ -993,12 +993,9 @@ class FastDecisionModel:images = None,audio = None,) -> dict:- """Answers one Decision API request: {name: answer} at the calibrated temperatures.- `images` (as in a row: PIL images, data URLs, or bytes / path dicts) are read by a Clef whose base model has a vision tower.- `audio` (as in a row: data URLs, bytes / path dicts, or decoded 16 kHz mono clips) is heard by a Clef whose base model has an audio tower.- Each answer is the Decision API's (choice / confidence, score / legend, or noul) plus- "answer" (the option, True / False for noul, the level number for score) and- "probabilities" over every option."""+ """Answers a Decision API request at calibrated temperatures; images (PIL, data URLs, bytes+ or path dicts) need a vision tower, audio (data URLs, bytes, path dicts or decoded 16 kHz+ mono clips) an audio tower; each answer adds answer and probabilities"""import torchfrom unsloth._vendor.clef.joint_schema_model import systemone_answerdiff --git a/unsloth/models/diffusion_infer.py b/unsloth/models/diffusion_infer.pyindex cd01a30f00b..a20c19aa7c6 100644--- a/unsloth/models/diffusion_infer.py+++ b/unsloth/models/diffusion_infer.py@@ -144,9 +144,7 @@ def capture_lock(device):def drop_on_move(module, attr):- """Forget ``module.<attr>`` whenever the module's tensors are moved or cast (``to`` / ``cpu`` / ``cuda`` /- ``half`` / ``float`` all go through ``Module._apply``): a cache kept as a plain attribute is not moved with- them, so it would keep the old device's memory alive until the next generate."""+ """Drop module.<attr> on each move or cast: a plain attribute is not moved and pins the old device."""cls = type(module)attrs = cls.__dict__.get("_unsloth_drop_on_apply")if attrs is None:@@ -303,9 +301,7 @@ def resolve_compile(compile, device):@contextlib.contextmanagerdef inference_compile(base, mode):- """Compile each decoder layer for this generate call and put the previous call path back afterwards, so a- later training step never runs an inference-mode (CUDA Graph) layer. The compiled wrapper is cached on the- layer, so dynamo reuses its graphs across calls. mode None does nothing."""+ """Compiles decoder layers for one generate call, then restores them so training never runs graphs."""if mode is None or mode == "graphs":yield 0returndiff --git a/unsloth/models/diffusion_loss.py b/unsloth/models/diffusion_loss.pyindex c5c2f065c10..9dad88518f0 100644--- a/unsloth/models/diffusion_loss.py+++ b/unsloth/models/diffusion_loss.py@@ -24,8 +24,7 @@ _MIN_ROWS = 16def diffusion_compile_mode(args):- """None (eager), "auto" (compiled CE chunks on CUDA), "loss" (compiled CE chunks anywhere) or "full"- (compiled CE chunks + per-layer backbone compile)."""+ """None eager; auto = compiled CE on CUDA; loss = anywhere; full adds backbone compile."""if os.environ.get("UNSLOTH_COMPILE_DISABLE", "0").lower() in ("1", "true", "yes"):return Nonevalue = getattr(args, "diffusion_compile", "auto") if args is not None else "auto"@@ -226,12 +225,8 @@ def chunked_cross_entropy(softcap = None,compiled = False,):- """sum(w * CE) and the unweighted CE sum over positions with target != -100.-- ``hidden`` is [..., H] projected by ``weight`` [V, H] (+ ``bias``), or already logits [..., V] when- ``weight`` is None. Logits are computed in the input dtype and upcast like ``head(h).float()``. The second- output carries no gradient (metrics). Returns (weighted_sum, ce_sum, count) as 0-dim tensors.- """+ """Returns (weighted sum, CE sum, count) over targets not equal to -100; logits computed in+ input dtype and upcast like head(h).float(); the CE sum has no gradient (metrics only)"""width = hidden.shape[-1]hidden = hidden.reshape(-1, width)targets = targets.reshape(-1)@@ -273,11 +268,8 @@ def is_plain_linear(module):def fusable_head(model, base):- """The plain nn.Linear output head whose input can be taken instead of logits, or None (dense logits).-- Decided once per head module (a head wrapped later, e.g. by PEFT, is re-checked): a LoRA / quantized /- offloaded / tied or post-scaled head, or a distributed wrapper (FSDP shards the weight outside its- forward), keeps the dense path."""+ """Plain nn.Linear head whose input can replace logits, else None; LoRA, quantized, offloaded,+ tied, post-scaled or distributed-wrapped heads stay dense"""if is_distributed_wrapper(model):return Nonehead = base.get_output_embeddings() if hasattr(base, "get_output_embeddings") else None@@ -335,9 +327,7 @@ def _decoder_layer_lists(model):def _warm_rotary_caches(model):- """LLaDA fills its RoPE cache lazily and moves it to the parameters' device on first use. Inside a compiled,- checkpointed layer that move happens in the forward but not in the recompute, so the two save different- tensors (CheckpointError). Fill it on the right device before compiling."""+ """Fill LLaDA's RoPE cache on the right device before compiling; else checkpoint recompute fails."""try:device = next(model.parameters()).deviceexcept StopIteration:diff --git a/unsloth/models/diffusion_samplers.py b/unsloth/models/diffusion_samplers.pyindex 5910440209d..c4aa904ad81 100644--- a/unsloth/models/diffusion_samplers.py+++ b/unsloth/models/diffusion_samplers.py@@ -320,8 +320,7 @@ def _block_sample(if int(high.sum()) >= count:transfer[row] = highelse:- # Never more than the masks left: the official top-k could overwrite prompt tokens sharing- # the first decoded block.+ # Cap at masks left; top-k could overwrite prompt tokens in first block.k = min(count, int(mask_index[row].sum()))transfer[row, torch.topk(confidence[row], k).indices] = Truewindow = x[:, start:end]diff --git a/unsloth/models/dpo.py b/unsloth/models/dpo.pyindex 4242f398391..d24b05353ac 100644--- a/unsloth/models/dpo.py+++ b/unsloth/models/dpo.py@@ -111,9 +111,8 @@ def _output_head(trainer, model):# A LoRA / modules_to_save head computes more than weight @ h; leave it to its own forward.if head is None or hasattr(head, "base_layer") or hasattr(head, "modules_to_save"):return None, None- # The kernel reads weight / bias directly: only a plain, unhooked nn.Linear is exactly F.linear(h, W, b).- # The head module is never called, so its module backward hooks (which may rewrite grad_input)- # would never fire either. Weight tensor / AccumulateGrad hooks still see the kernel's dW.+ # Only a plain unhooked nn.Linear is exactly F.linear(h, W, b); the kernel skips the head so its+ # module backward hooks never run, but weight or AccumulateGrad hooks still see the kernel dWif (type(head) is not torch.nn.Linearor hasattr(head, "_hf_hook")@@ -666,12 +665,9 @@ def unsloth_fused_dpo_compute_loss_v1(return_outputs = False,trl_semantics = None,):- """TRL 1.x ``DPOTrainer._compute_loss`` for text-only decoder models, scored from hidden- states in row chunks. Returns ``None`` (run TRL's own) whenever the inputs leave that case.-- ``trl_semantics`` is what rl_replacements read from the installed TRL's source: legacy_fdiv- (pre-1.10 f-divergence scores), entropy_mean (pre-1.3 entropy metric) and tp_size (1.13+- divides the token count by the tensor-parallel size)."""+ """Chunked TRL 1.x DPO loss for text-only decoders; None means run the TRL loss instead;+ trl_semantics mirrors installed TRL quirks: legacy_fdiv pre-1.10, entropy_mean pre-1.3,+ tp_size 1.13 and newer"""if not _dpo_v1_supported(trainer, model, inputs, return_outputs, trl_semantics):return Noneheads = _dpo_v1_heads(trainer, model)diff --git a/unsloth/models/falcon_h1.py b/unsloth/models/falcon_h1.pyindex 780b210b66b..4c4e26bc8c5 100644--- a/unsloth/models/falcon_h1.py+++ b/unsloth/models/falcon_h1.py@@ -344,8 +344,7 @@ def FalconH1Attention_fast_forward_inference(if bsz == 1:Qn *= self.scalar- # (Q * scalar) @ K beats (Q @ K) * scalar for stopping overflows; see ggerganov/llama.cpp#7805- # (comment 2153349963).+ # Scale Q before Q @ K to avoid overflow; see ggerganov/llama.cpp 7805.A = _gqa_decode_scores(Qn, Knn, self.attention[:, :, :, :cached_len])A[:] = torch_nn_functional_softmax(A, dim = -1, dtype = torch.float32)A = _gqa_decode_values(A, Vnn, Qn)diff --git a/unsloth/models/fsdp2.py b/unsloth/models/fsdp2.pyindex ea03997a5f8..bb836c8fb97 100644--- a/unsloth/models/fsdp2.py+++ b/unsloth/models/fsdp2.py@@ -432,8 +432,7 @@ def install_fsdp2_prepare_hook():def fsdp2_prepare_model(accelerator, model, *args, **kwargs):from .fsdp2_qlora import fsdp2_qlora_wrap- # The 4-bit fallback to uint8 storage first: float-packed weights would count as frozen- # 16-bit weights in the dtype unification.+ # uint8 storage first: float-packed 4-bit weights would count as frozen 16-bit weights.with fsdp2_qlora_wrap(model, original) as qlora:fill_fsdp2_mixed_precision(accelerator)unify_trainable_dtypes(accelerator, model)diff --git a/unsloth/models/fsdp2_bnb_optim.py b/unsloth/models/fsdp2_bnb_optim.pyindex f07ec148d4d..22011b1126e 100644--- a/unsloth/models/fsdp2_bnb_optim.py+++ b/unsloth/models/fsdp2_bnb_optim.py@@ -52,9 +52,7 @@ def _bnb_base_classes():def supports_local_shards(optimizer_or_cls):- """bitsandbytes Adam / AdamW (8-bit blockwise, paged or not, or 32-bit): Optimizer2State with- optimizer_name 'adam' (AdEMAMix keeps two first moments in one state and is not covered). The class- check alone when given a class."""+ """bnb Adam/AdamW on Optimizer2State with optimizer_name 'adam'; AdEMAMix is not covered."""base = _bnb_base_classes()if base is None:return False@@ -77,10 +75,7 @@ def supports_local_shards(optimizer_or_cls):def _plain_bnb_class(cls, base):- """Only bitsandbytes' own Adam / AdamW / PagedAdam(W) classes: every class above Optimizer2State- comes from bitsandbytes and none replaces step / init_state / update_step. A subclass elsewhere- (Unsloth's QGaLoreAdamW8bit: optimizer_name 'adam', its own step() projecting whole 2-D weights)- cannot be stepped shard by shard."""+ """Only plain bnb Adam/AdamW/PagedAdam classes; subclasses like QGaLoreAdamW8bit cannot step shards."""def unwrapped(fn):while hasattr(fn, "__wrapped__"):@@ -137,9 +132,7 @@ def _local_grad(grad, DTensor):return grad-# Blocks per pass when (de)quantizing a checkpointed state: 16384 blocks = 4M elements, so the-# temporaries (a float table and int64 indices per candidate scale) stay a few hundred MB however large-# the shard is. Every block is independent, so the result does not depend on the chunking.+# Blocks per pass bound the temporaries; blocks are independent, so chunking never changes results._CHUNK_BLOCKS = 16384@@ -149,8 +142,7 @@ def _dequantize(device,chunk_blocks = None,):- """float32 copy of state `key` on `device`, built chunk by chunk into the one output tensor. Paged- state reports the CPU device (unified memory)."""+ """float32 copy of a state key, built chunk by chunk; paged state reports the CPU device."""value = raw[key]if value.dtype != torch.uint8:return value.to(device = device, dtype = torch.float32)@@ -171,8 +163,7 @@ def _dequantize(def _nearest_codes(padded, sorted_code, scale):- """Per block: index into sorted_code of the nearest code * scale for each element, and the block's- total absolute reconstruction error."""+ """Per block: nearest sorted_code index for each element, and total reconstruction error."""table = sorted_code.unsqueeze(0) * scale.unsqueeze(1) # (blocks, 256), ascending per rowhi = torch.searchsorted(table, padded.contiguous()).clamp_(max = table.shape[1] - 1)lo = (hi - 1).clamp_(min = 0)@@ -189,13 +180,9 @@ def _quantize_into(out_absmax,chunk_blocks = None,):- """bitsandbytes' blockwise quantization of `values` (float32) into `out_codes` (uint8, same shape)- and `out_absmax` (one float32 per 256 elements), inverting a dequantization exactly. bitsandbytes- scales a block by its largest magnitude A, and the signed map has no -1.0: when that element is- negative it is stored as min_code * A. The scale is therefore the largest positive value, or the- largest |negative| / |min code| (with its float32 neighbours, since that division can round), and- each element maps to the nearest code * scale; per block the candidate with the smallest- reconstruction error wins (zero for the original scale). Runs `chunk_blocks` blocks at a time."""+ """bnb blockwise quant of float32 values into uint8 codes (same shape) and one float32 absmax+ per 256 elements; scale is the largest positive or largest |negative| / |min code| (bnb map+ has no -1.0); least error wins"""device = out_codes.devicecode = code.to(device = device, dtype = torch.float32)flat = values.reshape(-1)@@ -340,9 +327,8 @@ class _LocalShardMixin:return keysdef _export_aux(self, p, raw, keys, out):- """Each rank's history vectors for a DTensor parameter, as one Shard(0) DTensor of shape- (world * n,) over the parameter's mesh, so the full checkpoint holds every rank's vector and a- same-world-size resume gets its own back; a replicated parameter's vector is plain."""+ """Each rank history vector as one Shard(0) DTensor of shape (world * n,) over the parameter+ mesh (plain if replicated), so a same-world-size resume gets its own vector back"""DTensor = _dtensor_class()local = _local(p, DTensor)for key in keys:@@ -606,11 +592,7 @@ def rename_optimizer_state_for(optimizer, full_state):def _align_param_group_keys(optimizer, full_state):- """Saved param groups from the other optimizer carry its own hyperparameter keys (torch AdamW's- amsgrad / foreach / ..., bitsandbytes' alpha / t_alpha / ...), which torch's state dict loaders- refuse. Keep the keys both optimizers have (lr, betas, eps, weight_decay: the saved values), drop- the saved-only ones and take this optimizer's own value for the rest. Only called for a- checkpoint of the other optimizer (its state keys were renamed)."""+ """Keeps shared group keys, drops saved-only ones (torch refuses them); live values fill the rest."""saved_groups = full_state.get("param_groups")live_groups = getattr(optimizer, "param_groups", None)if not isinstance(saved_groups, list) or not live_groups:diff --git a/unsloth/models/fsdp2_native.py b/unsloth/models/fsdp2_native.pyindex 04503d1b53f..25fccb1165f 100644--- a/unsloth/models/fsdp2_native.py+++ b/unsloth/models/fsdp2_native.py@@ -59,10 +59,8 @@ _LEAF_TYPES = (class FSDP2Config:param_dtype: Optional[torch.dtype] = None # None = model compute dtype (bf16; fp16 on T4)reduce_dtype: torch.dtype = torch.float32- # None = auto: when the whole model fits on one GPU (fsdp2_perf.plan_fsdp2_layout), frozen weights stay- # replicated (never gathered), only trainable ones are sharded, kept gathered from forward to backward- # (False) with next-block prefetch, and a small trainable set (LoRA) is one root unit; otherwise every- # block reshards after forward (True). An explicit bool / int is used as is. Last block always False.+ # None = auto: fit-on-one-GPU models keep frozen weights replicated; otherwise reshard every+ # block but the last.reshard_after_forward: Optional[Union[bool, int]] = Nonecpu_offload: bool = False # CPUOffloadPolicymesh: Optional[object] = None # DeviceMesh; None = 1-D over WORLD_SIZE@@ -830,9 +828,8 @@ def _resolve_param_dtype(model, config):if compute == torch.float16 and any(p.requires_grad and p.dtype == torch.float32 for p in model.parameters()):- # float16 gathers of float32 masters move the embedding / norm / lm_head backward into- # float16, where scaled gradients overflow and the GradScaler skips steps one GPU takes;- # gather the masters as they are and let autocast cast like one GPU does.+ # Gather fp32 masters as they are: a float16 gather overflows scaled grads and GradScaler+ # skips steps.return Nonereturn compute@@ -1750,9 +1747,8 @@ def shard_model(model, config: Optional[FSDP2Config] = None):and param_dtype in (torch.bfloat16, torch.float16)and _all_trainable_float32(model)):- # Fit layout: FSDP2 manages only trainable parameters. One GPU keeps float32 masters (LoRA) and- # lets autocast cast them at each op; a 16-bit gather casts them first, which moved Gemma4's step-0- # grad norm 0.2% off 1 GPU (A/A 0.01%). Gather them as they are; the 4-bit storage stays 16-bit.+ # Fit layout: only trainable params are sharded; gather float32 LoRA masters as they are (a+ # 16-bit gather moves grad norms off one GPU); the 4-bit storage stays 16-bit.gather_dtype = Nonemp_policy = MixedPrecisionPolicy(param_dtype = None, reduce_dtype = config.reduce_dtype)if not units and not layout.root_only:@@ -2377,8 +2373,7 @@ def _install_accelerate_hooks():_refuse_bnb_optimizer_instance(optimizer)if native and _mixed_param_groups(optimizer):if getattr(_inner_optimizer(optimizer), "state", None):- # The split carries no per-parameter state over; a mixed group stepping a foreach /- # fused kernel over DTensor and plain tensors fails.+ # Split drops per-parameter state; a mixed group breaks foreach / fused steps.raise RuntimeError(_MIXED_GROUPS_REFUSAL)if native and _split_mixed_param_groups(getattr(optimizer, "optimizer", optimizer)):_print_rank0(@@ -2691,8 +2686,7 @@ def native_load_optimizer_sharded(model, optimizer, directory):# The target layout: this rank's shards (empty optimizer state is initialised first).state = get_optimizer_state_dict(root, optimizer, options = options)unstepped = _match_saved_optimizer_keys(state, directory, root)- # Hyperparameter keys the checkpoint lacks (another optimizer class, or an older torch) keep this- # optimizer's values; dcp.load would refuse them as missing.+ # Missing hyperparameter keys keep this optimizer's values; dcp.load would refuse them.unsaved = _drop_unsaved_group_keys(state, directory)dcp.load(state, checkpoint_id = os.fspath(directory), process_group = group)for index, key, value in unsaved:@@ -2932,8 +2926,7 @@ def _native_load_hf_sharded(root, checkpoint):try:dcp.load(state, storage_reader = reader, process_group = group)except (Exception, CheckpointException) as exc:- # A read error reaches every rank as a CheckpointException (a BaseException, so `except- # Exception` alone would let it abort the resume).+ # CheckpointException is a BaseException, so `except Exception` alone would miss it.error = exc# The fallback is voted on too: the full load rewrites every tensor this one may have touched.if not _all_ranks_agree(error is None, group):@@ -3214,9 +3207,8 @@ def _install_trainer_hooks():return original_save_model(self, output_dir, _internal_call = _internal_call)if output_dir is None:output_dir = self.args.output_dir- # Collective gather on every rank (the Trainer would only call _save on rank 0). The sharded- # root, not a torch.compile (`_orig_mod`) / DDP-style (`.module`) wrapper around it: a- # compiled PeftModel is still an adapter checkpoint, and its state dict keys carry no prefix.+ # Gather on every rank from the sharded root, not a compile or DDP wrapper, so keys carry no+ # prefix.root = _native_root(model)if _is_peft(root):# The adapter save also writes frozen tensors (resized embeddings, inactive adapters,@@ -3279,8 +3271,7 @@ def _install_trainer_hooks():if is_native_fsdp2(getattr(self, "model", None)):# Before the LR scheduler records one base LR per group._split_mixed_param_groups(getattr(optimizer, "optimizer", optimizer))- # Localized, or refused here (a bitsandbytes optimizer that cannot step local shards- # would otherwise fail inside the first step).+ # A bnb optimizer that cannot step local shards is refused here, not in step one._refuse_bnb_optimizer_instance(optimizer)return optimizer@@ -3368,9 +3359,8 @@ def _install_trainer_hooks():]group, usable = _dcp_group(_native_root(model))if usable:- # What each rank sees on (possibly node-local) storage is voted on, so all ranks read- # the same format or skip together: [all see dcp, all see .pt, all see the scheduler,- # none sees an optimizer, none sees the scheduler].+ # Each rank's view of node-local storage is voted on, so all ranks read one format or+ # skip together.sharded, full, scheduler, none_saved, no_scheduler = _all_ranks_agree(local + [not (local[0] or local[1]), not local[2]], group)@@ -4244,10 +4234,8 @@ def native_fsdp2_trainer_setup()_refuse_bnb_optimizer_instance(optimizer)if is_native_fsdp2(model) and optimizer is not None and _mixed_param_groups(optimizer):- # The Trainer would split the groups after a scheduler recorded one base LR (and lambda)- # per group (the new groups keep their initial LR; a resumed scheduler state no longer- # matches), and a split cannot carry loaded per-parameter state, so it is skipped and the- # mixed group reaches a foreach / fused kernel. Only a fresh optimizer alone is split.+ # Split only a fresh optimizer: a late split breaks the scheduler's base LRs or loaded+ # state.if scheduler is not None or getattr(_inner_optimizer(optimizer), "state", None):raise RuntimeError(_MIXED_GROUPS_REFUSAL)if is_native_fsdp2(model):diff --git a/unsloth/models/fsdp2_native_quant.py b/unsloth/models/fsdp2_native_quant.pyindex 90b9755840f..7aa196b9795 100644--- a/unsloth/models/fsdp2_native_quant.py+++ b/unsloth/models/fsdp2_native_quant.py@@ -30,11 +30,9 @@ def _dtensor_class():@contextlib.contextmanagerdef native_quant_context(model, dtype = None):- """Enter around the fully_shard calls. Yields None for a model without bitsandbytes 4-bit weights- (nothing is touched), else the `prepare_fsdp2_qlora` info (`params4bit`, `converted`, `patched`,- `storage`, `reverted`). `dtype`: the float storage of the packed bytes, the mixed precision- param_dtype (default: the weights' compute dtype). load_in_4bit = False models are left exactly- as they are."""+ """Enter around the fully_shard calls; yields None for models without bitsandbytes 4-bit weights+ (untouched), else the prepare_fsdp2_qlora info; dtype is the float storage of the packed+ bytes."""with fsdp2_qlora_wrap(model, native = True, dtype = dtype) as info:yield info@@ -66,9 +64,8 @@ def sharding_report(model):def after_native_shard(model):- """After `fully_shard(model)`: install the DCP state dict handling of bitsandbytes 4-bit weights,- and average the gradient of any trainable parameter FSDP2 does not manage over ranks (like DDP),- so no replica drifts. Returns `sharding_report(model)` plus `reduced` (those parameter names)."""+ """After fully_shard: install DCP state-dict handling for bitsandbytes 4-bit weights, and+ DDP-average grads of unmanaged trainable params so replicas do not drift."""from .fsdp2_save import install_dcp_bnb_state_dict, reduce_unsharded_trainable_gradsif any(diff --git a/unsloth/models/fsdp2_perf.py b/unsloth/models/fsdp2_perf.pyindex 5cf1cedae33..add2b3cc78a 100644--- a/unsloth/models/fsdp2_perf.py+++ b/unsloth/models/fsdp2_perf.py@@ -45,8 +45,7 @@ def _param_bytes(params, dtype = None):def _device_bytes(device = None):- """Total memory of the GPU the model trains on; 0 for a CPU (or other non-CUDA) mesh, which plans- the per-block sharded layout as a CPU-only host does."""+ """Total memory of the GPU; 0 for CPU or non-CUDA meshes, which plan the sharded layout."""if device is not None and torch.device(device).type != "cuda":return 0try:@@ -149,9 +148,8 @@ def plan_fsdp2_layout(except ValueError:free_fraction = default_free_fractionmodel_bytes = layout.frozen_bytes + layout.trainable_bytes- # "Fits" = the whole model (what DDP keeps on every GPU) uses at most `fraction` of one device,- # leaving the rest for activations, gradients and optimizer state.- # CPU offload asks for memory, not speed: keep the plain sharded layout.+ # Fits = the whole model uses at most a fraction of one device; CPU offload keeps the sharded+ # layout.forced = os.environ.get("UNSLOTH_FSDP2_LAYOUT", "auto").strip().lower()if fits is None and forced in ("fit", "sharded"):fits = forced == "fit"@@ -190,9 +188,7 @@ def plan_fsdp2_layout(layout.prefetch = (layout.fits and os.environ.get("UNSLOTH_FSDP2_PREFETCH", "1").strip().lower() not in _FALSE)- # With the frozen weights replicated, what is left to shard (LoRA adapters) is small: one root- # unit = one all-gather + one reduce-scatter per step instead of a hook pair and two collectives- # per block, and the per-block saving it gives up is a few MB.+ # Small LoRA set as one root unit: one all-gather and reduce-scatter per step, not per block.units = os.environ.get("UNSLOTH_FSDP2_TRAINABLE_UNITS", "auto").strip().lower()small = layout.trainable_bytes <= min(1 << 30, 0.01 * layout.device_bytes)layout.root_only = (diff --git a/unsloth/models/fsdp2_qlora.py b/unsloth/models/fsdp2_qlora.pyindex 169103ebb0a..01cc9c650b2 100644--- a/unsloth/models/fsdp2_qlora.py+++ b/unsloth/models/fsdp2_qlora.py@@ -518,9 +518,8 @@ def patch_fsdp2_params4bit():getattr(self, "_unsloth_param_module", None),)if unsharded is not None and not getattr(unsharded, _GATHERED_MARK, False):- # unsloth-zoo's 4-bit MoE paths cache NF4 pointer tables by weight address; FSDP2- # frees and re-allocates this storage around every forward and backward, so they- # re-key it per call instead (zoo moe_ready_epoch.FSDP2_GATHERED).+ # FSDP2 reallocates NF4 storage each pass, so zoo's address-keyed tables are+ # re-keyed per call.try:setattr(unsharded, _GATHERED_MARK, True)except Exception:diff --git a/unsloth/models/fsdp2_save.py b/unsloth/models/fsdp2_save.pyindex b5aeeaad82d..7d233687c34 100644--- a/unsloth/models/fsdp2_save.py+++ b/unsloth/models/fsdp2_save.py@@ -203,10 +203,8 @@ def _wait_for_writer(writer,writer_rank = 0,):- """The other ranks wait for the writer's write, so no later collective overtakes it. A store key,- not a barrier: a merged or quantized export (and a Hub upload) can outlast the process group's- collective timeout, and NCCL ranks blocked in a barrier would abort before the writer arrives.- Keyed per writer rank so disjoint sub-meshes do not release each other."""+ """Store key, not a barrier: other ranks wait so no later collective overtakes the write, and a+ long export can outlast the collective timeout; keyed per writer rank."""_SAVE_COUNTER[writer_rank] = _SAVE_COUNTER.get(writer_rank, 0) + 1count = _SAVE_COUNTER[writer_rank]key = (@@ -346,8 +344,7 @@ def fsdp2_gathered(if not units or DTensor is None:yield Nonereturn- # An eval forward leaves the last block and the lm_head unit gathered; make every- # parameter a DTensor again so all ranks gather the same list.+ # An eval forward leaves units gathered; reshard first so all ranks gather the same list._reshard_units(units)dist = _dist()rank = dist.get_rank() if dist is not None else 0@@ -462,8 +459,7 @@ _MERGED_4BIT_METHODS = ("merged_4bit", "merged_4bit_forced", "forced_merged_4bitdef _merges_onto_dequantized_4bit(model):- """unsloth_zoo folds a merged_16bit LoRA onto dequant(W4) for a few architectures (falcon_h1),- dequantizing the live packed weight where it sits."""+ """zoo folds merged_16bit LoRA onto dequantized W4 for some architectures (falcon_h1)."""try:from unsloth_zoo.saving_utils import (_model_type_needs_dequant_merge_base,@@ -569,8 +565,7 @@ def _gathered_host_bytes(DTensor = _dtensor_class()if DTensor is None:return 0- # Counted as the gather will find them: it reshards first, so an eval forward's still- # gathered units are DTensors again by then.+ # Reshards first so the count matches what the gather finds._reshard_units(fsdp2_units(model))total = 0seen = set()@@ -818,12 +813,9 @@ def fsdp2_export_on_writer(convert_on = None,converts_in_place = False,):- """An export that rebuilds or quantizes the whole model in one process (GGUF, torchao, OpenVINO),- on a model FSDP2 shards. Every rank must call it. The writer (global rank 0, or the lowest rank- of a sub-mesh) first checks the gathered weights fit its host RAM, and every rank refuses if- not. Then the shards are gathered to the writer's CPU, the writer alone calls `run()`, the- ordinary single-process export, and the others wait on the store (a GGUF build can outlast any- collective timeout). Every rank returns the writer's result, or raises if the writer raised."""+ """Every rank must call it. The writer checks gathered weights fit its host RAM (all ranks+ refuse if not), gathers to CPU, alone runs the single-process export; others wait on the+ store; all return or raise with the writer."""dist = _dist()rank = dist.get_rank() if dist is not None else 0writer_rank = mesh_writer_rank(model)@@ -929,9 +921,7 @@ def _has_sharded_4bit(args, kwargs):def _has_native_replicated_4bit(args, kwargs):- """A natively sharded model (fsdp2_native, fit layout) whose Linear4bit weights FSDP2 left replicated:- they keep bitsandbytes' own `weight.absmax` / `quant_state` entries, which a strict DCP load rejects- as unexpected keys although the in-memory QuantState already equals them."""+ """Replicated Linear4bit weights keep weight.absmax and quant_state keys that strict DCP rejects."""model = args[0] if args else kwargs.get("model", None)if not isinstance(model, torch.nn.Module) or not getattr(model, "_unsloth_fsdp2_native", False):return False@@ -1142,9 +1132,8 @@ def _restore_quant_state(model, state_dict, options):loads_weight, saved = payload[0]if not saved:if loads_weight:- # A checkpoint written before QuantState was saved (a frozen QLoRA base): its packed- # bytes are the live ones, so the live scales are theirs. Other bytes would be- # dequantized with the wrong scales.+ # Pre-QuantState checkpoints: live scales apply only when the saved packed bytes+ # match the live ones.same = _same_packed_bytes(module.weight, state_dict.get(head[:-1]), dist if broadcast else None)@@ -1299,10 +1288,7 @@ def model_mesh(model):def mesh_all_reduce(tensor, mesh, dist):- """Sum `tensor` in place over every rank of `mesh` (the world when None), one all_reduce per mesh- dimension (the groups of each dimension partition the mesh, so an HSDP mesh is summed whole).- Returns the number of ranks summed. A sub-mesh (several models or replicas on disjoint ranks)- reduces only over its own ranks."""+ """One all_reduce per mesh dim sums an HSDP mesh whole; a sub-mesh reduces only over its own ranks."""if mesh is None:dist.all_reduce(tensor)return dist.get_world_size()diff --git a/unsloth/models/fsdp2_vision.py b/unsloth/models/fsdp2_vision.pyindex 7dfb22a9fa9..bae3e680bc1 100644--- a/unsloth/models/fsdp2_vision.py+++ b/unsloth/models/fsdp2_vision.py@@ -199,8 +199,7 @@ def _agree_counts(device,mesh = None,):- """Elementwise sum of `flags` over the ranks of `mesh` (the model's; the world when None), and- their number: one small all-reduce per mesh dimension."""+ """Sum of `flags` over `mesh` ranks (world when None) and the rank count, via all-reduce."""import torch.distributed as distif not (dist.is_available() and dist.is_initialized()):@@ -215,8 +214,7 @@ def _agree_counts(def _missing_required(fn, inputs):- """Parameters of `fn` with no default (not *args / **kwargs) that `inputs` does not supply. A- signature that cannot be read counts as unknown: ["?"]."""+ """Required params of `fn` (not *args/**kwargs) that `inputs` omits; ["?"] if unreadable."""try:signature = inspect.signature(inspect.unwrap(fn))except (TypeError, ValueError):@@ -277,13 +275,8 @@ def _install_presence_agreement(device_of,mesh = None,):- """Every forward of `host`, before any encoder runs: one all-reduce over [present per input,- cannot-run-a-dummy per modality]. Each input is encoded by its own call, so an input present on- some ranks only makes the ranks without it run the modality's dummy (`run_dummy`, the image inputs- a dummy stands in for), or, when there is no dummy for that input or it cannot be built on some- rank lacking it, raises on every rank alike (the ranks with it would otherwise wait in- collectives the others never enter). A dummy that cannot be built is found before the- collective, so that failure is agreed too."""+ """Agrees across ranks before encoding; an input with no dummy, or whose dummy cannot be built,+ raises on every rank so no rank waits in a collective others skip."""signature = _forward_signature(host)plan = [(m, m.groups(signature)) for m in modalities]slots = [@@ -373,11 +366,8 @@ def _audio_tower(module):def _audio_host(model, vision_host = None):- """The module whose forward receives the audio input on every rank: the outermost one taking an- audio input with an audio tower in its subtree. An inner module taking it too may run only on some- ranks (PeAudioVideoModel calls `audio_model` only when no video is given), and an agreement hook- there would leave the other ranks out of its collective. The vision host is reused when it takes an- audio input and holds the tower (Gemma3n / Gemma4), so one collective covers both."""+ """Outermost module taking audio with an audio tower in its subtree (inner ones may run on some+ ranks only); the vision host is reused when it takes audio and holds the tower."""candidates = [vision_host] if vision_host is not None else []candidates += list(model.modules())for module in candidates:@@ -526,10 +516,8 @@ def _float_sum(obj, acc = None):return accfields = getattr(obj, "__dataclass_fields__", None)if fields or isinstance(obj, dict):- # ModelOutput: Gemma4 assigns pooler_output (the embed_vision projection) to a- # BaseModelOutputWithPast after building it, so it is neither a field nor a dict item, only an- # instance attribute. Read the dict items, the fields and the instance attributes (a tensor- # counted twice only adds another 0 times it).+ # Gemma4 sets pooler_output only as an instance attribute, so read __dict__ values as well+ # as fields.values = list(obj.values()) if isinstance(obj, dict) else []values += [getattr(obj, name, None) for name in fields or ()]values += list(getattr(obj, "__dict__", {}).values())@@ -557,9 +545,8 @@ def _vision_modules(mm, tower):def _managed_by_fsdp(*modules):- """Some parameter of `modules` issues a gradient collective: a DTensor (FSDP2 reduce-scatters it,- but only where its gradient is not None), or a replicated trainable one whose gradient is averaged- by the all-reduce hook `fsdp2_save.reduce_unsharded_trainable_grads` installed."""+ """Whether any parameter issues a gradient collective: a DTensor (only where its gradient is not+ None), or a replicated trainable one with the all-reduce hook."""try:from torch.distributed.tensor import DTensorexcept ImportError:@@ -585,8 +572,7 @@ def _in_generate():def _vision_plan(model):- """(host, image modality or None, dummy tower or None, [separate video modality]) for the vision- encoders, or None when none issues collectives."""+ """(host, image, dummy tower, video) for vision encoders; None if none issue collectives."""mm = _multimodal_module(model)if mm is None:inline = _inline_multimodal_module(model)@@ -682,8 +668,7 @@ _TEXT_KWARGS = frozenset("args",))-# Media inputs by name (the ones above in this module, Fuyu's image_patches, ...) or by shape of the-# name, for models whose config carries no media sub-config.+# Media inputs are matched by name, or by name pattern for models without a media sub-config._MEDIA_KWARG_RE = re.compile(r"(pixel|image|img|video|audio|speech|patch|wave|mel|spectrogram|_features$|_values$)")@@ -692,8 +677,7 @@ _BACKBONE_NAMES = ("language_model", "text_model", "text_decoder")def _forward_chain(model):- """The outermost module and the wrapped models its forward hands kwargs to (PeftModel ->- LoraModel -> the transformers model), outermost first."""+ """Model and the wrapped models its forward passes kwargs to, outermost first."""chain = [model]for _ in range(6):current = chain[-1]@@ -729,8 +713,7 @@ def _media_candidates(chain):def _is_multimodal(chain, candidates):- """A media sub-config (vision_config, audio_config, audio_encoder_config, ...) on the model's- config, or a media-looking input in its forward."""+ """Has a media sub-config (vision_config, audio_config, ...) or a media-looking input."""for module in chain:config = getattr(module, "config", None)if config is None:@@ -743,9 +726,8 @@ def _is_multimodal(chain, candidates):def _outside_backbone(model, chain):- """Parameters outside the language model that are trainable or FSDP-managed (a DTensor): the- ones a media input alone reaches. The text backbone (`language_model` / `text_model`, else the- decoder) and the input / output embeddings do not count."""+ """Trainable or FSDP-managed (DTensor) parameters outside the language model that only a media+ input reaches; the text backbone and input and output embeddings do not count."""try:from torch.distributed.tensor import DTensorexcept ImportError:@@ -784,11 +766,10 @@ def _outside_backbone(model, chain):def _generic_media_plan(model, named):- """The outermost forward agrees on every media input whenever a multimodal model has trainable- or FSDP-managed parameters outside its language model: one bit per candidate input (a fixed,- sorted list of forward argument names read now). Inputs a named modality covers keep its dummy;- the others have none, so a mismatch raises on every rank. Returns (host, leftover modality or- None), or None (text-only model, or nothing outside the backbone)."""+ """Outermost forward agrees on each media input (one bit per sorted candidate argument name)+ when a multimodal model has trainable or FSDP-managed parameters outside its language model;+ inputs with no dummy raise on every rank on mismatch; returns (host, leftover modality) or+ None."""chain = _forward_chain(model)candidates = _media_candidates(chain)if not candidates or not _is_multimodal(chain, candidates):@@ -811,12 +792,9 @@ def _generic_media_plan(model, named):def install_vision_dummy(model):- """Per-modality presence agreement on a natively sharded `model` (vision and audio encoders that- issue gradient / gather collectives). Every forward agrees over ranks, with one small all-reduce,- which encoder inputs each rank has; a modality present on some ranks only runs a dummy on the- others (images, when a dummy input with every required argument can be built) or raises on every- rank. Models with no such encoder get no hook and pay nothing. Returns the host module (the vision- one when there is one), or None."""+ """Per-forward all-reduce so ranks agree on which encoder inputs they have; a modality on some+ ranks only runs a dummy (images, if buildable) on the rest or raises everywhere; no hook+ without such an encoder; returns the host module or None."""if os.environ.get("UNSLOTH_FSDP2_VISION_DUMMY", "1").strip().lower() in ("0","false",diff --git a/unsloth/models/glm4_moe.py b/unsloth/models/glm4_moe.pyindex 30cb4a1ce74..115a87c6c53 100644--- a/unsloth/models/glm4_moe.py+++ b/unsloth/models/glm4_moe.py@@ -105,15 +105,8 @@ torch_nn_functional_silu = torch.nn.functional.siludef Glm4MoeLiteMoE_fast_forward(self, hidden_states):- """- Optimized MoE forward pass using grouped GEMM.-- GLM4 MoE specifics:- - Uses sigmoid router activation (not softmax)- - Has routed_scaling_factor of 1.8- - Has 1 shared expert that always processes all tokens- - Uses group-based selection with topk_group- """+ """GLM4 MoE uses a sigmoid router (not softmax) with routed_scaling_factor 1.8, one shared+ expert that processes all tokens, and group-based selection with topk_group."""residuals = hidden_statesorig_shape = hidden_states.shapebatch_size, seq_len, hidden_dim = orig_shape@@ -181,17 +174,9 @@ def Glm4MoeLiteMoE_fast_forward(self, hidden_states):def Glm4MoeLiteNaiveMoe_fast_forward(self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor) -> torch.Tensor:- """- Optimized expert forward using grouped GEMM.-- Args:- hidden_states: [num_tokens, hidden_dim]- top_k_index: [num_tokens, top_k] indices of selected experts- top_k_weights: [num_tokens, top_k] weights for selected experts-- Returns:- [num_tokens, hidden_dim] output after weighted sum of expert outputs- """+ """Grouped GEMM expert forward: hidden_states is [num_tokens, hidden_dim], top_k_index and+ top_k_weights are [num_tokens, top_k]; returns the [num_tokens, hidden_dim] weighted expert+ sum."""num_tokens, hidden_dim = hidden_states.shapetop_k = top_k_index.shape[1]top_k_weights = top_k_weights.to(hidden_states.dtype)@@ -329,9 +314,6 @@ def Glm4MoeLiteDecoderLayer_fast_forward(def Glm4MoeLiteMLP_fast_forward(self, x):- """- Optimized MLP forward using fused SwiGLU.- """return fast_swiglu_inference(self, x)diff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex c943a8d79ca..104efb17707 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -1292,10 +1292,9 @@ __DTYPE_MAP = {def _is_left_padded(attention_mask):- # Dropping the training mask is exact only for right padding, where causal attention never- # reaches the trailing pads. A label-less forward (custom losses, rerankers) zeroes pad embeddings,- # so attending to left pads sends gradients to NaN (#3705). Checked only then: it syncs, so read- # one column; a left-padded row always starts with a pad.+ # Dropping the mask is exact only for right padding; in label-less forwards (custom losses,+ # rerankers) left pads, whose embeddings are zeroed, send NaN gradients (issue 3705); the check+ # syncs, so it reads column 0 only, where a left-padded row always starts with a pad.if attention_mask.dim() != 2 or attention_mask.shape[-1] < 2:return Falsereturn not bool(attention_mask[:, 0].all())@@ -1632,10 +1631,9 @@ def LlamaModel_fast_forward(and isinstance(self.rotary_emb, LongRopeRotaryEmbedding)and rope_len <= original < rope_rows):- # transformers' longrope_frequency_update picks the factors from max(position_ids) + 1, a host- # sync it pays too; other models and LongRoPE without position_ids stay sync-free.- # Also under compile (one graph break): an in-graph choice would rebuild full-size hybrid- # tables every forward, and this forward is not compiled by Unsloth.+ # Mirrors transformers longrope_frequency_update (factors from max(position_ids) + 1, a+ # host sync); other models and LongRoPE without position_ids stay sync-free; in-graph+ # choice under compile would rebuild tables each forward.rope_len = max(rope_len, int(position_ids.max()) + 1)# rope_rows only sizes the build; LongRoPE picks its short or long factors from rope_len.position_embeddings = self.rotary_emb.get_cached(rope_len, device_index)@@ -2705,9 +2703,8 @@ class LlamaRotaryEmbedding(_PerDeviceRopeCache, torch.nn.Module):t = torch.arange(self.current_rope_size, device = inv_freq.device, dtype = torch.int64).float()t = self._apply_time_scaling(t)- # Rows are independent, so the build goes 32768 rows at a time into the output (bit-identical,- # the same elementwise ops): the fp32 temporaries no longer scale with the cache size (about- # 2 GiB at 1M rows in one shot).+ # Rows are independent, so the build runs in 32768-row chunks (bit-identical), keeping fp32+ # temporaries from scaling with cache size (about 2 GiB at 1M rows in one shot).rows = self._rope_build_chunk_rowscos = sin = Nonefor start in range(0, max(seq_len, 1), rows):diff --git a/unsloth/models/lora_init.py b/unsloth/models/lora_init.pyindex 9f237d5ff20..d994672e5da 100644--- a/unsloth/models/lora_init.py+++ b/unsloth/models/lora_init.py@@ -32,13 +32,9 @@ _EPS32 = torch.finfo(torch.float32).eps / 2 # unit roundoff udef _orthonormalize_(Y, shift, failures, householder):- """Y <- Y R^-1 in place, fp32 shifted CholeskyQR (Fukaya et al. 2020); no host sync.-- Columns are scaled to unit norm first (Gram diagonal = 1, no overflow). The shift is Rump-Ogita's- breakdown bound 2.2 (n + 1) u tr(G) plus a sqrt(m) u n allowance for the Gram's rounding error.- Breakdown flags are appended to `failures` and checked once per call; any breakdown reruns the- whole call with Householder QR, which cannot fail on finite input.- """+ """Y <- Y R^-1 in place via fp32 shifted CholeskyQR (Fukaya et al. 2020), no host sync; columns+ unit-normed first; shift is Rump-Ogita's 2.2 (n + 1) u tr(G) plus sqrt(m) u n for the Gram's+ rounding error; breakdowns in failures rerun with Householder QR."""if householder:Y.copy_(torch.linalg.qr(Y).Q)returndiff --git a/unsloth/models/mxfp4_compressed_linear.py b/unsloth/models/mxfp4_compressed_linear.pyindex 4d41febea76..11b7a40dd2d 100644--- a/unsloth/models/mxfp4_compressed_linear.py+++ b/unsloth/models/mxfp4_compressed_linear.py@@ -139,10 +139,9 @@ def mxfp4_packed_matmul(out = None,bias = None,):- """``x @ W^T (+ bias)`` (``transpose=False``) or ``x @ W`` for the packed ``[out, in / 2]`` weight, in x's dtype.- Skinny forward inputs (decode, small batches) never build the 16-bit weight on sm_80+; below sm_80 they decode it- for cuBLAS only as far as memory allows (row chunks, else the tile kernel); the rest decode it once for cuBLAS.- Differentiable in ``x`` / ``bias``: the kernels and the reused chunk buffer have no autograd of their own."""+ """x @ W^T (+ bias) when transpose is False, else x @ W, for the packed [out, in / 2] weight in+ x dtype; skinny inputs never build the 16-bit weight on sm_80+, and below sm_80 decode only+ as memory allows; the rest decode it once for cuBLAS; differentiable in x and bias."""if torch.is_grad_enabled() and (x.requires_grad or (bias is not None and not transpose and bias.requires_grad)):@@ -232,9 +231,8 @@ def _bounded_dense_matmul_eager(out = None,bias = None,):- """``x @ W^T (+ bias)`` without ever holding more of the 16-bit W than fits: the whole W when it allocates- (one decode + one cuBLAS call), else row chunks of W written to ``y[..., r0:r1]`` (no cross-chunk sums),- else the tile kernel."""+ """x @ W^T (+ bias) without holding more of the 16-bit W than fits: the whole W if it allocates,+ else row chunks written to y[..., r0:r1] with no cross-chunk sums, else the tile kernel."""N, half = packed.shapeK = half * 2dtype, device = x.dtype, x.devicediff --git a/unsloth/models/pp_native.py b/unsloth/models/pp_native.pyindex 1e90619fd5d..3701d68d8d2 100644--- a/unsloth/models/pp_native.py+++ b/unsloth/models/pp_native.py@@ -365,10 +365,9 @@ def _find_parts(model) -> _Parts:base = getattr(child, "original_module", child) # PEFT modules_to_save wraps itnorm_like = "norm" in name.lower() or "Norm" in type(base).__name__too_big = bool(hidden) and sum(p.numel() for p in base.parameters()) > 4 * hidden- # A learned position / token-type table before the layers (GPT-2 wpe, OPT / BART / Whisper- # embed_positions): indexed by positions, not tokens, so later stages (whose pre-layer result is- # replaced by the received hidden states anyway) need nothing from it. A token-indexed table could- # feed the layers a side input and stays refused.+ # A learned position or token-type table before the layers (GPT-2 wpe, OPT/BART/Whisper+ # embed_positions) is indexed by positions, so later stages need nothing from it;+ # token-indexed tables stay refused.positional = (isinstance(base, nn.Embedding)and isinstance(vocab, int)@@ -1489,10 +1488,9 @@ class PipelineParallel:dp_mesh,mp_policy = None,):- """shard_model(model, FSDP2Config(mesh = dp_mesh)) sharded this stage: make the PipelineStage's module- the outer FSDP2 root (no parameters of its own), so torch's PipelineStage defers the gradient- reduce-scatter to the end of the step (set_requires_gradient_sync(False) per micro-batch backward,- one post_backward in perform_reduce_grad), as torchtitan's stage submodule does."""+ """After shard_model shards this stage, make the PipelineStage module the outer FSDP2 root+ with no parameters of its own, so the reduce-scatter defers to perform_reduce_grad, as+ torchtitan does."""from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shardif self.stages_per_rank > 1:@@ -1820,10 +1818,9 @@ class PipelineParallel:return self._batch_loss(m, device, None)def _average_replicated_grads(self):- """Trainable parameters FSDP2 keeps replicated (Unsloth averages them over dp like DDP from an- autograd callback, deferred while gradient sync is off): the pipeline schedule runs every micro-batch- backward with sync off and reduces FSDP2's own groups outside autograd, so average them here once.- Averaging equal values is a no-op, so an earlier per-backward average stays correct."""+ """Averages trainable FSDP2-replicated parameters over dp here, once: the schedule runs+ micro-batch backwards with gradient sync off and reduces FSDP2 groups outside autograd;+ re-averaging equal values is a no-op."""params = self.model.__dict__.get("_unsloth_replicated_grad_params")if not params:returndiff --git a/unsloth/models/remote_moe_shims.py b/unsloth/models/remote_moe_shims.pyindex 3d1ed3c683f..e029c147fa2 100644--- a/unsloth/models/remote_moe_shims.py+++ b/unsloth/models/remote_moe_shims.py@@ -507,8 +507,7 @@ def _grouped_experts(block):cached is None or _grouped_experts_live(block, cached, every = False)):return cached- # One thread stacks and re-points the weights; a concurrent first generate waits instead of capturing a- # graph over half re-pointed experts.+ # A concurrent first generate waits, so no graph is captured over half re-pointed experts.with _STACK_LOCK:cached = block.__dict__.get("_unsloth_grouped_experts", _MISSING)if cached is not _MISSING and (diff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex c4cd3b1c51d..f27e131b82a 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -1498,10 +1498,7 @@ def _pin_pristine_sft_loss_type(config_cls):_UNSLOTH_KBIT_PREP_GUARD_FLAG = "_unsloth_skips_kbit_prep_for_peft_models"-# TRL >= 1.7 enables the aux loss whenever output_router_logits is set; dense configs return no router logits and-# crash (`aux_loss.to`, or Jamba's load_balancing_loss_func indexing an empty tuple). Dense = every expert count-# 0 (granite-4.0-h-350m) or 1 (AI21-Jamba-Reasoning-3B builds a plain MLP for 1 expert; a 1-expert router's aux-# loss is a constant with no gradient anyway). Real MoE keeps its aux loss.+# Dense models (0 or 1 experts) need the aux loss off: TRL >= 1.7 enables it and they crash._DENSE_ROUTER_AUX_LOSS_OFF = ("if getattr(self, 'aux_loss_enabled', False) and hasattr(getattr(self, 'model', None), 'config'):\n"" _text_config = self.model.config\n"@@ -5009,8 +5006,7 @@ def _packing_honored(backbone, position_transform = None):if dtype not in (torch.float16, torch.bfloat16):dtype = torch.bfloat16 if params.dtype == torch.float32 else params.dtypetraining = [(module, module.training) for module in backbone.modules()]- # Training mode, as in the trainer: some models (gpt-oss) take a different attention path when training.- # Dropout off so the comparison is deterministic.+ # Train mode as in the trainer (gpt-oss differs), dropout off for a deterministic compare.backbone.train()for module in backbone.modules():if isinstance(module, torch.nn.modules.dropout._DropoutNd):diff --git a/unsloth/models/rl_config_compat.py b/unsloth/models/rl_config_compat.pyindex 3db6c210638..b29a65e50f5 100644--- a/unsloth/models/rl_config_compat.py+++ b/unsloth/models/rl_config_compat.py@@ -133,11 +133,7 @@ _ACCEPTED_CACHE = {}def _accepted_parameters(config_class):- """Names `config_class.__init__` accepts, and whether it takes `**kwargs`.-- A config with its own `**kwargs` may forward anywhere, so it is reported as- accepting everything and the caller forwards unfiltered.- """+ """Names `config_class.__init__` accepts; a `**kwargs` config is reported as accepting everything."""try:cached = _ACCEPTED_CACHE.get(config_class)except TypeError: # unhashable, so uncacheable; fall through and recompute@@ -242,14 +238,7 @@ def _is_untouched(def rename_value_is_unset(config_class, renamed, value):- """True if `value` carries no information and must not overwrite `renamed`.-- The legacy spellings are `Optional` and default to `None` (`per_gpu_*_batch_size`- in transformers 4.x), so a wrapper mirroring an old signature forwards `None`- for an argument nobody set. Writing that onto a target whose own default is a- number replaces a working value with one the trainer cannot do arithmetic on.- A target that defaults to `None` itself loses nothing, so it still migrates.- """+ """True if `value` is an unset None that must not overwrite `renamed`'s non-None default."""if value is not None:return Falsedefault = _field_default(config_class, renamed)@@ -271,10 +260,9 @@ def removal_source(key):def classify_config_kwarg(config_class, key):- """Verdict on `key`: accepted / rename / retired / unknown, or opaque when the- config declares nothing to judge by. A trailing `**kwargs` is deliberately not- acceptance: the generated `Unsloth<X>Config.__init__` has one, so trusting it- would put every retired field back to being swallowed."""+ """Verdict on key: accepted, rename, retired, unknown or opaque; a trailing **kwargs is not+ acceptance, since generated Unsloth configs have one and trusting it would swallow retired+ fields."""accepted, takes_var_keyword = _accepted_parameters(config_class)if key in accepted:return "accepted", key@@ -301,16 +289,7 @@ def filter_config_init_kwargs(notify = None,mirrored_from = None,):- """Return `kwargs` reduced to what `config_class.__init__` will accept.-- Renames are applied where TRL or transformers documented one; everything else- the config rejects is dropped. Each decision is reported through `notify`- (`print` by default, which shows up reliably in a notebook).-- `mirrored_from` is the generated config class whose `__init__` built `kwargs`.- It is what tells an untouched mirrored parameter apart from a real one, so- omitting it only costs a rename that loses to its own target's default.- """+ """Reduces kwargs to what `config_class.__init__` accepts, applying documented renames."""if not kwargs:return kwargsdiff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex 485e35c0875..8f9bca342e5 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -1464,9 +1464,8 @@ def sft_trainer_compute_loss(function_name, function):return_outputs = False,num_items_in_batch = None,):- # TRL >= 1.15 computes loss_type="dft" only in the compute_loss this replaces (else it trains as NLL):- # run it on TRL's fused LM head. Older TRL routes DFT through compute_loss_func.- # TRL label smoothing applies only to "nll", so label_smoother must not opt dft out.+ # Runs DFT on the TRL fused LM head (TRL >= 1.15 computes it only in compute_loss; older TRL+ # routes it via compute_loss_func); label smoothing must not opt dft out.if getattr(self.args, "loss_type", None) == "dft" and self.compute_loss_func is None:import trl.trainer.utils as _trl_utilsif hasattr(_trl_utils, "add_fused_lm_head"):@@ -3227,8 +3226,7 @@ def _unsloth_vllm_peft_unsupported(model):problems.append(f"LoRA on MultiheadAttention at {module_name}")breakfor module_name, module in model.named_modules():- # A custom tuner layer on a composite base: its weights live in child modules the copy- # merge does not see, so the merged weights would never be sent.+ # Custom tuner on a composite base: weights sit in child modules the merge never sees.if getattr(module, "base_layer", None) is None or not hasattr(module, "get_base_layer"):continuebase = module.get_base_layer()@@ -3343,11 +3341,9 @@ def _unsloth_vllm_sync_kind(trainer):problems.extend(f"one base weight shared by {names}" for names in _unsloth_vllm_shared_targets(model))- # Unsharded: every mergeable PEFT setup is merged out of place, so the frozen base never moves.- # ZeRO-3: TRL merges inside GatheredParameters(modifier_rank = None), which discards in-place edits- # of the gathered copy on exit, so its merge / unmerge cannot drift the stored base either.- # FSDP: TRL calls merge_adapter before it gathers the sharded parameters, so PEFT's full-size- # deltas meet sharded base weights (and the in-place round trip would drift a 16-bit base).+ # Unsharded merges out of place so the frozen base never moves; ZeRO-3 merges inside+ # GatheredParameters, which discards in-place edits on exit; FSDP is refused since TRL merges+ # before gathering shards.kind = "peft_merged" if not sharded else "trl"if getattr(trainer, "is_fsdp_enabled", False):problems.append(@@ -3846,8 +3842,7 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):def chunked_hidden_states_selective_log_softmax(hidden_states, _lm_head, *args, **kwargs):- # FSDP2's forward hooks replace Parameters. Read the current head- # at projection time, including the bias, instead of retaining a shard.+ # FSDP2 replaces Parameters; read the head at projection, not a saved shard.if _zero3_head is not None:head_weight, head_bias = _zero3_headelse:diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.pyindex 55be99db598..66491fba605 100644--- a/unsloth/models/sentence_transformer.py+++ b/unsloth/models/sentence_transformer.py@@ -132,8 +132,7 @@ def _install_fsdp2_collective_st_save(SentenceTransformer):returndef plainly_named(self, args, kwargs):- # The model card prints the architecture: name the modules as one process would, not- # FSDP2's FSDP<Name> subclasses.+ # Card prints class names: use the plain ones, not FSDP2's FSDP<Name> subclasses.renamed = []for module in self.modules():cls = type(module)@@ -154,8 +153,7 @@ def _install_fsdp2_collective_st_save(SentenceTransformer):if not fsdp2_units(self):return original(self, *args, **kwargs)if fsdp2_gather_active():- # The writer inside a gather already made (Trainer.save_model under native FSDP2, which- # also ran fsdp2_st_usage_snippet on every rank).+ # Gather already made the writer; Trainer.save_model ran the snippet on each rank.return plainly_named(self, args, kwargs)# No card: skip the snippet's unshard + forward.snippet = (@@ -163,8 +161,7 @@ def _install_fsdp2_collective_st_save(SentenceTransformer):if _save_creates_model_card(original, self, args, kwargs)else contextlib.nullcontext())- # Every parameter, not just the trainable ones: ST writes its other modules (Dense, ...) too,- # and embedding models are small.+ # All parameters, not only trainable ones: ST writes its other modules (Dense) too.with snippet, fsdp2_gathered(self) as writer:if writer is False:return None@@ -1540,9 +1537,8 @@ class FastSentenceTransformer(FastModel):@staticmethoddef _is_transformer_module_ref(class_ref):- """Name ST's Transformer without importing anything, since importing to compare is the same- execution the gate refuses. Any other spelling (or a subclass) is caught by `issubclass` in- _load_modules, after gating; refusals all live in _resolve_module_class."""+ """Match the ST Transformer by name without importing it, since importing is the execution+ the gate refuses; other spellings or subclasses are caught by issubclass after gating."""if not isinstance(class_ref, str):return False@@ -2089,8 +2085,7 @@ class FastSentenceTransformer(FastModel):folder = module_config.get("path")if not isinstance(folder, str):return- # A rooted path is not a repository folder: Path(model, "/x") is "/x" to the- # loader, so that local folder is the one to check.+ # A rooted path is a local folder (Path(model, "/x") is "/x"); check that folder.rooted = folder.startswith("/") or os.path.isabs(folder)# An empty path is the repository root, which sentence-transformers accepts and# loads the root config.json from. Skipping it left the whole check bypassable by@@ -2172,8 +2167,7 @@ class FastSentenceTransformer(FastModel):breakdef descend(route, sub_ref, sub_class, sub_depth):- # Router.load joins the route onto its own subfolder (Path(subfolder, route)),- # and fetches it from the same repository.+ # Router.load joins routes onto the subfolder and fetches them from the same repo.sub_folder = (routeif route.startswith("/") or os.path.isabs(route)@@ -3577,13 +3571,8 @@ def _patch_st_trainer_load_from_checkpoint():def _patch_pooling_float16_accumulation():- """Pool float16 token embeddings in float32.-- Pooling sums token embeddings in their own dtype, so float16 (T4 / V100, or Unsloth's- float32-forced mode, which keeps float16 weights) overflows to inf once a long input's- sum passes 65504, and Normalize turns that into NaN. Models whose token embeddings reach a- few thousand hit this on inputs of a few thousand tokens. bfloat16 / float32 are left alone;- the pooled vector stays float32 so Normalize and the loss don't overflow either."""+ """Pool float16 token embeddings in float32 (float16 sums pass 65504, go inf, then NaN in+ Normalize); bf16 and fp32 are left alone; the pooled vector stays float32."""try:from sentence_transformers.models import Poolingexcept Exception:diff --git a/unsloth/models/speculative.py b/unsloth/models/speculative.pyindex 3da8f813376..6c2155763ac 100644--- a/unsloth/models/speculative.py+++ b/unsloth/models/speculative.py@@ -72,11 +72,8 @@ def get_mtp_head(random_init = False,dtype = None,):- """Load the model's native MTP head, attach it to `model`, and return it.-- source: repo id / folder with the `mtp.*` tensors (default: the loaded checkpoint).- random_init: random weights, for checkpoints without a head. dtype: default float32.- """+ """Attach the native MTP head to model from source (default: loaded checkpoint) or from random+ weights with random_init; dtype defaults to float32."""import torchif source is None and not random_init:diff --git a/unsloth/models/tp_native.py b/unsloth/models/tp_native.pyindex 9f7d7061e0f..77ee7ba6b66 100644--- a/unsloth/models/tp_native.py+++ b/unsloth/models/tp_native.py@@ -3604,8 +3604,7 @@ def _install_tp_accelerate_hooks():init_fn.func, *init_fn.args, **{**init_fn.keywords, "rank": dp_rank})cls = type(self)- # accelerate shards the batches by num_processes / process_index: give it the dp layout, so the tp- # ranks of a replica read the same batches.+ # accelerate shards by process index: give it the dp layout so tp ranks share batches.self.__class__ = type("UnslothTensorParallelDataAccelerator",(cls,),diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex f09f84aa3f9..9630ae83ea9 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -2035,8 +2035,7 @@ def _static_cache_does_not_fit(model, input_ids, kwargs):need = _static_cache_bytes(model, input_ids, kwargs, exact = False)if need is None:return False- # mem_get_info is a driver call (p90 7-10 ms on a busy host), so a cache under 1/16- # of the card never pays it.+ # mem_get_info is a slow driver call, so caches under 1/16 of the card skip it.if need * 16 <= backend.get_device_properties(device).total_memory:return Falsefree = backend.mem_get_info(device)[0]diff --git a/unsloth/optimizers/flash_adamw.py b/unsloth/optimizers/flash_adamw.pyindex 3cc107abab8..ac731610975 100644--- a/unsloth/optimizers/flash_adamw.py+++ b/unsloth/optimizers/flash_adamw.py@@ -150,14 +150,11 @@ def _get_flash_adamw_class():)super().__init__(params, *args, master_weight_bits = master_weight_bits, **kwargs)- # flashoptim stores unquantized moments in the param dtype, so an fp16 variance- # (grad**2 * (1 - beta2)) underflows to 0 for small grads and the update becomes- # momentum / eps. quantize=True keeps the variance as sqrt with per-group scales.- # Checked per group after flashoptim fills its defaults (so positional and per-group- # quantize both count), for groups added at construction and by add_param_group later.+ # Unquantized fp16 variance underflows to 0 for small grads; quantize=True stores it as sqrt+ # with per-group scales; checked per group after flashoptim fills its defaults, including+ # add_param_group groups.def _group_quantizes(self, group):- # flashoptim resolves a group without the key (a vanilla AdamW state dict) to the- # optimizer-wide setting.+ # A group without `quantize` takes the optimizer-wide setting, like flashoptim.return group.get("quantize", getattr(self, "_quantize", True))def add_param_group(self, param_group):diff --git a/unsloth/optimizers/q_galore_adamw.py b/unsloth/optimizers/q_galore_adamw.pyindex 4cf54871944..b622cda69cf 100644--- a/unsloth/optimizers/q_galore_adamw.py+++ b/unsloth/optimizers/q_galore_adamw.py@@ -263,14 +263,8 @@ class QGaLoreAdamW8bit(Optimizer2State):group_size: int = 128,stochastic: bool = True,) -> None:- """Tag parameters for INT8 weight quantization.-- This marks eligible weights with quantization metadata so that- the optimizer knows to quantize/dequantize them during ``step()``.- **Weights are NOT converted to uint8 here** — they remain in float- so that the first forward/backward pass runs correctly. The actual- quantization happens at the end of the first ``step()`` call.- """+ """Tag INT8-eligible weights; they stay float until the first step() quantizes them, so the+ first forward and backward pass runs correctly."""weight_quant_params = set()for group in param_groups:if group.get("weight_quant", False):@@ -334,10 +328,7 @@ def _weight_quant_load_state_dict_hook(module, state_dict, prefix, *args):def install_weight_quant_hooks(model: torch.nn.Module) -> list:- """Register forward and checkpoint hooks for INT8-quantized weights.-- Returns a list of hook handles so the caller can remove them if needed.- """+ """Register forward and checkpoint hooks for INT8 weights; returns handles to remove them later."""handles = [model.register_forward_pre_hook(_weight_quant_model_pre_hook, prepend = True, with_kwargs = Truediff --git a/unsloth/optimizers/q_galore_projector.py b/unsloth/optimizers/q_galore_projector.pyindex 5dc2e3b265c..587c7e5e80f 100644--- a/unsloth/optimizers/q_galore_projector.py+++ b/unsloth/optimizers/q_galore_projector.py@@ -178,14 +178,7 @@ class GaLoreProjector:return low_rank_graddef project_back(self, low_rank_grad: torch.Tensor) -> torch.Tensor:- """Project a low-rank update back to full rank.-- Args:- low_rank_grad: The low-rank gradient/update tensor.-- Returns:- The full-rank update scaled by ``self.scale``.- """+ """Project a low-rank update back to full rank, scaled by `self.scale`."""float_ortho = self._ortho_float_cacheself._ortho_float_cache = Noneif float_ortho is None:@@ -200,16 +193,7 @@ class GaLoreProjector:@staticmethoddef _compute_orthogonal(weights: torch.Tensor, rank: int, side: str) -> torch.Tensor:- """Compute the top-``rank`` orthogonal matrix via truncated SVD.-- Args:- weights: 2-D tensor (typically the gradient).- rank: Number of singular vectors to keep.- side: ``'left'`` returns U[:, :rank], ``'right'`` returns Vh[:rank, :].-- Returns:- Orthogonal matrix of shape ``(rank, N)`` (right) or ``(M, rank)`` (left).- """+ """Truncated-SVD orthogonal factor: U[:, :rank] for side 'left', Vh[:rank, :] for 'right'."""original_dtype = weights.dtypeoriginal_device = weights.devicediff --git a/unsloth/optimizers/state_offload.py b/unsloth/optimizers/state_offload.pyindex 1b6acb7ceea..26c27333922 100644--- a/unsloth/optimizers/state_offload.py+++ b/unsloth/optimizers/state_offload.py@@ -160,8 +160,7 @@ class _StateOffloader:params = None,device_of = None,):- # device_of(param, key, tensor) names the device of state that is already on the host- # (a checkpoint just loaded there), None to leave it host-only.+ # device_of returns the device for host-resident state, or None to leave it host-only.devices = set()for param, state in self._states(params):for key, value in list(state.items()):@@ -383,8 +382,7 @@ def offload_optimizer_state(optimizer = _innermost(optimizer)if not isinstance(optimizer, torch.optim.Optimizer):return None- # transformers' LayerWiseDummyOptimizer (galore/apollo *_layerwise): the real per-parameter- # optimizers live in optimizer_dict and step from gradient hooks.+ # LayerWiseDummyOptimizer keeps real optimizers in optimizer_dict, stepped by grad hooks.layerwise = getattr(optimizer, "optimizer_dict", None)if isinstance(layerwise, dict):unique = {id(o): o for o in layerwise.values()}.values()@@ -401,8 +399,7 @@ def offload_optimizer_state(return Noneoffloader = _StateOffloader(optimizer, pin_memory = pin_memory, chunk_bytes = chunk_bytes)- # Hooks, not an optimizer.step override: accelerate swaps the instance's step attribute on- # every fp16 step, and hooks run whichever bound step a caller kept.+ # Step hooks, not a step override: accelerate swaps the instance's step on each fp16 step.optimizer.register_step_pre_hook(offloader._pre_step)optimizer.register_step_post_hook(offloader._post_step)diff --git a/unsloth/save.py b/unsloth/save.pyindex 5a5c6105634..197956973bd 100644--- a/unsloth/save.py+++ b/unsloth/save.py@@ -1884,8 +1884,7 @@ def unsloth_save_model(raise ValueError("Unsloth: a model with a trained MTP head saves as safetensors; drop `safe_serialization = False`.")- # Already `True` from the normalisation at the top of this function; the caller having- # passed `None` is what keeps the downgrade below from undoing it.+ # Already True above; the caller passing None keeps the downgrade below from undoing it.if _force_safe_serialization:save_pretrained_settings["safe_serialization"] = safe_serialization@@ -6876,9 +6875,7 @@ def unsloth_generic_save('written. Call `reap_prune(..., save_directory = "pruned_model")` (or save the pruned '"model and load it again) before `get_peft_model`.")- # The pruned base REAP saved is a local folder: an adapter pushed against it names a path no one- # else can load. In this process the marker says so (even if the folder moved since); after a- # reload from that folder, the provenance file reap_prune wrote there does.+ # Pushing an adapter against a local pruned base names a path others cannot load.if (push_to_huband isinstance(model, PeftModel)@@ -7259,9 +7256,8 @@ def _fsdp2_merged_gather_options(model, args, kwargs):@_fsdp2_collective_save(lambda self, args, kwargs: isinstance(self, PeftModel)and _is_adapter_save_method(_merged_save_method(args, kwargs)),- # Packed 4-bit weights are staged on the CPU as they are gathered. merged_4bit merges with PEFT- # one layer at a time on the GPU the packed weight came from, so those layers' LoRA weights stay- # on that device; every other gathered weight goes to the CPU.+ # Packed 4-bit weights are staged on CPU as gathered; merged_4bit keeps those layers LoRA+ # weights on the packed weight GPU; every other gathered weight goes to CPU.offload_to_cpu = lambda self, args, kwargs: _fsdp2_merged_offload(self, args, kwargs),gather_options = _fsdp2_merged_gather_options,)diff --git a/unsloth/trainer.py b/unsloth/trainer.pyindex aa19b61b9d9..ee2554116ea 100644--- a/unsloth/trainer.py+++ b/unsloth/trainer.py@@ -276,11 +276,7 @@ def _should_skip_auto_packing_error(exc: Exception) -> bool:def _should_skip_auto_padding_free_error(exc: Exception) -> bool:- """Net for a TRL that words the padding-free / `max_length` guard differently.-- rl.py already handles the known wording; both terms must appear here so an- unrelated ValueError still propagates.- """+ """Matches a reworded TRL padding_free + max_length error; both terms, so other errors propagate."""message = str(exc).lower()return "padding_free" in message and "max_length" in message@@ -690,11 +686,7 @@ def _forward_accepts_packing_kwargs(model, name = "packed_seq_lengths") -> bool:def _forward_signature_accepts_packing(forward, name = "packed_seq_lengths") -> bool:- """The signature question alone, so a class can be asked it as well as an instance.-- Shared, not duplicated: a disagreement would turn padding-free on for one- spelling of a checkpoint and off for the other.- """+ """Signature check for a class or instance; shared so the two never disagree on padding-free."""if forward is None:return Truetry:@@ -801,11 +793,8 @@ def _string_model_trust_remote_code(config_arg):def _is_hybrid_linear_attention_model(model) -> bool:- """Detect models mixing linear-attention / state-space mixers (gated-delta,- Mamba-style) with a causal conv1d, e.g. Qwen3.5 / Qwen3-Next. Packing and- padding-free flatten the batch, and those recurrent + conv ops leak state- across sequence boundaries, so they must not be packed. Uses composite- structural evidence rather than a model-name match."""+ """Hybrid linear-attention/state-space models with causal conv1d leak state across packed+ sequences, so they must not be packed; detected by structural evidence, not model name."""if model is None:return False@@ -855,9 +844,7 @@ def _config_has_stateful_mixer(config, trust_remote_code = False) -> bool:def _resolve_string_model_config(model_name, config_arg):- """TRL materializes a string ``model=`` inside ``__init__``; resolve its config- up front so the packing guards run before the dataset is packed. Best-effort:- returns None if the config cannot be loaded."""+ """Config of a string `model=`, resolved early so packing guards run first; None if unloadable."""try:from transformers import AutoConfig@@ -1318,9 +1305,7 @@ def _install_legacy_scheduler_resume(scheduler, optimizer):base.load_state_dict(self, state_dict)self._last_lr = [group["lr"] for group in self.optimizer.param_groups]return- # Gated on the optimizer having just migrated: length alone cannot tell a legacy- # [ordinary, embedding] pair from two current non-embedding groups, and remapping- # the latter collapses distinct per-group min_lr floors onto the first.+ # Remap only when the optimizer just migrated; length alone cannot tell legacy pairs apart.if not getattr(built, "_unsloth_loaded_legacy", False):return base.load_state_dict(self, state_dict)for key in ("base_lrs", "_last_lr", "min_lrs"):@@ -1488,10 +1473,8 @@ class UnslothTrainer(SFTTrainer):)if not any("rank" in group for group in param_groups):- # make_q_galore_param_groups selects on param.dim() == 2, and FSDP1 hands us 1-D- # views: FlatParameter with use_orig_params=False, and a 1-D sharded view even- # with use_orig_params=True. Nothing matches, so a requested Q-GaLore run would- # quietly become ordinary 8-bit AdamW. Say so instead.+ # FSDP1 gives 1-D views that Q-GaLore's 2-D selection never matches, so raise, not run+ # plain AdamW.raise ValueError("Unsloth: Q-GaLore was requested but no parameter matched, so the run would ""silently be ordinary AdamW 8bit. Projection needs 2-D parameters; under FSDP "diff --git a/unsloth/utils/hf_packed_attention.py b/unsloth/utils/hf_packed_attention.pyindex 567b4f17524..64e9723c906 100644--- a/unsloth/utils/hf_packed_attention.py+++ b/unsloth/utils/hf_packed_attention.py@@ -661,8 +661,7 @@ def _sdpa_packed_varlen(except RuntimeError as exc:if _ACCELERATOR_ERROR is not None and isinstance(exc, _ACCELERATOR_ERROR):raise- # A build whose varlen picks a backend without causal GQA (cuDNN) refuses at forward: stop- # using it and give this call to the wrapped sdpa.+ # Varlen on cuDNN refuses causal GQA: stop using it and send the call to sdpa._TORCH_VARLEN[:] = [None]logging.getLogger(__name__).info(f"Unsloth: torch varlen_attn unavailable ({exc})")HF_PACKED_ATTENTION_STATS["fast"] -= 1@@ -962,8 +961,7 @@ def enable_hf_packed_attention() -> bool:current = ALL_ATTENTION_FUNCTIONS.get("sdpa", None)if current is None:return False- # Once per process: gemma-4's router stacked above does not forward our sentinel, and re-wrapping- # it would loop through its boxed original.+ # gemma-4's router drops our sentinel, so re-wrapping would loop through its original.if getattr(current, _FLAG, False) or _ORIG_SDPA[0] is not None:return True_ORIG_SDPA[0] = currentdiff --git a/unsloth/utils/mfu.py b/unsloth/utils/mfu.pyindex 97688914761..1a700586b63 100644--- a/unsloth/utils/mfu.py+++ b/unsloth/utils/mfu.py@@ -20,8 +20,7 @@ from collections.abc import Mappingimport torchfrom transformers import TrainerCallback-# Dense (no sparsity) 16 bit tensor core TFLOPs per GPU, from the vendor datasheets.-# Order matters: the first substring found in the device name wins.+# Dense 16-bit tensor TFLOPs per GPU; the first substring found in the device name wins._PEAK_TFLOPS_16BIT = (("H100 PCIE", 756.0),("H100 NVL", 835.0),@@ -29,17 +28,11 @@ _PEAK_TFLOPS_16BIT = (("H200 NVL", 835.5),("H200", 989.0),("GH200", 989.0),- # Dense = half NVIDIA's sparse figure (nvidia.com/en-us/data-center/hgx, gb200-nvl72).- # GB* first: the B200 / B300 keys would match inside their names.+ # Dense is half the sparse figure; GB* first, since B200/B300 match inside GB200/GB300.("GB300", 2500.0),("GB200", 2500.0),("B300", 2250.0),("B200", 2250.0),- # sm120. NVIDIA RTX PRO Blackwell GPU Architecture whitepaper v1.1, Table 4 (dense FP16 / BF16- # tensor with FP32 accumulate): Workstation 503.8, Max-Q 438.9. Server Edition: nvidia.com- # rtx-pro-6000-blackwell-server-edition lists 1 PFLOP FP16 / BF16 with sparsity -> 500 dense.- # GeForce RTX 5090: NVIDIA RTX Blackwell GPU Architecture whitepaper v1.1, Table 3, 209.5 dense- # with FP32 accumulate (GeForce runs FP32 accumulate at half the FP16 accumulate rate).# Specific editions first; every key needs "PRO", so "RTX 6000 Ada Generation" never matches.("RTX PRO 6000 BLACKWELL MAX-Q", 438.9),("RTX PRO 6000 BLACKWELL SERVER", 500.0),@@ -363,9 +356,8 @@ def _unsupported_setup(args,trainer_name = "",):- """True where the per-token count does not describe the step, so nothing is reported:- diffusion objectives (extra no-grad passes, encoder + canvas, recomputed heads) and- single-process DataParallel (the hook runs once per replica, concurrently)."""+ """True for diffusion and single-process DataParallel steps, where the per-token count misleads,+ so nothing is reported."""model_type = str(getattr(_model_config(model), "model_type", "") or "")if "diffusion" in model_type.lower() or "Diffusion" in trainer_name:return True@@ -500,8 +492,7 @@ class UnslothMFUCallback(TrainerCallback):elif self._paused and self._last_step_end is not None:paused = now - self._last_step_endif self._step_end_events:- # The step's kernels may still be queued at on_step_end: exclude only the time- # after every GPU finished them.+ # Queued kernels may outlive on_step_end: pause only once every GPU is done.gaps = []for index, start in self._step_end_events:end = torch.cuda.Event(enable_timing = True)diff --git a/unsloth/utils/packing.py b/unsloth/utils/packing.pyindex b9bd807a26d..31e08f98ea5 100644--- a/unsloth/utils/packing.py+++ b/unsloth/utils/packing.py@@ -1077,10 +1077,8 @@ def _wrap_kwargs_mixer_forward(module) -> None:return outif _dynamo_folds_is_exporting():- # Eager even inside a compiled block: Dynamo folds torch.compiler.is_exporting() to True, so- # the hub-kernel wrappers trace their torch reference, which drops seq_idx / cu_seqlens and- # runs the packed documents into each other (Qwen3.5-0.8B per-document cosine 0.71). Newer- # torch traces the real kernels, and the eager mixer costs 6-20% per step there.+ # Dynamo folds is_exporting() to True, so this stays eager: the traced reference drops+ # seq_idx; newer torch traces real kernels, where eager costs 6-20% per step._packed_forward = torch.compiler.disable(_packed_forward)module.forward = forwarddiff --git a/unsloth/utils/padding_choice.py b/unsloth/utils/padding_choice.pyindex 885df578701..8043def2ddd 100644--- a/unsloth/utils/padding_choice.py+++ b/unsloth/utils/padding_choice.py@@ -23,11 +23,8 @@ _EFFICIENCY = (0.5 # fraction of the datasheet peak a LoRA step reaches when GPU bound (A100 measured 0.5))_MAX_PADDED_GPU_S = 0.10 # padded micro batch GPU estimate below which the host dominates-# Per compute capability, only where measured (padded + block compile vs padding-free, Qwen3 0.6B /-# 4B LoRA r16, 16 and 4 bit, 3 interleaved reps). A capability missing here keeps padding-free.-# sm75 T4, sm80 A100, sm89 L4 (torch 2.14.1): 0.10 s.-# sm120 RTX PRO 6000 Blackwell (Colab G4, torch 2.14.1 and 2.10.0): padded lost 24-29% at a-# ~92 ms estimate on torch 2.14.1 and won (+5% on 2.14.1, +15-64% on 2.10.0) at <= 45 ms.+# Padded GPU-time thresholds per compute capability, measured on torch 2.14.1 (sm120 also torch+# 2.10.0); unlisted capabilities keep padding-free._MAX_PADDED_GPU_S_BY_CAPABILITY = {(7, 5): 0.10,(8, 0): 0.10,@@ -57,10 +54,8 @@ def estimate_microbatch_tokens(max_length = None,seed = 0,):- """Expected (real tokens, padded tokens, attention pairs when padded) per micro batch.-- Batches are drawn uniformly from `lengths` (the trainer shuffles); padded = batch * longest.- """+ """Expected real tokens, padded tokens and attention pairs (when padded) per micro batch;+ batches drawn uniformly from lengths, padded to longest."""lengths = [int(x) for x in lengths if x is not None and int(x) > 0]if not lengths or batch_size < 1:return None@@ -88,10 +83,8 @@ def choose_padding(load_in_4bit = False,capability = None,):- """Pure rule. Returns (use_padding_free: bool, reason: str, padded_gpu_s: float | None).-- `capability` is the CUDA (major, minor); one that was never measured keeps padding-free.- None applies the default threshold (callers that know the device always pass it)."""+ """Returns (use_padding_free, reason, padded_gpu_s); capability is CUDA (major, minor), None+ applies the default threshold, unmeasured capabilities keep padding-free."""if not peak_tflops or peak_tflops <= 0 or not linear_flops_per_token or not padded_tokens:return True, "no estimate", Nonemax_gpu_s = _MAX_PADDED_GPU_Sdiff --git a/unsloth/utils/prefix_grouper.py b/unsloth/utils/prefix_grouper.pyindex c7d8a203abd..ec0e06ae000 100644--- a/unsloth/utils/prefix_grouper.py+++ b/unsloth/utils/prefix_grouper.py@@ -205,11 +205,7 @@ class GroupLayout:def _build_groups(ids_cpu, real_cols_cpu, cstart_cpu, num_generations, total_rows):- """CPU-side grouping mirroring the packed _pk_* partition, or None.-- Prompt = real columns < cstart_r = (L - logits_to_keep) - left_pad_r; every row of a group- must have a byte-identical prompt. Suffix tokens scatter exactly like the packed path.- """+ """CPU mirror of the packed _pk_* partition; None unless each group has byte-identical prompts."""G = num_generationsif G is None or G < 2 or total_rows % G != 0:return None@@ -274,10 +270,7 @@ def _build_group_layout_reference(apply_tokr_gate = True,max_segment_cap = None,):- """Token-by-token shared-prefix GroupLayout (build_group_layout's fallback), or None.-- input_ids [B, L]: prompt left-padded, completion right-padded.- """+ """Token-level GroupLayout fallback for build_group_layout; prompts left-, completions right-padded."""device = input_ids.devicetotal_rows, L = input_ids.shapekeep = input_ids != pad_id@@ -407,17 +400,8 @@ def build_group_layout(apply_tokr_gate = True,max_segment_cap = None,):- """Build the shared-prefix GroupLayout, or return None to fall back to the packed path.-- input_ids : [B, L]. GRPO's layout is left-padded in the prompt and right-padded in- the completion. Real tokens of a row are a contiguous run not necessarily- starting at column 0.- logits_to_keep : int- left_pad_tokens_per_prompt : [B] long tensor (per-row left-pad count in the prompt).-- Same result as _build_group_layout_reference, with one device->host and one- host->device copy instead of per-token loops.- """+ """Shared-prefix GroupLayout, or None to fall back to the packed path; input_ids [B, L] with+ left-padded prompts and right-padded completions; same result as the reference."""args = (input_ids, logits_to_keep, pad_id, num_generations, left_pad_tokens_per_prompt)kwargs = dict(apply_tokr_gate = apply_tokr_gate, max_segment_cap = max_segment_cap)lp = left_pad_tokens_per_promptdiff --git a/unsloth/utils/prefix_grouper_kernel.py b/unsloth/utils/prefix_grouper_kernel.pyindex fbbcfdd60fa..44bb264a344 100644--- a/unsloth/utils/prefix_grouper_kernel.py+++ b/unsloth/utils/prefix_grouper_kernel.py@@ -167,8 +167,7 @@ def build_seg_info_multigroup(def _seg_labels_host(group_specs):- """CPU int64 [3, T_pad] rows (group_of_kv, is_prefix, suffix_of_kv), pad sentinels- included, plus T, T_pad, group_meta and signature parts."""+ """CPU int64 [3, T_pad] rows (group_of_kv, is_prefix, suffix_of_kv); T, T_pad, group_meta."""group_meta = []sig_parts = []seg_lens = []@@ -229,11 +228,8 @@ _BLOCK_MASK_CACHE: Dict[Tuple, BlockMask] = {}def _make_mask_mod(group_of_kv, is_prefix, suffix_of_kv):- """Same group and causal, and kv is a prefix token or in q's own suffix.-- Every prefix index precedes every suffix index of its group, so the one ``kv <= q`` guard- gives prefix-causal and full-prefix visibility for suffixes, matching the SDPA oracle.- """+ """Same group, and kv is a prefix token or in the same suffix as q; one kv <= q guard covers+ both, since every prefix index precedes every suffix index; matches the SDPA oracle."""def mask_mod(b, h, q_idx, kv_idx):same_group = group_of_kv[q_idx] == group_of_kv[kv_idx]diff --git a/unsloth/utils/token_budget.py b/unsloth/utils/token_budget.pyindex 1a14a73682d..6eb2e041468 100644--- a/unsloth/utils/token_budget.py+++ b/unsloth/utils/token_budget.py@@ -278,11 +278,8 @@ def _splittable_keys(batch):def split_batch_by_token_budget(batch, budget):- """Split a collated text batch into sub-batches of at most `budget` tokens, else return `[batch]`.-- Padding-free batches ([1, T] with sequence boundaries) split between whole sequences; padded- batches ([B, L]) split by rows. Anything else (vision tensors, unknown shapes) is not split.- """+ """Splits a batch to at most budget tokens: padding-free [1, T] batches between whole sequences,+ padded [B, L] by rows; other shapes are never split."""if not isinstance(batch, Mapping) or budget is None or budget <= 0:return [batch]input_ids = batch.get("input_ids")@@ -423,8 +420,7 @@ def _padded_batches(trainer):def _balance_dataloader(trainer, dataloader):if _exactness_blocker(trainer) is not None:return False- # A padded micro-batch costs rows x its longest row: equal token sums put a long row in every- # micro-batch, which adds padding without lowering the peak.+ # Padded cost is rows x longest row: equal token sums add padding but not lower the peak.if _padded_batches(trainer):return False# accelerate's DataLoaderDispatcher deals successive inner batches to ranks behind a plain BatchSampler.@@ -598,9 +594,8 @@ def _metric_lengths(trainer):def _global_chunk_weights(trainer, chunks, accelerator):- """Per-key chunk weights. With several processes TRL gathers each chunk's sums across ranks, so the- weight is the chunk's token count summed over ranks. Older TRL (attention style) averages per-rank- entropy ratios, which cannot be refolded, so entropy is left unfolded there."""+ """Multi-process weights sum token counts over ranks; older attention-style TRL averages+ per-rank entropy ratios, which cannot be refolded, so entropy stays unfolded."""weights = {key: [count(trainer, chunk) for chunk in chunks] for key, count in _RATIO_METRICS.items()}diff --git a/unsloth_cli/__init__.py b/unsloth_cli/__init__.pyindex fb4514bf6eb..b918ee108d8 100644--- a/unsloth_cli/__init__.py+++ b/unsloth_cli/__init__.py@@ -221,13 +221,9 @@ app = typer.Typer(def _invocation_args(ctx):- """The arguments this invocation was given, not the host process's argv.-- A library calling `app(args = [...])` or CliRunner never touches sys.argv, so- reading it there would classify somebody else's command line and could move- the process out from under the caller's relative paths. The `unsloth` console- script never reaches here: it is classified at import, from the real argv.- """+ """The invocation's own args, not sys.argv: a library calling app(args=...) or CliRunner would+ have someone else's command line classified and could move the process out from under the+ caller's relative paths; the console script is classified at import from real argv."""captured = ctx.meta.get(_ARGV_META_KEY)if captured is not None:return list(captured)diff --git a/unsloth_cli/_inference.py b/unsloth_cli/_inference.pyindex 471ad9eb9e8..ad27ef9650b 100644--- a/unsloth_cli/_inference.py+++ b/unsloth_cli/_inference.py@@ -143,11 +143,9 @@ _cache_env_seeded = Falsedef _seed_cache_env() -> None:- """Pin the cache locations the backend pins, for in-process CLI commands.-- Otherwise they inherit unsloth_zoo's relative UNSLOTH_COMPILE_LOCATION, resolved against the- working directory, leaving an unsloth_compiled_cache cache_cleanup will not remove (#8865).- """+ """Pin cache locations as the backend does: unsloth_zoo's relative UNSLOTH_COMPILE_LOCATION+ would resolve against the cwd, leaving unsloth_compiled_cache that cache_cleanup misses+ (issue 8865)."""global _cache_env_seededif _cache_env_seeded:return@@ -411,10 +409,8 @@ def render_columns(def stats_hit_token_limit(stats) -> bool:- """Whether a backend's end-of-generation stats say the reply ran out of budget.-- Safetensors reports ``truncated``; MLX and llama-server report a finish reason.- """+ """Whether end-of-generation stats show the reply ran out of budget: safetensors sets truncated;+ MLX and llama-server set finish_reason to length."""if not isinstance(stats, dict):return Falsereturn bool(stats.get("truncated")) or stats.get("finish_reason") == "length"@@ -767,11 +763,8 @@ def load_chat_backend(model_config = None,fresh_backend: bool = False,):- """Load `model` in-process: GGUF via llama-server, else the orchestrator.-- fresh_backend uses a private orchestrator so a second model (compare's- base column) can run alongside the main one.- """+ """Load model in-process, GGUF via llama-server else the orchestrator; fresh_backend uses a+ private orchestrator so a second model (compare's base column) runs alongside."""from unsloth_cli._studio_deps import studio_backend_importswith studio_backend_imports("unsloth inference", studio_only = True), quiet_if_nonzero_mlx_rank():@@ -866,8 +859,7 @@ _STUDIO_SERVICE_MARKER = "Unsloth UI Backend"def _recorded_loopback_bases(address: Optional[str], port: str) -> list:- """Loopback bases for a server recorded at *address*. The wrong family reaches whoever else- holds that port number."""+ """Loopback bases for a recorded address; the wrong family hits whoever holds that port."""import ipaddressloopback, parsed_any = set(), False@@ -932,8 +924,7 @@ def _answers_as_studio(base: str, timeout: float) -> bool:def find_studio_server(timeout: float = 3.0) -> Optional[str]:base = os.environ.get("UNSLOTH_STUDIO_URL", "http://127.0.0.1:8888").rstrip("/")candidates = _loopback_candidate_bases(base)- # Try the concrete loopback addresses in order and return the first that answers, so the rest of- # the flow talks to that exact address.+ # Use the first loopback address that answers, so the flow talks to that exact address.found = next((c for c in candidates if _answers_as_studio(c, timeout)), None)if os.environ.get("UNSLOTH_STUDIO_URL"):return found@@ -1011,8 +1002,7 @@ def verify_studio_identity(base: str, timeout: float = 3.0) -> bool:def _studio_token() -> Optional[str]:- """Self-issue a JWT: the CLI runs as the same OS user as the server, so it- signs with the same stored secret the server validates against."""+ """Signs a JWT with the server's stored secret, since the CLI runs as the same OS user."""try:import studio.backend.core # noqa: F401 puts studio/backend on sys.pathdiff --git a/unsloth_cli/_model_catalog.py b/unsloth_cli/_model_catalog.pyindex 8d3b39882c6..d9bdb6be526 100644--- a/unsloth_cli/_model_catalog.py+++ b/unsloth_cli/_model_catalog.py@@ -151,11 +151,8 @@ def exported_entries() -> List[ModelEntry]:def _pinned_snapshot(repo_path: Path, load_id: Optional[str]) -> Optional[Path]:- """The snapshot a pinned row will open, when ``load_id`` names one inside this repo.-- A pin beats ``refs/main``, because the inventory pins exactly when the ref would resolve- somewhere worse, so the ref names a revision this row never loads.- """+ """Snapshot a pinned row opens when load_id names one in this repo; a pin beats refs/main, which+ would resolve to a revision this row never loads."""if not load_id:return Nonetry:@@ -170,13 +167,9 @@ def _pinned_snapshot(repo_path: Path, load_id: Optional[str]) -> Optional[Path]:def _reachable_snapshots(repo_path: Path, load_id: Optional[str] = None) -> List[Path]:- """The snapshots a load through this row could actually open.-- The pinned one when the row carries a pin, else ``refs/main`` alone when it names one,- since that is what a bare repo id resolves to and another revision's quants are files the- selection cannot reach. A commit- or tag-pinned fetch leaves no ``refs/main``, and those- rows are pinned rather than dropped, so they describe every snapshot instead.- """+ """Snapshots a load through this row can open: the pinned one if pinned, else refs/main alone,+ since other revisions' quants are unreachable; commit- or tag-pinned rows with no refs/main+ describe every snapshot."""snapshots = repo_path / "snapshots"try:available = sorted(path for path in snapshots.iterdir() if path.is_dir())@@ -342,12 +335,9 @@ def _is_loose_gguf_companion(path: str) -> bool:def _gguf_file_as_the_loader_opens_it(path: str) -> str:- """*path*, collapsed to shard 1 when the LOADER reads it as a complete split family.-- Asked of _local_gguf_load_path, not restated: the scan's _GGUF_SPLIT_RE takes three or more- digits and the loader's _GGUF_SPLIT_FILE_RE exactly five, so a local rule would rewrite- model-002-of-003.gguf onto a sibling detect_gguf_model still opens as its own model.- """+ """Shard 1 for a split family as the loader reads it, not restated: the loader's+ _GGUF_SPLIT_FILE_RE takes exactly five digits, the scan's _GGUF_SPLIT_RE three or more; a+ local rule would rewrite model-002-of-003.gguf onto a sibling."""try:from utils.models.model_config import _local_gguf_load_pathexcept ImportError:@@ -360,15 +350,9 @@ def _gguf_file_as_the_loader_opens_it(path: str) -> str:def _gguf_load_target(target: str) -> str:- """The GGUF a picker row should load.-- A row naming a .gguf loads that file: resolving it through the folder returned the best quant- across every unrelated GGUF beside it (#10352). Shards are the exception, collapsed to the- one the loader opens anyway so _dedup_key offers a split family once.-- A FOLDER still resolves: detect_gguf_model takes the largest complete file, commonly the F16,- where cached and exported rows take a Q4-class quant. An OOM by source alone, not a taste.- """+ """A .gguf row loads its own file, not a folder's best quant across unrelated GGUFs (issue+ 10352); shards collapse to the file the loader opens; a folder takes the largest, often an+ F16 that risks OOM."""if _is_gguf_file(target):return _gguf_file_as_the_loader_opens_it(target)return _preferred_complete_gguf(target) or target@@ -395,15 +379,9 @@ def _preferred_complete_gguf(path: str) -> Optional[str]:def _cached_gguf_load_id(row: dict) -> str:- """A concrete local GGUF for a cached row, falling back to the identifier it came with.-- An inactive-cache row already carries a snapshot path, so this resolves the quant inside it.- An ACTIVE-cache row carries the bare repo id, which is right for the inventory and wrong- for a picker: from_identifier() sends a non-path through detect_gguf_model_remote(), whose- GatedRepoError branch is permanent and returns None without the offline local-cache- fallback, so a fully downloaded gated GGUF reads as non-GGUF and hits the Transformers- loader. Resolving the on-disk file keeps the pick on the weights the row was listed for.- """+ """Concrete local GGUF for a cached row, else the identifier it came with; an active-cache bare+ repo id reaches detect_gguf_model_remote, whose permanent GatedRepoError returns None without+ the local-cache fallback, so a downloaded gated GGUF reads as non-GGUF."""load_id = row.get("load_id") or row["repo_id"]resolved = _preferred_complete_gguf(load_id)if resolved:@@ -546,12 +524,8 @@ def _local_dir_holds_a_payload(path: Path) -> bool:def _local_is_a_diffusers_pipeline(model) -> bool:- """Whether a local row is a diffusers pipeline, which never answers a chat turn.-- An unrecognised pipeline gets no task and no root config for can_chat to read, so both- gates pass it while the payload check accepts its pipeline index. The cached path says- this with the row's ``diffusers`` flag; this is the local twin.- """+ """Diffusers pipelines never answer chat; an unrecognised one passes both can_chat gates with no+ task or root config, so the local check mirrors the cached diffusers flag."""from hub.services.models.catalog_classification import _local_is_diffusersreturn bool(_local_is_diffusers(model))diff --git a/unsloth_cli/_npu.py b/unsloth_cli/_npu.pyindex 0e75ae9f4ad..cf7ec8290c6 100644--- a/unsloth_cli/_npu.py+++ b/unsloth_cli/_npu.py@@ -63,10 +63,8 @@ def _read_json(response) -> dict:def prepare_npu_model(request: Callable[..., object], model_path: str, echo: Callable[[str], None]) -> None:- """Enable the NPU runtime and download `model_path` on the Studio behind `request`.-- `request(method, path, payload, timeout)` returns an open HTTP response for that Studio.- """+ """Enable the NPU runtime and download model_path on the Studio behind request(method, path,+ payload, timeout), which returns an open HTTP response."""import http.clienttry:_prepare_npu_model(request, model_path, echo)diff --git a/unsloth_cli/_ssl_keylog.py b/unsloth_cli/_ssl_keylog.pyindex 98e4a201b8b..675ceecb0ee 100644--- a/unsloth_cli/_ssl_keylog.py+++ b/unsloth_cli/_ssl_keylog.py@@ -6,13 +6,9 @@ import sysdef drop_unwritable_ssl_keylog_file():- """Unset SSLKEYLOGFILE when this process cannot append to it.-- ssl.create_default_context opens that path for every context it builds, so an- unwritable one makes every HTTPS client raise: httpx at construction, which- kills the Studio backend on import, and requests on every call. Some security- software sets it machine-wide to a path no user process can open.- """+ """Unset SSLKEYLOGFILE if it cannot be appended: ssl.create_default_context opens it per+ context, so an unwritable path makes every HTTPS client raise; security software sets it+ machine-wide."""path = os.environ.get("SSLKEYLOGFILE")if not path:return Falsediff --git a/unsloth_cli/_system_dir_guard.py b/unsloth_cli/_system_dir_guard.pyindex bd6ae7089fe..caf4ac68e2e 100644--- a/unsloth_cli/_system_dir_guard.py+++ b/unsloth_cli/_system_dir_guard.py@@ -26,12 +26,8 @@ def windows_roots(pathmod = _os.path,isdir = None,):- """Every real Windows directory.-- Candidates are checked, not trusted: a WINDIR aimed at the user's profile- would make ordinary folders look like system ones, and one aimed elsewhere- would disarm the guard. So a directory counts only if it holds System32.- """+ """Real Windows directories only: candidates from SystemRoot, WINDIR and the default folder+ count only if they hold System32, since an aimed WINDIR could disarm the guard."""if isdir is None:isdir = pathmod.isdirsystem_root = environ.get("SystemRoot")@@ -94,12 +90,9 @@ def is_system_dir(def _is_rooted(path, pathmod):- """Absolute, or at least rooted at a drive.-- "." and "C:sub" name no directory on their own, so they are no escape- (pin_relative_overrides resolves the drive-relative form separately). A- leading separator is not absolute, but can never resolve back into System32.- """+ """Absolute or drive-rooted only: '.' and 'C:sub' name no directory alone+ (pin_relative_overrides handles the drive-relative form), and a leading separator cannot+ resolve back into System32."""stripped = _strip_extended_prefix(path)return pathmod.isabs(stripped) or stripped.startswith(("\\", "/"))@@ -218,9 +211,8 @@ def _carries_a_value(arg):def _takes_a_path(rest):- """Whether this `studio` invocation can carry a caller's path. Blunt on- purpose: the bare forms the desktop runs carry none, so anything else might.- """+ """Whether this studio invocation can carry a caller's path; blunt on purpose, since the bare+ forms the desktop runs carry none and anything else might."""if not rest:return Falseif rest[0] in _PATH_TAKING_STUDIO_COMMANDS:@@ -231,11 +223,8 @@ def _takes_a_path(rest):def is_relocatable_invocation(argv, environ):- """True when this invocation is desktop-managed or provably cwd-independent.-- The argv arm matters on its own: it fixes users whose desktop build predates- the Rust-side fix and so sets no marker.- """+ """True when desktop-managed or provably cwd-independent; the argv arm alone fixes desktop+ builds that predate the Rust-side fix and set no marker."""args = [arg for arg in argv if arg]if not args:return False@@ -362,11 +351,8 @@ def pin_relative_overrides(expandvars = None,expanduser = None,):- """Rewrite relative path overrides so they keep naming the same folder.-- Returns the names pinned. A `~` value is written out, since only some readers- expand it themselves.- """+ """Rewrite relative path overrides to keep naming the same folder, returning the names pinned; a+ leading ~ is written out since only some readers expand it."""pinned = []for name in _RELATIVE_PATH_ENV:value = (environ.get(name) or "").strip()@@ -447,18 +433,9 @@ def pin_relative_sys_path(exists = None,expanduser = None,):- """Anchor the relative import roots this interpreter already carries.-- sys.path holds PYTHONPATH entries as written, including the two spellings that- follow the process rather than the caller: an empty entry means the working- directory, and a leading `~` is never expanded there.-- Only an entry naming something on disk is touched, folder or archive. The rest- are other people's strings rather than paths, such as the relative sentinel- setuptools registers for an editable install and accepts back by exact- equality; rewriting one breaks the import it was meant to protect, and leaving- a real archive breaks the next import from it.- """+ """Anchor relative PYTHONPATH entries that name something on disk (an empty entry means the+ working directory; a leading ~ is never expanded there); setuptools editable sentinels match+ exactly and stay untouched."""if syspath is None:import sys as _syssyspath = _sys.path@@ -509,16 +486,8 @@ def _anchor_list_entry(def _expand_settled(value, expandvars):- """The value expanded exactly once, or None if one pass does not settle it.-- One pass is what every reader does, so one pass is what the guard does. The- result is only usable if expanding it again would change nothing, because the- reader expands whatever gets written back: a value that still holds a- reference (a nested %LOCALAPPDATA% that itself holds %USERPROFILE%, an escaped- %%NAME%%, a self-reference) would be expanded a second time by the reader and- read as a folder with another drive in the middle of it. Those are left- exactly as written instead.- """+ """Expands once, returning None unless a second pass changes nothing: readers re-expand what is+ written back, so nested or self-referencing values stay as written."""expanded = expandvars(value)return expanded if expandvars(expanded) == expanded else None@@ -532,10 +501,8 @@ def _anchor(expandvars = None,expanduser = None,):- """The value rewritten to name the same folder from anywhere, or None.-- None means no rewriting is needed: empty, or already fully qualified.- """+ """The value rewritten to name the same folder from anywhere; None when empty or already fully+ qualified."""original = value = (value or "").strip()if value.startswith("~"):# llama_cpp.py hands UNSLOTH_LLAMA_CPP_PATH straight to Path(), so expand ~ now.@@ -646,11 +613,8 @@ def check_working_directory(expandvars = None,relocate = True,):- """Decide what to do about the current working directory.-- Returns (message, colour, fatal). `fatal` is the caller's cue to exit 1;- a message with fatal False is a warning printed after a successful move.- """+ """Decide what to do about the cwd, returning (message, colour, fatal); fatal means exit 1,+ while a non-fatal message is a warning printed after a successful move."""if platform != "win32":return None, None, Falsediff --git a/unsloth_cli/commands/_password_prompt.py b/unsloth_cli/commands/_password_prompt.pyindex 741fc94aa73..237c33b7883 100644--- a/unsloth_cli/commands/_password_prompt.py+++ b/unsloth_cli/commands/_password_prompt.py@@ -30,12 +30,8 @@ class PromptUnattended(Exception):def _wait_for_first_key(timeout: float) -> bool:- """Whether a keystroke arrived within ``timeout`` seconds.-- Requires cbreak mode already set: canonical mode holds input until a newline,- so the fd would not become readable on the first character. True on any doubt- (the blocking behaviour).- """+ """Whether a keystroke arrived within timeout seconds; needs cbreak mode already set, since+ canonical mode holds input until a newline. True on any doubt (blocking)."""if os.name == "nt":import time@@ -287,8 +283,7 @@ def resolve_supplied_password(cli_value: "str | None", out: TextIO | None = Nonedef validate_new_password(candidate: str, verify_current: Callable[[str], bool]) -> "str | None":- """Error message if ``candidate`` is unacceptable (too short or equal to the- current password), else None. Same policy as the interactive loop."""+ """Error if candidate is short, has spaces, or repeats the current password; else None."""if len(candidate) < MIN_PASSWORD_LENGTH:return f"Password must be at least {MIN_PASSWORD_LENGTH} characters."if any(ch.isspace() for ch in candidate):diff --git a/unsloth_cli/commands/doctor.py b/unsloth_cli/commands/doctor.pyindex 7e8a0827366..ecc47147b29 100644--- a/unsloth_cli/commands/doctor.py+++ b/unsloth_cli/commands/doctor.py@@ -174,12 +174,9 @@ def _nvml_int(pynvml, name, default):def nvml_topology(pynvml, gpus: List[dict]):- """({(a, b): {"level": "PHB", "nvlink": bool, "p2p_read": bool}} keyed by torch index, error).-- Handles are looked up by PCI bus id (else device UUID), since NVML numbers GPUs in- PCI order and ignores CUDA_VISIBLE_DEVICES / CUDA_DEVICE_ORDER, which renumber them.- A query a virtualised GPU refuses degrades that field instead of the whole table.- """+ """Returns ({(a, b): {level: PHB, nvlink: bool, p2p_read: bool}} keyed by torch index, error);+ handles by PCI bus id, else UUID, since NVML numbers GPUs in PCI order and ignores+ CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER; a refused query degrades only its field."""if pynvml is None:return None, "nvidia-ml-py is not installed"if len(gpus) < 2 or any(g["pci"] is None and not g.get("uuid") for g in gpus):@@ -325,11 +322,8 @@ def allreduce_smoke(extra_env: Optional[dict] = None,numel: int = 16 * 1024 * 1024,) -> dict:- """Run one all_reduce over `world` local ranks in fresh processes.-- Separate interpreters rather than threads: a hung NCCL communicator can only be- recovered by killing its process, and the doctor must answer instead of hanging.- """+ """Run one all_reduce over world local ranks in fresh processes: a hung NCCL communicator only+ recovers by killing its process, so the doctor must not hang."""env = dict(os.environ)env.update(MASTER_ADDR = "127.0.0.1",@@ -387,8 +381,7 @@ def allreduce_smoke(f.seek(0)outputs.append(f.read())finally:- # Ctrl-C on a hung run must not leave ranks holding GPU contexts behind. Bounded:- # a rank stuck in an uninterruptible driver call may never be reaped.+ # Ctrl-C must not orphan GPU ranks; reaping is bounded, as a stuck rank may survive.for q in procs:if q.poll() is None:q.kill()diff --git a/unsloth_cli/commands/mcp.py b/unsloth_cli/commands/mcp.pyindex 430ab245873..3307d5405a8 100644--- a/unsloth_cli/commands/mcp.py+++ b/unsloth_cli/commands/mcp.py@@ -159,9 +159,8 @@ def codex_check(old_text: str, new_text: str, name: str, expected: dict) -> None"""Raise ValueError unless the splice changed exactly mcp_servers.NAME."""loads = _toml_loads()if loads is None:- # No TOML parser (Python < 3.11 without tomli): refuse any other mention of NAME, and- # anything that makes the line-based splice unsafe: a multi-line string can hold a- # line that looks like a table header, and a line opening with "[" can be array data.+ # With no TOML parser (Python < 3.11 without tomli), refuse other mentions of NAME and any+ # multi-line string or line opening with [ that could fool the splice.block = _codex_block(name, *expected.values())if name in new_text.replace(block, ""):raise ValueError(f"{name} is also defined in another form")diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.pyindex c36615adb92..c70f2dbf342 100644--- a/unsloth_cli/commands/start.py+++ b/unsloth_cli/commands/start.py@@ -1849,11 +1849,8 @@ def _loaded_models_response(key: str,timeout = 30,) -> dict:- """Raw listing of what this server has resident. Startup and key checks need no more.-- /v1/models answers the same question but waits for disk and media discovery first,- which on a slow scan folder outlasts the deadline below.- """+ """Raw listing of resident models, enough for startup and key checks; unlike /v1/models it skips+ disk and media discovery, which can outlast the deadline on a slow scan folder."""try:answer = _http_json("GET", f"{base}/api/inference/loaded-models", key, timeout = timeout)if isinstance(answer.get("data"), list):@@ -6254,8 +6251,7 @@ def _vibe_env(model: dict,request_body: Optional[dict] = None,) -> dict:- """Vibe settings as VIBE_* env vars: that layer outranks user and project config.toml, so- nothing is written to the user's Vibe config."""+ """VIBE_* env vars outrank config.toml, so the user's Vibe config is never written."""entry = {"name": model["id"], "provider": _VIBE_PROVIDER, "alias": _VIBE_MODEL_ALIAS}# Vibe sends its own temperature (0.2 by default) with every request.temperature = (request_body or {}).get("temperature")@@ -6572,13 +6568,8 @@ def write_dsh_patch(path: Path,request_body: Optional[dict] = None,) -> None:- """Write the dsh loader patch that points the booted profile at Unsloth.-- dsh 0.1.7 dropped `settings.yaml`: it now imports a leftover one into the profile only- after the first boot has settled, so that boot still runs on the DeepSeek default. A- `--patch` overlay is read at boot on every dsh release this supports, and the file is- Unsloth's own, so it is rewritten whole rather than merged.- """+ """dsh 0.1.7 dropped settings.yaml, which only applies after a first boot still on the DeepSeek+ default; the --patch overlay is read at boot and rewritten whole, as it is Unsloth's own."""import yamlmodel_entry = {"id": model["id"]}@@ -8709,8 +8700,7 @@ def vibe(# Vibe keeps its own home; the env layer pins provider and model above its config files.request_body = server_options.request_body()if "temperature" not in request_body:- # Vibe always sends a temperature, which the server honours over the model's- # recommended one, so pass the recommendation along explicitly.+ # Vibe always sends a temperature that beats the model's recommendation; pass that on.status = _inference_status(base, key, entry["id"])recommended = (status.get("inference") or {}).get("temperature")if recommended is not None and any(diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex 809520efa79..32ec30189be 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -338,8 +338,7 @@ def _studio_runtime_launch_guard(*, inherited: bool = False, wait: bool = False)def _stream_for_subprocess(stream):- """Return *stream* if it has a real OS fd, else None: Windows will not inherit std handles- unless passed explicitly, and a test-captured stream has no fd."""+ """Return None without a real OS fd; Windows needs std handles passed explicitly."""if stream is None:return Nonetry:@@ -371,8 +370,7 @@ def _is_wildcard_bind(host: str) -> bool:def _openable_host_for_bind(run_mod, host: str) -> str:- """Host to print in a URL: the LAN address when one resolves, else loopback. A- wildcard bind must never be printed as-is; no browser can open it."""+ """URL host: the LAN address if one resolves, else loopback, never a wildcard bind."""share_host = _network_share_host_for_bind(run_mod, host)if _is_wildcard_bind(share_host):return _loopback_bind_host_for(host)@@ -505,8 +503,7 @@ def _running_in_studio_venv(venv_dir: Path) -> bool:def _managed_cli_site_packages_layout(python: Path) -> bool:- """On-disk hint that the venv still carries the CLI. Weaker than the import probe: an empty- unsloth_cli/ or an orphaned dist-info passes here."""+ """Weaker than the import probe: an empty unsloth_cli/ or orphaned dist-info still passes."""site_packages = python.parent.parent / "Lib" / "site-packages"if (site_packages / "unsloth_cli").is_dir():return True@@ -853,14 +850,9 @@ def _wait_for_server(def _cli_api_key_secret_path(name: str) -> Path:- """Cache path for the raw API key named *name*.-- Identity is the digest; the stem is only so a human can tell the files apart.- Sharing a stem would hand one label's credential to another (`foo/bar` vs- `foo?bar`, past the 64-char cut, `cli` vs `CLI` on APFS/NTFS). ASCII-only- keeps 64 chars at 64 bytes: NAME_MAX is 255 BYTES, so multibyte alnums made a- 282-byte name that failed to cache and re-minted every launch (#10595 again).- """+ """Identity is the digest, so a shared stem (foo/bar vs foo?bar, cli vs CLI) cannot share a+ credential; ASCII-only keeps names within NAME_MAX (255 bytes); multibyte names were+ re-minted every launch (issue 10595)."""safe = "".join(ch if (ch.isascii() and ch.isalnum()) or ch in "-_" else "_" for ch in name).strip("_")@@ -1204,8 +1196,7 @@ _UNATTENDED_PROMPT_DONE_ENV = "UNSLOTH_STUDIO_UNATTENDED_PROMPT_DONE"def _deadline_sentence() -> str:- """Say what will actually happen: BOOTSTRAP_TIMEOUT=0 arms no deadline, and promising one an- operator acts on is worse than saying nothing."""+ """Say only what happens: BOOTSTRAP_TIMEOUT=0 arms no deadline, so promising one misleads."""if _bootstrap_deadline_active():return ("Unsloth shuts down after the bootstrap deadline "@@ -1317,9 +1308,8 @@ def _cli_update_password(def _apply_supplied_password_before_launch(supplied_password: "str | None") -> None:- """Non-interactively set the INITIAL admin password before the server binds. Only ever the- FIRST one: an override would be an auth bypass, and the parent runs it so the secret never- crosses to child argv."""+ """Set the INITIAL admin password before the server binds, and only the first: an override would+ be an auth bypass; the parent runs it so the secret stays out of child argv."""if not supplied_password:returntry:@@ -3175,8 +3165,7 @@ PID_FILE_GLOB = "studio-*.pid"def _pid_alive(pid: int) -> bool:- """Return True if a process with ``pid`` exists. os.kill(pid, 0) raises WinError 87 for- every pid on Windows, so use tasklist there."""+ """True if pid exists; os.kill(pid, 0) raises WinError 87 on Windows, so tasklist is used."""if sys.platform == "win32":try:out = subprocess.run(@@ -3229,8 +3218,7 @@ def _read_pid_record(path: Path) -> "tuple[int, RecordedStart, str | None] | Nondef _unlink_quietly(path: Path) -> None:- """Drop a record without letting one bad file end the loop: an undeletable record must- not stop us reaching the other servers."""+ """Unlink quietly: an undeletable record must not stop us reaching the other servers."""try:path.unlink(missing_ok = True)except OSError as e:@@ -3250,9 +3238,8 @@ def _report_unreadable(paths: "list[Path]") -> None:def _pid_file_entries(unreadable: "list[Path] | None" = None,) -> "list[tuple[int, list[RecordedStart], list[Path]]]":- """(pid, create_times, files) per recorded server, including the legacy studio.pid. Grouped by- PID: a second SIGTERM would hard-kill a server mid-shutdown. Every recorded time is kept, so a- stale file cannot veto a live server."""+ """Per recorded server (pid, create_times, files), grouped by PID so a second SIGTERM cannot+ hard-kill mid-shutdown; stale files cannot veto a live server."""by_pid: "dict[int, tuple[list[RecordedStart], list[Path]]]" = {}try:paths = sorted(STUDIO_HOME.glob(PID_FILE_GLOB)) + [_PID_FILE]@@ -3743,12 +3730,9 @@ _UV_TRUE = ("1", "y", "yes", "t", "true", "on")def _uv_no_cache_requested() -> bool:- """uv --no-cache caches in a temporary directory and discards it, outranks --cache-dir,- and recording it would aim later updates at a cache that never existed.-- Not stripped, matching clap and therefore both installers: uv rejects a padded value- outright rather than reading it as true, so ` true ` leaves uv's cache ON and this must- not stand the selection down for it."""+ """uv --no-cache discards its cache and outranks --cache-dir, so recording it aims updates at a+ nonexistent cache; UV_NO_CACHE is not stripped, so a padded value leaves the uv cache on and+ this must not stand the selection down."""return (os.environ.get("UV_NO_CACHE") or "").lower() in _UV_TRUE@@ -3919,8 +3903,7 @@ def _uv_cache_is_writable(cache_dir: Path) -> bool:def _with_studio_uv_cache(env: Optional[dict], cwd: Optional[Path] = None) -> Optional[dict]:- """An update reached neither installer nor _setup_cache_env, so uv re-downloaded- what the install had just fetched."""+ """Without the installer or _setup_cache_env, uv re-downloads what the install fetched."""if (os.environ.get("UV_CACHE_DIR") or "").strip():return envif _uv_no_cache_requested():@@ -4661,9 +4644,8 @@ class _WindowsLauncherUpdateTransaction:return Falsedef _move_launcher_aside(self) -> None:- """Free the canonical path so the installer can publish a replacement: uv deletes a third-party- console script outright and hard-errors when it is in use, after which the pip fallback- no-ops. Non-fatal; it costs only the upgrade."""+ """Frees the canonical launcher path so the installer can publish a replacement (uv deletes+ third-party scripts and hard-errors when in use); non-fatal, it costs only the upgrade."""assert self.launcher is not None and self.stale is not Noneif not self._is_valid_pe(self.launcher):return@@ -4685,8 +4667,7 @@ class _WindowsLauncherUpdateTransaction:return Nonedef _recovery_candidates(self) -> List[Path]:- """Copies that could stand in for the launcher, best first. All are kept: passing the header- check does not make any of them runnable."""+ """Stand-in copies, best first; passing the header check does not make one runnable."""seen: List[Path] = []for path in (self.backup, self.stale, self.legacy_backup, self.shim):if path is None or not self._is_valid_pe(path):@@ -4717,9 +4698,8 @@ class _WindowsLauncherUpdateTransaction:return self._restore_failure_reason() is Nonedef _restore_failure_reason(self) -> Optional[str]:- """Put back the first copy that actually runs; return why the CLI still cannot, or None.- Under Application Control every --version dies in CreateProcess, so this degrades to the- shape check."""+ """Restore the first runnable copy, or return why the CLI still cannot run; under+ Application Control --version dies in CreateProcess, so only shape is checked."""if self._launcher_health_error() is None:return Nonecandidates = self._recovery_candidates()@@ -4759,9 +4739,8 @@ class _WindowsLauncherUpdateTransaction:return Nonedef _launcher_health_error(self) -> Optional[str]:- """Whether the update left a working CLI. Identical to _launcher_runs_error except for an- Application Control denial, which happens before Python starts: ask the signed interpreter,- or every update on such a machine rolls a good install back (#8490)."""+ """Whether the update left a working CLI; asks the signed interpreter on an Application+ Control denial, else good installs roll back (issue 8490)."""error = self._launcher_runs_error()if error is self._POLICY_BLOCKED:return self._interpreter_health_error(error)diff --git a/unsloth_cli/commands/train.py b/unsloth_cli/commands/train.pyindex c180d1bf548..d497e90bf01 100644--- a/unsloth_cli/commands/train.py+++ b/unsloth_cli/commands/train.py@@ -57,14 +57,9 @@ def _create_cli_trainer(model_name: str, hf_token: Optional[str]):def _optimizer_for_host(requested: Optional[str] = None) -> str:- """The CLI exposes no --optim, so trainer.py would fall back to its own `adamw_8bit`- literal, which cannot complete a step on Intel XPU. Resolve the same device policy the- Studio route and worker config use, so `unsloth train` lands on the same optimizer a- Studio run on this host would. Non-XPU hosts keep `adamw_8bit` exactly as before.-- Takes `requested` rather than only filling a default, so a future --optim carrying a- bitsandbytes name is normalized too instead of reaching the trainer unchanged.- """+ """The CLI has no --optim, so trainer.py's adamw_8bit default cannot finish a step on Intel XPU;+ resolve the Studio device policy here, keep adamw_8bit elsewhere, and normalize any requested+ name."""ensure_studio_backend_path()with studio_backend_imports("unsloth train"):from studio.backend.core.training.training import (diff --git a/unsloth_cli/options.py b/unsloth_cli/options.pyindex 8a6d4abe75d..3816ec14501 100644--- a/unsloth_cli/options.py+++ b/unsloth_cli/options.py@@ -56,10 +56,8 @@ def _get_python_type(annotation: Any) -> type:def _collect_config_fields(config_class: type[BaseModel]) -> list[tuple[str, Any]]:- """- Flatten config class fields (recursing into nested models) into a list of- (name, field_info) tuples. Raises ValueError on duplicate field names.- """+ """Flatten config fields (recursing into nested models) into (name, field_info) tuples; raises+ ValueError on duplicate field names."""fields = []seen_names: set[str] = set()@@ -80,12 +78,8 @@ def _collect_config_fields(config_class: type[BaseModel]) -> list[tuple[str, Anydef add_options_from_config(config_class: type[BaseModel]) -> Callable:- """- Decorator that adds CLI options for all fields in a Pydantic config model.-- The decorated function should declare a `config_overrides: dict = None` parameter- which will receive a dict of all CLI-provided config values.- """+ """Decorator adding CLI options for every config model field; the function should declare a+ config_overrides: dict = None parameter, which receives all CLI-provided values."""fields = _collect_config_fields(config_class)field_names = {name for name, _field_info in fields}diff --git a/unsloth_cli/tests/test_claude_subagent_mcp.py b/unsloth_cli/tests/test_claude_subagent_mcp.pyindex 58968ffe413..1407a3b1e28 100644--- a/unsloth_cli/tests/test_claude_subagent_mcp.py+++ b/unsloth_cli/tests/test_claude_subagent_mcp.py@@ -535,8 +535,7 @@ def test_read_only_local_child_uses_plan_mode(monkeypatch, tmp_path):command = captured["command"]assert command[command.index("--permission-mode") + 1] == "plan"assert command[command.index("--tools") + 1] == "Read,Grep,Glob,ExitPlanMode"- # No Bash: plan mode routes it through a classifier served by this same local model, so a- # "read-only" child with Bash can still write files.+ # No Bash: plan-mode classifier runs on this same local model, so Bash could still write.prompt = command[command.index("--append-system-prompt") + 1]assert "read-only local coding subagent" in promptdiff --git a/unsloth_cli/tests/test_eval.py b/unsloth_cli/tests/test_eval.pyindex 182bad150f0..2abc7743a91 100644--- a/unsloth_cli/tests/test_eval.py+++ b/unsloth_cli/tests/test_eval.py@@ -875,8 +875,7 @@ def test_silence_keeps_the_reconfigured_stdout_encoding(tmp_path):@pytest.mark.parametrize("backend", ["unsloth", "hf"])def test_gpu_memory_utilization_says_it_only_applies_to_vllm(env, monkeypatch, tmp_path, backend):- """Only the vllm branch forwards it, so a user capping memory on another backend would- otherwise read the dropped cap as an OOM."""+ """Only vllm forwards it, so a cap dropped on other backends would read as an OOM."""result = _run("org/model","--tasks",diff --git a/unsloth_cli/tests/test_studio_password_prompt.py b/unsloth_cli/tests/test_studio_password_prompt.pyindex 7a9b047625a..3d9170a9042 100644--- a/unsloth_cli/tests/test_studio_password_prompt.py+++ b/unsloth_cli/tests/test_studio_password_prompt.py@@ -166,8 +166,7 @@ def _install_prompt_env(interactive,scripted = _NEW_PW,):- """Tmp STUDIO_HOME + fake tty + scripted prompt. Returns the event log that- records prompt calls and re-exec argv in order."""+ """Temp STUDIO_HOME and fake tty with scripted prompts; returns the ordered event log."""studio_mod = _studio()events = []@@ -218,8 +217,7 @@ def _install_run_reexec(monkeypatch, events):)fake_bin = fake_venv / "bin" / "unsloth"real_is_file = Path.is_file- # Pin platform.system() too: the launcher name comes from it, so a Windows runner would miss the- # POSIX fixture.+ # Pin platform.system() too: launcher names derive from it, else Windows misses POSIX.monkeypatch.setattr(studio_mod.platform, "system", lambda: "Linux")monkeypatch.setattr(Path,@@ -671,9 +669,8 @@ def test_studio_default_non_tty_fails_closed_when_bootstrap_removal_fails(monkeyclass _FailingSelectConn:- """Wrap a real auth connection but raise on the gate's must_change SELECT,- so seeding + commit still happen and only the read-back fails (a locked-DB- window that lands after _ensure_cli_default_admin already wrote the file)."""+ """Wrap a real auth connection, raising only on the must_change SELECT, so seeding and commit+ still happen and only the read-back fails (a locked-DB window)."""def __init__(self, inner):self._inner = innerdiff --git a/unsloth_cli/tests/test_studio_refresh_shortcuts_installer_source.py b/unsloth_cli/tests/test_studio_refresh_shortcuts_installer_source.pyindex 27070404eaf..a42c52a8363 100644--- a/unsloth_cli/tests/test_studio_refresh_shortcuts_installer_source.py+++ b/unsloth_cli/tests/test_studio_refresh_shortcuts_installer_source.py@@ -29,9 +29,8 @@ class _Result:def _posix(monkeypatch, tmp_path):- """POSIX refresh with no checkout in sight, the shape of a wheel install. The tests run- from a clone, so _PACKAGE_ROOT would otherwise short-circuit every fetch.- """+ """POSIX refresh with no checkout, the shape of a wheel install; tests run from a clone, so+ _PACKAGE_ROOT would short-circuit every fetch."""studio = _studio()monkeypatch.setattr(studio.platform, "system", lambda: "Linux")monkeypatch.setattr(studio, "_PACKAGE_ROOT", tmp_path / "no-checkout-here")@@ -321,11 +320,8 @@ def test_markers_do_not_pin_internal_function_names():def test_a_local_installer_that_cannot_be_launched_falls_back_to_the_network(monkeypatch, tmp_path):- """Pre-refactor the candidate loop caught the exec OSError and carried on.-- A machine that cannot spawn bash for the checkout must still reach the fetch, or a- refactor that only reorganised the code would have stopped refreshing launchers.- """+ """A checkout installer that cannot be launched must still fall through to the network fetch;+ the old loop caught the exec OSError and carried on."""studio = _studio()checkout = tmp_path / "checkout"checkout.mkdir()@@ -374,9 +370,8 @@ def test_building_the_opener_never_mutates_global_urllib(monkeypatch):def test_a_second_on_disk_installer_is_tried_before_the_network(monkeypatch, tmp_path):- """The old loop probed and launched in one pass, so an unlaunchable candidate left- the next one to try. Selecting only the first match would drop that second chance- and reach for the network while a usable installer sat on disk."""+ """The old loop probed and launched in one pass, so an unlaunchable candidate left the next to+ try before the network; picking only the first match would skip a usable on-disk installer."""studio = _studio()local = tmp_path / "local"pkg = tmp_path / "pkg"diff --git a/unsloth_cli/tests/test_studio_run_parallel_flag.py b/unsloth_cli/tests/test_studio_run_parallel_flag.pyindex 784ba247d86..01009db025f 100644--- a/unsloth_cli/tests/test_studio_run_parallel_flag.py+++ b/unsloth_cli/tests/test_studio_run_parallel_flag.py@@ -21,8 +21,7 @@ if str(_REPO_ROOT) not in sys.path:def _load_run_command():- """Import `studio` without triggering server start; backend imports- are lazy inside run()."""+ """Import studio without starting the server; backend imports are lazy inside run()."""from unsloth_cli.commands import studio as _studioreturn _studio@@ -347,8 +346,7 @@ def test_in_venv_child_reports_bound_port_before_start_api_key(def test_run_default_sets_tool_call_env(monkeypatch):- """Plain `unsloth run` enables healing and nudging via the inherited env- (written before the re-exec so the child server picks them up at import)."""+ """Plain run enables healing and nudging via the inherited env, set before the re-exec."""studio_mod = _load_run_command()monkeypatch.delenv("UNSLOTH_DISABLE_TOOL_CALL_HEALING", raising = False)monkeypatch.delenv("UNSLOTH_TOOL_CALL_NUDGE", raising = False)@@ -372,8 +370,7 @@ def test_run_disable_flags_set_tool_call_env(monkeypatch):@pytest.mark.parametrize("inherited", ["0", "false", "False", "no", ""])def test_run_omitted_flag_respects_inherited_env(monkeypatch, inherited):- """When the flag is omitted, a value the parent set (e.g. `unsloth start`) wins- instead of being reset to the default."""+ """Omitted flag keeps a value the parent set (e.g. unsloth start) instead of resetting it."""studio_mod = _load_run_command()monkeypatch.setenv("UNSLOTH_TOOL_CALL_NUDGE", inherited)monkeypatch.delenv("UNSLOTH_DISABLE_TOOL_CALL_HEALING", raising = False)@@ -514,8 +511,7 @@ def test_reexec_forwards_speculative_options(monkeypatch):def test_reexec_forwards_dflash_speculative_type(monkeypatch):- """SpeculativeType is what Typer validates the option against, so a mode missing- from the literal is rejected before any loading code runs."""+ """Typer validates the option against SpeculativeType; a mode missing from it fails early."""result, captured = _invoke_run(monkeypatch,_BASE + ["--speculative-type", "dflash"],@@ -704,9 +700,8 @@ def test_load_model_http_payload_for_dspark(monkeypatch):def test_load_model_http_fails_on_a_deferred_error(monkeypatch):- """A slow load commits its 200 and pads the body (routes/inference.py- _tunnel_safe_json), so a late failure arrives in-band; it must still surface as the- RuntimeError `run` reports, not as a successful load."""+ """A slow load commits its 200 and pads the body, so a late failure arrives in-band and must+ still raise the RuntimeError run reports, not a successful load."""studio_mod = _load_run_command()def urlopen(request, timeout):@@ -788,9 +783,8 @@ def test_context_length_banner_line_omits_unknown_values(value):],)def test_reexec_forwards_load_in_4bit_in_both_directions(monkeypatch, user_flag, expected_in_child):- """Re-exec must emit the chosen polarity (or the typer default),- so a future default flip on one layer can't silently invert- behaviour for users who never typed the flag."""+ """Re-exec must forward the chosen polarity or the typer default, so a default flip on one layer+ cannot silently invert behaviour for users who never typed the flag."""extras = [user_flag] if user_flag else []result, captured = _invoke_run(monkeypatch, _BASE + extras)assert len(captured) == 1@@ -860,8 +854,7 @@ def test_studio_default_rejects_api_only_when_subcommand_invoked():def test_studio_default_default_parallel_with_subcommand_does_not_error():- """Omitting --parallel on the group must still let subcommands- run; the group's default 1 is benign."""+ """Omitting --parallel on the group must not block subcommands; its default 1 is benign."""studio_mod = _load_run_command()import typer as _typerdiff --git a/unsloth_cli/tests/test_studio_run_short_alias_clashes.py b/unsloth_cli/tests/test_studio_run_short_alias_clashes.pyindex 6cb0ab15de9..254f18b00e4 100644--- a/unsloth_cli/tests/test_studio_run_short_alias_clashes.py+++ b/unsloth_cli/tests/test_studio_run_short_alias_clashes.py@@ -188,8 +188,7 @@ def test_legacy_model_alias_conflicts_with_long_form(monkeypatch):def test_clustered_tokens_are_not_promoted(monkeypatch):- """`-mg` / `-fa` / `-fitt` are llama-server flags and must survive- in the tail even though they start with `-m` / `-f`."""+ """llama-server flags -mg, -fa and -fitt must survive, though they start with -m or -f."""captured = _invoke(monkeypatch,["--model", "X", "-mg", "0", "-fa", "-fitt", "1024"],@@ -366,8 +365,7 @@ def test_expand_np_handles_signed_attached_forms(monkeypatch, attached, expected[("-np8x", "8x"), ("-np-1foo", "-1foo"), ("-np9bar", "9bar")],)def test_expand_np_rewrites_numeric_prefix_even_with_junk(monkeypatch, attached, expected_suffix):- """`-np8x` would surface as a baffling --port error; rewriting to- `-np 8x` makes typer report against `-np` where it was typed."""+ """Rewrite -np8x as -np 8x so errors cite the typed -np, not a baffling --port."""monkeypatch.setattr(sys, "argv", ["unsloth", "run", attached])_studio_mod()._expand_attached_np_short()assert sys.argv == ["unsloth", "run", "-np", expected_suffix]@@ -395,8 +393,7 @@ def test_consume_helper_rejects_empty_inline_value():],)def test_third_party_importers_do_not_trigger_np_rewrite(monkeypatch, third_party_argv0):- """Only the `unsloth` / `unsloth.exe` console-script may run the- canonicaliser; third-party scripts must keep their argv intact."""+ """Only unsloth and unsloth.exe may run the canonicaliser; third-party scripts keep argv."""import os as _osimport importlibdiff --git a/unsloth_cli/tests/test_studio_update_uv_cache.py b/unsloth_cli/tests/test_studio_update_uv_cache.pyindex c9b0e58417c..be4f17eca3b 100644--- a/unsloth_cli/tests/test_studio_update_uv_cache.py+++ b/unsloth_cli/tests/test_studio_update_uv_cache.py@@ -113,8 +113,7 @@ def test_an_explicit_uv_cache_dir_still_wins(monkeypatch, tmp_path, caches):def test_verbose_keeps_its_own_flag_alongside_the_cache(monkeypatch, tmp_path, caches):- """The verbose branch builds env first; the cache seeding must extend it, not- replace it."""+ """The verbose branch builds env first; cache seeding must extend that env, not replace it."""studio = _studio()studio_cache, _default = caches_fill(studio_cache)@@ -167,9 +166,8 @@ def test_the_windows_branch_gets_the_same_cache(monkeypatch, tmp_path, caches):def test_a_unicode_digit_version_is_not_a_bucket(monkeypatch, tmp_path, caches):- """str.isdigit() is true for Arabic-Indic and superscript digits; the sh `*[!0-9]*` case- and the PowerShell \\A[0-9]+\\z both reject them, and uv writes ASCII. Python was the- only one of the three that would have counted such a directory as warmth."""+ """str.isdigit() accepts Arabic-Indic and superscript digits, but the sh and PowerShell bucket+ checks reject them since uv writes ASCII; Python alone would count them as warm."""studio = _studio()assert studio._uv_is_bucket_name("archive-v0")assert not studio._uv_is_bucket_name("archive-v\u0661")@@ -461,9 +459,8 @@ def test_an_emptied_recorded_cache_does_not_outrank_a_warm_one(monkeypatch, tmp_def test_a_reinstall_into_a_custom_cache_is_not_shadowed_by_the_old_marker(monkeypatch, tmp_path, caches):- """A reinstall with a nonblank UV_CACHE_DIR fills that cache, so it is recorded too:- a stale marker would aim later updates at a cache this install never filled, and both- hold packages, so nothing downstream could notice."""+ """A reinstall with a nonblank UV_CACHE_DIR must record that cache, since a stale marker would+ aim later updates at a cache it never filled, and nothing downstream would notice."""studio_cache, _default = cachescustom = tmp_path / "caller cache"_fill(studio_cache)@@ -638,9 +635,8 @@ def test_the_backfill_replaces_a_symlink_rather_than_its_target(monkeypatch, tmp@pytest.mark.skipif(os.name != "posix", reason = "POSIX filesystem byte semantics")def test_a_cache_path_that_is_not_utf_8_is_recorded_and_read_back(monkeypatch, tmp_path):- """An undecodable POSIX path arrives as surrogates, and encoding those raises- UnicodeEncodeError, not an OSError, so it escaped the best-effort handler and failed- an update whose setup had succeeded, with its marker already gone."""+ """Undecodable POSIX paths hold surrogates that raise UnicodeEncodeError, not OSError, escaping+ the best-effort handler and failing an update whose setup had succeeded."""studio = _studio()weird = (tmp_path / os.fsdecode(b"caf\xe9-cache")).resolve()_fill(weird)@@ -689,9 +685,8 @@ def test_the_probe_asks_from_the_directory_setup_will_ask_from(monkeypatch, tmp_def test_the_windows_handoff_probes_from_the_directory_it_hands_the_child(monkeypatch, tmp_path):- """setup.ps1 never changes directory: it hands install_python_stack.py the cwd it- inherited (setup.ps1:5191), so probing the script's directory would answer for a- configuration the child never sees, and that answer is forced on it."""+ """setup.ps1 never changes directory and hands install_python_stack.py its inherited cwd+ (setup.ps1:5191), so the probe must run from that cwd, not the script directory."""studio = _studio()repo_root = tmp_path / "repo"(repo_root / "studio").mkdir(parents = True)@@ -919,9 +914,8 @@ def test_files_outside_a_bucket_are_not_warm(tmp_path):def test_a_recorded_cache_that_is_no_longer_writable_loses_to_the_studio_cache(monkeypatch, tmp_path, caches):- """setup treats the value this hands it as the caller's choice and never probes it- again, and uv aborts on a cache it cannot write, so a share remounted read-only since- the install has to lose here."""+ """setup treats the recorded cache handed to it as the caller's choice and never probes it+ again, and uv aborts on an unwritable cache, so a share remounted read-only must lose."""if getattr(os, "geteuid", lambda: 1)() == 0:pytest.skip("root can write anywhere")studio = _studio()@@ -946,13 +940,9 @@ def test_a_recorded_cache_that_is_no_longer_writable_loses_to_the_studio_cache(os.name != "posix", reason = "POSIX mode bits; chmod(0o555) denies nothing on Windows")def test_an_unwritable_studio_cache_is_not_forced_on_setup(monkeypatch, tmp_path, caches):- """The last fallback was the one branch here that never probed.-- setup.sh treats any UV_CACHE_DIR it inherits as the caller's choice and skips its own- write probe, so handing it a Studio cache uv cannot write aborts every uv command in- the update. Leaving the variable alone lets setup.sh probe and fall back to uv's- default, which is what it does when it runs standalone.- """+ """setup.sh treats an inherited UV_CACHE_DIR as the caller's choice and skips its write probe,+ so an unwritable Studio cache would abort every uv command; leaving it unset lets setup probe+ and fall back to uv's default."""if getattr(os, "geteuid", lambda: 1)() == 0:pytest.skip("root can write anywhere")studio = _studio()@@ -991,9 +981,8 @@ def test_a_store_with_a_two_digit_version_is_probed(tmp_path):def test_a_mistyped_studio_home_is_not_materialised_by_the_probe(monkeypatch, tmp_path):- """setup.sh fails fast on a STUDIO_HOME override that does not exist, so a typo cannot- leave an empty workspace behind. Creating the cache under it first satisfies that guard- and the update runs on against a tree with no venv."""+ """setup.sh fails fast on a missing STUDIO_HOME override, so the probe must not create the cache+ under it; that would pass the guard and run against a tree with no venv."""studio = _studio()missing = tmp_path / "typo studio home"monkeypatch.setattr(studio, "STUDIO_HOME", missing)@@ -1033,9 +1022,8 @@ def test_a_dangling_symlink_where_a_store_belongs_is_rejected(tmp_path):os.name != "posix", reason = "POSIX mode bits; chmod(0o555) denies nothing on Windows")def test_a_case_folded_store_name_is_probed(monkeypatch, tmp_path):- """On APFS or NTFS `Python-V0` is the same path uv opens as `python-v0`. This box is ext4,- so the fold is stubbed: what is under test is that the probe acts on the answer, not that- it can measure a folding filesystem it does not have."""+ """On APFS or NTFS Python-V0 is the same path uv opens as python-v0; ext4 cannot show that, so+ the fold is stubbed and the test checks the probe acts on the answer."""if getattr(os, "geteuid", lambda: 1)() == 0:pytest.skip("root can write anywhere")studio = _studio()