Skip to content

studio/tests: AbortSignal-bound in-page fetches and wall-clock watchdog for Playwright probes - #5391

Merged
danielhanchen merged 2 commits into
mainfrom
studio-playwright-deadlines
May 12, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-playwright-deadlines

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

  • Add evaluate_fetch(...) in tests/studio/_playwright_robust.py: wraps fetch() inside page.evaluate with an AbortController so a hung in-browser request resolves to {status: 0, error: "AbortError..."} after a configurable budget instead of wedging the script.
  • Add install_wall_clock_watchdog(...): daemon threading.Timer that hard-exits the process at a configurable deadline so any wedge that bypasses every per-action timeout still surfaces as a clean failure with a stderr line, not a 30-min runner cancel.
  • Wire both into playwright_chat_ui.py and playwright_extra_ui.py. Replace every page.evaluate(async () => fetch(...)) site with evaluate_fetch(...) (five in chat, two in extra). Arm the watchdog at the top of with sync_playwright() and cancel it on clean exit.

Why

Run 25696797934 / job 75446949358 on PR #5387 cancelled the macos-14 Chat UI Tests job at exactly 30 min. studio.log went idle after the chat surface mounted, no further HTTP requests reached the server, and Playwright sat for 27+ minutes on a page.evaluate(async () => fetch(/api/inference/load)) before the runner-level timeout fired. The other two Chat UI Tests jobs on the same SHA passed in 5-17 min, so this was a transient renderer wedge under --single-process Chromium on macos-14 (the renderer's network thread stalls behind the busy main thread), not a regression from the security bumps in #5387.

Playwright's page.evaluate(...) takes no timeout= argument. If the JS body awaits a fetch whose promise never settles, the whole Python script hangs until something external kills it. This change makes that class of wedge bounded and debuggable.

Knobs

All defaults are safe; override only for slow runners.

  • STUDIO_UI_WALL_TIMEOUT_S (default 720s)
  • STUDIO_UI_FETCH_TIMEOUT_MS (default 30000ms)
  • STUDIO_UI_LOAD_TIMEOUT_MS (default 180000ms; the /api/inference/load call dominates because it pulls the model into the llama.cpp worker)

Test plan

  • ast.parse on the three modified files (clean).
  • Unit smoke: stub page.evaluate and confirm evaluate_fetch passes the expected AbortController-wrapped JS body and arg dict (url, method, headers, JSON-encoded body, timeoutMs).
  • Watchdog smoke: install_wall_clock_watchdog(2.0) returns a daemonised threading.Timer that responds to .cancel().
  • CI: Chat UI Tests matrix runs end-to-end across linux + macos + windows on this branch.
  • Forced-wedge fault injection (manual, optional): set STUDIO_UI_WALL_TIMEOUT_S=10 and confirm the watchdog hard-exits with the diagnostic stderr line.

Scope

This is a pure test-infrastructure change. No product code under studio/ or unsloth/ is touched. The bumped deps in #5387 (hono / ip-address / mermaid security) are unaffected; that PR can land on its own once its rerun goes green.

Run 25696797934 / job 75446949358 on PR #5387 cancelled the
"Chat UI Tests" macos-14 job at 30 min: studio.log went idle after
the chat surface mounted, no further requests reached the server,
and Playwright silently sat on a `page.evaluate(async () => fetch(
/api/inference/load))` for 27+ minutes before the runner-level
timeout fired. The two other Chat UI Tests jobs on the same SHA
passed in 5-17 min, so this was a transient renderer wedge under
--single-process Chromium, not a regression from the security
bumps in that PR.

Root cause: Playwright's `page.evaluate(...)` has no `timeout=`
argument. If the JS body awaits a fetch whose promise never
settles (the renderer's network thread stalls behind the busy main
thread on the free macos-14 runner), the entire Python script
hangs until something external kills it.

Add two helpers in `_playwright_robust.py`:

  - `evaluate_fetch(page, url, *, method, headers, body, timeout_ms)`
    wraps `fetch()` in an `AbortController` so the JS resolves
    either with a real response or with `{status: 0, error:
    "AbortError..."}` after the budget elapses. Callers fail loud
    on a non-None `error` and the wedge surfaces as a one-line
    diagnostic instead of a 30-min cancel.

  - `install_wall_clock_watchdog(deadline_s)` starts a daemon
    Timer that hard-exits the process at the deadline. Belt-and-
    suspenders for any wedge inside the browser that the per-
    action timeouts cannot bound. Default 720s (12 min); healthy
    runs measure 5-9 min on macos-14 so the headroom is small
    without amplifying a wedge to the 30-min runner cap.

