unsloth/tests/studio/test_playwright_server_lifecycle.py
Daniel Han df8fb6a03b
Say both load fallbacks when both fire, and repair the two suites that guard it (#9189)
* Repair the two chat auto-load suites that #9173 left red on main

#9173 added a vision-projector fallback to the auto-load success toast. Both
of the suites that read that code broke on it, and both were green on the
commit immediately before (54b6ca4c3).

72 tests, in two different shapes:

1. tests/studio/test_chat_autoload_failure_gate.py, 71 failures. The harness
   slices autoLoadSmallestModel verbatim out of chat-adapter.ts and runs it, so
   anything the slice references must exist in PREAMBLE. mmprojFallbackMessage
   did not, which is a bare ReferenceError inside the retry loop; the loop
   catches it and scores it as a failed load, so every scenario fails as a
   wrong-model assertion. The file's own guard caught this and named the symbol,
   which is what it was written for after #7699 did the same thing.

   Stubbed as a function of the reason rather than a copy of the real
   three-message record. The value only reaches `options.description`, and these
   scenarios assert on which model loaded, never on toast copy, so copying
   user-facing strings in here would give them a second home to drift from.

2. tests/studio/test_model_picker_contracts.py, 1 failure. It asserted the
   literal `description: cpuFallbackReason`, and the mmproj branch went in front
   of it. The property held; only the spelling moved. Its own comment records
   this happening once already, when the CPU-fallback branch first appeared, so
   it now pins the property: the description varies on both fallback reasons and
   still has an undefined arm for the ordinary path.

   Scoped to the description EXPRESSION, not the whole helper. `cpuFallbackReason`
   is also a parameter name in the signature above, so a substring test over the
   block stays green with the CPU branch deleted outright -- the first cut of this
   check did exactly that, and mutation caught it.

Three mutations verified red: the description no longer driven by any fallback
reason, the CPU branch dropped, and the mmproj branch dropped.

4223 passed, 4 skipped.

* Say both fallbacks when both fire, not just the projector one

Both load paths wrote the toast description as

  mmprojFallbackReason ? mmprojMessage : cpuFallbackReason ? cpuMessage : undefined

so whenever both reasons are set the CPU-fallback sentence is dropped. The user
is told "loaded without vision" and never told the model is running on the CPU,
which reads as a deliberate, explained degradation rather than an unaccelerated
session.

The combination is reachable. On a CPU-fallback replay llama_cpp.py preserves
_cpu_fallback_reason (it clears it only when not _replaying_cpu_fallback) and
resets _mmproj_fallback_reason so the projector can fail again inside that same
launch. A low VRAM machine whose Vulkan backend crashed is exactly where the
projector then falls back too.

loadFallbackNotice() in mmproj-fallback.ts is now the single composition of the
title suffix, the description and the degraded flag, and both call sites delegate
to it. CPU_FALLBACK_MESSAGE moves there as well, so the two paths cannot describe
the same condition differently again.

Tests: four combined-case cases in mmproj-fallback.test.ts, verified red against
the shipped nested ternary. test_model_picker_contracts.py now asserts the call
sites delegate and pass both reasons rather than matching the old inline ternary,
and test_chat_autoload_failure_gate.py's stub mirrors the composition so a call
site dropping a reason stays detectable.

* Repin the CPU-fallback toast test to behaviour, and unbreak the queued-capabilities test

Two frontend suites were red.

auto-load-cpu-fallback-toast.test.ts matched the warn-vs-success choice and the
message text as substrings of showAutoLoadSuccess. Both moved into
loadFallbackNotice, which is the single definition the explicit-load path now
shares, so the match went stale. Matching the inline form again would go red on a
refactor that changes nothing a user can see, and would stay green if only one of
the two load paths kept the behaviour. It now calls loadFallbackNotice and asserts
the verdict, and separately asserts the call site delegates to it.

queued-model-capabilities.test.ts was red on main before this branch. #9173 added
`import { isTextOnlyMmprojFallback } from "./mmproj-fallback"` to
image-input-support.ts, which the test imports statically. Extensionless is the
right form -- 2314 of the 2367 relative imports under src/ are written that way,
and vite and tsconfig's "bundler" mode resolve them -- but the bare node loader
does not, and a static import resolves before any registration can run. The test
now registers the bundler resolver and imports dynamically, which is what
mmproj-fallback.test.ts already does for the same module.

Both files reformatted by biome; regex literals hoisted out of the test bodies
for useTopLevelRegex.

Full frontend suite: 3734 pass, 0 fail. typecheck clean. The 4 biome errors in
chat-adapter.ts and use-chat-model-runtime.ts are byte-identical on origin/main.

* Order the split-axis abort against the mmproj strip, not against its argument

test_tensor_split_abort_raises_early_to_layer_fallback has been red on main
since #9173, which renamed the text-only strip's argument from _last_spawn_cmd
to _vision_gpu_cmd. That rename is right: the strip should read the vision GPU
command rather than whatever was spawned last, and #9173 refreshes
_last_spawn_cmd from the result immediately after. The test was pinned to the
old argument name, so a rename with no behavioural content took it down.

The failure also misreported itself. `assert raise_idx < src.find(needle)` reads
as an ordering check but is two claims at once, and when the landmark is gone it
fails with "assert 249423 < -1" -- which says the ordering broke, when what
happened is that the landmark moved. Each landmark is now required to exist
before it is ordered, and says so.

The strip is matched on the call rather than on what is passed to it. What this
test is about is that the abort raises BEFORE the projector is discarded (#6659);
which command the strip reads from is that code's own business.

Checked both ways: removing the strip call from load_model goes red with a
message naming the missing landmark, and renaming the argument again stays green.

* Name the endpoints when the heavy-thread harness catches a stray request

The harness records every /api/ URL issued during a measured action, then keeps
only the count, so the failure reads

  let 2 /api/ requests reach the network during the measured actions

and stops there. It says an interaction paid for a round trip without saying
which one, and the reader has to bisect the frontend to learn what the harness
already knew and discarded.

It now reports the endpoints. Deduplicated and capped at eight, because the case
this instrument exists to catch is a request issued once per message, which would
otherwise print hundreds of copies of one line.

This is why it surfaced now: the step has not run on main since #9173, whose unit
test break fails earlier in the same job and short-circuits it. It was last green
at 54b6ca4c3. With the unit tests repaired on this branch the job reaches the
step again, and the first thing it needed to say was the one thing it did not.

* Skip the playwright harness tests on the module they need, not the package

Five tests guard themselves with `pytest.importorskip("playwright")` and then
import a harness that does `from playwright.sync_api import Page`. On the Repo
tests (CPU) runner the top-level name resolves as a namespace directory with no
sync_api inside it, so the guard passes and the import dies with

  ImportError: cannot import name 'Page' from 'playwright.sync_api' (unknown location)

A skip condition reported as a failure, on every branch, for as long as that
runner stays that way. It is red on #9202 and #9213 too, neither of which touches
any of this.

One of the two files already said what the guard was really for: "importing a
harness pulls in playwright.sync_api". It now checks that.

* Stop the fork-count store asking the server about threads it has never seen

Two fixes, both found by the heavy-thread smoke once it could name what it caught.

The smoke reported "let 2 /api/ requests reach the network during the measured
actions" and, with the endpoints now printed, they were

  POST /api/chat/threads/__LOCALID_lsQbsDZ/forks

A `__LOCALID_` thread has no server record, so that request can only 404, and
getThreadForkCounts already maps 404 to the empty map the entry starts as. It is
a round trip whose answer is known before it is sent.

Not a rounding error. A new chat is in exactly that state, and this store
refreshes on CHAT_HISTORY_UPDATED_EVENT, which fires once per streaming chunk, so
the first reply in a new chat paid one useless request per debounce window for as
long as it streamed. #8992 added the store to stop the chat getting slower as a
thread fills; excluding threads the server has never seen is the same intent.
thread-ids.ts already had the predicate.

Two tests: a local thread must not fetch on subscribe or on a burst of history
events, and a saved thread on screen beside it must still refresh -- the guard has
to be per thread, not a global off switch. They import the real
isAssistantLocalThreadId rather than restating the prefix, so the rule under test
cannot drift from the app's. Both go red with the guard removed.

Second fix, same job: the playwright skip guard. The previous commit moved it from
"playwright" to "playwright.sync_api" and it still failed, because sync_api
resolves as a namespace package on that runner too. Only the symbol the harnesses
import distinguishes a usable install, so the guard now checks for Page the way
the harness does. Verified both ways against a Page-less sync_api: it skips, and
it still proceeds when Page is there.

Frontend suite 3789 pass, typecheck clean, tests/studio 4237 pass.

* Bound and retry the Playwright browser install so a stall is not a silent 30 minutes

This step stalls. Three times in one day it sat in apt's download loop until the
job's 30-minute timeout killed it, while the sibling shards finished the whole job
in 4 to 9 minutes. Twice on #9202 and once on #9189, always the same step.

The cost is out of proportion to the cause. GitHub scores a job timeout as
"cancelled" rather than a failure, prints no reason, and skips every step after
it, so the chat shard reported nothing about the chat surface for what both times
turned out to be an infrastructure hiccup that cleared on a plain re-run of the
same commit.

A per-attempt `timeout` turns the stall into a failure instead of a silent wait,
and the retry is what actually recovers. The healthy time is about 2 minutes, so 8
per attempt is 4x headroom and a merely slow mirror will not trip it.
timeout-minutes bounds the pair in case `timeout` is outlived by an unkillable
child. Same reasoning, and the same wording, as the bounded prime-hf step in
studio-mac-ui-smoke.yml.

Both install steps in this file, since ui-smoke and ui-indicator run the identical
command. Left alone on mac and windows: neither passes --with-deps, so neither has
the apt phase this is about, and neither has been observed to stall.

* Make the Playwright install retry able to actually recover

The bound added in the previous commit worked: the stall became an 8m37s step
FAILURE with a complete log instead of a silent 30-minute cancellation, and the
log named the cause on the first try.

It also showed the retry could not work. playwright shells out to apt-get as root,
so terminating the python parent leaves that child alive holding the lock, and
attempt 2 died two seconds later with

  E: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 4578 (apt-get)

A retry that cannot succeed is worse than no retry: it buries the real reason
under a second, different failure. Attempt 2 now waits for the lock to clear, up
to two minutes, and only then takes it -- the holder is our own orphan and the
runner is a throwaway.

Two smaller things the same log exposed. --kill-after was missing, so a process
that ignores SIGTERM would have been waited on forever inside the step bound. And
the warning said "did not finish within 8 minutes" about a two-second exit, which
sends the next reader looking for a stall that never happened; it now separates
timeout's 124/137 from playwright refusing outright, and prints the status.

timeout-minutes 18 to 22 to cover two 8-minute attempts plus the lock wait, still
inside the job's 30.
2026-08-18 20:58:30 -07:00

223 lines
8.4 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""The dev-server lifecycle the browser smokes share.
Linux CI exercises the POSIX path only, and the Windows path is the one nobody runs until it
is broken on someone's machine. These drive both by injecting `os.name`, so the branch that
picks CREATE_NEW_PROCESS_GROUP and taskkill is checked on every run.
Everything here is monkeypatched: no npm, no browser, no sockets bound.
"""
from __future__ import annotations
import signal
import subprocess
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent))
import _playwright_robust as robust # noqa: E402
# Unix-only, so a Windows interpreter cannot name it even to drive the POSIX branch.
SIGKILL = getattr(signal, "SIGKILL", 9)
HARNESSES = (
"playwright_chat_autoscroll",
"playwright_research_freeze",
"playwright_strip_ansi_smoke",
"playwright_stream_pacing",
)
class _FakeProc:
"""A child that never dies, so both escalation steps are reachable."""
def __init__(self) -> None:
self.pid = 4242
self.stdout = None
self.returncode = None
def poll(self):
return None
def wait(self, timeout = None):
raise subprocess.TimeoutExpired("vite", timeout or 0)
@pytest.fixture
def no_signals(monkeypatch):
monkeypatch.setattr(robust, "_arm_teardown_signals", lambda: None)
monkeypatch.setattr(robust, "_LIVE_SERVERS", [])
@pytest.fixture
def posix_branch(monkeypatch, no_signals):
"""Drive the POSIX teardown from any host: os.killpg and signal.SIGKILL are Unix-only."""
monkeypatch.setattr(robust.os, "name", "posix")
monkeypatch.setattr(robust.signal, "SIGKILL", SIGKILL, raising = False)
@pytest.mark.parametrize("osname", ["posix", "nt"])
def test_start_vite_picks_the_platform_process_group(monkeypatch, no_signals, osname) -> None:
captured: dict = {}
monkeypatch.setattr(robust.os, "name", osname)
monkeypatch.setattr(robust, "_port_is_taken", lambda port, host: False)
monkeypatch.setattr(
robust.threading, "Thread", lambda **kw: type("T", (), {"start": lambda self: None})()
)
monkeypatch.setattr(
robust.subprocess, "Popen", lambda cmd, **kw: captured.update(cmd = cmd, kw = kw) or _FakeProc()
)
if osname == "nt":
monkeypatch.setattr(robust.subprocess, "CREATE_NEW_PROCESS_GROUP", 0x200, raising = False)
robust.start_vite(5199)
assert "--strictPort" in captured["cmd"], "a drifting port must fail, not pick another"
if osname == "nt":
assert captured["kw"]["creationflags"] == 0x200
assert "start_new_session" not in captured["kw"]
else:
# Without its own session, killing the npm wrapper orphans the node child.
assert captured["kw"]["start_new_session"] is True
assert "creationflags" not in captured["kw"]
def _require_playwright_page():
"""
Skip unless `from playwright.sync_api import Page` would actually work.
Two weaker guards were tried and both let this through. Checking the
top-level package passes because "playwright" resolves as a namespace
directory on the Repo tests (CPU) runner; checking "playwright.sync_api"
passes too, because that resolves as a namespace package as well. Only the
symbol the harnesses import is a real test of whether the import below can
succeed, so that is what is checked, and it is checked the way the harness
does it. The failure mode is a skip condition reported as
ImportError: cannot import name 'Page' from 'playwright.sync_api'
(unknown location)
on every branch, which costs an investigation each time it is seen.
"""
sync_api = pytest.importorskip("playwright.sync_api")
if not hasattr(sync_api, "Page"):
pytest.skip(
"playwright.sync_api resolved from "
f"{getattr(sync_api, '__file__', None) or list(getattr(sync_api, '__path__', []))} "
"but has no Page; playwright is not usably installed here"
)
def test_posix_teardown_signals_the_group_and_escalates(monkeypatch, posix_branch) -> None:
sent = []
monkeypatch.setattr(
robust.os, "killpg", lambda pid, sig: sent.append((pid, sig)), raising = False
)
robust.stop_process(_FakeProc())
assert sent == [(4242, signal.SIGTERM), (4242, SIGKILL)]
def test_windows_teardown_kills_the_tree_and_escalates(monkeypatch, no_signals) -> None:
calls = []
monkeypatch.setattr(robust.os, "name", "nt")
monkeypatch.setattr(robust.subprocess, "run", lambda cmd, **kw: calls.append(cmd))
robust.stop_process(_FakeProc())
assert calls == [
["taskkill", "/PID", "4242", "/T"],
["taskkill", "/PID", "4242", "/T", "/F"],
]
def test_teardown_never_raises_over_the_failure_that_called_it(monkeypatch, posix_branch) -> None:
"""stop_process runs from a `finally`. A child that outlives SIGKILL must not replace the
harness's real error with a TimeoutExpired."""
monkeypatch.setattr(robust.os, "killpg", lambda pid, sig: None, raising = False)
robust.stop_process(_FakeProc())
def test_teardown_tolerates_a_process_that_already_vanished(monkeypatch, posix_branch) -> None:
def gone(pid, sig):
raise ProcessLookupError
monkeypatch.setattr(robust.os, "killpg", gone, raising = False)
robust.stop_process(_FakeProc())
def test_an_occupied_port_is_refused_rather_than_measured(monkeypatch, no_signals) -> None:
"""--strictPort makes our vite exit, and the readiness poll would then be reading whatever
else holds the port. Refuse up front instead."""
monkeypatch.setattr(robust, "_port_is_taken", lambda port, host: True)
with pytest.raises(RuntimeError, match = "already serving"):
robust.start_vite(5199)
def test_readiness_gives_up_as_soon_as_our_server_dies(monkeypatch, no_signals) -> None:
"""Otherwise a dead server costs the full timeout, three times over, per CI run."""
class Dead:
returncode = 1
vite_tail = ["Port 5199 is already in use"]
def poll(self):
return 1
with pytest.raises(RuntimeError, match = "vite exited with code 1") as caught:
robust.wait_for_smoke_page(
"http://127.0.0.1:5199/x.html", "x.tsx", proc = Dead(), timeout_s = 30.0
)
assert "already in use" in str(caught.value), "vite's own reason should be surfaced"
@pytest.mark.parametrize("harness", HARNESSES)
def test_ports_do_not_collide_and_are_overridable(harness) -> None:
import re
src = (Path(__file__).resolve().parent / f"{harness}.py").read_text(encoding = "utf-8")
assert re.search(r'SMOKE_PORT",\s*"\d+"', src), f"{harness} has no SMOKE_PORT default"
def test_every_harness_picks_a_different_default_port() -> None:
import re
ports = {}
for harness in HARNESSES:
src = (Path(__file__).resolve().parent / f"{harness}.py").read_text(encoding = "utf-8")
ports[harness] = re.search(r'SMOKE_PORT",\s*"(\d+)"', src).group(1)
assert len(set(ports.values())) == len(HARNESSES), f"default ports collide: {ports}"
@pytest.mark.parametrize("harness", HARNESSES)
def test_an_empty_smoke_base_url_means_unset(harness, monkeypatch) -> None:
"""Exported-but-empty is common in shell wrappers. `in os.environ` would call it external
and then drive "" as the base URL."""
_require_playwright_page()
import importlib
monkeypatch.setenv("SMOKE_BASE_URL", "")
module = importlib.reload(importlib.import_module(harness))
try:
assert module.BASE.startswith("http://"), f"empty SMOKE_BASE_URL gave BASE={module.BASE!r}"
finally:
monkeypatch.delenv("SMOKE_BASE_URL", raising = False)
importlib.reload(module)
@pytest.mark.parametrize("harness", ("playwright_chat_autoscroll", "playwright_research_freeze"))
def test_an_external_smoke_base_url_is_still_honoured(harness, monkeypatch) -> None:
"""The documented pre-existing invocation. A harness that started its own server anyway
would fail on the busy-port check."""
_require_playwright_page()
import importlib
monkeypatch.setenv("SMOKE_BASE_URL", "http://127.0.0.1:9999")
module = importlib.reload(importlib.import_module(harness))
try:
assert module.BASE == "http://127.0.0.1:9999"
assert module.OWNS_SERVER is False
finally:
monkeypatch.delenv("SMOKE_BASE_URL", raising = False)
importlib.reload(module)