Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fix(browser): name web-bundle budgets and recover web deadlines
Name the existing heap, per-script, and total web-bundle phases, and reject a per-script deadline above the total. Promote capture, CDP command, source-map decode, and source-map fetch deadlines at today's defaults. Name DevTools timeoutMs, and state that discovery, cleanup grace, byte budgets, and Electron hook retention have no runtime override.

Refs #5910

Co-authored-by: morluto <morluto@users.noreply.github.com>
  • Loading branch information
cursoragent and morluto committed Oct 21, 2026
commit 7f5c93aacb9c052615951a16990b8a16ba11eb2d
37 changes: 22 additions & 15 deletions docs/browser-observation.md
Original file line number Diff line number Diff line change
Expand Up @@ -386,22 +386,26 @@ section explicitly truncated.
Disallowed-origin entries are filtered before retention.

Selected script-source collection shares a 32 MiB aggregate UTF-8 retention
budget and a 20-second deadline across the capture. An oversized source is
budget and the `command_timeout_ms` deadline (default 20000 ms) across the
capture. The byte budget has no runtime override. An oversized source is
omitted while later smaller sources may still fit. When the deadline expires,
remaining source reads are skipped. Script metadata, per-item omission reasons,
and `script_sources` completeness remain available. A single CDP response can
still be materialized up to the separate 64 MiB transport limit before source
admission; the retention budget does not bound that transient allocation.

Bundle parsing and semantic inspection run sequentially in an owned child,
without executing captured code. `max_heap_mb` defaults to 1024 MiB V8
old-space; `analysis_timeout_ms` defaults to 30000 per script, including startup
and transfer. A failed or timed-out script becomes an explicit unknown while
completed findings and later scripts remain available. `total_analysis_timeout_ms`
defaults to 300000 across script analysis; expiry returns a typed timeout with
partial Evidence and identifies unstarted scripts. These controls are also
available as CLI flags with hyphenated names. Capture and optional source-map
fetching have separate budgets.
without executing captured code. These are separate phases. `max_heap_mb`
defaults to 1024 MiB V8 old-space (range 128..16384). `analysis_timeout_ms`
defaults to 30000 per script, including startup and transfer.
`total_analysis_timeout_ms` defaults to 300000 across script analysis. A
per-script deadline above the effective total is rejected. A failed or
timed-out script becomes an explicit unknown while completed findings and later
scripts remain available. Total-deadline expiry returns a typed timeout with
partial Evidence and identifies unstarted scripts. `source_map_fetch_timeout_ms`
defaults to 30000 and is an item limitation, not that analysis timeout. These
controls are also available as CLI flags with hyphenated names. Worker protocol
and result byte budgets have no runtime override.

One web-bundle capture/analysis is admitted per REA process at a time. Completed
script results share an 8 MiB serialized transfer budget, with host heap
Expand Down Expand Up @@ -431,12 +435,15 @@ an invalid supplied size remains unknown with incomplete resource coverage while
the resource's other facts are retained. Zero and nonnegative fractional sizes
are preserved.