Wire both into `playwright_chat_ui.py` and `playwright_extra_ui.py`:

  - Replace every `page.evaluate(async () => fetch(...))` site
    with `evaluate_fetch(...)`: refresh-token exchange, defaults
    fetch, inference load, health probe, post-rotation refresh.
    Five sites in chat_ui, two in extra_ui.
  - Arm the watchdog at the top of `with sync_playwright()` and
    cancel it on clean exit.

Knobs (all default-safe, override only for slow runners):
  STUDIO_UI_WALL_TIMEOUT_S   (default 720s)
  STUDIO_UI_FETCH_TIMEOUT_MS (default 30000ms)
  STUDIO_UI_LOAD_TIMEOUT_MS  (default 180000ms)

Verified locally with `python -c "ast.parse(...)"` on all three
files and a unit smoke that confirms `evaluate_fetch`'s JS argument
shape and that `install_wall_clock_watchdog` returns a daemonised
Timer that responds to `.cancel()`.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 22a0f83dfc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

# Wall-clock cap for the entire script. A healthy comprehensive run is
# 5-9 min; 12 min leaves headroom. Tunable via STUDIO_UI_WALL_TIMEOUT_S.
# See _playwright_robust.install_wall_clock_watchdog for rationale.
WALL_TIMEOUT_S = float(os.environ.get("STUDIO_UI_WALL_TIMEOUT_S", "720"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Align wall-clock cap with slow UI turn budgets

In the macOS and Windows UI smoke workflows I checked, the env raises STUDIO_UI_TURN_TIMEOUT_MS to 540000 but does not set STUDIO_UI_WALL_TIMEOUT_S. With this new 720s default watchdog, a legitimate slow run can be killed before the existing per-turn waits have expired: this script runs five chat turns, and those workflows explicitly document runners where turn latency can crowd the old 180s budget. A couple of slow turns plus model load can exceed 12 minutes while no individual Playwright wait has failed, producing a false exit(2) instead of exercising the intended retry/failure paths; please either set the wall cap in those workflows or derive it from the configured turn timeout.

Useful? React with 👍 / 👎.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces robust timeout and error-handling mechanisms for Playwright-based UI tests to prevent silent hangs in CI environments. Key additions include an evaluate_fetch utility that wraps in-page JavaScript fetches with an AbortController and a global wall-clock watchdog that forces a process exit if a predefined deadline is exceeded. The reviewer identified a logic issue in evaluate_fetch where the response stream could be locked if JSON parsing fails, preventing a fallback to plain text, and noted that the timeout should cover the entire body streaming process rather than just the initial response headers.

Comment on lines +461 to +482
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), timeoutMs);
try {
const opts = {method: method, headers: headers, signal: ctrl.signal};
if (body !== null) opts.body = body;
const r = await fetch(url, opts);
clearTimeout(t);
let parsed;
try {
parsed = await r.json();
} catch (_e) {
try {
parsed = await r.text();
} catch (_e2) {
parsed = null;
}
}
return {status: r.status, body: parsed, error: null};
} catch (e) {
clearTimeout(t);
return {status: 0, body: null, error: String(e)};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current implementation of evaluate_fetch has two logic issues in the injected JavaScript:

  1. Body parsing race: r.json() consumes the response stream. If the response is not valid JSON (e.g., plain text from /api/health), r.json() will throw, and the subsequent r.text() call in the catch block will fail with a TypeError because the stream is already locked/consumed. This results in body being null for any non-JSON response.
  2. Timeout coverage: clearTimeout(t) is called immediately after the fetch promise resolves (headers received). If the body streaming subsequently hangs, the AbortSignal will not fire because the timer was already cleared. The timeout should encompass the entire operation, including reading the body.

Reading the body as text first, then clearing the timeout, and finally attempting to parse the text as JSON is a more robust pattern.

Suggested change
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), timeoutMs);
try {
const opts = {method: method, headers: headers, signal: ctrl.signal};
if (body !== null) opts.body = body;
const r = await fetch(url, opts);
clearTimeout(t);
let parsed;
try {
parsed = await r.json();
} catch (_e) {
try {
parsed = await r.text();
} catch (_e2) {
parsed = null;
}
}
return {status: r.status, body: parsed, error: null};
} catch (e) {
clearTimeout(t);
return {status: 0, body: null, error: String(e)};
}
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), timeoutMs);
try {
const opts = {method: method, headers: headers, signal: ctrl.signal};
if (body !== null) opts.body = body;
const r = await fetch(url, opts);
const text = await r.text();
clearTimeout(t);
let parsed;
try {
parsed = JSON.parse(text);
} catch (_e) {
parsed = text || null;
}
return {status: r.status, body: parsed, error: null};
} catch (e) {
clearTimeout(t);
return {status: 0, body: null, error: String(e)};
}

@danielhanchen
danielhanchen merged commit 9d47eb2 into main May 12, 2026
22 checks passed
@danielhanchen
danielhanchen deleted the studio-playwright-deadlines branch May 12, 2026 03:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant