Skip to content

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.

Fail the mac tab-capability smoke on a backend that never comes back, not on a stall (#9711)

Daniel Han19d7d6486a4a
diff --git a/tests/studio/playwright_mac_tab_capabilities.py b/tests/studio/playwright_mac_tab_capabilities.py
index 9713096af3c..0fda86d0d59 100644
--- a/tests/studio/playwright_mac_tab_capabilities.py
+++ b/tests/studio/playwright_mac_tab_capabilities.py
@@ -21,6 +21,28 @@ Covers the two field failures from Unsloth Desktop 0.1.524-beta on Apple Silicon
C-extension imports, so probes time out while the process is perfectly alive.
This polls the backend across the whole warm window and asserts it survives.
+ "Survives" here means the backend answered again, not that it answered every
+ probe. A probe that times out while the process is alive is the symptom this
+ file was written about, so failing on one states the opposite of the thing it
+ is trying to prove. Run 32862298967 went red on one timed-out probe per route
+ out of eighteen, on a commit that changed one frontend unit test. The stall
+ behind it was real -- the server served no request at all for 10.0s and then
+ 33.2s, both windows ending on an /api/inference/status that had been in flight
+ throughout -- and it is worth a warning, but the backend was serving again
+ seconds later and was answering at the end of the run.
+
+ The verdict deliberately does not reproduce the launcher's watchdog. See
+ BackendSurvivalPoller.report: this phase runs no watchdog at all, and its 120s
+ window is shorter than the rule needs to reach any verdict. What fails here is
+ a backend that stops answering and never comes back, a non-200 answer, or a
+ refused port.
+
+ "Never comes back" is decided by await_recovery, which keeps watching after
+ sampling stops rather than letting one probe settle it. Sampling ends at an
+ arbitrary moment, so a stall straddling that boundary would otherwise fail a
+ run where the same stall a minute earlier only warned, which is this file's
+ own flake moved to the edge of the window instead of removed.
+
Runs against a live Studio; drives the real UI. Env contract matches the other
scripts here: BASE_URL, STUDIO_OLD_PW, PW_ART_DIR.
"""
@@ -58,14 +80,52 @@ NEW = os.environ.get("STUDIO_NEW_PW") or f"{OLD}-Rotated1!"
ART = Path(os.environ.get("PW_ART_DIR", "logs/playwright_mac_tabs"))
ART.mkdir(parents = True, exist_ok = True)
-# The watchdog kills after 3 consecutive failures at a 15s interval, and the
-# backend's startup grace is 300s. Outliving the grace is the whole point: a
-# backend that dies at t+66s (the reported crash) fails here.
+# How long to keep polling the backend. The reported crash landed at t+66s, so the
+# window has to reach well past that; the workflow narrows it to 120s because nothing in
+# this phase runs the launcher's watchdog and the longer window buys no extra evidence.
SURVIVAL_S = float(os.environ.get("STUDIO_MAC_SURVIVAL_S", "330"))
POLL_INTERVAL_S = float(os.environ.get("STUDIO_MAC_POLL_INTERVAL_S", "5"))
WALL_TIMEOUT_S = float(os.environ.get("STUDIO_UI_WALL_TIMEOUT_S", "900"))
# How long the forced-verdict check gives the row to settle into its pending state.
FORCED_PENDING_S = float(os.environ.get("STUDIO_MAC_FORCED_PENDING_S", "15"))
+# Matches HEALTH_PROBE_TIMEOUT in studio/src-tauri/src/commands.rs, so a probe here waits
+# as long as the launcher's does before calling it a miss. It is the only watchdog number
+# this file needs; see BackendSurvivalPoller.report for why it does not mirror the rest.
+PROBE_TIMEOUT_S = 10.0
+# How long to keep watching after sampling stops before calling a stall terminal.
+#
+# Sized from the stalls actually observed on this job rather than from a round number. In
+# run 32862298967 one macOS runner produced four of them, at 10.03s, 25.1s, 27.75s and
+# 33.2s, so a window that decides "this one never ended" has to comfortably clear 33.2s.
+# 90s is a little under three times that.
+#
+# This EXTENDS OBSERVATION; it is not a retry. A retry re-asks a question that already has
+# an answer and hopes for a better one, which is how a flaky test hides a real failure. The
+# question here has no answer yet: a probe that timed out says only that nothing came back
+# within its budget, and the run ended at an arbitrary point that may fall mid-stall. A
+# backend that is genuinely dead answers none of these probes either, so the window costs
+# these seconds only on a run that was already going to fail, and it cannot turn a real
+# death into a pass.
+RECOVERY_WINDOW_S = 90.0
+# Minimum spacing between recovery probes.
+#
+# _transport_kind classifies a connection reset as a stall rather than a death, on
+# purpose, because a reset means a listener accepted and then failed to finish. But a
+# reset comes back in about a millisecond, so an unpaced loop turns this window into
+# thousands of connections against a backend that is already in trouble, which can
+# prolong the fault it is waiting to clear. Spacing costs nothing on the case that
+# matters: a real stall spends the full probe budget before returning, so no pause is
+# added at all there.
+RECOVERY_PROBE_SPACING_S = 2.0
+# Health replies are a few hundred bytes; these bound a body read that is going wrong.
+_READ_CHUNK_BYTES = 65536
+_MAX_BODY_BYTES = 1 << 20
+
+LIVENESS_PATH = "/api/liveness"
+HEALTH_PATH = "/api/health"
+# Both are polled, and an answer from either is proof the backend was serving, matching
+# check_health_inner, which probes /api/liveness and falls back to /api/health.
+PROBE_PATHS = (LIVENESS_PATH, HEALTH_PATH)
# Every tab the user reported interacting with, plus the ones that share the
# chat-only gate. (route, nav row id, human name).
TABS = [
@@ -125,18 +185,223 @@ def fail(m: str) -> None:
_failed.append(m)
-def _get_json(path: str, timeout: float = 10.0) -> tuple[int, dict | None]:
+def _transport_kind(err: object) -> str:
+ """Classify a failed probe as a dead port or a stalled one.
+
+ ECONNREFUSED is the only error that proves nothing is bound: the kernel answers it
+ itself, immediately, without a server involved. Everything else here -- a budget that
+ ran out, a reset, a truncated response -- is a listener that accepted the connection
+ and then failed to finish, which is the stall this poller is measuring. Treating those
+ as death is what made a backend the launcher would have kept come out as a crash.
+ """
+ if isinstance(err, ConnectionRefusedError):
+ return "refused"
+ return "timeout"
+
+
+def _read_within(resp, deadline: float) -> str:
+ """Read a response body under one deadline for the whole read.
+
+ urllib's ``timeout`` is per socket operation, not per request. A peer that dribbles
+ bytes resets it on every chunk, so ``resp.read()`` can outlive any probe budget and,
+ here, the script's own wall-clock watchdog. These probes exist to decide whether the
+ backend is answering; a probe that never ends is the one outcome that must not
+ happen, because a hung job reports nothing and burns the runner.
+
+ read1() returns as soon as any data arrives rather than looping to fill the buffer,
+ so the deadline is checked between arrivals and the whole read is bounded by the
+ deadline plus at most one socket timeout.
+ """
+ reader = getattr(resp, "read1", None) or resp.read
+ chunks: list[bytes] = []
+ total = 0
+ while True:
+ if time.monotonic() >= deadline:
+ raise TimeoutError("response body did not finish inside the probe budget")
+ chunk = reader(_READ_CHUNK_BYTES)
+ if not chunk:
+ break
+ chunks.append(chunk)
+ total += len(chunk)
+ if total > _MAX_BODY_BYTES:
+ # A health reply is a few hundred bytes. Anything this large is a fault, and
+ # reading it to the end would be another way to sit here indefinitely.
+ raise TimeoutError("response body exceeded the probe's size cap")
+ return b"".join(chunks).decode("utf-8", "replace")
+
+
+def _probe_once(path: str, timeout: float) -> tuple[int, dict | None, str]:
+ """One GET attempt. Do not call directly; _get_json is what bounds it.
+
+ ``kind`` keeps apart the outcomes the desktop watchdog keeps apart, because they
+ are different failures and only one of them means the process is gone:
+
+ "ok" -- answered 200.
+ "http" -- answered, with a status that is not 200. The server is up and saying
+ something is wrong.
+ "timeout" -- no answer inside the budget. The port is still there; the server is
+ stalled. This is the case the watchdog spends extra patience on.
+ "refused" -- the connection was rejected. Nothing is listening, which is the only
+ one of these that means the backend died.
+
+ Collapsing all three into "status != 200", which this used to do, reports a 10s
+ stall in the same words as a crash.
+
+ Only ECONNREFUSED earns "refused". A reset or a half-read response means there WAS
+ a listener that failed to see the request through, which is a stall wearing a
+ different errno, so it is counted as one rather than as a death.
+ """
+ deadline = time.monotonic() + timeout
try:
with urllib.request.urlopen(f"{BASE}{path}", timeout = timeout) as resp:
- body = resp.read().decode("utf-8", "replace")
+ kind = "ok" if resp.status == 200 else "http"
+ body = _read_within(resp, deadline)
try:
- return resp.status, json.loads(body)
+ return resp.status, json.loads(body), kind
except ValueError:
- return resp.status, None
+ return resp.status, None, kind
except urllib.error.HTTPError as exc:
- return exc.code, None
- except Exception:
- return 0, None
+ return exc.code, None, "http"
+ except urllib.error.URLError as exc:
+ # A connect-time failure arrives wrapped, so the reason decides, not the class.
+ return 0, None, _transport_kind(exc.reason)
+ except Exception as exc:
+ # A read-time failure raises directly: TimeoutError, or an http.client error
+ # when the peer went away mid-response.
+ return 0, None, _transport_kind(exc)
+
+
+def _get_json(path: str, timeout: float = PROBE_TIMEOUT_S) -> tuple[int, dict | None, str]:
+ """GET *path* under a WHOLE-REQUEST deadline, returning (status, body, kind).
+
+ *timeout* bounds the entire probe: DNS, connect, response headers and body. It is
+ not a per-socket-operation timeout, and it must not be turned back into one.
+
+ That distinction is the whole reason this wrapper exists. urllib's own timeout
+ applies to each socket operation separately, so any peer that keeps sending
+ something, anything, more often than the timeout holds the call open forever. Each
+ layer was bounded in turn and the hole simply moved: capping the body read left
+ urlopen able to block indefinitely while response HEADERS trickled, because urlopen
+ has not returned yet at that point and the body deadline never gets to run. Bounding
+ the next layer down would only move it again, to the redirect chain or the TLS
+ handshake. A deadline outside all of them cannot be outflanked by any of them.
+
+ The probe therefore runs on a daemon thread and this joins it for at most *timeout*.
+ A join that expires is a timeout, and the thread is abandoned rather than waited on:
+ it is a daemon, so it cannot hold up interpreter exit, and _probe_once carries its
+ own body deadline and size cap so an abandoned one still lets go of its socket
+ instead of buffering forever. Those inner bounds are hygiene for the abandoned case;
+ the join is what actually enforces the budget.
+
+ Abandoning a thread per hung probe is affordable here because a backend that hangs
+ probes is one this script is about to report on and exit.
+ """
+ outcome: list[tuple[int, dict | None, str]] = []
+
+ def attempt() -> None:
+ outcome.append(_probe_once(path, timeout))
+
+ worker = threading.Thread(target = attempt, name = f"probe-{path}", daemon = True)
+ worker.start()
+ worker.join(timeout)
+ if outcome:
+ return outcome[0]
+ # Either still running, or it died without recording anything. Both are "no answer
+ # inside the budget", which is exactly what a timeout means here.
+ return 0, None, "timeout"
+
+
+def await_recovery(
+ window_s: float = RECOVERY_WINDOW_S, spacing_s: float = RECOVERY_PROBE_SPACING_S
+) -> tuple[str, int, float]:
+ """Watch the backend after sampling stops, until it answers or *window_s* elapses.
+
+ Returns (kind, status, seconds spent watching, probes), where *probes* are
+ sample-shaped records of every attempt, on the poller's clock.
+
+ Only a stall is worth waiting on, so this returns the moment a probe brings back
+ anything decisive: an answer of any status settles whether the process is alive, and
+ a refused port is already death. Neither gets the window.
+
+ Without this the verdict turned on one probe taken at whatever moment the UI drive
+ happened to finish, which put the arbitrary end of the survival window in charge of
+ the result. A 25s stall in the middle of the run warned and passed while the same
+ stall straddling the boundary failed, which is the flake this file was changed to
+ remove, moved to the edge rather than fixed.
+ """
+ began = time.monotonic()
+ probes: list[dict] = []
+ status, kind = 0, "timeout"
+ while True:
+ remaining = window_s - (time.monotonic() - began)
+ if probes and remaining <= 0:
+ # No time left to give a probe. Starting one anyway is how the watch ran
+ # past its own bound: the pacing sleep is clamped to the window, so the
+ # loop could arrive here with nothing left and still begin a full-budget
+ # request. That is the overrun the wall watchdog exists to catch, and it
+ # would terminate the run before the report it is waiting for.
+ break
+ # Never hand out more budget than the window has left either. A probe started
+ # near the end with the default PROBE_TIMEOUT_S can outlive the window by most
+ # of that budget on its own.
+ probe_began = time.monotonic()
+ status, _, kind = _get_json(LIVENESS_PATH, timeout = min(PROBE_TIMEOUT_S, remaining))
+ # Recorded in the same shape and on the same clock as the poller's samples, so
+ # the caller can lay them end to end. Without this a stall that starts after
+ # sampling stops is invisible: the verdict knows it waited, but nothing knows
+ # for how long or that anything went wrong, and a recovered stall that goes
+ # unreported is the one thing this window was added to avoid.
+ probes.append(
+ {
+ "t": round(time.monotonic(), 1),
+ "path": LIVENESS_PATH,
+ "status": status,
+ "kind": kind,
+ "ms": round((time.monotonic() - probe_began) * 1000, 1),
+ "inference_active": None,
+ "hardware_detecting": None,
+ "torch_warm_in_progress": None,
+ }
+ )
+ if kind != "timeout":
+ break
+ elapsed = time.monotonic() - began
+ if elapsed >= window_s:
+ break
+ # A probe that failed instantly did not spend its budget, so it was a reset
+ # rather than silence. Pace the next one, and never past the end of the window.
+ idle = spacing_s - (time.monotonic() - probe_began)
+ if idle > 0:
+ time.sleep(min(idle, window_s - elapsed))
+ return kind, status, round(time.monotonic() - began, 1), probes
+
+
+def _stall_windows(samples: list[dict]) -> list[tuple[float, float, bool]]:
+ """Spans where no probe answered, merged across both routes.
+
+ One answer from either route is proof the backend was serving at that instant, so an
+ answer closes whatever span was open. A span is closed at the moment the successful
+ probe was ISSUED rather than when it came back, which understates a stall that ended
+ mid-probe; the number here only ever feeds a warning, so erring short is the right
+ way to be wrong.
+
+ The third element says the span was still open when sampling stopped, which is the
+ only shape that can be a terminal stall.
+ """
+ ordered = sorted(samples, key = lambda s: s["t"])
+ spans: list[tuple[float, float, bool]] = []
+ open_start = None
+ for s in ordered:
+ began = s["t"] - s["ms"] / 1000.0
+ if s["kind"] == "ok":
+ if open_start is not None:
+ spans.append((open_start, began, False))
+ open_start = None
+ elif open_start is None:
+ open_start = began
+ if open_start is not None:
+ spans.append((open_start, ordered[-1]["t"], True))
+ return spans
class BackendSurvivalPoller:
@@ -157,15 +422,20 @@ class BackendSurvivalPoller:
def _run(self) -> None:
while not self.stop.is_set():
- for path in ("/api/liveness", "/api/health"):
+ for path in PROBE_PATHS:
began = time.monotonic()
- status, body = _get_json(path)
+ status, body, kind = _get_json(path)
self.samples.append(
{
"t": round(time.monotonic(), 1),
"path": path,
"status": status,
+ "kind": kind,
"ms": round((time.monotonic() - began) * 1000, 1),
+ # Recorded for whoever reads the artifact after a stall, since
+ # "was it generating at the time" is the first question asked of
+ # one. No verdict below reads it.
+ "inference_active": (body or {}).get("inference_active"),
"hardware_detecting": (body or {}).get("hardware_detecting"),
# Stage 0 of the warm only sets hardware_detecting; this one stays
# lit through the transformers and datasets imports after it, so the
@@ -180,31 +450,157 @@ class BackendSurvivalPoller:
self.stop.set()
self.thread.join(timeout = 30)
- def report(self) -> None:
- (ART / "survival_samples.json").write_text(
- json.dumps(self.samples, indent = 1),
- encoding = "utf-8",
- )
- for path in ("/api/liveness", "/api/health"):
+ def report(
+ self,
+ final_kind: str = "ok",
+ final_status: int = 200,
+ final_wait_s: float = 0.0,
+ recovery_samples: "list[dict] | tuple" = (),
+ ) -> None:
+ """Write the samples out and decide whether the backend survived.
+
+ *final_kind* is what await_recovery saw once sampling stopped, and *final_wait_s*
+ is how long it watched for. Together they separate a stall that happened to be in
+ progress when the run ended from a backend that is genuinely gone, which is not a
+ distinction the samples alone can make: they stop at an arbitrary moment.
+
+ *recovery_samples* are that watch's own probes, on the same clock, and they are
+ laid end to end with the poller's. A stall can begin after sampling stops, and
+ one that then clears is exactly the case this file argues is worth reporting
+ rather than failing; measuring spans from the poller's samples alone would let it
+ pass in silence.
+ """
+ # Written below, once the recovery probes have been folded in. Serialising
+ # self.samples alone published a healthy timeline next to a log reporting a long
+ # post-run stall, which removes the evidence a reader needs to check the very
+ # thing the warning announces.
+ for path in PROBE_PATHS:
got = [s for s in self.samples if s["path"] == path]
if not got:
fail(f"no samples collected for {path}")
continue
- bad = [s for s in got if s["status"] != 200]
+ bad = [s for s in got if s["kind"] != "ok"]
worst = max(s["ms"] for s in got)
unmeasured = sum(1 for s in got if s["hardware_detecting"] is True)
warming = sum(1 for s in got if s["torch_warm_in_progress"] is True)
info(
- f"{path}: {len(got)} samples, {len(bad)} non-200, worst {worst}ms, "
+ f"{path}: {len(got)} samples, {len(bad)} miss(es), worst {worst}ms, "
f"{unmeasured} with an unmeasured verdict, {warming} with the warm still running"
)
- if bad:
+ # These two are the backend saying something, not failing to. Neither is a
+ # stall, so neither gets the watchdog's patience: they fail on sight.
+ refused = [s for s in got if s["kind"] == "refused"]
+ answered_badly = [s for s in got if s["kind"] == "http"]
+ if refused:
+ # The port stopped accepting. Nothing transient does this to a backend
+ # that is meant to be up, so it is fatal on the first occurrence.
fail(
- f"{path} returned non-200 {len(bad)} time(s) "
- f"(first at t={bad[0]['t']}s status={bad[0]['status']}); "
- "the backend did not stay up through the warm window"
+ f"{path}: connection refused at t={refused[0]['t']}s; the port was gone, "
+ "so the backend did not stay up through the warm window"
+ )
+ elif answered_badly:
+ fail(
+ f"{path}: answered {answered_badly[0]['status']} at "
+ f"t={answered_badly[0]['t']}s; the backend stayed up but reported itself "
+ "unhealthy through the warm window"
)
+ # What is left of the verdict, and deliberately so.
+ #
+ # This used to replay the launcher's watchdog: a 15s grid, three consecutive
+ # misses, the widened budget while inference_active is latched, the 30s
+ # last-chance probe. Mirroring that state machine in Python turned every detail
+ # of studio/src-tauri/src/commands.rs into a correctness requirement for a smoke
+ # test, and it cannot pay off here for two reasons.
+ #
+ # The window is too small for the rule to run. This phase gets
+ # STUDIO_MAC_SURVIVAL_S = 120 (.github/workflows/studio-mac-ui-smoke.yml), while
+ # the busy path alone is HEALTH_WATCHDOG_MAX_FAILURES_BUSY * 15s plus a 30s
+ # confirmation, about 210s, and BACKEND_STARTUP_GRACE_PERIOD is 300s before a
+ # backend that has not yet answered healthy counts a failure at all. A verdict
+ # reached in 120s is a statement about a rule that never had room to run.
+ #
+ # And the watchdog is not running here in the first place. This phase boots
+ # `unsloth studio` directly, with no Tauri shell, which the workflow says at the
+ # step itself; the watchdog's own behaviour is covered by the Rust tests beside
+ # it in commands.rs. So the rule was being re-implemented to judge a process that
+ # was not subject to it.
+ #
+ # What is left is the part that needs no arithmetic and cannot false-positive: a
+ # backend that stops answering and never comes back did not survive. Anything
+ # that answers again did, on any reading of any budget, so it warns and passes.
+ # If you are tempted to put a threshold back, it has to be strictly longer than
+ # the launcher's most generous path, and nothing that long fits in this window.
+ # One timeline: the poller's samples then the watch's probes, same clock. A span
+ # is therefore measured across the join rather than truncated at it, and a stall
+ # that starts after sampling stops gets a span of its own instead of none.
+ observed = list(self.samples) + list(recovery_samples)
+ (ART / "survival_samples.json").write_text(
+ json.dumps(observed, indent = 1),
+ encoding = "utf-8",
+ )
+ sampling_ended = max((s["t"] for s in self.samples), default = 0.0)
+ spans = _stall_windows(observed)
+ terminal = next((sp for sp in spans if sp[2]), None)
+ longest = max(((end - start) for start, end, _ in spans), default = 0.0)
+ widest = max(spans, key = lambda sp: sp[1] - sp[0], default = None)
+
+ if final_kind == "refused":
+ fail(
+ f"{LIVENESS_PATH} was refused after the run ({final_wait_s}s of watching); "
+ "the port is gone, so the backend did not survive the window"
+ )
+ elif final_kind == "http":
+ fail(
+ f"{LIVENESS_PATH} answered {final_status} after the run; the backend is up "
+ "but reporting itself unhealthy"
+ )
+ elif final_kind == "timeout":
+ # Nothing came back for the whole recovery window. A stall that was going to
+ # end had every one of those seconds to end in.
+ if terminal is not None:
+ # terminal spans the recovery probes too, now that they are on the same
+ # timeline, so the total already includes the watch. Naming the watch
+ # again as extra time on top of it would count it twice.
+ fail(
+ f"the backend stopped answering at t={round(terminal[0], 1)}s and never "
+ f"answered again: {round(terminal[1] - terminal[0], 1)}s of silence in "
+ f"total, of which the last {final_wait_s}s was the post-run watch. It "
+ "did not survive the window."
+ )
+ else:
+ fail(
+ f"backend answered nothing for {final_wait_s}s after the run "
+ f"({LIVENESS_PATH} kept timing out), so it did not survive the window"
+ )
+ elif spans:
+ # It came back, so the launcher would have kept it on any budget and this run
+ # is green. Say so anyway: a stall this long is a real backend defect even
+ # when it is not a fatal one, and it must not vanish into a pass.
+ worst_ms = max(s["ms"] for s in observed)
+ # Where the longest stall sits relative to the end of sampling decides what
+ # can honestly be said about it. All three cases are recovered stalls; only
+ # the first one cleared while the run was still watching in the normal way.
+ if widest is None or widest[1] <= sampling_ended:
+ cleared = "It answered again before the run ended."
+ elif widest[0] >= sampling_ended:
+ cleared = (
+ "That stall began after sampling ended and was seen only by the "
+ f"post-run watch, which ran for {final_wait_s}s before it cleared."
+ )
+ else:
+ cleared = (
+ "Sampling ended during that stall; it cleared during the post-run "
+ f"watch, which ran for {final_wait_s}s. The length above spans both."
+ )
+ print(
+ f"::warning::backend stalled: {len(spans)} window(s) with nothing answering, "
+ f"longest {round(longest, 1)}s, worst single probe {worst_ms}ms against a "
+ f"{PROBE_TIMEOUT_S}s budget. {cleared} Not a failure here. See "
+ "logs/studio_tabs.log for which request was in flight.",
+ flush = True,
+ )
+
def rotate_password(page) -> None:
"""Complete the forced password change a bootstrap login lands on.
@@ -419,7 +815,7 @@ def assert_pending_state_on_forced_verdict(page) -> None:
having read the row.
"""
step("forcing an unmeasured verdict and re-checking the pinned Train row")
- status, live = _get_json("/api/health")
+ status, live, _kind = _get_json("/api/health")
if status != 200 or not isinstance(live, dict):
fail(
"/api/health gave no body to base the provisional reply on "
@@ -615,13 +1011,25 @@ def main() -> int:
ctx.close()
browser.close()
- watchdog.cancel()
poller.finish()
- poller.report()
- status, _ = _get_json("/api/liveness")
- if status != 200:
- fail(f"backend was not alive at the end of the run (/api/liveness -> {status})")
+ # Watched after sampling stopped and handed to report(), which needs it to tell a
+ # stall still in progress at the end of the run from a backend that never came back.
+ step(f"watching up to {RECOVERY_WINDOW_S:.0f}s more for the backend to answer")
+ kind, status, waited, recovery = await_recovery()
+ info(f"post-run {LIVENESS_PATH}: {kind} after {waited}s of watching, {len(recovery)} probe(s)")
+ poller.report(
+ final_kind = kind,
+ final_status = status,
+ final_wait_s = waited,
+ recovery_samples = recovery,
+ )
+
+ # Cancelled only now. The recovery watch adds up to RECOVERY_WINDOW_S after the UI
+ # drive, so disarming before it ran left the longest-running part of the script with
+ # nothing enforcing WALL_TIMEOUT_S, and a probe that would not end had the job's own
+ # cap as its only bound. A hung job reports nothing, which is the worst outcome here.
+ watchdog.cancel()
if _failed:
print(f"[mac-tabs] {len(_failed)} FAILURE(S)", flush = True)
diff --git a/tests/studio/test_mac_tab_capability_warm_window.py b/tests/studio/test_mac_tab_capability_warm_window.py
index f483612fc50..721a59b0a86 100644
--- a/tests/studio/test_mac_tab_capability_warm_window.py
+++ b/tests/studio/test_mac_tab_capability_warm_window.py
@@ -18,8 +18,10 @@ neither playwright nor a Studio is installed.
from __future__ import annotations
import importlib.util
+import json
import re
import sys
+import time
import types
from pathlib import Path
@@ -185,7 +187,7 @@ def _health(mod, bodies):
def fake(path, timeout = 10.0):
body = queue.pop(0) if len(queue) > 1 else queue[0]
- return 200, dict(body)
+ return 200, dict(body), "ok"
mod._get_json = fake
@@ -274,7 +276,7 @@ def test_forced_body_is_a_real_reply_with_the_measurement_removed(tmp_path, monk
def test_unreadable_health_fails_rather_than_returning_early(tmp_path, monkeypatch):
"""No body to build the provisional reply from means the check did not run. Say so."""
mod = _load(tmp_path, monkeypatch)
- mod._get_json = lambda path, timeout = 10.0: (0, None)
+ mod._get_json = lambda path, timeout = 10.0: (0, None, "refused")
page = FakePage({TRAIN: SPINNING})
mod.assert_row_never_greyed_while_unmeasured(page)
@@ -413,3 +415,778 @@ def test_the_forced_verdict_check_is_wired_into_the_public_entry_point():
"assert_row_never_greyed_while_unmeasured", set()
)
assert "assert_row_never_greyed_while_unmeasured" in called.get("main", set())
+
+
+# --------------------------------------------------------------------------------
+# What the survival poller fails on, now that it no longer replays the watchdog.
+# --------------------------------------------------------------------------------
+
+POLL_S = 5.0
+BUDGET_S = 10.0
+
+
+def _timeline(duration_s, stalls = ()):
+ """Simulate the poller against a backend that answers nothing during *stalls*.
+
+ Each stall is a (start, end) window in seconds. A probe issued inside one answers
+ when the stall lifts if that falls inside its 10s budget, and times out otherwise.
+ Probes are sequential and a timeout costs the whole budget before the next route is
+ tried, which is what the real poller does.
+ """
+
+ def lifts_at(t):
+ for start, end in stalls:
+ if start <= t < end:
+ return end
+ return None
+
+ samples, now = [], 0.0
+ while now < duration_s:
+ for path in ("/api/liveness", "/api/health"):
+ end = lifts_at(now)
+ if end is None:
+ took, kind = 0.005, "ok"
+ elif end - now <= BUDGET_S:
+ took, kind = end - now, "ok"
+ else:
+ took, kind = BUDGET_S, "timeout"
+ now += took
+ samples.append(
+ {
+ "t": round(now, 3),
+ "path": path,
+ "kind": kind,
+ "status": 200 if kind == "ok" else 0,
+ "ms": round(took * 1000, 1),
+ "inference_active": None,
+ "hardware_detecting": None,
+ "torch_warm_in_progress": None,
+ }
+ )
+ now += POLL_S
+ return samples
+
+
+def _recovery_probes(
+ start_t,
+ timeouts,
+ settles = "ok",
+):
+ """Probes in the shape await_recovery records them: N timeouts, then one answer."""
+ out, now = [], float(start_t)
+ for _ in range(timeouts):
+ now += BUDGET_S
+ out.append(
+ {
+ "t": round(now, 3),
+ "path": "/api/liveness",
+ "kind": "timeout",
+ "status": 0,
+ "ms": BUDGET_S * 1000,
+ "inference_active": None,
+ "hardware_detecting": None,
+ "torch_warm_in_progress": None,
+ }
+ )
+ if settles is not None:
+ now += 0.005
+ out.append(
+ {
+ "t": round(now, 3),
+ "path": "/api/liveness",
+ "kind": settles,
+ "status": 200 if settles == "ok" else 0,
+ "ms": 5.0,
+ "inference_active": None,
+ "hardware_detecting": None,
+ "torch_warm_in_progress": None,
+ }
+ )
+ return out
+
+
+def _verdict(
+ mod,
+ samples,
+ final_kind = "ok",
+ final_status = 200,
+ final_wait_s = 0.0,
+ recovery_samples = (),
+):
+ poller = mod.BackendSurvivalPoller()
+ poller.samples = samples
+ poller.report(
+ final_kind = final_kind,
+ final_status = final_status,
+ final_wait_s = final_wait_s,
+ recovery_samples = recovery_samples,
+ )
+ return list(mod._failed)
+
+
+def test_a_stall_the_backend_recovers_from_is_not_a_failure(tmp_path, monkeypatch):
+ """The case run 32862298967 went red on. A backend that stops answering and then
+ answers again survived, on any reading of any budget, so it warns and passes."""
+ mod = _load(tmp_path, monkeypatch)
+ samples = _timeline(150, stalls = [(30, 63)])
+ assert any(s["kind"] == "timeout" for s in samples), "fixture stopped producing a stall"
+ assert _verdict(mod, samples) == []
+
+
+def 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."""
+ 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."""
+ mod = _load(tmp_path, monkeypatch)
+ failed = _verdict(
+ mod, _timeline(150, stalls = [(60, 9999)]), final_kind = "timeout", final_status = 0
+ )
+ assert len(failed) == 1, failed
+ assert "never answered again" in failed[0], failed
+
+
+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."""
+ mod = _load(tmp_path, monkeypatch)
+ samples = _timeline(150, stalls = [(60, 9999)])
+ assert samples[-1]["kind"] == "timeout", "fixture no longer ends mid-stall"
+ assert _verdict(mod, samples, final_kind = "ok") == []
+
+
+def test_a_dead_backend_with_no_samples_still_fails(tmp_path, monkeypatch):
+ """The post-run watch is load-bearing on its own, not only as a tie-breaker."""
+ mod = _load(tmp_path, monkeypatch)
+ failed = _verdict(mod, _timeline(60), final_kind = "refused", final_status = 0)
+ assert len(failed) == 1, failed
+ assert "port is gone" in failed[0], failed
+
+
+def test_a_refused_connection_fails_on_the_first_one(tmp_path, monkeypatch):
+ """A refused port is death, not a stall, and nothing transient produces it against a
+ backend that is meant to be up. It is fatal even though the backend recovers."""
+ mod = _load(tmp_path, monkeypatch)
+ samples = _timeline(120)
+ hit = [s for s in samples if s["t"] > 50][0]
+ hit["kind"], hit["status"], hit["ms"] = "refused", 0, 1.0
+ failed = _verdict(mod, samples)
+ assert any("refused" in m for m in failed), failed
+
+
+def test_a_non_200_answer_fails_on_the_first_one(tmp_path, monkeypatch):
+ """An answered non-200 is the backend itself saying it is unhealthy. Also not a stall,
+ and also fatal even though every other probe in the run succeeded."""
+ mod = _load(tmp_path, monkeypatch)
+ samples = _timeline(120)
+ hit = [s for s in samples if s["t"] > 50][0]
+ hit["kind"], hit["status"], hit["ms"] = "http", 503, 4.0
+ failed = _verdict(mod, samples)
+ assert any("unhealthy" in m for m in failed), failed
+
+
+def test_only_a_refused_connection_counts_as_a_dead_port(tmp_path, monkeypatch):
+ """ECONNREFUSED is the kernel saying nothing is bound. A reset or a truncated read is
+ a listener that accepted and then failed to finish, which is a stall."""
+ mod = _load(tmp_path, monkeypatch)
+ assert mod._transport_kind(ConnectionRefusedError()) == "refused"
+ assert mod._transport_kind(ConnectionResetError()) == "timeout"
+ assert mod._transport_kind(TimeoutError()) == "timeout"
+ assert mod._transport_kind(OSError("something else entirely")) == "timeout"
+
+
+def test_an_answer_from_either_route_closes_a_stall(tmp_path, monkeypatch):
+ """check_health_inner falls back from /api/liveness to /api/health, so one answer
+ from either is proof the backend was serving and ends the span."""
+ mod = _load(tmp_path, monkeypatch)
+ samples = [
+ {
+ "t": 10.0,
+ "path": "/api/liveness",
+ "kind": "timeout",
+ "status": 0,
+ "ms": 10000.0,
+ "inference_active": None,
+ "hardware_detecting": None,
+ "torch_warm_in_progress": None,
+ },
+ {
+ "t": 10.1,
+ "path": "/api/health",
+ "kind": "ok",
+ "status": 200,
+ "ms": 5.0,
+ "inference_active": None,
+ "hardware_detecting": None,
+ "torch_warm_in_progress": None,
+ },
+ ]
+ spans = mod._stall_windows(samples)
+ assert len(spans) == 1, spans
+ assert spans[0][2] is False, spans
+
+
+def test_the_probe_budget_is_the_launchers_own_number():
+ """The one watchdog constant this file still mirrors. If HEALTH_PROBE_TIMEOUT moves
+ and this does not, a probe here calls a miss at a different point than the product."""
+ rust = (REPO / "studio/src-tauri/src/commands.rs").read_text(encoding = "utf-8")
+ match = re.search(r"const HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs\((\d+)\);", rust)
+ assert match, "HEALTH_PROBE_TIMEOUT is not in commands.rs any more"
+ assert _module_constant("PROBE_TIMEOUT_S") == float(match.group(1))
+
+
+def test_the_watchdog_replay_is_gone():
+ """It was removed on purpose: mirroring the launcher's state machine made every line
+ of commands.rs a correctness requirement here, for a rule this phase never runs and
+ could not decide inside its 120s window. Reintroducing it should be a deliberate act,
+ not a quiet one."""
+ source = SCRIPT.read_text(encoding = "utf-8")
+ for gone in ("watchdog_replay", "WATCHDOG_MAX_FAILURES", "WATCHDOG_INTERVAL_S"):
+ assert f"def {gone}" not in source and f"\n{gone} =" not in source, gone
+
+
+# --------------------------------------------------------------------------------
+# The post-run watch, which is what stops the window boundary deciding the verdict.
+# --------------------------------------------------------------------------------
+
+
+def _scripted_probes(mod, kinds):
+ """Point _get_json at a scripted sequence of outcomes; the last one repeats."""
+ seq = list(kinds)
+ calls = []
+
+ def fake(path, timeout = 10.0):
+ kind = seq.pop(0) if len(seq) > 1 else seq[0]
+ calls.append(path)
+ return (200 if kind == "ok" else (503 if kind == "http" else 0)), None, kind
+
+ mod._get_json = fake
+ return calls
+
+
+def test_the_watch_keeps_probing_until_the_backend_answers(tmp_path, monkeypatch):
+ """A stall straddling the end of sampling is not a dead backend. One probe cannot
+ tell the difference, so the watch keeps asking until something comes back."""
+ mod = _load(tmp_path, monkeypatch)
+ calls = _scripted_probes(mod, ["timeout", "timeout", "ok"])
+ # spacing off: this case is about the loop continuing, not about how it paces.
+ kind, status, _, probes = mod.await_recovery(window_s = 30.0, spacing_s = 0.0)
+ assert (kind, status) == ("ok", 200)
+ assert len(calls) == 3, calls
+ assert len(probes) == len(calls), "the watch dropped probes from its history"
+ assert [pr["kind"] for pr in probes] == ["timeout", "timeout", "ok"], probes
+
+
+def test_the_watch_gives_up_and_reports_a_timeout(tmp_path, monkeypatch):
+ """Bounded, so a genuinely dead backend still fails. It answers none of these
+ probes either, which is why extending the observation cannot rescue a real death."""
+ mod = _load(tmp_path, monkeypatch)
+ calls = _scripted_probes(mod, ["timeout"])
+ kind, _, _, probes = mod.await_recovery(window_s = 0.05, spacing_s = 0.0)
+ assert kind == "timeout"
+ assert len(calls) >= 1, calls
+
+
+def test_a_refused_port_does_not_get_the_recovery_window(tmp_path, monkeypatch):
+ """Only a stall is worth waiting on. A refused port is already decided, so it fails
+ at once rather than costing the run 90 seconds to reach the same answer."""
+ mod = _load(tmp_path, monkeypatch)
+ calls = _scripted_probes(mod, ["refused"])
+ # Small but non-zero on purpose. A build that stopped returning early would spend it
+ # and rack up probes, so this fails on the call count in a moment rather than hanging
+ # the suite for as long as the real window lasts.
+ kind, _, _, probes = mod.await_recovery(window_s = 2.0, spacing_s = 0.0)
+ assert kind == "refused"
+ assert len(calls) == 1, f"spent the window instead of returning at once: {len(calls)} probes"
+
+
+def test_an_answered_non_200_does_not_get_the_recovery_window(tmp_path, monkeypatch):
+ """Also already decided: the backend answered, so waiting adds nothing."""
+ mod = _load(tmp_path, monkeypatch)
+ calls = _scripted_probes(mod, ["http"])
+ kind, status, _, probes = mod.await_recovery(window_s = 2.0, spacing_s = 0.0)
+ assert (kind, status) == ("http", 503)
+ assert len(calls) == 1, f"spent the window instead of returning at once: {len(calls)} probes"
+
+
+def 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."""
+ longest_observed_s = 33.2
+ assert _module_constant("RECOVERY_WINDOW_S") > 2 * longest_observed_s
+
+
+def test_the_post_run_watch_is_wired_into_the_public_entry_point():
+ """report() is driven with an injected verdict everywhere above, so nothing there
+ would notice main() dropping the watch and going back to a single probe."""
+ import ast
+
+ tree = ast.parse(SCRIPT.read_text(encoding = "utf-8"))
+ main = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "main")
+ called = {
+ sub.func.id
+ for sub in ast.walk(main)
+ if isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name)
+ }
+ assert "await_recovery" in called
+ reports = [
+ sub
+ for sub in ast.walk(main)
+ if isinstance(sub, ast.Call)
+ and isinstance(sub.func, ast.Attribute)
+ and sub.func.attr == "report"
+ and sub.keywords
+ ]
+ assert reports, "main() no longer hands a post-run verdict to report()"
+ passed = {kw.arg for call in reports for kw in call.keywords}
+ assert {"final_kind", "final_wait_s"} <= passed, passed
+
+
+# --------------------------------------------------------------------------------
+# The watch has to be bounded, paced, and honest about what it saw.
+# --------------------------------------------------------------------------------
+
+
+def _serve(
+ handler_body,
+ trickle = False,
+ huge = False,
+):
+ """A one-shot HTTP server on a free port. Returns (base_url, state, shutdown)."""
+ import http.server
+ import threading
+
+ state = {"chunks": 0, "payload": 0}
+
+ class H(http.server.BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def do_GET(self):
+ if trickle:
+ # Headers, then a byte at a time forever. Every chunk resets urllib's
+ # per-operation timeout, which is the shape that hangs a naive read().
+ self.send_response(200)
+ self.send_header("Content-Length", "1000000")
+ self.end_headers()
+ try:
+ while True:
+ self.wfile.write(b"x")
+ self.wfile.flush()
+ state["chunks"] += 1
+ time.sleep(0.02)
+ except Exception:
+ pass
+ return
+ payload = b"x" * (4 << 20) if huge else handler_body
+ state["payload"] = len(payload)
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+ def log_message(self, *a):
+ pass
+
+ srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
+ threading.Thread(target = srv.serve_forever, daemon = True).start()
+ return f"http://127.0.0.1:{srv.server_port}", state, srv.shutdown
+
+
+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."""
+ mod = _load(tmp_path, monkeypatch)
+ base, state, shutdown = _serve(b"{}", trickle = True)
+ monkeypatch.setattr(mod, "BASE", base)
+ try:
+ returned, value, elapsed = _probe_bounded(mod, "/api/liveness", timeout = 0.5, wait = 5.0)
+ finally:
+ shutdown()
+ assert state["chunks"] >= 3, f"fixture stopped dribbling after {state['chunks']} chunks"
+ assert returned, "the probe never returned: a read with no deadline hangs the job"
+ assert value[2] == "timeout", value
+ assert 0.4 <= elapsed < 5.0, f"probe ran {elapsed:.2f}s against a 0.5s budget"
+
+
+def test_an_oversized_body_does_not_get_read_to_the_end(tmp_path, monkeypatch):
+ """The other way to sit on a socket indefinitely. A health reply is a few hundred
+ bytes, so a body this size is a fault and reading it all is not the way to find out."""
+ mod = _load(tmp_path, monkeypatch)
+ base, state, shutdown = _serve(b"", huge = True)
+ monkeypatch.setattr(mod, "BASE", base)
+ try:
+ returned, value, _ = _probe_bounded(mod, "/api/liveness", timeout = 30.0, wait = 30.0)
+ finally:
+ shutdown()
+ assert (
+ state["payload"] > mod._MAX_BODY_BYTES
+ ), f"fixture body {state['payload']}B no longer exceeds the {mod._MAX_BODY_BYTES}B cap"
+ assert returned, "the probe never returned"
+ assert value[2] == "timeout", value
+
+
+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."""
+ mod = _load(tmp_path, monkeypatch)
+ calls = _scripted_probes(mod, ["timeout"])
+ began = time.monotonic()
+ kind, _, _, probes = mod.await_recovery(window_s = 1.0, spacing_s = 0.2)
+ elapsed = time.monotonic() - began
+ assert kind == "timeout"
+ assert len(calls) <= 8, f"unpaced: {len(calls)} probes in {elapsed:.2f}s"
+ assert elapsed < 3.0, f"paced past the window: {elapsed:.2f}s"
+
+
+def test_a_real_stall_is_not_slowed_down_by_the_pacing(tmp_path, monkeypatch):
+ """A probe that spends its whole budget needs no pause after it, so the spacing costs
+ nothing on the case the window actually exists for."""
+ mod = _load(tmp_path, monkeypatch)
+
+ def slow(path, timeout = 10.0):
+ time.sleep(0.25)
+ return 0, None, "timeout"
+
+ mod._get_json = slow
+ began = time.monotonic()
+ mod.await_recovery(window_s = 0.5, spacing_s = 0.2)
+ assert time.monotonic() - began < 1.5
+
+
+def test_the_wall_watchdog_stays_armed_through_recovery_and_reporting():
+ """The watch runs after the UI drive and can add RECOVERY_WINDOW_S, so disarming
+ before it left the longest part of the script with nothing enforcing the deadline."""
+ import ast
+
+ tree = ast.parse(SCRIPT.read_text(encoding = "utf-8"))
+ main = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "main")
+ cancels = [
+ n.lineno
+ for n in ast.walk(main)
+ if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) and n.func.attr == "cancel"
+ ]
+ reports = [
+ n.lineno
+ for n in ast.walk(main)
+ if isinstance(n, ast.Call)
+ and isinstance(n.func, ast.Attribute)
+ and n.func.attr == "report"
+ and n.keywords
+ ]
+ recoveries = [
+ n.lineno
+ for n in ast.walk(main)
+ if isinstance(n, ast.Call)
+ and isinstance(n.func, ast.Name)
+ and n.func.id == "await_recovery"
+ ]
+ assert cancels and reports and recoveries
+ assert min(cancels) > max(recoveries), "watchdog disarmed before the recovery watch"
+ assert min(cancels) > max(reports), "watchdog disarmed before 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."""
+ mod = _load(tmp_path, monkeypatch)
+ # A SHORT trailing stall on purpose. With a long one the span alone clears any
+ # threshold and the assertion below passes whether or not the wait is counted, which
+ # is how this test first shipped without discriminating.
+ samples = _timeline(150, stalls = [(140, 9999)])
+ assert samples[-1]["kind"] == "timeout", "fixture no longer ends mid-stall"
+ raw = max(end - start for start, end, _ in mod._stall_windows(samples))
+ assert raw < 40.0, f"fixture stall is already long enough to pass on its own: {raw}s"
+ # The watch keeps probing for another 40s before it clears.
+ recovery = _recovery_probes(samples[-1]["t"], timeouts = 4)
+ assert (
+ _verdict(mod, samples, final_kind = "ok", final_wait_s = 40.0, recovery_samples = recovery) == []
+ )
+ warning = [ln for ln in capsys.readouterr().out.splitlines() if ln.startswith("::warning::")]
+ assert warning, "no warning emitted for a stall that cleared after the run"
+ longest = float(re.search(r"longest ([\d.]+)s", warning[0]).group(1))
+ assert longest >= raw + 40.0 - 0.5, f"post-run wait not counted: {longest}s vs span {raw}s"
+ assert "post-run watch" in warning[0], warning[0]
+ assert "before the run ended" not in warning[0], warning[0]
+
+
+def test_the_warning_still_says_before_the_run_when_that_is_true(tmp_path, monkeypatch, capsys):
+ """The other half: a stall that closed while sampling was still going did clear before
+ the run ended, and the wording has to keep saying so."""
+ mod = _load(tmp_path, monkeypatch)
+ assert _verdict(mod, _timeline(150, stalls = [(30, 63)]), final_kind = "ok") == []
+ warning = [ln for ln in capsys.readouterr().out.splitlines() if ln.startswith("::warning::")]
+ assert warning and "before the run ended" in warning[0], warning
+ assert "post-run watch" not in warning[0], warning[0]
+
+
+def test_pacing_never_sleeps_past_the_end_of_the_window(tmp_path, monkeypatch):
+ """The pause is clamped to whatever is left. A spacing wider than the remaining window
+ must not extend the watch, or the bound the wall watchdog is enforcing stops holding."""
+ mod = _load(tmp_path, monkeypatch)
+ _scripted_probes(mod, ["timeout"])
+ began = time.monotonic()
+ mod.await_recovery(window_s = 0.3, spacing_s = 5.0)
+ elapsed = time.monotonic() - began
+ assert elapsed < 2.0, f"slept past the window: {elapsed:.2f}s for a 0.3s window"
+
+
+def _serve_trickling_headers():
+ """A listener that accepts, then dribbles response HEADERS and never finishes them.
+
+ Deliberately raw sockets rather than http.server: the point is to stall inside
+ urlopen's header parsing, which is before any body-level bound can run, and a
+ BaseHTTPRequestHandler writes its headers in one go.
+ """
+ import socket as socket_mod
+ import threading
+
+ srv = socket_mod.socket(socket_mod.AF_INET, socket_mod.SOCK_STREAM)
+ srv.setsockopt(socket_mod.SOL_SOCKET, socket_mod.SO_REUSEADDR, 1)
+ srv.bind(("127.0.0.1", 0))
+ srv.listen(4)
+ srv.settimeout(0.25)
+ port = srv.getsockname()[1]
+ state = {"accepted": 0, "lines": 0}
+ stop = threading.Event()
+
+ def drip(conn):
+ try:
+ conn.recv(4096)
+ # One header line that is never terminated, a byte at a time. Whole header
+ # LINES would hit http.client's own _MAXHEADERS cap of 100 and end the call
+ # on their own at about two seconds, which would make this fixture pass
+ # against a build that has no deadline at all. An unterminated line has no
+ # such cap and blocks urlopen for as long as the peer keeps dribbling.
+ conn.sendall(b"HTTP/1.1 200 OK\r\nX-Pad: ")
+ while not stop.is_set():
+ conn.sendall(b"x")
+ state["lines"] += 1
+ time.sleep(0.02)
+ except Exception:
+ pass
+ finally:
+ try:
+ conn.close()
+ except Exception:
+ pass
+
+ def accept_loop():
+ while not stop.is_set():
+ try:
+ conn, _ = srv.accept()
+ except Exception:
+ continue
+ state["accepted"] += 1
+ threading.Thread(target = drip, args = (conn,), daemon = True).start()
+
+ threading.Thread(target = accept_loop, daemon = True).start()
+
+ def shutdown():
+ stop.set()
+ try:
+ srv.close()
+ except Exception:
+ pass
+
+ return f"http://127.0.0.1:{port}", state, shutdown
+
+
+def _probe_bounded(mod, path, timeout, wait):
+ """Call mod._get_json on a daemon thread and join for *wait*.
+
+ No test here may detect its own mutation by hanging: a hang reports nothing and
+ burns the runner, which is the failure these tests are about. A build whose probe
+ cannot end fails the assertion below instead of stopping the suite.
+ """
+ import threading
+
+ box = {}
+
+ def run():
+ box["value"] = mod._get_json(path, timeout = timeout)
+
+ worker = threading.Thread(target = run, daemon = True)
+ began = time.monotonic()
+ worker.start()
+ worker.join(wait)
+ return (not worker.is_alive()), box.get("value"), time.monotonic() - began
+
+
+def test_trickling_response_headers_cannot_outlive_the_probe_budget(tmp_path, monkeypatch):
+ """The body deadline does not cover this. While response headers are still arriving,
+ urlopen has not returned, so nothing inside it is running yet and only urllib's
+ per-socket-operation timeout applies, which a peer resets by dribbling. The budget is
+ whole-request for that reason: connect, headers and body under one deadline."""
+ mod = _load(tmp_path, monkeypatch)
+ base, state, shutdown = _serve_trickling_headers()
+ monkeypatch.setattr(mod, "BASE", base)
+ try:
+ returned, value, elapsed = _probe_bounded(mod, "/api/liveness", timeout = 0.5, wait = 6.0)
+ finally:
+ shutdown()
+ # Fixture preconditions first, so a server that stopped trickling fails loudly
+ # instead of letting the probe return fast and passing for free.
+ assert state["accepted"] >= 1, "fixture never accepted a connection"
+ assert state["lines"] >= 3, f"fixture stopped trickling headers after {state['lines']} bytes"
+ assert state["lines"] < 100, (
+ "fixture is sending whole header lines again; http.client's _MAXHEADERS would "
+ "end the call by itself and this would pass without any deadline"
+ )
+ assert returned, "probe never returned: urlopen is outside the deadline again"
+ assert value[2] == "timeout", value
+ assert 0.4 <= elapsed < 4.0, f"probe took {elapsed:.2f}s against a 0.5s whole-request budget"
+
+
+def 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."""
+ source = SCRIPT.read_text(encoding = "utf-8")
+ assert "WHOLE-REQUEST deadline" in source
+ assert "worker.join(timeout)" in source
+
+
+def test_a_stall_that_begins_after_sampling_is_still_reported(tmp_path, monkeypatch, capsys):
+ """The gap the recovery watch opened. Sampling can end on a good probe and the backend
+ stall immediately afterwards; the watch then sees several timeouts, gets an answer, and
+ returns ok. Measuring spans from the poller's samples alone leaves that stall in no
+ span at all, so the run passes in silence. A recovered stall reported nowhere is the
+ one outcome this window was added to avoid, since the argument for warning instead of
+ failing is that somebody reads the warning."""
+ mod = _load(tmp_path, monkeypatch)
+ samples = _timeline(120)
+ assert all(s["kind"] == "ok" for s in samples), "fixture must end with sampling healthy"
+ assert not mod._stall_windows(samples), "fixture already has a stall during sampling"
+ # 60s of silence after sampling stops, then the backend answers.
+ recovery = _recovery_probes(samples[-1]["t"], timeouts = 6)
+ assert (
+ _verdict(mod, samples, final_kind = "ok", final_wait_s = 60.0, recovery_samples = recovery) == []
+ )
+ warning = [ln for ln in capsys.readouterr().out.splitlines() if ln.startswith("::warning::")]
+ assert warning, "a 60s post-run stall was not reported at all"
+ longest = float(re.search(r"longest ([\d.]+)s", warning[0]).group(1))
+ assert longest >= 50.0, f"post-run stall understated as {longest}s: {warning[0]}"
+ assert "began after sampling ended" in warning[0], warning[0]
+ assert "before the run ended" not in warning[0], warning[0]
+
+
+def test_the_watch_history_is_handed_to_the_report(tmp_path, monkeypatch):
+ """main() must pass await_recovery's probes to report(), or the span maths above sees
+ the poller's samples only and the case that test covers cannot arise in a real run."""
+ import ast
+
+ tree = ast.parse(SCRIPT.read_text(encoding = "utf-8"))
+ main = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "main")
+ reports = [
+ n
+ for n in ast.walk(main)
+ if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) and n.func.attr == "report"
+ ]
+ assert reports, "main() no longer reports"
+ passed = {kw.arg for call in reports for kw in call.keywords}
+ assert "recovery_samples" in passed, passed
+
+
+def test_no_probe_is_given_more_budget_than_the_window_has_left(tmp_path, monkeypatch):
+ """A probe started near the end of the window with the full default budget can run
+ most of PROBE_TIMEOUT_S past it, which is the overrun the wall watchdog catches by
+ terminating the run before it reports. The budget is clamped to what is left."""
+ mod = _load(tmp_path, monkeypatch)
+ window = 1.0
+ budgets, started_at = [], []
+ began = time.monotonic()
+
+ def fake(path, timeout = 10.0):
+ budgets.append(timeout)
+ started_at.append(time.monotonic() - began)
+ time.sleep(0.05)
+ return 0, None, "timeout"
+
+ mod._get_json = fake
+ mod.await_recovery(window_s = window, spacing_s = 0.0)
+
+ assert budgets, "the watch made no probes"
+ assert len(budgets) > 1, "fixture ended after one probe; the clamp is never exercised"
+ assert max(budgets) <= window, f"a probe was handed {max(budgets)}s of a {window}s window"
+ for budget, start in zip(budgets, started_at):
+ assert (
+ budget <= window - start + 0.05
+ ), f"a probe starting at {start:.2f}s got {budget:.2f}s, past the end of the window"
+
+
+def test_a_probe_is_not_started_with_no_time_left(tmp_path, monkeypatch):
+ """The pacing sleep is clamped to the window, so the loop can arrive at the deadline
+ with nothing left. It must stop there rather than begin another request."""
+ mod = _load(tmp_path, monkeypatch)
+ starts = []
+ began = time.monotonic()
+
+ def fake(path, timeout = 10.0):
+ starts.append(time.monotonic() - began)
+ time.sleep(0.05)
+ return 0, None, "timeout"
+
+ mod._get_json = fake
+ mod.await_recovery(window_s = 0.4, spacing_s = 0.1)
+
+ assert len(starts) > 1, "fixture ended after one probe; the guard is never exercised"
+ assert max(starts) < 0.4, f"a probe started at {max(starts):.2f}s, past the 0.4s window"
+
+
+def test_the_artifact_carries_what_the_verdict_was_computed_from(tmp_path, monkeypatch):
+ """survival_samples.json is the evidence for the warning beside it. Serialising the
+ poller's samples only published a healthy timeline next to a log reporting a long
+ post-run stall, so nobody could check the claim."""
+ mod = _load(tmp_path, monkeypatch)
+ samples = _timeline(120)
+ recovery = _recovery_probes(samples[-1]["t"], timeouts = 6)
+ assert all(s["kind"] == "ok" for s in samples), "fixture must end with sampling healthy"
+ assert any(pr["kind"] == "timeout" for pr in recovery), "fixture has no post-run stall"
+
+ _verdict(mod, samples, final_kind = "ok", final_wait_s = 60.0, recovery_samples = recovery)
+
+ written = json.loads((mod.ART / "survival_samples.json").read_text(encoding = "utf-8"))
+ assert len(written) == len(samples) + len(recovery), (
+ f"artifact holds {len(written)} records for a verdict computed from "
+ f"{len(samples) + len(recovery)}"
+ )
+ assert any(
+ r["kind"] == "timeout" for r in written
+ ), "the artifact shows an entirely healthy timeline while the warning reports a stall"
+
+
+def test_the_terminal_message_does_not_count_the_watch_twice(tmp_path, monkeypatch):
+ """The span now runs through the recovery probes, so its length already includes the
+ watch. Describing that length as silence "to the end of sampling" and then adding the
+ watch on top reads as a total nobody can reconcile with the artifact."""
+ mod = _load(tmp_path, monkeypatch)
+ samples = _timeline(150, stalls = [(140, 9999)])
+ recovery = _recovery_probes(samples[-1]["t"], timeouts = 4, settles = None)
+ failed = _verdict(
+ mod,
+ samples,
+ final_kind = "timeout",
+ final_status = 0,
+ final_wait_s = 40.0,
+ recovery_samples = recovery,
+ )
+ assert len(failed) == 1, failed
+ total = float(re.search(r"([\d.]+)s of silence in total", failed[0]).group(1))
+ spans = mod._stall_windows(samples + recovery)
+ widest = max(end - start for start, end, _ in spans)
+ assert abs(total - widest) < 0.5, f"reported {total}s against a {widest}s span"
+ assert total >= 40.0, f"the watch is missing from the total: {failed[0]}"
+ assert "then 40.0s more" not in failed[0], failed[0]