From 36ef25eb0eb39bb376186398684a84530fad0f36 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:06:51 +0800 Subject: [PATCH] refactor(pwntools): classify pwntools failures through the shared provider classifier (#10782) * refactor(pwntools): classify pwntools failures through the shared provider classifier pwntools' per-site classifier is replaced by pwntoolsFailureDialect for classifyProviderFailure. Command outcomes go through classifyProviderOutcome, launch refusals through launcherRefusalOf instead of a 'spawn ' syscall prefix check, the input limit through the file dialect's fileSize, and the cleanup report through commandCleanup. The shared read cancellation now carries the reader's partial observation, and resource-signal reports accept provider detail. * fix(pwntools): report a failed command's output once and expect resource_constraint for overflow The shared outcome owner already attaches the command's output as capturedOutput, so the pwntools adapter fallback no longer copies the same text into diagnostics.stdout, diagnostics.stderr and diagnostics.captured_output; diagnostics keep the exit facts. Update the overflow expectations the dialect migration missed (layout provider cleanup and over-budget rows, pwntools cleanup) to resource_constraint. --- .../provider-failure-classifier-baseline.json | 1 - .../verify/architecture-guard-baselines.json | 1 - src/native/pwndbg/PwndbgCoreContext.ts | 39 +- src/native/pwntools/PwntoolsDecoder.ts | 31 +- src/native/pwntools/PwntoolsFailures.test.ts | 71 ++- src/native/pwntools/PwntoolsFailures.ts | 566 ++++++++---------- src/process/classifyProviderOutcome.ts | 4 +- src/providers/classifyProviderFailure.ts | 4 + .../pwntoolsLayoutProvider.test.ts | 14 +- .../recordedCrashProvider.test.ts | 4 +- tests/process-global/pwntoolsCleanup.test.ts | 8 +- .../pwntoolsCliFinalization.test.ts | 6 +- .../pwntoolsStageRetirement.test.ts | 6 +- 13 files changed, 387 insertions(+), 368 deletions(-) diff --git a/scripts/lint/rules/provider-failure-classifier-baseline.json b/scripts/lint/rules/provider-failure-classifier-baseline.json index 72554b070c7..866856ffefb 100644 --- a/scripts/lint/rules/provider-failure-classifier-baseline.json +++ b/scripts/lint/rules/provider-failure-classifier-baseline.json @@ -69,7 +69,6 @@ "src/native/pe/PeBinaryFailure.ts": 1, "src/native/pe/PeImportsProvider.ts": 1, "src/native/pe/PeLoadConfigProvider.ts": 1, - "src/native/pwntools/PwntoolsFailures.ts": 2, "src/native/windows/WindowsShortcutProvider.ts": 1, "src/pcap/PcapProvider.ts": 2, "src/process/ArtifactAnalysisResources.ts": 3, diff --git a/scripts/verify/architecture-guard-baselines.json b/scripts/verify/architecture-guard-baselines.json index 80ae01b6db1..cc3ce19d02d 100644 --- a/scripts/verify/architecture-guard-baselines.json +++ b/scripts/verify/architecture-guard-baselines.json @@ -150,7 +150,6 @@ "src/native/pe/PeBinaryFailure.ts": 1, "src/native/pwndbg/PwndbgCoreContext.ts": 3, "src/native/pwntools/PwntoolsDecoder.ts": 8, - "src/native/pwntools/PwntoolsFailures.ts": 2, "src/native/pwntools/PwntoolsRecordedCrashProvider.ts": 1, "src/pcap/PcapCommand.ts": 2, "src/pcap/PcapNativeBound.ts": 1, diff --git a/src/native/pwndbg/PwndbgCoreContext.ts b/src/native/pwndbg/PwndbgCoreContext.ts index 4fab98a1991..9843657f4d9 100644 --- a/src/native/pwndbg/PwndbgCoreContext.ts +++ b/src/native/pwndbg/PwndbgCoreContext.ts @@ -1,3 +1,4 @@ +import { classifyProviderFailure } from "../../providers/classifyProviderFailure.js"; import { bindArtifactFileCleanup, artifactFileCancellationCause, @@ -32,7 +33,7 @@ import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorClean import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; import { capturedPwntoolsOutput, - pwntoolsDecoderFailure, + pwntoolsFailureDialect, pwntoolsBudgetRecovery, } from "../pwntools/PwntoolsFailures.js"; import { @@ -156,13 +157,15 @@ export const inspectPwndbgCore = async ({ producerLimits, }; const failure = (cause: unknown) => - pwntoolsDecoderFailure( + classifyProviderFailure( cause, - "debugger", - gdb, - environment.REA_PWNTOOLS_PYTHON ?? "", - {}, - failureContext, + pwntoolsFailureDialect( + "debugger", + gdb, + environment.REA_PWNTOOLS_PYTHON ?? "", + {}, + failureContext, + ), ); try { checkCancelled(); @@ -306,18 +309,20 @@ export const inspectPwndbgCore = async ({ return { context: { ...reply.value, diagnostics: output }, finalization }; } catch (cause: unknown) { if (cause instanceof AnalysisError && cause.cleanupIncomplete) throw cause; - const primary = pwntoolsDecoderFailure( + const primary = classifyProviderFailure( cause, - "debugger", - gdb, - environment.REA_PWNTOOLS_PYTHON ?? "", - await readPwntoolsFailureEvidence( - cause, - stage, - resources, - producerLimits, + pwntoolsFailureDialect( + "debugger", + gdb, + environment.REA_PWNTOOLS_PYTHON ?? "", + await readPwntoolsFailureEvidence( + cause, + stage, + resources, + producerLimits, + ), + failureContext, ), - failureContext, ); throw primary; } diff --git a/src/native/pwntools/PwntoolsDecoder.ts b/src/native/pwntools/PwntoolsDecoder.ts index 378d22b353b..bf0cf2762b1 100644 --- a/src/native/pwntools/PwntoolsDecoder.ts +++ b/src/native/pwntools/PwntoolsDecoder.ts @@ -1,3 +1,4 @@ +import { classifyProviderFailure } from "../../providers/classifyProviderFailure.js"; import { snapshotEnvironment } from "../../process/snapshotEnvironment.js"; import { safeParseUtf8Json } from "../../domain/safeJson.js"; import { @@ -9,7 +10,7 @@ import { artifactFileCancellationCause, } from "../../artifacts/ArtifactFileOperation.js"; import { - pwntoolsDecoderFailure, + pwntoolsFailureDialect, pwntoolsUnavailable, capturedPwntoolsOutput, pwntoolsBudgetRecovery, @@ -324,13 +325,15 @@ export class PwntoolsDecoder< let phase: "configuration" | "artifact-read" | "decoder" = "configuration"; const executablePath = environment.REA_PWNTOOLS_PYTHON ?? ""; const failure = (cause: unknown) => - pwntoolsDecoderFailure( + classifyProviderFailure( cause, - phase, - phase === "configuration" ? executablePath : input.path, - executablePath, - {}, - context, + pwntoolsFailureDialect( + phase, + phase === "configuration" ? executablePath : input.path, + executablePath, + {}, + context, + ), ); try { if (options?.signal?.aborted) @@ -679,13 +682,15 @@ export class PwntoolsDecoder< this.#resources, producerLimits, ); - const primary = pwntoolsDecoderFailure( + const primary = classifyProviderFailure( cause, - phase, - phase === "configuration" ? executablePath : input.path, - executablePath, - evidence, - context, + pwntoolsFailureDialect( + phase, + phase === "configuration" ? executablePath : input.path, + executablePath, + evidence, + context, + ), ); result = err(primary); } diff --git a/src/native/pwntools/PwntoolsFailures.test.ts b/src/native/pwntools/PwntoolsFailures.test.ts index 90c82366acf..949cabfa79b 100644 --- a/src/native/pwntools/PwntoolsFailures.test.ts +++ b/src/native/pwntools/PwntoolsFailures.test.ts @@ -3,9 +3,15 @@ import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js"; import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; import { OwnedCommandFailure } from "../../process/OwnedCommand.js"; import { pwntoolsHostSupported } from "./PwntoolsDecoder.js"; -import { pwntoolsDecoderFailure } from "./PwntoolsFailures.js"; +import { pwntoolsFailureDialect } from "./PwntoolsFailures.js"; +import { classifyProviderFailure } from "../../providers/classifyProviderFailure.js"; import { resolvePwntoolsLimits } from "../../domain/native/pwntoolsResourceLimits.js"; +const pwntoolsDecoderFailure = ( + cause: unknown, + ...phase: Parameters +) => classifyProviderFailure(cause, pwntoolsFailureDialect(...phase)); + it.each([undefined, null, false, 0, "stop", { stop: true }, new Error("stop")])( "preserves opaque cancellation from command and artifact owners: %s", (reason) => { @@ -33,7 +39,7 @@ it("keeps the caller-selected pwntools input-limit source", () => { new ArtifactReaderFailure( "limit", "artifact exceeds the input allowance", - {}, + { boundary: "file-size" }, ), "artifact-read", "/selected", @@ -67,7 +73,7 @@ it("names a runtime pwntools ceiling instead of the built-in default", () => { new ArtifactReaderFailure( "limit", "artifact exceeds the input allowance", - {}, + { boundary: "file-size" }, ), "artifact-read", "/selected", @@ -212,7 +218,10 @@ it("retains legacy owner causes without guessing cancellation from error text", "decoder", "/selected", ); - expect(result.cause).toBe(reason); + // The shared outcome owner keeps the unannotated failure itself as the + // reason, so the owner's cause stays one step down. + expect(result.cause).toBeInstanceOf(OwnedCommandFailure); + expect((result.cause as OwnedCommandFailure).cause).toBe(reason); const physical = Object.assign(new Error("physical failure"), { name: "AbortError", }); @@ -221,6 +230,60 @@ it("retains legacy owner causes without guessing cancellation from error text", ); }); +it.each(["ENOEXEC", "EACCES"])( + "reports a launcher's %s refusal as the selected Python being unavailable", + (code) => { + // Node throws ENOEXEC with a bare `spawn` syscall; the launcher names it. + const refusal = Object.assign(new Error(`spawn ${code}`), { + code, + syscall: "spawn /python", + path: "/python", + }); + const projected = projectAnalysisError( + pwntoolsDecoderFailure(refusal, "decoder", "/selected", "/python"), + ); + expect(projected).toMatchObject({ + code: "provider_unavailable", + details: { + rejections: [ + { + diagnostics: { executable_path: "/python", system_code: code }, + }, + ], + }, + }); + }, +); + +it("does not read an errno from another syscall as a launch refusal", () => { + const unrelated = Object.assign(new Error("open EACCES"), { + code: "EACCES", + syscall: "open", + }); + expect( + pwntoolsDecoderFailure(unrelated, "decoder", "/selected", "/python")._tag, + ).toBe("ProviderAdapterError"); +}); + +it("keeps the reader's partial observation on a cancelled selected-object read", () => { + const reason = { stop: "caller" }; + const observation = { + kind: "retained-evidence", + evidence_id: "evidence-1", + } as const; + const failure = pwntoolsDecoderFailure( + new ArtifactReaderFailure("cancelled", "cancelled", { + cancellation: { reason }, + partialObservation: observation, + }), + "artifact-read", + "/selected", + ); + expect(failure._tag).toBe("AnalysisCancelledError"); + expect(failure.cause).toBe(reason); + expect(failure.partialObservation).toEqual(observation); +}); + it("restricts the verified host profile to Linux x64", () => { expect(pwntoolsHostSupported("linux", "x64")).toBe(true); expect(pwntoolsHostSupported("linux", "arm64")).toBe(false); diff --git a/src/native/pwntools/PwntoolsFailures.ts b/src/native/pwntools/PwntoolsFailures.ts index cdcaeb973ed..9058a54e854 100644 --- a/src/native/pwntools/PwntoolsFailures.ts +++ b/src/native/pwntools/PwntoolsFailures.ts @@ -4,31 +4,18 @@ import { resolvePwntoolsLimits, type PwntoolsProducerLimits, } from "../../domain/native/pwntoolsResourceLimits.js"; -import { - artifactFileCancellationCause, - bindArtifactFileCleanup, -} from "../../artifacts/ArtifactFileOperation.js"; -import { completedStableArtifactObservation } from "../../artifacts/StableArtifactObservation.js"; -import { stableArtifactInputRecovery } from "../../artifacts/StableArtifactFailure.js"; -import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js"; -import { - AnalysisError, - type AnalysisCapturedOutput, -} from "../../domain/analysisErrorBase.js"; +import type { AnalysisCapturedOutput } from "../../domain/analysisErrorBase.js"; import type { ProviderProcessSnapshot } from "../../process/ProviderProcess.js"; import { - AnalysisAccessDeniedError, - AnalysisArtifactChangedError, - AnalysisCancelledError, AnalysisInputError, - AnalysisOutputError, - AnalysisTimeoutError, AnalysisResourceConstraintError, } from "../../domain/analysisErrorCore.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; import { ProviderSelectionError } from "../../domain/providerSelectionError.js"; +import type { ProviderOutcomeContext } from "../../process/classifyProviderOutcome.js"; import { OwnedCommandFailure } from "../../process/OwnedCommand.js"; +import type { ProviderFailureDialect } from "../../providers/classifyProviderFailure.js"; import type { PwntoolsFailureEvidence } from "./PwntoolsResourceLimits.js"; import { nativeDeadlineRecovery } from "../../domain/native/nativeDeadlines.js"; import { @@ -107,62 +94,153 @@ const DEFAULT_CONTEXT = { providerId: PWNTOOLS_PROVIDER_IDENTITY.id, }; -/** Keep read, engine, output and owned-lifecycle failure reasons distinct. */ -export const pwntoolsDecoderFailure = ( - cause: unknown, +/** One pwntools phase, with the evidence its owned reports left. */ +interface PwntoolsPhase { + readonly phase: string; + readonly path: string; + readonly executablePath: string; + readonly failureEvidence: PwntoolsFailureEvidence; + readonly context: PwntoolsFailureContext; +} + +/** + * pwntools' failure dialect for one phase of a decoder or debugger operation; + * `classifyProviderFailure` keeps read, engine, output and owned-lifecycle + * failure reasons distinct. + */ +export const pwntoolsFailureDialect = ( phase: string, path: string, executablePath = path, failureEvidence: PwntoolsFailureEvidence = {}, context: PwntoolsFailureContext = DEFAULT_CONTEXT, -): AnalysisError => { - const error = classifyPwntoolsDecoderFailure( - cause, +): ProviderFailureDialect => { + const state: PwntoolsPhase = { phase, path, executablePath, failureEvidence, context, - ); - if (phase === "artifact-read") { - const observation = completedStableArtifactObservation(cause, path); - if (observation !== undefined) error.retainPartialObservation(observation); - } - return error; + }; + const limits = context.producerLimits ?? resolvePwntoolsLimits(); + return { + providerId: context.providerId, + operation: context.operation, + command: () => pwntoolsCommandContext(state, limits), + commandCleanup: (failure) => { + const output = combinedPwntoolsOutput(failure.snapshot, context); + return new ProviderCleanupError( + context.providerId, + failure.resources, + { + reason: failure.cleanupFailure, + ...(output === undefined ? {} : { captured_output: { ...output } }), + previous_error: { + failure_kind: failure.reason, + message: failure.message, + exit_code: failure.snapshot?.exitCode ?? null, + signal: failure.snapshot?.signal ?? null, + stdout: failure.snapshot?.stdout.text ?? null, + stderr: failure.snapshot?.stderr.text ?? null, + }, + }, + { operation: context.operation, cause: failure }, + ); + }, + // Only the configuration phase checks the selected Python by path. + recognise: (cause) => + phase === "configuration" && cause instanceof Error && "code" in cause + ? pwntoolsUnavailable( + `Selected Python executable is unavailable (${String(cause.code)}): ${path}. Check the caller-selected path and execute access.`, + path, + String(cause.code), + undefined, + context, + ) + : undefined, + ...(phase === "artifact-read" + ? { + file: { + path, + description: "object", + retainCompletedIdentity: true, + fileSize: (limit, details) => + new AnalysisInputError( + context.operation, + { + ...details, + userMessage: `${limit.message} ${pwntoolsInputLimitFact(limits.input_bytes, context.inputBytesSource)} ${pwntoolsBudgetRecovery(limits)}`, + remediationAction: pwntoolsInputLimitRecovery( + limits.input_bytes, + context.inputBytesSource, + ), + limit: analysisSettingLimit( + "pwntools.max_input_bytes", + limits.input_bytes, + context.inputBytesSource, + ), + }, + [ + { + path: ["path"], + reason: "out_of_range", + message: `${limit.message} REA_PWNTOOLS_MAX_INPUT_BYTES defaults to ${String(PWNTOOLS_LIMITS.input_bytes)} bytes.`, + }, + ], + ), + }, + } + : {}), + observedOutput: context.precedingOutput, + unclassified: (cause, details) => + new ProviderAdapterError(context.providerId, context.operation, { + ...details, + cause, + diagnostics: { + ...pwntoolsPhaseDiagnostics(state), + reason: cause instanceof Error ? cause.message : String(cause), + }, + }), + }; }; -const classifyPwntoolsDecoderFailure = ( - cause: unknown, - phase: string, - path: string, - executablePath: string, - failureEvidence: PwntoolsFailureEvidence, - context: PwntoolsFailureContext, -): AnalysisError => { +/** The owned Python bridge's dialect: its reserved exits and selected budgets. */ +const pwntoolsCommandContext = ( + state: PwntoolsPhase, + limits: PwntoolsProducerLimits, +): ProviderOutcomeContext => { + const { executablePath, failureEvidence, context } = state; const limitReport = failureEvidence.limits; - const limits = context.producerLimits ?? resolvePwntoolsLimits(); const budgetRecovery = pwntoolsBudgetRecovery(limits); - if (cause instanceof AnalysisError) return cause; - if (cause instanceof OwnedCommandFailure) { - const currentOutput = - cause.snapshot === null - ? undefined - : capturedPwntoolsOutput(cause.snapshot); - const combinedOutput = - context.precedingOutput === undefined - ? currentOutput - : currentOutput === undefined - ? context.precedingOutput - : { - stdout: `[core decoder]\n${context.precedingOutput.stdout}\n[debugger]\n${currentOutput.stdout}`, - stderr: `[core decoder]\n${context.precedingOutput.stderr}\n[debugger]\n${currentOutput.stderr}`, - truncated: - context.precedingOutput.truncated || currentOutput.truncated, - }; - const outputOptions = { - ...(combinedOutput === undefined + const reportFailure = + limitReport?.failure === null || limitReport === undefined + ? "" + : ` Effective limit report unavailable: ${limitReport.failure}`; + const reportedLimits = limitReport?.limits ?? null; + const allowance = fileSizeAllowance( + limitReport?.limits?.file_size_bytes, + limits.file_bytes, + ); + const fileSizeRecovery = `Review the reported worker file-size limits and write failure. ${allowance} Repeating the unchanged request fails the same way.`; + const timeoutMs = context.timeoutMs ?? PWNTOOLS_LIMITS.command_timeout_ms; + const deadline = nativeDeadlineRecovery({ + timeoutMs, + setting: "pwntools_timeout_ms", + cliFlag: "--pwntools-timeout-ms", + defaultMs: PWNTOOLS_LIMITS.command_timeout_ms, + phase: "pwntools command deadline", + unchanged: budgetRecovery, + }); + return { + operation: context.operation, + capturedOutput: (snapshot) => + combinedPwntoolsOutput(snapshot, context) ?? + capturedPwntoolsOutput(snapshot), + details: { + // A failure before any output still reports the earlier stage's output. + ...(context.precedingOutput === undefined ? {} - : { capturedOutput: combinedOutput }), + : { capturedOutput: context.precedingOutput }), ...(failureEvidence.finalizationFailures === undefined ? {} : { @@ -171,261 +249,127 @@ const classifyPwntoolsDecoderFailure = ( failureEvidence.finalizationFailures, }, }), - }; - if (cause.cleanupFailure !== null) - return new ProviderCleanupError( - context.providerId, - cause.resources, - { - reason: cause.cleanupFailure, - ...(combinedOutput === undefined - ? {} - : { - captured_output: { ...combinedOutput }, - }), - previous_error: { - failure_kind: cause.reason, - message: cause.message, - exit_code: cause.snapshot?.exitCode ?? null, - signal: cause.snapshot?.signal ?? null, - stdout: cause.snapshot?.stdout.text ?? null, - stderr: cause.snapshot?.stderr.text ?? null, - }, - }, - { operation: context.operation, cause }, - ); - if (cause.reason === "cancelled") - return new AnalysisCancelledError(context.operation, { - ...outputOptions, - cause: - cause.cancellation === undefined - ? cause.cause - : cause.cancellation.reason, - }); - if (cause.reason === "timeout") { - const timeoutMs = context.timeoutMs ?? PWNTOOLS_LIMITS.command_timeout_ms; - return new AnalysisTimeoutError(context.operation, timeoutMs, { - ...outputOptions, - ...nativeDeadlineRecovery({ - timeoutMs, - setting: "pwntools_timeout_ms", - cliFlag: "--pwntools-timeout-ms", - defaultMs: PWNTOOLS_LIMITS.command_timeout_ms, - phase: "pwntools command deadline", - unchanged: budgetRecovery, - }), - }); - } - if (cause.reason === "output-limit") - return new AnalysisOutputError(context.operation, cause.message, { - ...outputOptions, - userMessage: `${cause.message} ${budgetRecovery}`, - remediationAction: budgetRecovery, - }); - if ( - cause.reason === "process" && - (cause.snapshot?.signal === "SIGXFSZ" || - (failureEvidence.marker?.resource === "file-size" && - cause.snapshot?.exitCode === PWNTOOLS_FILE_SIZE_FAILURE_EXIT && - cause.snapshot.signal === null)) - ) { - const allowance = fileSizeAllowance( - limitReport?.limits?.file_size_bytes, - limits.file_bytes, - ); - return new AnalysisResourceConstraintError( - context.operation, - "file-size", - (cause.snapshot.signal === "SIGXFSZ" - ? "Owned Python terminated with SIGXFSZ; the exact signal cause is unknown." - : "The owned Python bridge reported EFBIG while writing a file; the exact write failure cause is unknown.") + - (limitReport?.failure === null || limitReport === undefined - ? "" - : ` Effective limit report unavailable: ${limitReport.failure}`) + - ` ${allowance}`, - limitReport?.limits ?? null, - { - ...outputOptions, - remediationAction: `Review the reported worker file-size limits and write failure. ${allowance} Repeating the unchanged request fails the same way.`, - }, - ); - } - if (cause.reason === "process" && cause.snapshot?.signal === "SIGXCPU") - return new AnalysisResourceConstraintError( - context.operation, - "cpu", - "Owned Python terminated with SIGXCPU; the exact signal cause is unknown." + - (limitReport?.failure === null || limitReport === undefined - ? "" - : ` Effective limit report unavailable: ${limitReport.failure}`) + - ` Selected producer_limits.cpu_seconds is ${String(limits.cpu_seconds)} seconds; inherited tighter limits remain enforced.`, - limitReport?.limits ?? null, - { - ...outputOptions, - remediationAction: `Review the reported worker CPU limit and observed signal; the signal alone does not establish exhaustion. Increase producer_limits.cpu_seconds above ${String(limits.cpu_seconds)} on the next call (CLI --producer-limits JSON) when that policy was limiting. No restart is required; a tighter inherited limit remains enforced. pwntools_timeout_ms does not raise CPU admission.`, - }, - ); - if ( - cause.reason === "process" && - failureEvidence.marker?.resource === "memory" && - cause.snapshot?.exitCode === PWNTOOLS_MEMORY_FAILURE_EXIT && - cause.snapshot.signal === null - ) - return new AnalysisResourceConstraintError( - context.operation, - "memory", - "The owned Python bridge reported a memory allocation failure without a structured reply; the exact allocation cause is unknown." + - (limitReport?.failure === null || limitReport === undefined - ? "" - : ` Effective limit report unavailable: ${limitReport.failure}`) + - ` The selected producer_limits.address_space_bytes allowance is ${String(limits.address_space_bytes)} bytes; tighter inherited limits remain enforced.`, - limitReport?.limits ?? null, - { - ...outputOptions, - remediationAction: `Review the reported worker memory limits and available host memory. ${budgetRecovery}`, - }, - ); - } - if ( - cause instanceof Error && - "code" in cause && - "syscall" in cause && - typeof cause.syscall === "string" && - cause.syscall.startsWith("spawn ") - ) - return pwntoolsUnavailable( - `Selected Python could not launch (${String(cause.code)}): ${executablePath}. Check the configured executable, its interpreter and host execute access.`, - executablePath, - String(cause.code), - undefined, - context, - ); - if (cause instanceof ArtifactReaderFailure) { - if (cause.reason === "integrity") - return new AnalysisArtifactChangedError( - context.operation, - path, - cause.message, - { - cause, - }, - ); - if (cause.reason === "cancelled") { - const error = new AnalysisCancelledError(context.operation, { - cause: artifactFileCancellationCause(cause), - cleanup: cause.cleanup, - partialObservation: cause.partialObservation, - capturedOutput: context.precedingOutput, - }); - bindArtifactFileCleanup(cause, error); - return error; - } - if ( - cause.reason === "limit" || - cause.reason === "path" || - cause.reason === "format" - ) - return new AnalysisInputError( - context.operation, - { - cause, - ...stableArtifactInputRecovery(cause), - ...(cause.reason === "limit" - ? { - userMessage: `${cause.message} ${pwntoolsInputLimitFact(limits.input_bytes, context.inputBytesSource)} ${budgetRecovery}`, - remediationAction: pwntoolsInputLimitRecovery( - limits.input_bytes, - context.inputBytesSource, - ), - limit: analysisSettingLimit( - "pwntools.max_input_bytes", - limits.input_bytes, - context.inputBytesSource, - ), - } - : {}), - }, - [ - { - path: ["path"], - reason: - cause.reason === "limit" ? "out_of_range" : "invalid_format", - message: - cause.reason === "limit" - ? `${cause.message} REA_PWNTOOLS_MAX_INPUT_BYTES defaults to ${String(PWNTOOLS_LIMITS.input_bytes)} bytes.` - : cause.message, - }, - ], - ); - } - if (cause instanceof Error && "code" in cause) { - if (phase === "configuration") - return pwntoolsUnavailable( - `Selected Python executable is unavailable (${String(cause.code)}): ${path}. Check the caller-selected path and execute access.`, - path, - String(cause.code), - undefined, - context, - ); - if ( - phase === "artifact-read" && - (cause.code === "EACCES" || cause.code === "EPERM") - ) - return new AnalysisAccessDeniedError( - context.operation, - path, - cause.code, - { - cause, - }, - ); - if ( - phase === "artifact-read" && - (cause.code === "ENOENT" || cause.code === "ENOTDIR") - ) - return new AnalysisInputError(context.operation, { cause }, [ - { - path: ["path"], - reason: "invalid_value", - message: `Selected object could not be read (${String(cause.code)}): ${path}.`, - }, - ]); - } - return new ProviderAdapterError(context.providerId, context.operation, { - cause, - diagnostics: { - phase, - path, - ...(failureEvidence.finalizationFailures === undefined - ? {} - : { - receipt_finalization_failures: failureEvidence.finalizationFailures, - }), - ...(context.precedingOutput === undefined - ? {} - : { preceding_output: { ...context.precedingOutput } }), - reason: cause instanceof Error ? cause.message : String(cause), - ...(failureEvidence.marker === undefined - ? {} - : { resource_failure_marker: { ...failureEvidence.marker } }), - ...(cause instanceof OwnedCommandFailure - ? { - failure_kind: cause.reason, - exit_code: cause.snapshot?.exitCode ?? null, - signal: cause.snapshot?.signal ?? null, - stdout: cause.snapshot?.stdout.text ?? null, - stderr: cause.snapshot?.stderr.text ?? null, - ...(cause.snapshot === null - ? {} - : { - captured_output: { - ...capturedPwntoolsOutput(cause.snapshot), - }, - }), - } - : {}), }, - }); + timeout: { + ms: timeoutMs, + userMessage: deadline.userMessage, + remediationAction: deadline.remediationAction, + }, + outputLimit: { + limits: { + output_bytes: limits.output_bytes, + diagnostic_bytes: limits.diagnostic_bytes, + }, + recovery: { remediationAction: budgetRecovery }, + }, + resourceSignal: (signal) => + signal === "SIGXFSZ" + ? { + limits: reportedLimits, + detail: `${reportFailure} ${allowance}`.trim(), + recovery: { remediationAction: fileSizeRecovery }, + } + : { + limits: reportedLimits, + detail: + `${reportFailure} Selected producer_limits.cpu_seconds is ${String(limits.cpu_seconds)} seconds; inherited tighter limits remain enforced.`.trim(), + recovery: { + remediationAction: `Review the reported worker CPU limit and observed signal; the signal alone does not establish exhaustion. Increase producer_limits.cpu_seconds above ${String(limits.cpu_seconds)} on the next call (CLI --producer-limits JSON) when that policy was limiting. No restart is required; a tighter inherited limit remains enforced. pwntools_timeout_ms does not raise CPU admission.`, + }, + }, + dialect: (outcome, details) => { + if (outcome.kind === "launch-refused") + return pwntoolsUnavailable( + `Selected Python could not launch (${outcome.refusal.code}): ${executablePath}. Check the configured executable, its interpreter and host execute access.`, + executablePath, + outcome.refusal.code, + undefined, + context, + ); + // A reserved exit means a resource failure only when the bridge's + // marker names that resource. + const reservedExit = + outcome.kind === "exited" && outcome.signal === null + ? outcome.exitCode + : undefined; + const marked = failureEvidence.marker?.resource; + if ( + marked === "file-size" && + reservedExit === PWNTOOLS_FILE_SIZE_FAILURE_EXIT + ) + return new AnalysisResourceConstraintError( + context.operation, + "file-size", + `The owned Python bridge reported EFBIG while writing a file; the exact write failure cause is unknown.${reportFailure} ${allowance}`, + reportedLimits, + { ...details, remediationAction: fileSizeRecovery }, + ); + if (marked === "memory" && reservedExit === PWNTOOLS_MEMORY_FAILURE_EXIT) + return new AnalysisResourceConstraintError( + context.operation, + "memory", + `The owned Python bridge reported a memory allocation failure without a structured reply; the exact allocation cause is unknown.${reportFailure} The selected producer_limits.address_space_bytes allowance is ${String(limits.address_space_bytes)} bytes; tighter inherited limits remain enforced.`, + reportedLimits, + { + ...details, + remediationAction: `Review the reported worker memory limits and available host memory. ${budgetRecovery}`, + }, + ); + // The shared owner already carries the command's output as + // `details.capturedOutput`; diagnostics keep only the exit facts. + const snapshot = outcome.output?.snapshot; + return new ProviderAdapterError(context.providerId, context.operation, { + ...details, + diagnostics: { + ...pwntoolsPhaseDiagnostics(state), + reason: outcome.message, + failure_kind: + outcome.cause instanceof OwnedCommandFailure + ? outcome.cause.reason + : outcome.kind, + exit_code: snapshot?.exitCode ?? null, + signal: snapshot?.signal ?? null, + }, + }); + }, + }; +}; + +/** Diagnostics every unrecognised pwntools failure reports. */ +const pwntoolsPhaseDiagnostics = ({ + phase, + path, + failureEvidence, + context, +}: PwntoolsPhase) => ({ + phase, + path, + ...(failureEvidence.finalizationFailures === undefined + ? {} + : { receipt_finalization_failures: failureEvidence.finalizationFailures }), + ...(context.precedingOutput === undefined + ? {} + : { preceding_output: { ...context.precedingOutput } }), + ...(failureEvidence.marker === undefined + ? {} + : { resource_failure_marker: { ...failureEvidence.marker } }), +}); + +/** The debugger's output follows the core decoder's when both ran. */ +const combinedPwntoolsOutput = ( + snapshot: ProviderProcessSnapshot | null, + context: PwntoolsFailureContext, +): AnalysisCapturedOutput | undefined => { + const current = + snapshot === null ? undefined : capturedPwntoolsOutput(snapshot); + const preceding = context.precedingOutput; + if (preceding === undefined || current === undefined) + return current ?? preceding; + return { + stdout: `[core decoder]\n${preceding.stdout}\n[debugger]\n${current.stdout}`, + stderr: `[core decoder]\n${preceding.stderr}\n[debugger]\n${current.stderr}`, + truncated: preceding.truncated || current.truncated, + }; }; /** Report caller-selected engine absence with its actual configuration and host constraint. */ diff --git a/src/process/classifyProviderOutcome.ts b/src/process/classifyProviderOutcome.ts index 9bc903ff4cc..c7c60887b12 100644 --- a/src/process/classifyProviderOutcome.ts +++ b/src/process/classifyProviderOutcome.ts @@ -70,6 +70,8 @@ export interface ProviderOutcomeContext { readonly resourceSignal?: (signal: "SIGXCPU" | "SIGXFSZ") => { readonly limits: ReportedLimits; readonly recovery: ResourceConstraintRecovery; + /** Provider facts appended to the shared report, such as the selected allowance. */ + readonly detail?: string; }; /** * The provider's memory setting for a runtime exhaustion report, such as @@ -148,7 +150,7 @@ export const classifyProviderOutcome = ( return new AnalysisResourceConstraintError( operation, outcome.signal === "SIGXFSZ" ? "file-size" : "cpu", - `Producer terminated with ${outcome.signal}; the signal's exact cause is not independently established.`, + `Producer terminated with ${outcome.signal}; the signal's exact cause is not independently established.${reported?.detail === undefined ? "" : ` ${reported.detail}`}`, reported?.limits ?? null, { ...details, ...reported?.recovery }, ); diff --git a/src/providers/classifyProviderFailure.ts b/src/providers/classifyProviderFailure.ts index 61a0a988107..8cafe75bafa 100644 --- a/src/providers/classifyProviderFailure.ts +++ b/src/providers/classifyProviderFailure.ts @@ -144,6 +144,10 @@ const fileFailure = ( carriedReason(artifactFileCancellationCause(physical)), { ...cancellationDetails, + // What the reader had already established stays reported. + ...(physical.partialObservation === undefined + ? {} + : { partialObservation: physical.partialObservation }), ...(dialect.observedOutput === undefined ? {} : { capturedOutput: dialect.observedOutput }), diff --git a/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts b/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts index 2a5eea58311..265de9b9251 100644 --- a/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts +++ b/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts @@ -80,7 +80,7 @@ it.runIf(!unsupportedHost).each([ expect(result.error.message).toContain( failure === "EFBIG" ? "exact write failure cause is unknown" - : "exact signal cause is unknown", + : "exact cause is not independently established", ); if (scenario !== "reported") expect(result.error.message).toContain("limit report unavailable"); @@ -138,7 +138,7 @@ it.runIf(!unsupportedHost)( capturedOutput: { truncated: true, stderr: "" }, diagnostics: { primary_error: { - code: "unreadable_output", + code: "resource_constraint", }, cleanup_error: { code: "cleanup_incomplete", @@ -288,7 +288,7 @@ it.runIf(!unsupportedHost).each([ if (result.ok) throw new Error("Excess diagnostics must not return partial success"); expect(projectAnalysisError(result.error)).toMatchObject({ - code: "unreadable_output", + code: "resource_constraint", details: { captured_output: { truncated: true } }, }); } @@ -400,14 +400,12 @@ it.runIf(!unsupportedHost).each(["cancelled", "output-limit", "process"])( scenario === "cancelled" ? "AnalysisCancelledError" : scenario === "output-limit" - ? "AnalysisOutputError" + ? "AnalysisResourceConstraintError" : "ProviderAdapterError", ...(scenario === "process" ? { - diagnostics: { - exit_code: 7, - stderr: "decoder exited unexpectedly", - }, + diagnostics: { exit_code: 7 }, + capturedOutput: { stderr: "decoder exited unexpectedly" }, } : {}), }, diff --git a/tests/boundary/binaryDiagnostics/recordedCrashProvider.test.ts b/tests/boundary/binaryDiagnostics/recordedCrashProvider.test.ts index e872c15ebf8..8bf60a1370b 100644 --- a/tests/boundary/binaryDiagnostics/recordedCrashProvider.test.ts +++ b/tests/boundary/binaryDiagnostics/recordedCrashProvider.test.ts @@ -471,7 +471,9 @@ const expectOptionalContextFailure = ( details: { diagnostics: { preceding_output: { stdout: "basic stage diagnostic" }, - stderr: "debugger failed", + }, + captured_output: { + stderr: expect.stringContaining("debugger failed"), }, }, }); diff --git a/tests/process-global/pwntoolsCleanup.test.ts b/tests/process-global/pwntoolsCleanup.test.ts index d28557f0311..df5b0aeaa53 100644 --- a/tests/process-global/pwntoolsCleanup.test.ts +++ b/tests/process-global/pwntoolsCleanup.test.ts @@ -118,7 +118,7 @@ it.runIf(supportedHost)( capturedOutput: { truncated: true }, diagnostics: { primary_error: { - code: "unreadable_output", + code: "resource_constraint", }, cleanup_error: { code: "cleanup_incomplete" }, }, @@ -213,11 +213,9 @@ it.runIf(supportedHost)( throw new Error("Expected command and root-removal failures"); expect(result.error).toMatchObject({ cleanupIncomplete: true, + capturedOutput: { stdout: "retained diagnostic" }, diagnostics: { - primary_error: { - code: "execution_failure", - details: { diagnostics: { stdout: "retained diagnostic" } }, - }, + primary_error: { code: "execution_failure" }, cleanup_error: { code: "cleanup_incomplete" }, }, }); diff --git a/tests/process-global/pwntoolsCliFinalization.test.ts b/tests/process-global/pwntoolsCliFinalization.test.ts index 6f264db5fe4..fd707a24dab 100644 --- a/tests/process-global/pwntoolsCliFinalization.test.ts +++ b/tests/process-global/pwntoolsCliFinalization.test.ts @@ -142,10 +142,8 @@ it.runIf(supportedHost).each(["decoded", "failed"] as const)( expect(output).toMatchObject({ code: "execution_failure", details: { - diagnostics: { - exit_code: 2, - captured_output: { stdout: "decoder output" }, - }, + diagnostics: { exit_code: 2 }, + captured_output: { stdout: "decoder output" }, }, }); expect(output).not.toHaveProperty("details.cleanup"); diff --git a/tests/process-global/pwntoolsStageRetirement.test.ts b/tests/process-global/pwntoolsStageRetirement.test.ts index 08afd470e95..abfc9de5621 100644 --- a/tests/process-global/pwntoolsStageRetirement.test.ts +++ b/tests/process-global/pwntoolsStageRetirement.test.ts @@ -191,7 +191,9 @@ it.runIf(supportedHost).each(["decoder", "debugger"] as const)( phase: stage, resource_failure_marker: { resource: null }, exit_code: PWNTOOLS_MEMORY_FAILURE_EXIT, - captured_output: { stdout: "stage diagnostic" }, + }, + captured_output: { + stdout: expect.stringContaining("stage diagnostic"), }, }, }); @@ -362,7 +364,7 @@ it.runIf(supportedHost)( code: "cleanup_incomplete", details: { captured_output: { truncated: true }, - diagnostics: { primary_error: { code: "unreadable_output" } }, + diagnostics: { primary_error: { code: "resource_constraint" } }, partial_observation: { artifact: { path }, diagnostics: { stdout: "basic diagnostic" },