fix(javascript): preserve selected inputs and completed source evidence

This commit is contained in:
morluto committed 2026-10-26 17:39:29 +08:00
1 parent 3864c7d667
commit 721dd3d1aa
11 files changed
+453 -177

No files matched your search

@@ -10,13 +10,34 @@ import {
ProviderProcessSupervisor,
spawnOwnedProviderProcess,
} from "../../process/ProviderProcess.js";
import { WEB_SOURCE_MAP_LIMITS } from "../../domain/webSourceLocation.js";
import {
WEB_SOURCE_MAP_LIMITS,
type WebSourceMapReport,
} from "../../domain/webSourceLocation.js";
import { traceSourceMap } from "./TraceSourceMap.js";
import {
runSourceMapCommand,
SOURCE_MAP_CODEC_MEMORY_LIMIT_BYTES,
type SourceMapCleanupRetention,
} from "./SourceMapCommand.js";
const report = traceSourceMap(
JSON.stringify({ version: 3, sources: [], names: [], mappings: "" }),
"https://app.test/app.map",
{ line: 1, column: 0 },
);
const completedReport: WebSourceMapReport = {
...report,
runtime:
report.runtime.id === "node-v8"
? { ...report.runtime, v8_heap_limit_bytes: 200 * 1024 * 1024 }
: {
...report.runtime,
process_memory_limit_bytes: SOURCE_MAP_CODEC_MEMORY_LIMIT_BYTES,
},
};
const completedCodec = `process.stdout.write(${JSON.stringify(JSON.stringify({ state: "success", report: completedReport }))})`;
const unexpectedCleanup: SourceMapCleanupRetention = {};
afterEach(async () => {
const owner = unexpectedCleanup.owner;
@@ -114,7 +135,7 @@ it.each([null, { caller: "late source-map cancellation" }])(
launcher: async (options) =>
spawnOwnedProviderProcess({
...options,
arguments: ["-e", 'process.stdout.write("complete")'],
arguments: ["-e", completedCodec],
}),
},
retainedCleanup,
@@ -141,8 +162,8 @@ it.each([null, { caller: "late source-map cancellation" }])(
);
it("returns completed codec output after successful cleanup", async () => {
const result = await runChild(undefined, 'process.stdout.write("complete")');
expect(result).toEqual({ ok: true, value: "complete" });
const result = await runChild(undefined, completedCodec);
expect(result).toEqual({ ok: true, value: completedReport });
});
it("preserves exact caller reason when cancellation precedes process exit", async () => {
+14 -5
View File
@@ -14,13 +14,15 @@ import {
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import { err, ok, type Result } from "../../domain/result.js";
import { err, type Result } from "../../domain/result.js";
import { noRuntimeOverrideSentence } from "../../domain/browserDeadline.js";
import {
DEFAULT_WEB_SOURCE_MAP_DECODE_TIMEOUT_MS,
WEB_SOURCE_MAP_LIMITS,
webSourceMapDecodeTimeoutRecovery,
type WebSourceMapReport,
} from "../../domain/webSourceLocation.js";
import { parseSourceMapReply } from "./SourceMapReply.js";
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
import {
RuntimeControlUnavailableError,
@@ -99,7 +101,7 @@ export class SourceMapCleanupFailure extends ProviderCleanupError {
}
}
/** Run a trusted codec command and release its process/root before returning output. */
/** Interpret a trusted codec reply, then release its process and private root. */
export const runSourceMapCommand = async (
request: string,
path: string,
@@ -107,7 +109,7 @@ export const runSourceMapCommand = async (
dependencies: SourceMapDecoderDependencies,
retainedCleanup: SourceMapCleanupRetention,
decodeTimeoutMs: number = DEFAULT_WEB_SOURCE_MAP_DECODE_TIMEOUT_MS,
): Promise<Result<string, AnalysisError>> => {
): Promise<Result<WebSourceMapReport, AnalysisError>> => {
try {
await (dependencies.prepareOwnership ?? prepareProcessOwnershipInspection)(
options?.signal,
@@ -135,10 +137,14 @@ export const runSourceMapCommand = async (
options?.signal,
);
const command = new OwnedCodec(path, dependencies, deadline, decodeTimeoutMs);
let result: Result<string, AnalysisError>;
let result: Result<WebSourceMapReport, AnalysisError>;
try {
await command.start(request);
result = ok(await command.collect());
result = parseSourceMapReply(
await command.collect(),
path,
SOURCE_MAP_CODEC_MEMORY_LIMIT_BYTES,
);
} catch (cause: unknown) {
result = err(command.failure(cause));
} finally {
@@ -146,15 +152,18 @@ export const runSourceMapCommand = async (
deadline.dispose();
}
const cleanup = await command.close();
const observation = result.ok ? result.value : undefined;
const completed =
result.ok && options?.signal?.aborted
? err(
new AnalysisCancelledError(OPERATION, {
cause: options.signal.reason,
partialObservation: observation,
}),
)
: result;
if (cleanup === undefined) return completed;
if (observation !== undefined) cleanup.retainPartialObservation(observation);
retainedCleanup.owner = command;
return completed.ok
? err(cleanup)
+3 -91
View File
@@ -3,25 +3,18 @@ import type { WebSourceMapPort } from "../../application/WebSourceLocationPorts.
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
import { err, ok, type Result } from "../../domain/result.js";
import { javaScriptRuntime } from "../../domain/runtimeVersion.js";
import { err, type Result } from "../../domain/result.js";
import { noRuntimeOverrideSentence } from "../../domain/browserDeadline.js";
import {
DEFAULT_WEB_SOURCE_MAP_DECODE_TIMEOUT_MS,
WEB_SOURCE_MAP_LIMITS,
type WebSourceMapReport,
} from "../../domain/webSourceLocation.js";
import { sourceMapCodecInputSchema } from "./SourceMapCodecProtocol.js";
import {
sourceMapCodecInputSchema,
sourceMapCodecReplySchema,
} from "./SourceMapCodecProtocol.js";
import {
SOURCE_MAP_CODEC_MEMORY_LIMIT_BYTES,
runSourceMapCommand,
type SourceMapCleanupOwner,
type SourceMapCleanupRetention,
@@ -125,36 +118,7 @@ export class SourceMapDecoder implements WebSourceMapPort {
);
if (retainedCleanup.owner !== undefined)
this.#pendingCleanup = retainedCleanup.owner;
if (!response.ok) return response;
let value: unknown;
try {
value = JSON.parse(response.value);
} catch (cause: unknown) {
return err(
new AnalysisOutputError(
OPERATION,
`Malformed codec JSON reply: ${cause instanceof Error ? cause.message : String(cause)}`,
),
);
}
const reply = sourceMapCodecReplySchema.safeParse(value);
if (!reply.success)
return err(
new AnalysisOutputError(
OPERATION,
`Malformed codec reply: ${reply.error.message}`,
),
);
if (options?.signal?.aborted)
return err(
new AnalysisCancelledError(OPERATION, { cause: options.signal.reason }),
);
if (reply.data.state === "failure")
return codecFailure(input.path, reply.data.reason, reply.data.message);
const runtimeFailure = codecRuntimeFailure(reply.data.report.runtime);
return runtimeFailure === undefined
? ok(reply.data.report)
: err(new AnalysisOutputError(OPERATION, runtimeFailure));
return response;
}
async close(): Promise<void> {
@@ -180,55 +144,3 @@ export class SourceMapDecoder implements WebSourceMapPort {
return undefined;
}
}
/**
* The codec runs on this process's executable. Only a V8 report carries a heap
* limit; a Bun report must name the process limit its launcher enforced.
*/
const codecRuntimeFailure = (
runtime: WebSourceMapReport["runtime"],
): string | undefined => {
if (
runtime.id !==
(javaScriptRuntime(process.versions).id === "bun" ? "bun" : "node-v8")
)
return `Codec reported runtime ${runtime.id}, not the runtime that launched it.`;
if (
runtime.id === "node-v8" &&
runtime.v8_heap_limit_bytes > 256 * 1024 * 1024
)
return "Codec reported a V8 heap limit exceeding its independent process budget.";
if (
runtime.id === "bun" &&
runtime.process_memory_limit_bytes !== SOURCE_MAP_CODEC_MEMORY_LIMIT_BYTES
)
return "Codec reported a process memory limit other than the one its launcher enforced.";
return undefined;
};
const codecFailure = (
path: string,
reason: "format" | "unsupported" | "limit",
detail: string,
): Result<never, AnalysisError> =>
err(
reason === "limit"
? new ArtifactOperationError(
OPERATION,
"limit",
undefined,
`${path}: ${detail}`,
)
: reason === "unsupported"
? new AnalysisCapabilityUnavailableError(
"source-map-decoder",
OPERATION,
"unsupported_source_map_profile",
{ userMessage: `${path}: ${detail}` },
)
: new AnalysisInputError(OPERATION, undefined, [
{
path: ["source_map", "path"],
reason: "invalid_format",
message: `${path}: ${detail}`,
},
]),
);
+101
View File
@@ -0,0 +1,101 @@
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
import { err, ok, type Result } from "../../domain/result.js";
import { javaScriptRuntime } from "../../domain/runtimeVersion.js";
import type { WebSourceMapReport } from "../../domain/webSourceLocation.js";
import { sourceMapCodecReplySchema } from "./SourceMapCodecProtocol.js";
const OPERATION = "trace_web_source_location";
/** Interpret the complete codec reply before its command owner finalizes. */
export const parseSourceMapReply = (
text: string,
path: string,
processMemoryLimitBytes: number | null,
): Result<WebSourceMapReport, AnalysisError> => {
let value: unknown;
try {
value = JSON.parse(text);
} catch (cause: unknown) {
return err(
new AnalysisOutputError(
OPERATION,
`Malformed codec JSON reply: ${cause instanceof Error ? cause.message : String(cause)}`,
),
);
}
const reply = sourceMapCodecReplySchema.safeParse(value);
if (!reply.success)
return err(
new AnalysisOutputError(
OPERATION,
`Malformed codec reply: ${reply.error.message}`,
),
);
if (reply.data.state === "failure")
return codecFailure(path, reply.data.reason, reply.data.message);
const runtimeFailure = codecRuntimeFailure(
reply.data.report.runtime,
processMemoryLimitBytes,
);
return runtimeFailure === undefined
? ok(reply.data.report)
: err(new AnalysisOutputError(OPERATION, runtimeFailure));
};
/** Only the launched Node runtime's V8 heap, or Bun's process limit, is admitted. */
const codecRuntimeFailure = (
runtime: WebSourceMapReport["runtime"],
processMemoryLimitBytes: number | null,
): string | undefined => {
if (
runtime.id !==
(javaScriptRuntime(process.versions).id === "bun" ? "bun" : "node-v8")
)
return `Codec reported runtime ${runtime.id}, not the runtime that launched it.`;
if (
runtime.id === "node-v8" &&
runtime.v8_heap_limit_bytes > 256 * 1024 * 1024
)
return "Codec reported a V8 heap limit exceeding its independent process budget.";
if (
runtime.id === "bun" &&
runtime.process_memory_limit_bytes !== processMemoryLimitBytes
)
return "Codec reported a process memory limit other than the one its launcher enforced.";
return undefined;
};
const codecFailure = (
path: string,
reason: "format" | "unsupported" | "limit",
detail: string,
): Result<never, AnalysisError> =>
err(
reason === "limit"
? new ArtifactOperationError(
OPERATION,
"limit",
undefined,
`${path}: ${detail}`,
)
: reason === "unsupported"
? new AnalysisCapabilityUnavailableError(
"source-map-decoder",
OPERATION,
"unsupported_source_map_profile",
{ userMessage: `${path}: ${detail}` },
)
: new AnalysisInputError(OPERATION, undefined, [
{
path: ["source_map", "path"],
reason: "invalid_format",
message: `${path}: ${detail}`,
},
]),
);