test(source-maps): consolidate decoder and evidence coverage

This commit is contained in:
morluto committed 2026-11-17 21:02:58 -05:00
1 parent c77d4261a1
commit e415ba6673
25 files changed
+1288 -2664

No files matched your search

+288 -143
View File
@@ -1,9 +1,10 @@
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import { access } from "node:fs/promises";
import { expect, it, vi } from "vitest";
import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js";
import { PrivateRuntimeRootUnavailableError } from "../../../src/domain/privateRuntimeRootUnavailableError.js";
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { webSourceMapReportSchema } from "../../../src/domain/webSourceLocation.js";
import { SourceMapDecoder } from "../../../src/javascript/sourceMaps/SourceMapDecoder.js";
import type { SourceMapDecoderDependencies } from "../../../src/javascript/sourceMaps/SourceMapCommand.js";
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
@@ -49,32 +50,151 @@ const input = {
position: webSourceLocationArgs.generated_position,
};
it("starts the codec deadline after cold ownership preparation", async () => {
vi.useFakeTimers();
try {
let prepared = false;
const responsePromise = realDecoder({
prepareOwnership: async (signal) => {
await vi.advanceTimersByTimeAsync(20_001);
expect(signal?.aborted).not.toBe(true);
prepared = true;
},
launcher: (options) => {
expect(prepared).toBe(true);
expect(options.signal?.aborted).not.toBe(true);
return Promise.reject(new Error("observed launch after preparation"));
},
}).trace(input);
const response = await responsePromise;
if (response.ok) throw new Error("expected launch failure");
expect(response.error).toMatchObject({
diagnostics: { error_message: "observed launch after preparation" },
it.each([
{ name: "null", reason: null },
{
name: "an opaque cleanup error",
reason: new ProviderCleanupError("caller", ["caller-owned-resource"], {}),
},
])(
"preserves cancellation during ownership preparation with $name",
async ({ reason }) => {
const controller = new AbortController();
const createRuntime = vi.fn(async () => {
throw new Error("Cancelled preparation must not acquire a runtime");
});
} finally {
vi.useRealTimers();
}
const launcher = vi.fn(async () => {
throw new Error("Cancelled preparation must not launch a codec");
});
const decoder = realDecoder({
prepareOwnership: async (signal) => {
controller.abort(reason);
signal?.throwIfAborted();
},
createRuntime,
launcher,
});
const result = await decoder.trace(input, { signal: controller.signal });
if (result.ok) throw new Error("Expected preparation cancellation");
expect(result.error).toMatchObject({
_tag: "AnalysisCancelledError",
cleanupIncomplete: false,
cleanupResources: [],
});
expect(result.error.cause).toBe(reason);
await decoder.close();
if (reason instanceof ProviderCleanupError) {
expect(reason.cleanupIncomplete).toBe(true);
expect(reason.cleanupResources).toEqual(["caller-owned-resource"]);
}
expect(createRuntime).not.toHaveBeenCalled();
expect(launcher).not.toHaveBeenCalled();
},
);
it("retains diagnostics for an unknown ownership preparation failure", async () => {
const cause = new Error("unexpected ownership failure");
const createRuntime = vi.fn(async () => {
throw new Error("Failed preparation must not acquire a runtime");
});
const decoder = realDecoder({
prepareOwnership: async () => {
throw cause;
},
createRuntime,
});
const result = await decoder.trace(input);
if (result.ok) throw new Error("Expected preparation failure");
expect(result.error).toMatchObject({
_tag: "ProviderAdapterError",
cleanupIncomplete: false,
diagnostics: {
map_path: input.path,
error_message: cause.message,
phase: "process_ownership_preparation",
},
});
expect(result.error.cause).toBe(cause);
expect(createRuntime).not.toHaveBeenCalled();
});
it.each([
{ retryable: true, category: "unavailable" },
{ retryable: false, category: "unsupported_provider" },
])(
"preserves private-runtime rejection as $category",
async ({ retryable, category }) => {
const reason = "Native runtime self-test failed with a sharing violation";
const launcher = vi.fn(async () => {
throw new Error("A refused runtime must not launch a codec");
});
const decoder = realDecoder({
prepareOwnership: async () => {},
createRuntime: async () => {
throw new PrivateRuntimeRootUnavailableError(reason, { retryable });
},
launcher,
});
const result = await decoder.trace(input);
if (result.ok) throw new Error("Expected runtime refusal");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "capability_unavailable",
category,
retryable,
details: {
provider_id: "source-map-decoder",
operation: "trace_web_source_location",
reason,
},
});
expect(result.error.cleanupIncomplete).toBe(false);
expect(launcher).not.toHaveBeenCalled();
},
);
it.each([
{ name: "default", selected: undefined, expectedMs: 20_000 },
{ name: "selected", selected: 250, expectedMs: 250 },
])(
"starts the $name codec deadline after ownership preparation",
async ({ selected, expectedMs }) => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });
let path: string | undefined;
try {
const response = await realDecoder({
prepareOwnership: async () => {
await vi.advanceTimersByTimeAsync(20_001);
},
createRuntime: async () => {
const root = await PrivateRuntimeRoot.create();
path = root.path;
return root;
},
launcher: async ({ signal }) => {
await vi.advanceTimersByTimeAsync(expectedMs - 1);
expect(signal?.aborted).toBe(false);
await vi.advanceTimersByTimeAsync(1);
expect(signal?.aborted).toBe(true);
throw new Error("launcher settled after deadline");
},
}).trace({
...input,
...(selected === undefined ? {} : { decodeTimeoutMs: selected }),
});
if (response.ok) throw new Error("expected decode deadline");
expect(response.error).toMatchObject({
_tag: "AnalysisTimeoutError",
userMessage: expect.stringContaining(String(expectedMs)),
});
expect(response.error.userMessage).toContain("decode_timeout_ms");
if (path === undefined) throw new Error("runtime not acquired");
await expect(access(path)).rejects.toMatchObject({ code: "ENOENT" });
} finally {
vi.useRealTimers();
}
},
);
it.each([
{ heap: undefined, effectiveHeap: 192 },
{ heap: 384, effectiveHeap: 384 },
@@ -101,7 +221,10 @@ it.each([
if (!response.ok) throw response.error;
expect(response.value).toMatchObject({
engine: { id: "jridgewell-trace-mapping", version: "0.3.31" },
matches: [{ content: { text: "original" } }],
source_map_sha256: fixture.sourceMap.file.sha256,
url_context: input.url,
lookup: { requested: input.position },
matches: [{ state: "mapped", content: { text: "original" } }],
});
if (process.versions.bun === undefined) {
expect(response.value.runtime).toMatchObject({
@@ -135,7 +258,6 @@ it.each([
);
it.each([
{ cancel: false, denyCleanup: false },
{ cancel: true, denyCleanup: false },
{ cancel: false, denyCleanup: true },
{ cancel: true, denyCleanup: true },
@@ -145,7 +267,7 @@ it.each([
const controller = new AbortController();
const reason = { phase: "source-map root finalization" };
let path: string | undefined;
let cleanupAttempts = 0;
let denyNextClose = denyCleanup;
const decoder = realDecoder({
createRuntime: async () => {
const root = await PrivateRuntimeRoot.create();
@@ -153,10 +275,11 @@ it.each([
return {
path: root.path,
close: async () => {
cleanupAttempts += 1;
if (cancel) controller.abort(reason);
if (denyCleanup && cleanupAttempts === 1)
if (denyNextClose) {
denyNextClose = false;
throw new Error("controlled source-map cleanup denial");
}
await root.close();
},
};
@@ -166,39 +289,33 @@ it.each([
const response = await decoder.trace(input, {
signal: controller.signal,
});
expect(response.ok).toBe(!cancel && !denyCleanup);
const report = webSourceMapReportSchema.parse(
response.ok ? response.value : response.error.partialObservation,
);
if (response.ok) throw new Error("Expected interrupted finalization");
const { error } = response;
const report = error.partialObservation;
expect(report).toMatchObject({
source_map_sha256: fixture.sourceMap.file.sha256,
url_context: input.url,
lookup: { requested: input.position },
matches: [{ state: "mapped", content: { text: "original" } }],
});
expect(error).toMatchObject({ operation: "trace_web_source_location" });
expect(projectAnalysisError(error)).toMatchObject({
details: { partial_observation: report },
});
if (cancel) {
const primary = error.cleanupPrimary ?? error;
expect(primary._tag).toBe("AnalysisCancelledError");
expect(primary.cause).toBe(reason);
}
if (path === undefined) throw new Error("runtime not acquired");
if (!response.ok) {
expect(response.error).toMatchObject({
operation: "trace_web_source_location",
});
expect(projectAnalysisError(response.error)).toMatchObject({
details: { partial_observation: report },
});
if (cancel) {
const primary = response.error.cleanupPrimary ?? response.error;
expect(primary._tag).toBe("AnalysisCancelledError");
expect(primary.cause).toBe(reason);
}
expect(response.error.cleanupIncomplete).toBe(denyCleanup);
if (denyCleanup) {
expect(response.error.cleanupResources).toEqual([path]);
await expect(access(path)).resolves.toBeUndefined();
await decoder.close();
expect(cleanupAttempts).toBe(2);
expect(response.error.cleanupIncomplete).toBe(false);
expect(response.error.cleanupResources).toEqual([]);
expect(response.error.partialObservation).toEqual(report);
}
expect(error.cleanupIncomplete).toBe(denyCleanup);
if (denyCleanup) {
expect(error.cleanupResources).toEqual([path]);
await expect(access(path)).resolves.toBeUndefined();
await decoder.close();
expect(error.cleanupIncomplete).toBe(false);
expect(error.cleanupResources).toEqual([]);
expect(error.partialObservation).toEqual(report);
}
await expect(access(path)).rejects.toMatchObject({ code: "ENOENT" });
} finally {
@@ -212,17 +329,20 @@ it.each([false, true])(
async (denyCleanup) => {
const controller = new AbortController();
const reason = new Error("cancel after codec refusal");
let cleanupAttempts = 0;
let path: string | undefined;
let denyNextClose = denyCleanup;
const decoder = realDecoder({
createRuntime: async () => {
const root = await PrivateRuntimeRoot.create();
path = root.path;
return {
path: root.path,
close: async () => {
cleanupAttempts += 1;
controller.abort(reason);
if (denyCleanup && cleanupAttempts === 1)
if (denyNextClose) {
denyNextClose = false;
throw new Error("controlled refusal cleanup denial");
}
await root.close();
},
};
@@ -234,15 +354,28 @@ it.each([false, true])(
{ signal: controller.signal },
);
if (response.ok) throw new Error("Expected malformed-map refusal");
expect(controller.signal.reason).toBe(reason);
expect(response.error.cleanupPrimary ?? response.error).toBeInstanceOf(
AnalysisInputError,
const { error } = response;
const primary = error.cleanupPrimary ?? error;
expect(primary).toMatchObject({
_tag: "AnalysisInputError",
operation: "trace_web_source_location",
issues: [{ reason: "invalid_format" }],
});
const cancellation = primary.secondaryFailures.find(
({ _tag }) => _tag === "AnalysisCancelledError",
);
expect(response.error.partialObservation).toBeUndefined();
expect(response.error.cleanupIncomplete).toBe(denyCleanup);
await decoder.close();
expect(response.error.cleanupIncomplete).toBe(false);
expect(cleanupAttempts).toBe(denyCleanup ? 2 : 1);
expect(cancellation?.cause).toBe(reason);
expect(error.partialObservation).toBeUndefined();
if (path === undefined) throw new Error("runtime not acquired");
expect(error.cleanupIncomplete).toBe(denyCleanup);
if (denyCleanup) {
expect(error.cleanupResources).toEqual([path]);
await expect(access(path)).resolves.toBeUndefined();
await decoder.close();
expect(error.cleanupIncomplete).toBe(false);
expect(error.cleanupResources).toEqual([]);
}
await expect(access(path)).rejects.toMatchObject({ code: "ENOENT" });
} finally {
await decoder.close();
}
@@ -250,14 +383,6 @@ it.each([false, true])(
);
it.each([
{
failure: "malformed JSON",
text: "{",
error: {
_tag: "AnalysisInputError",
issues: [{ reason: "invalid_format" }],
},
},
{
failure: "external section",
text: JSON.stringify({
@@ -279,7 +404,12 @@ it.each([
failure: "malformed embedded map before row admission",
text: JSON.stringify({
version: 3,
sections: [{ offset: { line: 1000000000, column: 0 }, map: {} }],
sections: [
{
offset: { line: 1000000000, column: 0 },
map: { version: "3", sections: [] },
},
],
}),
error: {
_tag: "AnalysisInputError",
@@ -308,6 +438,49 @@ it.each([
detail: expect.stringContaining("generated-row decoder budget"),
},
},
{
failure: "invalid section list with regular-map fields",
text: JSON.stringify({
version: 3,
sections: null,
sources: ["ignored.ts"],
mappings: "AAAA",
}),
error: {
_tag: "AnalysisInputError",
issues: [
{
reason: "invalid_format",
message: expect.stringContaining("sections"),
},
],
},
},
{
failure: "overlapping indexed mappings",
text: JSON.stringify({
version: 3,
sections: [
{
offset: { line: 0, column: 0 },
map: { version: 3, sources: ["a.js"], mappings: "AAAA,EAAA" },
},
{
offset: { line: 0, column: 1 },
map: { version: 3, sources: ["b.js"], mappings: "AAAA" },
},
],
}),
error: {
_tag: "AnalysisInputError",
issues: [
{
reason: "invalid_format",
message: expect.stringContaining("overlap"),
},
],
},
},
])("preserves actual producer failures: $failure", async ({ text, error }) => {
const response = await realDecoder().trace({ ...input, text });
if (response.ok) throw new Error("expected failed map");
@@ -317,47 +490,8 @@ it.each([
});
});
it("keeps indexed section overlap typed as a malformed source map", async () => {
const text = JSON.stringify({
version: 3,
sections: [
{
offset: { line: 0, column: 0 },
map: {
version: 3,
sources: ["a.js"],
sourcesContent: ["x();"],
names: [],
mappings: "AAAA,EAAA",
},
},
{
offset: { line: 0, column: 1 },
map: {
version: 3,
sources: ["b.js"],
sourcesContent: ["y();"],
names: [],
mappings: "AAAA",
},
},
],
});
const response = await realDecoder().trace({ ...input, text });
if (response.ok) throw new Error("expected overlapping map rejection");
expect(response.error).toBeInstanceOf(AnalysisInputError);
if (!(response.error instanceof AnalysisInputError))
throw new Error("expected malformed source-map input error");
expect(response.error.issues).toEqual(
expect.arrayContaining([
expect.objectContaining({
reason: "invalid_format",
message: expect.stringContaining("overlap"),
}),
]),
);
});
it("cancels a real owned process and removes the runtime request", async () => {
const reason = { caller: "cancel active codec" };
const controller = new AbortController();
let path: string | undefined;
const response = await realDecoder({
@@ -375,46 +509,57 @@ it("cancels a real owned process and removes the runtime request", async () => {
],
});
await waitForProviderProcessReady(child.process);
setImmediate(() => controller.abort());
setImmediate(() => controller.abort(reason));
return child;
},
}).trace(input, { signal: controller.signal });
if (response.ok) throw new Error("expected cancellation");
expect(response.error._tag).toBe("AnalysisCancelledError");
expect(response.error.cause).toBe(reason);
if (path === undefined) throw new Error("runtime not acquired");
await expect(access(path)).rejects.toMatchObject({ code: "ENOENT" });
});
it("retains final diagnostic bytes for an actual failed codec process", async () => {
const response = await realDecoder({
launcher: (options) =>
spawnOwnedProviderProcess({
...options,
arguments: [
"-e",
'process.stderr.write("final diagnostic"); process.exitCode = 7',
],
}),
}).trace(input);
if (response.ok) throw new Error("expected exit failure");
expect(response.error).toMatchObject({
diagnostics: { exit_code: 7, stderr: "final diagnostic" },
});
});
it("reports complete evidence amplification as a resource failure before serializing an oversized reply", async () => {
const text = JSON.stringify({
it("returns all point matches when they fit and reports output exhaustion otherwise", async () => {
const embedded = "a".repeat(1_800);
const text = `\uFEFF)]}'transport prefix\r${JSON.stringify({
version: 3,
sources: ["large.ts"],
sourcesContent: ["a".repeat(600000)],
sources: ["original.ts"],
sourcesContent: [embedded],
names: [],
mappings: Array.from({ length: 60 }, () => "AAAA").join(","),
});
const response = await realDecoder().trace({ ...input, text });
if (response.ok) throw new Error("expected complete-evidence budget failure");
expect(response.error).toMatchObject({
mappings: "AAAA,AAAC,AAAC,AAAC",
})}`;
const trace = (outputBytes: number) =>
realDecoder().trace({
...input,
text,
limits: { output_bytes: outputBytes },
});
const complete = await trace(14_000);
if (!complete.ok) throw complete.error;
expect(complete.value.source_map_sha256).toBe(
createHash("sha256").update(text).digest("hex"),
);
expect(complete.value.matches).toMatchObject(
[0, 1, 2, 3].map((column) => ({
reported_source: "original.ts",
original_position: { line: 1, column },
content: { state: "embedded", text: embedded },
})),
);
const budget = 5_500;
expect(Buffer.byteLength(JSON.stringify(complete.value))).toBeGreaterThan(
budget,
);
const limited = await trace(budget);
if (limited.ok) throw new Error("expected complete-evidence budget failure");
expect(limited.error).toMatchObject({
_tag: "ArtifactOperationError",
reason: "limit",
detail: expect.stringContaining("no partial"),
detail: expect.stringContaining("source_map_limits.output_bytes is 5500"),
});
expect(limited.error.partialObservation).toBeUndefined();
});
it("rejects a malformed actual subprocess reply", async () => {
const response = await realDecoder({