diff --git a/tests/restart-chaos/README.md b/tests/restart-chaos/README.md index d6cc3949994..be5c24be737 100644 --- a/tests/restart-chaos/README.md +++ b/tests/restart-chaos/README.md @@ -311,9 +311,39 @@ behind its agent's full `maxConcurrentRuns` cap, with the queue-wait proof findi assignment run started ahead of it, is not graded: `SUMMARY.md` names it on a `Not graded` line and `hosted-release-swap.json` lists it under `notGraded`. The runs holding the slots are still graded. +**Failure evidence** (`hosted-diagnostics.ts`). The health probe opens a new connection for every probe and closes it +after the answer, so a stale keep-alive socket cannot look like an outage. Every request records its connection: +new or reused socket (API requests, from undici's diagnostics channels), remote and local address, and the DNS, +connect, TLS and first-byte times where they are cheap to read. Every failed request in `health.jsonl` and +`requests.jsonl` carries a `failure` object: for an answer, its status, the headers `x-paperclip-status`, `retry-after`, +`server`, `via`, `x-railway-request-id`, `x-railway-edge`, `cf-ray`, `date`, `content-type`, `cache-control` and +`connection`, the first 512 bytes of the body (the health client stops reading a non-2xx body after 16 KiB), and the parsed `error` and `statusPage.code`; for an exception, undici's +`error.cause` (`code`, `errno`, `syscall`, `hostname`, `address`, `port`, message, and the socket's addresses and byte +counts for `UND_ERR_SOCKET`). It also records the client clock: how late an abort fired (`timerLagMs`), how far the +wall clock moved past the monotonic clock, the event loop's longest delay (`monitorEventLoopDelay`), and the pause +before the probe. Right after any failure the harness requests `https://www.cloudflare.com/cdn-cgi/trace` (the control +probe) and, for a GET that did not time out, retries the same URL once with a 2 s limit, and records both outcomes and +timings. Neither counts as a request. The failure is recorded at once and this evidence is attached in the background, +so neither the health probe loop nor the API client's own retries wait for it. After the drain, the grade stops the +health probe, freezes its samples, waits up to 30 s for their evidence, and detects the releases from those samples. A +diagnosis that did not finish stays pending and counts as a failure (unclassified, and a failed probe for release detection). +A failed probe that has no class in the summary counts as unclassified. A failed probe's line goes into `health.jsonl` when its evidence is complete. The health client follows up to +three same-origin redirects. If an answer is cut short, its status, headers and partial body are kept with the error. +Only the live entry point (`hosted-main.ts`) turns the control probe on; unit tests never reach the network for it. + +Each failure gets a class. Server-side: any HTTP answer that is not a readable 2xx; a reset or refused connection +while the control probe succeeded; a timeout while the control probe succeeded and the client did not stall. +Client-side: a `client_stall` (an abort more than 1 s late, a clock jump over 1 s, an event-loop delay over 1 s, or a +pause before the probe longer than twice the interval); a control probe that failed too, once the neutral endpoint +has answered at least once in the run (the run probes it right after sign-in; if it never answered, a failed control +probe proves nothing and the failure stays unclassified); a client DNS failure +(`EAI_AGAIN`, or `ENOTFOUND` that the immediate retry did not repeat). Anything else is unclassified. Release +detection skips client-side failures, so a client-side failure in a swap gap does not make a release stop-then-start. + **Gate D verdict** (`hosted-gate.ts`). A run exits 0 only when every check in the `Gate D` block of `SUMMARY.md` holds: every started task completed hands-off; every task the harness launched was created; every started task passes the local waves' -R1 (`gradeR1` from `grader.ts`); no Retry banner was shown; no health probe failed; no overlapping runs, duplicated +R1 (`gradeR1` from `grader.ts`); no Retry banner was shown; no health probe failed server-side or unclassified (client-side +failures are listed under `Health probe failures` with their evidence but do not fail the gate); no overlapping runs, duplicated agent comments or duplicated subtasks; no release was stop-then-start; and at least one release was detected, each with a live run carried across it. A fixed batch (`--hosted-releases 0`) skips the release check. R1 uses the staging-mix budget (`stagingMixBudgetMs`); a subtask the agent created under a launched task is graded from its own creation time with the diff --git a/tests/restart-chaos/hosted-api.ts b/tests/restart-chaos/hosted-api.ts index 7189756d01a..ce028bd7bb1 100644 --- a/tests/restart-chaos/hosted-api.ts +++ b/tests/restart-chaos/hosted-api.ts @@ -5,8 +5,16 @@ import { setTimeout as delay } from "node:timers/promises"; import { ChaosApiError, rateLimitDelayMs } from "./api.js"; import { assertSameOrigin, type HostedTarget } from "./hosted-guard.js"; import type { HealthSample } from "./hosted-release.js"; +import { + answerEvidence, CONTROL_TIMEOUT_MS, CONTROL_URL, classifyFailure, connections, errorCause, followUp, freshConnectionFetch, isAbort, newRequestId, partialAnswerOf, readClock, + REQUEST_ID_HEADER, resetEventLoopDelay, RETRY_TIMEOUT_MS, startClock, summarizeFailures, watchEventLoop, type AnswerEvidence, type ClockStart, type ConnectionInfo, + type FailureClassSummary, type FailureRecord, + type FollowUp, type ProbeContext, +} from "./hosted-diagnostics.js"; export const HOSTED_TOKEN_ENV = "PAPERCLIP_HOSTED_TOKEN"; +export const HEALTH_TIMEOUT_MS = 10_000; +export const SETTLE_DEADLINE_MS = 30_000; const TRANSIENT_STATUSES = new Set([502, 503, 504]); export const ANSWERED_REFUSALS: ReadonlySet = new Set([400, 404, 409, 422]); @@ -29,7 +37,17 @@ export function hostedToken(target: HostedTarget, env: NodeJS.ProcessEnv = proce + "Ask the owner to approve a board sign-in for this host first (README: Hosted mode, Sign-in)."); } -export interface RequestRecord { at: number; ok: boolean; reachable: boolean; status: number | null; ms: number; method: string; kind: "health" | "api"; path: string } +export interface RequestRecord { at: number; ok: boolean; reachable: boolean; status: number | null; ms: number; method: string; kind: "health" | "api"; path: string; + connection?: ConnectionInfo | null; failure?: FailureRecord } + +export interface HostedProbes { live?: boolean; health?: typeof fetch; control?: typeof fetch; controlUrl?: string } + +interface OnceResult { status: number | null; text: string; retryAfterMs: number | null; record: RequestRecord; clock: ClockStart; url: string; headers: Headers | null } + +function failureText(error: unknown, failure: FailureRecord): string { + const message = error instanceof Error ? error.message : String(error); + return failure.cause?.code ? `${message} (${failure.cause.code})` : message; +} export function pathClass(route: string): string { return route.split("?")[0]!.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, ":id"); @@ -37,31 +55,115 @@ export function pathClass(route: string): string { export class HostedApi { readonly requests: RequestRecord[] = []; + private readonly healthFetcher: typeof fetch; + private readonly controlFetcher: typeof fetch | null; + private readonly controlUrl: string; + private control: { at: number; outcome: Promise } | null = null; + private controlReached = false; + private readonly expired = new WeakSet(); + private readonly diagnosing = new WeakMap>(); constructor(readonly target: HostedTarget, private readonly token: string, private readonly timeoutMs = 20_000, - private readonly fetcher: typeof fetch = fetch) {} + private readonly fetcher: typeof fetch = fetch, probes: HostedProbes = {}) { + this.healthFetcher = probes.health ?? (probes.live ? freshConnectionFetch : fetcher); + this.controlFetcher = probes.control ?? (probes.live ? freshConnectionFetch : null); + this.controlUrl = probes.controlUrl ?? CONTROL_URL; + connections.subscribe(); + watchEventLoop(); + } get baseUrl(): string { return this.target.baseUrl; } - private async once(method: string, route: string, body: unknown, timeoutMs: number): Promise<{ status: number | null; text: string; retryAfterMs: number | null; record: RequestRecord }> { + private headers(body: unknown): Record { + return { authorization: `Bearer ${this.token}`, accept: "application/json", origin: this.target.baseUrl, ...(body === undefined ? {} : { "content-type": "application/json" }) }; + } + + private async once(method: string, route: string, body: unknown, timeoutMs: number, probe?: ProbeContext): Promise { const url = `${this.target.baseUrl}${route}`; assertSameOrigin(this.target, url); + const kind = route === "/api/health" ? "health" : "api"; + const fetcher = kind === "health" ? this.healthFetcher : this.fetcher; + const id = newRequestId(); const started = Date.now(); + const clock = startClock(); + const base = { at: started, method, kind, path: pathClass(route) } as const; + let response: Response; try { - const response = await this.fetcher(url, { method, cache: "no-store", signal: AbortSignal.timeout(timeoutMs), - headers: { authorization: `Bearer ${this.token}`, accept: "application/json", origin: this.target.baseUrl, - ...(body === undefined ? {} : { "content-type": "application/json" }) }, + response = await fetcher(url, { method, cache: "no-store", signal: AbortSignal.timeout(timeoutMs), headers: { ...this.headers(body), [REQUEST_ID_HEADER]: id }, body: body === undefined ? undefined : JSON.stringify(body) }); - const text = await response.text(); - const record: RequestRecord = { at: started, ok: response.ok || (route !== "/api/health" && ANSWERED_REFUSALS.has(response.status)), reachable: response.status < 500, status: response.status, - ms: Date.now() - started, method, kind: route === "/api/health" ? "health" : "api", path: pathClass(route) }; - this.requests.push(record); - return { status: response.ok ? 200 : response.status, text, retryAfterMs: rateLimitDelayMs(response, text), record }; } catch (error) { - const record: RequestRecord = { at: started, ok: false, reachable: false, status: null, ms: Date.now() - started, method, kind: route === "/api/health" ? "health" : "api", path: pathClass(route) }; + const partial = partialAnswerOf(error); + const record: RequestRecord = { ...base, ok: false, reachable: partial !== null && partial.status < 500, status: partial?.status ?? null, ms: Date.now() - started, + connection: connections.take(id) }; this.requests.push(record); - return { status: null, text: error instanceof Error ? error.message : String(error), retryAfterMs: null, record }; + record.failure = this.diagnose({ method, url, timeoutMs, clock, probe, error, connection: record.connection ?? null, + answer: partial ? answerEvidence(partial.status, partial.headers, partial.body) : null }); + const answered = partial !== null && (partial.status < 200 || partial.status >= 300) ? partial.status : null; + return { status: answered, text: failureText(error, record.failure), retryAfterMs: null, record, clock, url, headers: partial?.headers ?? null }; } + let text: string; + try { + text = await response.text(); + } catch (error) { + const record: RequestRecord = { ...base, ok: false, reachable: response.status < 500, status: response.status, ms: Date.now() - started, connection: connections.take(id) }; + this.requests.push(record); + record.failure = this.diagnose({ method, url, timeoutMs, clock, probe, error, connection: record.connection ?? null, + answer: answerEvidence(response.status, response.headers, "") }); + return { status: response.ok ? null : response.status, text: failureText(error, record.failure), retryAfterMs: null, record, clock, url, headers: response.headers }; + } + const record: RequestRecord = { ...base, ok: response.ok || (kind === "api" && ANSWERED_REFUSALS.has(response.status)), reachable: response.status < 500, status: response.status, + ms: Date.now() - started, connection: connections.take(id) }; + this.requests.push(record); + if (!record.ok) record.failure = this.diagnose({ method, url, timeoutMs, clock, probe, answer: answerEvidence(response.status, response.headers, text), error: null, + connection: record.connection ?? null }); + return { status: response.ok ? 200 : response.status, text, retryAfterMs: rateLimitDelayMs(response, text), record, clock, url, headers: response.headers }; + } + + private controlProbe(): Promise | null { + if (!this.controlFetcher) return null; + if (this.control && Date.now() - this.control.at < 1_000) return this.control.outcome; + const outcome = followUp(this.controlFetcher, this.controlUrl, {}, CONTROL_TIMEOUT_MS).then(result => { + if (result.ok) this.controlReached = true; + return result; + }); + this.control = { at: Date.now(), outcome }; + return outcome; + } + + async primeControl(): Promise { + return await this.controlProbe(); + } + + private diagnose(input: { method: string; url: string; timeoutMs: number; clock: ClockStart; probe: ProbeContext | undefined; answer: AnswerEvidence | null; + error: unknown; connection: ConnectionInfo | null }): FailureRecord { + const aborted = input.error !== null && isAbort(input.error); + const failure: FailureRecord = { url: input.url.slice(this.target.baseUrl.length), method: input.method, aborted, answer: input.answer, + cause: input.error === null ? null : errorCause(input.error), connection: input.connection, clock: readClock(input.clock, input.timeoutMs, aborted, input.probe), + control: null, retry: null, controlReachedThisRun: false, class: "unclassified", reason: "diagnosis pending", state: "pending" }; + const fetcher = input.url.endsWith("/api/health") ? this.healthFetcher : this.fetcher; + const retry = this.controlFetcher !== null && input.method === "GET" && !aborted ? followUp(fetcher, input.url, this.headers(undefined), RETRY_TIMEOUT_MS) : null; + const task = Promise.all([this.controlProbe(), retry]).then(([control, retried]) => { + Object.assign(failure, { control, retry: retried, controlReachedThisRun: this.controlReached }); + if (!this.expired.has(failure)) Object.assign(failure, classifyFailure(failure), { state: "settled" }); + }); + this.diagnosing.set(failure, task); + return failure; + } + + async settleDiagnostics(failures?: ReadonlyArray, deadlineMs = SETTLE_DEADLINE_MS): Promise { + const targets = failures ? failures.filter((failure): failure is FailureRecord => failure !== undefined && this.diagnosing.has(failure)) + : [...this.requests.flatMap(record => record.failure && this.diagnosing.has(record.failure) ? [record.failure] : [])]; + const waits = targets.map(failure => this.diagnosing.get(failure)!); + let timer: NodeJS.Timeout | undefined; + await Promise.race([Promise.all(waits), new Promise(resolve => { timer = setTimeout(resolve, deadlineMs); })]); + clearTimeout(timer); + const unfinished = targets.filter(failure => failure.state === "pending"); + for (const failure of unfinished) this.expired.add(failure); + return unfinished.length; + } + + diagnosed(failure: FailureRecord | undefined): Promise { + return (failure && this.diagnosing.get(failure)) ?? Promise.resolve(); } private async request(method: string, route: string, body?: unknown, timeoutMs = this.timeoutMs): Promise { @@ -85,17 +187,21 @@ export class HostedApi { catch (error) { if (!(options?.allowNotFound && error instanceof ChaosApiError && error.status === 404)) throw error; } } - async health(): Promise { + async health(probe?: ProbeContext): Promise { const at = Date.now(); - const result = await this.once("GET", "/api/health", undefined, 10_000); - const ms = Date.now() - at; - if (result.status !== 200) return { at, ok: false, status: result.status, ms, processStartedAt: null, commit: null, error: result.text.slice(0, 200) }; + const result = await this.once("GET", "/api/health", undefined, HEALTH_TIMEOUT_MS, probe); + const ms = result.record.ms; + const connection = result.record.connection ?? null; + if (result.status !== 200) return { at, ok: false, status: result.status, ms, processStartedAt: null, commit: null, error: result.text.slice(0, 200), connection, + failure: result.record.failure }; try { const body = JSON.parse(result.text) as { commit?: string; serverInfo?: { processStartedAt?: string } }; - return { at, ok: true, status: 200, ms, processStartedAt: body.serverInfo?.processStartedAt ?? null, commit: body.commit ?? null }; + return { at, ok: true, status: 200, ms, processStartedAt: body.serverInfo?.processStartedAt ?? null, commit: body.commit ?? null, connection }; } catch (error) { result.record.ok = false; - return { at, ok: false, status: 200, ms, processStartedAt: null, commit: null, error: `unparseable health: ${String(error)}` }; + result.record.failure = this.diagnose({ method: "GET", url: result.url, timeoutMs: HEALTH_TIMEOUT_MS, clock: result.clock, probe, + answer: answerEvidence(200, result.headers ?? new Headers(), result.text), error: null, connection }); + return { at, ok: false, status: 200, ms, processStartedAt: null, commit: null, error: `unparseable health: ${String(error)}`, connection, failure: result.record.failure }; } } } @@ -110,9 +216,12 @@ export class HealthProbe { start(): this { this.loop = (async () => { + let lastEnded: number | null = null; while (!this.stopped) { const started = Date.now(); - const sample = await this.api.health(); + resetEventLoopDelay(); + const sample = await this.api.health({ gapBeforeMs: lastEnded === null ? null : started - lastEnded, intervalMs: this.intervalMs }); + lastEnded = Date.now(); this.samples.push(sample); this.onSample(sample); const wait = this.intervalMs - (Date.now() - started); @@ -141,14 +250,19 @@ export interface RequestBreakdown { insideReleases: number; outsideReleases: number; outside: Array<{ at: string; method: string; path: string; status: number | null }>; + byClass: Omit; } +export const classifyRequests = (records: readonly RequestRecord[]): FailureClassSummary => summarizeFailures(records); + export function requestBreakdown(records: readonly RequestRecord[], windows: ReadonlyArray<{ from: number; to: number }>): RequestBreakdown { const failed = records.filter(record => !record.ok); const inside = (at: number) => windows.some(window => at >= window.from && at <= window.to); const byStatus: Record = {}; for (const record of failed) byStatus[String(record.status ?? "no answer")] = (byStatus[String(record.status ?? "no answer")] ?? 0) + 1; const outside = failed.filter(record => !inside(record.at)); + const { client, server, unclassified } = classifyRequests(failed); return { requests: records.length, failures: failed.length, byStatus, insideReleases: failed.length - outside.length, outsideReleases: outside.length, - outside: outside.slice(0, 50).map(record => ({ at: new Date(record.at).toISOString(), method: record.method, path: record.path, status: record.status })) }; + outside: outside.slice(0, 50).map(record => ({ at: new Date(record.at).toISOString(), method: record.method, path: record.path, status: record.status })), + byClass: { client, server, unclassified } }; } diff --git a/tests/restart-chaos/hosted-diagnostics.test.ts b/tests/restart-chaos/hosted-diagnostics.test.ts new file mode 100644 index 00000000000..32d1b5793e1 --- /dev/null +++ b/tests/restart-chaos/hosted-diagnostics.test.ts @@ -0,0 +1,369 @@ +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import http from "node:http"; +import type { AddressInfo, Socket } from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { HealthProbe, HostedApi } from "./hosted-api.js"; +import { + answerEvidence, classifyFailure, connections, failureLines, followUp, freshConnectionFetch, newRequestId, REQUEST_ID_HEADER, summarizeFailures, type ClientClock, type FailureDiagnosis, +} from "./hosted-diagnostics.js"; +import { hostedGate } from "./hosted-gate.js"; +import { hostedTarget } from "./hosted-guard.js"; +import { watchIdentity } from "./hosted-main.js"; +import { detectReleases, type HealthSample } from "./hosted-release.js"; + +const host = "release-proof-1.staging.paperclip.app"; +const target = hostedTarget(`https://${host}`, host); +const servers: http.Server[] = []; +afterEach(async () => { for (const server of servers.splice(0)) await new Promise(resolve => server.close(resolve)); }); + +const clock = (overrides: Partial = {}): ClientClock => ({ timeoutMs: 10_000, elapsedMs: 40, monotonicMs: 40, timerLagMs: null, clockJumpMs: 0, + loopDelayMaxMs: 25, gapBeforeMs: 1_960, intervalMs: 2_000, ...overrides }); +const ok = { url: "https://www.cloudflare.com/cdn-cgi/trace", ok: true, status: 200, ms: 35, error: null, remoteAddress: "104.16.124.96" }; +const down = { ...ok, ok: false, status: null, ms: 42, error: { name: "TypeError", message: "fetch failed", code: "ENETUNREACH" } }; +const diagnosis = (overrides: Partial = {}): FailureDiagnosis => ({ url: "/api/health", method: "GET", aborted: false, answer: null, + cause: { name: "Error", message: "fetch failed: read ECONNRESET", code: "ECONNRESET", errno: -54, syscall: "read" }, connection: null, clock: clock(), control: ok, retry: ok, + controlReachedThisRun: true, ...overrides }); + +function resetError(): TypeError { + const cause = Object.assign(new Error("other side closed"), { code: "UND_ERR_SOCKET", + socket: { localAddress: "192.168.1.20", localPort: 51799, remoteAddress: "66.33.22.11", remotePort: 443, remoteFamily: "IPv4", timeout: undefined, bytesWritten: 612, bytesRead: 0 } }); + return new TypeError("fetch failed", { cause }); +} + +const sample = (at: number, failure: FailureDiagnosis | null): HealthSample => ({ at, ok: failure === null, status: failure?.answer?.status ?? (failure ? null : 200), ms: 40, + processStartedAt: null, commit: null, ...(failure ? { failure: { ...failure, ...classifyFailure(failure), state: "settled" as const } } : {}) }); + +const gateInput = (healthSamples: HealthSample[]) => ({ handsOffPass: true, wantedReleases: 0, createErrors: 0, slotEvidenceMissing: [] as string[], + r1: [{ identifier: "GIT-1", result: { verdict: "pass" as const, detail: "done" } }], bannersShown: 0, + health: { requests: healthSamples.length, failures: healthSamples.filter(entry => !entry.ok).length, slow: 0, longestGapMs: 2_000, longestGap: null }, + healthClasses: summarizeFailures(healthSamples), duplicates: { overlappingRuns: [], duplicateComments: [], duplicateChildren: [] }, releases: [], metrics: [] }); + +describe("gate D failure classifier", () => { + it("counts a reset as server-side when the control probe to the neutral endpoint succeeded", () => { + expect(classifyFailure(diagnosis())).toMatchObject({ class: "server", reason: expect.stringContaining("connection reset (ECONNRESET)") }); + expect(classifyFailure(diagnosis({ cause: { name: "Error", message: "connect ECONNREFUSED", code: "ECONNREFUSED" } })).class).toBe("server"); + }); + + it("counts a reset as client-side when the control probe failed too", () => { + expect(classifyFailure(diagnosis({ control: down }))).toMatchObject({ class: "client", reason: expect.stringContaining("control probe") }); + expect(classifyFailure(diagnosis({ cause: { name: "Error", message: "connect timeout", code: "UND_ERR_CONNECT_TIMEOUT" }, + control: { ...down, error: { name: "TimeoutError", message: "aborted" } } })).class).toBe("client"); + }); + + it("counts a stalled client timer as client-side even when the control probe succeeded", () => { + const slept = diagnosis({ aborted: true, cause: { name: "TimeoutError", message: "The operation was aborted due to timeout" }, + clock: clock({ elapsedMs: 18_500, monotonicMs: 10_020, timerLagMs: 8_500, clockJumpMs: 8_480 }) }); + expect(classifyFailure(slept)).toMatchObject({ class: "client", reason: expect.stringMatching(/^client_stall: the 10000 ms abort fired after 18500 ms/) }); + expect(classifyFailure(diagnosis({ clock: clock({ gapBeforeMs: 16_000 }) })).reason).toMatch(/^client_stall: the probe loop paused 16000 ms/); + expect(classifyFailure(diagnosis({ clock: clock({ loopDelayMaxMs: 4_000 }) })).reason).toMatch(/^client_stall: the event loop was blocked/); + const onTime = diagnosis({ aborted: true, cause: { name: "TimeoutError", message: "aborted" }, clock: clock({ elapsedMs: 10_004, monotonicMs: 10_004, timerLagMs: 4 }) }); + expect(classifyFailure(onTime)).toMatchObject({ class: "server", reason: expect.stringContaining("timeout") }); + }); + + it("does not trust a failed control probe when the neutral endpoint never answered in this run", () => { + expect(classifyFailure(diagnosis({ control: down, controlReachedThisRun: false }))).toMatchObject({ class: "unclassified", + reason: expect.stringContaining("has not answered once in this run") }); + const blocked = [{ at: 0, ok: true, status: 200, ms: 40, processStartedAt: "old", commit: "c" }, sample(2_000, diagnosis({ control: down, controlReachedThisRun: false })), + { at: 4_000, ok: true, status: 200, ms: 40, processStartedAt: "new", commit: "c" }]; + expect(detectReleases(blocked, { now: 600_000 })[0]!.shape).toBe("stop_then_start"); + expect(hostedGate(gateInput(blocked)).pass).toBe(false); + }); + + it("counts a pending diagnosis as unclassified in the summary", () => { + const pending = sample(1, diagnosis({ control: down })); + pending.failure = { ...pending.failure!, state: "pending" }; + expect(summarizeFailures([pending]).failures[0]).toMatchObject({ class: "unclassified", reason: "diagnosis did not finish before the grade" }); + pending.failure = { ...pending.failure!, class: "client" }; + const gap = [{ at: 0, ok: true, status: 200, ms: 40, processStartedAt: "old", commit: "c" }, { ...pending, at: 2_000 }, + { at: 4_000, ok: true, status: 200, ms: 40, processStartedAt: "new", commit: "c" }]; + expect(detectReleases(gap, { now: 600_000 })[0]!.shape).toBe("stop_then_start"); + }); + + it("counts a client DNS failure as client-side", () => { + expect(classifyFailure(diagnosis({ cause: { name: "Error", message: "getaddrinfo EAI_AGAIN", code: "EAI_AGAIN", hostname: host } })).class).toBe("client"); + expect(classifyFailure(diagnosis({ cause: { name: "Error", message: "getaddrinfo ENOTFOUND", code: "ENOTFOUND", hostname: host } })).class).toBe("client"); + expect(classifyFailure(diagnosis({ cause: { name: "Error", message: "getaddrinfo ENOTFOUND", code: "ENOTFOUND", hostname: host }, + retry: { ...down, error: { name: "Error", message: "getaddrinfo ENOTFOUND", code: "ENOTFOUND" } } })).class).toBe("unclassified"); + }); + + it("leaves a failure without enough evidence unclassified, and gate D fails on it", () => { + const bare = diagnosis({ cause: { name: "TypeError", message: "fetch failed" }, control: null, retry: null }); + expect(classifyFailure(bare).class).toBe("unclassified"); + expect(classifyFailure(diagnosis({ cause: { name: "Error", message: "certificate has expired", code: "CERT_HAS_EXPIRED" } })).class).toBe("unclassified"); + expect(classifyFailure(undefined)).toEqual({ class: "unclassified", reason: "no diagnosis recorded" }); + const gate = hostedGate(gateInput([sample(1, null), sample(2, bare)])); + expect(gate.pass).toBe(false); + expect(gate.lines).toContain("- FAIL health probes: 1 of 2 failed (0 server-side, 1 unclassified, 0 client-side, informational)"); + }); + + it("fails gate D on a failed health report whose samples are missing from the class summary", () => { + const failedReport = { ...gateInput([]), health: { requests: 10, failures: 1, slow: 0, longestGapMs: 2_000, longestGap: null } }; + const withEmptySummary = hostedGate(failedReport); + expect(withEmptySummary).toMatchObject({ pass: false, healthFailures: 1 }); + expect(withEmptySummary.lines).toContain("- FAIL health probes: 1 of 10 failed (0 server-side, 1 unclassified, 0 client-side, informational)"); + const { healthClasses: _ignored, ...withoutSummary } = failedReport; + expect(hostedGate(withoutSummary)).toMatchObject({ pass: false, healthFailures: 1 }); + }); + + it("does not call a release stop-then-start for a client-side failure in the swap gap", () => { + const answer = (at: number, processStartedAt: string): HealthSample => ({ at, ok: true, status: 200, ms: 40, processStartedAt, commit: "c" }); + const withGapFailure = (failure: FailureDiagnosis) => [answer(0, "old"), answer(2_000, "old"), sample(4_000, failure), answer(6_000, "new"), answer(8_000, "new")]; + const client = detectReleases(withGapFailure(diagnosis({ control: down })), { now: 600_000 }); + expect(client).toHaveLength(1); + expect(client[0]).toMatchObject({ shape: "clean_switch", failedRequests: 0, firstFailureAt: null }); + expect(detectReleases(withGapFailure(diagnosis()), { now: 600_000 })[0]).toMatchObject({ shape: "stop_then_start", failedRequests: 1 }); + const unclassified = diagnosis({ cause: { name: "TypeError", message: "fetch failed" }, control: null, retry: null }); + expect(detectReleases(withGapFailure(unclassified), { now: 600_000 })[0]!.shape).toBe("stop_then_start"); + }); + + it("passes gate D with only client-side failures and keeps them visible as informational lines", () => { + const samples = [sample(Date.parse("2026-11-23T08:05:35.000Z"), diagnosis({ control: down })), sample(Date.parse("2026-11-23T08:05:37.000Z"), null)]; + const gate = hostedGate(gateInput(samples)); + expect(gate).toMatchObject({ pass: true, healthFailures: 0, healthClientSide: 1 }); + expect(gate.lines).toContain("- pass health probes: 1 of 2 failed (0 server-side, 0 unclassified, 1 client-side, informational)"); + const lines = failureLines("Health probe failures", summarizeFailures(samples)); + expect(lines[0]).toBe("Health probe failures: 0 server-side, 0 unclassified, 1 client-side (informational, not counted by gate D)."); + expect(lines[1]).toMatch(/^- 2026-11-23T08:05:35\.000Z client-side \(informational\): the control probe .*Evidence: ECONNRESET read; .*control failed ENETUNREACH in 42 ms; retry ok 200/); + expect(hostedGate(gateInput([sample(1, diagnosis())])).pass).toBe(false); + const { healthClasses: _ignored, ...withoutClasses } = gateInput([sample(1, diagnosis({ control: down }))]); + expect(hostedGate(withoutClasses).pass).toBe(false); + }); +}); + +describe("hosted request failure recording", () => { + it("records the 503's status, headers, body excerpt, parsed error and statusPage code, and counts it server-side", async () => { + const body = JSON.stringify({ error: "Workspace is waking up", statusPage: { code: "idle_sweep" }, padding: "x".repeat(2_000) }); + const headers = { "x-paperclip-status": "waking", "retry-after": "5", server: "railway-edge", via: "1.1 railway", "x-railway-request-id": "req-1", "x-railway-edge": "edge-1", + "cf-ray": "8f-SJC", date: "Mon, 23 Nov 2026 08:05:35 GMT", "content-type": "application/json", "cache-control": "no-store", connection: "keep-alive", "set-cookie": "secret=1" }; + const controlCalls: string[] = []; + const api = new HostedApi(target, "t", 1_000, (async () => new Response(body, { status: 503, headers })) as unknown as typeof fetch, + { control: (async (url: string) => { controlCalls.push(url); return new Response("ok", { status: 200 }); }) as unknown as typeof fetch }); + const health = await api.health(); + await api.settleDiagnostics(); + expect(health).toMatchObject({ ok: false, status: 503 }); + const failure = health.failure!; + expect(failure).toMatchObject({ class: "server", reason: "HTTP 503", url: "/api/health", method: "GET" }); + expect(failure.answer).toMatchObject({ status: 503, error: "Workspace is waking up", statusPageCode: "idle_sweep" }); + const { "set-cookie": _cookie, ...kept } = headers; + expect(failure.answer!.headers).toEqual(kept); + expect(Buffer.byteLength(failure.answer!.bodyExcerpt)).toBe(512); + expect(failure.control).toMatchObject({ ok: true, status: 200 }); + expect(failure.retry).toMatchObject({ ok: false, status: 503 }); + expect(controlCalls).toEqual(["https://www.cloudflare.com/cdn-cgi/trace"]); + expect(api.requests).toHaveLength(1); + expect(api.requests[0]!.failure).toBe(failure); + }); + + it("records undici's error cause and socket for a reset, and classifies it by the control probe", async () => { + const reset = new HostedApi(target, "t", 1_000, (async () => { throw resetError(); }) as unknown as typeof fetch, + { control: (async () => new Response("ok", { status: 200 })) as unknown as typeof fetch }); + const sampleOk = await reset.health(); + await reset.settleDiagnostics(); + expect(sampleOk.error).toBe("fetch failed (UND_ERR_SOCKET)"); + expect(sampleOk.failure).toMatchObject({ class: "server", cause: { code: "UND_ERR_SOCKET", message: "fetch failed: other side closed", + socket: { localAddress: "192.168.1.20", localPort: 51799, remoteAddress: "66.33.22.11", remotePort: 443, bytesWritten: 612, bytesRead: 0 } } }); + let controlUp = true; + const flaky = new HostedApi(target, "t", 1_000, (async () => { throw resetError(); }) as unknown as typeof fetch, + { control: (async () => { + if (controlUp) return new Response("ok", { status: 200 }); + throw new TypeError("fetch failed", { cause: Object.assign(new Error("connect ENETUNREACH"), { code: "ENETUNREACH", syscall: "connect" }) }); + }) as unknown as typeof fetch }); + expect(await flaky.primeControl()).toMatchObject({ ok: true }); + controlUp = false; + await new Promise(resolve => setTimeout(resolve, 1_050)); + const flakySample = await flaky.health(); + await flaky.settleDiagnostics(); + expect(flakySample.failure).toMatchObject({ class: "client", control: { ok: false, error: { code: "ENETUNREACH", syscall: "connect" } } }); + }); + + it("does not repeat a failed non-GET request as the immediate retry", async () => { + let calls = 0; + const api = new HostedApi(target, "t", 1_000, (async () => { calls += 1; throw resetError(); }) as unknown as typeof fetch, + { control: (async () => new Response("ok", { status: 200 })) as unknown as typeof fetch }); + await expect(api.post("/api/companies/c1/issues", { title: "x" })).rejects.toThrow(/unreachable: fetch failed \(UND_ERR_SOCKET\)/); + await api.settleDiagnostics(); + expect(calls).toBe(1); + expect(api.requests[0]!.failure).toMatchObject({ retry: null, control: { ok: true }, class: "server" }); + }); + + it("returns a failed probe without waiting for the control probe and attaches its evidence later", async () => { + let release: (response: Response) => void = () => {}; + const control = (() => new Promise(resolve => { release = resolve; })) as unknown as typeof fetch; + const api = new HostedApi(target, "t", 1_000, (async () => { throw resetError(); }) as unknown as typeof fetch, { control }); + const health = await api.health(); + expect(health.failure).toMatchObject({ class: "unclassified", reason: "diagnosis pending", control: null }); + await expect(api.post("/api/companies/c1/issues", {})).rejects.toThrow(/unreachable/); + let written = false; + const done = api.diagnosed(health.failure).then(() => { written = true; }); + await new Promise(resolve => setTimeout(resolve, 10)); + expect(written).toBe(false); + release(new Response("ok", { status: 200 })); + await api.settleDiagnostics(); + await done; + expect(health.failure).toMatchObject({ class: "server", control: { ok: true } }); + expect(api.requests[1]!.failure).toMatchObject({ class: "server", control: { ok: true } }); + }); + + it("waits only for the frozen failures, up to a deadline, and leaves an unfinished one unclassified with the reason", async () => { + const api = new HostedApi(target, "t", 1_000, (async () => { throw resetError(); }) as unknown as typeof fetch, + { control: (() => new Promise(() => undefined)) as unknown as typeof fetch }); + const health = await api.health(); + expect(await api.settleDiagnostics([])).toBe(0); + expect(await api.settleDiagnostics([health.failure], 20)).toBe(1); + expect(health.failure).toMatchObject({ state: "pending" }); + expect(summarizeFailures([health]).failures[0]).toMatchObject({ class: "unclassified", reason: "diagnosis did not finish before the grade" }); + const gate = hostedGate(gateInput([health])); + expect(gate.pass).toBe(false); + }); + + it("keeps a diagnosis that missed the grade's deadline pending when its evidence arrives later", async () => { + let release: (response: Response) => void = () => {}; + const api = new HostedApi(target, "t", 1_000, (async () => { throw resetError(); }) as unknown as typeof fetch, + { control: (() => new Promise(resolve => { release = resolve; })) as unknown as typeof fetch }); + const health = await api.health(); + expect(await api.settleDiagnostics([health.failure], 10)).toBe(1); + release(new Response("ok", { status: 200 })); + await api.diagnosed(health.failure); + expect(health.failure).toMatchObject({ state: "pending", control: { ok: true } }); + expect(summarizeFailures([health]).unclassified).toBe(1); + }); + + it("reads the error and statusPage code from a truncated JSON body", () => { + const truncated = `{"error":"Workspace is waking up","statusPage":{"code":"idle_sweep","title":"x"},"padding":"${"x".repeat(100)}`; + expect(answerEvidence(503, new Headers(), truncated)).toMatchObject({ error: "Workspace is waking up", statusPageCode: "idle_sweep" }); + }); + + it("skips the same-URL retry after a timeout", async () => { + let calls = 0; + const api = new HostedApi(target, "t", 1_000, (async () => { calls += 1; throw new DOMException("The operation was aborted due to timeout", "TimeoutError"); }) as unknown as typeof fetch, + { control: (async () => new Response("ok", { status: 200 })) as unknown as typeof fetch }); + const health = await api.health(); + await api.settleDiagnostics(); + expect(calls).toBe(1); + expect(health.failure).toMatchObject({ aborted: true, retry: null, control: { ok: true }, class: "server" }); + }); + + it("runs no control probe unless the live entry point or a test asks for one", async () => { + const api = new HostedApi(target, "t", 1_000, (async () => { throw resetError(); }) as unknown as typeof fetch); + const health = await api.health(); + await api.settleDiagnostics(); + expect(health.failure).toMatchObject({ control: null, retry: null, class: "unclassified" }); + }); + + it("records a retry whose body cannot be read as failed", async () => { + const broken = new ReadableStream({ start(controller) { controller.error(Object.assign(new Error("terminated"), { code: "UND_ERR_SOCKET" })); } }); + const outcome = await followUp((async () => new Response(broken, { status: 200 })) as unknown as typeof fetch, "https://example.test/api/health", {}, 1_000); + expect(outcome).toMatchObject({ ok: false, status: 200, error: { code: "UND_ERR_SOCKET" } }); + }); + + it("writes a failed probe to health.jsonl only after its diagnosis, with the class", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "hosted-diag-")); + const file = path.join(dir, "health.jsonl"); + const api = new HostedApi(target, "t", 1_000, (async () => { throw resetError(); }) as unknown as typeof fetch, + { control: (async () => new Response("ok", { status: 200 })) as unknown as typeof fetch }); + const events: string[] = []; + const onSample = watchIdentity({ add: kind => { events.push(kind); } }, file, api); + onSample(await api.health()); + await api.settleDiagnostics(); + await new Promise(resolve => setImmediate(resolve)); + const saved = JSON.parse(await readFile(file, "utf8")); + await rm(dir, { recursive: true, force: true }); + expect(saved.failure).toMatchObject({ class: "server", control: { ok: true } }); + expect(events).toEqual(["hosted_health_failed", "hosted_health_failure_classified"]); + }); + + it("passes the gap before each probe to the health check", async () => { + const seen: Array = []; + const probe = new HealthProbe({ health: async context => { seen.push(context?.gapBeforeMs ?? null); return sample(Date.now(), null); } }, 5).start(); + while (seen.length < 3) await new Promise(resolve => setTimeout(resolve, 5)); + await probe.stop(); + expect(seen[0]).toBeNull(); + expect(seen.slice(1).every(gap => gap !== null && gap >= 0 && gap < 1_000)).toBe(true); + }); +}); + +describe("connection evidence", () => { + async function listen(handler: http.RequestListener): Promise<{ url: string; ports: number[] }> { + const ports: number[] = []; + const server = http.createServer((request, response) => { ports.push((request.socket as Socket).remotePort!); handler(request, response); }); + servers.push(server); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + return { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/health`, ports }; + } + + it("opens a fresh connection for every health probe and records its phases", async () => { + const { url, ports } = await listen((_request, response) => response.end("{}")); + for (let index = 0; index < 2; index += 1) { + const id = newRequestId(); + const response = await freshConnectionFetch(url, { headers: { [REQUEST_ID_HEADER]: id } }); + expect(await response.text()).toBe("{}"); + expect(connections.take(id)).toMatchObject({ reused: false, remoteAddress: "127.0.0.1", connectMs: expect.any(Number), ttfbMs: expect.any(Number) }); + } + expect(new Set(ports).size).toBe(2); + }); + + it("tags an API request's socket as new or reused", async () => { + connections.subscribe(); + const { url, ports } = await listen((_request, response) => response.end("{}")); + const tags: Array = []; + for (let index = 0; index < 2; index += 1) { + const id = newRequestId(); + await (await fetch(url, { headers: { [REQUEST_ID_HEADER]: id } })).text(); + await new Promise(resolve => setTimeout(resolve, 20)); + tags.push(connections.take(id)?.reused ?? null); + } + expect(tags).toEqual([false, true]); + expect(new Set(ports).size).toBe(1); + }); + + it("follows a same-origin redirect on a fresh connection and stops at a cross-origin one", async () => { + const { url } = await listen((request, response) => { + if (request.url === "/api/health") { response.writeHead(308, { location: "/api/health/" }).end(); return; } + if (request.url === "/away") { response.writeHead(302, { location: "https://elsewhere.example/" }).end(); return; } + response.end("{\"status\":\"ok\"}"); + }); + const followed = await freshConnectionFetch(url); + expect(followed.status).toBe(200); + expect(await followed.text()).toBe("{\"status\":\"ok\"}"); + expect((await freshConnectionFetch(url.replace("/api/health", "/away"))).status).toBe(302); + }); + + it("keeps the status, headers and partial body when an answer is cut short, and counts the 503 server-side", async () => { + const { url } = await listen((_request, response) => { + response.writeHead(503, { "content-type": "application/json", "x-paperclip-status": "draining", "content-length": "500" }); + response.write("{\"error\":\"draining\""); + setTimeout(() => response.socket?.destroy(), 20); + }); + const api = new HostedApi(target, "t", 1_000, fetch, { health: ((_input: string, init: RequestInit) => freshConnectionFetch(url, init)) as unknown as typeof fetch, + control: (async () => new Response("ok", { status: 200 })) as unknown as typeof fetch }); + const health = await api.health(); + await api.settleDiagnostics(); + expect(health).toMatchObject({ ok: false, status: 503 }); + expect(health.failure).toMatchObject({ class: "server", reason: "HTTP 503", cause: { code: "ECONNRESET" }, + answer: { status: 503, headers: { "x-paperclip-status": "draining" }, bodyExcerpt: "{\"error\":\"draining\"" } }); + }); + + it("stops reading a large non-2xx body and still keeps its parsed error and statusPage code", async () => { + const { url } = await listen((_request, response) => { + response.writeHead(503, { "content-type": "application/json" }); + response.end(JSON.stringify({ error: "Workspace is waking up", statusPage: { code: "idle_sweep" }, padding: "x".repeat(500_000) })); + }); + const answer = await freshConnectionFetch(url); + expect(answer.status).toBe(503); + const text = await answer.text(); + expect(text.length).toBe(16 * 1024); + const evidence = answerEvidence(503, answer.headers, text); + expect(evidence).toMatchObject({ error: "Workspace is waking up", statusPageCode: "idle_sweep" }); + expect(Buffer.byteLength(evidence.bodyExcerpt)).toBe(512); + }); + + it("reports a reset on a fresh connection with the socket's addresses and byte counts", async () => { + const { url } = await listen(request => request.socket.destroy()); + const error = await freshConnectionFetch(url).catch(caught => caught as TypeError); + expect(error).toBeInstanceOf(TypeError); + expect((error as TypeError & { cause: { code: string; socket: Record } }).cause).toMatchObject({ code: "ECONNRESET", + socket: { remoteAddress: "127.0.0.1", bytesWritten: expect.any(Number) } }); + }); +}); diff --git a/tests/restart-chaos/hosted-diagnostics.ts b/tests/restart-chaos/hosted-diagnostics.ts new file mode 100644 index 00000000000..d78b9148098 --- /dev/null +++ b/tests/restart-chaos/hosted-diagnostics.ts @@ -0,0 +1,390 @@ +import { randomUUID } from "node:crypto"; +import dc from "node:diagnostics_channel"; +import http from "node:http"; +import https from "node:https"; +import type { Socket } from "node:net"; +import { monitorEventLoopDelay, performance, type IntervalHistogram } from "node:perf_hooks"; + +export const REQUEST_ID_HEADER = "x-restart-chaos-request"; +export const CONTROL_URL = "https://www.cloudflare.com/cdn-cgi/trace"; +export const CONTROL_TIMEOUT_MS = 5_000; +export const STALL_MS = 1_000; +export const BODY_EXCERPT_BYTES = 512; +export const ERROR_BODY_READ_BYTES = 16 * 1024; +export const RETRY_TIMEOUT_MS = 2_000; +export const EVIDENCE_HEADERS = ["x-paperclip-status", "retry-after", "server", "via", "x-railway-request-id", "x-railway-edge", "cf-ray", "date", "content-type", + "cache-control", "connection"] as const; + +export interface SocketSnapshot { localAddress?: string; localPort?: number; remoteAddress?: string; remotePort?: number; remoteFamily?: string; bytesWritten?: number; bytesRead?: number } +export interface ErrorCause { name: string; message: string; code?: string; errno?: number; syscall?: string; hostname?: string; address?: string; port?: number; + socket?: SocketSnapshot; causes?: ErrorCause[] } +export interface ConnectionInfo { reused: boolean | null; remoteAddress: string | null; remotePort: number | null; localAddress: string | null; localPort: number | null; + dnsMs: number | null; connectMs: number | null; tlsMs: number | null; ttfbMs: number | null } +export interface AnswerEvidence { status: number; headers: Record; bodyExcerpt: string; error: string | null; statusPageCode: string | null } +export interface ClientClock { timeoutMs: number; elapsedMs: number; monotonicMs: number; timerLagMs: number | null; clockJumpMs: number; loopDelayMaxMs: number | null; + gapBeforeMs: number | null; intervalMs: number | null } +export interface FollowUp { url: string; ok: boolean; status: number | null; ms: number; error: ErrorCause | null; remoteAddress: string | null } +export interface FailureDiagnosis { url: string; method: string; aborted: boolean; answer: AnswerEvidence | null; cause: ErrorCause | null; connection: ConnectionInfo | null; + clock: ClientClock; control: FollowUp | null; retry: FollowUp | null; controlReachedThisRun: boolean } +export type FailureClass = "client" | "server" | "unclassified"; +export interface Classified { class: FailureClass; reason: string } +export type FailureRecord = FailureDiagnosis & Classified & { state: "pending" | "settled" }; +export const isClientSide = (failure: FailureRecord | null | undefined) => failure?.state === "settled" && failure.class === "client"; +export interface ProbeContext { gapBeforeMs: number | null; intervalMs: number | null } + +const DNS_CODES = new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_FAIL", "EAI_NODATA", "EAI_NONAME"]); +const RESET_CODES = new Set(["ECONNRESET", "EPIPE", "ECONNABORTED", "UND_ERR_SOCKET", "UND_ERR_CLOSED"]); +const REFUSED_CODES = new Set(["ECONNREFUSED"]); +const TIMEOUT_CODES = new Set(["ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT"]); + +const pick = (value: unknown, type: "string" | "number"): T | undefined => typeof value === type ? value as T : undefined; + +export function socketSnapshot(socket: unknown): SocketSnapshot | undefined { + if (!socket || typeof socket !== "object") return undefined; + const raw = socket as Record; + const snapshot: SocketSnapshot = { localAddress: pick(raw.localAddress, "string"), localPort: pick(raw.localPort, "number"), remoteAddress: pick(raw.remoteAddress, "string"), + remotePort: pick(raw.remotePort, "number"), remoteFamily: pick(raw.remoteFamily, "string"), bytesWritten: pick(raw.bytesWritten, "number"), bytesRead: pick(raw.bytesRead, "number") }; + const kept = Object.fromEntries(Object.entries(snapshot).filter(([, value]) => value !== undefined)); + return Object.keys(kept).length ? kept : undefined; +} + +function describeError(error: unknown, depth: number): ErrorCause { + if (!error || typeof error !== "object") return { name: "Error", message: String(error) }; + const raw = error as Record; + const cause: ErrorCause = { name: String(raw.name ?? "Error"), message: String(raw.message ?? "") }; + const code = pick(raw.code, "string"); + if (code) cause.code = code; + const errno = pick(raw.errno, "number"); + if (errno !== undefined) cause.errno = errno; + for (const key of ["syscall", "hostname", "address"] as const) { const value = pick(raw[key], "string"); if (value) cause[key] = value; } + const port = pick(raw.port, "number"); + if (port !== undefined) cause.port = port; + const socket = socketSnapshot(raw.socket); + if (socket) cause.socket = socket; + if (depth < 2 && Array.isArray(raw.errors) && raw.errors.length) cause.causes = raw.errors.slice(0, 4).map(inner => describeError(inner, depth + 1)); + return cause; +} + +export function errorCause(error: unknown): ErrorCause { + const outer = describeError(error, 0); + const inner = error && typeof error === "object" ? (error as { cause?: unknown }).cause : undefined; + if (!inner || typeof inner !== "object") return outer; + const cause = describeError(inner, 0); + if (!cause.code && cause.causes?.[0]?.code) cause.code = cause.causes[0].code; + return { ...cause, message: cause.message ? `${outer.message}: ${cause.message}` : outer.message }; +} + +export const isAbort = (error: unknown) => error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError"); + +export function answerEvidence(status: number, headers: Headers, text: string): AnswerEvidence { + const kept: Record = {}; + for (const name of EVIDENCE_HEADERS) { const value = headers.get(name); if (value !== null) kept[name] = value; } + const bytes = Buffer.from(text, "utf8"); + const bodyExcerpt = bytes.length <= BODY_EXCERPT_BYTES ? text : bytes.subarray(0, BODY_EXCERPT_BYTES).toString("utf8"); + let error: string | null = null; + let statusPageCode: string | null = null; + try { + const body = JSON.parse(text) as { error?: unknown; statusPage?: { code?: unknown } }; + if (typeof body.error === "string") error = body.error; + else if (body.error && typeof body.error === "object") error = JSON.stringify(body.error).slice(0, 200); + if (body.statusPage?.code !== undefined && body.statusPage.code !== null) statusPageCode = String(body.statusPage.code); + } catch { + error = /"error"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(text)?.[1] ?? null; + statusPageCode = /"statusPage"\s*:\s*\{[^{}]*?"code"\s*:\s*"?([^",}\s]+)/.exec(text)?.[1] ?? null; + } + return { status, headers: kept, bodyExcerpt, error, statusPageCode }; +} + +let loopDelay: IntervalHistogram | null = null; + +export function watchEventLoop(): void { + if (loopDelay) return; + loopDelay = monitorEventLoopDelay({ resolution: 20 }); + loopDelay.enable(); +} + +export function eventLoopDelayMaxMs(): number | null { + return loopDelay && loopDelay.count > 0 ? Math.round(loopDelay.max / 1e6) : null; +} + +export function resetEventLoopDelay(): void { loopDelay?.reset(); } + +export interface ClockStart { wall: number; mono: number } +export const startClock = (): ClockStart => ({ wall: Date.now(), mono: performance.now() }); + +export function readClock(start: ClockStart, timeoutMs: number, aborted: boolean, probe: ProbeContext | undefined): ClientClock { + const elapsedMs = Date.now() - start.wall; + const monotonicMs = Math.round(performance.now() - start.mono); + return { timeoutMs, elapsedMs, monotonicMs, timerLagMs: aborted ? elapsedMs - timeoutMs : null, clockJumpMs: elapsedMs - monotonicMs, + loopDelayMaxMs: eventLoopDelayMaxMs(), gapBeforeMs: probe?.gapBeforeMs ?? null, intervalMs: probe?.intervalMs ?? null }; +} + +interface Tracked { id: string; sentAt: number | null; info: ConnectionInfo } +const emptyInfo = (): ConnectionInfo => ({ reused: null, remoteAddress: null, remotePort: null, localAddress: null, localPort: null, dnsMs: null, connectMs: null, tlsMs: null, ttfbMs: null }); + +class ConnectionTracker { + private readonly byId = new Map(); + private readonly byRequest = new WeakMap(); + private readonly connectStarted = new WeakMap(); + private readonly socketConnectMs = new WeakMap(); + private readonly socketUses = new WeakMap(); + private subscribed = false; + + subscribe(): void { + if (this.subscribed) return; + this.subscribed = true; + dc.subscribe("undici:request:create", message => { + const request = (message as { request?: { headers?: unknown } }).request; + const id = request ? requestIdOf(request.headers) : null; + if (!request || !id) return; + const tracked: Tracked = { id, sentAt: null, info: emptyInfo() }; + this.byId.set(id, tracked); + this.byRequest.set(request, tracked); + }); + dc.subscribe("undici:client:beforeConnect", message => { + const params = (message as { connectParams?: object }).connectParams; + if (params) this.connectStarted.set(params, performance.now()); + }); + dc.subscribe("undici:client:connected", message => { + const { connectParams, socket } = message as { connectParams?: object; socket?: object }; + const started = connectParams ? this.connectStarted.get(connectParams) : undefined; + if (socket && started !== undefined) this.socketConnectMs.set(socket, Math.round(performance.now() - started)); + }); + dc.subscribe("undici:client:sendHeaders", message => { + const { request, socket } = message as { request?: object; socket?: Socket }; + const tracked = request ? this.byRequest.get(request) : undefined; + if (!tracked || !socket) return; + const uses = this.socketUses.get(socket) ?? 0; + this.socketUses.set(socket, uses + 1); + tracked.sentAt = performance.now(); + Object.assign(tracked.info, { reused: uses > 0, remoteAddress: socket.remoteAddress ?? null, remotePort: socket.remotePort ?? null, + localAddress: socket.localAddress ?? null, localPort: socket.localPort ?? null, connectMs: uses > 0 ? null : this.socketConnectMs.get(socket) ?? null }); + }); + dc.subscribe("undici:request:headers", message => { + const request = (message as { request?: object }).request; + const tracked = request ? this.byRequest.get(request) : undefined; + if (tracked?.sentAt != null) tracked.info.ttfbMs = Math.round(performance.now() - tracked.sentAt); + }); + } + + report(id: string, info: ConnectionInfo): void { this.byId.set(id, { id, sentAt: null, info }); } + + take(id: string): ConnectionInfo | null { + const tracked = this.byId.get(id); + this.byId.delete(id); + return tracked ? tracked.info : null; + } +} + +function requestIdOf(headers: unknown): string | null { + if (Array.isArray(headers)) { + for (let index = 0; index + 1 < headers.length; index += 2) if (String(headers[index]).toLowerCase() === REQUEST_ID_HEADER) return String(headers[index + 1]); + return null; + } + if (typeof headers === "string") return new RegExp(`${REQUEST_ID_HEADER}: ([^\\r\\n]+)`, "i").exec(headers)?.[1] ?? null; + return null; +} + +export const connections = new ConnectionTracker(); +export const newRequestId = () => randomUUID(); + +const NULL_BODY_STATUSES = new Set([101, 204, 205, 304]); + +export interface PartialAnswer { status: number; headers: Headers; body: string } +export const MAX_REDIRECTS = 3; +const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); + +export function partialAnswerOf(error: unknown): PartialAnswer | null { + for (let current = error, depth = 0; current && typeof current === "object" && depth < 3; current = (current as { cause?: unknown }).cause, depth += 1) { + const answer = (current as { answer?: PartialAnswer }).answer; + if (answer && typeof answer.status === "number") return answer; + } + return null; +} + +function answerHeaders(raw: http.IncomingHttpHeaders): Headers { + const headers = new Headers(); + for (const [name, value] of Object.entries(raw)) if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(", ") : value); + return headers; +} + +function freshHop(url: URL, init: RequestInit, headers: Record, id: string | null): Promise { + const client = url.protocol === "http:" ? http : https; + const info = emptyInfo(); + info.reused = false; + const started = performance.now(); + const since = () => Math.round(performance.now() - started); + return new Promise((resolve, reject) => { + let settled = false; + let answered: { response: http.IncomingMessage; chunks: Buffer[] } | null = null; + const partial = (): PartialAnswer | undefined => answered ? { status: answered.response.statusCode ?? 0, headers: answerHeaders(answered.response.headers), + body: Buffer.concat(answered.chunks).toString("utf8") } : undefined; + const failed = (error: Error) => new TypeError("fetch failed", { cause: Object.assign(error, { answer: partial(), socket: socketSnapshot({ localAddress: info.localAddress, + localPort: info.localPort, remoteAddress: info.remoteAddress, remotePort: info.remotePort, bytesWritten: request.socket?.bytesWritten, bytesRead: request.socket?.bytesRead }) }) }); + const finish = (outcome: () => void) => { if (settled) return; settled = true; init.signal?.removeEventListener("abort", onAbort); if (id) connections.report(id, info); outcome(); }; + const request = client.request(url, { method: init.method ?? "GET", headers, agent: false }); + const onAbort = () => { + request.destroy(); + const reason = init.signal!.reason as Error; + finish(() => reject(answered ? Object.assign(new Error(reason.message), { name: reason.name, answer: partial() }) : reason)); + }; + if (init.signal?.aborted) { onAbort(); return; } + init.signal?.addEventListener("abort", onAbort, { once: true }); + request.on("socket", socket => { + socket.once("lookup", () => { info.dnsMs = since(); }); + socket.once("connect", () => { info.connectMs = since(); Object.assign(info, { remoteAddress: socket.remoteAddress ?? null, remotePort: socket.remotePort ?? null, + localAddress: socket.localAddress ?? null, localPort: socket.localPort ?? null }); }); + socket.once("secureConnect", () => { info.tlsMs = since() - (info.connectMs ?? 0); }); + }); + request.on("response", response => { + info.ttfbMs = since(); + answered = { response, chunks: [] }; + const status = response.statusCode ?? 0; + const limit = status >= 200 && status < 300 ? Number.POSITIVE_INFINITY : ERROR_BODY_READ_BYTES; + let kept = 0; + const complete = () => finish(() => resolve(new Response(NULL_BODY_STATUSES.has(status) ? null : Buffer.concat(answered!.chunks), + { status, statusText: response.statusMessage, headers: answerHeaders(response.headers) }))); + response.on("data", (chunk: Buffer) => { + const piece = chunk.subarray(0, Math.min(chunk.length, limit - kept)); + kept += piece.length; + answered!.chunks.push(Buffer.from(piece)); + if (kept >= limit) { + complete(); + request.destroy(); + } + }); + response.on("error", error => finish(() => reject(failed(error)))); + response.on("aborted", () => finish(() => reject(failed(Object.assign(new Error("the answer was cut short"), { code: "ECONNRESET" }))))); + response.on("end", complete); + }); + request.on("error", error => finish(() => reject(failed(error)))); + request.end(typeof init.body === "string" ? init.body : undefined); + }); +} + +export const freshConnectionFetch = (async (input: string | URL | Request, init: RequestInit = {}): Promise => { + const origin = new URL(input instanceof Request ? input.url : String(input)); + const headers: Record = { ...Object.fromEntries(new Headers(init.headers).entries()), connection: "close" }; + const id = headers[REQUEST_ID_HEADER] ?? null; + let url = origin; + let hopInit = init; + for (let hop = 0; ; hop += 1) { + const response = await freshHop(url, hopInit, headers, id); + const location = response.headers.get("location"); + if (!REDIRECT_STATUSES.has(response.status) || !location || hop >= MAX_REDIRECTS || init.redirect === "manual") return response; + const next = new URL(location, url); + if (next.origin !== origin.origin) return response; + url = next; + if (response.status === 303) hopInit = { ...hopInit, method: "GET", body: undefined }; + } +}) as typeof fetch; + +export async function followUp(fetcher: typeof fetch, url: string, headers: Record, timeoutMs: number): Promise { + const id = newRequestId(); + const started = Date.now(); + const outcome = (fields: Pick): FollowUp => ({ url, ...fields, ms: Date.now() - started, + remoteAddress: connections.take(id)?.remoteAddress ?? null }); + let response: Response; + try { + response = await fetcher(url, { method: "GET", cache: "no-store", signal: AbortSignal.timeout(timeoutMs), headers: { ...headers, [REQUEST_ID_HEADER]: id } }); + } catch (error) { + return outcome({ ok: false, status: partialAnswerOf(error)?.status ?? null, error: errorCause(error) }); + } + try { + await response.arrayBuffer(); + } catch (error) { + return outcome({ ok: false, status: response.status, error: errorCause(error) }); + } + return outcome({ ok: response.ok, status: response.status, error: null }); +} + +export function clientStall(clock: ClientClock): string | null { + if (clock.timerLagMs !== null && clock.timerLagMs > STALL_MS) return `the ${clock.timeoutMs} ms abort fired after ${clock.elapsedMs} ms (${clock.timerLagMs} ms late)`; + if (Math.abs(clock.clockJumpMs) > STALL_MS) return `the wall clock moved ${clock.clockJumpMs} ms more than the monotonic clock`; + if (clock.loopDelayMaxMs !== null && clock.loopDelayMaxMs > STALL_MS) return `the event loop was blocked for up to ${clock.loopDelayMaxMs} ms`; + if (clock.gapBeforeMs !== null && clock.intervalMs !== null && clock.gapBeforeMs > 2 * clock.intervalMs) + return `the probe loop paused ${clock.gapBeforeMs} ms before this probe (interval ${clock.intervalMs} ms)`; + return null; +} + +const followUpText = (name: string, outcome: FollowUp | null) => outcome === null ? `${name} not run` + : outcome.ok ? `${name} ok ${outcome.status} in ${outcome.ms} ms` + : `${name} failed ${outcome.status ?? outcome.error?.code ?? outcome.error?.name ?? "?"} in ${outcome.ms} ms`; + +export function classifyFailure(diagnosis: FailureDiagnosis | null | undefined): Classified { + if (!diagnosis) return { class: "unclassified", reason: "no diagnosis recorded" }; + const answered = diagnosis.answer?.status ?? null; + const success = answered !== null && answered >= 200 && answered < 300; + if (answered !== null && !success) return { class: "server", reason: `HTTP ${answered}` }; + if (success && !diagnosis.cause) return { class: "server", reason: `HTTP ${answered} with an unreadable body` }; + const stall = clientStall(diagnosis.clock); + if (stall) return { class: "client", reason: `client_stall: ${stall}` }; + const { control, retry } = diagnosis; + const code = diagnosis.cause?.code ?? null; + if (control && !control.ok) return diagnosis.controlReachedThisRun + ? { class: "client", reason: `the control probe to the neutral endpoint failed too (${followUpText("control", control)})` } + : { class: "unclassified", reason: `the control probe failed and the neutral endpoint has not answered once in this run (${followUpText("control", control)})` }; + if (code && DNS_CODES.has(code)) { + if (code !== "ENOTFOUND") return { class: "client", reason: `client DNS failure (${code})` }; + if (retry && retry.error?.code !== "ENOTFOUND") return { class: "client", reason: "client DNS failure (ENOTFOUND, the immediate retry resolved the host)" }; + } + if (!control) return { class: "unclassified", reason: `${code ?? (diagnosis.aborted ? "timeout" : diagnosis.cause?.message ?? "failure")} without a control probe` }; + if (code && RESET_CODES.has(code)) return { class: "server", reason: `connection reset (${code}) while the control probe succeeded` }; + if (code && REFUSED_CODES.has(code)) return { class: "server", reason: `connection refused (${code}) while the control probe succeeded` }; + if (diagnosis.aborted || (code && TIMEOUT_CODES.has(code))) return { class: "server", reason: `timeout (${code ?? "abort"}) while the control probe succeeded and the client did not stall` }; + return { class: "unclassified", reason: `${code ?? diagnosis.cause?.message ?? "unknown failure"} with the control probe ok` }; +} + +export function failureEvidence(diagnosis: FailureDiagnosis | null | undefined): string { + if (!diagnosis) return "no diagnosis recorded"; + const parts: string[] = []; + if (diagnosis.answer) { + const { answer } = diagnosis; + parts.push(`status ${answer.status}`); + const headers = Object.entries(answer.headers).filter(([name]) => name !== "date" && name !== "content-type").map(([name, value]) => `${name}=${value}`); + if (headers.length) parts.push(headers.join(" ")); + if (answer.error) parts.push(`error "${answer.error}"`); + if (answer.statusPageCode) parts.push(`statusPage.code ${answer.statusPageCode}`); + if (answer.bodyExcerpt && !answer.error) parts.push(`body "${answer.bodyExcerpt.slice(0, 120).replace(/\s+/g, " ")}"`); + } + if (diagnosis.cause) { + const { cause } = diagnosis; + const where = cause.address ? ` ${cause.address}${cause.port ? `:${cause.port}` : ""}` : cause.hostname ? ` ${cause.hostname}` : ""; + parts.push(`${cause.code ?? cause.name}${cause.syscall ? ` ${cause.syscall}` : ""}${where}`); + if (cause.socket) parts.push(`socket ${cause.socket.localAddress ?? "?"}:${cause.socket.localPort ?? "?"} -> ${cause.socket.remoteAddress ?? "?"}:${cause.socket.remotePort ?? "?"}` + + `${cause.socket.bytesWritten !== undefined ? ` wrote ${cause.socket.bytesWritten} B` : ""}${cause.socket.bytesRead !== undefined ? ` read ${cause.socket.bytesRead} B` : ""}`); + } + if (diagnosis.connection) { + const { connection } = diagnosis; + parts.push(`${connection.reused === null ? "socket ?" : connection.reused ? "reused socket" : "new socket"}${connection.remoteAddress ? ` to ${connection.remoteAddress}` : ""}`); + } + const { clock } = diagnosis; + parts.push(`${clock.elapsedMs} ms of ${clock.timeoutMs} ms`); + if (clock.timerLagMs !== null) parts.push(`timer lag ${clock.timerLagMs} ms`); + if (clock.clockJumpMs) parts.push(`clock jump ${clock.clockJumpMs} ms`); + if (clock.loopDelayMaxMs !== null) parts.push(`loop delay max ${clock.loopDelayMaxMs} ms`); + if (clock.gapBeforeMs !== null) parts.push(`gap before ${clock.gapBeforeMs} ms`); + parts.push(followUpText("control", diagnosis.control), followUpText("retry", diagnosis.retry)); + return parts.join("; "); +} + +export interface ClassifiedFailure extends Classified { at: number; evidence: string } +export interface FailureClassSummary { client: number; server: number; unclassified: number; failures: ClassifiedFailure[] } + +export function summarizeFailures(entries: ReadonlyArray<{ at: number; ok: boolean; failure?: FailureRecord | null }>): FailureClassSummary { + const classOf = (failure: FailureRecord | null | undefined): Classified => !failure ? { class: "unclassified", reason: "no diagnosis recorded" } + : failure.state === "settled" ? { class: failure.class, reason: failure.reason } + : { class: "unclassified", reason: "diagnosis did not finish before the grade" }; + const failures = entries.filter(entry => !entry.ok).map((entry): ClassifiedFailure => ({ at: entry.at, ...classOf(entry.failure), evidence: failureEvidence(entry.failure) })); + return { client: failures.filter(entry => entry.class === "client").length, server: failures.filter(entry => entry.class === "server").length, + unclassified: failures.filter(entry => entry.class === "unclassified").length, failures }; +} + +const CLASS_LABEL: Record = { client: "client-side (informational)", server: "server-side", unclassified: "unclassified" }; + +export function failureLines(title: string, summary: FailureClassSummary, limit = 200): string[] { + if (!summary.failures.length) return []; + return [`${title}: ${summary.server} server-side, ${summary.unclassified} unclassified, ${summary.client} client-side (informational, not counted by gate D).`, + ...summary.failures.slice(0, limit).map(entry => `- ${new Date(entry.at).toISOString()} ${CLASS_LABEL[entry.class]}: ${entry.reason}. Evidence: ${entry.evidence}.`), + ...(summary.failures.length > limit ? [`- … ${summary.failures.length - limit} more in health.jsonl`] : [])]; +} diff --git a/tests/restart-chaos/hosted-gate.test.ts b/tests/restart-chaos/hosted-gate.test.ts index 85bb6a8954d..d02c2c2a696 100644 --- a/tests/restart-chaos/hosted-gate.test.ts +++ b/tests/restart-chaos/hosted-gate.test.ts @@ -6,7 +6,7 @@ import { hostedGate, hostedQueueWait, hostedR1, releaseOutages, subtaskRecord } import { gradeHosted } from "./hosted-grade.js"; import { continuity } from "./hosted-release.js"; import { runRow, type HostedRunRow } from "./hosted-readers.js"; -import type { DetectedRelease } from "./hosted-release.js"; +import type { DetectedRelease, HealthSample } from "./hosted-release.js"; import type { HostedTaskRecord } from "./hosted-workload.js"; import type { SwapMetrics } from "./release-swap-grade.js"; import { roundsFor, stagingMixBudgetMs, SUBTASK_ROUNDS } from "./staging-mix.js"; @@ -201,6 +201,39 @@ describe("hosted grade with the run's task records", () => { expect(graded.markdown).not.toContain("FAIL R1"); }); + it("stops the health probe, settles the frozen samples, and detects releases from them before grading", async () => { + const order: string[] = []; + const failure = { url: "/api/health", method: "GET", aborted: false, answer: null, cause: { name: "Error", message: "reset", code: "ECONNRESET" }, connection: null, + clock: { timeoutMs: 10_000, elapsedMs: 40, monotonicMs: 40, timerLagMs: null, clockJumpMs: 0, loopDelayMaxMs: 20, gapBeforeMs: null, intervalMs: 2_000 }, + control: null, retry: null, controlReachedThisRun: true, class: "unclassified" as const, reason: "diagnosis pending", state: "pending" as const }; + const answer = (at: number, processStartedAt: string) => ({ at, ok: true, status: 200, ms: 40, processStartedAt, commit: "c" }); + const samples = [answer(T0, "old"), answer(T0 + 2_000, "old"), { at: T0 + 4_000, ok: false, status: null, ms: 40, processStartedAt: null, commit: null, failure }, + answer(T0 + 6_000, "new")]; + const stale = await gradeHealth(samples, order, async () => { + order.push("settle"); + Object.assign(failure, { control: { url: "c", ok: false, status: null, ms: 40, error: { name: "TypeError", message: "fetch failed" }, remoteAddress: null }, + class: "client", reason: "control failed too", state: "settled" }); + return 0; + }); + expect(order.slice(0, 2)).toEqual(["stop", "settle"]); + expect(stale.markdown).toContain("- pass health probes: 1 of 4 failed (0 server-side, 0 unclassified, 1 client-side, informational)"); + expect(stale.markdown).toContain("- pass swap shape: no stop-then-start release"); + Object.assign(failure, { class: "unclassified", reason: "diagnosis pending", state: "pending" }); + const pending = await gradeHealth(samples, [], async () => 1); + expect(pending.pass).toBe(false); + expect(pending.markdown).toContain("FAIL swap shape: stop-then-start at release 1"); + expect(pending.markdown).toContain("diagnosis did not finish before the grade"); + }); + + const gradeHealth = async (samples: HealthSample[], order: string[], settle: () => Promise) => { + const dir = await mkdtemp(path.join(os.tmpdir(), "hosted-gate-")); + dirs.push(dir); + return gradeHosted({ api: apiFor([issue("i1")], [runOf("r1", "i1", 0, 10)]), companyId: "c1", agentIds: ["a1"], releases: [], health: () => continuity([]), + healthSamples: () => samples, stopHealthProbe: async () => { order.push("stop"); }, settleDiagnostics: settle, apiContinuity: () => continuity([]), + stopObserver: async () => {}, observedClicks: () => new Map(), lastReleaseAt: Date.now() - 1_000, settleMs: 5, drainMs: 5, dir, cancelled: () => false, + record: () => {}, pollMs: 5, tasks: () => [record()], wantedReleases: 0 }); + }; + it("fails the gate and records why when the agent list cannot be read", async () => { agentList = null; try { diff --git a/tests/restart-chaos/hosted-gate.ts b/tests/restart-chaos/hosted-gate.ts index ceafe7aa678..068673c40d4 100644 --- a/tests/restart-chaos/hosted-gate.ts +++ b/tests/restart-chaos/hosted-gate.ts @@ -1,6 +1,7 @@ import { agentSlotsFromRows, queueWaitFairnessFrom, slotFreeFrom, type QueueWaitFairness } from "./agent-slots.js"; import type { SlotFree } from "./universal.js"; import { gradeR1 } from "./grader.js"; +import type { FailureClassSummary } from "./hosted-diagnostics.js"; import type { ContinuityReport, DetectedRelease } from "./hosted-release.js"; import { ms, type HostedRunRow } from "./hosted-readers.js"; import type { HostedTaskRecord } from "./hosted-workload.js"; @@ -100,6 +101,7 @@ export interface HostedGate { r1Failed: Array<{ identifier: string | null; detail: string }>; bannersShown: number; healthFailures: number; + healthClientSide: number; duplicates: number; stopThenStart: number[]; unloaded: number[]; @@ -107,17 +109,24 @@ export interface HostedGate { } /** - * Gate D: every task hands-off and inside R1, no Retry banner, no failed health probe, no duplicated work, and every + * Gate D: every task hands-off and inside R1, no Retry banner, no server-side or unclassified failed health probe, no duplicated work, and every * release a swap two builds served (never stop-then-start) with at least one live run carried across it. A fixed batch * (`--hosted-releases 0`) waits for no release, so it is not required to see one. */ export function hostedGate(input: { handsOffPass: boolean; wantedReleases: number; createErrors: number; slotEvidenceMissing: readonly string[]; r1: ReadonlyArray<{ identifier: string | null; result: RuleResult }>; bannersShown: number; - health: ContinuityReport; duplicates: { overlappingRuns: readonly unknown[]; duplicateComments: readonly unknown[]; duplicateChildren: readonly unknown[] }; + health: ContinuityReport; healthClasses?: FailureClassSummary; duplicates: { overlappingRuns: readonly unknown[]; duplicateComments: readonly unknown[]; duplicateChildren: readonly unknown[] }; releases: readonly DetectedRelease[]; metrics: readonly SwapMetrics[] }): HostedGate { const r1Failed = input.r1.filter(entry => entry.result.verdict === "fail").map(entry => ({ identifier: entry.identifier, detail: entry.result.detail })); const duplicates = input.duplicates.overlappingRuns.length + input.duplicates.duplicateComments.length + input.duplicates.duplicateChildren.length; const stopThenStart = input.releases.filter(release => release.shape === "stop_then_start").map(release => release.index); const unloaded = input.metrics.filter(metric => metric.survivors.length === 0).map(metric => metric.index); + const classes = input.healthClasses; + const clientSide = classes?.client ?? 0; + const unmatched = classes ? Math.max(0, input.health.failures - classes.failures.length) : 0; + const unclassified = classes ? classes.unclassified + unmatched : input.health.failures; + const healthFailures = (classes?.server ?? 0) + unclassified; + const healthDetail = `${input.health.failures} of ${input.health.requests} failed` + + (classes ? ` (${classes.server} server-side, ${unclassified} unclassified, ${clientSide} client-side, informational)` : ""); const checks: Array<[string, boolean, string]> = [ ["hands-off", input.handsOffPass, input.handsOffPass ? "every started task done without a person" : "a task did not finish hands-off"], ["R1", r1Failed.length === 0, r1Failed.length ? `${r1Failed.length} failed (${r1Failed.slice(0, 3).map(entry => `${entry.identifier ?? "?"}: ${entry.detail}`).join("; ")})` @@ -126,7 +135,7 @@ export function hostedGate(input: { handsOffPass: boolean; wantedReleases: numbe ? `maxConcurrentRuns unreadable for ${input.slotEvidenceMissing.length} agent(s), so R1 queue credit cannot be proven` : "read for every agent"], ["tasks created", input.createErrors === 0, `${input.createErrors} task(s) could not be created`], ["Retry banners", input.bannersShown === 0, `${input.bannersShown} shown`], - ["health probes", input.health.failures === 0, `${input.health.failures} of ${input.health.requests} failed`], + ["health probes", healthFailures === 0, healthDetail], ["duplicates", duplicates === 0, `${duplicates} (overlapping runs, duplicated agent comments, duplicated subtasks)`], ["swap shape", stopThenStart.length === 0, stopThenStart.length ? `stop-then-start at release ${stopThenStart.join(", ")}` : "no stop-then-start release"], ...(input.wantedReleases > 0 ? [["releases under load", input.releases.length > 0 && unloaded.length === 0, @@ -134,6 +143,6 @@ export function hostedGate(input: { handsOffPass: boolean; wantedReleases: numbe : `${input.releases.length} release(s), each with a live run`]] as Array<[string, boolean, string]> : []), ]; const pass = checks.every(([, ok]) => ok); - return { pass, r1Failed, bannersShown: input.bannersShown, healthFailures: input.health.failures, duplicates, stopThenStart, unloaded, + return { pass, r1Failed, bannersShown: input.bannersShown, healthFailures, healthClientSide: clientSide, duplicates, stopThenStart, unloaded, lines: [`Gate D: ${pass ? "PASS" : "FAIL"}`, ...checks.map(([name, ok, detail]) => `- ${ok ? "pass" : "FAIL"} ${name}: ${detail}`)] }; } diff --git a/tests/restart-chaos/hosted-grade.ts b/tests/restart-chaos/hosted-grade.ts index 9ebeba5cf82..426cb0581cb 100644 --- a/tests/restart-chaos/hosted-grade.ts +++ b/tests/restart-chaos/hosted-grade.ts @@ -6,7 +6,8 @@ import { requestBreakdown, type HostedApi, type RequestRecord } from "./hosted-a import { hostedGate, hostedQueueWait, hostedR1, queuedBehindSlotCap, releaseOutages, slotQueuedRuns, subtaskRecord, type HostedAgentRow } from "./hosted-gate.js"; import { trackBanner, type HostedTaskRecord, type RetryBanner } from "./hosted-workload.js"; import { handsOffSummary, invariantLine, readAssignedWorkInvariant } from "./hosted-handsoff.js"; -import { releaseMarkdown, type ContinuityReport, type DetectedRelease } from "./hosted-release.js"; +import { failureLines, summarizeFailures, type FailureRecord } from "./hosted-diagnostics.js"; +import { continuity, detectReleases, releaseMarkdown, type ContinuityReport, type DetectedRelease, type HealthSample } from "./hosted-release.js"; import { duplicateAgentComments, duplicateChildren, failureChain, firstEventAfter, gradeRuns, hostedCompanyRuns, hostedIssues, issueViewFields, pendingPersonItems, startedIssues, UNAVAILABLE_OVER_API, type HostedRunRow, @@ -25,6 +26,9 @@ export interface HostedGradeInput { agentIds: string[]; releases: DetectedRelease[]; health: () => ContinuityReport; + healthSamples?: () => readonly HealthSample[]; + stopHealthProbe?: () => Promise; + settleDiagnostics?: (failures: ReadonlyArray) => Promise; apiContinuity: () => ContinuityReport; stopObserver: () => Promise; agentNames?: string[]; @@ -75,6 +79,11 @@ export async function gradeHosted(input: HostedGradeInput): Promise<{ headline: const { api, companyId, agentIds } = input; const now = input.now ?? Date.now; const drained = await drainHosted(input); + await input.stopHealthProbe?.(); + const frozen = input.healthSamples ? [...input.healthSamples()] : null; + const unfinished = frozen && input.settleDiagnostics ? await input.settleDiagnostics(frozen.map(sample => sample.failure)) : 0; + if (unfinished) input.record("hosted_diagnoses_unfinished", { count: unfinished }); + const releases = frozen ? detectReleases(frozen, { now: now() }) : input.releases; input.record("hosted_drained", drained); await input.stopObserver(); const clicks = new Map([...input.observedClicks()].map(([id, list]) => [id, [...list]])); @@ -146,7 +155,7 @@ export async function gradeHosted(input: HostedGradeInput): Promise<{ headline: pendingApproval: person.approvals.has(issue.id), pendingQuestion: person.questions.has(issue.id) })); const facts: SwapRunFact[] = runs.map(run => ({ runId: run.runId, issueId: run.issueId, status: run.status, errorCode: run.errorCode, startedAt: run.startedAt, finishedAt: run.finishedAt, ownerPidBeforeEnd: null })); - const windows = releaseWindows(input.releases); + const windows = releaseWindows(releases); const firstEvents = new Map(); for (const window of windows) { const stop = window.stopRequestedAt!; @@ -167,10 +176,11 @@ export async function gradeHosted(input: HostedGradeInput): Promise<{ headline: const failedRuns = []; for (const run of failed) failedRuns.push({ ...run, release: swapForFailedRun(windows, facts.find(fact => fact.runId === run.runId)!), chain: await failureChain(api, run.runId) }); - const health = input.health(); + const health = frozen ? continuity(frozen) : input.health(); + const healthClasses = frozen ? summarizeFailures(frozen) : undefined; const apiContinuity = input.apiContinuity(); const handsOffPass = result.uncollected === 0 && result.stillRunning === 0 && result.started > 0 && result.completedWithoutHuman === result.started; - const outages = releaseOutages(input.releases); + const outages = releaseOutages(releases); const started = new Set(issues.filter(issue => !notGradedIds.has(issue.id)).map(issue => issue.id)); const planned = input.tasks(); const plannedIds = new Set(planned.flatMap(task => task.issueId ? [task.issueId] : [])); @@ -178,25 +188,29 @@ export async function gradeHosted(input: HostedGradeInput): Promise<{ headline: identifier: issue.identifier }, clicks.get(issue.id) ?? [])); const r1 = [...planned.filter(task => task.issueId && started.has(task.issueId)), ...subtasks].map(task => ({ identifier: task.identifier, result: hostedR1({ record: task, view: views.get(task.issueId!), runs: runsByIssue.get(task.issueId!) ?? [], queueWait: slotProof.queueWait, outages }) })); - const gate = hostedGate({ handsOffPass, wantedReleases: input.wantedReleases, slotEvidenceMissing: slotProof.missing, createErrors: planned.filter(task => task.createError).length, r1, bannersShown: handsOff.bannerShown, health, duplicates, releases: input.releases, metrics }); - const releaseSpans = input.releases.map(release => ({ from: release.lastOldOnlyAt, to: Math.max(release.firstNewAt, release.lastOldAt) + 60_000 })); - const records = input.requests?.() ?? []; + const gate = hostedGate({ handsOffPass, wantedReleases: input.wantedReleases, slotEvidenceMissing: slotProof.missing, createErrors: planned.filter(task => task.createError).length, r1, bannersShown: handsOff.bannerShown, health, healthClasses, duplicates, releases, metrics }); + const releaseSpans = releases.map(release => ({ from: release.lastOldOnlyAt, to: Math.max(release.firstNewAt, release.lastOldAt) + 60_000 })); + const records = [...input.requests?.() ?? []]; + const unfinishedRequests = input.settleDiagnostics ? await input.settleDiagnostics(records.map(entry => entry.failure)) : 0; + if (unfinishedRequests) input.record("hosted_request_diagnoses_unfinished", { count: unfinishedRequests }); const breakdown = { api: requestBreakdown(records.filter(record => record.kind === "api"), releaseSpans), health: requestBreakdown(records.filter(record => record.kind === "health"), releaseSpans) }; const breakdownLine = (name: string, value: typeof breakdown.api) => `${name} failures by status: ${Object.entries(value.byStatus).map(([status, count]) => `${status} ${count}`).join(", ") || "none"}; ` - + `inside release windows ${value.insideReleases}, outside ${value.outsideReleases}${value.outside.length ? ` (first: ${value.outside.slice(0, 3).map(item => `${item.at} ${item.method} ${item.path} ${item.status ?? "no answer"}`).join("; ")})` : ""}.`; + + `inside release windows ${value.insideReleases}, outside ${value.outsideReleases}${value.outside.length ? ` (first: ${value.outside.slice(0, 3).map(item => `${item.at} ${item.method} ${item.path} ${item.status ?? "no answer"}`).join("; ")})` : ""}; ` + + `server-side ${value.byClass.server}, unclassified ${value.byClass.unclassified}, client-side ${value.byClass.client}.`; const markdown = [ ...handsOff.lines, invariantLine(invariant), "", ...gate.lines, + ...(healthClasses ? failureLines("Health probe failures", healthClasses) : []), ...(notGraded.length ? [`Not graded: ${notGraded.length} task(s) still queued behind a full agent slot cap when the grade read the runs, proven by the agent's slot evidence ` + `(${notGraded.map(entry => entry.identifier ?? entry.issueId).join(", ")}).`] : []), "", releaseSwapMarkdown(result, metrics, windows.map(() => null), duplicates, grades, failedOutsideSwaps(windows, facts)).trimEnd(), "", "Hosted mode: releases came from the instance's own deploys, detected by polling /api/health. Lost-while-old-alive and late/preparation probes are not measured (see Unavailable).", - ...releaseMarkdown(input.releases, health, apiContinuity), + ...releaseMarkdown(releases, health, apiContinuity), ...(records.length ? [breakdownLine("Health probe", breakdown.health), breakdownLine("API request", breakdown.api)] : []), "", "Unavailable over the API:", @@ -204,7 +218,7 @@ export async function gradeHosted(input: HostedGradeInput): Promise<{ headline: "", ].join("\n"); await writeFile(path.join(input.dir, "hosted-release-swap.json"), `${JSON.stringify({ schema: "paperclip.restart-chaos.hosted-release-swap/v1", result, handsOff: { ...handsOff, banners: Object.fromEntries(banners) }, gate, r1, notGraded, invariant, - releases: input.releases, health, api: apiContinuity, requestBreakdown: breakdown, metrics, duplicates, failedRuns, grades, drained, + releases, health, healthFailures: healthClasses, api: apiContinuity, requestBreakdown: breakdown, metrics, duplicates, failedRuns, grades, drained, unavailable: UNAVAILABLE_OVER_API }, null, 2)}\n`, { mode: 0o600 }); await writeFile(path.join(input.dir, "SUMMARY.md"), markdown, { mode: 0o600 }); input.record("hosted_graded", { gate: gate.pass, r1Failed: gate.r1Failed.length, headline: result.headline, byVerdict: result.byVerdict, byLabel: result.byLabel, retry: result.retry, diff --git a/tests/restart-chaos/hosted-main.ts b/tests/restart-chaos/hosted-main.ts index 47b20922200..9b75d42541c 100644 --- a/tests/restart-chaos/hosted-main.ts +++ b/tests/restart-chaos/hosted-main.ts @@ -5,6 +5,7 @@ import { setTimeout as delay } from "node:timers/promises"; import type { ChaosApi } from "./api.js"; import { apiRequests, HealthProbe, HostedApi, hostedToken, requestSamples, type RequestRecord } from "./hosted-api.js"; import { parseHostedCommand, type HostedOptions } from "./hosted-config.js"; +import { failureLines, summarizeFailures } from "./hosted-diagnostics.js"; import { gradeHosted } from "./hosted-grade.js"; import { continuity, detectReleases, identityOf, releaseMarkdown, type DetectedRelease, type HealthSample } from "./hosted-release.js"; import { cleanupHosted, inventory, loadState, resolveCompany, setupHosted, type HostedState } from "./hosted-setup.js"; @@ -51,11 +52,15 @@ export async function finalizeHosted(input: { api: Parameters ({ errors: [String(error)] })); } -function watchIdentity(timeline: Timeline, samplesPath: string) { +export function watchIdentity(timeline: { add: (kind: string, data: Record) => unknown }, samplesPath: string, api: Pick) { let last: string | null = null; let failing = false; return (sample: HealthSample) => { - appendFileSync(samplesPath, `${JSON.stringify(sample)}\n`, { mode: 0o600 }); + if (sample.ok) appendFileSync(samplesPath, `${JSON.stringify(sample)}\n`, { mode: 0o600 }); + else void api.diagnosed(sample.failure).then(() => { + appendFileSync(samplesPath, `${JSON.stringify(sample)}\n`, { mode: 0o600 }); + timeline.add("hosted_health_failure_classified", { at: new Date(sample.at).toISOString(), class: sample.failure?.class ?? null, reason: sample.failure?.reason ?? null }); + }); if (!sample.ok) { if (!failing) timeline.add("hosted_health_failed", { status: sample.status, ms: sample.ms, error: sample.error ?? null }); failing = true; @@ -72,8 +77,10 @@ function watchIdentity(timeline: Timeline, samplesPath: string) { async function observe(options: HostedOptions, probe: HealthProbe, api: HostedApi, dir: string, started: number, cancelled: () => boolean, timeline: Timeline): Promise { while (!cancelled() && Date.now() - started < options.maxWaitMs && !releasesReached(detectReleases(probe.samples, { now: Date.now() }), options.releases)) await delay(LOOP_MS); await probe.stop(); + await api.settleDiagnostics(); const releases = detectReleases(probe.samples, { now: Date.now() }); - const lines = releaseMarkdown(releases, continuity(probe.samples), continuity(requestSamples(apiRequests(api.requests)))); + const lines = [...releaseMarkdown(releases, continuity(probe.samples), continuity(requestSamples(apiRequests(api.requests)))), + ...failureLines("Health probe failures", summarizeFailures(probe.samples))]; await writeFile(path.join(dir, "SUMMARY.md"), `${lines.join("\n")}\n`, { mode: 0o600 }); timeline.add("hosted_observed", { releases: releases.map(release => ({ shape: release.shape, firstNewAt: new Date(release.firstNewAt).toISOString(), lastOldAt: new Date(release.lastOldAt).toISOString(), failed: release.failedRequests, commitChanged: release.commitChanged })) }); @@ -92,12 +99,13 @@ export async function runHosted(argv: readonly string[]): Promise { process.on("SIGINT", onSignal); process.on("SIGTERM", onSignal); const cancelled = () => interrupted; - const api = new HostedApi(options.target, hostedToken(options.target)); + const api = new HostedApi(options.target, hostedToken(options.target), undefined, fetch, { live: true }); try { const exit = await hostedSession({ options, dir, timeline, record, cancelled, api, interrupted: () => interrupted }); console.info(`Hosted run ${options.label}: results ${dir}`); return exit; } finally { + await api.settleDiagnostics(); await saveRequests(dir, api.requests, options.mode); process.off("SIGINT", onSignal); process.off("SIGTERM", onSignal); @@ -119,6 +127,8 @@ async function hostedSession(input: { options: HostedOptions; dir: string; timel const { options, dir, timeline, record, cancelled, api } = input; const me = await api.get<{ userId?: string; companyIds?: string[] }>("/api/cli-auth/me"); timeline.add("hosted_signed_in", { baseUrl: options.target.baseUrl, mode: options.mode, label: options.label, companies: me.companyIds?.length ?? 0 }); + const control = await api.primeControl(); + timeline.add("hosted_control_probe", { ok: control?.ok ?? null, status: control?.status ?? null, ms: control?.ms ?? null, error: control?.error?.code ?? control?.error?.name ?? null }); if (options.mode === "cleanup") { const state = await loadState(dir); @@ -131,7 +141,7 @@ async function hostedSession(input: { options: HostedOptions; dir: string; timel const census = await inventory(api, options.label); timeline.add("hosted_inventory", { ...census }); const started = Date.now(); - const probe = new HealthProbe(api, options.healthMs, watchIdentity(timeline, path.join(dir, "health.jsonl"))).start(); + const probe = new HealthProbe(api, options.healthMs, watchIdentity(timeline, path.join(dir, "health.jsonl"), api)).start(); if (options.mode === "observe") return await observe(options, probe, api, dir, started, cancelled, timeline); let state: HostedState | null = null; @@ -161,7 +171,7 @@ async function hostedSession(input: { options: HostedOptions; dir: string; timel if (options.releases > 0 && !releasesReached(releases, options.releases)) timeline.add("hosted_releases_short", { wanted: options.releases, seen: releases.length }); polling = keepPolling(workload); const graded = await gradeHosted({ api, companyId, agentIds: Object.values(state.agents).map(agent => agent!.id), releases, - health: () => continuity(probe.samples), apiContinuity: () => continuity(requestSamples(apiRequests(api.requests))), requests: () => api.requests, + health: () => continuity(probe.samples), healthSamples: () => probe.samples, stopHealthProbe: () => probe.stop(), settleDiagnostics: failures => api.settleDiagnostics(failures), apiContinuity: () => continuity(requestSamples(apiRequests(api.requests))), requests: () => api.requests, quietMs: options.quietMs, stopObserver: () => polling!.stop(), observedClicks: () => observedClicks(workload.records), banners: () => new Map(workload.banners), tasks: () => workload.records, wantedReleases: options.releases, @@ -177,7 +187,9 @@ async function hostedSession(input: { options: HostedOptions; dir: string; timel } finally { await polling?.stop(); await probe.stop(); - await writeFile(path.join(dir, "health-summary.json"), `${JSON.stringify({ releases: detectReleases(probe.samples), health: continuity(probe.samples), + const finalSamples = [...probe.samples]; + await api.settleDiagnostics(finalSamples.map(sample => sample.failure)); + await writeFile(path.join(dir, "health-summary.json"), `${JSON.stringify({ releases: detectReleases(finalSamples), health: continuity(finalSamples), api: continuity(requestSamples(apiRequests(api.requests))), inventory: census }, null, 2)}\n`, { mode: 0o600 }); const cleaned = await finalizeHosted({ api, keep: options.keep, label: options.label, dir, state, record }); if (cleaned && cleaned.errors.length) exit = Math.max(exit, 1); diff --git a/tests/restart-chaos/hosted-release.ts b/tests/restart-chaos/hosted-release.ts index b857e963d49..e183a8206d5 100644 --- a/tests/restart-chaos/hosted-release.ts +++ b/tests/restart-chaos/hosted-release.ts @@ -1,3 +1,5 @@ +import { isClientSide, type ConnectionInfo, type FailureRecord } from "./hosted-diagnostics.js"; + export interface HealthSample { at: number; ok: boolean; @@ -6,6 +8,8 @@ export interface HealthSample { processStartedAt: string | null; commit: string | null; error?: string | null; + connection?: ConnectionInfo | null; + failure?: FailureRecord; } export type ReleaseShape = "overlap" | "stop_then_start" | "clean_switch"; @@ -43,8 +47,8 @@ export const identityOf = (sample: Pick left.at - right.at); - const now = options.now ?? sorted.at(-1)?.at ?? 0; + const sorted = samples.filter(sample => sample.ok || !isClientSide(sample.failure)).sort((left, right) => left.at - right.at); + const now = options.now ?? samples.reduce((latest, sample) => Math.max(latest, sample.at), 0); const releases: DetectedRelease[] = []; let current: HealthSample | null = null; let lastCurrentOnlyAt: number | null = null;