Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
175 changes: 153 additions & 22 deletions pm-stack/exporters/src/watchdog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ export interface WatchdogEffects {
/** Live CDP liveness: does the browser's /json/version answer? */
probeCdp(port: number): Promise<{ ok: boolean; detail: string }>;
/** Rung 2: re-validate the CDP session (browser alive, an allowlist
* origin open, adapter cookies present BY NAME). */
* page open AND its renderer answering — the wedge probe — and the
* adapter cookies present BY NAME). */
rung2(adapter: WatchdogAdapter): Promise<RungOutcome>;
/** Rung 3: re-login driver via the provider's own SSO flow. Stops
* dead at a human-only challenge. */
Expand Down Expand Up @@ -161,6 +162,90 @@ async function cdpCookieNames(port: number, origins: string[], timeoutMs = 5000)
});
}

/** One /json/list target, reduced to the fields the watchdog uses. */
interface CdpTarget {
type?: string;
url?: string;
webSocketDebuggerUrl?: string;
}

/** The allowlist page target rung 2 should talk to: a page (not a
* background page, service worker, or other non-page target) on one
* of the adapter's origins, with a debugger websocket. Pure — the
* wedge probe's target choice is testable without a browser. */
export function pickAllowlistTarget(targets: CdpTarget[], origins: string[]): CdpTarget | null {
return (
targets.find(
(t) =>
(t.type === undefined || t.type === "page") &&
typeof t.webSocketDebuggerUrl === "string" &&
t.webSocketDebuggerUrl.length > 0 &&
origins.some((o) => (t.url ?? "").startsWith(o)),
) ?? null
);
}

/** Wedge probe (#10630): does the page's renderer answer a trivial
* Runtime.evaluate over its own debugger websocket? A hung renderer
* leaves every browser-level endpoint (/json/version, /json/list,
* Storage.getCookies) answering while the page itself never replies
* — the silent shape of the 2026-11-13→16 outage. The reply's value
* is discarded; answering at all is the signal. */
export async function cdpPageResponsive(
webSocketDebuggerUrl: string,
timeoutMs = 5000,
): Promise<{ ok: boolean; detail: string }> {
return await new Promise((resolve) => {
let settled = false;
const done = (r: { ok: boolean; detail: string }) => {
if (!settled) {
settled = true;
resolve(r);
}
};
let ws: WebSocket;
try {
ws = new WebSocket(webSocketDebuggerUrl);
} catch (e) {
done({ ok: false, detail: `page websocket unusable: ${e instanceof Error ? e.message : String(e)}` });
return;
}
const timer = setTimeout(() => {
try {
ws.close();
} catch {
/* already closed */
}
done({ ok: false, detail: `page unresponsive: Runtime.evaluate not answered within ${timeoutMs} ms` });
}, timeoutMs);
ws.onopen = () => {
ws.send(
JSON.stringify({ id: 1, method: "Runtime.evaluate", params: { expression: "1", returnByValue: true } }),
);
};
ws.onmessage = (ev) => {
try {
const msg = JSON.parse(String(ev.data)) as { id?: number; error?: { message?: string } };
if (msg.id !== 1) return;
clearTimeout(timer);
try {
ws.close();
} catch {
/* already closed */
}
if (msg.error) done({ ok: false, detail: `page evaluate errored: ${msg.error.message ?? "unknown CDP error"}` });
else done({ ok: true, detail: "page renderer answered Runtime.evaluate" });
} catch {
/* not our reply frame — keep waiting for the reply or the timeout */
}
};
ws.onerror = () => {
clearTimeout(timer);
done({ ok: false, detail: "page websocket errored before answering" });
};
});
}

