Files
rea/src/application/WebSourceLocationService.test.ts
T
0155b89953 fix(browser): name web-bundle budgets and recover web deadlines (#6036)
* 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>

* fix(browser): apply selected web deadlines to the owning phase

Keep HTTP and browser-socket discovery on the fixed discovery deadline so a
short command_timeout_ms starts at the handshake. Apply scenario
command_timeout_ms to launch startup and the primary connect session, and
keep service-worker restoration on the fixed 5000 ms grace. Omit
command_timeout_ms from recovery text when the operation does not accept it.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(browser): retain scenario commands that finish after their deadline

A timed-out scenario command stays owned so cleanup can close a late
browser or context and restore a mutation that lands after the deadline.
Child storage replies use that deadline, scenario recovery names
command_timeout_ms in the capture JSON, and the session test connection
implements beginCleanupGrace.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(browser): keep child command timeouts as the public failure

A nested command such as Page.enable that is delivered but never answered
was stored as protocol_error, hiding the command name, selected deadline,
and recovery. Store the typed timeout and assert that public error.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(browser): keep runtime cleanup on the fixed grace

Switch runtime restoration to the cleanup grace before the first send so a
short command_timeout_ms cannot fail an otherwise successful observation.
Stop advertising command_timeout_ms on list_browser_targets, which never
bounds a post-discovery command.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* test(browser): prove a short command deadline cannot fail runtime cleanup

Drive restoration through the runtime fixture. A cleanup command that
outlives command_timeout_ms still succeeds, and a stalled restoration
names the fixed 5000 ms grace.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(browser): name the effective source-map decode deadline

codecBudgetLimitation reported a fixed 20-second deadline after a
caller selected decode_timeout_ms. Result and Evidence limitations
now name that effective millisecond deadline.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(browser): separate handshake and target-attach deadlines

A browser-level Target.attachToTarget no longer shares the WebSocket
handshake budget. Blocked service-worker attachment keeps discovery on
its fixed deadline and applies command_timeout_ms to the later handshake
and attach.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(browser): name the web-bundle resource each runtime exhausts

Bun ignores the V8 old-space flag. A Windows Job reports the process
commit limit, and other Bun hosts no longer suggest raising max_heap_mb.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(browser): cite the browser-socket discovery message budget

WebSocket discovery enforces the 64 MiB protocol budget. Timeout
recovery no longer advertises the 8 MiB HTTP document budget.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(browser): bound the blocked service-worker check before discovery

The first registration check has its own fixed 10s deadline. Discovery,
handshake, and Target.attachToTarget stay on their separate deadlines.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(browser): name the operand that stopped web-bundle admission

Host heap pressure no longer claims the fixed result budget is exhausted.
A Windows Bun allocation before the commit limit still names that limit.

Co-authored-by: morluto <morluto@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
2026-10-22 05:47:38 +08:00

253 lines
8.7 KiB
TypeScript

import { expect, it } from "vitest";
import {
webSourceLocationArgs as args,
webSourceLocationFixture,
webSourceMapDecoderFixture as decoder,
} from "../../tests/fixtures/webSourceLocation.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { parseEvidence } from "../domain/evidence.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import { ok } from "../domain/result.js";
import {
DEFAULT_WEB_SOURCE_MAP_DECODE_TIMEOUT_MS,
webSourceLocationResultSchema,
} from "../domain/webSourceLocation.js";
import { WebSourceLocationService } from "./WebSourceLocationService.js";
import type { WebSourceMapPort } from "./WebSourceLocationPorts.js";
const service = (data = webSourceLocationFixture(), port = decoder) =>
new WebSourceLocationService({ load: () => Promise.resolve(ok(data)) }, port);
const expectCodecDeadline = (
evidence: {
readonly limitations: readonly string[];
readonly normalized_result: unknown;
},
timeoutMs: number,
): void => {
const phrase = `${String(timeoutMs)} ms decode_timeout_ms deadline`;
const result = webSourceLocationResultSchema.parse(
evidence.normalized_result,
);
expect(
evidence.limitations.filter((text) => text.includes(phrase)),
).toHaveLength(1);
expect(
result.limitations.filter((text) => text.includes(phrase)),
).toHaveLength(1);
};
it("passes an explicit decode deadline and omits the default from Evidence", async () => {
const seen: Array<number | undefined> = [];
const port: WebSourceMapPort = {
trace: (input) => {
seen.push(input.decodeTimeoutMs);
return decoder.trace(input);
},
};
const explicit = await service(undefined, port).trace({
...args,
decode_timeout_ms: 250,
});
if (!explicit.ok) throw explicit.error;
expect(explicit.value.parameters.decode_timeout_ms).toBe(250);
expectCodecDeadline(explicit.value, 250);
const omitted = await service(undefined, port).trace(args);
if (!omitted.ok) throw omitted.error;
expect(omitted.value.parameters).not.toHaveProperty("decode_timeout_ms");
expectCodecDeadline(omitted.value, DEFAULT_WEB_SOURCE_MAP_DECODE_TIMEOUT_MS);
expect(seen).toEqual([250, undefined]);
});
it.each([
{ ...args, manifest_path: "relative.json" },
{ ...args, script_index: -1 },
{ ...args, source_map: { ...args.source_map, path: "relative.map" } },
{ ...args, source_map: { ...args.source_map, url: "relative.map" } },
{ ...args, generated_position: { line: 0, column: 0 } },
])(
"rejects invalid selected context before acquiring artifacts: %j",
async (input) => {
const response = await new WebSourceLocationService(
{
load: () => {
throw new Error("must not acquire");
},
},
decoder,
).trace(input);
if (response.ok) throw new Error("expected invalid input");
expect(projectAnalysisError(response.error).code).toBe("invalid_request");
},
);
it.each([
"file:///analysis/app.map",
"webpack:///bundle/app.map",
"https://selected-user:selected-value@app.test/maps/app.map",
])(
"retains an absolute inert map context without fetching: %s",
async (url) => {
const fixture = webSourceLocationFixture();
const data = { ...fixture, sourceMap: { ...fixture.sourceMap, url } };
const response = await service(data).trace({
...args,
source_map: { ...args.source_map, url },
});
if (!response.ok) throw response.error;
expect(
webSourceLocationResultSchema.parse(response.value.normalized_result)
.url_context,
).toBe(url);
},
);
it.each(["source", "map", "map-path", "map-url"])(
"rejects changed artifact identity before decoding: %s",
async (variant) => {
const fixture = webSourceLocationFixture();
const data = {
...fixture,
source: variant === "source" ? "different" : fixture.source,
sourceMap: { ...fixture.sourceMap },
};
if (variant === "map") data.sourceMap.text += " ";
if (variant === "map-path") data.sourceMap.file.path = "/other.map";
if (variant === "map-url") data.sourceMap.url = "https://other.test/";
const response = await service(data, {
trace: () => {
throw new Error("must not decode");
},
}).trace(args);
if (response.ok) throw new Error("expected changed identity failure");
expect(response.error._tag).toBe("AnalysisOutputError");
},
);
it.each(["digest", "url", "point"])(
"rejects changed codec identity: %s",
async (variant) => {
const port: WebSourceMapPort = {
trace: async (input) => {
const decoded = await decoder.trace(input);
if (!decoded.ok) return decoded;
const report = decoded.value;
if (variant === "digest") report.source_map_sha256 = "f".repeat(64);
if (variant === "url") report.url_context = "https://other.test/";
if (variant === "point") report.lookup.requested.column += 1;
return Promise.resolve(ok(report));
},
};
const response = await service(undefined, port).trace(args);
if (response.ok) throw new Error("expected changed codec identity failure");
expect(response.error._tag).toBe("AnalysisOutputError");
},
);
it.each([
{
runtime: {
id: "node-v8",
version: "v24.18.0",
v8_heap_limit_bytes: 201326592,
},
limitation: "192 MiB old-generation heap and one V8 worker",
},
{
runtime: {
id: "bun",
version: "1.4.2",
node_compatibility_version: "24.3.0",
v8_heap_limit_bytes: null,
process_memory_limit_bytes: 738197504,
},
limitation:
"a Windows Job Object limited its committed memory to 738197504 bytes",
},
{
runtime: {
id: "bun",
version: "1.4.2",
node_compatibility_version: "24.3.0",
v8_heap_limit_bytes: null,
process_memory_limit_bytes: null,
},
limitation: "so no codec heap limit is established",
},
] as const)(
"states the codec memory bound its runtime enforced: $limitation",
async ({ runtime, limitation }) => {
const response = await service(undefined, {
trace: async (input) => {
const decoded = await decoder.trace(input);
if (!decoded.ok) return decoded;
return ok({ ...decoded.value, runtime });
},
}).trace(args);
if (!response.ok) throw response.error;
expect(
response.value.limitations.filter((text) => text.includes(limitation)),
).toHaveLength(1);
},
);
it("honors cancellation both before acquisition and across decoder completion", async () => {
const first = new AbortController();
const firstReason = { caller: "before source-map acquisition" };
first.abort(firstReason);
const response = await new WebSourceLocationService(
{
load: () => {
throw new Error("must not acquire");
},
},
decoder,
).trace(args, { signal: first.signal });
expect(response.ok).toBe(false);
if (!response.ok) expect(response.error.cause).toBe(firstReason);
const controller = new AbortController();
const lateReason = { caller: "after source-map provider completion" };
const late = await service(undefined, {
trace: (input) => {
controller.abort(lateReason);
return decoder.trace(input);
},
}).trace(args, { signal: controller.signal });
if (late.ok) throw new Error("expected cancellation");
expect(late.error).toBeInstanceOf(AnalysisCancelledError);
expect(late.error.cause).toBe(lateReason);
expect(parseEvidence(late.error.partialObservation)).toMatchObject({
operation: "trace_web_source_location",
confidence: "derived",
});
const malformedDecoder: WebSourceMapPort = {
trace: async (input, options) => {
const decoded = await decoder.trace(input, options);
return decoded.ok
? ok({ ...decoded.value, source_map_sha256: "b".repeat(64) })
: decoded;
},
};
const malformed = await new WebSourceLocationService(
{ load: () => Promise.resolve(ok(webSourceLocationFixture())) },
malformedDecoder,
).trace(args);
expect(malformed.ok).toBe(false);
if (!malformed.ok)
expect(malformed.error).toBeInstanceOf(AnalysisOutputError);
const invalidController = new AbortController();
const malformedLate = await new WebSourceLocationService(
{ load: () => Promise.resolve(ok(webSourceLocationFixture())) },
{
trace: async (input, options) => {
const decoded = await decoder.trace(input, options);
invalidController.abort();
return decoded.ok
? ok({ ...decoded.value, source_map_sha256: "b".repeat(64) })
: decoded;
},
},
).trace(args, { signal: invalidController.signal });
expect(malformedLate.ok).toBe(false);
if (!malformedLate.ok)
expect(malformedLate.error).toBeInstanceOf(AnalysisOutputError);
});