Compare commits

..
Author SHA1 Message Date
Kaoru0822andClaude Opus 5.5 38998e465f fix(browser): keep cancellation for scenario captures cancelled during startup
capture_browser_scenario turned a cancellation into unreadable_output
whenever the retained capture failed the completed-report schema. A capture
cancelled while the initial navigation was pending retains no steps and no
completeness, which the partial-observation type deliberately allows, so the
caller lost both the typed cancellation and the retained observation. Only a
capture that reports completeness now claims to be a completed report; other
cancelled captures keep their cancellation and raw partial observation.

Fixes #5364

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 15:09:23 +00:00
gensokyo-dev e52a71602d test: stabilize worker cancellation and trailer regressions (#5497) 2026-10-20 23:06:09 +08:00
HawkForge 8443692e2b fix(javascript): keep overflowing timer delays unknown (#3456)
Normalize non-finite timer literals to the existing unknown value at the semantic fact producer. Keep timers, source provenance, binding resolution and unrelated functions; preserve all finite delay values.

Qualify shared CLI/MCP behavior with precise regression oracles, 111 tests, actual source fixtures, real-package summary/fact/Evidence workflows and current-main integration.

Fixes #3400.
2026-10-20 15:02:38 +00:00
12 changed files with 355 additions and 99 deletions

No files matched your search

@@ -1,6 +1,9 @@
import { expect, it } from "vitest";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import { parseEvidence } from "../domain/evidence.js";
import { browserScenarioInputSchema } from "../domain/browserScenario.js";
@@ -77,6 +80,45 @@ it("converts a raw scenario capture retained after cleanup failure", async () =>
}
});
it("keeps cancellation and the incomplete capture retained before navigation finished", async () => {
const { completeness: _completeness, ...complete } = capture;
// The startup failure path retains no steps and no completeness.
const incomplete = { ...complete, steps: [] };
const failure = new AnalysisCancelledError("capture_browser_scenario", {
partialObservation: {
kind: "browser-scenario-observation",
capture: incomplete,
},
});
const provider: BrowserScenarioCapturePort = {
identity: () => ({ id: "fixture", name: "fixture", version: "1" }),
captureScenario: async () => err(failure),
};
const result = await captureBrowserScenario(provider, scenario);
if (result.ok) throw new Error("Expected cancellation");
expect(result.error).toBe(failure);
expect(result.error.partialObservation).toEqual({
kind: "browser-scenario-observation",
capture: incomplete,
});
});
it("rejects a cancelled capture that claims completeness but is malformed", async () => {
const failure = new AnalysisCancelledError("capture_browser_scenario", {
partialObservation: {
kind: "browser-scenario-observation",
capture: { ...capture, steps: [] },
},
});
const provider: BrowserScenarioCapturePort = {
identity: () => ({ id: "fixture", name: "fixture", version: "1" }),
captureScenario: async () => err(failure),
};
const result = await captureBrowserScenario(provider, scenario);
if (result.ok) throw new Error("Expected failure");
expect(result.error).toBeInstanceOf(AnalysisOutputError);
});
it.each([
null,
{ request: "opaque cancellation" },
@@ -53,7 +53,13 @@ export const captureBrowserScenario = async (
provider.identity(),
);
} else if (!report.success) {
if (captured.error instanceof AnalysisCancelledError)
// Only a capture that reports completeness claims to be a completed
// report; one cancelled earlier, e.g. during initial navigation, is a
// legitimately incomplete observation and keeps its cancellation.
if (
captured.error instanceof AnalysisCancelledError &&
"completeness" in partial.capture
)
return err(
new AnalysisOutputError(
OPERATION,
+2
View File
@@ -74,6 +74,8 @@ describe("CLI JSON path normalization", () => {
expect(parsed.error.issues).toEqual([
expect.objectContaining({
path: ["executable_path"],
code: "invalid_format",
message: expect.stringContaining("absolute local filesystem path"),
}),
]);
});
@@ -73,6 +73,23 @@ describe("JavaScript semantic analysis: runtime boundaries 1", () => {
]);
});
it("keeps an overflowing timer delay unknown in a complete semantic result", () => {
const ir = analyzeJavaScriptSemantics(`
function greet() { return "hello"; }
setTimeout(() => greet(), 1e999);
`);
expect(ir.timerOperations).toEqual([
expect.objectContaining({
kind: "schedule",
method: "setTimeout",
delayMilliseconds: null,
resolution: "complete",
}),
]);
expect(ir.callables.some(({ name }) => name === "greet")).toBe(true);
});
it("does not treat shadowed timer globals as Node timers", () => {
const ir = analyzeJavaScriptSemantics(`
function run(setTimeout, clearTimeout) {
@@ -368,7 +368,11 @@ const timerDelay = (candidate: TimerCandidate): number | null => {
if (candidate.kind !== "schedule" || candidate.method === "setImmediate")
return null;
const delay = candidate.node.arguments[1];
return t.isNumericLiteral(delay) ? delay.value : null;
// An overflowing literal such as 1e999 parses to Infinity, which JSON
// Evidence cannot carry; keep that delay unknown like any other.
return t.isNumericLiteral(delay) && Number.isFinite(delay.value)
? delay.value
: null;
};
const timerId = (candidate: TimerCandidate): string =>
+1 -6
View File
@@ -38,12 +38,7 @@ export const classifySwiftSymbol = (
let category: SwiftTypeCategory | null = null;
for (;;) {
const end = identifierEnd(mangling, offset);
if (end === undefined) {
// A word-substituted or punycode identifier (`0…`) may name a nested
// type of any kind, so the enclosing nominal no longer decides it.
if (mangling.charAt(offset) === "0") category = null;
break;
}
if (end === undefined) break;
const kind = mangling.charAt(end);
const nominal = NOMINAL_CATEGORIES.get(kind);
if (nominal === undefined) {
-14
View File
@@ -28,10 +28,6 @@ describe("modern Swift category evidence", () => {
"$sSi4mainE7doubledSiyF",
"$s9999999999999999999999BadVMa",
"$s4main04PairVMa",
// Nested types named by punycode identifiers inside struct Envelope.
"_$s6Nested8EnvelopeV007IhuqBAbO8describeSSyF",
"_$s6Nested8EnvelopeV007jvrtDBlCAEycfC",
"_$s6Nested8EnvelopeV007jvrtDBlCMa",
];
const result = categorizeSwiftTypes(
names.map((name, index) => ({ address: String(index), name })),
@@ -56,16 +52,6 @@ describe("modern Swift category evidence", () => {
).toMatchObject({ total: 0, unclassified: [] });
});
it("keeps a nested punycode class unresolved under a class filter", () => {
const name = "_$s6Nested8EnvelopeV007jvrtDBlCMa";
expect(
categorizeSwiftTypes([{ address: "0x1", name }], { category: "classes" }),
).toMatchObject({
total: 0,
unclassified: [{ name, reason: "category_not_decoded" }],
});
});
it("deduplicates display names after selecting a category", () => {
expect(
categorizeSwiftTypes(
@@ -217,6 +217,8 @@ cliTest(
issues: [
{
path: ["executable_path"],
reason: "invalid_format",
message: expect.stringContaining("absolute local filesystem path"),
},
],
},
+69 -64
View File
@@ -557,70 +557,75 @@ captureTest(
},
);
captureTest(
"keeps malformed gRPC-web trailers partial through CLI and MCP without changing capture bytes",
async ({ cli, mcp }) => {
const trailerCases = [
["valid", "grpc-status", "0", "complete"],
["uppercase", "Grpc-Status", "0", "partial"],
["nul", "grpc-status", "0\u0000bad", "partial"],
["lf", "grpc-status", "0\nbad", "partial"],
["cr", "grpc-status", "0\rbad", "partial"],
["vt", "grpc-status", "0\u000bbad", "partial"],
["del", "grpc-status", "0\u007fbad", "partial"],
] as const;
captureTest.for(
(["grpc-web", "grpc-web-text"] as const).flatMap((framing) =>
trailerCases.map(([name, headerName, value, status]) => ({
framing,
name,
headerName,
value,
status,
})),
),
)(
"preserves $framing trailer case $name through CLI and MCP without changing capture bytes",
async ({ framing, name, headerName, value, status }, { cli, mcp }) => {
const root = await createTestTempDirectory("rea-grpc-web-trailers-");
for (const framing of ["grpc-web", "grpc-web-text"] as const)
for (const [name, headerName, value, status] of [
["valid", "grpc-status", "0", "complete"],
["uppercase", "Grpc-Status", "0", "partial"],
["nul", "grpc-status", "0\u0000bad", "partial"],
["lf", "grpc-status", "0\nbad", "partial"],
["cr", "grpc-status", "0\rbad", "partial"],
["vt", "grpc-status", "0\u000bbad", "partial"],
["del", "grpc-status", "0\u007fbad", "partial"],
] as const) {
const path = join(root, `${framing}-${name}.har`);
const trailer = Buffer.from(`${headerName}: ${value}\r\n`);
const body = Buffer.concat([
protobufFrame(Buffer.from([8, 1])),
protobufFrame(trailer, 128),
]);
const original = protobufHar(
framing === "grpc-web-text"
? Buffer.from(body.toString("base64"))
: body,
`application/${framing}`,
);
await writeFile(path, original);
const response = await cli.run({
arguments: [
"inspect-web-network-capture",
path,
"har",
"--record",
"0",
"--protobuf-framing",
"auto",
"--json",
],
});
expect(response.exitCode, response.stdout + response.stderr).toBe(0);
const evidence = parseEvidence(response.json);
const report = webNetworkCaptureSchema.parse(
evidence.normalized_result,
);
expect(report.protobuf_coverage?.status, name).toBe(status);
expect(report.records[0]?.protobuf?.[0]).toMatchObject({
status,
framing,
examined_bytes: body.length,
frames: [
{ kind: "data", status: "complete", examined_bytes: 2 },
{ kind: "trailer", status, examined_bytes: trailer.length },
],
fields: [{ number: 1, wire_type: "varint", value: "1" }],
});
const reply = await mcp.call("inspect_web_network_capture", {
capture_path: path,
format: "har",
record_ordinals: [0],
protobuf: { framing: "auto" },
});
expect(reply.isError, JSON.stringify(reply)).not.toBe(true);
expect(reply.structuredContent).toEqual(response.json);
expect(await readFile(path, "utf8")).toBe(original);
}
const path = join(root, `${framing}-${name}.har`);
const trailer = Buffer.from(`${headerName}: ${value}\r\n`);
const body = Buffer.concat([
protobufFrame(Buffer.from([8, 1])),
protobufFrame(trailer, 128),
]);
const original = protobufHar(
framing === "grpc-web-text" ? Buffer.from(body.toString("base64")) : body,
`application/${framing}`,
);
await writeFile(path, original);
const response = await cli.run({
arguments: [
"inspect-web-network-capture",
path,
"har",
"--record",
"0",
"--protobuf-framing",
"auto",
"--json",
],
});
expect(response.exitCode, response.stdout + response.stderr).toBe(0);
const evidence = parseEvidence(response.json);
const report = webNetworkCaptureSchema.parse(evidence.normalized_result);
expect(report.protobuf_coverage?.status, name).toBe(status);
expect(report.records[0]?.protobuf?.[0]).toMatchObject({
status,
framing,
examined_bytes: body.length,
frames: [
{ kind: "data", status: "complete", examined_bytes: 2 },
{ kind: "trailer", status, examined_bytes: trailer.length },
],
fields: [{ number: 1, wire_type: "varint", value: "1" }],
});
const reply = await mcp.call("inspect_web_network_capture", {
capture_path: path,
format: "har",
record_ordinals: [0],
protobuf: { framing: "auto" },
});
expect(reply.isError, JSON.stringify(reply)).not.toBe(true);
expect(reply.structuredContent).toEqual(response.json);
expect(await readFile(path, "utf8")).toBe(original);
},
);
@@ -125,6 +125,41 @@ it("resolves erased wrappers through the composed application graph", async () =
expect(parseJavaScriptSource(source, "app.mts")?.errors).toEqual([]);
});
it.each([
{
name: "earlier",
source: 'export const target = () => "ready", result = target();',
resolved: true,
},
{
name: "later",
source: 'export const result = target(), target = () => "ready";',
resolved: false,
},
])(
"orders $name exported declarator reads in the composed application graph",
async ({ source, resolved }) => {
const analysis = await analyzeFiles(new Map([["app.mts", source]]));
const calls = analysis.semantic_graph.relations.filter(
({ relation }) => relation === "calls",
);
if (resolved) {
expect(calls).toEqual([
expect.objectContaining({ resolution: "resolved" }),
]);
} else {
expect(calls.some(({ resolution }) => resolution === "resolved")).toBe(
false,
);
expect(analysis.semantic_graph.unknowns).toContainEqual(
expect.objectContaining({
relation_kinds: expect.arrayContaining(["calls"]),
}),
);
}
},
);
it.each([
{
name: "path-value wrappers",
@@ -1,13 +1,63 @@
import { createHash } from "node:crypto";
import { once } from "node:events";
import { createInterface } from "node:readline";
import { PassThrough, type Readable } from "node:stream";
import { setImmediate as yieldToIo } from "node:timers/promises";
import { expect, it } from "vitest";
import {
AnalysisCancelledError,
AnalysisOutputError,
} from "../../../src/domain/analysisErrorCore.js";
import { JavaScriptAnalysisWorker } from "../../../src/javascript/analysis/JavaScriptAnalysisWorker.js";
import {
javaScriptWorkerMessageSchema,
type JavaScriptWorkerMessage,
} from "../../../src/javascript/analysis/JavaScriptAnalysisWorkerProtocol.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import type { JavaScriptArtifactFile } from "../../../src/domain/javascript/javascriptArtifactFiles.js";
const observeWorkerFrames = (
stdout: Readable | null | undefined,
observe: (frame: JavaScriptWorkerMessage, beforeEof: boolean) => void,
): void => {
if (stdout === null || stdout === undefined)
throw new Error("Expected fixture worker stdout pipe");
// The runtime attaches its diagnostic and protocol readers together after
// adopting the launch. Wait for that owner before starting a flowing reader.
const attach = (event: string | symbol): void => {
if (event !== "data") return;
stdout.off("newListener", attach);
createInterface({ input: stdout }).on("line", (line) =>
observe(
javaScriptWorkerMessageSchema.parse(JSON.parse(line)),
!stdout.readableEnded,
),
);
};
stdout.on("newListener", attach);
};
it("preserves buffered startup bytes until the runtime owns stdout", async () => {
const stdout = new PassThrough();
const frame = { kind: "ready", heap_limit_bytes: 1 } as const;
const encoded = JSON.stringify(frame) + "\n";
const observed: JavaScriptWorkerMessage[] = [];
const owned: Buffer[] = [];
observeWorkerFrames(stdout, (message) => observed.push(message));
try {
stdout.write(encoded);
await yieldToIo();
expect(observed).toEqual([]);
stdout.on("data", (chunk: Buffer) => owned.push(chunk));
stdout.end();
await once(stdout, "end");
expect(observed).toEqual([frame]);
expect(Buffer.concat(owned).toString()).toBe(encoded);
} finally {
stdout.destroy();
}
});
const sourceText = "export const observed = 1;";
const file: JavaScriptArtifactFile = {
path: "app.mjs",
@@ -396,10 +446,11 @@ it("keeps a parsed terminal failure primary over startup-close abort", async ()
});
it.each([false, true])(
"admits a valid complete response with static facts before EOF cancellation (%s)",
"admits valid static facts and honors cancellation before terminal admission (%s)",
async (abortAfterTerminal) => {
const controller = new AbortController();
const reason = { requested: "abort after valid terminal frame" };
let abortedBeforeEof = false;
const encodedStatic = JSON.stringify(staticCheckpointFacts);
const worker = new JavaScriptAnalysisWorker(
{ heapMb: 128, timeoutMs: 30_000 },
@@ -411,10 +462,13 @@ it.each([false, true])(
`${ready} const fs=require("node:fs"); const {createHash}=require("node:crypto"); const staticFacts=JSON.parse(${JSON.stringify(encodedStatic)}); let id; require("node:readline").createInterface({input:process.stdin}).on("line", line => { const request=JSON.parse(line); if(request.file){ id=request.id; const text=JSON.stringify(staticFacts); fs.writeFileSync(id+".static.json",text); process.stdout.write(JSON.stringify({kind:"static",id,bytes:Buffer.byteLength(text),sha256:createHash("sha256").update(text).digest("hex")})+"\\n"); } else { process.stdout.write(JSON.stringify({kind:"complete",id,descriptor:null})+"\\n",()=>process.exit(0)); } });`,
],
});
if (abortAfterTerminal)
launched.process.once("close", () =>
queueMicrotask(() => controller.abort(reason)),
);
if (abortAfterTerminal) {
observeWorkerFrames(launched.process.stdout, (frame, beforeEof) => {
if (frame.kind !== "complete") return;
abortedBeforeEof = beforeEof;
controller.abort(reason);
});
}
return launched;
},
);
@@ -426,6 +480,7 @@ it.each([false, true])(
);
expect(controller.signal.aborted).toBe(abortAfterTerminal);
if (abortAfterTerminal) {
expect(abortedBeforeEof).toBe(true);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error.error._tag).toBe("AnalysisCancelledError");
@@ -1076,15 +1131,13 @@ it.each([
...request,
arguments: [
"-e",
`${ready} process.stdin.once("data", chunk => { const id=JSON.parse(String(chunk)).id; process.stdout.write(JSON.stringify({kind:"phase",id,phase:"parse"})+"\\n"); const failure=${JSON.stringify(failure)}; failure.kind="failure"; failure.id=id; setTimeout(() => process.stdout.write(JSON.stringify(failure)+"\\n"),20); setInterval(()=>{},1000); });`,
`${ready} process.stdin.once("data", chunk => { const id=JSON.parse(String(chunk)).id; const phase={kind:"phase",id,phase:"parse"}; const failure={...${JSON.stringify(failure)},kind:"failure",id,message:"fixture failure delivered after caller cancellation"}; process.stdout.write(JSON.stringify(phase)+"\\n"+JSON.stringify(failure)+"\\n"); setInterval(()=>{},1000); });`,
],
});
launched.process.stdout?.on("data", (chunk: Buffer | string) => {
if (String(chunk).includes('"kind":"phase"')) controller.abort(null);
if (
controller.signal.aborted &&
String(chunk).includes('"kind":"failure"')
)
observeWorkerFrames(launched.process.stdout, (frame) => {
// This launcher observer precedes the worker's protocol reader.
if (frame.kind === "phase") controller.abort(null);
if (controller.signal.aborted && frame.kind === "failure")
failureFrameSeenAfterAbort = true;
});
return launched;
@@ -0,0 +1,109 @@
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { expect } from "vitest";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"retains unknown timer delays and unrelated facts through public CLI and MCP",
{ timeout: 60_000 },
async ({ cli }) => {
const root = await createTestTempDirectory("rea-timer-delay-");
const source = [
'export function greet() { return "hello"; }',
"setTimeout(() => greet(), 1e999);",
"setInterval(() => greet(), 1e309);",
"setTimeout(() => greet(), 100);",
"setTimeout(() => greet(), 1e308);",
"setTimeout(() => greet(), Infinity);",
"setImmediate(() => greet());",
].join("\n");
const path = join(root, "main.js");
await writeFile(path, source);
const digest = createHash("sha256").update(source).digest("hex");
const cliResult = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(cliResult.exitCode).toBe(0);
const contract = toolContract("analyze_javascript_application");
const cliEvidence = contract.outputSchema.parse(cliResult.json);
const graph = javascriptApplicationAnalysisResultSchema.parse(
cliEvidence.normalized_result,
).semantic_graph;
const timers = graph.nodes.filter(({ kind }) => kind === "timer");
const pairs = timers.map(({ properties }) => [
properties.method,
properties.delay_milliseconds,
]);
const sorted = (values: unknown[]) =>
values.map((value) => JSON.stringify(value)).sort();
expect(sorted(pairs)).toEqual(
sorted([
["setTimeout", null],
["setInterval", null],
["setTimeout", 100],
["setTimeout", 1e308],
["setTimeout", null],
["setImmediate", null],
]),
);
expect(
graph.nodes.find(
({ kind, label }) => kind === "function" && label === "greet",
)?.identity,
).toMatchObject({ module_path: "main.js", artifact_sha256: digest });
for (const timer of timers) {
expect(Object.hasOwn(timer.properties, "delay_milliseconds")).toBe(true);
expect(timer.identity).toMatchObject({
module_path: "main.js",
artifact_sha256: digest,
});
}
const client = new Client({ name: "timer-delay-boundary", version: "1" });
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
cwd: process.cwd(),
env: { PATH: process.env.PATH ?? "" },
stderr: "pipe",
});
transport.stderr?.on("data", () => undefined);
try {
await client.connect(transport);
const reply = await client.callTool({
name: contract.name,
arguments: { input_path: root },
});
expect(reply.isError).not.toBe(true);
const evidence = contract.outputSchema.parse(reply.structuredContent);
expect(evidence.evidence_id).toBe(cliEvidence.evidence_id);
const text = reply.content.find((item) => item.type === "text");
if (text?.type !== "text") throw new Error("Missing inline Evidence");
expect(
contract.outputSchema.parse(JSON.parse(text.text)).evidence_id,
).toBe(evidence.evidence_id);
const retained = javascriptApplicationAnalysisResultSchema.parse(
evidence.normalized_result,
).semantic_graph;
expect(retained.nodes.filter(({ kind }) => kind === "timer")).toEqual(
timers,
);
expect(
retained.nodes.some(
({ kind, label }) => kind === "function" && label === "greet",
),
).toBe(true);
await expect(client.ping()).resolves.toEqual({});
} finally {
await Promise.all([client.close(), transport.close()]);
}
expect(await readFile(path, "utf8")).toBe(source);
},
);