async function systemctlUser(args: string[], timeoutMs = 30000): Promise<{ ok: boolean; detail: string }> {
try {
const proc = Bun.spawn(["systemctl", "--user", ...args], { stdout: "pipe", stderr: "pipe" });
Expand Down Expand Up @@ -213,28 +298,74 @@ export function productionEffects(env: Record<string, string | undefined> = proc
}
return { outcome: "failed", detail: probe.detail };
}
// Browser answers: an allowlist origin must be open, and the
// adapter's cookies must be present by name.
let targets: { url?: string }[] = [];
try {
targets = (await fetchJson(`http://127.0.0.1:${adapter.cdpPort}/json/list`, 3000)) as typeof targets;
} catch (e) {
return { outcome: "failed", detail: `CDP /json/list failed: ${e instanceof Error ? e.message : String(e)}` };
}
const open = targets.some((t) => adapter.origins.some((o) => (t.url ?? "").startsWith(o)));
if (adapter.origins.length > 0 && !open) {
return { outcome: "failed", detail: "no tab on an adapter allowlist origin" };
}
if (adapter.cookieNames.length > 0) {
const names = await cdpCookieNames(adapter.cdpPort, adapter.origins);
if (names === null) return { outcome: "failed", detail: "cookie presence check could not run (CDP websocket)" };
const missing = adapter.cookieNames.filter((n) => !names.includes(n));
if (missing.length > 0) return { outcome: "failed", detail: `cookies missing by name: ${missing.join(", ")}` };
}
return {
outcome: "succeeded",
detail: "CDP session re-validated: browser live, allowlist origin open, cookies present by name",
// Browser answers at the endpoint. Validate the session in
// layers: an allowlist page is open, its renderer answers an
// evaluate (the wedge probe — browser-level endpoints answer
// even when the page is hung), and the adapter's cookies are
// present by name.
const validate = async (): Promise<{ ok: boolean; wedged: boolean; detail: string }> => {
let targets: CdpTarget[] = [];
try {
targets = (await fetchJson(`http://127.0.0.1:${adapter.cdpPort}/json/list`, 3000)) as CdpTarget[];
} catch (e) {
return {
ok: false,
wedged: false,
detail: `CDP /json/list failed: ${e instanceof Error ? e.message : String(e)}`,
};
}
if (adapter.origins.length > 0) {
const target = pickAllowlistTarget(targets, adapter.origins);
if (!target) {
const anyOpen = targets.some((t) => adapter.origins.some((o) => (t.url ?? "").startsWith(o)));
return {
ok: false,
wedged: false,
detail: anyOpen
? "allowlist page is open but exposes no debugger websocket — cannot probe it"
: "no tab on an adapter allowlist origin",
};
}
const page = await cdpPageResponsive(target.webSocketDebuggerUrl!);
if (!page.ok) return { ok: false, wedged: true, detail: `browser wedged: ${page.detail}` };
}
if (adapter.cookieNames.length > 0) {
const names = await cdpCookieNames(adapter.cdpPort, adapter.origins);
if (names === null)
return { ok: false, wedged: false, detail: "cookie presence check could not run (CDP websocket)" };
const missing = adapter.cookieNames.filter((n) => !names.includes(n));
if (missing.length > 0)
return { ok: false, wedged: false, detail: `cookies missing by name: ${missing.join(", ")}` };
}
return {
ok: true,
wedged: false,
detail: "CDP session re-validated: browser live, allowlist page responsive, cookies present by name",
};
};
let v = await validate();
if (!v.ok && v.wedged && adapter.browserUnit) {
// Wedged browser: one bounded supervised restart, then the
// FULL validation again — a restart that leaves the page
// hung is a failure, not a repair. (Recovery is only real
// when a later tick observes a fresh producer read; that is
// the recovery path's job, not this rung's claim.)
const rs = await systemctlUser(["restart", adapter.browserUnit]);
if (!rs.ok)
return { outcome: "failed", detail: `${v.detail}; restart of ${adapter.browserUnit} failed: ${rs.detail}` };
await sleep(3000);
const again = await probeCdp(adapter.cdpPort);
if (!again.ok)
return { outcome: "failed", detail: `browser unit restarted but CDP still unreachable: ${again.detail}` };
v = await validate();
if (v.ok)
return {
outcome: "succeeded",
detail: `browser wedged; unit ${adapter.browserUnit} restarted; ${v.detail}`,
};
return { outcome: "failed", detail: `browser still wedged after unit restart: ${v.detail}` };
}
return v.ok ? { outcome: "succeeded" as const, detail: v.detail } : { outcome: "failed" as const, detail: v.detail };
},
async rung3(adapter) {
if (!adapter.cdpPort || !adapter.loginUrl)
Expand Down
114 changes: 114 additions & 0 deletions pm-stack/exporters/test/watchdog-wedge.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Tests for the CDP wedge probe (#10630).
//
// Oracles, named per the testing doctrine (AGENTS.md):
// - Wire oracle: cdpPageResponsive runs against a real local
// websocket server speaking just enough CDP. A renderer that
// answers Runtime.evaluate reads responsive; one that accepts
// the socket and never replies (the hung-renderer shape) reads
// unresponsive within the timeout; one that replies with a CDP
// error reads unresponsive with the error named; a dead
// endpoint reads unresponsive instead of throwing.
// - Target-choice oracle: pickAllowlistTarget picks the page-type
// allowlist target with a debugger websocket and nothing else —
// background pages, workers, off-origin pages, and pages with
// no debugger websocket never count as "the page is open".

import { describe, expect, test } from "bun:test";
import { cdpPageResponsive, pickAllowlistTarget } from "../src/watchdog.ts";

function fakePage(mode: "answer" | "silent" | "error") {
const server = Bun.serve({
port: 0,
fetch(req, srv) {
if (srv.upgrade(req)) return undefined;
return new Response("not a websocket", { status: 400 });
},
websocket: {
message(ws, message) {
const msg = JSON.parse(String(message)) as { id?: number; method?: string };
if (msg.method !== "Runtime.evaluate") return;
if (mode === "answer") {
ws.send(JSON.stringify({ id: msg.id, result: { result: { type: "number", value: 1 } } }));
} else if (mode === "error") {
ws.send(JSON.stringify({ id: msg.id, error: { message: "Cannot find context" } }));
}
// "silent": the hung renderer — socket open, never replies.
},
},
});
return { url: `ws://127.0.0.1:${server.port}/devtools/page/fake`, stop: () => server.stop(true) };
}

describe("wedge probe — cdpPageResponsive (wire oracle)", () => {
test("a renderer that answers Runtime.evaluate is responsive", async () => {
const page = fakePage("answer");
try {
const r = await cdpPageResponsive(page.url, 2000);
expect(r.ok).toBe(true);
expect(r.detail).toContain("answered");
} finally {
page.stop();
}
});

test("a renderer that never answers is unresponsive within the timeout", async () => {
const page = fakePage("silent");
try {
const r = await cdpPageResponsive(page.url, 300);
expect(r.ok).toBe(false);
expect(r.detail).toContain("unresponsive");
} finally {
page.stop();
}
});

test("a CDP error reply is unresponsive and names the error", async () => {
const page = fakePage("error");
try {
const r = await cdpPageResponsive(page.url, 2000);
expect(r.ok).toBe(false);
expect(r.detail).toContain("Cannot find context");
} finally {
page.stop();
}
});

test("a dead websocket endpoint is unresponsive, not a throw", async () => {
const r = await cdpPageResponsive("ws://127.0.0.1:1/devtools/page/none", 1000);
expect(r.ok).toBe(false);
});
});

describe("wedge probe — pickAllowlistTarget (target-choice oracle)", () => {
const origins = ["https://fixture.invalid"];

test("picks the page target on an allowlist origin with a debugger websocket", () => {
const t = pickAllowlistTarget(
[
{ type: "page", url: "https://other.invalid/", webSocketDebuggerUrl: "ws://x/1" },
{ type: "page", url: "https://fixture.invalid/app", webSocketDebuggerUrl: "ws://x/2" },
],
origins,
);
expect(t?.webSocketDebuggerUrl).toBe("ws://x/2");
});

test("background pages and workers on the origin do not count", () => {
const t = pickAllowlistTarget(
[
{ type: "background_page", url: "https://fixture.invalid/bg", webSocketDebuggerUrl: "ws://x/1" },
{ type: "service_worker", url: "https://fixture.invalid/sw", webSocketDebuggerUrl: "ws://x/2" },
],
origins,
);
expect(t).toBeNull();
});

test("a page without a debugger websocket does not count", () => {
expect(pickAllowlistTarget([{ type: "page", url: "https://fixture.invalid/" }], origins)).toBeNull();
});

test("no targets at all is null", () => {
expect(pickAllowlistTarget([], origins)).toBeNull();
});
});