diff --git a/scripts/verify/architecture-guards.mjs b/scripts/verify/architecture-guards.mjs index aff0c091c1..0c35a3a9cf 100644 --- a/scripts/verify/architecture-guards.mjs +++ b/scripts/verify/architecture-guards.mjs @@ -166,6 +166,32 @@ check( ], ); +// Node clamps a timer delay above the signed 32-bit bound to 1 ms. Durations +// use MAX_NODE_TIMER_DELAY_MS or timerDurationMsSchema from their one owner. +// The allowed files bound signed 32-bit integers that are not timer delays. +check( + "signed 32-bit bound literal (use MAX_NODE_TIMER_DELAY_MS or timerDurationMsSchema from src/domain/analysisResourceLimits for durations)", + files, + /\b2_?147_?483_?647\b/u, + [ + "src/domain/analysisResourceLimits.ts", + // JADX MCP `limit` argument: a Java int, not a duration. + "src/android/JadxAnalysis.ts", + // JVM `-XX:ActiveProcessorCount`: a Java int processor count. + "src/android/JadxConfiguration.ts", + // TShark `-c` packet count: a C int, not a duration. + "src/domain/captures/packetCapture.ts", + // DEX static `int` value range. + "src/domain/android/androidAnalysis.ts", + // Signed 32-bit bitmask operand range. + "src/domain/javascript/javascriptSemanticResources.ts", + // Recorded crash pid, signal number and code fields. + "src/domain/native/recordedCrash.ts", + // Java int parsing for Ghidra launch properties. + "src/ghidra/GhidraInstallationPolicy.ts", + ], +); + // Mach-O load-command codes have one table; a local copy drifts from it. check( "local Mach-O load-command code (import LC from src/domain/apple/machoLoadCommandCodes)", diff --git a/src/android/JadxConfiguration.ts b/src/android/JadxConfiguration.ts index ea46137285..6340eda048 100644 --- a/src/android/JadxConfiguration.ts +++ b/src/android/JadxConfiguration.ts @@ -2,7 +2,10 @@ import { absoluteCallerPath, appendCallerPath, } from "../filesystem/callerPath.js"; -import { DEFAULT_JADX_OPERATION_TIMEOUT_MS } from "../domain/analysisResourceLimits.js"; +import { + DEFAULT_JADX_OPERATION_TIMEOUT_MS, + MAX_NODE_TIMER_DELAY_MS, +} from "../domain/analysisResourceLimits.js"; import { jadxOperationTimeoutGuidance, JADX_OPERATION_TIMEOUT_REMEDIATION, @@ -679,6 +682,9 @@ const requireJavaHomeExecutable = async ( } }; +/** `-XX:ActiveProcessorCount` is a Java `int`; this is a count, not a duration. */ +const JAVA_INT_MAX = 2_147_483_647; + const resolveJvmArguments = ( environment: Readonly>, ): readonly string[] => { @@ -698,7 +704,7 @@ const resolveJvmArguments = ( ); if ( name === "REA_JADX_ACTIVE_PROCESSOR_COUNT" && - Number(value) > 2_147_483_647 + Number(value) > JAVA_INT_MAX ) throw configurationFailure( "open_options_invalid", @@ -722,7 +728,7 @@ const readOperationTimeout = ( if (parsed.success) return parsed.data; throw configurationFailure( "open_options_invalid", - `REA_JADX_OPERATION_TIMEOUT_MS must be a decimal millisecond count from 1 to 2147483647; received ${value}.`, + `REA_JADX_OPERATION_TIMEOUT_MS must be a decimal millisecond count from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)}; received ${value}.`, { setting: "REA_JADX_OPERATION_TIMEOUT_MS", value }, "operation_timeout", ); diff --git a/src/android/JadxOperationTimeout.ts b/src/android/JadxOperationTimeout.ts index bb0240eda3..f03b26a6cd 100644 --- a/src/android/JadxOperationTimeout.ts +++ b/src/android/JadxOperationTimeout.ts @@ -1,8 +1,11 @@ import { analysisSettingLimit } from "../domain/analysisSettingDefinitions.js"; -import { DEFAULT_JADX_OPERATION_TIMEOUT_MS } from "../domain/analysisResourceLimits.js"; +import { + DEFAULT_JADX_OPERATION_TIMEOUT_MS, + MAX_NODE_TIMER_DELAY_MS, +} from "../domain/analysisResourceLimits.js"; /** Remediation when the JADX operation deadline override is malformed. */ -export const JADX_OPERATION_TIMEOUT_REMEDIATION = `Set REA_JADX_OPERATION_TIMEOUT_MS to a decimal millisecond count from 1 to 2147483647, or unset it to keep the ${String(DEFAULT_JADX_OPERATION_TIMEOUT_MS)} ms default.`; +export const JADX_OPERATION_TIMEOUT_REMEDIATION = `Set REA_JADX_OPERATION_TIMEOUT_MS to a decimal millisecond count from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)}, or unset it to keep the ${String(DEFAULT_JADX_OPERATION_TIMEOUT_MS)} ms default.`; /** Name the launch-environment deadline when a JADX operation reaches it. */ export const jadxOperationTimeoutGuidance = (timeoutMs: number) => ({ @@ -12,5 +15,5 @@ export const jadxOperationTimeoutGuidance = (timeoutMs: number) => ({ undefined, ), userMessage: `JADX reached its configured operation deadline of ${String(timeoutMs)} ms (deadlineExpired).`, - remediationAction: `Set REA_JADX_OPERATION_TIMEOUT_MS in REA's launch environment to an integer from 1 to 2147483647 milliseconds (omitted means ${String(DEFAULT_JADX_OPERATION_TIMEOUT_MS)} ms). For a running MCP server, use update_analysis_settings with setting jadx.operation_timeout_ms and action set; it applies to the next operation without restarting REA. Environment changes apply on the next REA process start. The effective deadline for this attempt was ${String(timeoutMs)} ms. It does not raise the bridge's 30000 ms startup handshake. Raising only the MCP client deadline does not change this budget. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`, + remediationAction: `Set REA_JADX_OPERATION_TIMEOUT_MS in REA's launch environment to an integer from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)} milliseconds (omitted means ${String(DEFAULT_JADX_OPERATION_TIMEOUT_MS)} ms). For a running MCP server, use update_analysis_settings with setting jadx.operation_timeout_ms and action set; it applies to the next operation without restarting REA. Environment changes apply on the next REA process start. The effective deadline for this attempt was ${String(timeoutMs)} ms. It does not raise the bridge's 30000 ms startup handshake. Raising only the MCP client deadline does not change this budget. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`, }); diff --git a/src/apktool/ApktoolDecodeTimeout.test.ts b/src/apktool/ApktoolDecodeTimeout.test.ts index e5c016db7a..7b124f50f3 100644 --- a/src/apktool/ApktoolDecodeTimeout.test.ts +++ b/src/apktool/ApktoolDecodeTimeout.test.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -5,10 +6,7 @@ import { afterEach, expect, it, vi } from "vitest"; import { ApktoolResourceAnalysisService } from "../application/apktool/ApktoolResourceAnalysisService.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; -import { - DEFAULT_APKTOOL_DECODE_TIMEOUT_MS, - MAX_APKTOOL_DECODE_TIMEOUT_MS, -} from "../domain/apktool/apktoolResourceAnalysis.js"; +import { DEFAULT_APKTOOL_DECODE_TIMEOUT_MS } from "../domain/apktool/apktoolResourceAnalysis.js"; import { OwnedCommandFailure, runOwnedCommand, @@ -72,7 +70,7 @@ const installLauncher = (): void => { // process-tree cleanup are covered by apktoolDecodeDeadline.test.ts. if ( limits.timeoutMs === 200 || - limits.timeoutMs === MAX_APKTOOL_DECODE_TIMEOUT_MS + limits.timeoutMs === MAX_NODE_TIMER_DELAY_MS ) throw new OwnedCommandFailure("timeout", "Command deadline elapsed."); const outputIndex = spawn.arguments.indexOf("-o"); @@ -127,7 +125,7 @@ it("applies the omitted 600000 ms decode deadline and a selected value on the ne expect(projected.message).toContain("200 ms"); expect(projected.remediation.action).toContain("decode_timeout_ms"); expect(projected.remediation.action).toContain( - String(MAX_APKTOOL_DECODE_TIMEOUT_MS), + String(MAX_NODE_TIMER_DELAY_MS), ); expect(projected.remediation.action).toContain("600000"); expect(projected.remediation.action).toContain("next decode"); @@ -146,7 +144,7 @@ it("applies the omitted 600000 ms decode deadline and a selected value on the ne 5_000, ]); - const maximum = await decode(provider, path, MAX_APKTOOL_DECODE_TIMEOUT_MS); + const maximum = await decode(provider, path, MAX_NODE_TIMER_DELAY_MS); if (maximum.ok) throw new Error("Expected the maximum decode deadline"); expect(projectAnalysisError(maximum.error).remediation.action).toContain( "do not increase it further", diff --git a/src/apktool/ApktoolProvider.ts b/src/apktool/ApktoolProvider.ts index e3e5f37cde..03c6e6c65c 100644 --- a/src/apktool/ApktoolProvider.ts +++ b/src/apktool/ApktoolProvider.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { processInspectionCancellationError } from "../providers/OwnedCommandCleanup.js"; import { APKTOOL_PROVIDER_IDENTITY } from "./ApktoolProviderIdentity.js"; import { countDecodedFiles } from "./ApktoolDecodedInventory.js"; @@ -42,7 +43,6 @@ import { apktoolResultSchemas, apktoolStringTablesRequested, DEFAULT_APKTOOL_DECODE_TIMEOUT_MS, - MAX_APKTOOL_DECODE_TIMEOUT_MS, type ApktoolRequest, type ApktoolDecodeResult, } from "../domain/apktool/apktoolResourceAnalysis.js"; @@ -113,9 +113,9 @@ const apktoolDecodeTimeoutGuidance = ( ): { readonly userMessage: string; readonly remediationAction: string } => ({ userMessage: `apktool decode reached its ${String(timeoutMs)} ms wall-clock deadline (deadlineExpired).`, remediationAction: `${ - timeoutMs < MAX_APKTOOL_DECODE_TIMEOUT_MS - ? `Increase decode_timeout_ms above ${String(timeoutMs)} (integer milliseconds from 1 to ${String(MAX_APKTOOL_DECODE_TIMEOUT_MS)}; omitted means ${String(DEFAULT_APKTOOL_DECODE_TIMEOUT_MS)}), or use rea decode-android-resources --decode-timeout-ms on the CLI.` - : `decode_timeout_ms is already at the maximum ${String(MAX_APKTOOL_DECODE_TIMEOUT_MS)} ms; do not increase it further.` + timeoutMs < MAX_NODE_TIMER_DELAY_MS + ? `Increase decode_timeout_ms above ${String(timeoutMs)} (integer milliseconds from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)}; omitted means ${String(DEFAULT_APKTOOL_DECODE_TIMEOUT_MS)}), or use rea decode-android-resources --decode-timeout-ms on the CLI.` + : `decode_timeout_ms is already at the maximum ${String(MAX_NODE_TIMER_DELAY_MS)} ms; do not increase it further.` } A change applies on the next decode. It does not raise the ${String(DECODE_MAX_OUTPUT_BYTES)}-byte output capture allowance or the version probe; both have no runtime override. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`, }); diff --git a/src/application/DoctorDiagnostics.ts b/src/application/DoctorDiagnostics.ts index dd9573226d..fe6595149a 100644 --- a/src/application/DoctorDiagnostics.ts +++ b/src/application/DoctorDiagnostics.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { SUPPORTED_NODE_VERSION_PROSE, supportsJavaScriptRuntime, @@ -222,8 +223,7 @@ const optionalHopperStartupTimeoutCheck = ( : `REA_HOPPER_STARTUP_TIMEOUT_MS: ${parsed.error.settings.map(({ constraint }) => constraint).join("; ")}`, { classification: "config_drift", - remediation: - "Unset REA_HOPPER_STARTUP_TIMEOUT_MS to use the default, or set it to a positive decimal integer from 1 to 2147483647 milliseconds.", + remediation: `Unset REA_HOPPER_STARTUP_TIMEOUT_MS to use the default, or set it to a positive decimal integer from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)} milliseconds.`, }, ); }; diff --git a/src/application/reverse/ReverseEngineeringService.ts b/src/application/reverse/ReverseEngineeringService.ts index c3aa241a19..34c44c65d7 100644 --- a/src/application/reverse/ReverseEngineeringService.ts +++ b/src/application/reverse/ReverseEngineeringService.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../../domain/analysisResourceLimits.js"; import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js"; import { bindArtifactFileCleanup } from "../../artifacts/ArtifactFileOperation.js"; import { @@ -41,7 +42,6 @@ import { DEFAULT_REVERSE_COMMAND_TIMEOUT_MS, DEFAULT_REVERSE_COMMAND_OUTPUT_BYTES, MAX_REVERSE_COMMAND_OUTPUT_BYTES, - MAX_REVERSE_COMMAND_TIMEOUT_MS, objdumpInputSchema, rizinInputSchema, type RizinInput, @@ -1433,9 +1433,9 @@ const reverseCommandTimeoutGuidance = ( ): { readonly userMessage: string; readonly remediationAction: string } => ({ userMessage: `This objdump or rizin command reached its ${String(timeoutMs)} ms server/provider deadline (command_timeout_ms) during target preflight or the one-shot command (deadlineExpired). This is not a Ghidra or Hopper startup deadline and not a debugger session deadline.`, remediationAction: `${ - timeoutMs < MAX_REVERSE_COMMAND_TIMEOUT_MS - ? `Increase command_timeout_ms above ${String(timeoutMs)} (integer milliseconds from 1 to ${String(MAX_REVERSE_COMMAND_TIMEOUT_MS)}; omitted means ${String(DEFAULT_REVERSE_COMMAND_TIMEOUT_MS)}), or use --command-timeout-ms on the CLI.` - : `command_timeout_ms is already at the maximum ${String(MAX_REVERSE_COMMAND_TIMEOUT_MS)} ms; no higher deadline is supported.` + timeoutMs < MAX_NODE_TIMER_DELAY_MS + ? `Increase command_timeout_ms above ${String(timeoutMs)} (integer milliseconds from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)}; omitted means ${String(DEFAULT_REVERSE_COMMAND_TIMEOUT_MS)}), or use --command-timeout-ms on the CLI.` + : `command_timeout_ms is already at the maximum ${String(MAX_NODE_TIMER_DELAY_MS)} ms; no higher deadline is supported.` } The new value applies on the next call; no restart is required. The combined output allowance is separately selected by max_output_bytes (default ${String(DEFAULT_REVERSE_COMMAND_OUTPUT_BYTES)} bytes). Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`, }); diff --git a/src/browser/CdpCaptureValues.ts b/src/browser/CdpCaptureValues.ts index c93d4df376..f40c1eeb67 100644 --- a/src/browser/CdpCaptureValues.ts +++ b/src/browser/CdpCaptureValues.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js"; import { sanitizeBrowserUrl } from "../domain/browserObservation.js"; @@ -81,12 +82,11 @@ export const delayWithCancellation = async ( operation: BrowserObservationOperation, signal?: AbortSignal, ): Promise => { - const maximumTimerDelay = 2_147_483_647; let remaining = durationMs; while (remaining > 0) { if (signal?.aborted === true) throw new AnalysisCancelledError(operation, { cause: signal.reason }); - const delay = Math.min(remaining, maximumTimerDelay); + const delay = Math.min(remaining, MAX_NODE_TIMER_DELAY_MS); await new Promise((resolve, reject) => { const timer = setTimeout(() => { signal?.removeEventListener("abort", onAbort); diff --git a/src/browser/CdpConnection.ts b/src/browser/CdpConnection.ts index 2d61e81e4b..68bbac315c 100644 --- a/src/browser/CdpConnection.ts +++ b/src/browser/CdpConnection.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import WebSocket, { type RawData } from "ws"; import { isUtf8 } from "node:buffer"; @@ -18,7 +19,6 @@ import { cdpCommandTimeoutIsSelectable, cdpCommandTimeoutUnrelatedControl, DEFAULT_CDP_COMMAND_TIMEOUT_MS, - MAX_BROWSER_DEADLINE_MS, noRuntimeOverrideSentence, } from "../domain/browserDeadline.js"; import { safeParseJson } from "../domain/safeJson.js"; @@ -667,7 +667,7 @@ const waitForOpen = async ( signal?.removeEventListener("abort", onAbort); }; const boundedTimeoutMs = Math.min( - MAX_BROWSER_DEADLINE_MS, + MAX_NODE_TIMER_DELAY_MS, handshakeTimeoutMs, ); const timer = setTimeout(() => { diff --git a/src/browser/CdpTargetSession.ts b/src/browser/CdpTargetSession.ts index bd308be30a..e956d3c650 100644 --- a/src/browser/CdpTargetSession.ts +++ b/src/browser/CdpTargetSession.ts @@ -1,7 +1,7 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { CDP_DISCOVERY_RESPONSE_TIMEOUT_MS, DEFAULT_CDP_COMMAND_TIMEOUT_MS, - MAX_BROWSER_DEADLINE_MS, } from "../domain/browserDeadline.js"; import type { BrowserObservationEndpoint } from "../domain/browserObservation.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; @@ -178,7 +178,7 @@ export const openCdpEndpoint = async ( // The browser-socket handshake and discovery commands stay on the discovery // deadline. The selected command deadline starts only after discovery returns. const discoveryGuardTimeoutMs = Math.min( - MAX_BROWSER_DEADLINE_MS, + MAX_NODE_TIMER_DELAY_MS, discoveryTimeoutMs + 1_000, ); const discoveryLimits = { diff --git a/src/browser/CdpTargetSessionOwner.ts b/src/browser/CdpTargetSessionOwner.ts index 190560b0aa..95ca89bdfd 100644 --- a/src/browser/CdpTargetSessionOwner.ts +++ b/src/browser/CdpTargetSessionOwner.ts @@ -1,9 +1,9 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { AnalysisCleanupLease, AnalysisCleanupLeaseGroup, } from "../artifacts/AnalysisCleanupLease.js"; import type { JsonValue } from "../domain/jsonValue.js"; -import { MAX_BROWSER_DEADLINE_MS } from "../domain/browserDeadline.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { BrowserObservationError } from "../domain/browserObservationError.js"; import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js"; @@ -270,7 +270,7 @@ export class CdpTargetSessionOwner { ? {} : { maxPayloadBytes: limits.maxPayloadBytes }), commandTimeoutMs: limits.commandTimeoutMs, - handshakeTimeoutMs: MAX_BROWSER_DEADLINE_MS, + handshakeTimeoutMs: MAX_NODE_TIMER_DELAY_MS, }, ); if (this.#pendingBrowserSockets.get(url) === pending) diff --git a/src/browser/PlaywrightExecutionBoundary.ts b/src/browser/PlaywrightExecutionBoundary.ts index 72c46f264b..2d47cfc25b 100644 --- a/src/browser/PlaywrightExecutionBoundary.ts +++ b/src/browser/PlaywrightExecutionBoundary.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { AnalysisCancelledError, AnalysisTimeoutError, @@ -36,7 +37,10 @@ export const withPlaywrightExecutionBoundary = ( fail(timeoutError()); return; } - timer = setTimeout(scheduleTimeout, Math.min(remaining, 2_147_483_647)); + timer = setTimeout( + scheduleTimeout, + Math.min(remaining, MAX_NODE_TIMER_DELAY_MS), + ); timer.unref(); }; const cleanup = (): void => { diff --git a/src/browser/ScenarioCommandDeadline.ts b/src/browser/ScenarioCommandDeadline.ts index 0cf4e31250..41c9d7873d 100644 --- a/src/browser/ScenarioCommandDeadline.ts +++ b/src/browser/ScenarioCommandDeadline.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { createRequire } from "node:module"; import { BrowserObservationError } from "../domain/browserObservationError.js"; import { @@ -6,7 +7,6 @@ import { CDP_CLEANUP_GRACE_MS, CDP_DISCOVERY_RESPONSE_TIMEOUT_MS, DEFAULT_CDP_COMMAND_TIMEOUT_MS, - MAX_BROWSER_DEADLINE_MS, selectedCdpCommandTimeoutMs, type CdpCommandDeadlinePhase, } from "../domain/browserDeadline.js"; @@ -50,9 +50,9 @@ const scenarioCommandDeadlineRecovery = ( ? `Browser launch and persistent-context startup exceeded its ${String(timeoutMs)} ms command_timeout_ms deadline (deadlineExpired). This is not the caller observation window, the ${String(CDP_DISCOVERY_RESPONSE_TIMEOUT_MS)} ms CDP discovery deadline, or the ${String(CDP_CLEANUP_GRACE_MS)} ms cleanup grace.` : cdpCommandDeadlineRecovery(timeoutMs, phase, method).userMessage; const increase = - timeoutMs < MAX_BROWSER_DEADLINE_MS - ? `Set command_timeout_ms in the capture-browser-scenario JSON above ${String(timeoutMs)} (integer milliseconds from 1 to ${String(MAX_BROWSER_DEADLINE_MS)}; omitted means ${String(DEFAULT_CDP_COMMAND_TIMEOUT_MS)}).` - : `command_timeout_ms is already at the maximum ${String(MAX_BROWSER_DEADLINE_MS)} ms; do not increase it further.`; + timeoutMs < MAX_NODE_TIMER_DELAY_MS + ? `Set command_timeout_ms in the capture-browser-scenario JSON above ${String(timeoutMs)} (integer milliseconds from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)}; omitted means ${String(DEFAULT_CDP_COMMAND_TIMEOUT_MS)}).` + : `command_timeout_ms is already at the maximum ${String(MAX_NODE_TIMER_DELAY_MS)} ms; do not increase it further.`; return { userMessage, remediationAction: `${increase} ${browserDeadlineRetry} command_timeout_ms does not raise the fixed protocol, retained-event, or source byte budgets, the ${String(CDP_DISCOVERY_RESPONSE_TIMEOUT_MS)} ms CDP discovery response deadline, or the ${String(CDP_CLEANUP_GRACE_MS)} ms cleanup grace. Those have no runtime override.`, diff --git a/src/config/debuggerSessionLimits.test.ts b/src/config/debuggerSessionLimits.test.ts index 7cbdd2a06b..8042122add 100644 --- a/src/config/debuggerSessionLimits.test.ts +++ b/src/config/debuggerSessionLimits.test.ts @@ -4,7 +4,6 @@ import { ConfigurationError } from "../domain/configurationErrors.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { DEFAULT_DEBUGGER_MAX_COMMAND_OUTPUT_BYTES, - MAXIMUM_DEBUGGER_COMMAND_DEADLINE_MS, MAXIMUM_DEBUGGER_MAX_COMMAND_OUTPUT_BYTES, MAXIMUM_DEBUGGER_MAX_PENDING_COMMANDS, MAXIMUM_DEBUGGER_MAX_SESSIONS, @@ -12,6 +11,7 @@ import { MINIMUM_DEBUGGER_MAX_COMMAND_OUTPUT_BYTES, MINIMUM_DEBUGGER_MAX_PENDING_COMMANDS, MINIMUM_DEBUGGER_MAX_SESSIONS, + MAX_NODE_TIMER_DELAY_MS, } from "../domain/analysisResourceLimits.js"; import { GdbSessionManager } from "../gdb/GdbSessionManager.js"; import { RizinDebugSessionManager } from "../rizin/RizinDebugSessionManager.js"; @@ -33,7 +33,7 @@ it("uses the shared defaults when the settings are unset", () => { value: 120_000, source: "default", minimum: MINIMUM_DEBUGGER_COMMAND_DEADLINE_MS, - maximum: MAXIMUM_DEBUGGER_COMMAND_DEADLINE_MS, + maximum: MAX_NODE_TIMER_DELAY_MS, unit: "ms", }); expect(parsed.value.maxSessions).toMatchObject({ @@ -93,7 +93,7 @@ it.each([ DEBUGGER_COMMAND_DEADLINE_SETTING, "0", MINIMUM_DEBUGGER_COMMAND_DEADLINE_MS, - MAXIMUM_DEBUGGER_COMMAND_DEADLINE_MS, + MAX_NODE_TIMER_DELAY_MS, 120_000, "ms", ], diff --git a/src/config/debuggerSessionLimits.ts b/src/config/debuggerSessionLimits.ts index b844eef219..2f58366fa1 100644 --- a/src/config/debuggerSessionLimits.ts +++ b/src/config/debuggerSessionLimits.ts @@ -6,7 +6,6 @@ import { DEFAULT_DEBUGGER_MAX_COMMAND_OUTPUT_BYTES, DEFAULT_DEBUGGER_MAX_PENDING_COMMANDS, DEFAULT_DEBUGGER_MAX_SESSIONS, - MAXIMUM_DEBUGGER_COMMAND_DEADLINE_MS, MAXIMUM_DEBUGGER_MAX_COMMAND_OUTPUT_BYTES, MAXIMUM_DEBUGGER_MAX_PENDING_COMMANDS, MAXIMUM_DEBUGGER_MAX_SESSIONS, @@ -14,6 +13,7 @@ import { MINIMUM_DEBUGGER_MAX_COMMAND_OUTPUT_BYTES, MINIMUM_DEBUGGER_MAX_PENDING_COMMANDS, MINIMUM_DEBUGGER_MAX_SESSIONS, + MAX_NODE_TIMER_DELAY_MS, } from "../domain/analysisResourceLimits.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; import { err, ok, type Result } from "../domain/result.js"; @@ -63,7 +63,7 @@ export const DEFAULT_DEBUGGER_COMMAND_DEADLINE: DebuggerAdmissionLimit = limit( DEBUGGER_COMMAND_DEADLINE_SETTING, DEFAULT_DEBUGGER_COMMAND_DEADLINE_MS, MINIMUM_DEBUGGER_COMMAND_DEADLINE_MS, - MAXIMUM_DEBUGGER_COMMAND_DEADLINE_MS, + MAX_NODE_TIMER_DELAY_MS, "ms", ); export const DEFAULT_DEBUGGER_MAX_SESSIONS_LIMIT: DebuggerAdmissionLimit = @@ -113,7 +113,7 @@ const debuggerMaxCommandOutputBytesConstraint = constraintFor( export const debuggerCommandDeadlineMsSchema = positiveDecimalIntegerSchema( MINIMUM_DEBUGGER_COMMAND_DEADLINE_MS, - MAXIMUM_DEBUGGER_COMMAND_DEADLINE_MS, + MAX_NODE_TIMER_DELAY_MS, debuggerCommandDeadlineConstraint, ); export const debuggerMaxSessionsSchema = positiveDecimalIntegerSchema( diff --git a/src/config/mcpStartupBudgets.test.ts b/src/config/mcpStartupBudgets.test.ts index cf5fbddb09..e6a01e7268 100644 --- a/src/config/mcpStartupBudgets.test.ts +++ b/src/config/mcpStartupBudgets.test.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { expect, it } from "vitest"; import { ConfigurationError } from "../domain/configurationErrors.js"; @@ -5,7 +6,6 @@ import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { parseEnvironment } from "./environment.js"; import { MCP_PHASE_BUDGET_FLOOR_MS, - MCP_PHASE_BUDGET_MAXIMUM_MS, parseMcpStartupBudgets, resolveMcpStartupBudgets, } from "./mcpStartupBudgets.js"; @@ -67,7 +67,7 @@ it("uses valid phase budget overrides", () => { REA_MCP_INITIALIZE_BUDGET_MS: "16000", REA_MCP_TOOLS_LIST_BUDGET_MS: "6000", REA_MCP_FIRST_CATALOG_BUDGET_MS: "21000", - REA_MCP_DOCTOR_DEADLINE_MS: String(MCP_PHASE_BUDGET_MAXIMUM_MS), + REA_MCP_DOCTOR_DEADLINE_MS: String(MAX_NODE_TIMER_DELAY_MS), }), ).toEqual({ ok: true, @@ -108,7 +108,7 @@ it.each([ ["REA_MCP_INITIALIZE_BUDGET_MS", " 15000"], ["REA_MCP_TOOLS_LIST_BUDGET_MS", "5000 "], ["REA_MCP_FIRST_CATALOG_BUDGET_MS", "1.5"], - ["REA_MCP_DOCTOR_DEADLINE_MS", String(MCP_PHASE_BUDGET_MAXIMUM_MS + 1)], + ["REA_MCP_DOCTOR_DEADLINE_MS", String(MAX_NODE_TIMER_DELAY_MS + 1)], ["REA_MCP_INITIALIZE_BUDGET_MS", "9".repeat(40)], ])("rejects invalid %s=%j as a configuration error", (setting, value) => { const parsed = parseMcpStartupBudgets({ [setting]: value }); @@ -120,7 +120,7 @@ it.each([ expect(constraint).toContain(setting); expect(constraint).toContain("positive decimal integer"); expect(constraint).toContain( - `from ${String(MCP_PHASE_BUDGET_FLOOR_MS)} to ${String(MCP_PHASE_BUDGET_MAXIMUM_MS)} ms`, + `from ${String(MCP_PHASE_BUDGET_FLOOR_MS)} to ${String(MAX_NODE_TIMER_DELAY_MS)} ms`, ); expect(parsed.error.message).toBe(constraint); const startup = parseEnvironment({ [setting]: value }); diff --git a/src/config/mcpStartupBudgets.ts b/src/config/mcpStartupBudgets.ts index cf62a3c56c..b38356784d 100644 --- a/src/config/mcpStartupBudgets.ts +++ b/src/config/mcpStartupBudgets.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { positiveDecimalIntegerSchema } from "./positiveDecimalInteger.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; @@ -6,13 +7,6 @@ import { err, ok, type Result } from "../domain/result.js"; /** Smallest phase budget. Zero is not a deadline, and Node's timer needs a positive delay. */ export const MCP_PHASE_BUDGET_FLOOR_MS = 1; -/** - * Largest delay Node schedules exactly. A `setTimeout` delay above this - * signed 32-bit bound is clamped to 1 ms, so a phase budget past it would - * expire immediately. The setting stops here instead of growing without a bound. - */ -export const MCP_PHASE_BUDGET_MAXIMUM_MS = 2_147_483_647; - /** One MCP startup phase budget and where its effective milliseconds came from. */ export interface McpPhaseBudget { readonly setting: string; @@ -67,12 +61,12 @@ const PHASES = [ ] as const satisfies readonly McpPhaseBudgetDefinition[]; const phaseConstraint = (phase: McpPhaseBudgetDefinition): string => - `${phase.setting} must be a positive decimal integer from ${String(MCP_PHASE_BUDGET_FLOOR_MS)} to ${String(MCP_PHASE_BUDGET_MAXIMUM_MS)} ms; the default is ${String(phase.defaultMilliseconds)} ms. Node schedules a delay above that maximum as 1 ms, so a larger value is refused.`; + `${phase.setting} must be a positive decimal integer from ${String(MCP_PHASE_BUDGET_FLOOR_MS)} to ${String(MAX_NODE_TIMER_DELAY_MS)} ms; the default is ${String(phase.defaultMilliseconds)} ms. Node schedules a delay above that maximum as 1 ms, so a larger value is refused.`; const phaseBudgetSchema = (phase: McpPhaseBudgetDefinition) => positiveDecimalIntegerSchema( MCP_PHASE_BUDGET_FLOOR_MS, - MCP_PHASE_BUDGET_MAXIMUM_MS, + MAX_NODE_TIMER_DELAY_MS, phaseConstraint(phase), ); @@ -95,7 +89,7 @@ const defaultBudget = (phase: McpPhaseBudgetDefinition): McpPhaseBudget => ({ source: "default", defaultMilliseconds: phase.defaultMilliseconds, floorMilliseconds: MCP_PHASE_BUDGET_FLOOR_MS, - maximumMilliseconds: MCP_PHASE_BUDGET_MAXIMUM_MS, + maximumMilliseconds: MAX_NODE_TIMER_DELAY_MS, }); const parsePhaseBudget = ( @@ -112,7 +106,7 @@ const parsePhaseBudget = ( source: "setting", defaultMilliseconds: phase.defaultMilliseconds, floorMilliseconds: MCP_PHASE_BUDGET_FLOOR_MS, - maximumMilliseconds: MCP_PHASE_BUDGET_MAXIMUM_MS, + maximumMilliseconds: MAX_NODE_TIMER_DELAY_MS, }) : err( new ConfigurationError(phaseConstraint(phase), { diff --git a/src/config/providerStartupTimeout.ts b/src/config/providerStartupTimeout.ts index 6fc9d922cf..ddc80c30d3 100644 --- a/src/config/providerStartupTimeout.ts +++ b/src/config/providerStartupTimeout.ts @@ -1,6 +1,6 @@ import { - MAX_NODE_TIMER_DELAY_MS, MAX_GHIDRA_DECOMPILE_TIMEOUT_SECONDS, + timerDurationMsSchema, } from "../domain/analysisResourceLimits.js"; import { z } from "zod"; @@ -20,4 +20,4 @@ export const providerStartupTimeoutSchema = z .string() .regex(/^[1-9]\d*$/u, "must be a positive decimal integer") .transform(Number) - .pipe(z.int().min(1).max(MAX_NODE_TIMER_DELAY_MS)); + .pipe(timerDurationMsSchema); diff --git a/src/config/regexMatchingDeadline.test.ts b/src/config/regexMatchingDeadline.test.ts index 10181d2243..10e8e77220 100644 --- a/src/config/regexMatchingDeadline.test.ts +++ b/src/config/regexMatchingDeadline.test.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { expect, it, vi } from "vitest"; import { HopperProvider } from "../hopper/HopperProvider.js"; @@ -18,7 +19,6 @@ import { regexMatchingDeadlineContinuingRecovery, regexMatchingDeadlineRecovery, } from "./regexMatchingDeadline.js"; -import { MAXIMUM_REGEX_MATCHING_DEADLINE_MS } from "../domain/analysisResourceLimits.js"; const configured = (deadlineMs: number) => ({ deadlineMs, source: "setting" }) as const; @@ -48,7 +48,7 @@ it("keeps the 5000 ms deadline when the setting is unset", () => { effective_value: 5000, unit: "ms", minimum: 1, - maximum: MAXIMUM_REGEX_MATCHING_DEADLINE_MS, + maximum: MAX_NODE_TIMER_DELAY_MS, source: "default", applies_at: "next_operation", agent_editable: true, @@ -87,11 +87,9 @@ it("uses a valid REA_REGEX_MATCHING_DEADLINE_MS override", () => { ok: true, value: configured(10_000), }); - expect( - parseRegexMatchingDeadline(String(MAXIMUM_REGEX_MATCHING_DEADLINE_MS)), - ).toEqual({ + expect(parseRegexMatchingDeadline(String(MAX_NODE_TIMER_DELAY_MS))).toEqual({ ok: true, - value: configured(MAXIMUM_REGEX_MATCHING_DEADLINE_MS), + value: configured(MAX_NODE_TIMER_DELAY_MS), }); const parsed = parseConfig({ REA_REGEX_MATCHING_DEADLINE_MS: "10000" }); if (!parsed.ok) throw new Error("valid deadline was rejected"); @@ -138,7 +136,7 @@ it.each([ " 5000", "5000 ", "1.5", - String(MAXIMUM_REGEX_MATCHING_DEADLINE_MS + 1), + String(MAX_NODE_TIMER_DELAY_MS + 1), "9".repeat(40), ])("rejects invalid %j as a configuration error", (value) => { const parsed = parseRegexMatchingDeadline(value); diff --git a/src/config/regexMatchingDeadline.ts b/src/config/regexMatchingDeadline.ts index 0afdd56f46..8ce3ec4403 100644 --- a/src/config/regexMatchingDeadline.ts +++ b/src/config/regexMatchingDeadline.ts @@ -1,6 +1,6 @@ import { DEFAULT_REGEX_MATCHING_DEADLINE_MS, - MAXIMUM_REGEX_MATCHING_DEADLINE_MS, + MAX_NODE_TIMER_DELAY_MS, } from "../domain/analysisResourceLimits.js"; import { positiveDecimalIntegerSchema } from "./positiveDecimalInteger.js"; @@ -21,12 +21,12 @@ export const DEFAULT_REGEX_MATCHING_DEADLINE: RegexMatchingDeadline = { source: "default", }; -const regexMatchingDeadlineConstraint = `${REGEX_MATCHING_DEADLINE_SETTING} must be a positive decimal integer from 1 to ${String(MAXIMUM_REGEX_MATCHING_DEADLINE_MS)} ms; the default is ${String(DEFAULT_REGEX_MATCHING_DEADLINE_MS)} ms. Node schedules a delay above that maximum as 1 ms, so a larger value is refused.`; +const regexMatchingDeadlineConstraint = `${REGEX_MATCHING_DEADLINE_SETTING} must be a positive decimal integer from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)} ms; the default is ${String(DEFAULT_REGEX_MATCHING_DEADLINE_MS)} ms. Node schedules a delay above that maximum as 1 ms, so a larger value is refused.`; /** Optional decimal millisecond count for the supervised regex matching deadline. */ export const regexMatchingDeadlineMsSchema = positiveDecimalIntegerSchema( 1, - MAXIMUM_REGEX_MATCHING_DEADLINE_MS, + MAX_NODE_TIMER_DELAY_MS, regexMatchingDeadlineConstraint, ); @@ -69,7 +69,7 @@ export const resolveRegexMatchingDeadline = ( }; const regexMatchingDeadlineFacts = (deadline: RegexMatchingDeadline): string => - `The effective ${REGEX_MATCHING_DEADLINE_SETTING} value is ${String(deadline.deadlineMs)} ms (source ${deadline.source}; default ${String(DEFAULT_REGEX_MATCHING_DEADLINE_MS)} ms, floor 1 ms, maximum ${String(MAXIMUM_REGEX_MATCHING_DEADLINE_MS)} ms).`; + `The effective ${REGEX_MATCHING_DEADLINE_SETTING} value is ${String(deadline.deadlineMs)} ms (source ${deadline.source}; default ${String(DEFAULT_REGEX_MATCHING_DEADLINE_MS)} ms, floor 1 ms, maximum ${String(MAX_NODE_TIMER_DELAY_MS)} ms).`; /** Recovery after this REA process has exited. The next invocation reads the launch seed. */ export const regexMatchingDeadlineRecovery = ( @@ -77,7 +77,7 @@ export const regexMatchingDeadlineRecovery = ( ): string => [ regexMatchingDeadlineFacts(deadline), - `Set ${REGEX_MATCHING_DEADLINE_SETTING} in the environment that starts the next REA invocation. It must be a positive decimal integer from 1 to ${String(MAXIMUM_REGEX_MATCHING_DEADLINE_MS)}.`, + `Set ${REGEX_MATCHING_DEADLINE_SETTING} in the environment that starts the next REA invocation. It must be a positive decimal integer from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)}.`, "The worker old-generation heap does not raise this deadline.", ].join(" "); diff --git a/src/domain/analysisErrorProjection.test.ts b/src/domain/analysisErrorProjection.test.ts index 1d410fa164..d94a78c554 100644 --- a/src/domain/analysisErrorProjection.test.ts +++ b/src/domain/analysisErrorProjection.test.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "./analysisResourceLimits.js"; import { describe, expect, it } from "vitest"; import { AnalysisCapabilityUnavailableError, @@ -25,7 +26,6 @@ import { import { DEFAULT_HOPPER_DEMO_DIALOG_TIMEOUT_MS, HOPPER_DEMO_DIALOG_TIMEOUT_SETTING, - MAXIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS, MINIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS, type DialogTimeoutRejection, type HopperStartupFailureDiagnostic, @@ -998,7 +998,7 @@ describe("analysis error projection: Hopper startup failures", () => { value: "-5", source: "setting", minimum_ms: MINIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS, - maximum_ms: MAXIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS, + maximum_ms: MAX_NODE_TIMER_DELAY_MS, default_ms: DEFAULT_HOPPER_DEMO_DIALOG_TIMEOUT_MS, } satisfies DialogTimeoutRejection; const projected = projectAnalysisError( diff --git a/src/domain/analysisResourceLimits.ts b/src/domain/analysisResourceLimits.ts index 12efba352c..38fbdbff57 100644 --- a/src/domain/analysisResourceLimits.ts +++ b/src/domain/analysisResourceLimits.ts @@ -1,3 +1,5 @@ +import { z } from "zod"; + /** Numeric admission contracts shared by environment parsing and runtime tools. * Timer maxima follow signed 32-bit scheduling. ASAR's 256 MiB maximum and * worker 16 GiB maxima are REA policies, not claims about format/host capacity. @@ -55,11 +57,22 @@ export const DEFAULT_HOPPER_CALLER_SCAN_BUDGET_MS = 2_000; export const MINIMUM_HOPPER_CALLER_SCAN_BUDGET_MS = 1; /** - * Largest delay Node schedules exactly. Delays above this signed 32-bit - * boundary become a 1 ms timer, so startup and swiftc timeouts stop here. + * Largest delay Node schedules exactly. A `setTimeout` delay above this signed + * 32-bit bound is clamped to 1 ms, so a deadline past it would expire + * immediately. Every millisecond duration REA hands to a timer stops here; + * this is the only declaration of that bound. */ export const MAX_NODE_TIMER_DELAY_MS = 2_147_483_647; +/** + * A positive whole-millisecond duration Node can schedule exactly. Zero and + * negative values are not a deadline. + */ +export const timerDurationMsSchema = z + .int() + .min(1) + .max(MAX_NODE_TIMER_DELAY_MS); + /** * Ghidra 12.1.4 converts whole seconds to a signed int millisecond delay. * Keep that multiplication positive and exact rather than imposing a day cap. @@ -71,15 +84,6 @@ export const MAX_GHIDRA_DECOMPILE_TIMEOUT_SECONDS = Math.floor( /** Matching deadline used when the setting is unset. Today's fixed constant. */ export const DEFAULT_REGEX_MATCHING_DEADLINE_MS = 5_000; -/** - * Largest delay Node schedules exactly. A `setTimeout` delay above this - * signed 32-bit bound is clamped to 1 ms, so a matching deadline past it - * would expire immediately. The setting stops here instead of growing - * without a bound. The floor is 1 ms: zero and negative values are not a - * deadline. - */ -export const MAXIMUM_REGEX_MATCHING_DEADLINE_MS = 2_147_483_647; - /** Worker old-generation request used when the setting is unset. Today's constant. */ export const DEFAULT_REGEX_WORKER_HEAP_REQUEST_MIB = 128; @@ -127,13 +131,8 @@ export const DEFAULT_JADX_OPERATION_TIMEOUT_MS = 120_000; */ export const DEFAULT_DEBUGGER_COMMAND_DEADLINE_MS = 120_000; -/** - * Smallest command deadline. Zero is not a deadline. The maximum is the - * largest delay Node schedules exactly; a `setTimeout` delay above that - * signed 32-bit bound becomes 1 ms. - */ +/** Smallest command deadline. Zero is not a deadline; the maximum is MAX_NODE_TIMER_DELAY_MS. */ export const MINIMUM_DEBUGGER_COMMAND_DEADLINE_MS = 1; -export const MAXIMUM_DEBUGGER_COMMAND_DEADLINE_MS = 2_147_483_647; /** Debugger sessions admitted when the setting is unset. Today's constant. */ export const DEFAULT_DEBUGGER_MAX_SESSIONS = 8; diff --git a/src/domain/analysisSettingDefinitions.ts b/src/domain/analysisSettingDefinitions.ts index 5db2581cea..f1c83a0246 100644 --- a/src/domain/analysisSettingDefinitions.ts +++ b/src/domain/analysisSettingDefinitions.ts @@ -19,7 +19,6 @@ import { MAX_NODE_TIMER_DELAY_MS, MAX_GHIDRA_DECOMPILE_TIMEOUT_SECONDS, DEFAULT_REGEX_MATCHING_DEADLINE_MS, - MAXIMUM_REGEX_MATCHING_DEADLINE_MS, DEFAULT_REGEX_WORKER_HEAP_REQUEST_MIB, MINIMUM_REGEX_WORKER_HEAP_REQUEST_MIB, MAXIMUM_REGEX_WORKER_HEAP_REQUEST_MIB, @@ -37,7 +36,6 @@ import { MAXIMUM_BRIDGE_MAX_REQUEST_BYTES, DEFAULT_DEBUGGER_COMMAND_DEADLINE_MS, MINIMUM_DEBUGGER_COMMAND_DEADLINE_MS, - MAXIMUM_DEBUGGER_COMMAND_DEADLINE_MS, DEFAULT_DEBUGGER_MAX_COMMAND_OUTPUT_BYTES, MINIMUM_DEBUGGER_MAX_COMMAND_OUTPUT_BYTES, MAXIMUM_DEBUGGER_MAX_COMMAND_OUTPUT_BYTES, @@ -60,10 +58,7 @@ import { JAVASCRIPT_WORKER_HEAP_MIB_MINIMUM, JAVASCRIPT_WORKER_HEAP_MIB_MAXIMUM, } from "./javascript/javascriptAnalysisResourceControls.js"; -import { - DEFAULT_WASM_COMMAND_TIMEOUT_MS, - MAX_WASM_COMMAND_TIMEOUT_MS, -} from "./wasm/wasmArtifact.js"; +import { DEFAULT_WASM_COMMAND_TIMEOUT_MS } from "./wasm/wasmArtifact.js"; interface SettingDefinition { readonly environment?: string; readonly defaultValue: number | null; @@ -296,7 +291,7 @@ export const ANALYSIS_SETTINGS = { ...timer, environment: "REA_REGEX_MATCHING_DEADLINE_MS", defaultValue: DEFAULT_REGEX_MATCHING_DEADLINE_MS, - maximum: MAXIMUM_REGEX_MATCHING_DEADLINE_MS, + maximum: MAX_NODE_TIMER_DELAY_MS, provider: "regex", relatedProviders: ["ida", "hopper", "kuna"], operations: ["search_strings", "search_procedures"], @@ -358,7 +353,7 @@ export const ANALYSIS_SETTINGS = { updateMode: "runtime", ...timer, defaultValue: DEFAULT_WASM_COMMAND_TIMEOUT_MS, - maximum: MAX_WASM_COMMAND_TIMEOUT_MS, + maximum: MAX_NODE_TIMER_DELAY_MS, provider: "wabt-artifact", operations: ["inspect_wasm_artifact"], parameter: "command_timeout_ms", @@ -442,7 +437,7 @@ export const ANALYSIS_SETTINGS = { environment: "REA_DEBUGGER_COMMAND_DEADLINE_MS", defaultValue: DEFAULT_DEBUGGER_COMMAND_DEADLINE_MS, minimum: MINIMUM_DEBUGGER_COMMAND_DEADLINE_MS, - maximum: MAXIMUM_DEBUGGER_COMMAND_DEADLINE_MS, + maximum: MAX_NODE_TIMER_DELAY_MS, provider: "gdb", relatedProviders: ["rizin"], operations: [ diff --git a/src/domain/apktool/apktoolResourceAnalysis.test.ts b/src/domain/apktool/apktoolResourceAnalysis.test.ts index 2e8c666197..ce856aa983 100644 --- a/src/domain/apktool/apktoolResourceAnalysis.test.ts +++ b/src/domain/apktool/apktoolResourceAnalysis.test.ts @@ -1,10 +1,10 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../analysisResourceLimits.js"; import { expect, it } from "vitest"; import { androidLocaleDirectorySuffix, apktoolInputSchemas, classifyAndroidStringsTable, DEFAULT_APKTOOL_DECODE_TIMEOUT_MS, - MAX_APKTOOL_DECODE_TIMEOUT_MS, } from "./apktoolResourceAnalysis.js"; it.each([ @@ -101,7 +101,7 @@ it("keeps 600000 ms as the omitted apktool decode deadline", () => { ); }); -it.each([1, 600_000, MAX_APKTOOL_DECODE_TIMEOUT_MS])( +it.each([1, 600_000, MAX_NODE_TIMER_DELAY_MS])( "accepts decode_timeout_ms %s", (decode_timeout_ms) => { expect( @@ -110,7 +110,7 @@ it.each([1, 600_000, MAX_APKTOOL_DECODE_TIMEOUT_MS])( }, ); -it.each([0, -1, 1.5, MAX_APKTOOL_DECODE_TIMEOUT_MS + 1])( +it.each([0, -1, 1.5, MAX_NODE_TIMER_DELAY_MS + 1])( "rejects decode_timeout_ms %s", (decode_timeout_ms) => { expect( diff --git a/src/domain/apktool/apktoolResourceAnalysis.ts b/src/domain/apktool/apktoolResourceAnalysis.ts index 71f8a30b99..852c570199 100644 --- a/src/domain/apktool/apktoolResourceAnalysis.ts +++ b/src/domain/apktool/apktoolResourceAnalysis.ts @@ -1,3 +1,4 @@ +import { timerDurationMsSchema } from "../analysisResourceLimits.js"; import { z } from "zod"; import { localPathStringSchema } from "../localPath.js"; import { digestSchema } from "../digests.js"; @@ -9,8 +10,6 @@ export const DEFAULT_APKTOOL_STRING_TABLE_BYTES = 8 * 1024 * 1024; export const DEFAULT_APKTOOL_TOTAL_STRING_TABLE_BYTES = 32 * 1024 * 1024; /** Decode wall clock used when decode_timeout_ms is omitted. */ export const DEFAULT_APKTOOL_DECODE_TIMEOUT_MS = 600_000; -/** Largest delay supported without overflowing Node timers. */ -export const MAX_APKTOOL_DECODE_TIMEOUT_MS = 2_147_483_647; const ANDROID_NON_LOCALE_QUALIFIERS = new Set([ "car", "desk", @@ -129,11 +128,7 @@ export const apktoolInputSchemas = { .describe( `Project multiple localized string tables from res/values-/strings.xml alongside the default table (up to ${String(MAX_SELECTED_LOCALES)} locales per call; split larger selections into separate calls and verify target.sha256)`, ), - decode_timeout_ms: z - .number() - .int() - .min(1) - .max(MAX_APKTOOL_DECODE_TIMEOUT_MS) + decode_timeout_ms: timerDurationMsSchema .exactOptional() .describe( `Decode wall-clock budget in milliseconds (default ${String(DEFAULT_APKTOOL_DECODE_TIMEOUT_MS)}), from apktool d start through process exit. Omitted means ${String(DEFAULT_APKTOOL_DECODE_TIMEOUT_MS)}. Applies on the next decode. Does not raise the fixed output capture allowance or the version probe.`, diff --git a/src/domain/browserDeadline.ts b/src/domain/browserDeadline.ts index 9925733ac3..f0115e4806 100644 --- a/src/domain/browserDeadline.ts +++ b/src/domain/browserDeadline.ts @@ -1,10 +1,10 @@ -import { z } from "zod"; +import { + MAX_NODE_TIMER_DELAY_MS, + timerDurationMsSchema, +} from "./analysisResourceLimits.js"; import type { BrowserObservationOperation } from "./browserObservationErrors.js"; -/** Largest delay supported without overflowing Node timers. */ -export const MAX_BROWSER_DEADLINE_MS = 2_147_483_647; - /** * CDP command and WebSocket handshake deadline. Discovery and cleanup grace * are separate phases and stay fixed. @@ -19,13 +19,7 @@ export const CDP_CLEANUP_GRACE_MS = 5_000; /** Optional caller deadline. An omitted field stays absent in Evidence. */ export const optionalBrowserDeadlineMs = (description: string) => - z - .number() - .int() - .min(1) - .max(MAX_BROWSER_DEADLINE_MS) - .optional() - .describe(description); + timerDurationMsSchema.optional().describe(description); export const selectedBrowserDeadlineMs = ( selected: number | undefined, @@ -38,9 +32,9 @@ export const browserDeadlineIncrease = ( defaultMs: number, cli: string, ): string => - timeoutMs < MAX_BROWSER_DEADLINE_MS - ? `Increase ${key} above ${String(timeoutMs)} (integer milliseconds from 1 to ${String(MAX_BROWSER_DEADLINE_MS)}; omitted means ${String(defaultMs)}), or use ${cli} on the CLI.` - : `${key} is already at the maximum ${String(MAX_BROWSER_DEADLINE_MS)} ms; do not increase it further.`; + timeoutMs < MAX_NODE_TIMER_DELAY_MS + ? `Increase ${key} above ${String(timeoutMs)} (integer milliseconds from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)}; omitted means ${String(defaultMs)}), or use ${cli} on the CLI.` + : `${key} is already at the maximum ${String(MAX_NODE_TIMER_DELAY_MS)} ms; do not increase it further.`; export const browserDeadlineRetry = "Applies on the next call. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying."; diff --git a/src/domain/browserScenarioValues.ts b/src/domain/browserScenarioValues.ts index e6edf5fbfc..e60745c4e4 100644 --- a/src/domain/browserScenarioValues.ts +++ b/src/domain/browserScenarioValues.ts @@ -1,3 +1,4 @@ +import { timerDurationMsSchema } from "./analysisResourceLimits.js"; import { z } from "zod"; import { IDENTIFIER_PATTERN } from "./stringPatterns.js"; @@ -349,15 +350,9 @@ const locatorSchema = z.discriminatedUnion("kind", [ }), ]); -// Playwright forwards these intervals to Node timers. -const MAX_BROWSER_SCENARIO_TIMEOUT_MS = 2_147_483_647; - const stepBase = { step_id: scenarioIdentifierSchema, - timeout_ms: z - .int() - .min(1) - .max(MAX_BROWSER_SCENARIO_TIMEOUT_MS) + timeout_ms: timerDurationMsSchema .optional() .describe( "Optional action deadline in milliseconds; omitted means wait until completion or request cancellation.", @@ -452,13 +447,9 @@ export const browserScenarioActionSchema = z.discriminatedUnion("action", [ z.strictObject({ step_id: scenarioIdentifierSchema, action: z.literal("wait_for_timeout"), - duration_ms: z - .int() - .min(1) - .max(MAX_BROWSER_SCENARIO_TIMEOUT_MS) - .describe( - "Wait this many milliseconds; the wait ends early on cancellation.", - ), + duration_ms: timerDurationMsSchema.describe( + "Wait this many milliseconds; the wait ends early on cancellation.", + ), }), ]); export type BrowserScenarioAction = z.infer; diff --git a/src/domain/captures/packetCapture.ts b/src/domain/captures/packetCapture.ts index bfb51a654a..235e8513f6 100644 --- a/src/domain/captures/packetCapture.ts +++ b/src/domain/captures/packetCapture.ts @@ -11,6 +11,9 @@ import { } from "../localPath.js"; const argument = processArgumentSchema.min(1).max(8192); +/** TShark parses `-c` as a C `int` packet count; this is not a timer delay. */ +const MAX_TSHARK_PACKET_COUNT = 2_147_483_647; + const captureInputShape = z.strictObject({ producer_limits: boundedProducerLimitsSchema, path: localPathStringSchema.describe("Absolute local capture path"), @@ -36,7 +39,7 @@ const captureInputShape = z.strictObject({ .number() .int() .positive() - .max(2147483647) + .max(MAX_TSHARK_PACKET_COUNT) .nullable() .default(null) .describe( diff --git a/src/domain/evm/evmInterface.ts b/src/domain/evm/evmInterface.ts index 9612c5f6ed..f2266e4882 100644 --- a/src/domain/evm/evmInterface.ts +++ b/src/domain/evm/evmInterface.ts @@ -1,3 +1,7 @@ +import { + MAX_NODE_TIMER_DELAY_MS, + timerDurationMsSchema, +} from "../analysisResourceLimits.js"; import { z } from "zod"; import { absoluteLocalPathStringSchema } from "../localPath.js"; @@ -43,8 +47,6 @@ const byteOffset = z.int().nonnegative(); const sha256 = z.string().regex(/^[a-f0-9]{64}$/); /** Owned EVMole worker deadline. Omission keeps this value. */ export const DEFAULT_EVM_TIMEOUT_MS = 30_000; -/** Largest delay supported without overflowing Node timers. */ -export const MAX_EVM_TIMEOUT_MS = 2_147_483_647; /** Select the carrier representation explicitly; no RPC or deployed-contract lookup is implied. */ export const inspectEvmInterfaceInputSchema = z.strictObject({ @@ -61,14 +63,10 @@ export const inspectEvmInterfaceInputSchema = z.strictObject({ .describe( "Per-call carrier/reply/diagnostic bytes, address-space/file bytes and CPU seconds. Omission preserves documented defaults; omitted file_bytes follows selected output_bytes. Tighter inherited Linux limits remain enforced. timeout_ms and the 256 MiB worker heap are independent.", ), - timeout_ms: z - .number() - .int() - .min(1) - .max(MAX_EVM_TIMEOUT_MS) + timeout_ms: timerDurationMsSchema .optional() .describe( - `Deadline in milliseconds for the owned EVMole worker command (default ${String(DEFAULT_EVM_TIMEOUT_MS)}), not carrier acquisition or final reply reads. An integer from 1 to ${String(MAX_EVM_TIMEOUT_MS)} applies on the next call. Does not raise the separately selected producer_limits or the 256 MiB worker heap.`, + `Deadline in milliseconds for the owned EVMole worker command (default ${String(DEFAULT_EVM_TIMEOUT_MS)}), not carrier acquisition or final reply reads. An integer from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)} applies on the next call. Does not raise the separately selected producer_limits or the 256 MiB worker heap.`, ), }); diff --git a/src/domain/firmware/firmwareAnalysis.ts b/src/domain/firmware/firmwareAnalysis.ts index d7e3801d23..81de10662c 100644 --- a/src/domain/firmware/firmwareAnalysis.ts +++ b/src/domain/firmware/firmwareAnalysis.ts @@ -1,3 +1,4 @@ +import { timerDurationMsSchema } from "../analysisResourceLimits.js"; import { z } from "zod"; import { digestSchema } from "../digests.js"; import { jsonValueSchema, type JsonValue } from "../jsonValue.js"; @@ -7,20 +8,17 @@ const bytes = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER); const range = z.strictObject({ offset: bytes, length: bytes.positive() }); /** Default analysis phase budget, excluding queue admission and publication. */ export const DEFAULT_FIRMWARE_ANALYSIS_TIMEOUT_MS = 120_000; -/** Largest delay supported without overflowing Node timers. */ -export const MAX_FIRMWARE_TIMEOUT_MS = 2_147_483_647; /** Largest staging file-byte budget the schema accepts. */ export const MAX_FIRMWARE_STAGING_BYTES = 512 * 1024 * 1024; /** Largest staging entry budget the schema accepts. */ export const MAX_FIRMWARE_STAGING_ENTRIES = 100_000; /** Largest extraction depth the input contract accepts. */ export const MAX_FIRMWARE_EXTRACTION_DEPTH = 10; -const timeout = z.number().int().min(1).max(MAX_FIRMWARE_TIMEOUT_MS); const target = { path: absoluteLocalPathStringSchema.describe( "Absolute local firmware file; never executed. Relative paths are rejected.", ), - analysis_timeout_ms: timeout + analysis_timeout_ms: timerDurationMsSchema .optional() .describe( "Analysis wall-clock budget in milliseconds (default 120000), from tool resolution through inspection and its final workspace cleanup, or extraction through inventory. Excludes queue admission and extraction publication. Does not raise fixed CPU, memory or byte limits.", @@ -61,7 +59,7 @@ export const firmwareInputSchemas = { .max(MAX_FIRMWARE_STAGING_ENTRIES) .default(10_000) .describe("Staging entry budget, including directories and links"), - publication_timeout_ms: timeout + publication_timeout_ms: timerDurationMsSchema .default(120_000) .describe( "Publication and final cleanup budget in milliseconds, started after extraction and inventory; increase for a slow destination", @@ -100,7 +98,7 @@ const engine = z.strictObject({ }); /** Small execution metadata contract; historical omissions remain unknown. */ export const firmwareExecutionBudgetSchema = z.object({ - analysis_timeout_ms: timeout + analysis_timeout_ms: timerDurationMsSchema .exactOptional() .describe( "Actual analysis phase budget in milliseconds; absent in historical Evidence means unknown", diff --git a/src/domain/hopperStartupFailure.ts b/src/domain/hopperStartupFailure.ts index b9c8340ef8..185f89cbc9 100644 --- a/src/domain/hopperStartupFailure.ts +++ b/src/domain/hopperStartupFailure.ts @@ -15,19 +15,13 @@ export const DEFAULT_HOPPER_DEMO_DIALOG_TIMEOUT_MS = 10_000; /** Smallest accepted dialog watch. Zero is not a deadline. */ export const MINIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS = 1; -/** - * Largest accepted dialog watch. Delays above this signed 32-bit bound are - * the same ceiling REA uses for its other millisecond settings. - */ -export const MAXIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS = MAX_NODE_TIMER_DELAY_MS; - /** Rejected dialog-timeout setting retained with the adapter diagnostic. */ export type DialogTimeoutRejection = { readonly setting: typeof HOPPER_DEMO_DIALOG_TIMEOUT_SETTING; readonly value: string; readonly source: "setting"; readonly minimum_ms: typeof MINIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS; - readonly maximum_ms: typeof MAXIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS; + readonly maximum_ms: typeof MAX_NODE_TIMER_DELAY_MS; readonly default_ms: typeof DEFAULT_HOPPER_DEMO_DIALOG_TIMEOUT_MS; }; @@ -40,7 +34,7 @@ export const invalidDialogTimeoutMessage = ( ? "was rejected" : `is ${JSON.stringify(setting.value)} ms`; const floor = String(MINIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS); - const maximum = String(MAXIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS); + const maximum = String(MAX_NODE_TIMER_DELAY_MS); const source = setting?.source ?? "setting"; return [ `The effective ${HOPPER_DEMO_DIALOG_TIMEOUT_SETTING} value ${current} (source ${source}; default ${String(DEFAULT_HOPPER_DEMO_DIALOG_TIMEOUT_MS)} ms, floor ${floor} ms, maximum ${maximum} ms).`, @@ -183,8 +177,7 @@ const isDialogTimeoutRejection = ( source === "setting" && Reflect.get(value, "minimum_ms") === MINIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS && - Reflect.get(value, "maximum_ms") === - MAXIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS && + Reflect.get(value, "maximum_ms") === MAX_NODE_TIMER_DELAY_MS && Reflect.get(value, "default_ms") === DEFAULT_HOPPER_DEMO_DIALOG_TIMEOUT_MS ); }; diff --git a/src/domain/javascript/javascriptAnalysisResourceControls.ts b/src/domain/javascript/javascriptAnalysisResourceControls.ts index 7a6c7c4401..7816aceb9e 100644 --- a/src/domain/javascript/javascriptAnalysisResourceControls.ts +++ b/src/domain/javascript/javascriptAnalysisResourceControls.ts @@ -1,3 +1,4 @@ +import { timerDurationMsSchema } from "../analysisResourceLimits.js"; import { JAVASCRIPT_SEMANTIC_PRECISION_DEFAULTS, javaScriptSemanticPrecisionSchema, @@ -258,11 +259,7 @@ export const javaScriptAnalysisResourceControlsSchema = z.strictObject({ .describe( "Maximum V8 old-space heap in MiB for the isolated JavaScript source analyzer; defaults to 1024. This does not change the CLI/MCP process heap. When REA runs on Bun, which ignores V8 heap flags, Windows instead limits the analyzer's committed memory to this budget plus a 512 MiB runtime reserve; other Bun hosts enforce no limit.", ), - analysis_timeout_ms: z - .number() - .int() - .min(1) - .max(2_147_483_647) + analysis_timeout_ms: timerDurationMsSchema .optional() .describe( "Maximum startup, analysis and transfer time per JavaScript source, in milliseconds; defaults to 300000. On timeout, return collected partial Evidence and stop the analysis.", diff --git a/src/domain/native/nativeDeadlines.test.ts b/src/domain/native/nativeDeadlines.test.ts index 01b4c71465..50afae3354 100644 --- a/src/domain/native/nativeDeadlines.test.ts +++ b/src/domain/native/nativeDeadlines.test.ts @@ -1,10 +1,10 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../analysisResourceLimits.js"; import { expect, it } from "vitest"; import { DEFAULT_NATIVE_COMMAND_TIMEOUT_MS, DEFAULT_NATIVE_UI_DEADLINE_MS, DEFAULT_PWNTOOLS_TIMEOUT_MS, - MAX_NATIVE_TIMER_MS, nativeCommandTimeoutField, nativeUiDeadlineField, pwntoolsTimeoutField, @@ -15,7 +15,7 @@ it("keeps today's omitted native deadlines and the shared timer range", () => { expect(DEFAULT_NATIVE_COMMAND_TIMEOUT_MS).toBe(60_000); expect(DEFAULT_NATIVE_UI_DEADLINE_MS).toBe(180_000); expect(DEFAULT_PWNTOOLS_TIMEOUT_MS).toBe(30_000); - expect(MAX_NATIVE_TIMER_MS).toBe(2_147_483_647); + expect(MAX_NODE_TIMER_DELAY_MS).toBe(2_147_483_647); for (const field of [ nativeCommandTimeoutField, nativeUiDeadlineField, @@ -23,9 +23,9 @@ it("keeps today's omitted native deadlines and the shared timer range", () => { ]) { expect(field.safeParse(undefined).success).toBe(true); expect(field.safeParse(1).success).toBe(true); - expect(field.safeParse(MAX_NATIVE_TIMER_MS).success).toBe(true); + expect(field.safeParse(MAX_NODE_TIMER_DELAY_MS).success).toBe(true); expect(field.safeParse(0).success).toBe(false); - expect(field.safeParse(MAX_NATIVE_TIMER_MS + 1).success).toBe(false); + expect(field.safeParse(MAX_NODE_TIMER_DELAY_MS + 1).success).toBe(false); expect(field.safeParse(1.5).success).toBe(false); } }); diff --git a/src/domain/native/nativeDeadlines.ts b/src/domain/native/nativeDeadlines.ts index 472396b1a1..f3402dadf8 100644 --- a/src/domain/native/nativeDeadlines.ts +++ b/src/domain/native/nativeDeadlines.ts @@ -1,13 +1,13 @@ -import { z } from "zod"; +import { + MAX_NODE_TIMER_DELAY_MS, + timerDurationMsSchema, +} from "../analysisResourceLimits.js"; import { fixedAllowanceRemediation, type FixedAllowanceKind, } from "../fixedAllowanceRemediation.js"; -/** Largest delay Node honors as a timer rather than clamping to 1 ms. */ -export const MAX_NATIVE_TIMER_MS = 2_147_483_647; - /** * Omitted `native_command_timeout_ms`. This is the macOS Xcode-tool wall * clock, not objdump/rizin `command_timeout_ms` (default 120000). @@ -26,29 +26,22 @@ export const DEFAULT_PWNTOOLS_TIMEOUT_MS = 30_000; */ export const NATIVE_UI_WAIT_STEP_MAX_MS = 180_000; -/** Integer millisecond deadline shared by the native command, UI, and pwntools settings. */ -export const nativeDeadlineMsSchema = z - .number() - .int() - .min(1) - .max(MAX_NATIVE_TIMER_MS); - const deadlineField = (description: string) => - nativeDeadlineMsSchema.optional().describe(description); + timerDurationMsSchema.optional().describe(description); /** Per-call macOS native command deadline. Omitted means 60000 ms. */ export const nativeCommandTimeoutField = deadlineField( - "Wall-clock budget in milliseconds for each macOS native command in this call (lipo, codesign, plutil, swift-demangle, and the other allowlisted Xcode tools). Omitted means 60000. Integer from 1 to 2147483647. Applies on the next call. Does not raise the fixed 67108864-byte output allowance or the 65536-byte failure-diagnostic excerpt. Named native_command_timeout_ms rather than command_timeout_ms because command_timeout_ms is the separate one-shot objdump and rizin deadline (default 120000).", + `Wall-clock budget in milliseconds for each macOS native command in this call (lipo, codesign, plutil, swift-demangle, and the other allowlisted Xcode tools). Omitted means 60000. Integer from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)}. Applies on the next call. Does not raise the fixed 67108864-byte output allowance or the 65536-byte failure-diagnostic excerpt. Named native_command_timeout_ms rather than command_timeout_ms because command_timeout_ms is the separate one-shot objdump and rizin deadline (default 120000).`, ); /** Per-call native UI observation deadline. Omitted means 180000 ms. */ export const nativeUiDeadlineField = deadlineField( - "Deadline in milliseconds for this UI observation or scenario, including helper preparation and captures. Omitted means 180000. Integer from 1 to 2147483647. Applies on the next call. Does not raise the fixed 67108864-byte scenario output allowance or the 180000 ms cap on one wait step. A partial observation may already be retained when this deadline expires.", + `Deadline in milliseconds for this UI observation or scenario, including helper preparation and captures. Omitted means 180000. Integer from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)}. Applies on the next call. Does not raise the fixed 67108864-byte scenario output allowance or the 180000 ms cap on one wait step. A partial observation may already be retained when this deadline expires.`, ); /** Per-call pwntools command deadline. Omitted means 30000 ms. */ export const pwntoolsTimeoutField = deadlineField( - "Deadline in milliseconds for each owned pwntools command in this call. Omitted means 30000, range 1..2147483647; applies on the next call. Independent CPU, output, diagnostic, file and address-space allowances are selected in producer_limits. input_bytes overrides REA_PWNTOOLS_MAX_INPUT_BYTES; otherwise that launch default applies.", + `Deadline in milliseconds for each owned pwntools command in this call. Omitted means 30000, range 1..${String(MAX_NODE_TIMER_DELAY_MS)}; applies on the next call. Independent CPU, output, diagnostic, file and address-space allowances are selected in producer_limits. input_bytes overrides REA_PWNTOOLS_MAX_INPUT_BYTES; otherwise that launch default applies.`, ); type NativeDeadlineRead = @@ -65,7 +58,7 @@ export const readNativeDeadline = ( defaultMs: number, ): NativeDeadlineRead => { if (value === undefined) return { ok: true, timeoutMs: defaultMs }; - const parsed = nativeDeadlineMsSchema.safeParse(value); + const parsed = timerDurationMsSchema.safeParse(value); if (parsed.success) return { ok: true, timeoutMs: parsed.data }; const invalidType = parsed.error.issues.some( (issue) => issue.code === "invalid_type", @@ -73,7 +66,7 @@ export const readNativeDeadline = ( return { ok: false, reason: invalidType ? "invalid_type" : "out_of_range", - message: `Expected an integer from 1 to ${String(MAX_NATIVE_TIMER_MS)} milliseconds; received ${JSON.stringify(value)}. Omitted means ${String(defaultMs)}.`, + message: `Expected an integer from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)} milliseconds; received ${JSON.stringify(value)}. Omitted means ${String(defaultMs)}.`, }; }; @@ -87,10 +80,10 @@ export const nativeDeadlineRecovery = (input: { readonly unchanged: string; readonly detail?: string; }): { readonly userMessage: string; readonly remediationAction: string } => { - const atMaximum = input.timeoutMs >= MAX_NATIVE_TIMER_MS; + const atMaximum = input.timeoutMs >= MAX_NODE_TIMER_DELAY_MS; const adjustment = atMaximum - ? `${input.setting} (${input.cliFlag} on the CLI) is already at the maximum ${String(MAX_NATIVE_TIMER_MS)} ms; do not increase it.` - : `Increase ${input.setting} above ${String(input.timeoutMs)} (integer milliseconds from 1 to ${String(MAX_NATIVE_TIMER_MS)}; omitted means ${String(input.defaultMs)}), or pass ${input.cliFlag} on the CLI. A change applies on the next call.`; + ? `${input.setting} (${input.cliFlag} on the CLI) is already at the maximum ${String(MAX_NODE_TIMER_DELAY_MS)} ms; do not increase it.` + : `Increase ${input.setting} above ${String(input.timeoutMs)} (integer milliseconds from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)}; omitted means ${String(input.defaultMs)}), or pass ${input.cliFlag} on the CLI. A change applies on the next call.`; return { userMessage: `This request reached REA's ${input.phase} of ${String(input.timeoutMs)} ms (${input.setting}). This is a server/provider deadline, not the MCP client deadline.${input.detail ?? ""}`, remediationAction: `${adjustment} ${input.unchanged} Allow execution, cleanup, and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`, diff --git a/src/domain/producerResourceLimits.ts b/src/domain/producerResourceLimits.ts index fc44bbb33c..866b510912 100644 --- a/src/domain/producerResourceLimits.ts +++ b/src/domain/producerResourceLimits.ts @@ -1,12 +1,12 @@ import { z } from "zod"; -import { MAX_NODE_TIMER_DELAY_MS } from "./analysisResourceLimits.js"; +import { timerDurationMsSchema } from "./analysisResourceLimits.js"; /** Per-call owned producer budgets. Each adapter advertises only consumed fields. */ export const producerResourceLimitsSchema = z.strictObject({ input_bytes: z.int().positive().optional(), output_bytes: z.int().positive().optional(), diagnostic_bytes: z.int().positive().optional(), - command_timeout_ms: z.int().min(1).max(MAX_NODE_TIMER_DELAY_MS).optional(), + command_timeout_ms: timerDurationMsSchema.optional(), address_space_bytes: z.int().positive().optional(), file_bytes: z.int().positive().optional(), cpu_seconds: z.int().positive().optional(), diff --git a/src/domain/reverseEngineering.ts b/src/domain/reverseEngineering.ts index f21d0c8558..5de146bb4e 100644 --- a/src/domain/reverseEngineering.ts +++ b/src/domain/reverseEngineering.ts @@ -1,3 +1,4 @@ +import { timerDurationMsSchema } from "./analysisResourceLimits.js"; import { z } from "zod"; import { constants as bufferConstants } from "node:buffer"; import { commandEvidenceDetailSchema } from "./commandObservation.js"; @@ -7,8 +8,6 @@ import { rejectUnpairedSurrogates } from "./stringPatterns.js"; /** Omitted one-shot objdump/rizin wall clock. Preflight shares it; the command gets it again. */ export const DEFAULT_REVERSE_COMMAND_TIMEOUT_MS = 120_000; -/** Node timer ceiling. Larger deadlines would be clamped instead of honored. */ -export const MAX_REVERSE_COMMAND_TIMEOUT_MS = 2_147_483_647; /** Combined stdout/stderr admission, before UTF-8 decoding and Evidence expansion. */ export const DEFAULT_REVERSE_COMMAND_OUTPUT_BYTES = 16 * 1024 * 1024; @@ -27,11 +26,7 @@ export const reverseCommandOutputBytesSchema = z ); /** Per-call deadline for one-shot objdump and rizin commands. */ -export const reverseCommandTimeoutSchema = z - .number() - .int() - .min(1) - .max(MAX_REVERSE_COMMAND_TIMEOUT_MS) +export const reverseCommandTimeoutSchema = timerDurationMsSchema .exactOptional() .describe( "Wall-clock budget in milliseconds. Target preflight shares one budget across stat and digest, and the one-shot command receives that budget again (default 120000 each). Omitted means 120000. Applies on the next call. Output admission is separately controlled by max_output_bytes; does not raise Ghidra or Hopper startup deadlines or debugger session deadlines.", diff --git a/src/domain/sqlite/sqliteDatabase.ts b/src/domain/sqlite/sqliteDatabase.ts index dfe5df6f2f..c776d0471b 100644 --- a/src/domain/sqlite/sqliteDatabase.ts +++ b/src/domain/sqlite/sqliteDatabase.ts @@ -1,3 +1,4 @@ +import { timerDurationMsSchema } from "../analysisResourceLimits.js"; import { z } from "zod"; import { absoluteLocalPathStringSchema } from "../localPath.js"; import type { JsonValue } from "../jsonValue.js"; @@ -14,8 +15,6 @@ export const sqliteSchemaHasObjectDeclaration = (name: string): boolean => export const SQLITE_ROW_LIMIT_DEFAULT = 20; /** Execution budget, bounded by the runtime's signed 32-bit timer range. */ export const DEFAULT_SQLITE_WORKER_TIMEOUT_MS = 30_000; -export const MAX_SQLITE_WORKER_TIMEOUT_MS = 2_147_483_647; -const workerTimeout = z.number().int().min(1).max(MAX_SQLITE_WORKER_TIMEOUT_MS); const nonnegative = z.int().nonnegative(); const hex = z.string().regex(/^(?:[0-9a-f]{2})*$/); @@ -113,7 +112,7 @@ export const inspectSqliteDatabaseInputSchema = sqliteTableSelectionSchema path: absoluteLocalPathStringSchema.describe( "Absolute path to an offline SQLite database snapshot", ), - worker_timeout_ms: workerTimeout + worker_timeout_ms: timerDurationMsSchema .optional() .describe( `Deadline in milliseconds for worker startup, queries and reply writing (default ${String(DEFAULT_SQLITE_WORKER_TIMEOUT_MS)}), not snapshot acquisition or the whole call. Allow client headroom for acquisition, reply reads, cleanup and delivery. Fixed byte/heap limits do not change.`, @@ -151,7 +150,7 @@ export const sqliteDatabaseSchema = z name: z.literal("SQLite"), version: z.string().min(1), }), - worker_timeout_ms: workerTimeout + worker_timeout_ms: timerDurationMsSchema .exactOptional() .describe( "Actual parent-supervised worker deadline in milliseconds; absent in historical Evidence means unknown, not the default.", diff --git a/src/domain/wasm/wasmArtifact.ts b/src/domain/wasm/wasmArtifact.ts index f205085580..edeb391b0a 100644 --- a/src/domain/wasm/wasmArtifact.ts +++ b/src/domain/wasm/wasmArtifact.ts @@ -1,3 +1,4 @@ +import { timerDurationMsSchema } from "../analysisResourceLimits.js"; import { wasmInterfaceSchema, wasmInterfaceByteBudgetSchema, @@ -28,7 +29,6 @@ const artifact = z.strictObject({ }); /** Default execution budget; upper bound is the runtime's signed 32-bit timer range. */ export const DEFAULT_WASM_COMMAND_TIMEOUT_MS = 30_000; -export const MAX_WASM_COMMAND_TIMEOUT_MS = 2_147_483_647; export const DEFAULT_WASM_ARTIFACT_PATHS = 16; export const MAX_WASM_ARTIFACT_PATHS = 0xffff_ffff; /** Defaults preserve the original WABT admission and capture envelope. */ @@ -97,11 +97,7 @@ export const inspectWasmArtifactInputSchema = z.strictObject({ WASM_RESOURCE_DEFAULTS.outputBytes, WASM_RESOURCE_MAXIMUMS.outputBytes, ), - command_timeout_ms: z - .number() - .int() - .min(1) - .max(MAX_WASM_COMMAND_TIMEOUT_MS) + command_timeout_ms: timerDurationMsSchema .exactOptional() .describe( `Deadline in milliseconds for each WABT version/analysis command (default ${String(DEFAULT_WASM_COMMAND_TIMEOUT_MS)}), not the whole inspection. Allow additional client time for all commands, file checks and cleanup. Does not raise max_input_bytes, max_tool_bytes or max_output_bytes.`, diff --git a/src/domain/webBundleAnalysis.ts b/src/domain/webBundleAnalysis.ts index ba3313dc5f..4da6dfb5cd 100644 --- a/src/domain/webBundleAnalysis.ts +++ b/src/domain/webBundleAnalysis.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "./analysisResourceLimits.js"; import { javaScriptSemanticPrecisionSchema } from "./javascript/javascriptSemanticPrecision.js"; import { fetchedSourceMapLimitsSchema } from "./sourceMapLimits.js"; import { z } from "zod"; @@ -6,7 +7,6 @@ import { webPageInspectionSchema } from "./browserObservationSchemas.js"; import { javaScriptRouteInventorySchema } from "./javascript/javascriptRouteInventory.js"; import { - MAX_BROWSER_DEADLINE_MS, browserDeadlineIncrease, browserDeadlineRetry, noRuntimeOverrideSentence, @@ -35,9 +35,9 @@ export const DEFAULT_SOURCE_MAP_FETCH_TIMEOUT_MS = 30_000; const webBundleHeapDescription = `Heap phase: maximum V8 old-space for the isolated inert-script analyzer, in MiB (default ${String(DEFAULT_WEB_BUNDLE_HEAP_MB)}, range ${String(MIN_WEB_BUNDLE_HEAP_MB)}..${String(MAX_WEB_BUNDLE_HEAP_MB)}). Omitted means ${String(DEFAULT_WEB_BUNDLE_HEAP_MB)} and applies on the next call. This is not a total process RSS limit, not analysis_timeout_ms, and not total_analysis_timeout_ms. Bun ignores V8 flags; Windows Bun uses an owned process commit limit plus a 512 MiB runtime reserve, while other Bun hosts have no enforced memory limit. Raising max_heap_mb does not raise the fixed worker protocol or result byte budgets.`; -const webBundleScriptTimeoutDescription = `Per-script deadline phase: maximum startup, analysis and result transfer time for one captured script, in milliseconds (default ${String(DEFAULT_WEB_BUNDLE_SCRIPT_TIMEOUT_MS)}, range 1..${String(MAX_BROWSER_DEADLINE_MS)}). Omitted means ${String(DEFAULT_WEB_BUNDLE_SCRIPT_TIMEOUT_MS)}. deadlineExpired for one script is not total_analysis_timeout_ms. A per-script value above the effective total is rejected. Timed-out scripts are explicit unknowns and other scripts may still be analyzed. Applies on the next call.`; +const webBundleScriptTimeoutDescription = `Per-script deadline phase: maximum startup, analysis and result transfer time for one captured script, in milliseconds (default ${String(DEFAULT_WEB_BUNDLE_SCRIPT_TIMEOUT_MS)}, range 1..${String(MAX_NODE_TIMER_DELAY_MS)}). Omitted means ${String(DEFAULT_WEB_BUNDLE_SCRIPT_TIMEOUT_MS)}. deadlineExpired for one script is not total_analysis_timeout_ms. A per-script value above the effective total is rejected. Timed-out scripts are explicit unknowns and other scripts may still be analyzed. Applies on the next call.`; -const webBundleTotalTimeoutDescription = `Total analysis deadline phase: maximum time for all captured-script analysis, in milliseconds (default ${String(DEFAULT_WEB_BUNDLE_TOTAL_TIMEOUT_MS)}, range 1..${String(MAX_BROWSER_DEADLINE_MS)}). Omitted means ${String(DEFAULT_WEB_BUNDLE_TOTAL_TIMEOUT_MS)}. This is not the per-script analysis_timeout_ms, not capture, and not source-map fetch. A per-script timeout above this total is rejected. Unstarted scripts remain explicit unknowns. Applies on the next call.`; +const webBundleTotalTimeoutDescription = `Total analysis deadline phase: maximum time for all captured-script analysis, in milliseconds (default ${String(DEFAULT_WEB_BUNDLE_TOTAL_TIMEOUT_MS)}, range 1..${String(MAX_NODE_TIMER_DELAY_MS)}). Omitted means ${String(DEFAULT_WEB_BUNDLE_TOTAL_TIMEOUT_MS)}. This is not the per-script analysis_timeout_ms, not capture, and not source-map fetch. A per-script timeout above this total is rejected. Unstarted scripts remain explicit unknowns. Applies on the next call.`; /** Capture-and-analyze input with optional source-map fetching. */ export const analyzeWebBundleInputSchema = inspectWebPageWithSourceInputSchema diff --git a/src/domain/webExecution.ts b/src/domain/webExecution.ts index dc1d9fc6b9..5e854b2454 100644 --- a/src/domain/webExecution.ts +++ b/src/domain/webExecution.ts @@ -1,6 +1,6 @@ +import { timerDurationMsSchema } from "./analysisResourceLimits.js"; import { z } from "zod"; import { utcDateTimeSchema } from "./offsetDateTime.js"; -import { MAX_BROWSER_DEADLINE_MS } from "./browserDeadline.js"; import { jsonObjectSchema } from "./jsonValue.js"; import { webRuntimeLocationSchema, @@ -12,7 +12,7 @@ import { browserVersionSchema } from "./browserObservationSchemas.js"; /** Explicit instrumentation request for one finite, externally driven execution window. */ export const observeWebExecutionInputSchema = webRuntimeScopeSchema.extend({ - observation_ms: z.int().min(1).max(MAX_BROWSER_DEADLINE_MS).default(10_000), + observation_ms: timerDurationMsSchema.default(10_000), }); export type ObserveWebExecutionInput = z.infer< typeof observeWebExecutionInputSchema diff --git a/src/evm/EvmoleFailures.test.ts b/src/evm/EvmoleFailures.test.ts index 8ce2bf2a3f..ecd4c3ce53 100644 --- a/src/evm/EvmoleFailures.test.ts +++ b/src/evm/EvmoleFailures.test.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { readFile, symlink } from "node:fs/promises"; import { join } from "node:path"; import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; @@ -11,7 +12,6 @@ import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { DEFAULT_EVM_TIMEOUT_MS, - MAX_EVM_TIMEOUT_MS, selectedEvmProducerLimits, } from "../domain/evm/evmInterface.js"; import type { ProviderProcessSnapshot } from "../process/ProviderProcess.js"; @@ -111,7 +111,9 @@ it("names timeout_ms, the omitted default, and the caps it does not raise", () = expect(projected.message).toContain("timeout_ms"); expect(projected.message).toContain(String(DEFAULT_EVM_TIMEOUT_MS)); expect(projected.remediation.action).toContain("--timeout-ms"); - expect(projected.remediation.action).toContain(String(MAX_EVM_TIMEOUT_MS)); + expect(projected.remediation.action).toContain( + String(MAX_NODE_TIMER_DELAY_MS), + ); expect(projected.remediation.action).toContain("does not raise"); expect(projected.remediation.action).toContain("no server restart"); }); diff --git a/src/evm/EvmoleFailures.ts b/src/evm/EvmoleFailures.ts index ace2cff924..08309ff835 100644 --- a/src/evm/EvmoleFailures.ts +++ b/src/evm/EvmoleFailures.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import type { EvmWorkerLimits } from "./EvmWorkerLimits.js"; import type { AnalysisCapturedOutput, @@ -14,7 +15,6 @@ import type { ProviderOutcomeContext } from "../process/classifyProviderOutcome. import type { ProviderFailureDialect } from "../providers/classifyProviderFailure.js"; import { DEFAULT_EVM_TIMEOUT_MS, - MAX_EVM_TIMEOUT_MS, selectedEvmProducerLimits, evmProducerLimitRecovery, type EvmProducerLimits, @@ -50,9 +50,9 @@ export const evmReplyBudgetFailure = ( const evmTimeoutRecovery = (timeoutMs: number): string => `${ - timeoutMs < MAX_EVM_TIMEOUT_MS - ? `Increase timeout_ms above ${String(timeoutMs)} (integer milliseconds, maximum ${String(MAX_EVM_TIMEOUT_MS)}), or use rea inspect-evm-interface --timeout-ms on the CLI.` - : `timeout_ms is already at the maximum supported ${String(MAX_EVM_TIMEOUT_MS)} ms; no higher worker deadline is supported. Report this blocker or select another suitable complete carrier with caller approval.` + timeoutMs < MAX_NODE_TIMER_DELAY_MS + ? `Increase timeout_ms above ${String(timeoutMs)} (integer milliseconds, maximum ${String(MAX_NODE_TIMER_DELAY_MS)}), or use rea inspect-evm-interface --timeout-ms on the CLI.` + : `timeout_ms is already at the maximum supported ${String(MAX_NODE_TIMER_DELAY_MS)} ms; no higher worker deadline is supported. Report this blocker or select another suitable complete carrier with caller approval.` } This is a per-call setting; no server restart is needed. It covers the owned EVMole worker command, not carrier acquisition or final reply reads. Allow the MCP client deadline to cover acquisition, the worker, reply reads, cleanup and delivery; increasing only that client deadline does not change this budget. Separate producer_limits control carrier/reply/diagnostic bytes, address-space/file bytes and CPU seconds; timeout_ms does not raise them. The 256 MiB worker heap stays independent. Resolve any incomplete cleanup before retrying; do not repeat the unchanged failed call.`; /** Correlate a reserved exit with the owned worker's actual failure branch. */ diff --git a/src/firmware/FirmwareFailures.ts b/src/firmware/FirmwareFailures.ts index ea79d7a254..a1c4f62e6e 100644 --- a/src/firmware/FirmwareFailures.ts +++ b/src/firmware/FirmwareFailures.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import type { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js"; import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js"; import { @@ -23,7 +24,6 @@ import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import type { FirmwareDeadline } from "./FirmwareDeadline.js"; import { firmwareDeadlineElapsed } from "./FirmwareDeadline.js"; import { z } from "zod"; -import { MAX_FIRMWARE_TIMEOUT_MS } from "../domain/firmware/firmwareAnalysis.js"; import { FIRMWARE_LIMITS } from "./FirmwareRelease.js"; /** Fixed firmware allowance. analysis_timeout_ms does not raise it. */ @@ -122,7 +122,7 @@ const timeoutFailure = ( } : { userMessage: `Firmware analysis exceeded its ${deadline.timeoutMs}ms wall-clock budget${operation === "extract_firmware" ? " before publication" : " during inspection or its final workspace cleanup"}.`, - remediationAction: `Retry the same operation and preserve the selected input and analysis question. ${deadline.timeoutMs < MAX_FIRMWARE_TIMEOUT_MS ? `Increase analysis_timeout_ms (--analysis-timeout-ms in the CLI), an integer from 1 to ${MAX_FIRMWARE_TIMEOUT_MS} (default 120000).` : `analysis_timeout_ms (--analysis-timeout-ms in the CLI) is already at the maximum ${MAX_FIRMWARE_TIMEOUT_MS}; do not increase it further.`} Set the client tool-call timeout above the analysis budget plus publication and cleanup headroom. publication_timeout_ms only controls the later publication phase and cannot repair this analysis timeout. Fixed per-process CPU, memory and byte limits are unchanged. If cleanup is incomplete, resolve the reported owned resources before retrying; no server restart is needed after confirmed cleanup.`, + remediationAction: `Retry the same operation and preserve the selected input and analysis question. ${deadline.timeoutMs < MAX_NODE_TIMER_DELAY_MS ? `Increase analysis_timeout_ms (--analysis-timeout-ms in the CLI), an integer from 1 to ${MAX_NODE_TIMER_DELAY_MS} (default 120000).` : `analysis_timeout_ms (--analysis-timeout-ms in the CLI) is already at the maximum ${MAX_NODE_TIMER_DELAY_MS}; do not increase it further.`} Set the client tool-call timeout above the analysis budget plus publication and cleanup headroom. publication_timeout_ms only controls the later publication phase and cannot repair this analysis timeout. Fixed per-process CPU, memory and byte limits are unchanged. If cleanup is incomplete, resolve the reported owned resources before retrying; no server restart is needed after confirmed cleanup.`, }), }); diff --git a/src/hopper/HopperRequestQueue.ts b/src/hopper/HopperRequestQueue.ts index 2ba4b4bce3..d072232104 100644 --- a/src/hopper/HopperRequestQueue.ts +++ b/src/hopper/HopperRequestQueue.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import type { ProgressReporter, ProgressUpdate, @@ -17,9 +18,6 @@ import { err, type Result } from "../domain/result.js"; type HopperRequestResult = Result; -/** Node timer ceiling; larger deadlines would be clamped instead of honored. */ -const MAX_TIMEOUT_MS = 2_147_483_647; - interface HopperRequestQueueOptions { readonly signal?: AbortSignal; /** Caller deadline from admission, including time waiting in the FIFO. */ @@ -83,12 +81,12 @@ export class HopperRequestQueue { timeoutMs !== undefined && (!Number.isInteger(timeoutMs) || timeoutMs < 0 || - timeoutMs > MAX_TIMEOUT_MS) + timeoutMs > MAX_NODE_TIMER_DELAY_MS) ) return Promise.resolve( err( new HopperProtocolError( - `Hopper timeoutMs must be an integer between 0 and ${String(MAX_TIMEOUT_MS)}`, + `Hopper timeoutMs must be an integer between 0 and ${String(MAX_NODE_TIMER_DELAY_MS)}`, ), ), ); diff --git a/src/hopper/LinuxPrivateDisplayDiagnostic.ts b/src/hopper/LinuxPrivateDisplayDiagnostic.ts index e8f39b0328..f8c4d52a3e 100644 --- a/src/hopper/LinuxPrivateDisplayDiagnostic.ts +++ b/src/hopper/LinuxPrivateDisplayDiagnostic.ts @@ -1,10 +1,10 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { z } from "zod"; import { DEFAULT_HOPPER_DEMO_DIALOG_TIMEOUT_MS, HOPPER_DEMO_DIALOG_TIMEOUT_SETTING, isHopperStartupFailureCode, - MAXIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS, MINIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS, type HopperStartupDiagnostic, } from "../domain/hopperStartupFailure.js"; @@ -42,7 +42,7 @@ const dialogTimeoutSchema = z value: z.string().max(128), source: z.literal("setting"), minimum_ms: z.literal(MINIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS), - maximum_ms: z.literal(MAXIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS), + maximum_ms: z.literal(MAX_NODE_TIMER_DELAY_MS), default_ms: z.literal(DEFAULT_HOPPER_DEMO_DIALOG_TIMEOUT_MS), }) .strict(); diff --git a/src/ida/IdaConfiguration.ts b/src/ida/IdaConfiguration.ts index bb3a9cf9b4..0b399e3c43 100644 --- a/src/ida/IdaConfiguration.ts +++ b/src/ida/IdaConfiguration.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { isAbsolute } from "node:path"; import { z } from "zod"; import { jsonRecordSchema } from "../domain/jsonRecord.js"; @@ -27,8 +28,6 @@ import { readBoundedFileBytes } from "../process/BoundedFileBytes.js"; export const DEFAULT_IDA_REQUEST_TIMEOUT_MS = 300_000; /** Shortest valid registration request timeout. */ const MIN_IDA_REQUEST_TIMEOUT_MS = 1; -/** Node timer ceiling. Larger registration values would be clamped instead of honored. */ -export const MAX_IDA_REQUEST_TIMEOUT_MS = 2_147_483_647; /** Loopback names plus the Docker and Podman gateway names for the container's host. */ const LOCAL_IDA_HTTP_HOSTS: ReadonlySet = new Set([ "localhost", @@ -50,7 +49,7 @@ const common = { timeoutMs: z .int() .min(MIN_IDA_REQUEST_TIMEOUT_MS) - .max(MAX_IDA_REQUEST_TIMEOUT_MS) + .max(MAX_NODE_TIMER_DELAY_MS) .default(DEFAULT_IDA_REQUEST_TIMEOUT_MS), workspaceRoot: z .string() @@ -98,7 +97,7 @@ const registrationConstraint = ( issue: AnalysisInputIssue, ): string | undefined => { if (issue.path.length === 1 && issue.path[0] === "timeoutMs") - return `timeoutMs must be an integer from ${String(MIN_IDA_REQUEST_TIMEOUT_MS)} to ${String(MAX_IDA_REQUEST_TIMEOUT_MS)} milliseconds`; + return `timeoutMs must be an integer from ${String(MIN_IDA_REQUEST_TIMEOUT_MS)} to ${String(MAX_NODE_TIMER_DELAY_MS)} milliseconds`; return issue.message === undefined ? undefined : `${issue.path.join(".") || "registration"}: ${issue.message}`; @@ -323,7 +322,7 @@ export const idaRegistrationTimeoutGuidance = ( : ceilingMs === timeoutMs ? `This IDA request reached the registration timeoutMs deadline of ${String(timeoutMs)} ms (deadlineExpired).` : `This IDA request reached its ${String(timeoutMs)} ms deadline (deadlineExpired), within the registration timeoutMs ceiling of ${String(ceilingMs)} ms.`, - remediationAction: `Set timeoutMs in the JSON file named by REA_IDA_MCP_CONFIG to an integer from 1 to ${String(MAX_IDA_REQUEST_TIMEOUT_MS)} (omitted means ${String(DEFAULT_IDA_REQUEST_TIMEOUT_MS)}). REA applies the edited file on the next IDA connection after it re-reads the registration; an already open session keeps the timeout it connected with. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`, + remediationAction: `Set timeoutMs in the JSON file named by REA_IDA_MCP_CONFIG to an integer from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)} (omitted means ${String(DEFAULT_IDA_REQUEST_TIMEOUT_MS)}). REA applies the edited file on the next IDA connection after it re-reads the registration; an already open session keeps the timeout it connected with. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`, }); /** A REA_IDA_MCP_CONFIG rejection that names the setting it concerns. */ diff --git a/src/javascript/analysis/JavaScriptAnalysisWorker.ts b/src/javascript/analysis/JavaScriptAnalysisWorker.ts index dc4af6c852..b61c4d7a45 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorker.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorker.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../../domain/analysisResourceLimits.js"; import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js"; import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js"; import { bindArtifactFileCleanup } from "../../artifacts/ArtifactFileOperation.js"; @@ -221,7 +222,7 @@ export class JavaScriptAnalysisWorker { limits.heapMb > JAVASCRIPT_WORKER_HEAP_MIB_MAXIMUM || !Number.isSafeInteger(limits.timeoutMs) || limits.timeoutMs <= 0 || - limits.timeoutMs > 2_147_483_647 + limits.timeoutMs > MAX_NODE_TIMER_DELAY_MS ) throw new RangeError( "JavaScript worker requires valid heap and execution limits", diff --git a/src/kuna/KunaConfiguration.ts b/src/kuna/KunaConfiguration.ts index a35cc9797e..00386f9a08 100644 --- a/src/kuna/KunaConfiguration.ts +++ b/src/kuna/KunaConfiguration.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { isAbsolute } from "node:path"; import { ConfigurationError } from "../domain/configurationErrors.js"; @@ -172,7 +173,7 @@ const refuseInvalidLaunch = ( if (parsed.launchValid) return ok(undefined); return failure( "open_options_invalid", - `${setting} must be a decimal millisecond count from 1 to 2147483647; received ${String(raw)}.`, + `${setting} must be a decimal millisecond count from 1 to ${String(MAX_NODE_TIMER_DELAY_MS)}; received ${String(raw)}.`, setting, ); }; diff --git a/src/native/NativeMacOSProvider.ts b/src/native/NativeMacOSProvider.ts index e7b0231996..ba59d4c80a 100644 --- a/src/native/NativeMacOSProvider.ts +++ b/src/native/NativeMacOSProvider.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { withArtifactTargetIdentity } from "../artifacts/withArtifactTargetIdentity.js"; import { translateNativeCommandFailure } from "./NativeCommandAnalysisError.js"; import { @@ -79,7 +80,6 @@ import { import { DEFAULT_NATIVE_COMMAND_TIMEOUT_MS, DEFAULT_NATIVE_UI_DEADLINE_MS, - MAX_NATIVE_TIMER_MS, readNativeDeadline, } from "../domain/native/nativeDeadlines.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; @@ -496,7 +496,7 @@ class NativeMacOSClient implements AnalysisClient { reason: deadline.reason, message: deadline.message, minimum: 1, - maximum: MAX_NATIVE_TIMER_MS, + maximum: MAX_NODE_TIMER_DELAY_MS, }, ]), ); @@ -642,7 +642,7 @@ class NativeMacOSClient implements AnalysisClient { reason: timeout.reason, message: timeout.message, minimum: 1, - maximum: MAX_NATIVE_TIMER_MS, + maximum: MAX_NODE_TIMER_DELAY_MS, }, ]), ), diff --git a/src/process/capture/ProcessTimer.ts b/src/process/capture/ProcessTimer.ts index 02897ef353..47b2e486fe 100644 --- a/src/process/capture/ProcessTimer.ts +++ b/src/process/capture/ProcessTimer.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../../domain/analysisResourceLimits.js"; /** A timer owned by one process capture or replay endpoint. */ export interface ProcessTimer { cancel(): void; @@ -22,14 +23,13 @@ export const scheduleProcessDelay = ( ): ProcessTimer => { if (!Number.isSafeInteger(delayMs) || delayMs < 0) throw new RangeError("Process delay must be a nonnegative safe integer"); - const maximumTimerDelay = 2_147_483_647; let remaining = delayMs; let timer: ProcessTimer | undefined; let cancelled = false; const scheduleNext = (): void => { if (cancelled) return; - const interval = Math.min(remaining, maximumTimerDelay); + const interval = Math.min(remaining, MAX_NODE_TIMER_DELAY_MS); timer = schedule(() => { if (cancelled) return; remaining -= interval; diff --git a/src/sqlite/SqliteDatabaseFailures.ts b/src/sqlite/SqliteDatabaseFailures.ts index ac17c84438..d56b562e98 100644 --- a/src/sqlite/SqliteDatabaseFailures.ts +++ b/src/sqlite/SqliteDatabaseFailures.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js"; import { stableArtifactInputFailure } from "../artifacts/StableArtifactFailure.js"; import { @@ -31,10 +32,7 @@ import { OwnedCommandFailure } from "../process/OwnedCommand.js"; import type { ProviderProcessSnapshot } from "../process/ProviderProcess.js"; import { providerOutcomeOf } from "../process/ProviderOutcome.js"; import { runtimeExhaustionReport } from "../process/RuntimeExhaustion.js"; -import { - DEFAULT_SQLITE_WORKER_TIMEOUT_MS, - MAX_SQLITE_WORKER_TIMEOUT_MS, -} from "../domain/sqlite/sqliteDatabase.js"; +import { DEFAULT_SQLITE_WORKER_TIMEOUT_MS } from "../domain/sqlite/sqliteDatabase.js"; import { SQLITE_PROVIDER_IDENTITY } from "../domain/sqlite/SqliteProviderIdentity.js"; import { SQLITE_DATABASE_LIMITS } from "./SqliteDatabaseLimits.js"; import { SqliteSnapshotAcquisitionFailure } from "./SqliteDatabaseSnapshot.js"; @@ -255,9 +253,9 @@ const ownedCommandFailure = ( ...options, userMessage: `The SQLite worker reached its ${String(workerTimeoutMs)} ms server/provider deadline (worker_timeout_ms). This is not a whole-inspection or MCP client deadline.`, remediationAction: `${ - workerTimeoutMs < MAX_SQLITE_WORKER_TIMEOUT_MS - ? `Increase worker_timeout_ms above ${String(workerTimeoutMs)} (integer milliseconds, maximum ${String(MAX_SQLITE_WORKER_TIMEOUT_MS)}), or use rea inspect-sqlite-database --worker-timeout-ms on the CLI.` - : `worker_timeout_ms is already at the maximum supported ${String(MAX_SQLITE_WORKER_TIMEOUT_MS)} ms; no higher worker deadline is supported. Report the blocker or narrow the question with caller approval.` + workerTimeoutMs < MAX_NODE_TIMER_DELAY_MS + ? `Increase worker_timeout_ms above ${String(workerTimeoutMs)} (integer milliseconds, maximum ${String(MAX_NODE_TIMER_DELAY_MS)}), or use rea inspect-sqlite-database --worker-timeout-ms on the CLI.` + : `worker_timeout_ms is already at the maximum supported ${String(MAX_NODE_TIMER_DELAY_MS)} ms; no higher worker deadline is supported. Report the blocker or narrow the question with caller approval.` } This per-call setting needs no server restart. It covers worker startup, queries and reply writing, not snapshot acquisition or final reply reads/cleanup. Allow client headroom for the whole call; increasing only the client deadline does not change the worker budget. Keep the selected database/WAL and requested facts; narrow table/columns/schema_scope/row_limit only if the question permits it. Byte and heap safety limits remain fixed. Resolve incomplete cleanup before retrying; do not repeat the unchanged failed call.`, }) : undefined; diff --git a/src/wasm/WabtFailures.ts b/src/wasm/WabtFailures.ts index ad1b37f590..8f5538bbbc 100644 --- a/src/wasm/WabtFailures.ts +++ b/src/wasm/WabtFailures.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { analysisSettingLimit } from "../domain/analysisSettingDefinitions.js"; import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js"; import { artifactFilePrimaryFacts } from "../artifacts/ArtifactFileOperation.js"; @@ -24,7 +25,6 @@ import { WabtAdmissionError } from "./WabtAdmissionError.js"; import { DEFAULT_WASM_COMMAND_TIMEOUT_MS, WABT_VERSION, - MAX_WASM_COMMAND_TIMEOUT_MS, WASM_RESOURCE_DEFAULTS, WASM_RESOURCE_MAXIMUMS, type WasmResourceLimits, @@ -108,9 +108,9 @@ const wabtCommandTimeout = (execution: WabtFailureContext | undefined) => { ), userMessage: `A WABT command reached its ${String(timeoutMs)} ms server/provider deadline (command_timeout_ms), not the whole-inspection or MCP client deadline.`, remediationAction: `${ - timeoutMs < MAX_WASM_COMMAND_TIMEOUT_MS - ? `Increase command_timeout_ms above ${String(timeoutMs)} (integer milliseconds, maximum ${String(MAX_WASM_COMMAND_TIMEOUT_MS)}), or use rea inspect-wasm-artifact --command-timeout-ms on the CLI.` - : `command_timeout_ms is already at the maximum supported ${String(MAX_WASM_COMMAND_TIMEOUT_MS)} ms; no higher command deadline is supported. Report this blocker or select another suitable complete artifact with caller approval.` + timeoutMs < MAX_NODE_TIMER_DELAY_MS + ? `Increase command_timeout_ms above ${String(timeoutMs)} (integer milliseconds, maximum ${String(MAX_NODE_TIMER_DELAY_MS)}), or use rea inspect-wasm-artifact --command-timeout-ms on the CLI.` + : `command_timeout_ms is already at the maximum supported ${String(MAX_NODE_TIMER_DELAY_MS)} ms; no higher command deadline is supported. Report this blocker or select another suitable complete artifact with caller approval.` } This is a per-call setting; no server restart is needed. Allow the MCP client deadline to cover all version/analysis commands, file checks, cleanup and delivery; increasing only that client deadline does not change this budget. max_input_bytes, max_tool_bytes and max_output_bytes are independent per-call controls; detail: summary reduces delivery size, not analysis work. Resolve any incomplete cleanup before retrying; do not repeat the unchanged failed call.`, }; }; diff --git a/tests/boundary/browser/cdpTargetDeadlines.test.ts b/tests/boundary/browser/cdpTargetDeadlines.test.ts index 803442a38e..88133b6fe8 100644 --- a/tests/boundary/browser/cdpTargetDeadlines.test.ts +++ b/tests/boundary/browser/cdpTargetDeadlines.test.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../../../src/domain/analysisResourceLimits.js"; import { createServer as createHttpServer } from "node:http"; import { createServer, type Socket } from "node:net"; @@ -12,10 +13,7 @@ import { } from "../../../src/browser/PlaywrightScenarioServiceWorkers.js"; import { AnalysisTimeoutError } from "../../../src/domain/analysisErrorCore.js"; import { CdpWebRuntimeProvider } from "../../../src/browser/execution/CdpWebRuntimeProvider.js"; -import { - CDP_DISCOVERY_RESPONSE_TIMEOUT_MS, - MAX_BROWSER_DEADLINE_MS, -} from "../../../src/domain/browserDeadline.js"; +import { CDP_DISCOVERY_RESPONSE_TIMEOUT_MS } from "../../../src/domain/browserDeadline.js"; import { BrowserObservationError } from "../../../src/domain/browserObservationError.js"; import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; import { @@ -777,14 +775,14 @@ it("applies caller-selected discovery_timeout_ms to HTTP discovery independently } }); -it("clamps browser-socket handshake timers at MAX_BROWSER_DEADLINE_MS without 32-bit timer overflow", async () => { +it("clamps browser-socket handshake timers at MAX_NODE_TIMER_DELAY_MS without 32-bit timer overflow", async () => { const browser = await startFakeCdpBrowser({ handshakeDelayMs: 60 }); const provider = new CdpBrowserProvider(); try { const listed = await provider.listTargets( listBrowserTargetsInputSchema.parse({ cdp_endpoint: browser.browserWebSocketUrl, - discovery_timeout_ms: MAX_BROWSER_DEADLINE_MS, + discovery_timeout_ms: MAX_NODE_TIMER_DELAY_MS, }), ); if (!listed.ok) throw listed.error; @@ -794,9 +792,9 @@ it("clamps browser-socket handshake timers at MAX_BROWSER_DEADLINE_MS without 32 .mock.calls.flatMap(([, delay]) => typeof delay === "number" ? [delay] : [], ); - expect(scheduledDelays).toContain(MAX_BROWSER_DEADLINE_MS); + expect(scheduledDelays).toContain(MAX_NODE_TIMER_DELAY_MS); expect(Math.max(...scheduledDelays)).toBeLessThanOrEqual( - MAX_BROWSER_DEADLINE_MS, + MAX_NODE_TIMER_DELAY_MS, ); } finally { await provider.close(); @@ -820,19 +818,19 @@ it("clamps browser-socket handshake timers at MAX_BROWSER_DEADLINE_MS without 32 ), "list_browser_targets", undefined, - MAX_BROWSER_DEADLINE_MS, + MAX_NODE_TIMER_DELAY_MS, ).catch((cause: unknown) => cause); await waitFor(() => expect(sockets.size).toBe(1)); - expireEveryTimer(MAX_BROWSER_DEADLINE_MS); + expireEveryTimer(MAX_NODE_TIMER_DELAY_MS); const failure = await pending; expect(failure).toBeInstanceOf(BrowserObservationError); if (!(failure instanceof BrowserObservationError)) throw new Error("Expected maximum discovery deadline failure"); expect(failure.userMessage).toContain( - `CDP browser-socket discovery exceeded its ${String(MAX_BROWSER_DEADLINE_MS)} ms discovery_timeout_ms deadline`, + `CDP browser-socket discovery exceeded its ${String(MAX_NODE_TIMER_DELAY_MS)} ms discovery_timeout_ms deadline`, ); expect(failure.remediationAction).toContain( - `discovery_timeout_ms is already at the maximum ${String(MAX_BROWSER_DEADLINE_MS)} ms`, + `discovery_timeout_ms is already at the maximum ${String(MAX_NODE_TIMER_DELAY_MS)} ms`, ); } finally { for (const socket of sockets) socket.destroy(); diff --git a/tests/boundary/mcp/mcpDoctor.test.ts b/tests/boundary/mcp/mcpDoctor.test.ts index c3d52fcc64..2123232db1 100644 --- a/tests/boundary/mcp/mcpDoctor.test.ts +++ b/tests/boundary/mcp/mcpDoctor.test.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../../../src/domain/analysisResourceLimits.js"; import { contractsForToolFamilies } from "../../../src/contracts/toolFamilies.js"; import { HOT_TOOL_NAMES, @@ -33,7 +34,6 @@ import { ok } from "../../../src/domain/result.js"; import { resolveMcpStartupBudgets, MCP_PHASE_BUDGET_FLOOR_MS, - MCP_PHASE_BUDGET_MAXIMUM_MS, } from "../../../src/config/mcpStartupBudgets.js"; import { mcpDoctorDeadlineRecovery, @@ -951,7 +951,7 @@ describe("production MCP doctor request-flow deadline", () => { "REA_MCP_INITIALIZE_BUDGET_MS", "REA_MCP_DOCTOR_DEADLINE_MS", ]); - const budgetRange = `from ${String(MCP_PHASE_BUDGET_FLOOR_MS)} to ${String(MCP_PHASE_BUDGET_MAXIMUM_MS)} ms`; + const budgetRange = `from ${String(MCP_PHASE_BUDGET_FLOOR_MS)} to ${String(MAX_NODE_TIMER_DELAY_MS)} ms`; expect(result.checks[0]?.detail).toContain("REA_MCP_INITIALIZE_BUDGET_MS"); expect(result.checks[0]?.detail).toContain(budgetRange); expect(result.checks[1]?.detail).toContain("REA_MCP_DOCTOR_DEADLINE_MS"); diff --git a/tests/boundary/providers/hopper/linuxPrivateDisplay.test.ts b/tests/boundary/providers/hopper/linuxPrivateDisplay.test.ts index a66f540b0a..ff2e4aa958 100644 --- a/tests/boundary/providers/hopper/linuxPrivateDisplay.test.ts +++ b/tests/boundary/providers/hopper/linuxPrivateDisplay.test.ts @@ -1,3 +1,4 @@ +import { MAX_NODE_TIMER_DELAY_MS } from "../../../../src/domain/analysisResourceLimits.js"; import { spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url"; @@ -10,7 +11,6 @@ import * as ownership from "../../../../src/process/ProcessOwnership.js"; import { DEFAULT_HOPPER_DEMO_DIALOG_TIMEOUT_MS, HOPPER_DEMO_DIALOG_TIMEOUT_SETTING, - MAXIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS, MINIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS, type HopperStartupDiagnostic, type HopperStartupFailureCode, @@ -165,7 +165,7 @@ describe("Hopper demo dialog timeout outcomes", () => { value: "-5", source: "setting", minimum_ms: MINIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS, - maximum_ms: MAXIMUM_HOPPER_DEMO_DIALOG_TIMEOUT_MS, + maximum_ms: MAX_NODE_TIMER_DELAY_MS, default_ms: DEFAULT_HOPPER_DEMO_DIALOG_TIMEOUT_MS, }, },