From cfa04985c210cccc71483df1bf370824c6995bc5 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:55:15 -0500 Subject: [PATCH] test(browser): consolidate runtime window and request contracts (#13230) * test(browser): consolidate runtime window and request contracts * test(browser): distinguish reused request producer fields --- .../execution/CdpExecutionWindow.test.ts | 72 +++++----------- .../execution/CdpRuntimeRequests.test.ts | 57 +++--------- .../execution/CdpRuntimeRetention.test.ts | 58 ++++--------- .../browser/cdpRuntimeFrameIdentity.test.ts | 12 ++- tests/boundary/browser/cdpWebRuntime.test.ts | 50 ++++++++--- .../browser/cdpWebRuntimeReview.test.ts | 86 ------------------- 6 files changed, 93 insertions(+), 242 deletions(-) diff --git a/src/browser/execution/CdpExecutionWindow.test.ts b/src/browser/execution/CdpExecutionWindow.test.ts index 40854eb0d2..71f776f314 100644 --- a/src/browser/execution/CdpExecutionWindow.test.ts +++ b/src/browser/execution/CdpExecutionWindow.test.ts @@ -38,8 +38,9 @@ it("ends the actual armed window at its selected duration and disposes its timer const window = new CdpExecutionWindow(selectedSession()); try { const result = window.start(10); + vi.advanceTimersByTime(9); expect(window.active).toBe(true); - vi.advanceTimersByTime(10); + vi.advanceTimersByTime(1); await expect(result).resolves.toBe("window_elapsed"); expect(window.active).toBe(false); expect(vi.getTimerCount()).toBe(0); @@ -78,43 +79,15 @@ it("settles caller cancellation and removes its local timer", async () => { } }); -it("keeps a root document transition distinct from a child frame event", async () => { - const rootSession = selectedSession(); - const root = new CdpExecutionWindow(rootSession); - const rootResult = root.start(30_000); - deliver(rootSession, root, { - method: "Page.frameNavigated", - params: { frame: { id: "new-main", url: "https://example.test/" } }, - }); - await expect(rootResult).resolves.toBe("document_changed"); - - const childSession = selectedSession(); - const child = new CdpExecutionWindow(childSession); - const childResult = child.start(30_000); - deliver(childSession, child, { - method: "Page.frameNavigated", - params: { - frame: { - id: "child-frame", - parentId: "selected-main", - url: "https://example.test/child", - }, - }, - }); - expect(child.active).toBe(true); - child.end("window_elapsed"); - await expect(childResult).resolves.toBe("window_elapsed"); -}); - // The target session's document owner decides whether a main-frame commit is // another document; a re-fired commit of the selected one keeps the window. it.each([ - ["the selected loader again", "loader-selected", "/", "window_elapsed"], - ["a new loader", "loader-next", "/", "document_changed"], - ["no loader", undefined, "/", "document_changed"], + ["the selected loader again", "loader-selected", "window_elapsed"], + ["a new loader", "loader-next", "document_changed"], + ["no loader", undefined, "document_changed"], ] as const)( "ends the window on a main-frame commit with %s only when the document may differ", - async (_label, loaderId, path, expected) => { + async (_label, loaderId, expected) => { const session = selectedSession(); const window = new CdpExecutionWindow(session); const result = window.start(30_000); @@ -124,11 +97,23 @@ it.each([ frame: { id: "selected-main", ...(loaderId === undefined ? {} : { loaderId }), - url: "https://example.test" + path, + url: "https://example.test/", }, }, }); - if (window.active) window.end("window_elapsed"); + if (expected === "window_elapsed") { + deliver(session, window, { + method: "Page.frameNavigated", + params: { + frame: { + id: "child-frame", + parentId: "selected-main", + url: "https://example.test/child", + }, + }, + }); + } + window.end("window_elapsed"); await expect(result).resolves.toBe(expected); }, ); @@ -156,20 +141,3 @@ it.each([ await expect(result).resolves.toBe(expected); }, ); - -it("surfaces malformed frame identity as a protocol failure without guessing a transition", async () => { - const session = selectedSession(); - const window = new CdpExecutionWindow(session); - const result = window.start(30_000); - deliver(session, window, { - method: "Page.frameNavigated", - params: { - frame: { id: "child-frame", parentId: 7, url: "https://example.test/" }, - }, - }); - await expect(result).rejects.toMatchObject({ - _tag: "BrowserObservationError", - reason: "protocol_error", - }); - expect(window.reason).toBeUndefined(); -}); diff --git a/src/browser/execution/CdpRuntimeRequests.test.ts b/src/browser/execution/CdpRuntimeRequests.test.ts index a3d742589e..4e055f337e 100644 --- a/src/browser/execution/CdpRuntimeRequests.test.ts +++ b/src/browser/execution/CdpRuntimeRequests.test.ts @@ -1,6 +1,4 @@ import { expect, it } from "vitest"; -import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; -import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js"; import { WEB_RUNTIME_LIMITS } from "../../domain/webRuntime.js"; import { receiveCdpEvent } from "../CdpConnection.js"; import { CdpRuntimeRequests } from "./CdpRuntimeRequests.js"; @@ -59,51 +57,16 @@ it("preserves a typed resource refusal for oversized retained initiator facts", ), ), ); - try { - requests.result(); - expect.fail( - "Expected the retained initiator allowance to refuse the result", - ); - } catch (cause) { - expect(cause).toBeInstanceOf(AnalysisResourceConstraintError); - if (!(cause instanceof AnalysisResourceConstraintError)) throw cause; - expect(projectAnalysisError(cause)).toMatchObject({ - code: "resource_constraint", - details: { resource: "capacity" }, - }); - } -}); - -it("retains separate occurrences of a reused request identity and raw initiator facts", () => { - const requests = new CdpRuntimeRequests(sources); - for (const timestamp of [0, 1.25]) { - const request = event({ url: `${origin}/resource-${timestamp}` }); - requests.ingest( - receiveCdpEvent({ - ...request, - params: { - ...request.params, - timestamp, - initiator: { - type: "parser", - vendor_extension: { occurrence: timestamp, labels: ["observed"] }, - }, - }, + expect(() => requests.result()).toThrow( + expect.objectContaining({ + _tag: "AnalysisResourceConstraintError", + operation: "observe_web_execution", + resource: "capacity", + reportedLimits: expect.objectContaining({ + boundary: "browser-runtime-retention", + kind: "requests", + limit_bytes: WEB_RUNTIME_LIMITS.retainedEventBytes, }), - ); - } - expect(requests.result()).toEqual( - [0, 1.25].map((timestamp) => - expect.objectContaining({ - request_id: "request", - url: `${origin}/resource-${timestamp}`, - timestamp_seconds: timestamp, - reported_initiator: { - type: "parser", - vendor_extension: { occurrence: timestamp, labels: ["observed"] }, - }, - causal_attribution: "unknown", - }), - ), + }), ); }); diff --git a/src/browser/execution/CdpRuntimeRetention.test.ts b/src/browser/execution/CdpRuntimeRetention.test.ts index 1be7cec033..f4f0f1f59e 100644 --- a/src/browser/execution/CdpRuntimeRetention.test.ts +++ b/src/browser/execution/CdpRuntimeRetention.test.ts @@ -1,52 +1,30 @@ -import { describe, expect, it } from "vitest"; +import { expect, it } from "vitest"; import { WEB_RUNTIME_LIMITS } from "../../domain/webRuntime.js"; import { RuntimeRetention } from "./CdpRuntimeRetention.js"; -describe("RuntimeRetention", () => { - it("admits retention up to the limit and reports the total a refused charge would reach", () => { - const retention = new RuntimeRetention("observe_web_runtime", "metadata"); - retention.charge(WEB_RUNTIME_LIMITS.retainedEventBytes - 1); +it.each([ + ["metadata", WEB_RUNTIME_LIMITS.retainedEventBytes], + ["sources", WEB_RUNTIME_LIMITS.sourceBytes], +] as const)( + "admits complete %s retention at its limit and reports the attempted total", + (kind, limit) => { + const retention = new RuntimeRetention("observe_web_execution", kind); + retention.charge(limit - 1); retention.charge(1); expect(() => retention.charge(5)).toThrow( expect.objectContaining({ - reportedLimits: expect.objectContaining({ - kind: "metadata", - retained_bytes: WEB_RUNTIME_LIMITS.retainedEventBytes + 5, - limit_bytes: WEB_RUNTIME_LIMITS.retainedEventBytes, - }), + reportedLimits: { + boundary: "browser-runtime-retention", + kind, + retained_bytes: limit + 5, + limit_bytes: limit, + }, fixedAllowance: expect.objectContaining({ - limit: WEB_RUNTIME_LIMITS.retainedEventBytes, + limit, unit: "bytes", }), }), ); - }); - - it("charges nothing for a refused retention", () => { - const retention = new RuntimeRetention("observe_web_runtime", "requests"); - retention.charge(10); - const room = WEB_RUNTIME_LIMITS.retainedEventBytes - 10; - expect(() => retention.charge(room + 1)).toThrow( - expect.objectContaining({ - reportedLimits: expect.objectContaining({ - retained_bytes: WEB_RUNTIME_LIMITS.retainedEventBytes + 1, - }), - }), - ); - // The refused charge left the remaining room intact. - expect(() => retention.charge(room)).not.toThrow(); - }); - - it("keeps the source-text limit separate from metadata", () => { - const retention = new RuntimeRetention("observe_web_runtime", "sources"); - expect(() => retention.charge(WEB_RUNTIME_LIMITS.sourceBytes + 1)).toThrow( - expect.objectContaining({ - reportedLimits: expect.objectContaining({ - kind: "sources", - limit_bytes: WEB_RUNTIME_LIMITS.sourceBytes, - }), - }), - ); - }); -}); + }, +); diff --git a/tests/boundary/browser/cdpRuntimeFrameIdentity.test.ts b/tests/boundary/browser/cdpRuntimeFrameIdentity.test.ts index 7d5a52eb23..241f7950e7 100644 --- a/tests/boundary/browser/cdpRuntimeFrameIdentity.test.ts +++ b/tests/boundary/browser/cdpRuntimeFrameIdentity.test.ts @@ -81,6 +81,7 @@ it.each([ ["execution", "equivalent inline fragment", false, "inline", null], ["listeners", "fragment change, no loader", false, changedFragment, changed], ["execution", "fragment change, same loader", true, changedFragment, null], + ["listeners", "path change, same loader", true, "new-path", null], ["listeners", "malformed fragment", true, badFragment, invalid], [ "listeners", @@ -111,7 +112,9 @@ it.each([ const updated = change === "inline" ? { url: `${url}#details`, urlFragment: undefined } - : change; + : change === "new-path" + ? { url: `${origin}/new-path?caller=value` } + : change; return frameTree(url, { loaderId: loader ? documentId : undefined, urlFragment: "#details", @@ -123,9 +126,10 @@ it.each([ const result = await run(browser, action); if (reason === null) { if (!result.ok) throw result.error; - expect(result.value.target.initial_url).toBe( - `${browser.allowedOrigin}${query}#details`, - ); + expect(result.value.target).toMatchObject({ + initial_url: `${browser.allowedOrigin}${query}#details`, + loader_id: loader ? documentId : null, + }); } else { expect(result).toMatchObject({ ok: false, error: { reason } }); } diff --git a/tests/boundary/browser/cdpWebRuntime.test.ts b/tests/boundary/browser/cdpWebRuntime.test.ts index 5a04d1cc22..e84e197266 100644 --- a/tests/boundary/browser/cdpWebRuntime.test.ts +++ b/tests/boundary/browser/cdpWebRuntime.test.ts @@ -33,8 +33,9 @@ const fixture = async (options: FakeOptions = {}) => { }; describe("native runtime producer boundary", () => { - it("binds complete producer stacks by script ID and ignores foreign sessions without URL guessing", async () => { + it("preserves requests with a reused ID, joining only selected-session producer stacks", async () => { const { browser, provider, execution } = await fixture(); + const redirectedUrl = `${browser.endpoint}/redirected?caller-value=retained`; const params = { requestId: "selected-request", frameId: "runtime-main", @@ -45,7 +46,7 @@ describe("native runtime producer boundary", () => { }, initiator: { type: "script", - producerExtension: "retain-unknown-fields", + producerExtension: { occurrence: 1, label: "initial" }, stack: { description: "observed-sync-stack", callFrames: [ @@ -73,6 +74,10 @@ describe("native runtime producer boundary", () => { }, }, }; + const redirectedInitiator = { + ...params.initiator, + producerExtension: { occurrence: 2, label: "redirected" }, + }; const result = await provider.observeExecution( { ...execution, observation_ms: 30 }, { @@ -89,23 +94,42 @@ describe("native runtime producer boundary", () => { params, sessionId: "session-1", }); + browser.emitEvent({ + method: "Network.requestWillBeSent", + params: { + ...params, + timestamp: 13, + request: { url: redirectedUrl, method: "GET" }, + initiator: redirectedInitiator, + }, + sessionId: "session-1", + }); }, }, }, ); if (!result.ok) throw result.error; - expect(result.value.requests).toHaveLength(1); - expect(result.value.requests[0]?.reported_initiator).toEqual( - params.initiator, - ); - expect(result.value.requests[0]?.callsites).toMatchObject([ - { script_id: "script-b", source_association: "script_id" }, - { script_id: "unknown-script", source_association: "unknown" }, + const expected = { + request_id: "selected-request", + callsites: [ + { script_id: "script-b", source_association: "script_id" }, + { script_id: "unknown-script", source_association: "unknown" }, + ], + async_parent_ids: [{ id: "async-parent", debugger_id: "other-debugger" }], + causal_attribution: "unknown", + }; + expect(result.value.requests).toMatchObject([ + { + ...expected, + url: params.request.url, + timestamp_seconds: 12.5, + method: "POST", + }, + { ...expected, url: redirectedUrl, timestamp_seconds: 13, method: "GET" }, ]); - expect(result.value.requests[0]?.async_parent_ids).toEqual([ - { id: "async-parent", debugger_id: "other-debugger" }, - ]); - expect(result.value.requests[0]?.causal_attribution).toBe("unknown"); + expect( + result.value.requests.map(({ reported_initiator }) => reported_initiator), + ).toEqual([params.initiator, redirectedInitiator]); }); }); diff --git a/tests/boundary/browser/cdpWebRuntimeReview.test.ts b/tests/boundary/browser/cdpWebRuntimeReview.test.ts index f6338ee9d2..e80a721039 100644 --- a/tests/boundary/browser/cdpWebRuntimeReview.test.ts +++ b/tests/boundary/browser/cdpWebRuntimeReview.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it, onTestFinished } from "vitest"; import { CdpWebRuntimeProvider } from "../../../src/browser/execution/CdpWebRuntimeProvider.js"; import { observeWebExecutionInputSchema } from "../../../src/domain/webExecution.js"; -import { inspectWebEventListenersInputSchema } from "../../../src/domain/webEventListeners.js"; import { negativeColumnScript, negativeColumnScriptUrl, @@ -9,91 +8,6 @@ import { startRuntimeBrowser, } from "../../fixtures/webRuntime.js"; -describe("runtime document identity across same-document URL changes", () => { - it.each(["execution", "listeners"] as const)( - "accepts a stable loader for %s while retaining the initial location", - async (operation) => { - const browser = await startRuntimeBrowser({ - commandResult: (command, origin, reads) => - command.method === "Page.getFrameTree" - ? { - frameTree: { - frame: { - id: "runtime-main", - url: `${origin}/${reads === 1 ? "allowed" : "new-path?caller=value#fragment"}`, - loaderId: "same-document", - }, - }, - } - : undefined, - }); - onTestFinished(() => browser.close()); - const provider = new CdpWebRuntimeProvider(); - const scope = { - cdp_endpoint: browser.endpoint, - target_id: "allowed-page", - }; - const result = - operation === "execution" - ? await provider.observeExecution( - observeWebExecutionInputSchema.parse({ - ...scope, - observation_ms: 5, - }), - ) - : await provider.inspectEventListeners( - inspectWebEventListenersInputSchema.parse({ - ...scope, - selector: "#selected", - }), - ); - if (!result.ok) throw result.error; - expect(result.value.target.initial_url).toBe( - `${browser.endpoint}/allowed`, - ); - expect(result.value.target.loader_id).toBe("same-document"); - }, - ); - - it.each([ - { loader: undefined, denied: false, reason: "target_changed" }, - { loader: "same-document", denied: true, reason: "target_not_allowed" }, - ])( - "preserves conservative identity and origin checks: $reason", - async ({ loader, denied, reason }) => { - const browser = await startRuntimeBrowser({ - commandResult: (command, origin, reads) => - command.method === "Page.getFrameTree" - ? { - frameTree: { - frame: { - id: "runtime-main", - url: - reads === 1 - ? `${origin}/allowed` - : denied - ? "https://unselected.example/new" - : `${origin}/new`, - ...(loader === undefined ? {} : { loaderId: loader }), - }, - }, - } - : undefined, - }); - onTestFinished(() => browser.close()); - const result = await new CdpWebRuntimeProvider().inspectEventListeners( - inspectWebEventListenersInputSchema.parse({ - cdp_endpoint: browser.endpoint, - target_id: "allowed-page", - selector: "#selected", - }), - ); - if (result.ok) throw new Error("Unverified document or origin must fail"); - expect(result.error).toMatchObject({ reason }); - }, - ); -}); - describe("runtime collector failure and uncertain source metadata", () => { it.each(["Debugger.scriptParsed", "Network.requestWillBeSent"])( "stops an armed long window immediately for malformed %s",