Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

perf(browser): normalize precise coverage once by script identity

morluto3d79903fb1eb
diff --git a/src/browser/execution/CdpExecutionCapture.ts b/src/browser/execution/CdpExecutionCapture.ts
index ebb675c56..023c3f8e2 100644
--- a/src/browser/execution/CdpExecutionCapture.ts
+++ b/src/browser/execution/CdpExecutionCapture.ts
@@ -94,9 +94,9 @@ export const captureWebExecution = async (
sources.belongsToDocument(id),
);
const sample =
- raw === undefined
- ? undefined
- : normalizePreciseCoverage(raw, sources, retained);
+ parsed?.success === true
+ ? normalizePreciseCoverage(parsed.data, sources, retained)
+ : undefined;
await session.options.progress?.report({
phase: "browser_execution",
completed: 2,
diff --git a/src/browser/execution/CdpPreciseCoverage.ts b/src/browser/execution/CdpPreciseCoverage.ts
index 977ee50f8..95e2cdc0d 100644
--- a/src/browser/execution/CdpPreciseCoverage.ts
+++ b/src/browser/execution/CdpPreciseCoverage.ts
@@ -1,34 +1,30 @@
+import type { z } from "zod";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import type { WebExecution } from "../../domain/webExecution.js";
import type { WebRuntimeSource } from "../../domain/webRuntime.js";
-import { preciseCoverageSchema } from "./CdpRuntimeProtocol.js";
+import type { preciseCoverageSchema } from "./CdpRuntimeProtocol.js";
import type { CdpRuntimeSources } from "./CdpRuntimeSources.js";
/** Validate source-range bounds against exact retained UTF-16 text without flattening nested counts. */
export const normalizePreciseCoverage = (
- raw: unknown,
+ parsed: z.infer<typeof preciseCoverageSchema>,
sources: CdpRuntimeSources,
retained: readonly WebRuntimeSource[],
): {
readonly coverage: WebExecution["coverage"];
readonly timestamp: number;
} => {
- const parsed = preciseCoverageSchema.safeParse(raw);
- if (!parsed.success)
- throw new AnalysisOutputError(
- sources.session.operation,
- `Malformed precise coverage: ${parsed.error.message}`,
- );
+ const retainedSources = new Map(
+ retained.map(({ script_id, source }) => [script_id, source]),
+ );
const scripts: WebExecution["coverage"]["scripts"] = [];
let excluded = 0;
- for (const script of parsed.data.result) {
+ for (const script of parsed.result) {
if (!sources.belongsToDocument(script.scriptId)) {
excluded += 1;
continue;
}
- const source = retained.find(
- (item) => item.script_id === script.scriptId,
- )?.source;
+ const source = retainedSources.get(script.scriptId);
scripts.push({
script_id: script.scriptId,
reported_url: sources.sourceUrl(script.scriptId, script.url),
@@ -57,7 +53,7 @@ export const normalizePreciseCoverage = (
});
}
return {
- timestamp: parsed.data.timestamp,
+ timestamp: parsed.timestamp,
coverage: {
state: "captured",
reason: null,
diff --git a/tests/boundary/browser/cdpWebRuntime.test.ts b/tests/boundary/browser/cdpWebRuntime.test.ts
index ac9049c62..7b5c772ca 100644
--- a/tests/boundary/browser/cdpWebRuntime.test.ts
+++ b/tests/boundary/browser/cdpWebRuntime.test.ts
@@ -188,6 +188,107 @@ describe("runtime window and producer granularity", () => {
});
});
+it("joins a reordered multi-script coverage sample by identity and preserves unavailable bounds", async () => {
+ const texts = new Map(
+ Array.from({ length: 256 }, (_, index) => [
+ `script-${index}`,
+ `// 🔥\r\n${" ".repeat(index)}function f(){return ${index};}`,
+ ]),
+ );
+ const { browser, provider, execution } = await fixture({
+ commandEvents: (command, origin) =>
+ command.method === "Debugger.enable"
+ ? [...texts.keys(), "foreign-script"].map((scriptId) => ({
+ ...(command.sessionId === undefined
+ ? {}
+ : { sessionId: command.sessionId }),
+ method: "Debugger.scriptParsed",
+ params: {
+ scriptId,
+ url: `${origin}/shared.js`,
+ executionContextId: scriptId === "foreign-script" ? 99 : 1,
+ startLine: 0,
+ startColumn: 0,
+ endLine: 1,
+ endColumn: 0,
+ },
+ }))
+ : undefined,
+ commandError: (command) =>
+ command.method === "Debugger.getScriptSource" &&
+ command.params.scriptId === "script-128"
+ ? { code: -32000, message: "Selected source is unavailable" }
+ : undefined,
+ commandResult: (command, origin) => {
+ if (command.method === "Debugger.getScriptSource")
+ return { scriptSource: texts.get(String(command.params.scriptId)) };
+ if (command.method !== "Profiler.takePreciseCoverage") return undefined;
+ return {
+ timestamp: 13,
+ result: [...texts]
+ .reverse()
+ .map(([scriptId, text]) => ({
+ scriptId,
+ url: `${origin}/shared.js`,
+ functions: [
+ {
+ functionName: "f",
+ isBlockCoverage: true,
+ ranges: [
+ { startOffset: 0, endOffset: text.length, count: 1 },
+ { startOffset: 8, endOffset: 9, count: 0 },
+ ],
+ },
+ ],
+ }))
+ .concat([
+ {
+ scriptId: "foreign-script",
+ url: `${origin}/shared.js`,
+ functions: [],
+ },
+ ]),
+ };
+ },
+ });
+ const result = await provider.observeExecution(execution);
+ if (!result.ok) throw result.error;
+ expect(result.value.coverage.excluded_scripts).toBe(1);
+ expect(
+ result.value.coverage.scripts.map(({ script_id }) => script_id),
+ ).toEqual([...texts.keys()].reverse());
+ for (const script of result.value.coverage.scripts) {
+ expect(script.functions[0]?.ranges).toEqual([
+ {
+ start_offset: 0,
+ end_offset: texts.get(script.script_id)?.length,
+ count: 1,
+ source_bounds:
+ script.script_id === "script-128" ? "unknown" : "verified",
+ },
+ {
+ start_offset: 8,
+ end_offset: 9,
+ count: 0,
+ source_bounds:
+ script.script_id === "script-128" ? "unknown" : "verified",
+ },
+ ]);
+ }
+ expect(
+ result.value.sources.find(({ script_id }) => script_id === "script-128")
+ ?.source,
+ ).toMatchObject({ state: "unavailable" });
+ expect(
+ browser.commands.some(
+ ({ method }) => method === "Profiler.stopPreciseCoverage",
+ ),
+ ).toBe(true);
+ expect(
+ browser.commands.some(({ method }) => method === "Target.detachFromTarget"),
+ ).toBe(true);
+});
+
describe("runtime source and listener identity", () => {
it("retains same-URL script identities, UTF-16 bounds, nested zero counts and actual cleanup", async () => {
const { browser, provider, execution } = await fixture();
diff --git a/tests/boundary/browser/cdpWebRuntimeSourceIdentity.test.ts b/tests/boundary/browser/cdpWebRuntimeSourceIdentity.test.ts
index e14b81d20..ef97f900a 100644
--- a/tests/boundary/browser/cdpWebRuntimeSourceIdentity.test.ts
+++ b/tests/boundary/browser/cdpWebRuntimeSourceIdentity.test.ts
@@ -5,6 +5,59 @@ import { observeWebExecutionInputSchema } from "../../../src/domain/webExecution
import { inspectWebEventListenersInputSchema } from "../../../src/domain/webEventListeners.js";
import { startRuntimeBrowser } from "../../fixtures/webRuntime.js";
+it("invalidates retained sources when their execution context is reused during another source read", async () => {
+ let emit: ((event: CdpEvent) => void) | undefined;
+ const browser = await startRuntimeBrowser({
+ commandResult: (command, origin) => {
+ if (
+ command.method === "Debugger.getScriptSource" &&
+ command.params.scriptId === "script-b"
+ )
+ emit?.({
+ sessionId: "session-1",
+ method: "Runtime.executionContextCreated",
+ params: {
+ context: {
+ id: 1,
+ uniqueId: "replacement-context",
+ origin,
+ name: "",
+ auxData: {
+ frameId: "runtime-main",
+ isDefault: true,
+ type: "default",
+ },
+ },
+ },
+ });
+ return undefined;
+ },
+ });
+ emit = browser.emitEvent;
+ onTestFinished(() => browser.close());
+ const result = await new CdpWebRuntimeProvider().observeExecution(
+ observeWebExecutionInputSchema.parse({
+ cdp_endpoint: browser.endpoint,
+ target_id: "allowed-page",
+ observation_ms: 5,
+ }),
+ );
+ if (!result.ok) throw result.error;
+ expect(result.value.coverage.scripts).toEqual([]);
+ expect(result.value.coverage.excluded_scripts).toBe(3);
+ expect(result.value.script_inventory.main_document_scripts).toBe(0);
+ for (const scriptId of ["script-a", "script-b"])
+ expect(
+ result.value.sources.find(({ script_id }) => script_id === scriptId),
+ ).toMatchObject({ frame_id: null, source: { state: "excluded" } });
+ expect(browser.commands.map(({ method }) => method)).toEqual(
+ expect.arrayContaining([
+ "Profiler.stopPreciseCoverage",
+ "Target.detachFromTarget",
+ ]),
+ );
+});
+
it.each(
["listeners", "execution"].flatMap((operation) =>
["source_read", "other_source_read", "final_assertion"].map((phase) => ({