fix(source-maps): report details.limit for source_map_limits refusals (#14797)

Share source_map_limits bounds through a domain-owned SOURCE_MAP_BUDGETS table and attach details.limit across local source-map read, decoder admission, codec reply, and memory/output limit refusals (Refs #14234).

Co-authored-by: Vincent Koc <vincentkoc@ieee.org>
This commit is contained in:
RRFZandVincent Koc authored and GitHub committed 2026-11-27 10:01:44 +08:00
1 parent cd744b1bfb
commit 3eb030ccb4
15 files changed
+550 -68

No files matched your search

@@ -6,11 +6,13 @@ import {
import { traceSourceMap } from "./TraceSourceMap.js";
import {
isSourceMapFailure,
isSourceMapLimit,
SOURCE_MAP_FORMAT,
sourceMapLimitFailure,
} from "../../domain/sourceMapFormat.js";
import { malformedInput } from "../../domain/parseFailure.js";
import {
codecSourceMapLimitFieldSchema,
sourceMapCodecInputSchema,
sourceMapCodecReplySchema,
} from "./SourceMapCodecProtocol.js";
@@ -63,6 +65,9 @@ const execute = async (): Promise<string> => {
)
)
throw cause;
const parsedLimit = isSourceMapLimit(cause)
? codecSourceMapLimitFieldSchema.safeParse(cause.failure.limit.name)
: undefined;
return JSON.stringify({
state: "failure",
reason:
@@ -72,6 +77,14 @@ const execute = async (): Promise<string> => {
? "malformed"
: cause.kind,
message: cause.message,
...(parsedLimit?.success && isSourceMapLimit(cause)
? {
limit: {
field: parsedLimit.data,
maximum: cause.failure.limit.maximum,
},
}
: {}),
});
}
};
@@ -1,9 +1,42 @@
import { z } from "zod";
import { SOURCE_MAP_BUDGETS } from "../../domain/sourceMapLimits.js";
import {
webSourceMapReportSchema,
webSourcePositionSchema,
} from "../../domain/webSourceLocation.js";
/** Limits that the isolated local source-map codec can raise on its own. */
export const CODEC_SOURCE_MAP_LIMIT_FIELDS = [
"map_bytes",
"output_bytes",
"decoded_rows",
"decoded_segments",
"decoded_records",
"section_depth",
] as const;
export type CodecSourceMapLimitField =
(typeof CODEC_SOURCE_MAP_LIMIT_FIELDS)[number];
export const codecSourceMapLimitFieldSchema = z.enum(
CODEC_SOURCE_MAP_LIMIT_FIELDS,
);
const codecFailureLimitSchema = z
.strictObject({
field: codecSourceMapLimitFieldSchema,
maximum: z.number().int(),
})
.superRefine((limit, context) => {
const budget = SOURCE_MAP_BUDGETS[limit.field];
if (limit.maximum < budget.minimum || limit.maximum > budget.maximum)
context.addIssue({
code: "custom",
path: ["maximum"],
message: `Codec reported ${limit.field} maximum ${String(limit.maximum)} outside ${String(budget.minimum)}..${String(budget.maximum)}.`,
});
});
/** Trusted codec process input; captured application code is never evaluated. */
export const sourceMapCodecInputSchema = z.strictObject({
text: z.string(),
@@ -12,14 +45,20 @@ export const sourceMapCodecInputSchema = z.strictObject({
});
/** Codec success or a specific producer/resource constraint. */
export const sourceMapCodecReplySchema = z.discriminatedUnion("state", [
export const sourceMapCodecReplySchema = z.union([
z.strictObject({
state: z.literal("success"),
report: webSourceMapReportSchema,
}),
z.strictObject({
state: z.literal("failure"),
reason: z.enum(["malformed", "unsupported", "limit"]),
reason: z.literal("limit"),
message: z.string(),
limit: codecFailureLimitSchema.exactOptional(),
}),
z.strictObject({
state: z.literal("failure"),
reason: z.enum(["malformed", "unsupported"]),
message: z.string(),
}),
]);
@@ -8,6 +8,7 @@ import {
AnalysisCancelledError,
AnalysisResourceConstraintError,
} from "../../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
import {
createSystemProcessOwnershipHost,
@@ -322,6 +323,68 @@ it("retains a physical process admission error alongside cancellation", async ()
expect(result.error.secondaryFailures[0]?.cause).toBe(reason);
});
it("reports details.limit and adjustable_budget refusal when the codec reaches codec_heap_mib", async () => {
const result = await runSourceMapCommand(
"{}",
"/probe/source.map",
undefined,
{
prepareOwnership: async () => {},
launcher: async (options) => {
const spawned = await spawnOwnedProviderProcess({
...options,
arguments: [
"-e",
'process.stderr.write("memory limit reached", () => process.exit(3))',
],
});
Object.defineProperty(spawned.process, "memoryLimitReached", {
get: () => spawned.process.exitCode !== null,
});
return spawned;
},
},
unexpectedCleanup,
);
if (result.ok) throw new Error("expected memory-limit refusal");
if (!(result.error instanceof AnalysisResourceConstraintError))
throw new Error("expected AnalysisResourceConstraintError");
expect(result.error.remediationAction).toBeUndefined();
expect(result.error).toMatchObject({
resource: "memory",
limit: {
control_kind: "parameter",
parameter: "source_map_limits.codec_heap_mib",
effective_value: 192,
unit: "MiB",
minimum: 128,
maximum: 16384,
default_value: 192,
applies_at: "next_call",
},
});
const projected = projectAnalysisError(result.error);
expect(projected).toMatchObject({
code: "resource_constraint",
details: {
limit: result.error.limit,
refusal: {
kind: "adjustable_budget",
operation: "trace_web_source_location",
control: "source_map_limits.codec_heap_mib",
effective_value: 192,
unit: "MiB",
range: { minimum: 128, maximum: 16384 },
default_value: 192,
},
},
});
expect(projected.remediation?.action).toContain(
"source_map_limits.codec_heap_mib",
);
expect(projected.remediation?.action).toContain("128..16384 MiB");
});
it.each([
"distinct reason",
"shared admission error",
+10 -4
View File
@@ -1,5 +1,6 @@
import {
WEB_SOURCE_MAP_LIMITS,
sourceMapBudgetLimit,
sourceMapLimitSelection,
sourceMapLimitRecovery,
type SourceMapLimits,
@@ -559,6 +560,14 @@ class OwnedCodec implements SourceMapCleanupOwner {
? "Codec output exceeds its complete-evidence budget."
: "Codec diagnostic output exceeds its 1048576-byte allowance.",
{
...(stream === "stdout"
? {
limit: sourceMapBudgetLimit(
"output_bytes",
this.limits.outputBytes,
),
}
: {}),
remediationAction:
stream === "stdout"
? sourceMapLimitRecovery("output_bytes", this.limits.outputBytes)
@@ -602,6 +611,7 @@ class OwnedCodec implements SourceMapCleanupOwner {
),
},
{
limit: sourceMapBudgetLimit("codec_heap_mib", this.limits.codecHeapMiB),
capturedOutput: {
stdout: "",
stderr: snapshot.stderr.text,
@@ -609,10 +619,6 @@ class OwnedCodec implements SourceMapCleanupOwner {
snapshot.diagnosticTruncated === true ||
!(this.#supervisor?.observedOutputClose() ?? false),
},
remediationAction: sourceMapLimitRecovery(
"codec_heap_mib",
this.limits.codecHeapMiB,
),
},
);
}
@@ -10,6 +10,7 @@ import {
SourceMapCleanupFailure,
type SourceMapDecoderDependencies,
} from "./SourceMapCommand.js";
import { parseSourceMapReply } from "./SourceMapReply.js";
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
import { assertProcessOwnershipInspectionActive } from "../../process/ProcessInspectionCancellation.js";
import { spawnOwnedProviderProcess } from "../../process/ProviderProcess.js";
@@ -471,3 +472,178 @@ it("does not claim an opaque caller reason's Darwin cleanup owner", async () =>
await decoder.close();
expect(ownerClosed).toBe(false);
});
it("reports details.limit for pre-spawn map_bytes, output_bytes, codec stdout output_bytes, and codec reply limits", async () => {
const decoder = new SourceMapDecoder();
try {
const mapBytesRefusal = await decoder.trace({
...input,
limits: { map_bytes: 16 },
});
if (mapBytesRefusal.ok) throw new Error("expected map_bytes refusal");
const mapProjected = projectAnalysisError(mapBytesRefusal.error);
expect(mapProjected.details?.limit).toEqual({
control_kind: "parameter",
parameter: "source_map_limits.map_bytes",
effective_value: 16,
unit: "bytes",
minimum: 1,
maximum: 536_870_887,
default_value: 8_388_608,
applies_at: "next_call",
required_value: Buffer.byteLength(input.text),
});
const outputBytesRefusal = await decoder.trace({
...input,
limits: { output_bytes: 16 },
});
if (outputBytesRefusal.ok) throw new Error("expected output_bytes refusal");
const outputProjected = projectAnalysisError(outputBytesRefusal.error);
expect(outputProjected.details?.limit).toEqual({
control_kind: "parameter",
parameter: "source_map_limits.output_bytes",
effective_value: 16,
unit: "bytes",
minimum: 1,
maximum: 536_870_887,
default_value: 33_554_432,
applies_at: "next_call",
});
expect(outputProjected.details?.limit).not.toHaveProperty("required_value");
} finally {
await decoder.close();
}
const stdoutDecoder = new SourceMapDecoder({
prepareOwnership: async () => {},
launcher: (options) =>
spawnOwnedProviderProcess({
...options,
arguments: ["-e", 'process.stdout.write("x".repeat(4096))'],
}),
});
try {
const stdoutRefusal = await stdoutDecoder.trace({
...input,
limits: { output_bytes: 1024 },
});
if (stdoutRefusal.ok)
throw new Error("expected stdout output_bytes refusal");
expect(stdoutRefusal.error._tag).toBe("AnalysisOutputError");
expect(projectAnalysisError(stdoutRefusal.error).details?.limit).toEqual({
control_kind: "parameter",
parameter: "source_map_limits.output_bytes",
effective_value: 1024,
unit: "bytes",
minimum: 1,
maximum: 536_870_887,
default_value: 33_554_432,
applies_at: "next_call",
});
} finally {
await stdoutDecoder.close();
}
const stderrDecoder = new SourceMapDecoder({
prepareOwnership: async () => {},
launcher: (options) =>
spawnOwnedProviderProcess({
...options,
arguments: [
"-e",
'process.stderr.write("x".repeat(1024 * 1024 + 64)); setInterval(() => {}, 1000);',
],
}),
});
try {
const stderrRefusal = await stderrDecoder.trace(input);
if (stderrRefusal.ok) throw new Error("expected stderr allowance refusal");
expect(stderrRefusal.error._tag).toBe("AnalysisOutputError");
expect(
projectAnalysisError(stderrRefusal.error).details?.limit,
).toBeUndefined();
} finally {
await stderrDecoder.close();
}
const parsedReply = parseSourceMapReply(
JSON.stringify({
state: "failure",
reason: "limit",
message: "record budget exceeded",
limit: { field: "decoded_records", maximum: 4 },
}),
input.path,
null,
);
if (parsedReply.ok) throw new Error("expected decoded_records refusal");
expect(projectAnalysisError(parsedReply.error).details?.limit).toEqual({
control_kind: "parameter",
parameter: "source_map_limits.decoded_records",
effective_value: 4,
unit: "count",
minimum: 1,
maximum: 0x7fff_ffff,
default_value: 262_144,
applies_at: "next_call",
});
const legacyLimitReply = parseSourceMapReply(
JSON.stringify({
state: "failure",
reason: "limit",
message: "record budget exceeded without structured limit",
}),
input.path,
null,
);
if (legacyLimitReply.ok) throw new Error("expected legacy limit refusal");
expect(legacyLimitReply.error._tag).toBe("ArtifactOperationError");
expect(
projectAnalysisError(legacyLimitReply.error).details?.limit,
).toBeUndefined();
for (const invalidReply of [
{
state: "failure",
reason: "limit",
message: "non-codec field",
limit: { field: "fetch_bytes", maximum: 1024 },
},
{
state: "failure",
reason: "limit",
message: "non-codec heap field",
limit: { field: "codec_heap_mib", maximum: 192 },
},
{
state: "failure",
reason: "limit",
message: "below range",
limit: { field: "decoded_records", maximum: 0 },
},
{
state: "failure",
reason: "limit",
message: "above range",
limit: { field: "output_bytes", maximum: 536_870_888 },
},
{
state: "failure",
reason: "malformed",
message: "limit on malformed reply",
limit: { field: "decoded_records", maximum: 4 },
},
]) {
const rejected = parseSourceMapReply(
JSON.stringify(invalidReply),
input.path,
null,
);
if (rejected.ok) throw new Error("expected malformed codec reply error");
expect(rejected.error._tag).toBe("AnalysisOutputError");
expect(projectAnalysisError(rejected.error).code).toBe("unreadable_output");
expect(projectAnalysisError(rejected.error).details?.limit).toBeUndefined();
}
});
@@ -2,6 +2,7 @@ import { QueuedProviderClose } from "../../providers/QueuedProviderClose.js";
import {
selectedSourceMapLimits,
localSourceMapLimitsSchema,
sourceMapBudgetLimit,
sourceMapLimitRecovery,
} from "../../domain/sourceMapLimits.js";
import type { ExecutionOptions } from "../../ports/AnalysisProvider.js";
@@ -110,6 +111,7 @@ export class SourceMapDecoder implements WebSourceMapPort {
const capacityFailure = (
field: "map_bytes" | "output_bytes",
value: number,
requiredValue?: number,
) => {
const recovery = sourceMapLimitRecovery(field, value);
return new ArtifactOperationError(
@@ -117,11 +119,15 @@ export class SourceMapDecoder implements WebSourceMapPort {
"limit",
undefined,
`${input.path}: Source-map admission exhausted. ${recovery}`,
{ remediationAction: recovery },
{
limit: sourceMapBudgetLimit(field, value, requiredValue),
remediationAction: recovery,
},
);
};
if (Buffer.byteLength(input.text) > limits.mapBytes)
return err(capacityFailure("map_bytes", limits.mapBytes));
const inputBytes = Buffer.byteLength(input.text);
if (inputBytes > limits.mapBytes)
return err(capacityFailure("map_bytes", limits.mapBytes, inputBytes));
const encoded: string[] = [];
let encodedBytes = 0;
for (const part of jsonParts(request.data)) {
+24 -4
View File
@@ -1,4 +1,7 @@
import { WEB_SOURCE_MAP_LIMITS } from "../../domain/sourceMapLimits.js";
import {
WEB_SOURCE_MAP_LIMITS,
sourceMapBudgetLimit,
} from "../../domain/sourceMapLimits.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCapabilityUnavailableError,
@@ -9,7 +12,10 @@ 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";
import {
sourceMapCodecReplySchema,
type CodecSourceMapLimitField,
} from "./SourceMapCodecProtocol.js";
import { errorMessage } from "../../kernel/errorMessage.js";
const OPERATION = "trace_web_source_location";
@@ -41,7 +47,12 @@ export const parseSourceMapReply = (
),
);
if (reply.data.state === "failure")
return codecFailure(path, reply.data.reason, reply.data.message);
return codecFailure(
path,
reply.data.reason,
reply.data.message,
reply.data.reason === "limit" ? reply.data.limit : undefined,
);
const runtimeFailure = codecRuntimeFailure(
reply.data.report.runtime,
processMemoryLimitBytes,
@@ -80,6 +91,10 @@ const codecFailure = (
path: string,
reason: "malformed" | "unsupported" | "limit",
detail: string,
limit?: {
readonly field: CodecSourceMapLimitField;
readonly maximum: number;
},
): Result<never, AnalysisError> =>
err(
reason === "limit"
@@ -88,7 +103,12 @@ const codecFailure = (
"limit",
undefined,
`${path}: ${detail}`,
{ remediationAction: detail },
{
...(limit === undefined
? {}
: { limit: sourceMapBudgetLimit(limit.field, limit.maximum) }),
remediationAction: detail,
},
)
: reason === "unsupported"
? new AnalysisCapabilityUnavailableError(