diff --git a/docs/reference/limits-and-recovery.md b/docs/reference/limits-and-recovery.md index aac14399b1..869b440fad 100644 --- a/docs/reference/limits-and-recovery.md +++ b/docs/reference/limits-and-recovery.md @@ -110,7 +110,8 @@ their per-call budgets (`max_file_bytes`, entry, depth and decoded-byte budgets, `inspect_elf_dependencies`, `inspect_elf_unwind_ranges`, `inspect_apple_ips`, `inspect_dwarf_units`, `inspect_native_initializers`, `inspect_pe_overlay`, `inspect_pe_resources` (`max_entries`), `inspect_api_contract` (`max_file_bytes`), -`compare_wasm_interfaces` (`max_interface_bytes`) and +`compare_wasm_interfaces` (`max_interface_bytes`), +`trace_web_source_location` (`source_map_limits.*`) and `inspect_erlang_beam` report it too. The per-page symbol-name text allowance of `inspect_elf_unwind_ranges` is a fixed allowance (`details.refusal.kind` `fixed_ceiling`); its `narrowing` asks for a smaller page `limit` or paging with `offset`. `inspect_erlang_beam` accepts `max_table_rows` (export, import and lambda rows combined; default 65,536, at most 1,048,576). diff --git a/scripts/verify/untyped-budget-refusal-baseline.json b/scripts/verify/untyped-budget-refusal-baseline.json index a177e51282..4b5765918f 100644 --- a/scripts/verify/untyped-budget-refusal-baseline.json +++ b/scripts/verify/untyped-budget-refusal-baseline.json @@ -31,7 +31,6 @@ "src/javascript/analysis/JavaScriptAnalysisWorker.ts": 8, "src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts": 1, "src/javascript/recovery/RecoveryFiles.ts": 1, - "src/javascript/sourceMaps/SourceMapCommand.ts": 1, "src/jeb/JebProvider.ts": 1, "src/kuna/KunaSessionClient.ts": 1, "src/main/StdioStartupInput.ts": 1, diff --git a/src/browser/assets/WebArtifactReads.ts b/src/browser/assets/WebArtifactReads.ts index f6438cffe8..3593992291 100644 --- a/src/browser/assets/WebArtifactReads.ts +++ b/src/browser/assets/WebArtifactReads.ts @@ -19,6 +19,7 @@ import { AnalysisError, primaryAnalysisError, } from "../../domain/analysisErrorBase.js"; +import type { AnalysisParameterLimit } from "../../domain/analysisSettings.js"; import { AnalysisAccessDeniedError, AnalysisInputError, @@ -44,6 +45,10 @@ export interface WebArtifactReadContext { readonly callerSelected: boolean; /** Exact resource recovery supplied by the selected artifact owner. */ readonly limitRecovery?: string; + /** Structured per-call limit supplied by the selected artifact owner. */ + readonly limit?: ( + cause: ArtifactReaderFailure, + ) => AnalysisParameterLimit | undefined; } /** The ParseFailure format of a captured web artifact document. */ @@ -197,7 +202,8 @@ const webArtifactPrimaryError = ( if ( origin === "owned-or-classified" && cause instanceof ArtifactReaderFailure - ) + ) { + const limit = cause.reason === "limit" ? context.limit?.(cause) : undefined; return new ArtifactOperationError( context.operation, artifactOperationReason(cause), @@ -207,6 +213,7 @@ const webArtifactPrimaryError = ( : cause.message, { cause, + ...(limit === undefined ? {} : { limit }), ...(cause.reason === "limit" && context.limitRecovery !== undefined ? { remediationAction: context.limitRecovery } : {}), @@ -215,6 +222,7 @@ const webArtifactPrimaryError = ( : { integrityCheck: cause.integrityCheck }), }, ); + } if ( cause instanceof Error && "code" in cause && diff --git a/src/browser/assets/WebSourceLocationArtifacts.ts b/src/browser/assets/WebSourceLocationArtifacts.ts index 0fe86aba4f..b9a3a0bc8f 100644 --- a/src/browser/assets/WebSourceLocationArtifacts.ts +++ b/src/browser/assets/WebSourceLocationArtifacts.ts @@ -1,5 +1,6 @@ import { selectedSourceMapLimits, + sourceMapBudgetLimit, sourceMapLimitRecovery, } from "../../domain/sourceMapLimits.js"; import type { WebSourceLocationArtifactPort } from "../../ports/WebSourceLocationPorts.js"; @@ -64,6 +65,17 @@ export class LocalWebSourceLocationArtifacts implements WebSourceLocationArtifac "map_bytes", selectedSourceMapLimits(input.source_map_limits).mapBytes, ), + limit: (failure) => + failure.boundary === "file-size" + ? sourceMapBudgetLimit( + "map_bytes", + selectedSourceMapLimits(input.source_map_limits).mapBytes, + failure.observedBytes !== undefined && + failure.observedBytes <= BigInt(Number.MAX_SAFE_INTEGER) + ? Number(failure.observedBytes) + : undefined, + ) + : undefined, }, options?.signal, ), diff --git a/src/domain/sourceMapLimits.ts b/src/domain/sourceMapLimits.ts index 3b171837be..e407db4da1 100644 --- a/src/domain/sourceMapLimits.ts +++ b/src/domain/sourceMapLimits.ts @@ -1,4 +1,9 @@ import { z } from "zod"; +import type { AnalysisParameterLimit } from "./analysisSettings.js"; +import { + parameterBudgetLimit, + type ParameterBudget, +} from "./parameterBudget.js"; /** Local map admission calibrated against public Actual Budget maps; other policies remain conservative. */ export const WEB_SOURCE_MAP_LIMITS = { @@ -17,52 +22,118 @@ export const WEB_SOURCE_MAP_LIMITS = { export const MAX_SOURCE_MAP_ENCODED_BYTES = 536870887; const MAX_RECORD_COUNT = 0x7fffffff; const MAX_CODEC_HEAP_MIB = 16384; -const bytes = z.int().min(1).max(MAX_SOURCE_MAP_ENCODED_BYTES); -const count = z.int().min(1).max(MAX_RECORD_COUNT); + +export const SOURCE_MAP_LIMIT_FIELDS = [ + "map_bytes", + "output_bytes", + "decoded_rows", + "decoded_segments", + "decoded_records", + "section_depth", + "codec_heap_mib", + "fetch_bytes", +] as const; + +export type SourceMapLimitField = (typeof SOURCE_MAP_LIMIT_FIELDS)[number]; + +export const sourceMapLimitFieldSchema = z.enum(SOURCE_MAP_LIMIT_FIELDS); + +/** Per-call source-map budgets shared by the input schema and refusal limits. */ +export const SOURCE_MAP_BUDGETS = { + map_bytes: { + minimum: 1, + maximum: MAX_SOURCE_MAP_ENCODED_BYTES, + default_value: WEB_SOURCE_MAP_LIMITS.mapBytes, + unit: "bytes", + }, + output_bytes: { + minimum: 1, + maximum: MAX_SOURCE_MAP_ENCODED_BYTES, + default_value: WEB_SOURCE_MAP_LIMITS.outputBytes, + unit: "bytes", + }, + decoded_rows: { + minimum: 1, + maximum: MAX_RECORD_COUNT, + default_value: WEB_SOURCE_MAP_LIMITS.decodedRows, + unit: "count", + }, + decoded_segments: { + minimum: 1, + maximum: MAX_RECORD_COUNT, + default_value: WEB_SOURCE_MAP_LIMITS.decodedSegments, + unit: "count", + }, + decoded_records: { + minimum: 1, + maximum: MAX_RECORD_COUNT, + default_value: WEB_SOURCE_MAP_LIMITS.decodedRecords, + unit: "count", + }, + section_depth: { + minimum: 1, + maximum: MAX_RECORD_COUNT, + default_value: WEB_SOURCE_MAP_LIMITS.sectionDepth, + unit: "count", + }, + codec_heap_mib: { + minimum: 128, + maximum: MAX_CODEC_HEAP_MIB, + default_value: WEB_SOURCE_MAP_LIMITS.codecHeapMiB, + unit: "MiB", + }, + fetch_bytes: { + minimum: 1, + maximum: MAX_SOURCE_MAP_ENCODED_BYTES, + default_value: WEB_SOURCE_MAP_LIMITS.fetchBytes, + unit: "bytes", + }, +} as const satisfies Record; + +/** Build a structured per-call refusal limit using the input schema's own bounds. */ +export const sourceMapBudgetLimit = ( + field: SourceMapLimitField, + effectiveValue: number, + requiredValue?: number, +): AnalysisParameterLimit => ({ + ...parameterBudgetLimit( + `source_map_limits.${field}`, + SOURCE_MAP_BUDGETS[field], + effectiveValue, + ), + ...(requiredValue === undefined ? {} : { required_value: requiredValue }), +}); + +const optionalBudget = (budget: ParameterBudget) => + z.int().min(budget.minimum).max(budget.maximum).exactOptional(); + export const sourceMapLimitsSchema = z.strictObject({ - map_bytes: bytes - .exactOptional() - .describe( - `Local source-map byte admission; default ${String(WEB_SOURCE_MAP_LIMITS.mapBytes)}. Applies before reading and again in the codec.`, - ), - output_bytes: bytes - .exactOptional() - .describe( - `Complete encoded request/reply or fetched-map representation budget; default ${String(WEB_SOURCE_MAP_LIMITS.outputBytes)}.`, - ), - decoded_rows: count - .exactOptional() - .describe( - `Generated-row admission before codec allocation; default ${String(WEB_SOURCE_MAP_LIMITS.decodedRows)}.`, - ), - decoded_segments: count - .exactOptional() - .describe( - `Mapping-segment admission before codec allocation; default ${String(WEB_SOURCE_MAP_LIMITS.decodedSegments)}.`, - ), - decoded_records: count - .exactOptional() - .describe( - `Shared structural record admission, including declarations, rows, segments and sections; default ${String(WEB_SOURCE_MAP_LIMITS.decodedRecords)}.`, - ), - section_depth: count - .exactOptional() - .describe( - `Indexed-section nesting admission; default ${String(WEB_SOURCE_MAP_LIMITS.sectionDepth)}. Each retained section also consumes the shared structural-record budget.`, - ), - codec_heap_mib: z - .int() - .min(128) - .max(MAX_CODEC_HEAP_MIB) - .exactOptional() - .describe( - `Local codec old-generation heap request in MiB; default ${String(WEB_SOURCE_MAP_LIMITS.codecHeapMiB)}. Independent of byte/record budgets and client receive limits.`, - ), - fetch_bytes: bytes - .exactOptional() - .describe( - `Aggregate fetched response bytes and, independently, retained resolved-identity bytes; each defaults to ${String(WEB_SOURCE_MAP_LIMITS.fetchBytes)}.`, - ), + map_bytes: optionalBudget(SOURCE_MAP_BUDGETS.map_bytes).describe( + `Local source-map byte admission; default ${String(WEB_SOURCE_MAP_LIMITS.mapBytes)}. Applies before reading and again in the codec.`, + ), + output_bytes: optionalBudget(SOURCE_MAP_BUDGETS.output_bytes).describe( + `Complete encoded request/reply or fetched-map representation budget; default ${String(WEB_SOURCE_MAP_LIMITS.outputBytes)}.`, + ), + decoded_rows: optionalBudget(SOURCE_MAP_BUDGETS.decoded_rows).describe( + `Generated-row admission before codec allocation; default ${String(WEB_SOURCE_MAP_LIMITS.decodedRows)}.`, + ), + decoded_segments: optionalBudget( + SOURCE_MAP_BUDGETS.decoded_segments, + ).describe( + `Mapping-segment admission before codec allocation; default ${String(WEB_SOURCE_MAP_LIMITS.decodedSegments)}.`, + ), + decoded_records: optionalBudget(SOURCE_MAP_BUDGETS.decoded_records).describe( + `Shared structural record admission, including declarations, rows, segments and sections; default ${String(WEB_SOURCE_MAP_LIMITS.decodedRecords)}.`, + ), + section_depth: optionalBudget(SOURCE_MAP_BUDGETS.section_depth).describe( + `Indexed-section nesting admission; default ${String(WEB_SOURCE_MAP_LIMITS.sectionDepth)}. Each retained section also consumes the shared structural-record budget.`, + ), + codec_heap_mib: optionalBudget(SOURCE_MAP_BUDGETS.codec_heap_mib).describe( + `Local codec old-generation heap request in MiB; default ${String(WEB_SOURCE_MAP_LIMITS.codecHeapMiB)}. Independent of byte/record budgets and client receive limits.`, + ), + fetch_bytes: optionalBudget(SOURCE_MAP_BUDGETS.fetch_bytes).describe( + `Aggregate fetched response bytes and, independently, retained resolved-identity bytes; each defaults to ${String(WEB_SOURCE_MAP_LIMITS.fetchBytes)}.`, + ), }); export type SourceMapLimitSelection = z.output; export type SourceMapLimits = typeof WEB_SOURCE_MAP_LIMITS; @@ -85,13 +156,7 @@ export const sourceMapLimitRecovery = ( field: keyof SourceMapLimitSelection, value: number, ): string => { - const maximum = - field === "codec_heap_mib" - ? MAX_CODEC_HEAP_MIB - : field.endsWith("bytes") - ? MAX_SOURCE_MAP_ENCODED_BYTES - : MAX_RECORD_COUNT; - const minimum = field === "codec_heap_mib" ? 128 : 1; + const { minimum, maximum } = SOURCE_MAP_BUDGETS[field]; const unit = field === "codec_heap_mib" ? "MiB" diff --git a/src/javascript/sourceMaps/SourceMapCodecProcess.ts b/src/javascript/sourceMaps/SourceMapCodecProcess.ts index e67e44a50f..6fbe24ab85 100644 --- a/src/javascript/sourceMaps/SourceMapCodecProcess.ts +++ b/src/javascript/sourceMaps/SourceMapCodecProcess.ts @@ -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 => { ) ) 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 => { ? "malformed" : cause.kind, message: cause.message, + ...(parsedLimit?.success && isSourceMapLimit(cause) + ? { + limit: { + field: parsedLimit.data, + maximum: cause.failure.limit.maximum, + }, + } + : {}), }); } }; diff --git a/src/javascript/sourceMaps/SourceMapCodecProtocol.ts b/src/javascript/sourceMaps/SourceMapCodecProtocol.ts index 4d339d1949..192db4c3f3 100644 --- a/src/javascript/sourceMaps/SourceMapCodecProtocol.ts +++ b/src/javascript/sourceMaps/SourceMapCodecProtocol.ts @@ -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(), }), ]); diff --git a/src/javascript/sourceMaps/SourceMapCommand.test.ts b/src/javascript/sourceMaps/SourceMapCommand.test.ts index 5ea4cabc12..e470d115fe 100644 --- a/src/javascript/sourceMaps/SourceMapCommand.test.ts +++ b/src/javascript/sourceMaps/SourceMapCommand.test.ts @@ -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", diff --git a/src/javascript/sourceMaps/SourceMapCommand.ts b/src/javascript/sourceMaps/SourceMapCommand.ts index 2c1b9d803a..02a9206523 100644 --- a/src/javascript/sourceMaps/SourceMapCommand.ts +++ b/src/javascript/sourceMaps/SourceMapCommand.ts @@ -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, - ), }, ); } diff --git a/src/javascript/sourceMaps/SourceMapDecoder.test.ts b/src/javascript/sourceMaps/SourceMapDecoder.test.ts index 326bf4e9e0..17e2c493c4 100644 --- a/src/javascript/sourceMaps/SourceMapDecoder.test.ts +++ b/src/javascript/sourceMaps/SourceMapDecoder.test.ts @@ -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(); + } +}); diff --git a/src/javascript/sourceMaps/SourceMapDecoder.ts b/src/javascript/sourceMaps/SourceMapDecoder.ts index a9d7ebceb7..7cf6e89da9 100644 --- a/src/javascript/sourceMaps/SourceMapDecoder.ts +++ b/src/javascript/sourceMaps/SourceMapDecoder.ts @@ -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)) { diff --git a/src/javascript/sourceMaps/SourceMapReply.ts b/src/javascript/sourceMaps/SourceMapReply.ts index 166494f196..4d5811f2f0 100644 --- a/src/javascript/sourceMaps/SourceMapReply.ts +++ b/src/javascript/sourceMaps/SourceMapReply.ts @@ -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 => 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( diff --git a/tests/acceptance/webSourceLocationCli.test.ts b/tests/acceptance/webSourceLocationCli.test.ts index 90b0c75512..c9b2bcee68 100644 --- a/tests/acceptance/webSourceLocationCli.test.ts +++ b/tests/acceptance/webSourceLocationCli.test.ts @@ -721,6 +721,18 @@ cliTest( code: "partial", details: { detail: expect.stringContaining("source_map_limits.map_bytes"), + limit: { + control_kind: "parameter", + parameter: "source_map_limits.map_bytes", + cli_flag: "--source-map-bytes", + effective_value: 128, + unit: "bytes", + minimum: 1, + maximum: 536_870_887, + default_value: 8_388_608, + applies_at: "next_call", + required_value: Buffer.byteLength(fixture.sourceMap.text), + }, }, }); const recovered = await cli.run({ diff --git a/tests/boundary/javascript/sourceMapDecoder.test.ts b/tests/boundary/javascript/sourceMapDecoder.test.ts index 27c7448442..9af39e3c37 100644 --- a/tests/boundary/javascript/sourceMapDecoder.test.ts +++ b/tests/boundary/javascript/sourceMapDecoder.test.ts @@ -593,7 +593,18 @@ it("returns all point matches when they fit and reports output exhaustion otherw _tag: "ArtifactOperationError", reason: "limit", detail: expect.stringContaining("source_map_limits.output_bytes is 5500"), + limit: { + control_kind: "parameter", + parameter: "source_map_limits.output_bytes", + effective_value: 5500, + unit: "bytes", + minimum: 1, + maximum: 536_870_887, + default_value: 33_554_432, + applies_at: "next_call", + }, }); + expect(limited.error.limit).not.toHaveProperty("required_value"); expect(limited.error.partialObservation).toBeUndefined(); }); it("admits a codec reply only from the selected runtime and memory envelope", async () => { @@ -691,6 +702,16 @@ it.each([true, false])( reportedLimits: { codec_process_memory_limit_bytes: expectedProcessMemoryLimitBytes, }, + 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", + }, capturedOutput: { stderr: "panic: out of memory" }, } : { diagnostics: { exit_code: 3, stderr: "panic: out of memory" } }, diff --git a/tests/boundary/mcp/webSourceLocationMcp.test.ts b/tests/boundary/mcp/webSourceLocationMcp.test.ts index a2a52d6db0..638026b50a 100644 --- a/tests/boundary/mcp/webSourceLocationMcp.test.ts +++ b/tests/boundary/mcp/webSourceLocationMcp.test.ts @@ -193,3 +193,44 @@ it("preserves missing Linux ps capability and recovery through source-map tracin expect(createRuntime).not.toHaveBeenCalled(); expect(launcher).not.toHaveBeenCalled(); }); + +it("reports details.limit without cli_flag for MCP source_map_limits refusals", async () => { + const data = webSourceLocationFixture(); + const decoder = new SourceMapDecoder(); + const harness = await createApplicationMcpHarness({ + serverOptions: { + webSourceLocation: new WebSourceLocationService( + { load: async () => ok(data) }, + decoder, + ), + }, + }); + onTestFinished(async () => { + await harness.close(); + await decoder.close(); + }); + const response = await harness.client.callTool({ + name: "trace_web_source_location", + arguments: { ...args, source_map_limits: { output_bytes: 16 } }, + }); + const { error } = parseMcpToolError(response); + expect(error).toMatchObject({ + code: "partial", + retryable: false, + details: { + limit: { + 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( + (error.details as { limit?: Record } | undefined)?.limit, + ).not.toHaveProperty("cli_flag"); +});