From f5055cd2ed46a6d3bab28e8f90d82fd9381a5dbe Mon Sep 17 00:00:00 2001 From: Sandiv Date: Mon, 30 Nov 2026 22:38:45 +1100 Subject: [PATCH] fix(process): report denied inspection as typed cleanup failures (#9261) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(process): report denied inspection as typed cleanup failures Preserve the native ps diagnostic through owned-worker cleanup and finalize one-shot JavaScript analysis before Evidence delivery. Retain mandatory inspection and existing cleanup authority. Preserve the inspector diagnostic when the initial process-table read succeeds but pre-signal revalidation fails, and remove the unreachable typed-error branch so retained artifact retry failures project through the existing cleanup contract. * fix(resources): preserve independent close failure ownership * fix(cli): retain cleanup recovery and nested close evidence * refactor(providers): classify rejected closes at the shared boundary * test(cli): preserve bundle metadata and physical inspection failures * fix(cli): preserve the JavaScript failure envelope after finalization * test(cli): validate the JavaScript error envelope at its boundary * fix(providers): preserve unnamed close failure resources * fix(cli): retain invocation owners through outer cleanup * test(cli): distinguish reported cleanup failures from uncaught errors * fix(cli): compose each runtime’s declared cleanup owners * test(cli): preserve the original cleanup rejection * test(cli): allow cleanup retry recovery after a reported failure * fix(cli): report final cleanup after returned results * fix(cli): preserve launcher executable mode * test(cli): retain invocation cleanup in file sessions --------- Co-authored-by: Vincent Koc --- .../javascript-artifact-reconstruction.md | 10 + scripts/rea.mjs | 20 +- src/cli.ts | 3 + src/cli/cliCommandRegistration.ts | 3 + src/cli/cliCommandRegistrations.ts | 11 +- src/cli/cliResources.ts | 22 +- src/cli/cliShell.ts | 4 + src/cli/coreAnalysisCommands.ts | 10 +- src/cli/coreBinaryCommands.ts | 13 +- src/cli/electronCommands.ts | 12 +- src/cli/javascriptApplicationAnalysis.ts | 85 ++++-- src/cliLoader.ts | 50 +++- src/cliOneShot.ts | 4 +- src/domain/analysisErrorCleanup.ts | 9 +- .../analysis/JavaScriptAnalysisWorker.ts | 23 +- src/process/OwnedWorkerRuntime.ts | 23 +- ...ProcessOwnership.inspectionFailure.test.ts | 187 ++++++++++++ .../ProcessOwnership.listCancellation.test.ts | 17 +- src/process/ProcessOwnership.ts | 44 ++- src/process/ProcessOwnershipObservation.ts | 48 ++- src/providers/artifactCloseFailure.ts | 117 ++++++++ src/providers/classifyProviderFailure.test.ts | 48 +++ src/providers/classifyProviderFailure.ts | 3 + src/providers/runOwned.ts | 28 +- src/resources/ArtifactReader.ts | 24 ++ src/resources/ArtifactResourceScope.test.ts | 281 +++++++++++++++++- src/resources/ArtifactResourceScope.ts | 42 ++- .../cli/cliJavaScriptResourceClose.test.ts | 214 +++++++++++++ tests/boundary/cli/cliOwnedResources.test.ts | 65 ++++ tests/boundary/cli/dispatcher.test.ts | 27 ++ .../javascriptInspectionCleanupCli.test.ts | 104 +++++++ .../fixtures/javascriptInspectionPreload.mjs | 53 ++++ tests/support/cli/cliCommandSessionWorker.mjs | 8 +- 33 files changed, 1501 insertions(+), 111 deletions(-) create mode 100644 src/process/ProcessOwnership.inspectionFailure.test.ts create mode 100644 src/providers/artifactCloseFailure.ts create mode 100644 tests/boundary/cli/javascriptInspectionCleanupCli.test.ts create mode 100644 tests/fixtures/javascriptInspectionPreload.mjs diff --git a/docs/guides/javascript/javascript-artifact-reconstruction.md b/docs/guides/javascript/javascript-artifact-reconstruction.md index 950b06cba2c..c9dad2b2189 100644 --- a/docs/guides/javascript/javascript-artifact-reconstruction.md +++ b/docs/guides/javascript/javascript-artifact-reconstruction.md @@ -10,6 +10,16 @@ then [read the analysis](#read-the-analysis). Use [application workflows](javasc for tracing and comparisons, or [partial recovery](#recover-partial-analysis) when an operation is interrupted. +If process-table inspection fails after analysis completes, the one-shot CLI returns +`cleanup_incomplete` with completed Evidence in `details.partial_observation`. +`details.diagnostics.inspection` identifies the inspector command, arguments, +and observed system error (for example `EPERM`). REA selects `ps` from its fixed +system locations, then the caller's PATH only when none is executable. Use a host +context that permits the reported inspector to execute and read the process table, +and review the reported retained resources. Analysis completion does not establish +cleanup. REA keeps inspection mandatory and ownership unresolved until the owning +runtime confirms resource release. + ## Public workflow The tool reads the caller-selected local directory or ASAR path directly: diff --git a/scripts/rea.mjs b/scripts/rea.mjs index 61b27e71e82..35e46dd7cc8 100755 --- a/scripts/rea.mjs +++ b/scripts/rea.mjs @@ -180,13 +180,19 @@ if (!(await compiledRuntimeExists(packageRoot, runtimeFiles))) { } catch (cleanup) { // The exit callback reports this same shared failure and then exits. if (!exiting) { - dispatchFailure = - dispatchFailure === undefined - ? cleanup - : new AggregateError( - [dispatchFailure, cleanup], - "CLI dispatch failed and the JavaScript analysis worker remained owned", - ); + if (dispatchFailure === undefined) { + // A handled command result already owns stdout and its exit status. + process.stderr.write( + `Failed to close CLI resources: ${cleanupFailureText(cleanup)}\n`, + ); + if (process.exitCode === undefined || process.exitCode === 0) + process.exitCode = 1; + } else { + dispatchFailure = new AggregateError( + [dispatchFailure, cleanup], + "CLI dispatch failed and the JavaScript analysis worker remained owned", + ); + } } } } diff --git a/src/cli.ts b/src/cli.ts index 7a65c3605c9..98e08cede0c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -9,6 +9,7 @@ import { type CliCommandModules, } from "./cli/cliCommandRegistrations.js"; import type { CliResultOutput } from "./cli/cliResultOutput.js"; +import type { CliJavaScriptAnalysisHost } from "./cli/javascriptApplicationAnalysis.js"; import { createCliShell } from "./cli/cliShell.js"; import type { CliInstance } from "./cli/types.js"; import { createDirectAnalysis } from "./composition/directAnalysis.js"; @@ -157,12 +158,14 @@ export const createCli = ( resultOutput?: CliResultOutput, fridaInstrumentation?: FridaInstrumentationPort, savedDefaults?: ReadonlySet, + javascriptAnalysis?: CliJavaScriptAnalysisHost, ): CliInstance => createCliShell({ selectedEnvironment, resultOutput, fridaInstrumentation, savedDefaults, + javascriptAnalysis, createAnalysis: createDirectAnalysis, registrations: CLI_REGISTRATION_ORDER.map((id) => ({ registration: CLI_COMMAND_REGISTRATIONS[id], diff --git a/src/cli/cliCommandRegistration.ts b/src/cli/cliCommandRegistration.ts index 10f66bbf3a7..0db0de54d48 100644 --- a/src/cli/cliCommandRegistration.ts +++ b/src/cli/cliCommandRegistration.ts @@ -3,6 +3,7 @@ import type { Logger } from "pino"; import type { FridaInstrumentationPort } from "../ports/frida/FridaInstrumentationPort.js"; import type { DirectAnalysis } from "../composition/directAnalysis.js"; import type { CliInstance } from "./types.js"; +import type { CliJavaScriptAnalysisHost } from "./javascriptApplicationAnalysis.js"; /** What a command registrar receives. */ export interface CliRegistrationContext { @@ -11,6 +12,8 @@ export interface CliRegistrationContext { readonly environment: Readonly>; readonly savedDefaults: ReadonlySet | undefined; readonly fridaInstrumentation: FridaInstrumentationPort | undefined; + /** Invocation-scoped JavaScript worker owner; absent when hosts stay reusable. */ + readonly javascriptAnalysis: CliJavaScriptAnalysisHost | undefined; } /** Context for registrars that run direct or provider analysis. */ diff --git a/src/cli/cliCommandRegistrations.ts b/src/cli/cliCommandRegistrations.ts index 0500e89dd5b..ce8aaa975b5 100644 --- a/src/cli/cliCommandRegistrations.ts +++ b/src/cli/cliCommandRegistrations.ts @@ -29,6 +29,7 @@ export const CLI_COMMAND_REGISTRATIONS = { context.logger, context.analysis.runDirectAnalysis, context.environment, + context.javascriptAnalysis, ), ), reverseEngineering: cliRegistrarWithEnvironment( @@ -217,9 +218,15 @@ export const CLI_COMMAND_REGISTRATIONS = { () => import("./browserScenarioCommands.js"), "registerBrowserScenarioCommands", ), - electron: cliRegistrarWithEnvironment( + electron: plain( () => import("./electronCommands.js"), - "registerElectronCommands", + (module, context) => + module.registerElectronCommands( + context.cli, + context.logger, + context.environment, + { javascriptAnalysis: context.javascriptAnalysis }, + ), ), javaScriptRuntimeObservation: cliRegistrarWithEnvironment( () => import("./javascriptRuntimeCommands.js"), diff --git a/src/cli/cliResources.ts b/src/cli/cliResources.ts index 0f54b3f02cd..6d6b27d00d9 100644 --- a/src/cli/cliResources.ts +++ b/src/cli/cliResources.ts @@ -47,12 +47,30 @@ export const registerCliScopeCleanup = ( * A closer can throw before it returns a promise. Each call starts on its * own turn so that failure stays with its owner and the others still settle. */ -export const closeCliResources = async (): Promise => { +const settleCliResources = async ( + owners: readonly (() => Promise)[], +): Promise => { const results = await Promise.allSettled( - [...closers.values()].map((close) => Promise.resolve().then(close)), + owners.map((close) => Promise.resolve().then(close)), ); const failures = results.flatMap((result) => result.status === "rejected" ? [result.reason] : [], ); throwCleanupFailures(failures, "CLI resource cleanup failed"); }; + +export const closeCliResources = (): Promise => + settleCliResources([...closers.values()]); + +/** Retain all runtime owners and share each attempt until every owner settles. */ +export const createCliResourceCloser = ( + ...owners: readonly (() => Promise)[] +): (() => Promise) => { + let closing: Promise | undefined; + return () => { + closing ??= settleCliResources(owners).finally(() => { + closing = undefined; + }); + return closing; + }; +}; diff --git a/src/cli/cliShell.ts b/src/cli/cliShell.ts index 01d917f8af2..88fef053d4c 100644 --- a/src/cli/cliShell.ts +++ b/src/cli/cliShell.ts @@ -1,6 +1,7 @@ import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import type { FridaInstrumentationPort } from "../ports/frida/FridaInstrumentationPort.js"; +import type { CliJavaScriptAnalysisHost } from "./javascriptApplicationAnalysis.js"; import { parseCliGlobalArguments } from "../cliBuiltinArguments.js"; import type { DirectAnalysis } from "../composition/directAnalysis.js"; import { parseLogLevel } from "../config/processStart.js"; @@ -39,6 +40,8 @@ export interface CliShellOptions { ) => DirectAnalysis; readonly resultOutput?: CliResultOutput | undefined; readonly fridaInstrumentation?: FridaInstrumentationPort | undefined; + /** Invocation-scoped JavaScript worker owner, when this invocation finalizes it. */ + readonly javascriptAnalysis?: CliJavaScriptAnalysisHost | undefined; } /** Run each registrar, creating analysis once for those that declare it. */ @@ -91,6 +94,7 @@ export const createCliShell = (options: CliShellOptions): CliInstance => { environment, savedDefaults: options.savedDefaults, fridaInstrumentation: options.fridaInstrumentation, + javascriptAnalysis: options.javascriptAnalysis, }, options, ); diff --git a/src/cli/coreAnalysisCommands.ts b/src/cli/coreAnalysisCommands.ts index 7211dd22156..c6f464a7642 100644 --- a/src/cli/coreAnalysisCommands.ts +++ b/src/cli/coreAnalysisCommands.ts @@ -3,6 +3,7 @@ import type { Logger } from "pino"; import { registerCoreBinaryCommands } from "./coreBinaryCommands.js"; import { registerCoreNativeCommands } from "./coreNativeCommands.js"; import type { CliInstance } from "./types.js"; +import type { CliJavaScriptAnalysisHost } from "./javascriptApplicationAnalysis.js"; /** Register core binary and native deep-analysis CLI commands. */ export const registerCoreAnalysisCommands = ( @@ -10,7 +11,14 @@ export const registerCoreAnalysisCommands = ( logger: Logger, runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], environment: Readonly>, + javascriptAnalysis?: CliJavaScriptAnalysisHost, ): void => { - registerCoreBinaryCommands(cli, logger, runDirectAnalysis, environment); + registerCoreBinaryCommands( + cli, + logger, + runDirectAnalysis, + environment, + javascriptAnalysis, + ); registerCoreNativeCommands(cli, logger, runDirectAnalysis); }; diff --git a/src/cli/coreBinaryCommands.ts b/src/cli/coreBinaryCommands.ts index 9f682a17d57..b111bff215d 100644 --- a/src/cli/coreBinaryCommands.ts +++ b/src/cli/coreBinaryCommands.ts @@ -16,6 +16,7 @@ import type { CliInstance } from "./types.js"; import { javaScriptApplicationCliProjection, runJavaScriptApplicationCommand, + type CliJavaScriptAnalysisHost, } from "./javascriptApplicationAnalysis.js"; import { registerDecompileDirectoryCommand } from "./decompileDirectoryCommand.js"; import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/officialToolContracts.js"; @@ -45,9 +46,16 @@ export const registerCoreBinaryCommands = ( logger: Logger, runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], environment: Readonly>, + javascriptAnalysis?: CliJavaScriptAnalysisHost, ): void => { const run = runDirectOnTarget(runDirectAnalysis, logger); - registerOverviewCommands(cli, logger, runDirectAnalysis, environment); + registerOverviewCommands( + cli, + logger, + runDirectAnalysis, + environment, + javascriptAnalysis, + ); registerDecompileCommand(cli, logger, run); registerDecompileDirectoryCommand(cli, logger, run); registerSearchCommand(cli, logger, run); @@ -187,6 +195,7 @@ const registerOverviewCommands = ( logger: Logger, runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], environment: Readonly>, + javascriptAnalysis?: CliJavaScriptAnalysisHost, ): void => { const description = "Get an overview of an app"; const target = "App, program, or analysis database path"; @@ -201,7 +210,7 @@ const registerOverviewCommands = ( viewDelivery: { invalidJson: "view must be valid JSON" }, }, // Route JavaScript targets exactly like analyze-javascript-application. - runJavaScriptApplicationCommand(environment), + runJavaScriptApplicationCommand(environment, javascriptAnalysis), { takes: async ({ path }) => typeof path === "string" && isJavaScriptApplicationPath(path), diff --git a/src/cli/electronCommands.ts b/src/cli/electronCommands.ts index 4ed1b34ad43..d4f033e1818 100644 --- a/src/cli/electronCommands.ts +++ b/src/cli/electronCommands.ts @@ -24,6 +24,7 @@ import { ELECTRON_FUSE_PROVIDER_IDENTITY } from "../electron/ElectronFuseProvide import { javaScriptApplicationCliProjection, runJavaScriptApplicationCommand, + type CliJavaScriptAnalysisHost, } from "./javascriptApplicationAnalysis.js"; import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; import type { ElectronActiveObservationPort } from "../ports/javascript/ElectronActiveObservationPort.js"; @@ -38,6 +39,7 @@ export const registerElectronCommands = ( logger: Logger, environment: Readonly>, options: { + readonly javascriptAnalysis?: CliJavaScriptAnalysisHost | undefined; readonly createActiveProvider?: ( environment: Readonly>, ) => ElectronActiveObservationPort; @@ -46,7 +48,12 @@ export const registerElectronCommands = ( registerElectronObservationCommands(cli, logger, environment); registerElectronFuseCommand(cli, logger); registerElectronActiveCommand(cli, logger, environment, options); - registerJavaScriptApplicationCommand(cli, logger, environment); + registerJavaScriptApplicationCommand( + cli, + logger, + environment, + options.javascriptAnalysis, + ); registerJavaScriptRuntimeReconciliationCommand(cli, logger); }; @@ -282,6 +289,7 @@ const registerJavaScriptApplicationCommand = ( cli: CliInstance, logger: Logger, environment: Readonly>, + javascriptAnalysis?: CliJavaScriptAnalysisHost, ): void => { registerContractCommand( cli as CliInstance, @@ -296,7 +304,7 @@ const registerJavaScriptApplicationCommand = ( evidenceDelivery: true, viewDelivery: { invalidJson: "view must be valid JSON" }, }, - runJavaScriptApplicationCommand(environment), + runJavaScriptApplicationCommand(environment, javascriptAnalysis), ); }; diff --git a/src/cli/javascriptApplicationAnalysis.ts b/src/cli/javascriptApplicationAnalysis.ts index 7516448a3dd..c3a438900ff 100644 --- a/src/cli/javascriptApplicationAnalysis.ts +++ b/src/cli/javascriptApplicationAnalysis.ts @@ -4,22 +4,24 @@ import type { AnalysisViewRequest } from "../domain/analysisView/analysisViewReq import { publishCliAnalysisEvidence } from "./analysisEvidenceDelivery.js"; import { JAVASCRIPT_APPLICATION_PROVIDER } from "../domain/investigationProviders.js"; import { createProgressReporter } from "../ports/ProgressReporter.js"; -import { - ArtifactReaderFailure, - ArtifactResourceScope, -} from "../resources/index.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { ArtifactResourceScope } from "../resources/index.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { completeProviderEvidence } from "../application/ProviderOperationExecution.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import type { JsonValue } from "../domain/jsonValue.js"; -import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; import { javaScriptSourcePathsSchema } from "../domain/javascript/javascriptSourceSelection.js"; import { parseCliJsonInput } from "./cliJsonInput.js"; import { writeCliProgressLine } from "./cliProgress.js"; import { ownCliProcessResource } from "./cliResources.js"; +import type { AnalysisCallerLifetime } from "../domain/analysisErrorBase.js"; +import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; +import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js"; +import { classifyProviderFailure } from "../providers/classifyProviderFailure.js"; +import { artifactCloseFailureDialect } from "../providers/artifactCloseFailure.js"; const OPERATION = "analyze_javascript_application"; +const CLI_ERROR = "JavaScript application analysis failed"; /** * Combine repeated `--source-path` values with `--source-paths-json`, an inline @@ -57,14 +59,16 @@ export const cliJavaScriptSourcePaths = async ( }; /** - * One parked JavaScript worker for one CLI host. A healthy worker stays - * parked between that host's commands. Independent hosts do not share it. + * JavaScript resources for one CLI host. Reusable hosts park healthy workers; + * invocation hosts finalize them before returning analysis. Hosts do not share scopes. */ export class CliJavaScriptAnalysisHost { #retainedScope: ArtifactResourceScope | undefined; - /** One shutdown shared by the exit callback and the dispatch `finally`. */ + /** Concurrent callers share one shutdown attempt; failed close stays retryable. */ #closing: Promise | undefined; + constructor(readonly callerLifetime: AnalysisCallerLifetime = "continuing") {} + scope(): ArtifactResourceScope { this.#retainedScope ??= new ArtifactResourceScope(); return this.#retainedScope; @@ -123,39 +127,68 @@ export const runCliJavaScriptApplicationAnalysis = async ( { minimumIntervalMs: 0 }, ); const resources = host.scope(); - const result = await analyzeJavaScriptApplication(input, resources, { + let result = await analyzeJavaScriptApplication(input, resources, { sourceAnalysis: javascriptSourceAnalysis, environment, progress, ...(signal === undefined ? {} : { signal }), }); + let completedBeforeCleanup: + | ReturnType + | undefined; try { // Retry failed owners without stopping a healthy parked worker. await resources.retryCleanup(); } catch (cause: unknown) { - const cleanup = ArtifactReaderFailure.cleanupObservation( + const failure = classifyProviderFailure( cause, - "JavaScript application resources", - ); - const failure = new ProviderCleanupError( - JAVASCRIPT_APPLICATION_PROVIDER.id, - cleanup.resources, - { reason: cleanup.reason }, - { cause, operation: "analyze_javascript_application" }, + artifactCloseFailureDialect( + JAVASCRIPT_APPLICATION_PROVIDER.id, + OPERATION, + "JavaScript application resources", + ), ); const completed = result.ok ? completeProviderEvidence(result.value, signal) : result; - if (completed.ok) failure.retainPartialObservation(completed.value); - return cliError( - completed.ok + if (completed.ok) { + completedBeforeCleanup = completed; + failure.retainPartialObservation(completed.value); + } + result = { + ok: false, + error: completed.ok ? failure - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( completed.error, failure, "analyze_javascript_application", ), + }; + } + if (host.callerLifetime === "invocation") { + const finalized = await finishAnalysisCommand( + async () => result, + host, + JAVASCRIPT_APPLICATION_PROVIDER.id, + OPERATION, + signal ?? new AbortController().signal, + undefined, + { + recoverResolvedCleanup: () => + completedBeforeCleanup?.ok ? completedBeforeCleanup.value : undefined, + }, ); + const output = finalized.ok + ? finalized + : { ok: false as const, error: { error: CLI_ERROR, ...finalized.error } }; + return delivery === undefined + ? projectCliAnalysisResult(output) + : publishCliAnalysisEvidence(output, { + ...delivery, + operation: OPERATION, + signal: signal ?? new AbortController().signal, + }); } const completed = result.ok ? completeProviderEvidence(result.value, signal) @@ -177,7 +210,7 @@ export const runCliJavaScriptApplicationAnalysis = async ( const cliError = ( error: Parameters[0], ): JsonValue => ({ - error: "JavaScript application analysis failed", + error: CLI_ERROR, ...projectAnalysisError(error), }); @@ -231,7 +264,10 @@ export const javaScriptApplicationCliProjection = (target: string) => * delivering Evidence as the caller selected. */ export const runJavaScriptApplicationCommand = - (environment: Readonly>) => + ( + environment: Readonly>, + host: CliJavaScriptAnalysisHost = processJavaScriptAnalysis, + ) => async ( input: object & { readonly source_paths?: readonly string[] | undefined }, { @@ -258,5 +294,6 @@ export const runJavaScriptApplicationCommand = environment, signal, delivery, + host, ); }; diff --git a/src/cliLoader.ts b/src/cliLoader.ts index 5cb07496d81..de7c310393b 100644 --- a/src/cliLoader.ts +++ b/src/cliLoader.ts @@ -77,35 +77,61 @@ export const loadCliRuntime = async ( global: CliGlobalArguments | undefined, environment: NodeJS.ProcessEnv, savedDefaults: ReadonlySet | undefined, + options: { readonly finalizeJavaScriptAnalysis?: boolean } = {}, ): Promise => { const ids = selectCliRegistrations( global, RECORDED_CLI_COMMAND_REGISTRATIONS, ); + // Load the JavaScript worker owner only for invocations that can run its + // registrars; other commands keep their recorded module graph. + const javascriptAnalysis = + options.finalizeJavaScriptAnalysis === true && + (ids === undefined || + ids.includes("coreAnalysis") || + ids.includes("electron")) + ? new ( + await import("./cli/javascriptApplicationAnalysis.js") + ).CliJavaScriptAnalysisHost("invocation") + : undefined; + const { createCliResourceCloser, closeCliResources: closeProcessResources } = + await import("./cli/cliResources.js"); + const retainInvocationOwner = (close: () => Promise) => + createCliResourceCloser( + close, + ...(javascriptAnalysis === undefined + ? [] + : [() => javascriptAnalysis.close()]), + ); if (ids === undefined) { const { createCli, closeCliResources } = await import("./cli.js"); return { createCli: (resultOutput) => - createCli(environment, resultOutput, undefined, savedDefaults), - closeCliResources, + createCli( + environment, + resultOutput, + undefined, + savedDefaults, + javascriptAnalysis, + ), + closeCliResources: retainInvocationOwner(closeCliResources), }; } const selected = ids.map((id) => CLI_COMMAND_REGISTRATIONS[id]); - const [modules, { createCliShell }, { closeCliResources }, analysis] = - await Promise.all([ - Promise.all(selected.map((registration) => registration.load())), - import("./cli/cliShell.js"), - import("./cli/cliResources.js"), - selected.some((registration) => registration.analysis) - ? import("./composition/directAnalysis.js") - : undefined, - ]); + const [modules, { createCliShell }, analysis] = await Promise.all([ + Promise.all(selected.map((registration) => registration.load())), + import("./cli/cliShell.js"), + selected.some((registration) => registration.analysis) + ? import("./composition/directAnalysis.js") + : undefined, + ]); return { createCli: (resultOutput) => createCliShell({ selectedEnvironment: environment, savedDefaults, resultOutput, + javascriptAnalysis, registrations: selected.map((registration, index) => ({ registration, module: modules[index], @@ -114,6 +140,6 @@ export const loadCliRuntime = async ( ? {} : { createAnalysis: analysis.createDirectAnalysis }), }), - closeCliResources, + closeCliResources: retainInvocationOwner(closeProcessResources), }; }; diff --git a/src/cliOneShot.ts b/src/cliOneShot.ts index 0d4a9292e17..6cb21ee9864 100644 --- a/src/cliOneShot.ts +++ b/src/cliOneShot.ts @@ -164,7 +164,9 @@ export const runOneShotCli = async ( // Loaded only now: the documents above answer without the command catalog. const { loadCliRuntime } = await import("./cliLoader.js"); - const runtime = await loadCliRuntime(global, environment, savedDefaults); + const runtime = await loadCliRuntime(global, environment, savedDefaults, { + finalizeJavaScriptAnalysis: true, + }); host.ownCliResources(runtime.closeCliResources); const { createCliResultOutput, cliOutputCancellationStatus } = await import("./cli/cliResultOutput.js"); diff --git a/src/domain/analysisErrorCleanup.ts b/src/domain/analysisErrorCleanup.ts index 6f3c59fb29a..2d789f90bf2 100644 --- a/src/domain/analysisErrorCleanup.ts +++ b/src/domain/analysisErrorCleanup.ts @@ -2,7 +2,10 @@ import type { JsonValue } from "./jsonValue.js"; import { ProviderAdapterError } from "./providerAdapterError.js"; import { ProviderCleanupError } from "./providerCleanupError.js"; import { childFailureDiagnostics } from "./analysisErrorProjection.js"; -import type { AnalysisError } from "./analysisErrorBase.js"; +import type { + AnalysisError, + AnalysisErrorOptions, +} from "./analysisErrorBase.js"; import { analysisErrorUserMessage, composedCallerGuidance, @@ -153,6 +156,7 @@ export const providerCleanupErrorFromCloseRejections = ( readonly operation: string; readonly message: string; readonly remediationAction?: string; + readonly invocationDiagnostics?: AnalysisErrorOptions["invocationDiagnostics"]; }, ): ProviderCleanupError => { const owners = rejections.flatMap(({ cleanupOwner }) => @@ -174,6 +178,9 @@ export const providerCleanupErrorFromCloseRejections = ( diagnostics, { operation: options.operation, + ...(options.invocationDiagnostics === undefined + ? {} + : { invocationDiagnostics: options.invocationDiagnostics }), cause: new AggregateError( rejections.map(({ cause }) => cause), options.message, diff --git a/src/javascript/analysis/JavaScriptAnalysisWorker.ts b/src/javascript/analysis/JavaScriptAnalysisWorker.ts index ccbfd2599e4..c1761e3441c 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorker.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorker.ts @@ -60,6 +60,7 @@ import { } from "../../domain/analysisErrorCore.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; +import type { ProcessInspectionDiagnostic } from "../../process/ProcessOwnership.js"; import { ok, err, type Result } from "../../domain/result.js"; import { javaScriptRuntime } from "../../domain/runtimeVersion.js"; import { @@ -751,6 +752,7 @@ export class JavaScriptAnalysisWorker { this.#lastFailure, cause.cleanupResources, cause.processId, + cause.inspection, ); cause.bindCleanupFailure(error); throw error; @@ -1431,6 +1433,7 @@ export class JavaScriptAnalysisWorker { this.#lastFailure, cause.cleanupResources, cause.processId, + cause.inspection, ); cause.bindCleanupFailure(error); return error; @@ -1502,6 +1505,7 @@ export class JavaScriptAnalysisWorker { ], processId: number | null = this.#runtime.supervisor?.launch.process.pid ?? null, + inspection?: ProcessInspectionDiagnostic, ): ProviderCleanupError { return new ProviderCleanupError( PROVIDER, @@ -1509,6 +1513,14 @@ export class JavaScriptAnalysisWorker { { reason, worker_pid: processId, + ...(inspection === undefined + ? {} + : { + inspection: { + ...inspection, + arguments: [...inspection.arguments], + }, + }), ...(original === undefined ? {} : { @@ -1525,6 +1537,9 @@ export class JavaScriptAnalysisWorker { }, { operation: OPERATION, + ...(inspection === undefined + ? {} + : { remediationAction: inspection.remediation_action }), ...(original === undefined ? {} : { cleanupPrimary: original }), cause: new Error( reason, @@ -1539,7 +1554,13 @@ export class JavaScriptAnalysisWorker { const stopped = await this.#runtime.stop(); if (stopped.status === "incomplete") { this.#resetState(); - const error = this.#cleanupError(stopped.reason, original); + const error = this.#cleanupError( + stopped.reason, + original, + undefined, + undefined, + stopped.cleanupResult?.inspection, + ); this.#runtime.bindCleanupFailure(error); return error; } diff --git a/src/process/OwnedWorkerRuntime.ts b/src/process/OwnedWorkerRuntime.ts index fc6c4d63300..5f1dd580e9c 100644 --- a/src/process/OwnedWorkerRuntime.ts +++ b/src/process/OwnedWorkerRuntime.ts @@ -9,7 +9,10 @@ import { type ProviderProcessStopResult, type ProviderProcessOutputTokenOptions, } from "./ProviderProcess.js"; -import { cleanupOwnedProcessGroup } from "./ProcessOwnership.js"; +import { + cleanupOwnedProcessGroup, + type ProcessInspectionDiagnostic, +} from "./ProcessOwnership.js"; import type { AnalysisCleanupReleaseClaim, AnalysisCleanupResourceOwner, @@ -75,17 +78,21 @@ export const processWorkerCleanup = new WorkerCleanupRegistry(); export class OwnedWorkerRuntimeCleanupError extends Error { readonly #cleanupEpoch: OwnedWorkerRuntimeCleanupEpoch | undefined; + readonly inspection: ProcessInspectionDiagnostic | undefined; constructor( readonly cleanupResources: readonly string[], readonly processId: number | null, message: string, cleanupEpoch: OwnedWorkerRuntimeCleanupEpoch | undefined, - options?: ErrorOptions, + options?: ErrorOptions & { + readonly inspection?: ProcessInspectionDiagnostic; + }, ) { super(message, options); this.name = "OwnedWorkerRuntimeCleanupError"; this.#cleanupEpoch = cleanupEpoch; + this.inspection = options?.inspection; } bindCleanupFailure(error: AnalysisError): void { @@ -442,7 +449,11 @@ export class OwnedWorkerRuntime { if (acquisition !== undefined) await acquisition.catch(() => undefined); const stopped = await this.stop(); if (stopped.status === "incomplete") - throw this.#cleanupError(stopped.reason); + throw this.#cleanupError( + stopped.reason, + undefined, + stopped.cleanupResult?.inspection, + ); if (this.#root !== undefined) { try { await this.#root.close(); @@ -492,6 +503,7 @@ export class OwnedWorkerRuntime { #cleanupError( reason: string, cause?: unknown, + inspection?: ProcessInspectionDiagnostic, ): OwnedWorkerRuntimeCleanupError { const resources = this.cleanupResources ?? []; return new OwnedWorkerRuntimeCleanupError( @@ -499,7 +511,10 @@ export class OwnedWorkerRuntime { this.#supervisor?.launch.process.pid ?? null, reason, this.#cleanupEpoch, - cause === undefined ? undefined : { cause }, + { + ...(cause === undefined ? {} : { cause }), + ...(inspection === undefined ? {} : { inspection }), + }, ); } } diff --git a/src/process/ProcessOwnership.inspectionFailure.test.ts b/src/process/ProcessOwnership.inspectionFailure.test.ts new file mode 100644 index 00000000000..cea435d677a --- /dev/null +++ b/src/process/ProcessOwnership.inspectionFailure.test.ts @@ -0,0 +1,187 @@ +import { expect, it, vi } from "vitest"; + +const inspect = vi.hoisted(() => vi.fn()); +vi.mock("./ExecFileOutput.js", async (importOriginal) => ({ + ...(await importOriginal()), + execFileOutput: inspect, +})); + +import { ExecFileOutputCancelledError } from "./ExecFileOutput.js"; +import { createSystemProcessOwnershipHost } from "./ProcessOwnershipObservation.js"; +import { + cleanupOwnedProcessGroup, + verifyNoTokenOwnedProcesses, +} from "./ProcessOwnership.js"; + +it.each(["darwin", "linux"] as const)( + "preserves the denied inspector at the %s host and cleanup boundaries", + async (platform) => { + inspect.mockRejectedValue( + Object.assign(new Error("spawn EPERM"), { + code: "EPERM", + syscall: "spawn ps", + }), + ); + const signalGroup = vi.fn(); + const host = { + ...createSystemProcessOwnershipHost( + platform, + {}, + { linuxPsLocations: [] }, + ), + signalGroup, + }; + const command = platform === "darwin" ? "/bin/ps" : "ps"; + const diagnostic = { + capability: "process_table", + command, + arguments: ["-axo", "pid=,ppid=,pgid=,uid=,stat=,command="], + system_code: "EPERM", + reason: "spawn EPERM", + }; + await expect(host.listProcesses()).rejects.toMatchObject({ + inspection: diagnostic, + }); + for (const outcome of [ + await cleanupOwnedProcessGroup( + { leaderPid: 100, processGroupId: 100, runId: "fixture" }, + host, + ), + await verifyNoTokenOwnedProcesses("fixture", host), + ]) { + expect(outcome).toMatchObject({ cleaned: false, inspection: diagnostic }); + } + expect(signalGroup).not.toHaveBeenCalled(); + }, +); + +it("retains inspection failure on the launcher-exit refresh without replacing the identity failure", async () => { + inspect.mockResolvedValueOnce({ stdout: "100 1 100 501 S fixture\n" }); + inspect.mockRejectedValueOnce( + Object.assign(new Error("spawn EPERM"), { code: "EPERM" }), + ); + const native = createSystemProcessOwnershipHost( + "linux", + {}, + { linuxPsLocations: [] }, + ); + const signalGroup = vi.fn(); + const result = await cleanupOwnedProcessGroup( + { + leaderPid: 100, + processGroupId: 100, + runId: "fixture", + expectedParentPid: 2, + }, + { + listProcesses: native.listProcesses, + environment: async () => ({ REA_PROCESS_RUN_ID: "fixture" }), + signalGroup, + }, + ); + expect(result).toMatchObject({ + cleaned: false, + reason: expect.stringContaining("parent"), + inspection: { command: "ps", system_code: "EPERM" }, + }); + expect(signalGroup).not.toHaveBeenCalled(); +}); + +it("retains the denied inspector when the pre-signal process-table refresh fails", async () => { + inspect.mockReset(); + inspect.mockResolvedValueOnce({ stdout: "100 1 100 501 S fixture\n" }); + inspect.mockRejectedValueOnce( + Object.assign(new Error("spawn EPERM"), { + code: "EPERM", + syscall: "spawn ps", + }), + ); + const native = createSystemProcessOwnershipHost( + "linux", + {}, + { linuxPsLocations: [] }, + ); + const signalGroup = vi.fn(); + const signalPid = vi.spyOn(process, "kill").mockReturnValue(true); + try { + const result = await cleanupOwnedProcessGroup( + { leaderPid: 100, processGroupId: 100, runId: "fixture" }, + { + listProcesses: native.listProcesses, + environment: async () => ({ REA_PROCESS_RUN_ID: "fixture" }), + signalGroup, + }, + ); + expect(inspect).toHaveBeenCalledTimes(2); + expect(signalGroup).not.toHaveBeenCalled(); + expect(signalPid).not.toHaveBeenCalled(); + expect(result).toMatchObject({ + cleaned: false, + reason: + "process ownership could not be revalidated: ps process-table inspection failed: spawn EPERM", + inspection: { + capability: "process_table", + command: "ps", + arguments: ["-axo", "pid=,ppid=,pgid=,uid=,stat=,command="], + system_code: "EPERM", + syscall: "spawn ps", + reason: "spawn EPERM", + remediation_action: expect.stringContaining("host context permits"), + }, + }); + if (result.cleaned) throw new Error("Expected unverified cleanup"); + expect(result.inspection?.system_code).toBe("EPERM"); + } finally { + signalPid.mockRestore(); + } +}); + +it("keeps unclassified revalidation failures unchanged without inferring inspector facts", async () => { + const signalGroup = vi.fn(); + const listProcesses = vi + .fn() + .mockResolvedValueOnce([ + { + pid: 100, + parentPid: 1, + processGroupId: 100, + state: "S", + command: "fixture", + }, + ]) + .mockRejectedValueOnce( + Object.assign(new Error("custom inspector failure"), { code: "EPERM" }), + ); + expect( + await cleanupOwnedProcessGroup( + { leaderPid: 100, processGroupId: 100, runId: "fixture" }, + { + listProcesses, + environment: async () => ({ REA_PROCESS_RUN_ID: "fixture" }), + signalGroup, + }, + ), + ).toEqual({ + cleaned: false, + reason: + "process ownership could not be revalidated: custom inspector failure", + }); + expect(listProcesses).toHaveBeenCalledTimes(2); + expect(signalGroup).not.toHaveBeenCalled(); +}); + +it("keeps caller cancellation distinct from an inspection refusal", async () => { + const controller = new AbortController(); + const reason = new Error("caller stopped inspection"); + controller.abort(reason); + inspect.mockRejectedValueOnce(new ExecFileOutputCancelledError(reason)); + const host = createSystemProcessOwnershipHost( + "linux", + {}, + { linuxPsLocations: [] }, + ); + await expect(host.listProcesses(controller.signal)).rejects.toMatchObject({ + _tag: "ProcessOwnershipInspectionCancelled", + reason, + }); +}); diff --git a/src/process/ProcessOwnership.listCancellation.test.ts b/src/process/ProcessOwnership.listCancellation.test.ts index 6bbac34f64c..a9d0bd6037b 100644 --- a/src/process/ProcessOwnership.listCancellation.test.ts +++ b/src/process/ProcessOwnership.listCancellation.test.ts @@ -9,7 +9,10 @@ vi.mock("./ExecFileOutput.js", async (original) => ({ import { AnalysisOutputError } from "../domain/analysisErrorCore.js"; import { ExecFileOutputCancelledError } from "./ExecFileOutput.js"; import { ProcessOwnershipInspectionCancelled } from "./ProcessInspectionCancellation.js"; -import { createSystemProcessOwnershipHost } from "./ProcessOwnershipObservation.js"; +import { + createSystemProcessOwnershipHost, + ProcessTableInspectionError, +} from "./ProcessOwnershipObservation.js"; import { readRunTokenCarriers } from "./ProcessRunTokenObservations.js"; const routes = ["list", "carriers"] as const; @@ -63,6 +66,16 @@ it.each(routes)( route === "list" ? host.listProcesses(controller.signal) : readRunTokenCarriers(host, "authored-run", controller.signal); - await expect(pending).rejects.toBe(physical); + const failure = await pending.catch((cause: unknown) => cause); + expect(failure).toBeInstanceOf(ProcessTableInspectionError); + expect(failure).not.toBeInstanceOf(ProcessOwnershipInspectionCancelled); + if (!(failure instanceof ProcessTableInspectionError)) throw failure; + expect(failure.cause).toBe(physical); + expect(failure.inspection).toMatchObject({ + capability: "process_table", + command: expect.stringMatching(/(?:^|\/)ps$/u), + system_code: null, + reason: physical.message, + }); }, ); diff --git a/src/process/ProcessOwnership.ts b/src/process/ProcessOwnership.ts index 92b47400671..9c449d99cd4 100644 --- a/src/process/ProcessOwnership.ts +++ b/src/process/ProcessOwnership.ts @@ -6,6 +6,7 @@ import { promisify } from "node:util"; import { setTimeout as delay } from "node:timers/promises"; import { + ProcessTableInspectionError, readNativeProcessIdentityMap, readProcessOwnershipFacts, reobserveUnavailableTokenFacts, @@ -291,6 +292,18 @@ export interface ProcessCleanupFailure { readonly signaled?: boolean; readonly failures?: readonly ProcessOwnershipValidationFailure[]; readonly unverified?: readonly OwnershipSweepUnverifiedProcess[]; + readonly inspection?: ProcessInspectionDiagnostic; +} + +/** Facts from the owner of a failed process-table command, without its environment. */ +export interface ProcessInspectionDiagnostic { + readonly capability: "process_table"; + readonly command: string; + readonly arguments: readonly string[]; + readonly system_code: string | number | null; + readonly syscall: string | null; + readonly reason: string; + readonly remediation_action: string; } /** Token-verified liveness result used by post-root-exit settlement. */ @@ -426,6 +439,9 @@ const cleanupOwnedProcessGroupAttempt = async ( return { cleaned: false, reason: `process table could not be inspected: ${processTable.reason}`, + ...(processTable.inspection === undefined + ? {} + : { inspection: processTable.inspection }), }; const plan = await createOwnedCleanupPlan( ownership, @@ -572,6 +588,9 @@ export const verifyNoTokenOwnedProcesses = async ( return { cleaned: false, reason: `process table could not be inspected: ${processTable.reason}`, + ...(processTable.inspection === undefined + ? {} + : { inspection: processTable.inspection }), }; const scan = await scanTokenOwnedProcesses( processTable.processes, @@ -603,7 +622,11 @@ const readLiveProcessTable = async ( readonly available: true; readonly processes: readonly ProcessTableEntry[]; } - | { readonly available: false; readonly reason: string } + | { + readonly available: false; + readonly reason: string; + readonly inspection?: ProcessInspectionDiagnostic; + } > => { try { return { @@ -612,7 +635,13 @@ const readLiveProcessTable = async ( }; } catch (cause: unknown) { rethrowProcessInspectionFailure(cause); - return { available: false, reason: errorMessage(cause) }; + return { + available: false, + reason: errorMessage(cause), + ...(cause instanceof ProcessTableInspectionError + ? { inspection: cause.inspection } + : {}), + }; } }; @@ -1019,7 +1048,13 @@ const settleLauncherExit = async ( classified.kind === "escaped" ? classified.groupIds : [], }; } - return { cleaned: false, reason }; + return { + cleaned: false, + reason, + ...(!refreshed.available && refreshed.inspection !== undefined + ? { inspection: refreshed.inspection } + : {}), + }; }; const createOwnedCleanupPlan = async ( @@ -1322,6 +1357,9 @@ const revalidateOwnedProcessGroup = async ( return { cleaned: false, reason: `process ownership could not be revalidated: ${errorMessage(cause)}`, + ...(cause instanceof ProcessTableInspectionError + ? { inspection: cause.inspection } + : {}), }; } const { failures, validatedMembers } = await processOwnershipFailures( diff --git a/src/process/ProcessOwnershipObservation.ts b/src/process/ProcessOwnershipObservation.ts index 235e7adfa8d..d5acebff1a4 100644 --- a/src/process/ProcessOwnershipObservation.ts +++ b/src/process/ProcessOwnershipObservation.ts @@ -62,6 +62,7 @@ import type { ProcessOwnershipBaseline, ProcessRunTokenObservation, ProcessTableEntry, + ProcessInspectionDiagnostic, } from "./ProcessOwnership.js"; import type { ProcessOwnershipEvidenceOwner } from "./ProcessOwnershipEvidence.js"; import { errorMessage } from "../kernel/errorMessage.js"; @@ -76,6 +77,35 @@ const rethrowInspectionFailure = (cause: unknown): void => { rethrowProcessOwnershipInspectionFailure(cause); }; +/** The native inspector owns command identity and error classification. */ +export class ProcessTableInspectionError extends Error { + readonly _tag = "ProcessTableInspectionError"; + readonly inspection: ProcessInspectionDiagnostic; + + constructor(command: string, arguments_: readonly string[], cause: unknown) { + const reason = errorMessage(cause); + super(`${command} process-table inspection failed: ${reason}`, { cause }); + this.name = "ProcessTableInspectionError"; + const code = + cause instanceof Error && "code" in cause ? cause.code : undefined; + const syscall = + cause instanceof Error && "syscall" in cause ? cause.syscall : undefined; + this.inspection = { + capability: "process_table", + command, + arguments: [...arguments_], + system_code: + typeof code === "string" || + (typeof code === "number" && Number.isSafeInteger(code)) + ? code + : null, + syscall: typeof syscall === "string" ? syscall : null, + reason, + remediation_action: `Ensure ${command} is available and the host context permits it to execute and read the process table. Review the reported retained resources; cleanup remains unverified until the owning runtime confirms release.`, + }; + } +} + /** Observe multiple groups from one process snapshot and one token batch. */ export const observeOwnedProcessGroups = async ( runId: string, @@ -1587,10 +1617,20 @@ export const createSystemProcessOwnershipHost = ( * Execution failures keep their identity; the message names the `ps` that * ran (`spawn /usr/bin/ps ENOENT`, or bare `ps` for the PATH fallback). */ - const listProcesses = async (signal?: AbortSignal) => - platform === "win32" - ? [] - : await listProcessesWith(await selectPs(), signal); + const listProcesses = async (signal?: AbortSignal) => { + if (platform === "win32") return []; + const ps = await selectPs(); + try { + return await listProcessesWith(ps, signal); + } catch (cause: unknown) { + rethrowInspectionFailure(cause); + throw new ProcessTableInspectionError( + ps.command, + PROCESS_INVENTORY_PS_ARGUMENTS, + cause, + ); + } + }; const safeListProcesses = async (signal?: AbortSignal) => { const ps = await selectPs(); try { diff --git a/src/providers/artifactCloseFailure.ts b/src/providers/artifactCloseFailure.ts new file mode 100644 index 00000000000..4767b571b4f --- /dev/null +++ b/src/providers/artifactCloseFailure.ts @@ -0,0 +1,117 @@ +import { + AnalysisCleanupLeaseGroup, + ArtifactReaderFailure, +} from "../resources/index.js"; +import { AnalysisError } from "../domain/analysisErrorBase.js"; +import { providerCleanupErrorFromCloseRejections } from "../domain/analysisErrorCleanup.js"; +import { childFailureDiagnostics } from "../domain/analysisErrorProjection.js"; +import { ProviderCleanupError } from "../domain/providerCleanupError.js"; +import { + classifyProviderFailure, + type ProviderFailureDialect, +} from "./classifyProviderFailure.js"; + +/** Rejected closes keep their own diagnostics, evidence and release authority. */ +export const artifactCloseFailureDialect = ( + providerId: string, + operation: string, + fallbackResource: string | readonly string[], +): ProviderFailureDialect => ({ + providerId, + operation, + phase: "close", + unclassified: (cause) => { + const observation = ArtifactReaderFailure.cleanupObservation( + cause, + fallbackResource, + ); + if ( + cause instanceof ArtifactReaderFailure && + cause.cleanupRejections !== undefined + ) { + const children = cause.cleanupRejections.map((rejection) => { + const child = classifyProviderFailure( + rejection.cause, + artifactCloseFailureDialect( + providerId, + operation, + rejection.cleanup.resources, + ), + ); + if (rejection.cleanupLeases === undefined) + return { cause: rejection.cause, error: child, leased: false }; + const projection = childFailureDiagnostics( + { cleanup_error: { error: child } }, + { reason: rejection.cleanup.reason }, + ); + const error = new ProviderCleanupError( + providerId, + rejection.cleanup.resources, + projection.diagnostics ?? {}, + { + cause: rejection.cause, + operation, + ...(projection.invocationDiagnostics === undefined + ? {} + : { invocationDiagnostics: projection.invocationDiagnostics }), + ...(child.partialObservation === undefined + ? {} + : { partialObservation: child.partialObservation }), + }, + ); + new AnalysisCleanupLeaseGroup(error, rejection.cleanupLeases); + return { cause: rejection.cause, error, leased: true }; + }); + const diagnostics = childFailureDiagnostics( + Object.fromEntries( + children.map(({ error }, index) => [ + `cleanup_error_${index + 1}`, + { error }, + ]), + ), + { reason: observation.reason }, + ); + const error = providerCleanupErrorFromCloseRejections( + providerId, + children.map(({ cause: rejection, error: child, leased }) => ({ + cause: rejection, + cleanupOwner: + leased || + (rejection instanceof AnalysisError && + rejection.cleanupIncomplete) || + (rejection instanceof ArtifactReaderFailure && + ((rejection.cleanup !== undefined && + rejection.cleanupLeases !== undefined) || + rejection.cleanupRejections !== undefined)) + ? child + : undefined, + unconfirmedResources: child.cleanupResources, + })), + diagnostics.diagnostics ?? {}, + { + operation, + message: observation.reason, + ...(diagnostics.invocationDiagnostics === undefined + ? {} + : { invocationDiagnostics: diagnostics.invocationDiagnostics }), + }, + ); + if (cause.partialObservation !== undefined) + error.retainPartialObservation(cause.partialObservation); + return error; + } + const error = new ProviderCleanupError( + providerId, + observation.resources, + { reason: observation.reason }, + { cause, operation }, + ); + if (cause instanceof ArtifactReaderFailure) { + if (cause.cleanup !== undefined && cause.cleanupLeases !== undefined) + new AnalysisCleanupLeaseGroup(error, cause.cleanupLeases); + if (cause.partialObservation !== undefined) + error.retainPartialObservation(cause.partialObservation); + } + return error; + }, +}); diff --git a/src/providers/classifyProviderFailure.test.ts b/src/providers/classifyProviderFailure.test.ts index d646a74d33f..209b4663001 100644 --- a/src/providers/classifyProviderFailure.test.ts +++ b/src/providers/classifyProviderFailure.test.ts @@ -14,6 +14,54 @@ import { AnalysisTimeoutError, } from "../domain/analysisErrorCore.js"; import { classifyProviderFailure } from "./classifyProviderFailure.js"; +import { artifactCloseFailureDialect } from "./artifactCloseFailure.js"; +import { ProviderCleanupError } from "../domain/providerCleanupError.js"; + +describe("classifyProviderFailure close phase", () => { + it("retains a launch denial as cleanup only at a rejected close boundary", () => { + const cause = Object.assign(new Error("spawn /bin/ps EPERM"), { + code: "EPERM", + syscall: "spawn /bin/ps", + path: "/bin/ps", + }); + const close = classifyProviderFailure( + cause, + artifactCloseFailureDialect("fixture", "close", "worker"), + ); + expect(close).toBeInstanceOf(ProviderCleanupError); + expect(close.cleanupIncomplete).toBe(true); + expect(close.cleanupResources).toEqual(["worker"]); + expect( + classifyProviderFailure(cause, { + providerId: "fixture", + operation: "launch", + unclassified: () => { + throw new Error("expected shared launch classification"); + }, + }), + ).not.toBeInstanceOf(ProviderCleanupError); + }); + + it("does not interpret a reader error without cleanup as confirmed release", () => { + const cause = new ArtifactReaderFailure("unavailable", "hook refused"); + const error = classifyProviderFailure( + cause, + artifactCloseFailureDialect("fixture", "close", "worker"), + ); + expect(error.cleanupIncomplete).toBe(true); + expect(error.cleanupResources).toEqual(["worker"]); + }); + + it("preserves already typed failures at a rejected close boundary", () => { + const cause = new AnalysisOutputError("close", "hook failed"); + expect( + classifyProviderFailure( + cause, + artifactCloseFailureDialect("fixture", "close", "worker"), + ), + ).toBe(cause); + }); +}); describe("classifyProviderFailure attribution", () => { const unclassified = (cause: unknown) => diff --git a/src/providers/classifyProviderFailure.ts b/src/providers/classifyProviderFailure.ts index d87b78e4f19..b43ad98ce17 100644 --- a/src/providers/classifyProviderFailure.ts +++ b/src/providers/classifyProviderFailure.ts @@ -59,6 +59,8 @@ export interface ProviderFileDialect { export interface ProviderFailureDialect { readonly providerId: string; readonly operation: string; + /** A rejected close is cleanup, even when its cause describes a command launch. */ + readonly phase?: "close"; /** * Attribution for a typed failure a lower layer already classified, such as * the accepted operation and the redacted endpoint it reached. Without it a @@ -272,6 +274,7 @@ export const classifyProviderFailure = ( ): AnalysisError => { if (cause instanceof AnalysisError) return dialect.attribute?.(cause) ?? cause; + if (dialect.phase === "close") return dialect.unclassified(cause, {}); const outcome = providerOutcomeOf(cause); if (outcome !== undefined && dialect.command !== undefined) return commandFailure(cause, outcome, dialect, dialect.command); diff --git a/src/providers/runOwned.ts b/src/providers/runOwned.ts index 2dc5eda5227..87036cf2527 100644 --- a/src/providers/runOwned.ts +++ b/src/providers/runOwned.ts @@ -25,7 +25,8 @@ import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import type { JsonValue } from "../domain/jsonValue.js"; import type { Result } from "../domain/result.js"; -import { errorMessage } from "../kernel/errorMessage.js"; +import { classifyProviderFailure } from "./classifyProviderFailure.js"; +import { artifactCloseFailureDialect } from "./artifactCloseFailure.js"; /** What closing the work's owner established. */ export type CleanupOutcome = @@ -209,22 +210,15 @@ const closeFailure = ( "providerId" | "operation" | "fallbackResource" >, ): AnalysisError => { - if (cause instanceof AnalysisError) return cause; - const observation = - cause instanceof ArtifactReaderFailure - ? ArtifactReaderFailure.cleanupObservation( - cause, - options.fallbackResource ?? `${options.operation} resources`, - ) - : { - reason: errorMessage(cause), - resources: [], - }; - return new ProviderCleanupError( - options.providerId, - observation.resources, - { reason: observation.reason }, - { cause, operation: options.operation }, + return classifyProviderFailure( + cause, + artifactCloseFailureDialect( + options.providerId, + options.operation, + cause instanceof ArtifactReaderFailure + ? (options.fallbackResource ?? `${options.operation} resources`) + : [], + ), ); }; diff --git a/src/resources/ArtifactReader.ts b/src/resources/ArtifactReader.ts index ab637c60e91..280be8d1a0a 100644 --- a/src/resources/ArtifactReader.ts +++ b/src/resources/ArtifactReader.ts @@ -37,6 +37,13 @@ import { } from "../domain/targetFailure.js"; import { ParseFailureError } from "../domain/parseFailure.js"; +/** One rejected close, with facts and optional authority from its owner. */ +export interface ArtifactCleanupRejection { + readonly cause: unknown; + readonly cleanup: AnalysisCleanupObservation; + readonly cleanupLeases?: readonly AnalysisCleanupLease[] | undefined; +} + export interface ArtifactReaderFailureOptions extends ErrorOptions { /** Recovery guidance established by the producing adapter, separate from diagnostics. */ readonly userMessage?: string | undefined; @@ -46,6 +53,8 @@ export interface ArtifactReaderFailureOptions extends ErrorOptions { readonly cleanup?: AnalysisCleanupObservation | undefined; /** Exact authority for all reported cleanup; undefined leaves ownership unknown. */ readonly cleanupLeases?: readonly AnalysisCleanupLease[] | undefined; + /** Independently rejected closes; retain their typed facts and ownership. */ + readonly cleanupRejections?: readonly ArtifactCleanupRejection[] | undefined; readonly partialObservation?: AnalysisPartialObservation | undefined; readonly secondaryFailures?: readonly ArtifactReaderFailure[]; /** The constrained resource bound for a limit failure. */ @@ -336,6 +345,7 @@ export class ArtifactReaderFailure extends Error { readonly cancellation: { readonly reason: unknown } | undefined; readonly cleanup: AnalysisCleanupObservation | undefined; readonly cleanupLeases: readonly AnalysisCleanupLease[] | undefined; + readonly cleanupRejections: readonly ArtifactCleanupRejection[] | undefined; partialObservation: AnalysisPartialObservation | undefined; secondaryFailures: readonly ArtifactReaderFailure[] | undefined; /** The constrained bound for a `limit` reason, when the reader knows it. */ @@ -405,6 +415,7 @@ export class ArtifactReaderFailure extends Error { this.cleanup = options?.cleanup; this.cleanupLeases = options?.cleanupLeases ?? (this.cleanup === undefined ? [] : undefined); + this.cleanupRejections = options?.cleanupRejections; this.partialObservation = options?.partialObservation; this.secondaryFailures = options?.secondaryFailures; this.boundary = options?.boundary; @@ -484,6 +495,7 @@ export class ArtifactReaderFailure extends Error { cleanup: AnalysisCleanupObservation, partialObservation?: AnalysisPartialObservation, cleanupLeases?: readonly AnalysisCleanupLease[], + addedRejections?: readonly ArtifactCleanupRejection[], ): ArtifactReaderFailure { const primary = cause instanceof ArtifactReaderFailure @@ -521,6 +533,18 @@ export class ArtifactReaderFailure extends Error { : appendCleanupObservation(previousCleanup, cleanup), cleanupLeases: cleanupLeases ?? (sameCleanup ? primary.cleanupLeases : undefined), + ...(primary.cleanupRejections === undefined + ? {} + : { + cleanupRejections: sameCleanup + ? primary.cleanupRejections + : [ + ...primary.cleanupRejections, + ...(addedRejections ?? [ + { cause: undefined, cleanup, cleanupLeases }, + ]), + ], + }), ...(mergedObservation === undefined ? {} : { partialObservation: mergedObservation }), diff --git a/src/resources/ArtifactResourceScope.test.ts b/src/resources/ArtifactResourceScope.test.ts index 10574957fcd..cbccacede1c 100644 --- a/src/resources/ArtifactResourceScope.test.ts +++ b/src/resources/ArtifactResourceScope.test.ts @@ -11,6 +11,7 @@ import { ArtifactResourceScope, } from "./ArtifactResourceScope.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; +import { AnalysisError } from "../domain/analysisErrorBase.js"; import { expect, it } from "vitest"; import { err, ok } from "../domain/result.js"; @@ -20,6 +21,20 @@ import { type ArtifactReader, } from "./ArtifactReader.js"; import { translateArtifactFailure } from "./ArtifactOperationFailure.js"; +import { classifyProviderFailure } from "../providers/classifyProviderFailure.js"; +import { artifactCloseFailureDialect } from "../providers/artifactCloseFailure.js"; +import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; + +const translateArtifactCloseFailure = ( + providerId: string, + operation: string, + cause: unknown, + resource: string, +) => + classifyProviderFailure( + cause, + artifactCloseFailureDialect(providerId, operation, resource), + ); it("waits for admitted operations and shares concurrent close", async () => { const scope = new ArtifactResourceScope(); @@ -125,14 +140,18 @@ it("stops a close hook even when retained cleanup is still failing", async () => ); expect(closeFailure).toMatchObject({ message: expect.stringContaining("stuck lease, close hook"), - failedOwners: [owner], + cleanupRejections: [ + { cause: expect.objectContaining({ failedOwners: [owner] }) }, + { cause: expect.any(Error) }, + ], cleanup: { reason: "still owned; hook still stopping", resources: ["stuck lease", "close hook"], }, }); - expect(closeFailure).toBeInstanceOf(ArtifactResourceRetryFailure); - const causes = (closeFailure as ArtifactResourceRetryFailure).cause; + expect(closeFailure).toBeInstanceOf(ArtifactReaderFailure); + expect(closeFailure).not.toBeInstanceOf(ArtifactResourceRetryFailure); + const causes = (closeFailure as ArtifactReaderFailure).cause; expect(causes).toBeInstanceOf(AggregateError); expect( (causes as AggregateError).errors.map((error) => @@ -179,6 +198,234 @@ it("rejects a close hook's undefined reason and retries through the same scope", } }); +it.each(["artifact", "hook"] as const)( + "preserves typed close diagnostics when the %s owner recovers first", + async (first) => { + const scope = new ArtifactResourceScope(); + let artifactDenied = true; + let hookDenied = true; + let hookReleased = false; + const owner = { + kind: "lease" as const, + resource: "artifact lease", + lease: { + async release() { + if (artifactDenied) throw new Error("artifact busy"); + }, + }, + }; + scope.retain(owner); + const inspection = { + capability: "process_table", + command: "/bin/ps", + system_code: "EPERM", + }; + const hookFailure = new ProviderCleanupError( + "fixture", + ["worker"], + { inspection }, + { + operation: "analyze_javascript_application", + remediationAction: "Run from a host context that permits /bin/ps.", + }, + ); + hookFailure.bindCleanupReleaseClaim({ + get cleanupReleased() { + return hookReleased; + }, + }); + scope.addCloseHook(async () => { + if (hookDenied) throw hookFailure; + hookReleased = true; + }); + try { + const cause = await scope.close().catch((failure: unknown) => failure); + expect(cause).toBeInstanceOf(ArtifactReaderFailure); + expect(cause).not.toBeInstanceOf(ArtifactResourceRetryFailure); + expect((cause as ArtifactReaderFailure).cleanupLeases).toBeUndefined(); + const error = translateArtifactCloseFailure( + "fixture", + "analyze_javascript_application", + cause, + "resources", + ); + expect(projectAnalysisError(error, "invocation")).toMatchObject({ + code: "cleanup_incomplete", + details: { + resources: ["artifact lease", "worker"], + diagnostics: { + cleanup_error_2: { + details: { diagnostics: { inspection } }, + remediation: { + action: "Run from a host context that permits /bin/ps.", + }, + }, + }, + }, + }); + if (first === "artifact") { + artifactDenied = false; + await scope.release(owner); + expect(error.cleanupResources).toEqual(["worker"]); + } else { + hookDenied = false; + await expect(scope.close()).rejects.toBeInstanceOf( + ArtifactResourceRetryFailure, + ); + expect(error.cleanupResources).toEqual(["artifact lease"]); + } + expect(error.cleanupIncomplete).toBe(true); + artifactDenied = false; + hookDenied = false; + await scope.close(); + expect(error.cleanupIncomplete).toBe(false); + expect(error.cleanupResources).toEqual([]); + } finally { + artifactDenied = false; + hookDenied = false; + await scope.close(); + } + }, +); + +it.each([undefined, new AnalysisOutputError("write", "hook output failed")])( + "keeps an unowned hook rejection unconfirmed after all retained artifact leases release (%s)", + async (rejection) => { + const scope = new ArtifactResourceScope(); + let denied = true; + const owner = { + kind: "lease" as const, + resource: "artifact lease", + lease: { + async release() { + if (denied) throw new Error("artifact busy"); + }, + }, + }; + scope.retain(owner); + scope.addCloseHook(async () => { + if (denied) throw rejection; + }); + try { + const cause = await scope.close().catch((failure: unknown) => failure); + const error = translateArtifactCloseFailure( + "fixture", + "close", + cause, + "resources", + ); + denied = false; + await scope.release(owner); + expect(error.cleanupIncomplete).toBe(true); + expect(error.cleanupResources).toEqual( + rejection === undefined ? ["close hook"] : [], + ); + await scope.close(); + // An opaque rejection never supplied a release claim for this report. + expect(error.cleanupIncomplete).toBe(true); + } finally { + denied = false; + await scope.close(); + } + }, +); + +it.each(["lease", "hook"] as const)( + "preserves wrapped close failures when the added %s recovers first", + async (first) => { + const scope = new ArtifactResourceScope(); + let firstDenied = true; + let addedDenied = true; + let hookDenied = true; + let hookReleased = false; + const owner = { + kind: "lease" as const, + resource: "first lease", + lease: { + async release() { + if (firstDenied) throw new Error("first busy"); + }, + }, + }; + const added = { + kind: "lease" as const, + resource: "added lease", + lease: { + async release() { + if (addedDenied) throw new Error("added busy"); + }, + }, + }; + scope.retain(owner); + const inspection = { command: "/bin/ps", system_code: "EPERM" }; + const hook = new ProviderCleanupError( + "fixture", + ["worker"], + { inspection }, + { remediationAction: "Permit /bin/ps on this host." }, + ); + hook.bindCleanupReleaseClaim({ + get cleanupReleased() { + return hookReleased; + }, + }); + scope.addCloseHook(async () => { + if (hookDenied) throw hook; + hookReleased = true; + }); + try { + const original = await scope.close().catch((cause: unknown) => cause); + const failed = await scope.release(added); + if (failed.kind !== "failed") + throw new Error("expected added lease failure"); + const wrapped = scope.cleanupFailure( + { kind: "failed", cause: original }, + [failed], + ); + expect(wrapped.cleanupRejections).toHaveLength(3); + const error = translateArtifactCloseFailure( + "fixture", + "close", + wrapped, + "resources", + ); + expect(projectAnalysisError(error, "invocation")).toMatchObject({ + details: { + diagnostics: { + cleanup_error_2: { + details: { diagnostics: { inspection } }, + remediation: { action: "Permit /bin/ps on this host." }, + }, + }, + }, + }); + firstDenied = false; + await scope.release(owner); + if (first === "lease") { + addedDenied = false; + await scope.release(added); + expect(error.cleanupResources).toEqual(["worker"]); + } else { + hookDenied = false; + await expect(scope.close()).rejects.toBeInstanceOf( + ArtifactResourceRetryFailure, + ); + expect(error.cleanupResources).toEqual(["added lease"]); + } + expect(error.cleanupIncomplete).toBe(true); + addedDenied = false; + hookDenied = false; + await scope.close(); + expect(error.cleanupIncomplete).toBe(false); + } finally { + firstDenied = false; + addedDenied = false; + hookDenied = false; + await scope.close(); + } + }, +); + it.each([ { name: "null", reason: null }, { name: "false", reason: false }, @@ -213,13 +460,17 @@ it("runs and retries all close hooks in order, preserving their exact failures", try { const failure = await scope.close().catch((cause: unknown) => cause); - if (!(failure instanceof AggregateError)) + if (!(failure instanceof ArtifactReaderFailure)) throw new Error("Expected all hook failures"); - expect(failure.errors).toStrictEqual(reasons); - expect(failure.errors[2]).toBe(reasons[2]); + expect(failure.cleanupRejections?.map(({ cause }) => cause)).toStrictEqual( + reasons, + ); + expect(failure.cleanupRejections?.[2]?.cause).toBe(reasons[2]); expect(attempted).toStrictEqual(reasons); - await expect(scope.close()).rejects.toMatchObject({ errors: reasons }); + await expect(scope.close()).rejects.toMatchObject({ + cleanupRejections: reasons.map((cause) => ({ cause })), + }); expect(attempted).toStrictEqual([...reasons, ...reasons]); } finally { denied = false; @@ -257,10 +508,8 @@ it("retains both a failed owner and an undefined hook failure until each recover (error: unknown) => err(error), ); expect(outcome.ok).toBe(false); - if (outcome.ok || !(outcome.error instanceof ArtifactResourceRetryFailure)) + if (outcome.ok || !(outcome.error instanceof ArtifactReaderFailure)) throw new Error("Expected both retained cleanup failures"); - expect(outcome.error.failedOwners).toEqual([owner]); - expect(outcome.error.failedOwners[0]).toBe(owner); expect(outcome.error.cleanup).toEqual({ reason: "lease still owned; undefined", resources: ["retained lease", "close hook"], @@ -719,8 +968,18 @@ it.each(["artifact", "domain"] as const)( ); expect(error.cleanupResources).toEqual(children); children = ["second child"]; - await expect(scope.retryCleanup()).rejects.toMatchObject({ + const retry = await scope.retryCleanup().catch((cause: unknown) => cause); + expect(retry).toBeInstanceOf(ArtifactResourceRetryFailure); + expect(retry).not.toBeInstanceOf(AnalysisError); + expect(retry).toMatchObject({ cleanupLeases: [attempt.lease], + cleanup: { + reason: + kind === "domain" + ? "Provider composite adapter failed during close_binary" + : "held children", + resources: children, + }, }); expect(error.cleanupIncomplete).toBe(true); expect(error.cleanupResources).toEqual(children); diff --git a/src/resources/ArtifactResourceScope.ts b/src/resources/ArtifactResourceScope.ts index d1837680a8b..826f2aa5f07 100644 --- a/src/resources/ArtifactResourceScope.ts +++ b/src/resources/ArtifactResourceScope.ts @@ -17,7 +17,6 @@ import { artifactPrimaryCleanupLeases, } from "./ArtifactReader.js"; import { AnalysisCleanupLease } from "./AnalysisCleanupLease.js"; -import { errorMessage } from "../kernel/errorMessage.js"; /** * Capabilities the scope needs from an output tree and a private runtime @@ -254,6 +253,11 @@ export class ArtifactResourceScope { inherited === undefined ? undefined : [...new Set([...inherited, ...failures.map(({ lease }) => lease)])], + failures.map(({ cause, lease }, index) => ({ + cause, + cleanup: observations[index]!, + cleanupLeases: [lease], + })), ); } @@ -306,9 +310,24 @@ export class ArtifactResourceScope { if (failures.length === 0) return ok(undefined); if (failures.length === 1) return err(failures[0]); return err( - new AggregateError( - failures, - failures.map((cause) => errorMessage(cause)).join("; "), + new ArtifactReaderFailure( + "unavailable", + "Close hooks remain incomplete", + { + cause: new AggregateError(failures), + cleanupRejections: failures.map((cause) => ({ + cause, + cleanup: ArtifactReaderFailure.cleanupObservation( + cause, + "close hook", + ), + })), + cleanup: failures + .map((cause) => + ArtifactReaderFailure.cleanupObservation(cause, "close hook"), + ) + .reduce(appendCleanupObservation), + }, ), ); } @@ -350,17 +369,14 @@ export class ArtifactResourceScope { "Retained cleanup and a close hook both failed", ), cleanup: observation, + cleanupRejections: [ + { cause: cleanup, cleanup: retained }, + { cause: hookFailure, cleanup: hook }, + ], }; const message = `Artifact cleanup remains incomplete: ${observation.resources.join(", ")}`; - if (cleanup instanceof ArtifactResourceRetryFailure) - return new ArtifactResourceRetryFailure( - cleanup.failedOwners.map((owner) => ({ - owner, - lease: this.#lease(owner), - })), - message, - options, - ); + // Retained leases cannot confirm release of an independently rejected hook. + // Keep the retry failure, with its exact owners, inside the composite. return new ArtifactReaderFailure("unavailable", message, options); } diff --git a/tests/boundary/cli/cliJavaScriptResourceClose.test.ts b/tests/boundary/cli/cliJavaScriptResourceClose.test.ts index 7c0140992ef..aa3a9d7d5d0 100644 --- a/tests/boundary/cli/cliJavaScriptResourceClose.test.ts +++ b/tests/boundary/cli/cliJavaScriptResourceClose.test.ts @@ -9,6 +9,7 @@ import { runCliJavaScriptApplicationAnalysis, } from "../../../src/cli/javascriptApplicationAnalysis.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js"; const originalClose = ArtifactResourceScope.prototype.close; @@ -95,6 +96,191 @@ it("retains completed JavaScript Evidence when cancellation arrives during final } }); +it("retains completed Evidence and inspector remediation when an artifact and the final hook both fail", async () => { + const root = await createTestTempDirectory("cli-js-mixed-cleanup-"); + await writeFile(join(root, "index.js"), "export const answer = 42;\n"); + const host = new CliJavaScriptAnalysisHost("invocation"); + let denied = true; + const inspection = { + capability: "process_table", + command: "/bin/ps", + system_code: "EPERM", + }; + const hookFailure = new ProviderCleanupError( + "javascript-static-analysis", + ["fixture-worker"], + { inspection }, + { + operation: "analyze_javascript_application", + remediationAction: "Run from a host context that permits /bin/ps.", + }, + ); + const owner = { + kind: "lease", + resource: "fixture-artifact", + lease: { + async release() { + if (denied) throw new Error("artifact busy"); + }, + }, + } as const; + const scope = host.scope(); + const retryCleanup = scope.retryCleanup.bind(scope); + const retry = vi + .spyOn(scope, "retryCleanup") + .mockImplementationOnce(async () => { + scope.retain(owner); + await retryCleanup(); + }); + host.scope().addCloseHook(async () => { + if (denied) throw hookFailure; + }); + try { + const result = await runCliJavaScriptApplicationAnalysis( + { input_path: root }, + {}, + undefined, + undefined, + host, + ); + expect(result).toMatchObject({ + code: "cleanup_incomplete", + details: { + partial_observation: { + operation: "analyze_javascript_application", + normalized_result: { input_path: root }, + }, + diagnostics: { + cleanup_error: { + details: { + diagnostics: { + cleanup_error_2: { + details: { diagnostics: { inspection } }, + remediation: { + action: "Run from a host context that permits /bin/ps.", + }, + }, + }, + }, + }, + }, + }, + }); + } finally { + denied = false; + retry.mockRestore(); + await host.close(); + } +}); + +it.each([false, true])( + "recovers completed Evidence after a final cleanup retry (cancelled=%s)", + async (cancelled) => { + const root = await createTestTempDirectory("cli-js-recovered-cleanup-"); + await writeFile(join(root, "index.js"), "export const answer = 42;\n"); + const host = new CliJavaScriptAnalysisHost("invocation"); + const controller = new AbortController(); + let attempts = 0; + const scope = host.scope(); + const retryCleanup = scope.retryCleanup.bind(scope); + const retry = vi + .spyOn(scope, "retryCleanup") + .mockImplementationOnce(async () => { + scope.retain({ + kind: "lease", + resource: "fixture-artifact", + lease: { + async release() { + attempts += 1; + if (attempts === 1) throw new Error("transient close failure"); + if (cancelled) controller.abort("stop during final cleanup"); + }, + }, + }); + await retryCleanup(); + }); + try { + const result = await runCliJavaScriptApplicationAnalysis( + { input_path: root }, + {}, + controller.signal, + undefined, + host, + ); + expect(attempts).toBe(2); + expect(result).toMatchObject( + cancelled + ? { + code: "cancelled", + details: { + partial_observation: { + operation: "analyze_javascript_application", + normalized_result: { input_path: root }, + }, + }, + } + : { + operation: "analyze_javascript_application", + normalized_result: { input_path: root }, + }, + ); + } finally { + retry.mockRestore(); + await host.close(); + } + }, +); + +it("keeps the primary analysis error when one-shot finalization fails and retains its owner for retry", async () => { + const host = new CliJavaScriptAnalysisHost("invocation"); + let denied = true; + let attempts = 0; + const failure = new ProviderCleanupError( + "javascript-static-analysis", + ["fixture-worker"], + { reason: "controlled inspection denial" }, + { operation: "analyze_javascript_application" }, + ); + let released = false; + failure.bindCleanupReleaseClaim({ + get cleanupReleased() { + return released; + }, + }); + host.scope().addCloseHook(async () => { + attempts += 1; + if (denied) throw failure; + released = true; + }); + try { + const result = await runCliJavaScriptApplicationAnalysis( + {}, + {}, + undefined, + undefined, + host, + ); + expect(attempts).toBe(1); + expect(result).toMatchObject({ + error: "JavaScript application analysis failed", + code: "cleanup_incomplete", + details: { + execution_failure: "invalid_request", + resources: ["fixture-worker"], + diagnostics: { primary_error: { code: "invalid_request" } }, + }, + }); + expect(failure.cleanupIncomplete).toBe(true); + denied = false; + await host.close(); + expect(attempts).toBe(2); + expect(failure.cleanupIncomplete).toBe(false); + } finally { + denied = false; + await host.close(); + } +}); + it("retries JavaScript worker shutdown when the first close fails", async () => { await closeCliResources(); let calls = 0; @@ -115,6 +301,34 @@ it("retries JavaScript worker shutdown when the first close fails", async () => expect(calls).toBe(2); }); +it("preserves the pre-delivery retry and final close retry before projecting the primary", async () => { + const host = new CliJavaScriptAnalysisHost("invocation"); + let attempts = 0; + host.scope().retain({ + kind: "lease", + resource: "fixture-retained-resource", + lease: { + release: async () => { + attempts += 1; + if (attempts === 1) throw new Error("controlled first retry failure"); + }, + }, + }); + try { + const result = await runCliJavaScriptApplicationAnalysis( + {}, + {}, + undefined, + undefined, + host, + ); + expect(attempts).toBe(2); + expect(result).toMatchObject({ code: "invalid_request" }); + } finally { + await host.close(); + } +}); + it("shares one in-flight JavaScript worker shutdown between callers", async () => { await closeCliResources(); let calls = 0; diff --git a/tests/boundary/cli/cliOwnedResources.test.ts b/tests/boundary/cli/cliOwnedResources.test.ts index f94ed2cff1e..7adafdd5cb8 100644 --- a/tests/boundary/cli/cliOwnedResources.test.ts +++ b/tests/boundary/cli/cliOwnedResources.test.ts @@ -2,14 +2,79 @@ import { afterEach, expect, it, vi } from "vitest"; import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js"; import { CliJavaScriptAnalysisHost } from "../../../src/cli/javascriptApplicationAnalysis.js"; +import { loadCliRuntime } from "../../../src/cliLoader.js"; +import { parseCliGlobalArguments } from "../../../src/cliBuiltinArguments.js"; const originalClose = ArtifactResourceScope.prototype.close; +const originalHostClose = CliJavaScriptAnalysisHost.prototype.close; afterEach(() => { ArtifactResourceScope.prototype.close = originalClose; vi.restoreAllMocks(); }); +it.each(["selected", "full"] as const)( + "retains the %s runtime's invocation owner across failed outer cleanup", + async (route) => { + const failure = new Error("fixture cleanup denied"); + let denied = true; + let attempts = 0; + let release = (): void => {}; + const gate = new Promise((resolve) => { + release = resolve; + }); + let invocation: CliJavaScriptAnalysisHost | undefined; + let retained: ArtifactResourceScope | undefined; + const hosts = vi + .spyOn(CliJavaScriptAnalysisHost.prototype, "close") + .mockImplementation(function (this: CliJavaScriptAnalysisHost) { + if (this.callerLifetime === "invocation" && invocation === undefined) { + invocation = this; + retained = this.scope(); + retained.addCloseHook(async () => { + attempts += 1; + await gate; + if (denied) throw failure; + }); + } + return originalHostClose.call(this); + }); + const runtime = await loadCliRuntime( + route === "full" + ? undefined + : parseCliGlobalArguments([ + "analyze-javascript-application", + "fixture", + "--json", + ]), + {}, + undefined, + { finalizeJavaScriptAnalysis: true }, + ); + try { + const first = runtime.closeCliResources(); + const rejected = expect(first).rejects.toBe(failure); + expect(runtime.closeCliResources()).toBe(first); + release(); + await rejected; + expect(invocation).toBeDefined(); + expect(invocation?.scope()).toBe(retained); + expect(attempts).toBe(1); + await expect(runtime.closeCliResources()).rejects.toBe(failure); + expect(attempts).toBe(2); + denied = false; + await runtime.closeCliResources(); + expect(attempts).toBe(3); + expect(invocation?.scope()).not.toBe(retained); + } finally { + release(); + denied = false; + await runtime.closeCliResources(); + hosts.mockRestore(); + } + }, +); + it("does not share a JavaScript worker scope or its in-flight close", async () => { let release = (): void => {}; const gate = new Promise((resolve) => { diff --git a/tests/boundary/cli/dispatcher.test.ts b/tests/boundary/cli/dispatcher.test.ts index ea073ad5ac7..82e04cbd6fb 100644 --- a/tests/boundary/cli/dispatcher.test.ts +++ b/tests/boundary/cli/dispatcher.test.ts @@ -30,6 +30,11 @@ const installCliRuntime = async ( await cp("dist/cli-runtime", workspace.path("dist/cli-runtime"), { recursive: true, }); + // Metadata remains external to the bundle and belongs to the same runtime. + await cp( + "dist/generatedPackageMetadata.js", + workspace.path("dist/generatedPackageMetadata.js"), + ); // Production chunks import their packages from the installation root. await symlink( resolve("node_modules"), @@ -392,6 +397,28 @@ describe("executable dispatcher", () => { }); describe("executable dispatcher JavaScript shutdown", () => { + workspaceCliTest.for([undefined, 0, 1, 130] as const)( + "preserves a returned result when final cleanup fails at status %s", + async (status, { processes, workspace }) => { + await installCliRuntime( + workspace, + `export const closeCliResources = async () => { throw new Error("fixture final cleanup incomplete"); }; export const createCli = () => ({ serve: (_args, options) => { process.exitCode = ${String(status)}; options.stdout('{"kept":true}\\n'); } });\n`, + ); + const result = await processes.run( + process.execPath, + [workspace.path("scripts/rea.mjs"), "fixture"], + { cwd: workspace.root }, + ); + expect(result.exitCode).toBe(status === 130 ? 130 : 1); + expect(result.stdout).toBe('{"kept":true}\n'); + expect(result.stderr).toContain( + "Failed to close CLI resources: Error: fixture final cleanup incomplete", + ); + expect(result.stderr).not.toContain("triggerUncaughtException"); + expect(result.stderr).not.toContain("Node.js v"); + }, + ); + workspaceCliTest.for([false, true])( "handles a thrown pipe error while preserving mixed cleanup failure: %s", async (cleanupFails, { processes, workspace }) => { diff --git a/tests/boundary/cli/javascriptInspectionCleanupCli.test.ts b/tests/boundary/cli/javascriptInspectionCleanupCli.test.ts new file mode 100644 index 00000000000..c24def3c222 --- /dev/null +++ b/tests/boundary/cli/javascriptInspectionCleanupCli.test.ts @@ -0,0 +1,104 @@ +import { readFile, rm, writeFile } from "node:fs/promises"; +import { join, resolve } from "node:path"; +import { expect, onTestFinished } from "vitest"; +import { cliTest } from "../../support/cli/cliFixture.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { analysisErrorProjectionSchema } from "../../../src/domain/analysisErrorProjectionSchema.js"; +import { analysisCliErrorEnvelopeSchema } from "../../../src/contracts/errorSchemas.js"; +import { parseEvidence } from "../../../src/domain/evidence.js"; +import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js"; +import { z } from "zod"; + +const workerRecord = z.object({ + kind: z.literal("worker"), + root: z.string(), + leaderPid: z.number().int().positive(), + processGroupId: z.number().int().positive(), + runId: z.string(), +}); + +cliTest.skipIf(process.platform === "win32").for([ + ["analyze", "deny"], + ["analyze-javascript-application", "deny"], + ["analyze", "cancel"], + ["analyze-javascript-application", "cancel"], + ["analyze", "normal"], + ["analyze-javascript-application", "normal"], +] as const)( + "finalizes %s before delivering its %s outcome", + async ([command, mode], { processes }) => { + const root = await createTestTempDirectory("rea-inspection-cli-"); + const trace = join(root, "inspection.txt"); + onTestFinished(async () => { + const records = (await readFile(trace, "utf8")).trim().split("\n"); + for (const record of records) { + const parsed = workerRecord.safeParse(JSON.parse(record)); + if (!parsed.success) continue; + expect(await cleanupOwnedProcessGroup(parsed.data)).toMatchObject({ + cleaned: true, + }); + await rm(parsed.data.root, { recursive: true, force: true }); + } + }); + await writeFile(join(root, "app.mjs"), "export const observed = 7;"); + const result = await processes.run( + process.execPath, + [ + "--import", + resolve("tests/fixtures/javascriptInspectionPreload.mjs"), + resolve("scripts/rea.mjs"), + command, + root, + "--json", + ], + { + env: { + ...process.env, + REA_INSPECTION_TRACE: trace, + REA_INSPECTION_MODE: mode, + }, + }, + ); + // The outer retry can recover after the command reports incomplete cleanup. + const cleanupReported = result.stderr.includes( + "Failed to close CLI resources:", + ); + if (mode !== "deny" || !cleanupReported) + expect(result.stderr).not.toMatch(/^\s+at /m); + expect(result.stderr).not.toContain("triggerUncaughtException"); + if (mode === "normal") { + expect(result.stderr).not.toContain("Failed to close CLI resources:"); + expect(result.exitCode, result.stderr).toBe(0); + expect(parseEvidence(JSON.parse(result.stdout)).operation).toBe( + "analyze_javascript_application", + ); + return; + } + expect(result.exitCode, result.stderr).toBe(mode === "deny" ? 1 : 130); + const { error: label, ...projection } = + analysisCliErrorEnvelopeSchema.parse(JSON.parse(result.stdout)); + expect(label).toBe("JavaScript application analysis failed"); + const failure = analysisErrorProjectionSchema.parse(projection); + expect(failure.code).toBe( + mode === "deny" ? "cleanup_incomplete" : "cancelled", + ); + if (mode === "deny") { + expect(await readFile(trace, "utf8")).toContain('"kind":"denied"'); + expect(failure.details).toMatchObject({ + cleanup: "incomplete", + diagnostics: { + inspection: { + capability: "process_table", + command: expect.stringMatching(/(^|[\\/])ps$/u), + system_code: "EPERM", + }, + }, + }); + expect(failure.remediation.action).toContain("ps"); + } + expect(parseEvidence(failure.details?.partial_observation)).toMatchObject({ + operation: "analyze_javascript_application", + subject: { local_path: root }, + }); + }, +); diff --git a/tests/fixtures/javascriptInspectionPreload.mjs b/tests/fixtures/javascriptInspectionPreload.mjs new file mode 100644 index 00000000000..01a4f92edfd --- /dev/null +++ b/tests/fixtures/javascriptInspectionPreload.mjs @@ -0,0 +1,53 @@ +import childProcess from "node:child_process"; +import { appendFileSync } from "node:fs"; +import { syncBuiltinESMExports } from "node:module"; +import { basename } from "node:path"; + +// Deny only post-analysis inspection. Startup and the real inert worker run normally. +let completed = false; +let interrupted = false; +const write = process.stderr.write.bind(process.stderr); +process.stderr.write = (chunk, ...args) => { + const text = String(chunk); + if ( + text.includes('"phase":"analyze_javascript_application"') && + text.includes('"terminal":true') + ) + completed = true; + return write(chunk, ...args); +}; +const spawn = childProcess.spawn; +childProcess.spawn = (command, ...args) => { + if (completed && basename(command) === "ps") { + if (process.env.REA_INSPECTION_MODE === "cancel" && !interrupted) { + interrupted = true; + process.emit("SIGINT"); + } + if (process.env.REA_INSPECTION_MODE !== "deny") + return spawn(command, ...args); + appendFileSync(process.env.REA_INSPECTION_TRACE, '{"kind":"denied"}\n'); + throw Object.assign(new Error("spawn EPERM"), { + code: "EPERM", + syscall: "spawn ps", + path: command, + }); + } + const child = spawn(command, ...args); + const options = args.at(-1); + if ( + options?.cwd?.includes("rea-javascript-analysis-") && + options?.env?.REA_PROCESS_RUN_ID?.startsWith("rea-javascript-analysis-") + ) + appendFileSync( + process.env.REA_INSPECTION_TRACE, + JSON.stringify({ + kind: "worker", + root: options.cwd, + leaderPid: child.pid, + processGroupId: child.pid, + runId: options.env.REA_PROCESS_RUN_ID, + }) + "\n", + ); + return child; +}; +syncBuiltinESMExports(); diff --git a/tests/support/cli/cliCommandSessionWorker.mjs b/tests/support/cli/cliCommandSessionWorker.mjs index a9a074e58f5..79c811763c4 100644 --- a/tests/support/cli/cliCommandSessionWorker.mjs +++ b/tests/support/cli/cliCommandSessionWorker.mjs @@ -46,6 +46,8 @@ if (!(await compiledRuntimeExists(packageRoot, runtimeFiles))) { const { closeCliResources } = await import("../../../dist/cli-runtime/cli.js"); const { runOneShotCli } = await import("../../../dist/cli-runtime/cliOneShot.js"); +/** @type {Array<() => unknown>} */ +const cleanupTasks = [closeCliResources]; const writeFrame = (value) => new Promise((resolveWrite, rejectWrite) => { @@ -103,7 +105,7 @@ try { await inputStopped; await chain; if (completion.kind === "failed") throw completion.cause; - }, [closeCliResources]); + }, cleanupTasks); } catch (cause) { console.error(cause); process.exit(1); @@ -216,7 +218,9 @@ async function runOneShot(args) { process.exitCode = code; }, // The session closes CLI resources once, after its last command. - ownCliResources: () => {}, + ownCliResources: (close) => { + cleanupTasks.push(close); + }, exitRequested: () => exitOutput !== undefined, // This process serves the next command; record the status and finish // the pending result in place of exiting.