CDP discovery has a 10-second deadline. Each WebSocket handshake and command
response has its own 20-second deadline, separate from the caller-selected
observation window. A stalled handshake or command reports `provider_timeout`;
CDP discovery has a 10-second response deadline and an 8 MiB document budget.
Neither has a runtime override. Each WebSocket handshake and command response
uses `command_timeout_ms` (default 20000), separate from the caller-selected
observation window, discovery, and the 5000 ms cleanup grace. A stalled
handshake or command reports `provider_timeout` and names `command_timeout_ms`;
caller cancellation still reports cancellation. WebSocket messages remain subject
to the [64 MiB limit](#request-boundary). REA does not impose a message-count or
pending-command quota. On cancellation, it closes only its own WebSocket,
to the [64 MiB limit](#request-boundary), which has no runtime override. REA does
not impose a message-count or pending-command quota. On cancellation, it closes
only its own WebSocket,
waiting up to one second before terminating it. Malformed unsolicited events
and malformed replies to pending commands poison the connection so later
commands fail closed. A correlated reply's session ID must match the command's
Expand All @@ -445,7 +452,7 @@ rejects it as unknown; other command rejections retain their reported failure.

Network and console coverage starts only after REA attaches and enables the relevant CDP domains. `prior_activity_available` is always `false`; absence from these arrays is not evidence that an event never occurred. Scripts are different: scripts the page parsed before REA attached are still reported under `scripts`. A page that loaded before attach can therefore list its scripts while `network.requests` lacks the requests that fetched them. If CDP reuses a request ID without supplying redirect metadata, REA retains the predecessor observation and marks network coverage incomplete.

Source maps are not fetched by inspection. Bundle analysis fetches them only when `fetch_source_maps` is selected, with exact-origin redirect checks and no credentials, cookies, or referrer. Each fetch operation has a 30-second deadline and a 64 MiB aggregate streamed-response budget across redirects. A deadline or byte-limit failure remains explicitly unavailable and makes bundle completeness partial. Source-map decoding also bounds raw resolved identities to 64 MiB and aggregate inline evidence to 32 MiB. Failed maps preserve their failure context when it fits; if another context cannot fit, collection stops with the full requested count, the returned processed count, and an explicit unknown-results limitation. Retained mappings and original sources are returned inline. See [source-location limits](web-source-location.md) for the structural decoder bounds. Original source artifacts with `.ts`, `.tsx`, `.mts`, or `.cts` suffixes carry `text/typescript`; other source names retain `text/javascript`.
Source maps are not fetched by inspection. Bundle analysis fetches them only when `fetch_source_maps` is selected, with exact-origin redirect checks and no credentials, cookies, or referrer. Each fetch operation uses `source_map_fetch_timeout_ms` (default 30000) and a 64 MiB aggregate streamed-response budget across redirects. The byte budget has no runtime override. A fetch overrun is an item limitation, not a thrown analysis timeout. A deadline or byte-limit failure remains explicitly unavailable and makes bundle completeness partial. Source-map decoding also bounds raw resolved identities to 64 MiB and aggregate inline evidence to 32 MiB. Failed maps preserve their failure context when it fits; if another context cannot fit, collection stops with the full requested count, the returned processed count, and an explicit unknown-results limitation. Retained mappings and original sources are returned inline. See [source-location limits](web-source-location.md) for the structural decoder bounds. Original source artifacts with `.ts`, `.tsx`, `.mts`, or `.cts` suffixes carry `text/typescript`; other source names retain `text/javascript`.

source-map items retain the script's `declared_url` separately from the observed
`effective_url`. successful maps use the latter as their source-resolution base.
Expand Down
5 changes: 3 additions & 2 deletions docs/web-network-captures.md
Original file line number Diff line number Diff line change
Expand Up @@ -611,13 +611,14 @@ and serves nothing.
## Resource and lifecycle boundaries

Complete evidence has a 32 MiB input, 96 MiB decoder reply and 64-level nesting
budget. Exceeding a budget returns no partial success.
budget. Those budgets have no runtime override. `capture_timeout_ms` does not
raise them. Exceeding a budget returns no partial success.
Oversized selected captures return an input error identifying `capture_path`
and the byte budget; owned reply/output failures remain output or provider errors.
HAR, SAZ and qlog run in an owned
192 MiB Node old-generation heap with one V8 worker. Mitmproxy decoding applies
Linux limits of 768 MiB address space, 30 seconds CPU and 96 MiB file output;
both commands have a 30-second wall deadline and independently supervised
both commands use `capture_timeout_ms` (default 30000) and independently supervised
process cleanup. Owned decoder diagnostics retain at most 1 MiB across stdout
and stderr; the collector drops overflow as it arrives, reports the limit
failure and verifies cleanup. Heap limits alone do not establish aggregate RSS limits.
Expand Down
5 changes: 3 additions & 2 deletions docs/web-source-location.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ implement every current source-map extension.
One owned Node subprocess decodes the map. Its private request directory is
removed before success is returned. Only this child's inherited `NODE_OPTIONS`
is removed; explicit V8 flags set a 192 MiB old-generation and 8 MiB semi-space
budget, one V8 worker and a 20-second deadline. Reported actual V8 heap limits
budget, one V8 worker and `decode_timeout_ms` (default 20000). The codec heap, map budget, and reply budget have no runtime override. Reported actual V8 heap limits
are checked. These are heap limits, not an aggregate process RSS limit. When
REA runs on Bun, the subprocess is Bun, which ignores these V8 flags: `runtime`
records `id: "bun"`, the Bun version, its Node.js compatibility version and a
Expand All @@ -86,7 +86,8 @@ cleanup overrides success with `cleanup_incomplete` and the owning
operation/resources.

Complete evidence is bounded by a 4 MiB map, 32 MiB codec reply, 262144 decoded
rows/segments and 64 nested section levels. Exceeding a budget returns an explicit
rows/segments and 64 nested section levels. Those structural budgets and the
192 MiB codec heap have no runtime override. Exceeding a budget returns an explicit
failure, without partial results. The existing 32 MiB manifest and 16 MiB selected
script boundaries also apply. No global toolchain or browser configuration changes
are made.
Expand Down
8 changes: 8 additions & 0 deletions src/application/BrowserEvidence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ const browserParameters = (
: "target_id" in input && observedOrigin !== undefined
? [observedOrigin]
: [],
...("command_timeout_ms" in input && input.command_timeout_ms !== undefined
? { command_timeout_ms: input.command_timeout_ms }
: {}),
};
if (!("target_id" in input)) return scope;
return {
Expand Down Expand Up @@ -171,6 +174,11 @@ const browserParameters = (
...(input.total_analysis_timeout_ms === undefined
? {}
: { total_analysis_timeout_ms: input.total_analysis_timeout_ms }),
...(input.source_map_fetch_timeout_ms === undefined
? {}
: {
source_map_fetch_timeout_ms: input.source_map_fetch_timeout_ms,
}),
}
: {}),
};
Expand Down
3 changes: 3 additions & 0 deletions src/application/WebNetworkCaptureService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,9 @@ export class WebNetworkCaptureService {
},
}),
sensitive_value_count: input.sensitive_values.length,
...(input.capture_timeout_ms === undefined
? {}
: { capture_timeout_ms: input.capture_timeout_ms }),
});
return ok(
createEvidence(
Expand Down
1 change: 1 addition & 0 deletions src/application/WebSourceLocationPorts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export interface WebSourceMapPort {
readonly path: string;
readonly url: string;
readonly position: WebSourceLocationInput["generated_position"];
readonly decodeTimeoutMs?: number;
},
options?: ExecutionOptions,
): Promise<Result<WebSourceMapReport, AnalysisError>>;
Expand Down
3 changes: 3 additions & 0 deletions src/application/WebSourceLocationService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ export class WebSourceLocationService {
path: map.file.path,
url: map.url,
position: input.generated_position,
...(input.decode_timeout_ms === undefined
? {}
: { decodeTimeoutMs: input.decode_timeout_ms }),
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
},
options,
);
Expand Down
3 changes: 3 additions & 0 deletions src/application/javascript/ElectronEvidence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ const parameters = (
target_id: input.target_id,
observation_ms: input.observation_ms,
include_script_sources: input.include_script_sources,
...(input.command_timeout_ms === undefined
? {}
: { command_timeout_ms: input.command_timeout_ms }),
}
: {}),
});
2 changes: 1 addition & 1 deletion src/browser/BrowserProcessStartup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,4 +178,4 @@ const browserStartupMessage = (
readonly stderr: string;
},
): string =>
`Chrome CDP startup ${failure}; executable=${diagnostics.executable}; elapsed_ms=${String(diagnostics.elapsedMs)}; startup_timeout_ms=${String(diagnostics.startupTimeoutMs)}; exit_code=${diagnostics.exitCode === null ? "null" : String(diagnostics.exitCode)}; signal=${diagnostics.signalCode ?? "null"}; stderr=${diagnostics.stderr.length === 0 ? "<empty>" : diagnostics.stderr}`;
`Chrome CDP startup ${failure}; executable=${diagnostics.executable}; elapsed_ms=${String(diagnostics.elapsedMs)}; timeoutMs=${String(diagnostics.startupTimeoutMs)} (DevToolsActivePort wait; omitted means ${String(BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS)} ms); exit_code=${diagnostics.exitCode === null ? "null" : String(diagnostics.exitCode)}; signal=${diagnostics.signalCode ?? "null"}; stderr=${diagnostics.stderr.length === 0 ? "<empty>" : diagnostics.stderr}`;
10 changes: 8 additions & 2 deletions src/browser/CdpBrowserProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ import {
type CdpTargetSession,
} from "./CdpTargetSession.js";
import { capturePage, type CapturedPage } from "./CdpPageCapture.js";
import { selectedCdpCommandTimeoutMs } from "../domain/browserDeadline.js";
import { fetchWebSourceMaps } from "./WebSourceMapFetcher.js";
import { authorizeCdpTarget } from "./CdpAuthorizedTarget.js";
import { observeCdpSession } from "./CdpObservationSession.js";
Expand Down Expand Up @@ -134,6 +135,7 @@ export class CdpBrowserProvider implements BrowserObservationPort {
options.signal,
undefined,
this.#owner,
selectedCdpCommandTimeoutMs(input.command_timeout_ms),
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
);
if (endpoint.connection !== undefined)
await this.#owner.finish(endpoint.connection);
Expand Down Expand Up @@ -359,7 +361,7 @@ interface CdpTargetOperationSession<Input> {
const withTargetSession = async <
Input extends Pick<
InspectWebPageInput,
"cdp_endpoint" | "target_id" | "allowed_origins"
"cdp_endpoint" | "target_id" | "allowed_origins" | "command_timeout_ms"
>,
Output,
>(
Expand All @@ -370,12 +372,16 @@ const withTargetSession = async <
owner: CdpTargetSessionOwner,
partialObservation?: (output: Output) => AnalysisPartialObservation,
): Promise<Output> => {
const commandTimeoutMs = selectedCdpCommandTimeoutMs(
input.command_timeout_ms,
);
const endpoint = await openCdpEndpoint(
input.cdp_endpoint,
operation,
options.signal,
undefined,
owner,
commandTimeoutMs,
);
let targetSession: CdpTargetSession | undefined;
let outcome: Result<Output, unknown>;
Expand All @@ -390,7 +396,7 @@ const withTargetSession = async <
target,
operation,
options.signal,
undefined,
{ commandTimeoutMs },
owner,
)
: await attachCdpTargetSession(
Expand Down
51 changes: 40 additions & 11 deletions src/browser/CdpConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import { AnalysisError } from "../domain/analysisErrorBase.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import { CdpCommandRejection } from "./CdpCommandRejection.js";
import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js";
import {
cdpCommandDeadlineRecovery,
DEFAULT_CDP_COMMAND_TIMEOUT_MS,
noRuntimeOverrideSentence,
} from "../domain/browserDeadline.js";
import { safeParseJson } from "../domain/safeJson.js";
import { WEB_RUNTIME_LIMITS } from "../domain/webRuntime.js";

Expand Down Expand Up @@ -51,6 +56,7 @@ export class CdpConnection {
private readonly socket: WebSocket,
private readonly operation: BrowserObservationOperation,
private readonly maxPayloadBytes: number,
private readonly commandTimeoutMs: number,
) {
socket.on("message", (data) => this.#receive(data));
socket.on("close", () => this.#disconnect());
Expand All @@ -68,15 +74,18 @@ export class CdpConnection {
url: string,
operation: BrowserObservationOperation,
signal?: AbortSignal,
limits?: { readonly maxPayloadBytes: number },
limits?: {
readonly maxPayloadBytes?: number;
readonly commandTimeoutMs?: number;
},
onConnected?: (connection: CdpConnection) => void,
): Promise<CdpConnection> {
if (signal?.aborted === true)
throw new AnalysisCancelledError(operation, { cause: signal.reason });
const maxPayloadBytes =
limits === undefined
? WEB_RUNTIME_LIMITS.protocolBytes
: limits.maxPayloadBytes;
limits?.maxPayloadBytes ?? WEB_RUNTIME_LIMITS.protocolBytes;
const commandTimeoutMs =
limits?.commandTimeoutMs ?? DEFAULT_CDP_COMMAND_TIMEOUT_MS;
if (
!Number.isSafeInteger(maxPayloadBytes) ||
maxPayloadBytes <= 0 ||
Expand All @@ -92,15 +101,20 @@ export class CdpConnection {
maxPayload: maxPayloadBytes,
perMessageDeflate: false,
});
const connection = new CdpConnection(socket, operation, maxPayloadBytes);
const connection = new CdpConnection(
socket,
operation,
maxPayloadBytes,
commandTimeoutMs,
);
try {
onConnected?.(connection);
} catch (cause: unknown) {
await connection.close();
throw cause;
}
try {
await waitForOpen(socket, operation, signal);
await waitForOpen(socket, operation, signal, commandTimeoutMs);
} catch (cause: unknown) {
if (onConnected === undefined) {
try {
Expand Down Expand Up @@ -184,12 +198,18 @@ export class CdpConnection {
const pending = this.#pending.get(id);
if (pending === undefined) return;
this.#complete(id, pending);
const recovery = cdpCommandDeadlineRecovery(
this.commandTimeoutMs,
"command",
method,
);
reject(
new BrowserObservationError(this.operation, "timeout", {
detail: `CDP command ${method} exceeded its ${String(WEB_RUNTIME_LIMITS.commandTimeoutMs)} ms response deadline.`,
detail: recovery.userMessage,
remediationAction: recovery.remediationAction,
}),
);
}, WEB_RUNTIME_LIMITS.commandTimeoutMs);
}, this.commandTimeoutMs);
signal?.addEventListener("abort", onAbort, { once: true });
this.#pending.set(id, {
method,
Expand Down Expand Up @@ -427,7 +447,10 @@ export class CdpConnection {
reason,
reason === "payload_limit"
? {
detail: `CDP message exceeded the selected ${String(this.maxPayloadBytes)} byte protocol budget.`,
detail: noRuntimeOverrideSentence(
`CDP message exceeded the ${String(this.maxPayloadBytes)} byte protocol budget.`,
"command_timeout_ms",
),
}
: undefined,
);
Expand Down Expand Up @@ -456,6 +479,7 @@ const waitForOpen = async (
socket: WebSocket,
operation: BrowserObservationOperation,
signal?: AbortSignal,
commandTimeoutMs: number = DEFAULT_CDP_COMMAND_TIMEOUT_MS,
): Promise<void> =>
await new Promise((resolve, reject) => {
const onOpen = (): void => {
Expand Down Expand Up @@ -492,12 +516,17 @@ const waitForOpen = async (
const timer = setTimeout(() => {
terminateSocket(socket);
cleanup();
const recovery = cdpCommandDeadlineRecovery(
commandTimeoutMs,
"handshake",
);
reject(
new BrowserObservationError(operation, "timeout", {
detail: `CDP WebSocket handshake exceeded its ${String(WEB_RUNTIME_LIMITS.commandTimeoutMs)} ms deadline.`,
detail: recovery.userMessage,
remediationAction: recovery.remediationAction,
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}),
);
}, WEB_RUNTIME_LIMITS.commandTimeoutMs);
}, commandTimeoutMs);
socket.once("open", onOpen);
socket.once("error", onFailure);
socket.once("close", onClose);
Expand Down
4 changes: 2 additions & 2 deletions src/browser/CdpElectronInspection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
ingestElectronScriptEvent,
type ElectronScriptDraft,
} from "./CdpElectronScriptEvents.js";
import { CDP_SCRIPT_SOURCE_BYTES_OMISSION_REASON } from "./CdpScriptSourceBudget.js";
import { captureElectronScripts } from "./CdpElectronScripts.js";
import { inspectElectronPageInputSchema } from "../domain/javascript/electronObservation.js";

Expand Down Expand Up @@ -221,8 +222,7 @@ it("admits a prefix and fitting suffix around an oversized Electron source", asy
expect(byHash.get("prefix")?.included).toBe(true);
expect(byHash.get("oversized")).toEqual({
included: false,
reason:
"script source was omitted because the aggregate 32 MiB source budget was exhausted",
reason: CDP_SCRIPT_SOURCE_BYTES_OMISSION_REASON,
});
expect(byHash.get("suffix")?.included).toBe(true);
expect(completeness.snapshot().excluded).toContainEqual({
Expand Down
Loading
Loading