diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index b7612e570ca..cf773b7fcba 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -1668,21 +1668,73 @@ enabling checkpoint mode requires the startup environment and an MCP restart. Storage is separated by target SHA-256 and analysis-profile identity, including the supported Ghidra version. Identical executable bytes at another path can -reuse the Program. One live REA session holds the checkpoint's socket lease; -a competing session reports that owner as a retryable `capability_unavailable` -failure and succeeds once it closes. If that owner saved Program edits when it -closed, the retry instead reports that the checkpoint changed and asks for the -target to be reopened, which restores the saved checkpoint. A process started -without the setting can -analyze the same target concurrently through an ephemeral import. Only -REA-owned Programs are checkpointed. Caller-selected existing projects retain -their separate read-only workflow below. +reuse the Program. Only REA-owned Programs are checkpointed. Caller-selected +existing projects retain their separate read-only workflow below. + +Several sessions and parallel CLI commands can use one checkpointed target at +the same time. Each restores the packed Program into its own private project, +so queries never wait for another session. Two sessions that both open a +target with no checkpoint both analyze it; the first to finish publishes the +initial checkpoint and the other keeps its own analysis without publishing a +second copy. + +Saving is not merged. A session saves only onto the checkpoint it started +from, and holds the checkpoint's socket lease only while it publishes. When +another session saved first, the later session's `close_binary` fails with +`cleanup_incomplete`, its remediation states that the edits were not saved, +and the current checkpoint is unchanged. That refusal is permanent for the +session: call `close_binary` again to discard its edits and release it, then +reopen the target and reapply them. That close succeeds with +`result.checkpoint` set to `{"status": "discarded", "reason": "superseded", +"directory": ...}`, alongside the snapshot receipt when `snapshot_path` was +given, so the discard is recorded rather than silent. Only the close that +releases the edits reports it. If a later cleanup step of that close fails, +the close reports `cleanup_incomplete` with the same object in +`details.partial_observation.checkpoint`, and its retry returns no second +report. Until that close, `open_binary` of another target, opening app +resources, `reset_investigation` and external mutations refuse with +`capability_unavailable` instead of releasing the edits unreported; call +`close_binary` first. To avoid the refusal, make edits to one target from one +session at a time. + +Two related refusals are not configuration faults and leave the checkpoint +intact. A session whose selected checkpoint was replaced before its Ghidra +process restored it, or whose initial analysis was overtaken by another +session's saved edits, reports `capability_unavailable` with +`retryable: false`; reopen the target. A save that waits its whole save wait +for another session's publication names that session. During startup it +reports a retryable `capability_unavailable`; during `close_binary` it reports +`cleanup_incomplete` with `recovery.kind=retry_cleanup` and keeps the session +and its edits. Repeat the call. + +The save wait is 30,000 ms by default. Set +`REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS` to an integer from 50 to 600,000 +milliseconds in the environment that starts REA to change how long +`close_binary`, or the first save of a startup, waits for another session's +publication. The floor is one 50 ms poll of the lease; the maximum is ten +minutes, past which a held lease is a stalled publisher and not a save in +progress. REA reads the value when it starts and each session keeps the bound +it opened with, so a change needs a restart; `update_analysis_settings` does +not change it and `inspect_analysis_settings` does not list it. The busy +refusal names the control, the value applied, whether it came from the default +or the launch environment, and the range, and reports them as an environment +`details.limit`. An empty, malformed or out-of-range value does not fall back +to the default: `rea doctor` and registration validation report it, REA still +starts, and a checkpointed Ghidra session refuses to open with +`configuration_invalid` until it is corrected. Sessions without a checkpoint +never apply the wait. The control lengthens only this session's wait; it does +not shorten the other session's save. It also cannot make an MCP client wait +longer: the client's own request deadline is separate and unknown to REA, so +keep the wait below it, or the client gives up while the close continues. A +forced stop, such as a cancelled request escalating a close, ends the wait +without publishing. The directory retains the current manifest and packed Program. Publication writes and syncs a new packed file before atomically replacing the manifest; superseded files are removed after publication. A failed save preserves the previous checkpoint and the live session for retry. Correct the reported storage -problem, then call `close_binary` again. Incomplete cleanup retains its owner. +problem, then call `close_binary` again; the refused save described above is +the exception, where the retry discards. Incomplete cleanup retains its owner. Corrupt, malformed or changed checkpoints fail explicitly instead of falling back to a fresh import. Preserve that directory and repair it or explicitly select a new directory to start fresh. diff --git a/docs/reference/rea-limit-inventory.md b/docs/reference/rea-limit-inventory.md index bde33221326..f403615c488 100644 --- a/docs/reference/rea-limit-inventory.md +++ b/docs/reference/rea-limit-inventory.md @@ -104,25 +104,26 @@ reports the current value, source, and range. A rejected Windows ChangeTime laun These stay out of `update_analysis_settings`. -| Environment | Owner | Default | Floor | Maximum | Read | Why restart-only | -| ----------------------------------- | -------------------------------------- | ------------------: | -------: | ------------------------: | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `REA_DEBUGGER_MAX_PENDING_COMMANDS` | `src/domain/analysisResourceLimits.ts` | 16 | 1 | 256 | debugger manager construction | Queue capacity of the manager created at startup. `update_mode: "restart"` and `pending_restart: false`. | -| `REA_DEBUGGER_MAX_SESSIONS` | `src/domain/analysisResourceLimits.ts` | 8 | 1 | 64 | debugger manager construction | Session-pool size of the manager created at startup. `update_mode: "restart"` and `pending_restart: false`. | -| `REA_GHIDRA_CANCEL_GRACE_MS` | `src/config/ghidraCancelGrace.ts` | 2000 | 100 | 60000 | REA startup; fixed per Ghidra session at request-queue construction | Bounds how long a cancelled read may take to answer before its session is closed, so a session keeps the grace it opened with. Prose in the session limitation and the queued-request failure. | -| `REA_HOPPER_DEMO_DIALOG_TIMEOUT_MS` | `src/hopper/HopperStartupFailure.ts` | 10000 | 1 | 2147483647 | Linux private-display adapter start | The helper reads the process environment. Prose restart. | -| `REA_JADX_ACTIVE_PROCESSOR_COUNT` | `src/android/JadxConfiguration.ts` | unset (JVM default) | 1 | 2147483647 | JADX JVM launch | `-XX:ActiveProcessorCount` is fixed for that JVM. Prose on invalid values. | -| `REA_JADX_HEAP_MIB` | `src/android/JadxConfiguration.ts` | unset (JVM default) | 1 | `Number.MAX_SAFE_INTEGER` | JADX JVM launch | `-Xmx` is fixed for that JVM. Prose on invalid values. | -| `REA_KUNA_CACHE_MAX_BYTES` | `src/kuna/KunaConfiguration.ts` | 4294967296 | 1048576 | `Number.MAX_SAFE_INTEGER` | Kuna cache construction | The cache is sized once for the provider. Prose restart. | -| `REA_KUNA_JOBS` | `src/kuna/KunaConfiguration.ts` | 1 | 1 | 32 | Kuna run-slot construction | Worker-pool width for the provider. Prose restart. | -| `REA_MCP_DOCTOR_DEADLINE_MS` | `src/config/mcpStartupBudgets.ts` | 30000 | 1 | 2147483647 | MCP server startup | Startup phase of the MCP server itself. Prose. | -| `REA_MCP_FIRST_CATALOG_BUDGET_MS` | `src/config/mcpStartupBudgets.ts` | 20000 | 1 | 2147483647 | MCP server startup | Startup phase of the MCP server itself. Prose. | -| `REA_MCP_INITIALIZE_BUDGET_MS` | `src/config/mcpStartupBudgets.ts` | 15000 | 1 | 2147483647 | MCP server startup | Startup phase of the MCP server itself. Prose. | -| `REA_MCP_MAX_INPUT_ELEMENTS` | `src/config/mcpInputBudget.ts` | 1024 | 1 | `Number.MAX_SAFE_INTEGER` | MCP server creation | Argument admission for the server process. Prose restart. | -| `REA_MCP_MAX_RESPONSE_BYTES` | `src/config/mcpResponseBudget.ts` | 10485760 when unset | 10485760 | `Number.MAX_SAFE_INTEGER` | MCP server creation | Stdio receive buffer and the paired client buffer. Prose restart. | -| `REA_MCP_TOOLS_LIST_BUDGET_MS` | `src/config/mcpStartupBudgets.ts` | 5000 | 1 | 2147483647 | MCP server startup | Startup phase of the MCP server itself. Prose. | -| `REA_MCP_TOOLS_LIST_PAGE_BYTES` | `src/config/mcpToolsListPageBudget.ts` | 917504 | 1 | 1048576 | MCP server creation | Tools/list page size for the server process. Prose restart. | -| `REA_RECONNECT_TIMEOUT_SECONDS` | `src/hopper/BridgeLauncher.ts` | 30 | 30 | 30 | written into the Hopper bridge helper | Not a caller setting. It is `HOPPER_SHUTDOWN_TIMEOUT_MS / 1000`. | -| `REA_SWIFTC_COMPILE_TIMEOUT_MS` | `src/config/providerStartupTimeout.ts` | 120000 | 1 | 2147483647 | Darwin ownership-helper reader construction | Captured at process start for that helper compile. Prose restart. | +| Environment | Owner | Default | Floor | Maximum | Read | Why restart-only | +| ------------------------------------ | ---------------------------------------- | ------------------: | -------: | ------------------------: | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `REA_DEBUGGER_MAX_PENDING_COMMANDS` | `src/domain/analysisResourceLimits.ts` | 16 | 1 | 256 | debugger manager construction | Queue capacity of the manager created at startup. `update_mode: "restart"` and `pending_restart: false`. | +| `REA_DEBUGGER_MAX_SESSIONS` | `src/domain/analysisResourceLimits.ts` | 8 | 1 | 64 | debugger manager construction | Session-pool size of the manager created at startup. `update_mode: "restart"` and `pending_restart: false`. | +| `REA_GHIDRA_CANCEL_GRACE_MS` | `src/config/ghidraCancelGrace.ts` | 2000 | 100 | 60000 | REA startup; fixed per Ghidra session at request-queue construction | Bounds how long a cancelled read may take to answer before its session is closed, so a session keeps the grace it opened with. Prose in the session limitation and the queued-request failure. | +| `REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS` | `src/config/ghidraCheckpointSaveWait.ts` | 30000 | 50 | 600000 | REA startup; fixed per Ghidra session at checkpoint construction | Bounds a close's wait on another session's save, so a session keeps the bound it opened with. Floor is one lease poll; maximum is ten minutes. Environment `details.limit` on the busy refusal. | +| `REA_HOPPER_DEMO_DIALOG_TIMEOUT_MS` | `src/hopper/HopperStartupFailure.ts` | 10000 | 1 | 2147483647 | Linux private-display adapter start | The helper reads the process environment. Prose restart. | +| `REA_JADX_ACTIVE_PROCESSOR_COUNT` | `src/android/JadxConfiguration.ts` | unset (JVM default) | 1 | 2147483647 | JADX JVM launch | `-XX:ActiveProcessorCount` is fixed for that JVM. Prose on invalid values. | +| `REA_JADX_HEAP_MIB` | `src/android/JadxConfiguration.ts` | unset (JVM default) | 1 | `Number.MAX_SAFE_INTEGER` | JADX JVM launch | `-Xmx` is fixed for that JVM. Prose on invalid values. | +| `REA_KUNA_CACHE_MAX_BYTES` | `src/kuna/KunaConfiguration.ts` | 4294967296 | 1048576 | `Number.MAX_SAFE_INTEGER` | Kuna cache construction | The cache is sized once for the provider. Prose restart. | +| `REA_KUNA_JOBS` | `src/kuna/KunaConfiguration.ts` | 1 | 1 | 32 | Kuna run-slot construction | Worker-pool width for the provider. Prose restart. | +| `REA_MCP_DOCTOR_DEADLINE_MS` | `src/config/mcpStartupBudgets.ts` | 30000 | 1 | 2147483647 | MCP server startup | Startup phase of the MCP server itself. Prose. | +| `REA_MCP_FIRST_CATALOG_BUDGET_MS` | `src/config/mcpStartupBudgets.ts` | 20000 | 1 | 2147483647 | MCP server startup | Startup phase of the MCP server itself. Prose. | +| `REA_MCP_INITIALIZE_BUDGET_MS` | `src/config/mcpStartupBudgets.ts` | 15000 | 1 | 2147483647 | MCP server startup | Startup phase of the MCP server itself. Prose. | +| `REA_MCP_MAX_INPUT_ELEMENTS` | `src/config/mcpInputBudget.ts` | 1024 | 1 | `Number.MAX_SAFE_INTEGER` | MCP server creation | Argument admission for the server process. Prose restart. | +| `REA_MCP_MAX_RESPONSE_BYTES` | `src/config/mcpResponseBudget.ts` | 10485760 when unset | 10485760 | `Number.MAX_SAFE_INTEGER` | MCP server creation | Stdio receive buffer and the paired client buffer. Prose restart. | +| `REA_MCP_TOOLS_LIST_BUDGET_MS` | `src/config/mcpStartupBudgets.ts` | 5000 | 1 | 2147483647 | MCP server startup | Startup phase of the MCP server itself. Prose. | +| `REA_MCP_TOOLS_LIST_PAGE_BYTES` | `src/config/mcpToolsListPageBudget.ts` | 917504 | 1 | 1048576 | MCP server creation | Tools/list page size for the server process. Prose restart. | +| `REA_RECONNECT_TIMEOUT_SECONDS` | `src/hopper/BridgeLauncher.ts` | 30 | 30 | 30 | written into the Hopper bridge helper | Not a caller setting. It is `HOPPER_SHUTDOWN_TIMEOUT_MS / 1000`. | +| `REA_SWIFTC_COMPILE_TIMEOUT_MS` | `src/config/providerStartupTimeout.ts` | 120000 | 1 | 2147483647 | Darwin ownership-helper reader construction | Captured at process start for that helper compile. Prose restart. | ## Restart-only non-numeric settings diff --git a/scripts/verify-real-ghidra-checkpoints.mjs b/scripts/verify-real-ghidra-checkpoints.mjs index e0c9226a048..fb5b65a8908 100644 --- a/scripts/verify-real-ghidra-checkpoints.mjs +++ b/scripts/verify-real-ghidra-checkpoints.mjs @@ -283,7 +283,7 @@ int main(void) { CheckpointRecord record = { 3, 11 }; return rea_checkpoint_leaf }, ); await phase( - "MCP preserves a live run, refuses a concurrent writer, and saves edits", + "MCP preserves a live run, shares the target with a second session, and refuses its later save", async () => { const active = await connect(); try { @@ -302,32 +302,54 @@ int main(void) { CheckpointRecord record = { 3, 11 }; return rea_checkpoint_leaf path: target, provider_id: "ghidra", }); - const error = requireMcpToolError(await other.raw("list_documents")); - // A held lease is contention that ends when its owner closes, not - // a configuration fault: the same call is retryable afterwards. - assert.equal(error.code, "capability_unavailable"); - assert.equal(error.retryable, true); - assert.match(error.message, /another REA session/); + // Both sessions restore the same generation into private + // projects and answer queries while the other is live. + const shared = await other.call("procedure_pseudo_code", { + detail: "complete", + procedure: "rea_checkpoint_leaf", + }); + assert.match(JSON.stringify(shared), /value/); + await other.call("annotate_native_function", { + procedure: "rea_checkpoint_leaf", + comment: "REA checkpoint comment from the later session", + }); + await active.call("open_binary", { + path: target, + provider_id: "ghidra", + }); + assert.equal( + (await active.call("binary_session")).analysis_run.run_id, + id, + ); + await active.call("annotate_native_function", { + procedure: "rea_checkpoint_leaf", + name: "rea_checkpoint_retained", + comment: "REA checkpoint first comment", + }); + await active.call("close_binary"); + const published = await manifest(); + assert.notDeepEqual(published, initialManifest); + // The later session started from the superseded generation: its + // save is refused rather than overwriting the first session's. + const refused = requireMcpToolError(await other.raw("close_binary")); + assert.equal(refused.code, "cleanup_incomplete"); + assert.deepEqual(refused.recovery, { + kind: "retry_cleanup", + operation: "close_binary", + }); + assert.match(refused.remediation.action, /edits were not saved/); + assert.deepEqual(await manifest(), published); + // The refusal is permanent, so the next close discards and releases. await other.call("close_binary"); + assert.deepEqual(await manifest(), published); } finally { await other.close(); } - await active.call("open_binary", { - path: target, - provider_id: "ghidra", - }); - assert.equal( - (await active.call("binary_session")).analysis_run.run_id, - id, - ); - await active.call("annotate_native_function", { - procedure: "rea_checkpoint_leaf", - name: "rea_checkpoint_retained", - comment: "REA checkpoint first comment", - }); - await active.call("close_binary"); - assert.notDeepEqual(await manifest(), initialManifest); - return { same_live_run: true, concurrent_owner_refused: true }; + return { + same_live_run: true, + concurrent_session_answered: true, + later_save_refused: true, + }; } finally { await active.close(); } diff --git a/scripts/verify/advertised-schemas/tools/close_binary.json b/scripts/verify/advertised-schemas/tools/close_binary.json index 2133786f101..67862d7308a 100644 --- a/scripts/verify/advertised-schemas/tools/close_binary.json +++ b/scripts/verify/advertised-schemas/tools/close_binary.json @@ -1,7 +1,7 @@ { "schemas": { "input compact": "1650d4dd6dfc3b5e", - "output compact": "67aadfbdedfd0c6e" + "output compact": "e49c0057adf971d0" }, "patterns": { "input": ["^[^\\x00]*$"] diff --git a/scripts/verify/rea-numeric-limits.mjs b/scripts/verify/rea-numeric-limits.mjs index b579b16203b..05bc16b3238 100644 --- a/scripts/verify/rea-numeric-limits.mjs +++ b/scripts/verify/rea-numeric-limits.mjs @@ -1194,6 +1194,21 @@ const restartOnlyBounds = (owners) => { "MAXIMUM_GHIDRA_CANCEL_GRACE_MS", ), ), + bound( + "REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS", + exportedNumber( + owners.ghidraCheckpointSaveWait, + "DEFAULT_GHIDRA_CHECKPOINT_SAVE_WAIT_MS", + ), + exportedNumber( + owners.ghidraCheckpointSaveWait, + "MINIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS", + ), + exportedNumber( + owners.ghidraCheckpointSaveWait, + "MAXIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS", + ), + ), bound( "REA_HOPPER_DEMO_DIALOG_TIMEOUT_MS", exportedNumber( @@ -1312,6 +1327,7 @@ export const loadExportedNumericLimitBounds = async () => { mcpResponse, startupTimeout, ghidraCancelGrace, + ghidraCheckpointSaveWait, sdk, ] = await Promise.all([ source("../../src/domain/analysisSettingDefinitions.ts"), @@ -1326,6 +1342,7 @@ export const loadExportedNumericLimitBounds = async () => { source("../../src/config/mcpResponseBudget.ts"), source("../../src/config/providerStartupTimeout.ts"), source("../../src/config/ghidraCancelGrace.ts"), + source("../../src/config/ghidraCheckpointSaveWait.ts"), import("@modelcontextprotocol/server"), ]); const owners = { @@ -1339,6 +1356,7 @@ export const loadExportedNumericLimitBounds = async () => { mcpResponse, startupTimeout, ghidraCancelGrace, + ghidraCheckpointSaveWait, sdk, }; const restart = restartOnlyBounds(owners); diff --git a/src/application/Doctor.test.ts b/src/application/Doctor.test.ts index 2b67c2fca42..295c16e2b13 100644 --- a/src/application/Doctor.test.ts +++ b/src/application/Doctor.test.ts @@ -174,6 +174,7 @@ describe("doctor native analysis configuration", () => { ["REA_MCP_DOCTOR_DEADLINE_MS", "0"], ["REA_GHIDRA_STARTUP_TIMEOUT_MS", "abc"], ["REA_GHIDRA_CANCEL_GRACE_MS", "99"], + ["REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS", "49"], ["REA_SWIFTC_COMPILE_TIMEOUT_MS", "0"], ["REA_LOG_LEVEL", "verbose"], ["REA_GHIDRA_COMPILER_SPEC_ID", "gcc"], diff --git a/src/application/RegistrationEnvironmentValidation.ts b/src/application/RegistrationEnvironmentValidation.ts index 5e30844d3e1..8b2b1fcc8db 100644 --- a/src/application/RegistrationEnvironmentValidation.ts +++ b/src/application/RegistrationEnvironmentValidation.ts @@ -1,5 +1,6 @@ import { inspectAnalysisSettingSeeds } from "../config/analysisSettings.js"; import { inspectGhidraCancelGrace } from "../config/ghidraCancelGrace.js"; +import { inspectGhidraCheckpointSaveWait } from "../config/ghidraCheckpointSaveWait.js"; import { parseEnvironment, parseEnvironmentValues, @@ -39,6 +40,7 @@ export const validateRegistrationEnvironment = ( const seedIssues = [ ...inspectAnalysisSettingSeeds(runtimeEnvironment, unresolvedSettings), ...inspectGhidraCancelGrace(runtimeEnvironment, unresolvedSettings), + ...inspectGhidraCheckpointSaveWait(runtimeEnvironment, unresolvedSettings), ]; if (seedIssues.length > 0) return err( diff --git a/src/application/SetupRegistrationEnvironment.ts b/src/application/SetupRegistrationEnvironment.ts index dfb483169c9..7183c604d8f 100644 --- a/src/application/SetupRegistrationEnvironment.ts +++ b/src/application/SetupRegistrationEnvironment.ts @@ -73,6 +73,7 @@ const SELECTED_REGISTRATION_SETTINGS = [ "REA_GHIDRA_SEED_FILE", "REA_GHIDRA_PROJECT_PATH", "REA_GHIDRA_CHECKPOINT_DIR", + "REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS", "REA_GHIDRA_PROGRAM_NAME", "REA_GHIDRA_NATIVEAOT_JAR", "REA_HOPPER_CALLER_SCAN_BUDGET_MS", diff --git a/src/application/binary/BinarySession.ts b/src/application/binary/BinarySession.ts index 89c698e1ca2..5236103a1a4 100644 --- a/src/application/binary/BinarySession.ts +++ b/src/application/binary/BinarySession.ts @@ -14,10 +14,7 @@ import { } from "../EvidenceBundleFiles.js"; import type { ResetInvestigationReceipt } from "../../domain/investigationLifecycle.js"; -import { - retainSavedAnalysisSnapshot, - type SavedAnalysisSnapshot, -} from "../../domain/savedAnalysisSnapshot.js"; +import type { SavedAnalysisSnapshot } from "../../domain/savedAnalysisSnapshot.js"; import type { BinaryTarget } from "../../domain/binaryTargetTypes.js"; import { AnalysisCleanupRelease } from "../../domain/analysisCleanupRelease.js"; @@ -93,6 +90,11 @@ import { commitExecutionProfile, prepareSessionExecution, } from "./BinarySessionExecution.js"; +import { + retainCloseOutcome, + type ClosedWithSnapshot, + type EngineCloseReport, +} from "../../domain/engineCloseReport.js"; import { closeAnalysisClient } from "../../providers/AnalysisClientCleanup.js"; import { bundleExecutableProvenance } from "../../domain/apple/bundleExecutableProvenance.js"; import { @@ -277,6 +279,11 @@ export class BinarySession if (!resolved.ok) return resolved; if (isAborted(options.signal)) return err(cancelledBy("open_bundle_resources", options.signal)); + const unreported = this.#refuseUnreportedRelease( + "open_bundle_resources", + { active: true }, + ); + if (unreported !== undefined) return err(unreported); const pendingClosed = await this.#retryPendingCleanup(); if (!pendingClosed.ok) return pendingClosed; const pendingResourcesClosed = @@ -623,6 +630,10 @@ export class BinarySession await this.#drainCalls(admittedThrough); if (isAborted(options.signal)) return err(cancelledBy("open_binary", options.signal)); + const unreported = this.#refuseUnreportedRelease("open_binary", { + active: false, + }); + if (unreported !== undefined) return err(unreported); const pendingClosed = await this.#retryPendingCleanup(); if (!pendingClosed.ok) return pendingClosed; const pendingResourcesClosed = @@ -639,6 +650,11 @@ export class BinarySession ); if (fastPath !== undefined) return fastPath; } + // A live retained engine stays bound above; replacing one releases it. + const replacing = this.#refuseUnreportedRelease("open_binary", { + active: true, + }); + if (replacing !== undefined) return err(replacing); const previous = this.#active; this.#active = undefined; if (previous !== undefined) { @@ -826,6 +842,10 @@ export class BinarySession this.#externalMutationCleanupFailure = undefined; } + const unreported = this.#refuseUnreportedRelease(operationName, { + active: true, + }); + if (unreported !== undefined) return err(unreported); const pendingCleanup = await this.#retryPendingCleanup(); if (!pendingCleanup.ok) return err( @@ -914,7 +934,7 @@ export class BinarySession readonly retainProviderDocuments?: boolean; readonly cleanupRetry?: AnalysisCleanupRetry; } = {}, - ): Promise> { + ): Promise> { return this.#serialize(async (admittedThrough) => { await this.#drainCalls(admittedThrough); return this.#offerCleanupRetry( @@ -931,7 +951,7 @@ export class BinarySession options: Pick & { readonly cleanupRetry?: AnalysisCleanupRetry; } = {}, - ): Promise> { + ): Promise> { return this.#serialize(async (admittedThrough) => { await this.#drainCalls(admittedThrough); const snapshot = this.exportAnalysisSnapshot(); @@ -955,8 +975,8 @@ export class BinarySession options.cleanupRetry, ); return closed.ok - ? ok(receipt) - : err(retainSavedAnalysisSnapshot(closed.error, receipt)); + ? ok(closed.value === null ? receipt : { ...receipt, ...closed.value }) + : err(retainCloseOutcome(closed.error, { saved_snapshot: receipt })); }); } @@ -969,9 +989,11 @@ export class BinarySession this.beginShutdown(); return this.#serialize(async (admittedThrough) => { await this.#drainCalls(admittedThrough); + // Disposal ends the process; no caller remains to read a close report. const closed = await this.#closeActive(options); - if (closed.ok) this.disposeInvestigationRecords(); - return closed; + if (!closed.ok) return closed; + this.disposeInvestigationRecords(); + return ok(null); }); } @@ -1004,6 +1026,10 @@ export class BinarySession return adapterResources; if (this.#externalMutationCleanupFailure?.cleanupIncomplete === true) return err(this.#externalMutationCleanupFailure); + const unreported = this.#refuseUnreportedRelease("reset_investigation", { + active: false, + }); + if (unreported !== undefined) return err(unreported); const pending = await this.#retryPendingCleanup(); if (!pending.ok) return pending; const bundles = await this.#retryPendingBundleResourceCleanup(); @@ -1055,10 +1081,10 @@ export class BinarySession } /** Offer the caller's retry only while this session retains the failed cleanup. */ - #offerCleanupRetry( - closed: Result, + #offerCleanupRetry( + closed: Result, retry: AnalysisCleanupRetry | undefined, - ): Result { + ): Result { this.#lastCloseCleanupFailure = undefined; if ( !closed.ok && @@ -1094,12 +1120,39 @@ export class BinarySession ); } + /** + * Only close_binary reports engine state released unsaved, so another + * transition that would release it refuses instead of dropping the report. + * `active` includes the bound engine for transitions that replace it. + */ + #refuseUnreportedRelease( + operation: string, + { active }: { readonly active: boolean }, + ): AnalysisError | undefined { + const report = + this.#pendingCleanup?.run.client.unsavedCloseReport?.() ?? + (active ? (this.#active?.client.unsavedCloseReport?.() ?? null) : null); + if (report === null) return undefined; + return new AnalysisCapabilityUnavailableError( + this.#pendingCleanup?.run.route.identity.id ?? + this.#active?.route.identity.id ?? + "rea", + operation, + "this session holds Program edits whose checkpoint save was refused, and this call would release them without reporting it", + { + userMessage: `Another REA session saved this target's checkpoint at ${JSON.stringify(report.checkpoint.directory)} first, so this session's Program edits cannot be saved; ${operation} would discard them.`, + remediationAction: + "Call close_binary first: it discards those edits and reports it. Then repeat this call, and reapply the edits to the current checkpoint if you still need them.", + }, + ); + } + async #closeActive( options: Pick & { readonly retainProviderDocuments?: boolean; }, onCleanupFailure?: (failure: AnalysisError) => void, - ): Promise> { + ): Promise> { const previous = this.#active; const previousResources = this.#activeBundleResources; this.#active = undefined; @@ -1149,17 +1202,20 @@ export class BinarySession "close_binary", ); } - if (!closed.ok && resourceFailure !== undefined) { - return err( - analysisErrorWithCloseRejections( - closed.error, - resourceFailure, - "close_binary", - ), - ); - } - if (!closed.ok) return closed; - return resourceFailure === undefined ? ok(null) : err(resourceFailure); + if (resourceFailure === undefined) return closed; + // A released engine's report stays with the close that released it. + return err( + retainCloseOutcome( + closed.ok + ? resourceFailure + : analysisErrorWithCloseRejections( + closed.error, + resourceFailure, + "close_binary", + ), + closed, + ), + ); } async #retryPendingBundleResourceCleanup( @@ -1201,7 +1257,7 @@ export class BinarySession readonly retainDocument?: boolean; readonly onCleanupFailure?: (failure: AnalysisError) => void; } = {}, - ): Promise> { + ): Promise> { this.#pendingCleanup = { run, retainDocument: options.retainDocument === true, @@ -1218,7 +1274,7 @@ export class BinarySession progress?: ExecutionOptions["progress"], retainDocument?: boolean, onCleanupFailure?: (failure: AnalysisError) => void, - ): Promise> { + ): Promise> { let pending = this.#pendingCleanup; if (pending === undefined) return ok(null); if (retainDocument !== undefined) { diff --git a/src/application/binary/BinarySessionPort.ts b/src/application/binary/BinarySessionPort.ts index 14cba20a469..b4500b44d32 100644 --- a/src/application/binary/BinarySessionPort.ts +++ b/src/application/binary/BinarySessionPort.ts @@ -26,7 +26,10 @@ import type { ProviderIdentity, } from "../../ports/AnalysisProvider.js"; -import type { SavedAnalysisSnapshot } from "../../domain/savedAnalysisSnapshot.js"; +import type { + ClosedWithSnapshot, + EngineCloseReport, +} from "../../domain/engineCloseReport.js"; /** Selection observed at the end of one serialized open attempt. */ export type OpenSelectionReceipt = @@ -112,7 +115,7 @@ export interface BinarySessionPort readonly retainProviderDocuments?: boolean; readonly cleanupRetry?: AnalysisCleanupRetry; }, - ): Promise>; + ): Promise>; /** Seal runtime acquisition and release investigation state after successful cleanup. */ dispose( options?: Pick & { @@ -136,7 +139,7 @@ export interface BinarySessionPort options?: Pick & { readonly cleanupRetry?: AnalysisCleanupRetry; }, - ): Promise>; + ): Promise>; /** Default complete detail; summary omits provider diagnostics and candidate capabilities. */ status(options?: { readonly signal?: AbortSignal; diff --git a/src/application/binary/CompositeProvider.ts b/src/application/binary/CompositeProvider.ts index 9dc7857218c..e46cc77f70e 100644 --- a/src/application/binary/CompositeProvider.ts +++ b/src/application/binary/CompositeProvider.ts @@ -19,6 +19,10 @@ import type { ProviderIdentity, } from "../../ports/AnalysisProvider.js"; import { closeAnalysisClient } from "../../providers/AnalysisClientCleanup.js"; +import { + engineCloseReportOf, + retainCloseOutcome, +} from "../../domain/engineCloseReport.js"; import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js"; /** Synthetic identity for a deterministic provider set. */ @@ -69,47 +73,50 @@ const closeCompositeClients = ( const failures = outcomes.flatMap(({ providerId, release, result }) => result.ok ? [] : [{ providerId, release, error: result.error }], ); - if (failures.length === 0) return ok(null); + // A child that released its engine reports it now, even when a sibling + // fails: a retry skips that released child and could not report it. + const report = engineCloseReportOf(...outcomes.map(({ result }) => result)); + if (failures.length === 0) return ok(report); if (failures.length === 1) { const failure = failures[0]; - if (failure !== undefined) return err(failure.error); + if (failure !== undefined) + return err(retainCloseOutcome(failure.error, report)); } const unknownReleases = failures.flatMap(({ error, release }) => error.carriesCleanup ? [] : [release], ); - return err( - new ProviderCleanupError( - identity.id, - [], - { - reason: - "Multiple composed provider clients could not be confirmed closed.", - failures: failures.map(({ providerId, error }) => ({ - provider_id: providerId, - message: error.message, - resources: [...error.cleanupResources], - ...(error.diagnostics === undefined - ? {} - : { diagnostics: error.diagnostics }), - })), - }, - { - remediationAction: [ - ...new Set( - failures.map( - ({ error }) => projectAnalysisError(error).remediation.action, - ), + const aggregate = new ProviderCleanupError( + identity.id, + [], + { + reason: + "Multiple composed provider clients could not be confirmed closed.", + failures: failures.map(({ providerId, error }) => ({ + provider_id: providerId, + message: error.message, + resources: [...error.cleanupResources], + ...(error.diagnostics === undefined + ? {} + : { diagnostics: error.diagnostics }), + })), + }, + { + remediationAction: [ + ...new Set( + failures.map( + ({ error }) => projectAnalysisError(error).remediation.action, ), - ].join("\n"), - cause: new AggregateError( - failures.map(({ error }) => error), - "Composed provider cleanup failed.", ), - }, - ) - .bindCleanupDependencies(failures.map(({ error }) => error)) - .bindCleanupReleaseClaim(allClientsReleased(unknownReleases)), - ); + ].join("\n"), + cause: new AggregateError( + failures.map(({ error }) => error), + "Composed provider cleanup failed.", + ), + }, + ) + .bindCleanupDependencies(failures.map(({ error }) => error)) + .bindCleanupReleaseClaim(allClientsReleased(unknownReleases)); + return err(retainCloseOutcome(aggregate, report)); }; }; @@ -275,6 +282,10 @@ export class CompositeProvider implements AnalysisProvider { ? "unknown" : "ready"; }, + unsavedCloseReport: () => + [...clients.values()] + .map((client) => client.unsavedCloseReport?.() ?? null) + .find((report) => report !== null) ?? null, operationHealthSnapshot: () => { const snapshots = [...clients.values()].map((client) => client.operationHealthSnapshot?.(), diff --git a/src/config/ghidraCheckpointSaveWait.test.ts b/src/config/ghidraCheckpointSaveWait.test.ts new file mode 100644 index 00000000000..3bd0abb8e68 --- /dev/null +++ b/src/config/ghidraCheckpointSaveWait.test.ts @@ -0,0 +1,149 @@ +import { expect, it } from "vitest"; + +import { ANALYSIS_SETTINGS } from "../domain/analysisSettingDefinitions.js"; +import { ConfigurationError } from "../domain/configurationErrors.js"; +import { validateRegistrationEnvironment } from "../application/RegistrationEnvironmentValidation.js"; +import { explicitSetupRegistrationEnvironment } from "../application/SetupRegistrationEnvironment.js"; +import { + ghidraCheckpointSaveWaitLimit, + ghidraCheckpointSaveWaitRecovery, + parseGhidraCheckpointSaveWait, +} from "./ghidraCheckpointSaveWait.js"; +import { + inspectNativeAnalysisConfiguration, + parseConfig, +} from "./parseConfig.js"; + +const SETTING = "REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS"; + +it("waits 30 seconds when the launch environment does not set the control", () => { + expect(parseGhidraCheckpointSaveWait(undefined)).toEqual({ + ok: true, + value: { waitMs: 30_000, source: "default" }, + }); + const config = parseConfig({}); + expect(config.ok && config.value.ghidraCheckpointSaveWait).toEqual({ + ok: true, + value: { waitMs: 30_000, source: "default" }, + }); +}); + +it.each([50, 1_200, 600_000])("admits a launch value of %d ms", (waitMs) => { + const expected = { ok: true, value: { waitMs, source: "setting" } }; + expect(parseGhidraCheckpointSaveWait(String(waitMs))).toEqual(expected); + const config = parseConfig({ [SETTING]: String(waitMs) }); + expect(config.ok && config.value.ghidraCheckpointSaveWait).toEqual(expected); +}); + +it.each([ + ["below the one-poll floor", "49"], + ["above the ten-minute maximum", "600001"], + ["far above the maximum", "99999999999999999999"], + ["zero", "0"], + ["empty", ""], + ["negative", "-1"], + ["leading zero", "0500"], + ["exponent", "1e4"], + ["separator", "30_000"], + ["fraction", "1500.5"], + ["padded", " 1500"], + ["unit suffix", "30s"], +])("refuses a value %s without using the default", (_case, raw) => { + const parsed = parseGhidraCheckpointSaveWait(raw); + if (parsed.ok) throw new Error(`accepted ${JSON.stringify(raw)}`); + expect(parsed.error).toBeInstanceOf(ConfigurationError); + expect(parsed.error.settings).toHaveLength(1); + expect(parsed.error.settings[0]?.setting).toBe(SETTING); + expect(parsed.error.settings[0]?.constraint).toContain("from 50 to 600000"); + expect(parsed.error.remediationAction).toContain( + "environment that starts REA", + ); + // The rejected text is never echoed. + if (raw.trim().length > 2) + expect(parsed.error.settings[0]?.constraint).not.toContain(raw); +}); + +it("keeps REA starting on an invalid value and reports it to doctor and registration", () => { + const environment = { [SETTING]: "49" }; + // Other providers and tools are unaffected; the Ghidra session refuses it. + const config = parseConfig(environment); + if (!config.ok) throw config.error; + const wait = config.value.ghidraCheckpointSaveWait; + expect(wait?.ok).toBe(false); + expect(inspectNativeAnalysisConfiguration(environment).issues).toEqual([ + expect.objectContaining({ setting: SETTING }), + ]); + expect(inspectNativeAnalysisConfiguration({}).issues).toEqual([]); + const registration = validateRegistrationEnvironment( + environment, + new Set(), + "effective", + "linux", + ); + if (registration.ok) throw new Error("registration accepted the value"); + expect(registration.error.settings).toEqual([ + expect.objectContaining({ setting: SETTING }), + ]); + // A client expression is not a known value, so it is not judged. + expect( + validateRegistrationEnvironment( + {}, + new Set([SETTING]), + "effective", + "linux", + ).ok, + ).toBe(true); +}); + +it("is forwarded by setup when the caller selected it", () => { + expect( + explicitSetupRegistrationEnvironment({ + [SETTING]: "45000", + REA_UNRELATED: "1", + }), + ).toEqual({ [SETTING]: "45000" }); +}); + +it("stays a launch-only control outside the runtime setting registry", () => { + const seeds: (string | undefined)[] = Object.values(ANALYSIS_SETTINGS).map( + (definition) => + "environment" in definition ? definition.environment : undefined, + ); + expect(seeds).toContain("REA_GHIDRA_STARTUP_TIMEOUT_MS"); + expect(seeds).not.toContain(SETTING); +}); + +it("reports the control, effective value, source and range of an exhausted wait", () => { + expect( + ghidraCheckpointSaveWaitLimit({ waitMs: 1_200, source: "setting" }), + ).toEqual({ + control_kind: "environment", + environment: SETTING, + effective_value: 1_200, + unit: "ms", + minimum: 50, + maximum: 600_000, + default_value: 30_000, + applies_at: "next_startup", + }); + const raised = ghidraCheckpointSaveWaitRecovery({ + waitMs: 1_200, + source: "setting", + }); + expect(raised).toContain(`${SETTING} is 1200 ms (source launch environment`); + expect(raised).toContain("floor 50, maximum 600000"); + expect(raised).toContain("restart REA"); + expect(raised).toContain("update_analysis_settings does not change it"); + // The client's deadline is independent, so a longer wait is no promise. + expect(raised).toContain( + "cannot make an MCP client wait longer: that client's own request deadline is separate and unknown to REA", + ); + const unset = ghidraCheckpointSaveWaitRecovery({ + waitMs: 30_000, + source: "default", + }); + expect(unset).toContain(`${SETTING} is 30000 ms (source default`); + expect( + ghidraCheckpointSaveWaitRecovery({ waitMs: 600_000, source: "setting" }), + ).toContain("already at its maximum"); +}); diff --git a/src/config/ghidraCheckpointSaveWait.ts b/src/config/ghidraCheckpointSaveWait.ts new file mode 100644 index 00000000000..f59e8e4939c --- /dev/null +++ b/src/config/ghidraCheckpointSaveWait.ts @@ -0,0 +1,118 @@ +import { positiveDecimalIntegerSchema } from "./positiveDecimalInteger.js"; + +import type { AnalysisControlLimit } from "../domain/analysisSettings.js"; +import { + ConfigurationError, + type ConfigurationSettingIssue, +} from "../domain/configurationErrors.js"; +import { err, ok, type Result } from "../domain/result.js"; + +export const GHIDRA_CHECKPOINT_SAVE_WAIT_SETTING = + "REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS"; + +/** How often a waiting save re-checks the publication lease. */ +export const GHIDRA_CHECKPOINT_SAVE_POLL_MS = 50; + +/** Wait applied when `REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS` is unset. */ +export const DEFAULT_GHIDRA_CHECKPOINT_SAVE_WAIT_MS = 30_000; + +/** + * One poll interval. A shorter wait would report the checkpoint busy without + * observing the lease a second time, which is a refusal and not a wait. + */ +export const MINIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS = + GHIDRA_CHECKPOINT_SAVE_POLL_MS; + +/** + * Ten minutes. The wait runs inside `close_binary` and the first save of a + * startup, and it covers only another session's publication: one copy and + * sync of a packed Program and a manifest rename. A lease still held after + * that long is a stalled publisher, which the busy refusal names so the caller + * can act instead of leaving the close blocked. The MCP client's own request + * deadline is separate and unknown to REA; a wait above it leaves the client + * giving up while the close continues, so recovery says to stay below it. + */ +export const MAXIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS = 600_000; + +/** The wait one session applies, and whether the launch environment chose it. */ +export interface GhidraCheckpointSaveWait { + readonly waitMs: number; + readonly source: "default" | "setting"; +} + +export const DEFAULT_GHIDRA_CHECKPOINT_SAVE_WAIT: GhidraCheckpointSaveWait = { + waitMs: DEFAULT_GHIDRA_CHECKPOINT_SAVE_WAIT_MS, + source: "default", +}; + +const constraint = `${GHIDRA_CHECKPOINT_SAVE_WAIT_SETTING} must be a decimal integer from ${String(MINIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS)} to ${String(MAXIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS)} ms; the default is ${String(DEFAULT_GHIDRA_CHECKPOINT_SAVE_WAIT_MS)} ms`; + +const schema = positiveDecimalIntegerSchema( + MINIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS, + MAXIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS, + constraint, +); + +/** Parse the launch value; an invalid value is refused, never replaced by the default. */ +export const parseGhidraCheckpointSaveWait = ( + value: string | undefined, +): Result => { + if (value === undefined) return ok(DEFAULT_GHIDRA_CHECKPOINT_SAVE_WAIT); + const parsed = schema.safeParse(value); + return parsed.success + ? ok({ waitMs: parsed.data, source: "setting" }) + : err( + new ConfigurationError( + `Invalid ${GHIDRA_CHECKPOINT_SAVE_WAIT_SETTING}`, + { + cause: parsed.error, + settings: [ + { setting: GHIDRA_CHECKPOINT_SAVE_WAIT_SETTING, constraint }, + ], + remediationAction: `Set ${GHIDRA_CHECKPOINT_SAVE_WAIT_SETTING} to a decimal integer from ${String(MINIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS)} to ${String(MAXIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS)} ms, or unset it for the ${String(DEFAULT_GHIDRA_CHECKPOINT_SAVE_WAIT_MS)} ms default, in the environment that starts REA, then restart REA. update_analysis_settings does not change it.`, + }, + ), + ); +}; + +/** Report an invalid launch value to doctor and registration validation. */ +export const inspectGhidraCheckpointSaveWait = ( + environment: Readonly>, + unresolvedSettings: ReadonlySet = new Set(), +): readonly ConfigurationSettingIssue[] => { + if (unresolvedSettings.has(GHIDRA_CHECKPOINT_SAVE_WAIT_SETTING)) return []; + const parsed = parseGhidraCheckpointSaveWait( + environment.REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS, + ); + return parsed.ok ? [] : parsed.error.settings; +}; + +/** Structured facts of the wait a busy refusal exhausted. */ +export const ghidraCheckpointSaveWaitLimit = ( + wait: GhidraCheckpointSaveWait, +): AnalysisControlLimit => ({ + control_kind: "environment", + environment: GHIDRA_CHECKPOINT_SAVE_WAIT_SETTING, + effective_value: wait.waitMs, + unit: "ms", + minimum: MINIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS, + maximum: MAXIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS, + default_value: DEFAULT_GHIDRA_CHECKPOINT_SAVE_WAIT_MS, + applies_at: "next_startup", +}); + +/** The control, effective value, source and range, as one clause. */ +export const ghidraCheckpointSaveWaitFacts = ( + wait: GhidraCheckpointSaveWait, +): string => + `${GHIDRA_CHECKPOINT_SAVE_WAIT_SETTING} is ${String(wait.waitMs)} ms (source ${wait.source === "setting" ? "launch environment" : "default"}; default ${String(DEFAULT_GHIDRA_CHECKPOINT_SAVE_WAIT_MS)}, floor ${String(MINIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS)}, maximum ${String(MAXIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS)})`; + +/** Recovery for a save that waited the whole bound. */ +export const ghidraCheckpointSaveWaitRecovery = ( + wait: GhidraCheckpointSaveWait, +): string => + `Wait for that session's save to finish, then repeat this call unchanged. If that save changes the checkpoint first, the repeated call reports that this session's checkpoint was superseded and names the next step, normally reopening the target. This session waited its whole save wait: ${ghidraCheckpointSaveWaitFacts(wait)}. ${ + wait.waitMs < MAXIMUM_GHIDRA_CHECKPOINT_SAVE_WAIT_MS + ? `To wait longer within one call, set ${GHIDRA_CHECKPOINT_SAVE_WAIT_SETTING} in the environment that starts REA and restart REA` + : `${GHIDRA_CHECKPOINT_SAVE_WAIT_SETTING} is already at its maximum` + }; update_analysis_settings does not change it, and it does not shorten the other session's save. Raising it cannot make an MCP client wait longer: that client's own request deadline is separate and unknown to REA, so keep the wait below it.`; diff --git a/src/config/parseConfig.ts b/src/config/parseConfig.ts index 5cd5914a973..ed959082c80 100644 --- a/src/config/parseConfig.ts +++ b/src/config/parseConfig.ts @@ -21,6 +21,10 @@ import { inspectGhidraCancelGrace, parseGhidraCancelGrace, } from "./ghidraCancelGrace.js"; +import { + inspectGhidraCheckpointSaveWait, + parseGhidraCheckpointSaveWait, +} from "./ghidraCheckpointSaveWait.js"; import { hopperCallerScanBudgetFromEnvironment } from "./hopperCallerScanBudget.js"; import { DEFAULT_REGEX_MATCHING_DEADLINE } from "./regexMatchingDeadline.js"; import { DEFAULT_REGEX_WORKER_HEAP_REQUEST } from "./regexWorkerHeapRequest.js"; @@ -57,6 +61,7 @@ export const inspectNativeAnalysisConfiguration = ( ...(parsed.ok ? [] : parsed.error.settings), ...inspectAnalysisSettingSeeds(nativeAnalysisEnvironment(environment)), ...inspectGhidraCancelGrace(environment), + ...inspectGhidraCheckpointSaveWait(environment), ]; const configuredTimeout = environment.REA_HOPPER_STARTUP_TIMEOUT_MS; if (configuredTimeout === undefined) return { issues }; @@ -161,6 +166,9 @@ export const parseConfig = ( ...(env.REA_GHIDRA_CHECKPOINT_DIR === undefined ? {} : { ghidraCheckpointDirectory: env.REA_GHIDRA_CHECKPOINT_DIR }), + ghidraCheckpointSaveWait: parseGhidraCheckpointSaveWait( + environment.REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS, + ), ghidraJavaHome: env.JAVA_HOME, ghidraStartupTimeoutMs: ghidraStartup ?? DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS, ghidraCancelGrace: parseGhidraCancelGrace( diff --git a/src/config/types.ts b/src/config/types.ts index 18ffbda0563..3b4b765db31 100644 --- a/src/config/types.ts +++ b/src/config/types.ts @@ -10,6 +10,7 @@ import type { McpToolsListPageBudget } from "./mcpToolsListPageBudget.js"; import type { BridgeMaxRequestBytes } from "./bridgeMaxRequestBytes.js"; import type { BridgeMaxReplyBytes } from "./bridgeMaxReplyBytes.js"; import type { GhidraCancelGrace } from "./ghidraCancelGrace.js"; +import type { GhidraCheckpointSaveWait } from "./ghidraCheckpointSaveWait.js"; import type { Result } from "../domain/result.js"; import type { RegexMatchingDeadline } from "./regexMatchingDeadline.js"; import type { RegexWorkerHeapRequest } from "./regexWorkerHeapRequest.js"; @@ -49,6 +50,15 @@ export interface AppConfig { readonly ghidraExistingProject?: GhidraProjectSelection; /** Opt-in storage for checkpoints of REA-owned Ghidra Programs. */ readonly ghidraCheckpointDirectory?: string; + /** + * Launch-only bound on a checkpoint save's wait for another session's + * publication; absent keeps the default. A refused launch value stays a + * failure for the sessions that would apply it, never the default. + */ + readonly ghidraCheckpointSaveWait?: Result< + GhidraCheckpointSaveWait, + ConfigurationError + >; readonly ghidraNativeAotJar?: string; readonly ilspyCmdPath: string | undefined; /** diff --git a/src/contracts/sessionToolContracts.ts b/src/contracts/sessionToolContracts.ts index 02053349cfc..4aa66775655 100644 --- a/src/contracts/sessionToolContracts.ts +++ b/src/contracts/sessionToolContracts.ts @@ -106,7 +106,7 @@ export const SESSION_TOOL_CONTRACTS = [ mayDiscardData: true, idempotent: false, }), - "Release the active engine and owned resources while retaining investigation Evidence and complete Unknown history in memory. Drains earlier requests and queues later ones. If cleanup fails, keep this connection and retry close_binary without snapshot_path after the reported condition settles. Optional snapshot_path saves a target-bound snapshot first; resource-only sessions have no snapshot binding, existing files require overwrite, and failed saves keep the engine open. Metadata edits prevent immutable snapshot saves until recreation. Ghidra checkpoint mode saves metadata on normal close and retains the Program for retry if saving fails. Closing does not persist investigation records: export_evidence_bundle to save them, or reset_investigation to clear them.", + "Release the active engine and owned resources while retaining investigation Evidence and complete Unknown history in memory. Drains earlier requests and queues later ones. If cleanup fails, keep this connection and retry close_binary without snapshot_path after the reported condition settles. Optional snapshot_path saves a target-bound snapshot first; resource-only sessions have no snapshot binding, existing files require overwrite, and failed saves keep the engine open. Metadata edits prevent immutable snapshot saves until recreation. Ghidra checkpoint mode saves metadata on normal close and retains the Program for retry if saving fails; after a save refused because another session published first, the next close releases the edits unsaved and reports checkpoint.status discarded. Closing does not persist investigation records: export_evidence_bundle to save them, or reset_investigation to clear them.", closeBinaryInputSchema, ), session( diff --git a/src/contracts/toolOutputSchemaGroups.ts b/src/contracts/toolOutputSchemaGroups.ts index 0315018d680..c0831552f48 100644 --- a/src/contracts/toolOutputSchemaGroups.ts +++ b/src/contracts/toolOutputSchemaGroups.ts @@ -1,4 +1,5 @@ import { coverageStatusSchema } from "../domain/coverage.js"; +import { discardedCheckpointEditsSchema } from "../domain/engineCloseReport.js"; import { procedureReferencesSchema } from "../domain/native/procedureReferences.js"; import { nativeAddressListSchema, @@ -529,7 +530,9 @@ export const sessionOutputSchemas = { .describe( "All retained Evidence records, including observations without replay bindings.", ), + checkpoint: discardedCheckpointEditsSchema.optional(), }), + z.strictObject({ checkpoint: discardedCheckpointEditsSchema }), ]), ), // Every session kind crossed with every detail level, so `detail` fixes diff --git a/src/domain/analysisErrorBase.ts b/src/domain/analysisErrorBase.ts index 4b5b69fb7ce..ce010852dcd 100644 --- a/src/domain/analysisErrorBase.ts +++ b/src/domain/analysisErrorBase.ts @@ -15,7 +15,7 @@ import type { PlaywrightTrace } from "./playwrightTrace/playwrightTrace.js"; import type { ErlangBeam } from "./erlang/beam.js"; import type { ApiContract } from "./apiContract/apiContract.js"; import type { GraphqlContract } from "./apiContract/graphqlContract.js"; -import type { SavedAnalysisSnapshotPartialObservation } from "./savedAnalysisSnapshot.js"; +import type { CloseOutcomePartialObservation } from "./engineCloseReport.js"; import type { AnalysisLimit } from "./analysisSettings.js"; import type { JsonValue } from "./jsonValue.js"; import type { AnalysisCleanupRetry } from "./analysisErrorRecovery.js"; @@ -753,7 +753,7 @@ export type AnalysisPartialObservation = | ApiContract | GraphqlContract | PlaywrightTrace - | SavedAnalysisSnapshotPartialObservation + | CloseOutcomePartialObservation | WebArtifactAcquisition | WebTraceObservation | CutterBridgeDiscovery diff --git a/src/domain/engineCloseReport.ts b/src/domain/engineCloseReport.ts new file mode 100644 index 00000000000..e61d3d4fc8a --- /dev/null +++ b/src/domain/engineCloseReport.ts @@ -0,0 +1,141 @@ +import { z } from "zod"; + +import type { + AnalysisError, + AnalysisPartialObservation, +} from "./analysisErrorBase.js"; +import { err, type Result } from "./result.js"; +import type { SavedAnalysisSnapshot } from "./savedAnalysisSnapshot.js"; + +/** + * Engine state a successful close released without persisting it. A Ghidra + * checkpoint session whose save another session superseded keeps its Program + * edits until the next close, which releases them unsaved. + */ +export const discardedCheckpointEditsSchema = z + .strictObject({ + status: z.literal("discarded"), + reason: z + .literal("superseded") + .describe( + "Another session published this target's checkpoint first, so the save was refused.", + ), + directory: z + .string() + .min(1) + .describe("Checkpoint directory whose current generation is unchanged."), + }) + .describe( + "This session's Program edits were released unsaved; reopen the target and reapply them to the current checkpoint.", + ); + +export type DiscardedCheckpointEdits = z.infer< + typeof discardedCheckpointEditsSchema +>; + +/** + * What a successful engine close reports beyond releasing its resources. A + * type alias, not an interface, so the JSON result contract accepts it. + */ +export type EngineCloseReport = { + readonly checkpoint: DiscardedCheckpointEdits; +}; + +/** A snapshot saved before the close, with what that close released unsaved. */ +export type ClosedWithSnapshot = SavedAnalysisSnapshot & + Partial; + +/** Every value a successful close returns. */ +export type CloseValue = EngineCloseReport | ClosedWithSnapshot | null; + +/** + * Facts a close completed before a later step of it failed: a published + * snapshot and engine state released unsaved. Both stay true after the + * failure, so the failure carries them as its partial observation. + */ +export interface CloseOutcomePartialObservation { + readonly saved_snapshot?: SavedAnalysisSnapshot; + readonly checkpoint?: DiscardedCheckpointEdits; + /** The failing cleanup producer's own observation, kept beside them. */ + readonly cleanup_observation?: AnalysisPartialObservation; +} + +type CloseFacts = Pick< + CloseOutcomePartialObservation, + "saved_snapshot" | "checkpoint" +>; + +const isCloseOutcome = ( + observation: AnalysisPartialObservation | undefined, +): observation is CloseOutcomePartialObservation => + typeof observation === "object" && + observation !== null && + !("kind" in observation) && + ("saved_snapshot" in observation || "checkpoint" in observation); + +const factsOfValue = (value: CloseValue): CloseFacts => { + if (value === null) return {}; + const { checkpoint, ...rest } = value; + return { + ...("path" in rest ? { saved_snapshot: rest } : {}), + ...(checkpoint === undefined ? {} : { checkpoint }), + }; +}; + +const observationOf = ( + outcome: Result, +): CloseOutcomePartialObservation => { + if (outcome.ok) return factsOfValue(outcome.value); + const observation = outcome.error.partialObservation; + if (observation === undefined) return {}; + return isCloseOutcome(observation) + ? observation + : { cleanup_observation: observation }; +}; + +/** + * Attach completed close facts to the failure that ends that close. This is + * the one composition point for them: every owner that turns a released + * engine or a published snapshot into a failure calls it on its outermost + * error, with the outcomes it composed, so composing errors cannot drop + * them. A failed outcome also contributes its producer's own observation. + * Facts already attached win. + */ +export const retainCloseOutcome = ( + error: Failure, + ...sources: readonly (CloseFacts | null | Result)[] +): Failure => { + let { saved_snapshot, checkpoint, cleanup_observation } = observationOf( + err(error), + ); + for (const source of sources) { + if (source === null) continue; + const facts: CloseOutcomePartialObservation = + "ok" in source ? observationOf(source) : source; + saved_snapshot ??= facts.saved_snapshot; + checkpoint ??= facts.checkpoint; + cleanup_observation ??= facts.cleanup_observation; + } + if (saved_snapshot === undefined && checkpoint === undefined) return error; + error.partialObservation = Object.freeze({ + ...(saved_snapshot === undefined + ? {} + : { saved_snapshot: Object.freeze({ ...saved_snapshot }) }), + ...(checkpoint === undefined + ? {} + : { checkpoint: Object.freeze({ ...checkpoint }) }), + ...(cleanup_observation === undefined ? {} : { cleanup_observation }), + }); + return error; +}; + +/** The engine report among close outcomes; one close releases at most one engine's edits. */ +export const engineCloseReportOf = ( + ...outcomes: readonly Result[] +): EngineCloseReport | null => { + for (const outcome of outcomes) { + const { checkpoint } = observationOf(outcome); + if (checkpoint !== undefined) return { checkpoint }; + } + return null; +}; diff --git a/src/domain/numericLimitRegistry.ts b/src/domain/numericLimitRegistry.ts index 359fb5f478c..b4eea62cc59 100644 --- a/src/domain/numericLimitRegistry.ts +++ b/src/domain/numericLimitRegistry.ts @@ -52,6 +52,14 @@ export const NUMERIC_LIMIT_REGISTRY = [ reason: "Parsed once when REA starts and fixed for each Ghidra session when its request queue is constructed. It bounds how long a cancelled read may take to answer before that session is closed, so a session keeps the grace it opened with.", }, + { + name: "REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS", + update_mode: "restart", + policy: "restart-only", + read: "startup", + reason: + "Parsed once when REA starts and fixed for each Ghidra session when its checkpoint owner is constructed. It bounds how long a close waits on another session's save, so a session keeps the bound it opened with.", + }, { name: "REA_HOPPER_DEMO_DIALOG_TIMEOUT_MS", update_mode: "restart", diff --git a/src/domain/savedAnalysisSnapshot.ts b/src/domain/savedAnalysisSnapshot.ts index 5fe34785b53..36e55bdc4cd 100644 --- a/src/domain/savedAnalysisSnapshot.ts +++ b/src/domain/savedAnalysisSnapshot.ts @@ -1,8 +1,3 @@ -import type { - AnalysisError, - AnalysisPartialObservation, -} from "./analysisErrorBase.js"; - /** Receipt for an atomically published analysis snapshot. */ export interface SavedAnalysisSnapshot { readonly path: string; @@ -14,23 +9,3 @@ export interface SavedAnalysisSnapshot { /** Includes retained observations without a replay binding. */ readonly evidence_records: number; } - -/** Publication remains committed even when subsequent lifecycle cleanup fails. */ -export interface SavedAnalysisSnapshotPartialObservation { - readonly saved_snapshot: SavedAnalysisSnapshot; - readonly cleanup_observation?: AnalysisPartialObservation; -} - -/** Attach publication facts without discarding a cleanup producer's own observation. */ -export const retainSavedAnalysisSnapshot = ( - error: AnalysisError, - receipt: SavedAnalysisSnapshot, -): AnalysisError => { - error.partialObservation = { - saved_snapshot: Object.freeze({ ...receipt }), - ...(error.partialObservation === undefined - ? {} - : { cleanup_observation: error.partialObservation }), - }; - return error; -}; diff --git a/src/ghidra/GhidraCheckpoint.test.ts b/src/ghidra/GhidraCheckpoint.test.ts index a753a7ae6de..feef706fede 100644 --- a/src/ghidra/GhidraCheckpoint.test.ts +++ b/src/ghidra/GhidraCheckpoint.test.ts @@ -1,23 +1,28 @@ -import { afterEach, expect, it, vi } from "vitest"; +import { afterEach, expect, it, onTestFinished, vi } from "vitest"; import { createHash } from "node:crypto"; import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; +import { waitFor } from "../../tests/support/testWait.js"; import { chmod, access, mkdir, readFile, readdir, + realpath, writeFile, rm, rename, symlink, type FileHandle, } from "node:fs/promises"; +import { createServer } from "node:net"; import { join } from "node:path"; +import { sha256Hex } from "../kernel/sha256Hex.js"; import { ArtifactResourceScope } from "../resources/ArtifactResourceScope.js"; import { createAnalysisProfile } from "../domain/analysisProfile.js"; import { acquireOwnedLease } from "../process/OwnedLease.js"; import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; +import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { GhidraCheckpoint, GhidraCheckpointBusyError, @@ -27,7 +32,9 @@ import { } from "./GhidraCheckpoint.js"; const controls = vi.hoisted(() => ({ - file: undefined as ((handle: FileHandle, path: string) => void) | undefined, + file: undefined as + | ((handle: FileHandle, path: string) => void | Promise) + | undefined, })); vi.mock("node:fs/promises", async (importOriginal) => { const actual = await importOriginal(); @@ -37,7 +44,7 @@ vi.mock("node:fs/promises", async (importOriginal) => { rm: vi.fn(actual.rm), open: async (...args: Parameters) => { const handle = await actual.open(...args); - controls.file?.(handle, String(args[0])); + await controls.file?.(handle, String(args[0])); return handle; }, }; @@ -65,7 +72,7 @@ afterEach(async () => { ); vi.mocked(rm).mockReset().mockImplementation(actual.rm); vi.mocked(rename).mockReset().mockImplementation(actual.rename); - for (const owner of owners.splice(0)) await owner.close(); + for (const owner of owners.splice(0)) await owner.retryCleanup(); }); it.skipIf(process.platform === "win32")( @@ -93,19 +100,34 @@ it.skipIf(process.platform === "win32")( }, }; }); - await f.owner.acquire("original"); - const retained = [...f.owner.cleanupResources]; - expect(retained).toHaveLength(1); - await expect(f.owner.close()).rejects.toThrow( + await f.owner.admit("original"); + expect(f.owner.hasResources).toBe(false); + await expect(f.owner.publish(f.packed)).rejects.toThrow( "controlled lease release failure", ); - expect(f.owner.cleanupResources).toEqual(retained); + // The manifest was committed; only the lease release is outstanding. + const committed = await readFile( + join(f.selection.directory, "current.json"), + "utf8", + ); + const retained = [...f.owner.cleanupResources]; + expect(retained).toHaveLength(1); expect(f.owner.hasResources).toBe(true); - await f.owner.close(); - expect(f.owner.cleanupResources).toEqual([]); const peer = new GhidraCheckpoint(f.selection, f.resources); owners.push(peer); - expect(await peer.acquire("replacement")).toBeUndefined(); + expect((await peer.admit("reader"))?.sha256).toBe( + f.owner.observation.source?.sha256, + ); + await f.owner.publish(f.packed); + expect(f.owner.cleanupResources).toEqual([]); + expect(f.owner.hasResources).toBe(false); + expect( + await readFile(join(f.selection.directory, "current.json"), "utf8"), + ).toBe(committed); + const edited = join(f.root, "edited.gzf"); + await writeFile(edited, "edited by the reader"); + await peer.publish(edited); + expect(peer.observation.state.kind).toBe("retained"); }, ); const profile = createAnalysisProfile( @@ -141,9 +163,9 @@ it.skipIf(process.platform === "win32").each( "preserves $stage cancellation=$cancel and descriptor cleanup=$closeFails", async ({ stage, cancel, closeFails }) => { const f = await fixture(); - await f.owner.acquire("writer"); + await f.owner.admit("writer"); await f.owner.publish(f.packed); - await f.owner.close(); + await f.owner.retryCleanup(); const controller = new AbortController(); const reason = { caller: "stopped hashing" }; controls.file = (handle, path) => { @@ -198,65 +220,468 @@ it("hashes packed checkpoint bytes beyond the first buffer", async () => { ); }); +const edit = async (f: { root: string }, name: string) => { + const path = join(f.root, `${name}.gzf`); + await writeFile(path, `${name} packed bytes`); + return path; +}; +const peerOf = (f: Awaited>) => { + const peer = new GhidraCheckpoint(f.selection, f.resources); + owners.push(peer); + return peer; +}; +const programs = async (directory: string) => + (await readdir(directory)).filter((name) => name.endsWith(".gzf")); + it.skipIf(process.platform === "win32")( - "refuses a concurrent owner and admits it after the original owner closes", + "admits concurrent sessions without holding a lease between publications", async () => { const f = await fixture(); - await f.owner.acquire("first"); - const other = new GhidraCheckpoint(f.selection, f.resources); - owners.push(other); - await expect(other.acquire("second")).rejects.toThrow( - /another REA session.*first/, + const other = peerOf(f); + expect(await f.owner.admit("first")).toBeUndefined(); + expect(await other.admit("second")).toBeUndefined(); + expect(f.owner.hasResources).toBe(false); + await f.owner.publish(f.packed); + expect(f.owner.hasResources).toBe(false); + const third = peerOf(f); + expect((await third.admit("third"))?.sha256).toBe( + f.owner.observation.source?.sha256, ); - await f.owner.close(); - expect(await other.acquire("second")).toBeUndefined(); }, ); it.skipIf(process.platform === "win32")( - "reports a busy retry as superseded once the owner saves edits and closes", + "adopts the initial analysis another session published first instead of publishing twice", async () => { const f = await fixture(); - await f.owner.acquire("first"); - const waiting = new GhidraCheckpoint(f.selection, f.resources); - owners.push(waiting); - await expect(waiting.acquire("second")).rejects.toBeInstanceOf( - GhidraCheckpointBusyError, - ); - // The first publication records initial analysis, which a waiting - // session may adopt; the second records the owner's Program edits. + const other = peerOf(f); + await f.owner.admit("first"); + await other.admit("second"); await f.owner.publish(f.packed); - const edited = join(f.root, "edited.gzf"); - await writeFile(edited, "edited checkpoint"); - await f.owner.publish(edited); - await f.owner.close(); - await expect(waiting.acquire("second")).rejects.toBeInstanceOf( + const manifest = join(f.selection.directory, "current.json"); + const committed = await readFile(manifest, "utf8"); + await other.publish(await edit(f, "second-initial")); + expect(await readFile(manifest, "utf8")).toBe(committed); + expect(await programs(f.selection.directory)).toHaveLength(1); + expect(other.observation).toMatchObject({ + source: f.owner.observation.source, + state: { kind: "initial-analysis" }, + pending_cleanup: [], + }); + expect(other.hasResources).toBe(false); + // The adopter's later edits build on the published generation. + await other.publish(await edit(f, "second-edited")); + expect(JSON.parse(await readFile(manifest, "utf8")).source).toEqual( + other.observation.source, + ); + expect(other.observation.state.kind).toBe("retained"); + }, +); + +it.skipIf(process.platform === "win32").each(["restored", "analyzed"] as const)( + "refuses to save over a generation another session published (%s session)", + async (start) => { + const f = await fixture(); + const stale = peerOf(f); + await f.owner.admit("first"); + if (start === "analyzed") await stale.admit("stale"); + await f.owner.publish(f.packed); + if (start === "restored") await stale.admit("stale"); + await f.owner.publish(await edit(f, "first-edited")); + const manifest = join(f.selection.directory, "current.json"); + const committed = await readFile(manifest, "utf8"); + const files = (await readdir(f.selection.directory)).sort(); + const staged = await edit(f, "stale-edited"); + for (let attempt = 0; attempt < 2; attempt += 1) { + const refused = await stale.publish(staged).catch((cause) => cause); + expect(refused).toBeInstanceOf(GhidraCheckpointSupersededError); + // A session that only analyzed has no edits to lose; it reopens. + expect(refused).toMatchObject({ + stage: start === "analyzed" ? "restore" : "save", + }); + expect(refused.message).toMatch( + start === "analyzed" ? /reopen the target/ : /were not saved/, + ); + if (start === "analyzed") + expect(refused.message).not.toMatch(/edits were not saved/); + expect(await readFile(manifest, "utf8")).toBe(committed); + expect((await readdir(f.selection.directory)).sort()).toEqual(files); + expect(stale.hasResources).toBe(false); + } + // The refused session did not disturb the winner or a later reader. + await f.owner.publish(await edit(f, "first-edited-again")); + const reader = peerOf(f); + const selection = await resolveGhidraCheckpoint( + f.root, + target, + profile, + f.resources, + ); + expect(selection.state).toEqual(f.owner.observation.state); + await expect(reader.admit("reader")).rejects.toBeInstanceOf( GhidraCheckpointSupersededError, ); }, ); +/** Fail the next acquired lease's first release, then release normally. */ +const failNextLeaseRelease = async () => { + const leases = await vi.importActual< + typeof import("../process/OwnedLease.js") + >("../process/OwnedLease.js"); + vi.mocked(acquireOwnedLease).mockImplementationOnce(async (input) => { + const result = await leases.acquireOwnedLease(input); + if (!result.acquired) return result; + let failed = false; + return { + acquired: true, + lease: { + ...result.lease, + release: async () => { + if (!failed) { + failed = true; + throw new Error("controlled lease release failure"); + } + await result.lease.release(); + }, + }, + }; + }); +}; + +it.skipIf(process.platform === "win32")( + "keeps a refused save typed when releasing its lease also fails", + async () => { + const f = await fixture(); + const stale = peerOf(f); + await f.owner.admit("first"); + await f.owner.publish(f.packed); + await stale.admit("stale"); + await f.owner.publish(await edit(f, "first-edited")); + const staged = await edit(f, "stale-edited"); + await failNextLeaseRelease(); + const refused = await stale.publish(staged).catch((cause) => cause); + // The refusal stays the owner's typed outcome, not a wrapped error. + expect(refused).toBeInstanceOf(GhidraCheckpointSupersededError); + expect(refused).toMatchObject({ stage: "save" }); + expect(refused.cleanupFailure?.cause).toMatchObject({ + message: "controlled lease release failure", + }); + expect(stale.hasResources).toBe(true); + await stale.retryCleanup(); + expect(stale.hasResources).toBe(false); + }, +); + +it.skipIf(process.platform === "win32")( + "stops before publishing when the lease wait is aborted while the lease is being acquired", + async () => { + const f = await fixture(); + await f.owner.admit("first"); + await f.owner.publish(f.packed); + const manifest = join(f.selection.directory, "current.json"); + const committed = await readFile(manifest, "utf8"); + const leases = await vi.importActual< + typeof import("../process/OwnedLease.js") + >("../process/OwnedLease.js"); + const forced = new AbortController(); + // The forced stop arrives during the acquisition's own directory work. + vi.mocked(acquireOwnedLease).mockImplementationOnce(async (input) => { + forced.abort(new Error("forced stop")); + return leases.acquireOwnedLease(input); + }); + await expect( + f.owner.publish(await edit(f, "edited"), undefined, forced.signal), + ).rejects.toThrow(); + expect(await readFile(manifest, "utf8")).toBe(committed); + // The acquired lease was released by the publication's cleanup. + expect(f.owner.hasResources).toBe(false); + const peer = peerOf(f); + expect((await peer.admit("peer"))?.sha256).toBe( + f.owner.observation.source?.sha256, + ); + }, +); + +it.skipIf(process.platform === "win32")( + "refuses a save when the manifest it restored was removed", + async () => { + const f = await fixture(); + await f.owner.admit("first"); + await f.owner.publish(f.packed); + await rm(join(f.selection.directory, "current.json")); + await expect( + f.owner.publish(await edit(f, "edited")), + ).rejects.toBeInstanceOf(GhidraCheckpointSupersededError); + await expect( + access(join(f.selection.directory, "current.json")), + ).rejects.toMatchObject({ code: "ENOENT" }); + }, +); + +it.skipIf(process.platform === "win32")( + "waits for another session's publication, then saves or reports contention", + async () => { + const f = await fixture(); + const other = peerOf(f); + await f.owner.admit("first"); + await other.admit("second"); + const actual = + await vi.importActual( + "node:fs/promises", + ); + let release!: () => void; + const held = new Promise((resolve) => (release = resolve)); + let reached!: () => void; + const renaming = new Promise((resolve) => (reached = resolve)); + vi.mocked(rename).mockImplementationOnce(async (...args) => { + reached(); + await held; + await actual.rename(...args); + }); + const publishing = f.owner.publish(f.packed); + await renaming; + // The peer polls the held lease; cancellation ends its wait. + const controller = new AbortController(); + const cancelled = other.publish( + await edit(f, "second-initial"), + controller.signal, + ); + await waitFor(() => + expect(vi.mocked(acquireOwnedLease).mock.calls.length).toBeGreaterThan(2), + ); + controller.abort({ caller: "stopped waiting" }); + await expect(cancelled).rejects.toBeInstanceOf(AnalysisCancelledError); + expect(other.hasResources).toBe(false); + // A second wait ends when the publication does, and adopts its result. + const waiting = other.publish(await edit(f, "second-initial-retry")); + await waitFor(() => + expect(vi.mocked(acquireOwnedLease).mock.calls.length).toBeGreaterThan(5), + ); + release(); + await publishing; + await waiting; + expect(other.observation.source).toEqual(f.owner.observation.source); + expect(await programs(f.selection.directory)).toHaveLength(1); + }, +); + +it.skipIf(process.platform === "win32").each([ + { + kind: "owner_unverified", + reason: "owner closed without a complete response", + }, + { kind: "recovery_busy", path: "/tmp/lease.sock.recovery" }, +] as const)( + "keeps waiting when a lease probe races the owner's release ($kind)", + async (race) => { + const f = await fixture(); + await f.owner.admit("first"); + const leases = await vi.importActual< + typeof import("../process/OwnedLease.js") + >("../process/OwnedLease.js"); + // The owner released while this probe read its identity, or another + // waiter was recovering the released socket: both end within the wait. + vi.mocked(acquireOwnedLease).mockImplementationOnce(async (input) => { + throw input.failure(race); + }); + await f.owner.publish(f.packed); + expect(f.owner.observation.state).toEqual({ kind: "initial-analysis" }); + expect(vi.mocked(acquireOwnedLease)).toHaveBeenCalledTimes(2); + // The same failure still surfaces once the wait is exhausted. + const session = new GhidraCheckpoint( + await resolveGhidraCheckpoint(f.root, target, profile, f.resources), + f.resources, + { waitMs: 50, source: "setting" }, + ); + owners.push(session); + await session.admit("second"); + vi.mocked(acquireOwnedLease).mockImplementation(async (input) => { + throw input.failure(race); + }); + await expect( + session.publish(await edit(f, "edited")), + ).rejects.toMatchObject({ + settings: [ + { + setting: "REA_GHIDRA_CHECKPOINT_DIR", + constraint: expect.stringContaining(`lease ${race.kind}`), + }, + ], + }); + vi.mocked(acquireOwnedLease).mockImplementation(leases.acquireOwnedLease); + }, +); + +it.skipIf(process.platform === "win32")( + "reports a publication lease held for the whole wait as busy and keeps the checkpoint", + async () => { + const f = await fixture(); + await f.owner.admit("first"); + await f.owner.publish(f.packed); + const committed = await readFile( + join(f.selection.directory, "current.json"), + "utf8", + ); + vi.mocked(acquireOwnedLease).mockResolvedValue({ + acquired: false, + owner: { runId: "publisher", processId: 4242 }, + }); + const now = vi.spyOn(performance, "now"); + now.mockReturnValueOnce(0).mockReturnValue(60_000); + const busy = await f.owner + .publish(await edit(f, "edited")) + .catch((cause) => cause); + expect(busy).toBeInstanceOf(GhidraCheckpointBusyError); + expect(busy).toMatchObject({ + owner: { runId: "publisher", processId: 4242 }, + }); + expect(f.owner.hasResources).toBe(false); + expect( + await readFile(join(f.selection.directory, "current.json"), "utf8"), + ).toBe(committed); + now.mockRestore(); + const leases = await vi.importActual< + typeof import("../process/OwnedLease.js") + >("../process/OwnedLease.js"); + vi.mocked(acquireOwnedLease).mockImplementation(leases.acquireOwnedLease); + await f.owner.publish(await edit(f, "edited-retry")); + expect(f.owner.observation.state.kind).toBe("retained"); + }, +); + +it.skipIf(process.platform === "win32").each([ + // Past the 30 s default, a longer launch value keeps polling. + // Each probe reads the clock to bound the owner response and again after + // the refusal. A poll that continues also reads it once the delay returns. + { + waitMs: 120_000, + clock: [0, 0, 60_000, 60_000, 60_000, 119_999, 119_999, 119_999, 120_000], + attempts: 3, + }, + // A shorter launch value reports busy where the default would still wait. + { waitMs: 50, clock: [0, 0, 50], attempts: 1 }, + // Unset: the default bound. + { + waitMs: undefined, + clock: [0, 0, 29_999, 29_999, 29_999, 30_000], + attempts: 2, + }, +])( + "holds a held lease for a save wait of $waitMs ms and names that bound when busy", + async ({ waitMs, clock, attempts }) => { + const f = await fixture(); + const wait = + waitMs === undefined + ? undefined + : ({ waitMs, source: "setting" } as const); + const session = new GhidraCheckpoint(f.selection, f.resources, wait); + owners.push(session); + await session.admit("waiting"); + vi.mocked(acquireOwnedLease) + .mockClear() + .mockResolvedValue({ + acquired: false, + owner: { runId: "publisher", processId: 4242 }, + }); + // The deadline reads the clock to start, then once to bound each owner + // probe, once after each refusal, and once when a poll delay returns. + const now = vi.spyOn(performance, "now"); + for (const reading of clock.slice(0, -1)) now.mockReturnValueOnce(reading); + now.mockReturnValue(clock.at(-1) ?? 0); + const busy = await session.publish(f.packed).catch((cause) => cause); + now.mockRestore(); + expect(busy).toBeInstanceOf(GhidraCheckpointBusyError); + expect(vi.mocked(acquireOwnedLease)).toHaveBeenCalledTimes(attempts); + expect(busy.wait).toEqual(wait ?? { waitMs: 30_000, source: "default" }); + expect(busy.message).toContain( + `REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS is ${String(waitMs ?? 30_000)} ms (source ${waitMs === undefined ? "default" : "launch environment"}; default 30000, floor 50, maximum 600000)`, + ); + expect(session.hasResources).toBe(false); + }, +); + +it.skipIf(process.platform === "win32").each(["manifest", "packed"] as const)( + "re-reads a checkpoint replaced while a lease-free reader had its %s open", + async (stage) => { + const f = await fixture(); + await f.owner.admit("writer"); + await f.owner.publish(f.packed); + await f.owner.publish(await edit(f, "first-edit")); + const superseded = f.owner.observation.source!; + const next = await edit(f, "second-edit"); + let interleaved = false; + controls.file = (handle, path) => { + if ( + interleaved || + !path.endsWith(stage === "manifest" ? "current.json" : superseded.file) + ) + return; + interleaved = true; + // A whole publication runs between the reader's admission of the + // superseded file and its first read of it. + const read = handle.read.bind(handle); + vi.spyOn(handle, "read").mockImplementationOnce( + async (...args: Parameters) => { + await f.owner.publish(next); + return read(...args); + }, + ); + }; + const selection = await resolveGhidraCheckpoint( + f.root, + target, + profile, + f.resources, + ); + controls.file = undefined; + expect(interleaved).toBe(true); + expect(f.owner.observation.source!.file).not.toBe(superseded.file); + expect(selection.state).toEqual({ + kind: "retained", + sha256: f.owner.observation.source!.sha256, + }); + expect(f.resources.hasPending).toBe(false); + }, +); + +it.skipIf(process.platform === "win32")( + "explains a restore whose packed file was superseded after admission", + async () => { + const f = await fixture(); + await f.owner.admit("writer"); + await f.owner.publish(f.packed); + const reader = peerOf(f); + const restored = await reader.admit("reader"); + expect(await reader.supersededRestore()).toBeUndefined(); + await f.owner.publish(await edit(f, "edited")); + await expect(access(restored!.path)).rejects.toMatchObject({ + code: "ENOENT", + }); + const superseded = await reader.supersededRestore(); + expect(superseded).toBeInstanceOf(GhidraCheckpointSupersededError); + expect(superseded).toMatchObject({ stage: "restore" }); + }, +); + it.skipIf(process.platform === "win32")( "refuses state changed after profile resolution without replacing the current manifest", async () => { const f = await fixture(); - await f.owner.acquire("first"); + await f.owner.admit("first"); await f.owner.publish(f.packed); - const edited = join(f.root, "edited.gzf"); - await writeFile(edited, "edited checkpoint"); - await f.owner.publish(edited); - await f.owner.close(); - const stale = new GhidraCheckpoint(f.selection, f.resources); - owners.push(stale); + await f.owner.publish(await edit(f, "edited")); + await f.owner.retryCleanup(); + const stale = peerOf(f); const bytes = await readFile( join(f.selection.directory, "current.json"), "utf8", ); - await expect(stale.acquire("stale")).rejects.toBeInstanceOf( - GhidraCheckpointSupersededError, - ); + const refused = await stale.admit("stale").catch((cause) => cause); + expect(refused).toBeInstanceOf(GhidraCheckpointSupersededError); + expect(refused).toMatchObject({ stage: "restore" }); await expect(stale.publish(f.packed)).rejects.toThrow( - /no admitted session lease/, + /no admitted session/, ); expect( await readFile(join(f.selection.directory, "current.json"), "utf8"), @@ -268,9 +693,9 @@ it.skipIf(process.platform === "win32")( "rejects an unknown manifest version without rewriting it", async () => { const f = await fixture(); - await f.owner.acquire("initial"); + await f.owner.admit("initial"); await f.owner.publish(f.packed); - await f.owner.close(); + await f.owner.retryCleanup(); const path = join(f.selection.directory, "current.json"); const record = JSON.parse(await readFile(path, "utf8")); const unknown = JSON.stringify({ ...record, version: 1 }); @@ -286,9 +711,9 @@ it.skipIf(process.platform === "win32")( "rejects corruption, malformed manifests, and traversal rather than silently importing fresh", async () => { const f = await fixture(); - await f.owner.acquire("first"); + await f.owner.admit("first"); await f.owner.publish(f.packed); - await f.owner.close(); + await f.owner.retryCleanup(); const manifestPath = join(f.selection.directory, "current.json"); const manifest = JSON.parse(await readFile(manifestPath, "utf8")); await writeFile( @@ -319,7 +744,7 @@ it.skipIf(process.platform === "win32")( "keeps the prior checkpoint after a failed publication and succeeds on retry", async () => { const f = await fixture("previous packed bytes"); - await f.owner.acquire("first"); + await f.owner.admit("first"); await f.owner.publish(f.packed); const directory = f.selection.directory; const previous = f.owner.observation.source!; @@ -358,7 +783,7 @@ it.skipIf(process.platform === "win32")( "retains publication and its old-file cleanup when cleanup fails, then retries without saving twice", async () => { const f = await fixture(); - await f.owner.acquire("first"); + await f.owner.admit("first"); await f.owner.publish(f.packed); const old = f.owner.observation.source!; const next = join(f.root, "next.gzf"); @@ -382,17 +807,94 @@ it.skipIf(process.platform === "win32")( "utf8", ); expect(f.owner.hasResources).toBe(true); - await expect(f.owner.close()).rejects.toMatchObject({ + await expect(f.owner.retryCleanup()).rejects.toMatchObject({ cause: expect.objectContaining({ message: "controlled cleanup failure", }), }); + // The retained file is not a publication: the lease is released, so + // another session's save does not wait on this cleanup. + expect(f.owner.cleanupResources).toEqual([ + join(f.selection.directory, old.file), + ]); + const peer = new GhidraCheckpoint( + await resolveGhidraCheckpoint(f.root, target, profile, f.resources), + f.resources, + { waitMs: 50, source: "setting" }, + ); + owners.push(peer); + await peer.admit("peer"); + vi.mocked(acquireOwnedLease).mockClear(); + await peer.publish(await edit(f, "peer-edited")); + expect(vi.mocked(acquireOwnedLease)).toHaveBeenCalledTimes(1); + const peerManifest = await readFile( + join(f.selection.directory, "current.json"), + "utf8", + ); + expect(peerManifest).not.toEqual(committed); vi.mocked(rm).mockImplementation(actual.rm); + // The owner's retry finishes its cleanup without saving `next` again. await f.owner.publish(next); expect( await readFile(join(f.selection.directory, "current.json"), "utf8"), - ).toEqual(committed); - await f.owner.close(); + ).toEqual(peerManifest); + await f.owner.retryCleanup(); + expect(f.owner.hasResources).toBe(false); + }, +); + +it.skipIf(process.platform === "win32")( + "reports both a failed old-file removal and a failed lease release, keeping both owned", + async () => { + const f = await fixture(); + await f.owner.admit("first"); + await f.owner.publish(f.packed); + const old = join(f.selection.directory, f.owner.observation.source!.file); + const next = join(f.root, "next.gzf"); + await writeFile(next, "changed"); + const leases = await vi.importActual< + typeof import("../process/OwnedLease.js") + >("../process/OwnedLease.js"); + vi.mocked(acquireOwnedLease).mockImplementationOnce(async (input) => { + const result = await leases.acquireOwnedLease(input); + if (!result.acquired) return result; + let failed = false; + return { + acquired: true, + lease: { + ...result.lease, + release: async () => { + if (!failed) { + failed = true; + throw new Error("controlled lease release failure"); + } + await result.lease.release(); + }, + }, + }; + }); + const files = + await vi.importActual( + "node:fs/promises", + ); + vi.mocked(rm).mockImplementation(async (path, options) => { + if (path === old) throw new Error("controlled removal failure"); + await files.rm(path, options); + }); + const failure = await f.owner.publish(next).then( + () => undefined, + (cause: unknown) => cause, + ); + expect(failure).toBeInstanceOf(ProviderCleanupError); + const cleanup = failure as ProviderCleanupError; + expect(cleanup.diagnostics?.reason).toMatch( + /controlled removal failure.*controlled lease release failure/, + ); + expect(cleanup.cleanupResources).toContain(old); + expect(cleanup.cleanupResources).toHaveLength(2); + expect(f.owner.hasResources).toBe(true); + vi.mocked(rm).mockImplementation(files.rm); + await f.owner.retryCleanup(); expect(f.owner.hasResources).toBe(false); }, ); @@ -401,7 +903,7 @@ it.skipIf(process.platform === "win32")( "preserves a published checkpoint when cancellation is observed after the manifest commit", async () => { const f = await fixture(); - await f.owner.acquire("first"); + await f.owner.admit("first"); const controller = new AbortController(); const actual = await vi.importActual( @@ -428,7 +930,7 @@ it.skipIf(process.platform === "win32")( const f = await fixture(); await mkdir(f.selection.directory, { mode: 0o755 }); await chmod(f.selection.directory, 0o755); - await expect(f.owner.acquire("first")).rejects.toThrow(/private directory/); + await expect(f.owner.admit("first")).rejects.toThrow(/private directory/); }, ); @@ -444,7 +946,7 @@ it.skipIf(process.platform === "win32")( ); const owner = new GhidraCheckpoint(selection, f.resources); owners.push(owner); - expect(await owner.acquire("long-directory")).toBeUndefined(); + expect(await owner.admit("long-directory")).toBeUndefined(); }, ); @@ -464,7 +966,7 @@ it.skipIf(process.platform === "win32")( expect(selection.directory.startsWith(selected)).toBe(true); const owner = new GhidraCheckpoint(selection, f.resources); owners.push(owner); - await owner.acquire("selected"); + await owner.admit("selected"); await owner.publish(f.packed); await access( join(f.root, "physical", "selected", selection.key, "current.json"), @@ -480,12 +982,241 @@ it.skipIf(process.platform === "win32")( ); const peer = new GhidraCheckpoint(alias, f.resources); owners.push(peer); - await expect(peer.acquire("physical")).rejects.toThrow( - /another REA session/, - ); - await owner.close(); - expect((await peer.acquire("physical"))?.sha256).toBe( + expect((await peer.admit("physical"))?.sha256).toBe( owner.observation.source?.sha256, ); + // Both spellings publish under one lease identity: the physical directory. + const identities: unknown[] = []; + const leases = await vi.importActual< + typeof import("../process/OwnedLease.js") + >("../process/OwnedLease.js"); + vi.mocked(acquireOwnedLease).mockImplementation((input) => { + identities.push(input.identity); + return leases.acquireOwnedLease(input); + }); + const selectedEdit = join(f.root, "selected-edit.gzf"); + await writeFile(selectedEdit, "selected edit"); + await owner.publish(selectedEdit); + const physicalEdit = join(f.root, "physical-edit.gzf"); + await writeFile(physicalEdit, "physical edit"); + await expect(peer.publish(physicalEdit)).rejects.toBeInstanceOf( + GhidraCheckpointSupersededError, + ); + expect(identities).toHaveLength(2); + expect(identities[1]).toEqual(identities[0]); + }, +); + +/** A peer that accepts the lease socket and never sends its identity. */ +const silentLeaseHolder = async ( + directory: string, +): Promise<() => Promise> => { + const canonical = await realpath(directory); + const key = sha256Hex( + JSON.stringify({ + kind: "ghidra-checkpoint-v1", + directory: canonical, + }), + ).slice(0, 32); + const leaseDirectory = join( + "/tmp", + `rea-ghidra-checkpoint-leases-${process.getuid?.() ?? "user"}`, + ); + await mkdir(leaseDirectory, { recursive: true, mode: 0o700 }); + const socketPath = join(leaseDirectory, `${key}.sock`); + await rm(socketPath, { force: true }); + const server = createServer((socket) => { + socket.resume(); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(socketPath, () => resolve()); + }); + return () => + new Promise((resolve) => { + server.close(() => resolve()); + }); +}; + +it.skipIf(process.platform === "win32")( + "reports a save wait that ends during an unanswered owner probe as busy", + async () => { + const f = await fixture(); + const session = new GhidraCheckpoint(f.selection, f.resources, { + waitMs: 50, + source: "setting", + }); + owners.push(session); + await session.admit("waiter"); + const release = await silentLeaseHolder(f.selection.directory); + onTestFinished(release); + const started = performance.now(); + const busy = await session + .publish(f.packed) + .catch((cause: unknown) => cause); + expect(performance.now() - started).toBeLessThan(220); + expect(busy).toBeInstanceOf(GhidraCheckpointBusyError); + expect(busy).toMatchObject({ + owner: undefined, + wait: { waitMs: 50, source: "setting" }, + }); + }, +); + +it.skipIf(process.platform === "win32")( + "stops an unanswered owner probe when the save is cancelled", + async () => { + const f = await fixture(); + const session = new GhidraCheckpoint(f.selection, f.resources); + owners.push(session); + await session.admit("waiter"); + const release = await silentLeaseHolder(f.selection.directory); + onTestFinished(release); + const controller = new AbortController(); + const started = performance.now(); + const pending = session.publish(f.packed, controller.signal); + setTimeout(() => controller.abort({ caller: "stop the probe" }), 30); + await expect(pending).rejects.toBeInstanceOf(AnalysisCancelledError); + expect(performance.now() - started).toBeLessThan(220); + }, +); + +it.skipIf(process.platform === "win32")( + "keeps a directory-close failure when cancellation arrives during lease acquisition", + async () => { + const f = await fixture(); + const session = new GhidraCheckpoint(f.selection, f.resources, { + waitMs: 50, + source: "setting", + }); + owners.push(session); + await session.admit("waiter"); + const controller = new AbortController(); + vi.mocked(acquireOwnedLease).mockImplementation(async (input) => { + controller.abort({ caller: "close failed" }); + throw input.failure( + { kind: "directory_close" }, + new Error("directory handle close failed"), + ); + }); + const rejected = await session + .publish(f.packed, controller.signal) + .catch((cause: unknown) => cause); + expect(rejected).toMatchObject({ + settings: [ + { + setting: "REA_GHIDRA_CHECKPOINT_DIR", + constraint: expect.stringContaining("lease directory_close"), + }, + ], + secondaryFailures: [{ cause: { caller: "close failed" } }], + }); + }, +); + +it.skipIf(process.platform === "win32")( + "reports busy when the lease frees only after the save wait", + async () => { + const f = await fixture(); + const session = new GhidraCheckpoint(f.selection, f.resources, { + waitMs: 50, + source: "setting", + }); + owners.push(session); + await session.admit("waiter"); + vi.mocked(acquireOwnedLease).mockImplementation(async () => + vi.mocked(acquireOwnedLease).mock.calls.length === 1 + ? { + acquired: false, + owner: { runId: "publisher", processId: 7 }, + } + : { + acquired: true, + lease: { release: async () => undefined }, + }, + ); + const now = vi.spyOn(performance, "now"); + now + .mockReturnValueOnce(0) + .mockReturnValueOnce(0) + .mockReturnValueOnce(40) + .mockReturnValue(50); + const busy = await session + .publish(f.packed) + .catch((cause: unknown) => cause); + now.mockRestore(); + expect(busy).toBeInstanceOf(GhidraCheckpointBusyError); + expect(busy).toMatchObject({ + owner: { runId: "publisher", processId: 7 }, + wait: { waitMs: 50, source: "setting" }, + }); + expect(vi.mocked(acquireOwnedLease)).toHaveBeenCalledTimes(1); + expect(session.observation.source).toBeNull(); + }, +); + +it.skipIf(process.platform === "win32")( + "reports a handoff when the lease frees only after the save wait", + async () => { + const f = await fixture(); + const session = new GhidraCheckpoint(f.selection, f.resources, { + waitMs: 50, + source: "setting", + }); + owners.push(session); + await session.admit("waiter"); + vi.mocked(acquireOwnedLease).mockImplementation(async (input) => { + if (vi.mocked(acquireOwnedLease).mock.calls.length === 1) + throw input.failure({ + kind: "owner_unverified", + reason: "owner closed without a complete response", + }); + return { acquired: true, lease: { release: async () => undefined } }; + }); + const now = vi.spyOn(performance, "now"); + now + .mockReturnValueOnce(0) + .mockReturnValueOnce(0) + .mockReturnValueOnce(40) + .mockReturnValue(50); + const rejected = await session + .publish(f.packed) + .catch((cause: unknown) => cause); + now.mockRestore(); + expect(rejected).toMatchObject({ + settings: [ + { + setting: "REA_GHIDRA_CHECKPOINT_DIR", + constraint: expect.stringContaining("lease owner_unverified"), + }, + ], + }); + expect(vi.mocked(acquireOwnedLease)).toHaveBeenCalledTimes(1); + expect(session.observation.source).toBeNull(); + }, +); + +it.skipIf(process.platform === "win32")( + "publishes when the first uncontended acquire finishes after the save wait", + async () => { + const f = await fixture(); + const session = new GhidraCheckpoint(f.selection, f.resources, { + waitMs: 50, + source: "setting", + }); + owners.push(session); + await session.admit("writer"); + vi.mocked(acquireOwnedLease).mockImplementation(async () => ({ + acquired: true, + lease: { release: async () => undefined }, + })); + const now = vi.spyOn(performance, "now"); + now.mockReturnValueOnce(0).mockReturnValueOnce(0).mockReturnValue(50); + await session.publish(f.packed); + now.mockRestore(); + expect(session.observation.source).toMatchObject({ + kind: "initial-analysis", + }); + expect(vi.mocked(acquireOwnedLease)).toHaveBeenCalledTimes(1); }, ); diff --git a/src/ghidra/GhidraCheckpoint.ts b/src/ghidra/GhidraCheckpoint.ts index 8a3049e6358..18f111873c0 100644 --- a/src/ghidra/GhidraCheckpoint.ts +++ b/src/ghidra/GhidraCheckpoint.ts @@ -1,11 +1,16 @@ import { appendCallerPath } from "../filesystem/callerPath.js"; +import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; +import { cancelledBy, isAborted } from "../domain/analysisErrorCore.js"; import { classifyProviderFailure } from "../providers/classifyProviderFailure.js"; import { createHash, randomUUID } from "node:crypto"; import { lstat, mkdir, open, realpath, rename, rm } from "node:fs/promises"; import { join } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; import { z } from "zod"; import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js"; +import { AnalysisError } from "../domain/analysisErrorBase.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; +import { Deadline } from "../domain/deadline.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { AnalysisCleanupRelease } from "../domain/analysisCleanupRelease.js"; import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; @@ -21,7 +26,20 @@ import { sameRegularFileState, RegularFileChangedError, } from "../filesystem/RegularFile.js"; -import { acquireOwnedLease, type OwnedLease } from "../process/OwnedLease.js"; +import { + acquireOwnedLease, + LEASE_OWNER_PROBE_ABORTED, + LEASE_OWNER_RESPONSE_TIMEOUT_MS, + LEASE_OWNER_RESPONSE_TIMED_OUT, + type LeaseAcquisition, + type OwnedLease, +} from "../process/OwnedLease.js"; +import { + DEFAULT_GHIDRA_CHECKPOINT_SAVE_WAIT, + GHIDRA_CHECKPOINT_SAVE_POLL_MS, + ghidraCheckpointSaveWaitFacts, + type GhidraCheckpointSaveWait, +} from "../config/ghidraCheckpointSaveWait.js"; import { copyGhidraRegularFile, ghidraFileDialect, @@ -92,33 +110,58 @@ const failure = (directory: string, reason: string, cause?: unknown) => ); /** - * Another live REA session holds this checkpoint's lease. The directory and - * its setting are valid, so this is contention that ends when that session - * closes the target, not a configuration fault. + * Another live REA session held this checkpoint's publication lease for the + * whole bounded wait. The directory and its setting are valid, so this is + * contention that ends when that publication finishes, not a configuration + * fault. `wait` is the bound this session applied. */ export class GhidraCheckpointBusyError extends Error { + /** Cleanup that also failed after the refusal; the refusal stays primary. */ + cleanupFailure: AnalysisError | undefined; constructor( readonly directory: string, - readonly owner: { readonly runId: string; readonly processId: number }, + readonly owner: + | { readonly runId: string; readonly processId: number } + | undefined, + readonly wait: GhidraCheckpointSaveWait, ) { + const holder = + owner === undefined + ? "another REA session" + : `another REA session (run ${owner.runId}, process ${String(owner.processId)})`; super( - `Ghidra checkpoint at ${JSON.stringify(directory)} is in use by another REA session (run ${owner.runId}, process ${String(owner.processId)})`, + `Ghidra checkpoint at ${JSON.stringify(directory)} is being saved by ${holder}, and that save did not finish within this session's save wait: ${ghidraCheckpointSaveWaitFacts(wait)}`, ); this.name = "GhidraCheckpointBusyError"; } } /** - * The checkpoint no longer holds the generation this session selected, - * normally because another session saved Program edits while this one - * waited. The current checkpoint is intact; reopening selects it. + * The checkpoint no longer holds the generation this session selected or + * restored. Nothing was published and the current checkpoint is unchanged: + * a restore must reopen the target, and a save was refused instead of + * overwriting the newer generation. */ export class GhidraCheckpointSupersededError extends Error { - constructor(readonly directory: string) { + /** Cleanup that also failed after the refusal; the refusal stays primary. */ + cleanupFailure: AnalysisError | undefined; + /** + * Whether the session holds Program edits this refusal kept from being + * saved. Only a save refuses edits: a restore, including a session whose + * initial analysis was overtaken, has none and simply reopens. + */ + readonly refusesEdits: boolean; + constructor( + readonly directory: string, + readonly stage: "restore" | "save", + ) { super( - `Ghidra checkpoint at ${JSON.stringify(directory)} changed after this session selected it, normally because another REA session saved Program edits; reopen the target to restore the current checkpoint`, + stage === "restore" + ? `Ghidra checkpoint at ${JSON.stringify(directory)} changed after this session selected it, normally because another REA session saved Program edits; reopen the target to restore the current checkpoint` + : `Ghidra checkpoint at ${JSON.stringify(directory)} changed after this session restored it, normally because another REA session saved Program edits first; this session's Program edits were not saved and the current checkpoint is unchanged. Closing the target again discards them; reopen the target and reapply them to the current checkpoint`, ); this.name = "GhidraCheckpointSupersededError"; + this.refusesEdits = stage === "save"; } } @@ -153,11 +196,13 @@ export const hashGhidraPackedProgram = ( }, ); -async function readSource( - selection: Omit, +type CheckpointSelectionKey = Omit; + +async function readManifest( + selection: CheckpointSelectionKey, resources: ArtifactResourceScope, signal?: AbortSignal, -) { +): Promise { let manifest: z.infer; try { manifest = await readGhidraProfileArtifact( @@ -188,7 +233,17 @@ async function readSource( selection.directory, "the manifest belongs to a different target or analysis profile", ); - const path = appendCallerPath(selection.directory, manifest.source.file); + return manifest.source; +} + +async function readVerifiedSource( + selection: CheckpointSelectionKey, + resources: ArtifactResourceScope, + signal?: AbortSignal, +): Promise { + const source = await readManifest(selection, resources, signal); + if (source === null) return null; + const path = appendCallerPath(selection.directory, source.file); let actual: string; try { actual = await hashGhidraPackedProgram(path, resources, signal); @@ -198,14 +253,61 @@ async function readSource( ghidraFileDialect("resolve_analysis_profile", { path }), ); } - if (actual !== manifest.source.sha256) + if (actual !== source.sha256) throw failure( selection.directory, "the packed Program checksum differs from its manifest", ); - return manifest.source; + return source; } +/** A publication renames a new manifest file into place, so its identity changes. */ +const manifestIdentity = async (directory: string): Promise => { + try { + const state = await lstat(appendCallerPath(directory, "current.json"), { + bigint: true, + }); + return `${String(state.dev)}:${String(state.ino)}`; + } catch { + return null; + } +}; + +/** + * Readers hold no lease. A publication replaces the manifest and then removes + * the packed file it superseded, so a read that straddles one can find the + * replaced manifest or the removed file. Only a read during which the manifest + * was replaced is repeated; any other failure is reported as it is. + */ +async function readSource( + selection: CheckpointSelectionKey, + resources: ArtifactResourceScope, + signal?: AbortSignal, +): Promise { + for (let attempt = 0; ; attempt += 1) { + const before = await manifestIdentity(selection.directory); + try { + return await readVerifiedSource(selection, resources, signal); + } catch (cause: unknown) { + if ( + attempt === 2 || + signal?.aborted === true || + resources.hasPending || + (await manifestIdentity(selection.directory)) === before + ) + throw cause; + } + } +} + +const sameSource = ( + left: CheckpointSource | null, + right: CheckpointSource | null, +): boolean => + left === null || right === null + ? left === right + : left.file === right.file && left.sha256 === right.sha256; + /** Resolve storage and content identity once for the shared CLI/MCP analysis profile. */ export async function resolveGhidraCheckpoint( root: string, @@ -227,9 +329,20 @@ export async function resolveGhidraCheckpoint( }; } -/** One session owns publication, the socket lease, and any failed staging cleanup. */ +/** + * One session's view of a shared checkpoint. Sessions restore the packed + * Program into private projects without a lease; the socket lease is held only + * while one of them publishes. Publication is a compare-and-set on the source + * this session started from, so a session never overwrites a generation it did + * not restore. The session owns its lease and any failed staging cleanup. + */ export class GhidraCheckpoint { #lease: OwnedLease | undefined; + /** Physical directory and lease owner of the admitted session. */ + #admission: + | { readonly directory: string; readonly runId: string } + | undefined; + /** The source this session's Program derives from; null before any publication. */ #source: CheckpointSource | null | undefined; #state: GhidraCheckpointSelection["state"]; readonly #pendingRemoval = new Set(); @@ -239,6 +352,8 @@ export class GhidraCheckpoint { constructor( readonly selection: GhidraCheckpointSelection, private readonly resources: ArtifactResourceScope, + /** Bound on waiting for another session's publication, fixed for this session. */ + private readonly saveWait: GhidraCheckpointSaveWait = DEFAULT_GHIDRA_CHECKPOINT_SAVE_WAIT, ) { this.#state = selection.state; } @@ -263,7 +378,8 @@ export class GhidraCheckpoint { }; } - async acquire( + /** Verify the selected generation and return its packed Program, if one exists. */ + async admit( runId: string, signal?: AbortSignal, ): Promise { @@ -280,24 +396,7 @@ export class GhidraCheckpoint { "the checkpoint directory must be a private directory owned by this user", ); const directory = await realpath(this.selection.directory); - const acquired = await acquireOwnedLease({ - identity: { kind: "ghidra-checkpoint-v1", directory }, - runId, - directory: join( - "/tmp", - `rea-ghidra-checkpoint-leases-${process.getuid?.() ?? "user"}`, - ), - resources: this.resources, - failure: (reason, cause) => - failure( - directory, - `lease ${reason.kind}${cause instanceof Error ? `: ${cause.message}` : ""}`, - cause, - ), - }); - if (!acquired.acquired) - throw new GhidraCheckpointBusyError(directory, acquired.owner); - this.#lease = acquired.lease; + this.#admission = undefined; this.#source = undefined; const current = await readSource(this.selection, this.resources, signal); const generation = checkpointState(current); @@ -306,78 +405,243 @@ export class GhidraCheckpoint { ? this.#state.kind === "initial-analysis" : this.#state.kind === "retained" && this.#state.sha256 === generation.sha256; - if (!aligned) throw new GhidraCheckpointSupersededError(directory); + if (!aligned) + throw new GhidraCheckpointSupersededError(directory, "restore"); assertArtifactReadActive(signal); + this.#admission = { directory, runId }; this.#source = current; return current === null ? undefined : { path: join(directory, current.file), sha256: current.sha256 }; } - /** Publish a new immutable blob, then atomically replace its manifest. */ - async publish(path: string, signal?: AbortSignal): Promise { - if (this.#lease === undefined || this.#source === undefined) + /** + * Explain a failed private restore: a publication after admission removes + * the packed file this session was about to copy. + */ + async supersededRestore( + signal?: AbortSignal, + ): Promise { + if (this.#admission === undefined || this.#source === undefined) + return undefined; + const current = await readManifest(this.selection, this.resources, signal); + return sameSource(current, this.#source) + ? undefined + : new GhidraCheckpointSupersededError( + this.#admission.directory, + "restore", + ); + } + + /** Wait a bounded time for another session's publication to finish. */ + async #acquireLease( + admission: { readonly directory: string; readonly runId: string }, + signal?: AbortSignal, + ): Promise { + const deadline = Deadline.after(this.saveWait.waitMs); + // An owner that releases while a probe reads its identity, or another + // waiter recovering the released socket, ends within the wait; any other + // lease failure, or one that outlasts the wait, is reported unchanged. + // The owner-identity probe itself stops at the remaining wait or when + // this save is cancelled. A probe cut off by that wait is the busy + // refusal: the socket was accepted and no identity arrived in time. + const handoff = new WeakSet(); + const probeTimedOut = new WeakSet(); + const probeAborted = new WeakSet(); + let heldBy: + | { readonly runId: string; readonly processId: number } + | undefined; + // A handoff that is still inside the wait. If the wait ends before the + // next probe, or that probe acquires only after the wait, this failure + // is the result: publication does not start. + let handoffFailure: Error | undefined; + for (;;) { + assertArtifactReadActive(signal); + let acquired: LeaseAcquisition | undefined; + try { + acquired = await acquireOwnedLease({ + identity: { + kind: "ghidra-checkpoint-v1", + directory: admission.directory, + }, + runId: admission.runId, + directory: join( + "/tmp", + `rea-ghidra-checkpoint-leases-${process.getuid?.() ?? "user"}`, + ), + resources: this.resources, + probe: { + ...(signal === undefined ? {} : { signal }), + timeoutMs: Math.min( + LEASE_OWNER_RESPONSE_TIMEOUT_MS, + deadline.remainingMs(), + ), + }, + failure: (reason, cause) => { + const error = failure( + admission.directory, + `lease ${reason.kind}${cause instanceof Error ? `: ${cause.message}` : ""}`, + cause, + ); + if ( + reason.kind === "owner_unverified" || + reason.kind === "recovery_busy" + ) + handoff.add(error); + if ( + reason.kind === "owner_unverified" && + reason.reason === LEASE_OWNER_RESPONSE_TIMED_OUT + ) + probeTimedOut.add(error); + if ( + reason.kind === "owner_unverified" && + reason.reason === LEASE_OWNER_PROBE_ABORTED + ) + probeAborted.add(error); + return error; + }, + }); + } catch (cause: unknown) { + // A probe this wait aborted has no cleanup of its own. Any other + // acquisition failure, including a directory handle whose close + // failed, stays primary and keeps the cancellation beside it. + if ( + isAborted(signal) && + !(cause instanceof Error && probeAborted.has(cause)) && + cause instanceof AnalysisError + ) + throw analysisErrorWithCancellation( + cause, + cancelledBy("checkpoint_program", signal), + ); + if (isAborted(signal)) assertArtifactReadActive(signal); + if ( + cause instanceof Error && + probeTimedOut.has(cause) && + deadline.expired() + ) + throw new GhidraCheckpointBusyError( + admission.directory, + undefined, + this.saveWait, + ); + if ( + !(cause instanceof Error && handoff.has(cause)) || + deadline.expired() + ) + throw cause; + handoffFailure = cause; + } + if (acquired?.acquired === true) { + // The wait bounds contention already observed: a holder, or a + // handoff that has not settled. An uncontended acquire that + // finishes late is this session's own overhead, so publication + // still proceeds. A late acquire after contention keeps the lease + // for cleanup and does not publish. + if (deadline.expired() && heldBy !== undefined) { + this.#lease = acquired.lease; + throw new GhidraCheckpointBusyError( + admission.directory, + heldBy, + this.saveWait, + ); + } + if (deadline.expired() && handoffFailure !== undefined) { + this.#lease = acquired.lease; + throw handoffFailure; + } + return acquired.lease; + } + const sawHolder = acquired !== undefined; + if (acquired !== undefined) { + heldBy = acquired.owner; + if (deadline.expired()) + throw new GhidraCheckpointBusyError( + admission.directory, + acquired.owner, + this.saveWait, + ); + } + await delay(GHIDRA_CHECKPOINT_SAVE_POLL_MS, undefined, { signal }).catch( + () => undefined, + ); + // The poll callback can run after the wait when the event loop stalls. + // Contention already observed for this poll used the whole wait, so + // do not probe again. A holder becomes the busy refusal. A handoff + // that outlasts the wait is reported unchanged. + assertArtifactReadActive(signal); + if (!deadline.expired()) continue; + if (sawHolder) + throw new GhidraCheckpointBusyError( + admission.directory, + heldBy, + this.saveWait, + ); + if (handoffFailure !== undefined) throw handoffFailure; + } + } + + /** + * Publish a new immutable blob, then atomically replace its manifest, only + * while the checkpoint still holds the source this session started from. + * Two sessions that both analyzed a target without a checkpoint hold the + * same initial generation, so the later one adopts the published Program + * instead of publishing a second copy. + */ + /** + * `leaseSignal` ends only the wait for another session's publication, which + * is this save's cancellation cutoff; once the lease is held, publication + * observes `signal` alone, so a close's save completes the bounded copy. + */ + async publish( + path: string, + signal?: AbortSignal, + leaseSignal: AbortSignal | undefined = signal, + ): Promise { + const admission = this.#admission; + if (admission === undefined || this.#source === undefined) throw failure( this.selection.directory, - "publication has no admitted session lease", + "publication has no admitted session", ); const previous = this.#source; await this.retryCleanup(); if (this.#publishedInput === path) return; - const file = `program-${randomUUID()}.gzf`; - const destination = appendCallerPath(this.selection.directory, file); - const temporary = appendCallerPath( - this.selection.directory, - `.current-${randomUUID()}.json`, - ); - this.#pendingRemoval.add(destination); - this.#pendingRemoval.add(temporary); + const classify = (cause: unknown) => + classifyProviderFailure( + cause, + ghidraFileDialect("checkpoint_program", { + path: this.selection.directory, + }), + ); let primary: unknown; let failed = false; try { - assertArtifactReadActive(signal); - const hash = createHash("sha256"); - await copyGhidraRegularFile(path, destination, this.resources, { - signal, - hash, - sync: true, - }); - const sha256 = hash.digest("hex"); - const source: CheckpointSource = { - file, - sha256, - kind: previous === null ? "initial-analysis" : "retained", - }; - const metadata = JSON.stringify({ - version: 2, - target_sha256: this.selection.target_sha256, - base_profile_digest: this.selection.base_profile_digest, - source, - }); - const handle = await open(temporary, "wx", 0o600); - await withArtifactFileHandle( - temporary, - handle, + this.#lease = await this.#acquireLease(admission, leaseSignal); + // Acquiring the lease is the cancellation cutoff: an abort that arrived + // during acquisition stops before publication, and the cleanup below + // releases the lease. Once past here the bounded publication completes. + assertArtifactReadActive(leaseSignal); + const current = await readManifest( + this.selection, this.resources, signal, - async (handle) => { - await handle.writeFile(metadata); - await handle.sync(); - }, ); - assertArtifactReadActive(signal); - await rename( - temporary, - appendCallerPath(this.selection.directory, "current.json"), - ); - this.#source = source; - this.#state = checkpointState(source); - this.#publishedInput = path; - this.#pendingRemoval.delete(destination); - this.#pendingRemoval.delete(temporary); - if (previous !== null) - this.#pendingRemoval.add( - appendCallerPath(this.selection.directory, previous.file), + if ( + previous === null && + current !== null && + current.kind === "initial-analysis" + ) { + this.#source = current; + this.#publishedInput = path; + } else if (sameSource(current, previous)) + await this.#replace(path, previous, signal); + // A session that never published holds only its initial analysis and no + // edits, so it is a superseded selection that a reopen restores. + else + throw new GhidraCheckpointSupersededError( + admission.directory, + previous === null ? "restore" : "save", ); } catch (cause: unknown) { primary = cause; @@ -386,57 +650,136 @@ export class GhidraCheckpoint { try { await this.retryCleanup(); } catch (cause: unknown) { - if (failed) - throw analysisErrorWithCleanupFailure( - classifyProviderFailure( - primary, - ghidraFileDialect("checkpoint_program", { - path: this.selection.directory, - }), - ), - classifyProviderFailure( - cause, - ghidraFileDialect("checkpoint_program", { - path: this.selection.directory, - }), - ), - ); - throw cause; + if (!failed) throw cause; + // A refusal is the owner's typed outcome: keep it primary, unwrapped, + // so its consumers still read it, and carry the cleanup failure on it. + if ( + primary instanceof GhidraCheckpointSupersededError || + primary instanceof GhidraCheckpointBusyError + ) { + primary.cleanupFailure ??= classify(cause); + throw primary; + } + throw analysisErrorWithCleanupFailure(classify(primary), classify(cause)); } if (failed) - throw classifyProviderFailure( - primary, - ghidraFileDialect("checkpoint_program", { - path: this.selection.directory, - }), - ); + throw primary instanceof GhidraCheckpointSupersededError || + primary instanceof GhidraCheckpointBusyError + ? primary + : classify(primary); assertArtifactReadActive(signal); } + /** Runs under the publication lease after the compare-and-set admitted it. */ + async #replace( + path: string, + previous: CheckpointSource | null, + signal?: AbortSignal, + ): Promise { + const file = `program-${randomUUID()}.gzf`; + const destination = appendCallerPath(this.selection.directory, file); + const temporary = appendCallerPath( + this.selection.directory, + `.current-${randomUUID()}.json`, + ); + this.#pendingRemoval.add(destination); + this.#pendingRemoval.add(temporary); + assertArtifactReadActive(signal); + const hash = createHash("sha256"); + await copyGhidraRegularFile(path, destination, this.resources, { + signal, + hash, + sync: true, + }); + const source: CheckpointSource = { + file, + sha256: hash.digest("hex"), + kind: previous === null ? "initial-analysis" : "retained", + }; + const metadata = JSON.stringify({ + version: 2, + target_sha256: this.selection.target_sha256, + base_profile_digest: this.selection.base_profile_digest, + source, + }); + const handle = await open(temporary, "wx", 0o600); + await withArtifactFileHandle( + temporary, + handle, + this.resources, + signal, + async (handle) => { + await handle.writeFile(metadata); + await handle.sync(); + }, + ); + assertArtifactReadActive(signal); + await rename( + temporary, + appendCallerPath(this.selection.directory, "current.json"), + ); + this.#source = source; + this.#state = checkpointState(source); + this.#publishedInput = path; + this.#pendingRemoval.delete(destination); + this.#pendingRemoval.delete(temporary); + if (previous !== null) + this.#pendingRemoval.add( + appendCallerPath(this.selection.directory, previous.file), + ); + } + + /** + * Remove owned staging and superseded files and release the publication + * lease. The manifest names none of these files and the lease serializes + * only publication, so a failed removal is retained without holding the + * lease that other sessions' saves wait on. + */ async retryCleanup(): Promise { + let removal: unknown; for (const path of this.#pendingRemoval) { try { await rm(path, { force: true }); this.#pendingRemoval.delete(path); } catch (cause: unknown) { - const error = new ProviderCleanupError( - "ghidra", - [...this.#pendingRemoval], - { - reason: `Checkpoint file cleanup failed: ${errorMessage(cause)}`, - checkpoint: this.observation, - }, - { cause }, - ); - throw this.#cleanupRelease.bind(error); + removal = cause; + break; } } + let release: { readonly cause: unknown } | undefined; + try { + await this.#lease?.release(); + this.#lease = undefined; + } catch (cause: unknown) { + // The lease stays owned for retry; a lone release failure keeps its + // own error, and one alongside a removal failure is reported with it. + if (removal === undefined) throw cause; + release = { cause }; + } + if (removal !== undefined) { + const error = new ProviderCleanupError( + "ghidra", + this.cleanupResources, + { + reason: + release === undefined + ? `Checkpoint file cleanup failed: ${errorMessage(removal)}` + : `Checkpoint file cleanup failed: ${errorMessage(removal)}; releasing the checkpoint lease also failed: ${errorMessage(release.cause)}`, + checkpoint: this.observation, + }, + { + cause: + release === undefined + ? removal + : new AggregateError( + [removal, release.cause], + "Checkpoint file removal and lease release failed", + ), + }, + ); + throw this.#cleanupRelease.bind(error); + } this.#cleanupRelease.confirm(); this.#cleanupRelease = new AnalysisCleanupRelease(); } - async close(): Promise { - await this.retryCleanup(); - await this.#lease?.release(); - this.#lease = undefined; - } } diff --git a/src/ghidra/GhidraClient.ts b/src/ghidra/GhidraClient.ts index d51db5cc9a3..c6a3532e0a4 100644 --- a/src/ghidra/GhidraClient.ts +++ b/src/ghidra/GhidraClient.ts @@ -26,6 +26,7 @@ import { import { AnalysisError } from "../domain/analysisErrorBase.js"; import type { JsonValue } from "../domain/jsonValue.js"; import type { NativeValueFlowLimits } from "../domain/native/nativeValueFlow.js"; +import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { AnalysisCleanupRelease } from "../domain/analysisCleanupRelease.js"; import { @@ -33,7 +34,12 @@ import { type ProviderOperationHealth, } from "../domain/providerOperationHealth.js"; import { readRuntimeSetting } from "../config/runtimeAnalysisSettings.js"; +import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { err, ok, type Result } from "../domain/result.js"; +import { + retainCloseOutcome, + type EngineCloseReport, +} from "../domain/engineCloseReport.js"; import { silentLogger } from "../logger.js"; import type { Logger } from "pino"; import { @@ -85,6 +91,7 @@ import { GhidraRequestQueue } from "./GhidraRequestQueue.js"; import { DEFAULT_GHIDRA_CANCEL_GRACE } from "../config/ghidraCancelGrace.js"; import { bindGhidraSessionFailure, + isGhidraCleanupCarrier, GHIDRA_STARTUP_DEADLINE_ELAPSED, GhidraSessionError, } from "./GhidraSessionError.js"; @@ -143,8 +150,14 @@ import { completeGhidraStartupHandshake } from "./GhidraClientStartup.js"; import { ghidraSessionRoot } from "./GhidraSessionRoot.js"; import { GhidraCheckpoint, + GhidraCheckpointBusyError, + GhidraCheckpointSupersededError, type GhidraPackedProgram, } from "./GhidraCheckpoint.js"; +import { + ghidraCheckpointSaveWaitLimit, + ghidraCheckpointSaveWaitRecovery, +} from "../config/ghidraCheckpointSaveWait.js"; import { errorMessage } from "../kernel/errorMessage.js"; const SHUTDOWN_TIMEOUT_MS = 10_000; @@ -189,6 +202,16 @@ export class GhidraClient { | { readonly path: string; readonly disposition: "publish" | "discard" } | undefined; #checkpointRestore: GhidraPackedProgram | undefined; + /** + * This session holds Program edits whose save was refused; it can never + * succeed later, so the next close discards and reports them. + */ + #checkpointSaveRefused = false; + /** + * Set when the JVM holding edits whose save was refused has stopped, until + * the close that stopped it reports the discard with its outcome. + */ + #releasedUnsaved: EngineCloseReport | undefined; /** Reported by every cleanup failure until a close releases everything. */ #cleanupRelease = new AnalysisCleanupRelease(); #targetAdmission: JsonValue | undefined; @@ -217,6 +240,12 @@ export class GhidraClient { | undefined; #closePromise: Promise | undefined; #closeForced = false; + /** + * Owned by the queued graceful close from the moment it is requested, so a + * forced stop that escalates it aborts its final checkpoint save's wait for + * another session's publication lease whenever that save starts. + */ + #closeEscalation: AbortController | undefined; readonly #failure = bindGhidraSessionFailure( (scope) => this.#diagnostics(scope), (value, incomplete) => this.#redactAuthentication(value, incomplete), @@ -264,7 +293,11 @@ export class GhidraClient { this.#checkpoint = options.checkpoint === undefined ? undefined - : new GhidraCheckpoint(options.checkpoint, this.#fileResources); + : new GhidraCheckpoint( + options.checkpoint, + this.#fileResources, + options.checkpointSaveWait, + ); this.#options = { ...options, startupTimeoutMs: @@ -923,12 +956,19 @@ export class GhidraClient { } /** Stop the owned process group and remove all project/runtime artifacts. */ - async close(): Promise> { + async close(): Promise> { + // The close that stops the JVM reports the discard once, whether a later + // cleanup step fails or not; a close that fails before keeps the refusal. try { await this.#requestClose(false); - return ok(null); + return ok(this.#takeReleasedUnsaved()); } catch (cause: unknown) { - return err(this.#cleanupError(cause)); + return err( + retainCloseOutcome( + this.#cleanupError(cause), + this.#takeReleasedUnsaved(), + ), + ); } finally { // Closing is the caller's explicit retry: the next start imports again. // Cleared after close settles, since a startup it waited for may have @@ -937,6 +977,32 @@ export class GhidraClient { } } + #takeReleasedUnsaved(): EngineCloseReport | null { + const report = this.#releasedUnsaved ?? null; + this.#releasedUnsaved = undefined; + return report; + } + + #discardReport(): EngineCloseReport | null { + return this.#checkpoint === undefined + ? null + : { + checkpoint: { + status: "discarded", + reason: "superseded", + directory: this.#checkpoint.selection.directory, + }, + }; + } + + /** What closing now reports as released unsaved, without closing. */ + unsavedCloseReport(): EngineCloseReport | null { + return ( + this.#releasedUnsaved ?? + (this.#checkpointSaveRefused ? this.#discardReport() : null) + ); + } + /** Verified source after startup: null for initial checkpointed analysis; undefined if disabled or unconfirmed. */ checkpointRestore(): GhidraPackedProgram | null | undefined { if (this.#checkpoint === undefined || !this.#startupSucceeded()) @@ -964,6 +1030,9 @@ export class GhidraClient { #cleanupError(cause: unknown): AnalysisError { if (cause instanceof AnalysisError && cause.cleanupIncomplete) return this.#retainCleanupFailure(cause); + const carried = isGhidraCleanupCarrier(cause) + ? cause.cleanupFailure + : undefined; const failure = new ProviderCleanupError( "ghidra", [ @@ -980,8 +1049,26 @@ export class GhidraClient { { reason: errorMessage(cause), diagnostics: this.#diagnostics(), + // A cause such as a checkpoint refusal stays primary; cleanup that + // also failed after it is reported beside it, its resources above. + ...(carried === undefined + ? {} + : { carried_cleanup_failure: projectAnalysisError(carried) }), + }, + { + cause, + ...(cause instanceof GhidraCheckpointSupersededError + ? { + remediationAction: + "Another REA session saved this target's Ghidra checkpoint first, so this session's Program edits were not saved and the current checkpoint is unchanged. Closing the target again discards those edits and releases the session; then reopen the target and reapply them.", + } + : cause instanceof GhidraCheckpointBusyError + ? { + remediationAction: ghidraCheckpointSaveWaitRecovery(cause.wait), + limit: ghidraCheckpointSaveWaitLimit(cause.wait), + } + : {}), }, - { cause }, ); return this.#retainCleanupFailure(failure); } @@ -1031,15 +1118,23 @@ export class GhidraClient { // stalled checkpoint or shutdown reply), then runs once it settles. if (previous !== undefined && (!forceStop || this.#closeForced)) return previous; - if (previous !== undefined) - this.#failAll( - this.#failure("process", "Ghidra close escalated to a forced stop"), + if (previous !== undefined) { + const escalation = this.#failure( + "process", + "Ghidra close escalated to a forced stop", ); + this.#closeEscalation?.abort(escalation); + this.#failAll(escalation); + } this.#closeForced = forceStop; + const escalation = forceStop ? undefined : new AbortController(); + if (escalation !== undefined) this.#closeEscalation = escalation; const attempt: Promise = (previous ?? Promise.resolve()) .catch(() => undefined) - .then(() => this.#close(starting, forceStop)) + .then(() => this.#close(starting, forceStop, escalation?.signal)) .finally(() => { + if (this.#closeEscalation === escalation) + this.#closeEscalation = undefined; if (this.#closePromise === attempt) { this.#closePromise = undefined; this.#closeForced = false; @@ -1174,7 +1269,7 @@ export class GhidraClient { if (!limits.ok) return limits; let packedProgram: GhidraPackedProgram | undefined; try { - packedProgram = await this.#checkpoint?.acquire( + packedProgram = await this.#checkpoint?.admit( this.#options.runId ?? randomUUID(), deadline.signal, ); @@ -1298,15 +1393,69 @@ export class GhidraClient { : launched.error instanceof GhidraLaunchError ? launched.error.primaryFailure : undefined; + // A save by another session after admission removes the packed file + // this launch was restoring; report that instead of the missing file. + // Only a failed restore can be explained that way: any other launch + // failure keeps its own cause, output and diagnostics. + // A failed manifest read is not an explanation. Keep the launch error + // primary and retain that read, including a descriptor close that + // failed after the bytes were read, so a later cleanup retry cannot + // drop the reason. + let manifestReadFailure: unknown; + const superseded = + packedProgram === undefined || + producerFailure instanceof AnalysisCancelledError || + !( + launched.error instanceof GhidraLaunchError && + launched.error.checkpointRestoreFailed + ) + ? undefined + : await this.#checkpoint + ?.supersededRestore(deadline.signal) + .catch((cause: unknown) => { + manifestReadFailure = cause; + return undefined; + }); + // The explanation replaces the launch outcome, not its cleanup: the + // launcher's retained restore cleanup failure travels on the refusal. + if (superseded !== undefined && isGhidraCleanupCarrier(launched.error)) + superseded.cleanupFailure ??= launched.error.cleanupFailure; const failure = producerFailure instanceof AnalysisCancelledError ? this.#interruptionFailure(deadline, launched.error, { reason: producerFailure.cause, }) - : launched.error instanceof GhidraSessionError - ? launched.error - : this.#failure("start", launched.error.message, launched.error); - return this.#startupFailure(failure, deadline); + : superseded !== undefined + ? this.#failure("checkpoint", superseded.message, superseded) + : launched.error instanceof GhidraSessionError + ? launched.error + : this.#failure("start", launched.error.message, launched.error); + const readError = + manifestReadFailure instanceof AnalysisError + ? manifestReadFailure + : manifestReadFailure === undefined + ? undefined + : new ProviderAdapterError("ghidra", "resolve_analysis_profile", { + ...(manifestReadFailure instanceof Error + ? { cause: manifestReadFailure } + : {}), + diagnostics: { + reason: + manifestReadFailure instanceof Error + ? manifestReadFailure.message + : "Ghidra checkpoint manifest read failed", + }, + }); + // Cleanup ownership caches the startup attempt until close. A read + // that failed without owning a handle is only a secondary fact, so + // the next start can try again. + const reported = + readError === undefined + ? failure + : readError.cleanupIncomplete + ? failure.withCleanupFailure(readError) + : failure.retainSecondaryFailure(readError); + return this.#startupFailure(reported, deadline); } this.#launch = launched.value; this.#process = new ProviderProcessSupervisor(launched.value, { @@ -1339,7 +1488,10 @@ export class GhidraClient { ? this.#interruptionFailure(deadline, cause) : this.#failure( "checkpoint", - "Initial Ghidra checkpoint could not be saved; check REA_GHIDRA_CHECKPOINT_DIR and reopen the target", + cause instanceof GhidraCheckpointSupersededError || + cause instanceof GhidraCheckpointBusyError + ? cause.message + : "Initial Ghidra checkpoint could not be saved; check REA_GHIDRA_CHECKPOINT_DIR and reopen the target", cause, ), deadline, @@ -1351,12 +1503,19 @@ export class GhidraClient { return completed; } - /** Save once at startup and after changes, retaining a failed publication for retry. */ - async #saveCheckpoint(force: boolean, signal?: AbortSignal): Promise { + /** + * Save once at startup and after changes, retaining a failed publication + * for retry. `leaseSignal` ends only the wait for another session's lease. + */ + async #saveCheckpoint( + force: boolean, + signal?: AbortSignal, + leaseSignal: AbortSignal | undefined = signal, + ): Promise { const owner = this.#checkpoint; const runtime = this.#runtimeRoot; if (owner === undefined || runtime === undefined) return; - await this.#finishCheckpointStaging(signal); + await this.#finishCheckpointStaging(signal, leaseSignal); const path = join(runtime.path, `checkpoint-${randomUUID()}.gzf`); // Checkpoints run at startup and during close, so they use the session's // admitted ceilings rather than the current settings. @@ -1392,7 +1551,7 @@ export class GhidraClient { ); if (!parsed.data.saved) return; this.#checkpointStaging = { path, disposition: "publish" }; - await this.#finishCheckpointStaging(signal); + await this.#finishCheckpointStaging(signal, leaseSignal); } /** An acknowledged failed export is owned but is not a valid checkpoint. */ @@ -1422,7 +1581,10 @@ export class GhidraClient { throw failure; } - async #finishCheckpointStaging(signal?: AbortSignal): Promise { + async #finishCheckpointStaging( + signal?: AbortSignal, + leaseSignal: AbortSignal | undefined = signal, + ): Promise { const staged = this.#checkpointStaging; if (staged === undefined) return; if (staged.disposition === "publish") { @@ -1431,7 +1593,20 @@ export class GhidraClient { "protocol", "Checkpoint publication owner is missing", ); - await this.#checkpoint.publish(staged.path, signal); + try { + await this.#checkpoint.publish(staged.path, signal, leaseSignal); + } catch (cause: unknown) { + // Any refusal is permanent for this generation, so the staged file is + // discarded; only refused edits are reported as released unsaved. + if (cause instanceof GhidraCheckpointSupersededError) { + this.#checkpointStaging = { + path: staged.path, + disposition: "discard", + }; + if (cause.refusesEdits) this.#checkpointSaveRefused = true; + } + throw cause; + } } await rm(staged.path, { force: true }); this.#checkpointStaging = undefined; @@ -1532,10 +1707,11 @@ export class GhidraClient { async #close( starting: GhidraStartupAttempt | undefined, forceStop: boolean, + escalation?: AbortSignal, ): Promise { try { await starting?.promise.catch(() => undefined); - await this.#cleanup(forceStop); + await this.#cleanup(forceStop, escalation); } finally { if ( this.#startupAttempt === starting && @@ -1545,7 +1721,8 @@ export class GhidraClient { } } - async #cleanup(forceStop = false): Promise { + /** `escalation` aborts a graceful close's lease wait when a forced stop follows. */ + async #cleanup(forceStop = false, escalation?: AbortSignal): Promise { this.#closing = true; let forcedStopFailure: { readonly cause: unknown } | undefined; try { @@ -1556,11 +1733,12 @@ export class GhidraClient { !forceStop && this.#startupSucceeded() && this.#checkpoint !== undefined && + !this.#checkpointSaveRefused && this.#socket !== undefined && !this.#socket.destroyed ) { try { - await this.#saveCheckpoint(false); + await this.#saveCheckpoint(false, undefined, escalation); } catch (cause: unknown) { this.#requestQueue.reopen(); throw cause; @@ -1625,10 +1803,15 @@ export class GhidraClient { ); } } + // The JVM holding the edits has stopped: they are released now. + if (this.#checkpointSaveRefused) { + this.#releasedUnsaved = this.#discardReport() ?? undefined; + this.#checkpointSaveRefused = false; + } this.#lastDiagnostics = this.#diagnostics(); this.#process = undefined; this.#launch = undefined; - await this.#checkpoint?.close(); + await this.#checkpoint?.retryCleanup(); await this.#fileResources.retryCleanup(); try { await this.#removeRuntimeRoots(); @@ -1638,6 +1821,7 @@ export class GhidraClient { } this.#snapshotPath = undefined; this.#checkpointStaging = undefined; + this.#checkpointSaveRefused = false; this.#checkpointRestore = undefined; this.#endpointPath = undefined; this.#token = undefined; diff --git a/src/ghidra/GhidraClientTypes.ts b/src/ghidra/GhidraClientTypes.ts index 146827743b3..1406eab0133 100644 --- a/src/ghidra/GhidraClientTypes.ts +++ b/src/ghidra/GhidraClientTypes.ts @@ -2,6 +2,7 @@ import type { Logger } from "pino"; import type { GhidraCheckpointSelection } from "./GhidraCheckpoint.js"; import type { BridgeMaxRequestBytes } from "../config/bridgeMaxRequestBytes.js"; import type { GhidraCancelGrace } from "../config/ghidraCancelGrace.js"; +import type { GhidraCheckpointSaveWait } from "../config/ghidraCheckpointSaveWait.js"; import type { BridgeMaxReplyBytes } from "../config/bridgeMaxReplyBytes.js"; import type { Result } from "../domain/result.js"; import type { LinuxCgroupMemoryState } from "../process/LinuxCgroupMemory.js"; @@ -74,6 +75,8 @@ export interface GhidraClientOptions { readonly targetSha256: string; readonly existingProject?: boolean; readonly checkpoint?: GhidraCheckpointSelection; + /** Bound on a checkpoint save's wait for another session; absent keeps the default. */ + readonly checkpointSaveWait?: GhidraCheckpointSaveWait; /** Installation host shared by runtime allocation and snapshot admission. */ readonly platform?: NodeJS.Platform; readonly transport?: GhidraTransportKind; diff --git a/src/ghidra/GhidraLauncher.ts b/src/ghidra/GhidraLauncher.ts index 613cf24833e..ecfe53f5825 100644 --- a/src/ghidra/GhidraLauncher.ts +++ b/src/ghidra/GhidraLauncher.ts @@ -142,6 +142,8 @@ export class GhidraLaunchError extends Error { readonly cleanupFailure: AnalysisError | undefined; /** Known producer outcome, independent of a signal that changes during finalization. */ readonly primaryFailure: AnalysisError | undefined; + /** The launch failed while copying or verifying the checkpoint's packed Program. */ + readonly checkpointRestoreFailed: boolean; constructor( message: string, @@ -152,9 +154,11 @@ export class GhidraLaunchError extends Error { readonly primaryFailure?: AnalysisError; readonly capturedOutput?: AnalysisCapturedOutput; readonly launchSupport?: readonly GhidraLaunchSupportDiagnostic[]; + readonly checkpointRestoreFailed?: boolean; }, ) { const { + checkpointRestoreFailed, partialLaunch, capturedOutput, launchSupport, @@ -166,6 +170,10 @@ export class GhidraLaunchError extends Error { super(message, errorOptions); this.name = "GhidraLaunchError"; this.#partialLaunch = partialLaunch; + this.checkpointRestoreFailed = + checkpointRestoreFailed ?? + (errorOptions.cause instanceof GhidraLaunchError && + errorOptions.cause.checkpointRestoreFailed); this.rollbackFailure = rollbackFailure; this.primaryFailure = primaryFailure ?? @@ -319,6 +327,9 @@ export class GhidraHeadlessLauncher implements GhidraLauncher { const platform = this.options.platform ?? HOST_PLATFORM.platform; const existingProject = this.options.existingProject; let started: SpawnedOwnedProviderProcess | undefined; + // Set only while the private checkpoint restore runs, so a caller can + // tell a failed restore from any other launch failure. + let restoringCheckpoint = false; let configuredMaxHeap: string | undefined; const launchSupport: GhidraLaunchSupportDiagnostic[] = []; try { @@ -365,6 +376,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher { let packedProgramPath: string | undefined; if (session.packedProgram !== undefined) { packedProgramPath = join(session.runtimeRoot, "restored-program.gzf"); + restoringCheckpoint = true; const packedHash = createHash("sha256"); try { await copyGhidraRegularFile( @@ -389,6 +401,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher { throw new GhidraLaunchError( "Ghidra checkpoint changed before its private import; reopen the target.", ); + restoringCheckpoint = false; } // Copy-first: open the caller's project only through the owned copy so // Ghidra never touches the original project files. @@ -670,6 +683,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher { ...(retained.cleanupIncomplete ? { cleanupFailure: retained } : {}), launchSupport, ...(capturedOutput === undefined ? {} : { capturedOutput }), + checkpointRestoreFailed: restoringCheckpoint, }, ); if (started === undefined) return err(launchFailure); @@ -719,6 +733,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher { : { cleanupFailure: launchFailure.cleanupFailure }), launchSupport, ...(capturedOutput === undefined ? {} : { capturedOutput }), + checkpointRestoreFailed: restoringCheckpoint, }, ), ); diff --git a/src/ghidra/GhidraProvider.behavior.test.ts b/src/ghidra/GhidraProvider.behavior.test.ts index 5e1deb129ea..80e308ade3b 100644 --- a/src/ghidra/GhidraProvider.behavior.test.ts +++ b/src/ghidra/GhidraProvider.behavior.test.ts @@ -5188,6 +5188,71 @@ describe("the cancel grace launch control", () => { }); }); +describe("the checkpoint save wait launch control", () => { + const open = async (environment: Readonly>) => { + const received: unknown[] = []; + const ghidra = provider( + installationHost(), + (options) => { + received.push(options.checkpointSaveWait); + return { + start: async () => ok(sessionInfo()), + callTool: async () => ok([]), + close: async () => ok(null), + }; + }, + environment, + ); + onTestFinished(async () => { + await ghidra.closeOwnedResources(); + }); + const target = executableTarget("elf", "x86_64"); + const profile = await ghidra.resolveAnalysisProfile(target); + if (!profile.ok || profile.value.profile === null) + throw new Error("Expected Ghidra analysis profile"); + const result = await ghidra + .createClient(target, profile.value.profile) + .execute("list_documents", {}); + return { received, result }; + }; + + it("hands a checkpointed session the launch value and leaves the default implicit", async () => { + const root = await createTestTempDirectory("rea-save-wait-"); + const selected = await open({ + REA_GHIDRA_CHECKPOINT_DIR: root, + REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS: "1200", + }); + expect(selected.received).toEqual([{ waitMs: 1_200, source: "setting" }]); + const unset = await open({ REA_GHIDRA_CHECKPOINT_DIR: root }); + expect(unset.received).toEqual([{ waitMs: 30_000, source: "default" }]); + }); + + it("refuses a checkpointed session on an invalid value and leaves ephemeral sessions alone", async () => { + const root = await createTestTempDirectory("rea-save-wait-invalid-"); + const refused = await open({ + REA_GHIDRA_CHECKPOINT_DIR: root, + REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS: "600001", + }); + expect(refused.received).toEqual([]); + if (refused.result.ok) throw new Error("invalid save wait was applied"); + expect(projectAnalysisError(refused.result.error)).toMatchObject({ + code: "configuration_invalid", + details: { + settings: [{ setting: "REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS" }], + }, + }); + // Without a checkpoint nothing applies the wait. + const ephemeral = await open({ + REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS: "600001", + }); + expect(ephemeral.received).toEqual([undefined]); + if (!ephemeral.result.ok) + expect(projectAnalysisError(ephemeral.result.error).code).not.toBe( + "configuration_invalid", + ); + }); +}); + const startFailure = async ( stdout: string, environment: Readonly> = {}, diff --git a/src/ghidra/GhidraProviderCapabilities.ts b/src/ghidra/GhidraProviderCapabilities.ts index c2142c74757..20e73935e98 100644 --- a/src/ghidra/GhidraProviderCapabilities.ts +++ b/src/ghidra/GhidraProviderCapabilities.ts @@ -81,7 +81,7 @@ export const ghidraHealthLimitations = ( : source === "owned-checkpoint" ? [ "Ghidra Program checkpoint mode is enabled (REA_GHIDRA_CHECKPOINT_DIR). Opening the same target/profile automatically restores saved analysis, names, comments and types; no separate save or restore tool is needed. Restored analysis is retained state, not a fresh discovery.", - "REA saves initial completed analysis and metadata changes on normal close (close_binary in MCP). A failed save retains the live session for close retry. Cancellation or process failure can lose changes after the last successful save; unfinished initial auto-analysis is not resumable.", + "REA saves initial completed analysis and metadata changes on normal close (close_binary in MCP). A failed save retains the live session for close retry. Sessions can share a target; a save is refused when another session saved first, and its edits must be reapplied after reopening. Cancellation or process failure can lose changes after the last successful save; unfinished initial auto-analysis is not resumable.", "The live project is a temporary working copy. Checkpoints persist in REA_GHIDRA_CHECKPOINT_DIR; source executables and caller-selected source projects are not modified.", ] : healthLimitations(cancelGrace); diff --git a/src/ghidra/GhidraProviderClient.ts b/src/ghidra/GhidraProviderClient.ts index c40389ef550..c662b030686 100644 --- a/src/ghidra/GhidraProviderClient.ts +++ b/src/ghidra/GhidraProviderClient.ts @@ -1,3 +1,4 @@ +import { retainCloseOutcome } from "../domain/engineCloseReport.js"; import { projectSessionError, type GhidraProjection, @@ -174,6 +175,7 @@ export type GhidraProviderClientFactory = ( | "callToolIfReady" | "checkpointRestore" | "operationHealthSnapshot" + | "unsavedCloseReport" | "runtimeLineage" | "readTargetSnapshot" | "readTargetSnapshotRanges" @@ -682,9 +684,25 @@ export const createGhidraProviderClient = (input: { if (cancelGraceSetting !== undefined && !cancelGraceSetting.ok) return cancelGraceSetting; const cancelGrace = cancelGraceSetting?.value ?? DEFAULT_GHIDRA_CANCEL_GRACE; + // Only a checkpointed session applies the save wait, so only it refuses an + // invalid launch value. + const checkpointSaveWait = config.ghidraCheckpointSaveWait; + if ( + checkpoint.data !== undefined && + checkpointSaveWait !== undefined && + !checkpointSaveWait.ok + ) + return checkpointSaveWait; const client = clientFactory({ cancelGrace, - ...(checkpoint.data === undefined ? {} : { checkpoint: checkpoint.data }), + ...(checkpoint.data === undefined + ? {} + : { + checkpoint: checkpoint.data, + ...(checkpointSaveWait?.ok === true + ? { checkpointSaveWait: checkpointSaveWait.value } + : {}), + }), startupTimeoutMs: startupTimeout.value, readStartupTimeoutMs: () => config.ghidraStartupTimeoutMs, bridgeMaxRequestBytes: config.bridgeMaxRequestBytes, @@ -1368,6 +1386,7 @@ export const createGhidraProviderClient = (input: { return inventoryExecution(operation, called); }, operationHealthSnapshot: () => client.operationHealthSnapshot?.(), + unsavedCloseReport: () => client.unsavedCloseReport?.() ?? null, runtimeLineageSnapshots: () => { const observation = client.runtimeLineage?.() ?? null; return observation === null @@ -1379,9 +1398,14 @@ export const createGhidraProviderClient = (input: { const closed = await client.close(); const retained = nativeAotOwner?.cleanupFailure; if (retained === undefined) return closed; - return closed.ok - ? err(retained) - : err(analysisErrorWithCleanupDependencies(closed.error, retained)); + return err( + retainCloseOutcome( + closed.ok + ? retained + : analysisErrorWithCleanupDependencies(closed.error, retained), + closed, + ), + ); }, }); }; diff --git a/src/ghidra/GhidraSessionError.ts b/src/ghidra/GhidraSessionError.ts index 4a375e5bc8e..2ed67571c98 100644 --- a/src/ghidra/GhidraSessionError.ts +++ b/src/ghidra/GhidraSessionError.ts @@ -11,6 +11,10 @@ import type { GhidraDiagnosticsScope } from "./GhidraDiagnostics.js"; import { isGhidraByteSearchCursorMismatch } from "./GhidraByteSearchCursorFailure.js"; import { ghidraFileOffsetOutcome } from "./GhidraFileOffsetFailure.js"; import { GhidraAdmissionError } from "./GhidraAdmissionError.js"; +import { + GhidraCheckpointBusyError, + GhidraCheckpointSupersededError, +} from "./GhidraCheckpoint.js"; import { GhidraLaunchSupportError } from "./GhidraJavaLaunch.js"; import { GhidraLaunchError, @@ -73,6 +77,8 @@ export class GhidraSessionError extends Error { readonly configurationFailure: ConfigurationError | undefined; readonly partialObservation: AnalysisPartialObservation | undefined; readonly concurrentCancellation: { readonly reason: unknown } | undefined; + /** Read failures that do not own cleanup, kept beside the primary outcome. */ + #secondaryFailures: AnalysisError[] = []; constructor( readonly kind: GhidraSessionFailureKind, @@ -92,6 +98,17 @@ export class GhidraSessionError extends Error { this.concurrentCancellation = options.concurrentCancellation; } + /** Failures recorded beside this outcome that do not own its cleanup. */ + get secondaryFailures(): readonly AnalysisError[] { + return [...this.#secondaryFailures]; + } + + /** Keep a non-cleanup fact, such as a manifest read that opened no handle. */ + retainSecondaryFailure(failure: AnalysisError): this { + this.#secondaryFailures.push(failure); + return this; + } + /** Refresh diagnostics without discarding owned failure or cleanup facts. */ withDiagnostics( diagnostics: Readonly>, @@ -147,7 +164,7 @@ export class GhidraSessionError extends Error { partialObservation = this.partialObservation, concurrentCancellation = this.concurrentCancellation, ): GhidraSessionError { - return new GhidraSessionError(this.kind, message, diagnostics, { + const copied = new GhidraSessionError(this.kind, message, diagnostics, { ...(Object.hasOwn(this, "cause") ? { cause: this.cause } : {}), ...(this.cancellation === undefined ? {} @@ -163,6 +180,12 @@ export class GhidraSessionError extends Error { ? {} : { concurrentCancellation }), }); + // A diagnostic refresh is not a new failure. Secondary facts recorded + // on this error, such as a manifest read that failed without owning + // cleanup, stay with the copy. + for (const secondary of this.secondaryFailures) + copied.retainSecondaryFailure(secondary); + return copied; } } @@ -260,6 +283,27 @@ export const isGhidraInputFailureCode = (code: string | undefined): boolean => code === "ambiguous"; /** Bind session-failure construction to its causal diagnostic scope. */ +/** + * Ghidra lifecycle errors that carry a cleanup failure beside their own + * outcome. Every consumer of a raw cause recognizes carriers here, so one + * carrier type cannot be read by one consumer and missed by another. + */ +const GHIDRA_CLEANUP_CARRIERS = [ + DarwinProcessOwnershipInspectionError, + GhidraLaunchError, + GhidraCheckpointSupersededError, + GhidraCheckpointBusyError, +] as const; + +export type GhidraCleanupCarrier = InstanceType< + (typeof GHIDRA_CLEANUP_CARRIERS)[number] +>; + +export const isGhidraCleanupCarrier = ( + cause: unknown, +): cause is GhidraCleanupCarrier => + GHIDRA_CLEANUP_CARRIERS.some((carrier) => cause instanceof carrier); + export const bindGhidraSessionFailure = ( diagnostics: ( @@ -299,13 +343,11 @@ export const bindGhidraSessionFailure = ...(cause === undefined ? {} : { cause }), ...options, }); - const cleanup = - cause instanceof DarwinProcessOwnershipInspectionError || - cause instanceof GhidraLaunchError - ? cause.cleanupFailure - : cause instanceof AnalysisError && cause.cleanupIncomplete - ? cause - : undefined; + const cleanup = isGhidraCleanupCarrier(cause) + ? cause.cleanupFailure + : cause instanceof AnalysisError && cause.cleanupIncomplete + ? cause + : undefined; return cleanup === undefined ? failure : failure.withCleanupFailure(cleanup); diff --git a/src/ghidra/GhidraSessionErrorProjection.checkpointBusy.test.ts b/src/ghidra/GhidraSessionErrorProjection.checkpointBusy.test.ts index 3c504bb8614..39b409605ab 100644 --- a/src/ghidra/GhidraSessionErrorProjection.checkpointBusy.test.ts +++ b/src/ghidra/GhidraSessionErrorProjection.checkpointBusy.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js"; +import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { GhidraCheckpointBusyError, GhidraCheckpointSupersededError, @@ -8,56 +9,87 @@ import { import { GhidraSessionError } from "./GhidraSessionError.js"; import { projectSessionError } from "./GhidraSessionErrorProjection.js"; -const project = (cause: Error) => - projectSessionError( - "list_documents", - new GhidraSessionError("checkpoint", cause.message, {}, { cause }), - { - limits: { ghidraStartupTimeoutMs: 1_000 }, - programName: undefined, - source: "owned-checkpoint", - }, - ); - -describe("a checkpoint held by another session", () => { +describe("a checkpoint being saved by another session", () => { it("projects as retryable contention, not as an invalid setting", () => { - const busy = new GhidraCheckpointBusyError("/private/checkpoints", { - runId: "run-a", - processId: 4242, - }); - const projected = project(busy); + const busy = new GhidraCheckpointBusyError( + "/private/checkpoints", + { runId: "run-a", processId: 4242 }, + { waitMs: 1_200, source: "setting" }, + ); + const projected = projectSessionError( + "list_documents", + new GhidraSessionError("checkpoint", busy.message, {}, { cause: busy }), + { + limits: { ghidraStartupTimeoutMs: 1_000 }, + programName: undefined, + source: "owned-checkpoint", + }, + ); if (!(projected instanceof AnalysisCapabilityUnavailableError)) throw new Error(`unexpected projection: ${projected.name}`); expect(projected.retryable).toBe(true); expect(projected.message).toContain("another REA session"); expect(projected.message).toContain("run-a"); expect(projected.remediationAction).toContain( - "Wait for that session to close the target", + "Wait for that session's save to finish", ); expect(projected.remediationAction).not.toContain( "Correct REA_GHIDRA_CHECKPOINT_DIR", ); + // The exhausted wait is a launch control: name it, its value and range. + expect(projected.limit).toEqual({ + control_kind: "environment", + environment: "REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS", + effective_value: 1_200, + unit: "ms", + minimum: 50, + maximum: 600_000, + default_value: 30_000, + applies_at: "next_startup", + }); + for (const text of [projected.message, projected.remediationAction]) + expect(text).toContain( + "REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS is 1200 ms (source launch environment; default 30000, floor 50, maximum 600000)", + ); + expect(projected.remediationAction).toContain( + "environment that starts REA and restart REA", + ); + expect(projectAnalysisError(projected, "continuing").details).toMatchObject( + { + limit: { + control_kind: "environment", + environment: "REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS", + effective_value: 1_200, + }, + }, + ); }); - it("tells a retry after the owner saved edits to reopen the target", () => { - const busy = project( - new GhidraCheckpointBusyError("/private/checkpoints", { - runId: "run-a", - processId: 4242, - }), + it("projects a superseded restore as a reopen, not as an invalid setting", () => { + const superseded = new GhidraCheckpointSupersededError( + "/private/checkpoints", + "restore", ); - if (!(busy instanceof AnalysisCapabilityUnavailableError)) - throw new Error(`unexpected projection: ${busy.name}`); - expect(busy.remediationAction).toContain( - "reports that the checkpoint changed; then reopen the target", + const projected = projectSessionError( + "list_documents", + new GhidraSessionError( + "checkpoint", + superseded.message, + {}, + { cause: superseded }, + ), + { + limits: { ghidraStartupTimeoutMs: 1_000 }, + programName: undefined, + source: "owned-checkpoint", + }, ); - const superseded = project( - new GhidraCheckpointSupersededError("/private/checkpoints"), - ); - if (!(superseded instanceof AnalysisCapabilityUnavailableError)) - throw new Error(`unexpected projection: ${superseded.name}`); - expect(superseded.retryable).toBe(false); - expect(superseded.remediationAction).toContain("call open_binary again"); - expect(superseded.remediationAction).not.toContain("repeat this call"); + if (!(projected instanceof AnalysisCapabilityUnavailableError)) + throw new Error(`unexpected projection: ${projected.name}`); + // The session's profile commits to the superseded generation. + expect(projected.retryable).toBe(false); + expect(projected.message).toContain("reopen the target"); + expect(projected.remediationAction).toContain("open_binary"); + expect(projected.remediationAction).toContain("needs no change"); }); }); diff --git a/src/ghidra/GhidraSessionErrorProjection.ts b/src/ghidra/GhidraSessionErrorProjection.ts index b9f06772866..4cf8112c117 100644 --- a/src/ghidra/GhidraSessionErrorProjection.ts +++ b/src/ghidra/GhidraSessionErrorProjection.ts @@ -11,6 +11,10 @@ import { MAXIMUM_GHIDRA_TYPE_DECLARATIONS_MAX_UTF16, MINIMUM_GHIDRA_C_TEXT_UTF16, } from "../domain/analysisResourceLimits.js"; +import { + ghidraCheckpointSaveWaitLimit, + ghidraCheckpointSaveWaitRecovery, +} from "../config/ghidraCheckpointSaveWait.js"; import { z } from "zod"; import { analysisClientFailureForOperation } from "../providers/AnalysisClientFailure.js"; import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; @@ -110,13 +114,17 @@ export const projectSessionError = ( request, entryHint, ); - return failure.cleanupFailure === undefined - ? primary - : analysisErrorWithCleanupDependencies( - primary, - failure.cleanupFailure, - operation, - ); + const projected = + failure.cleanupFailure === undefined + ? primary + : analysisErrorWithCleanupDependencies( + primary, + failure.cleanupFailure, + operation, + ); + for (const secondary of failure.secondaryFailures) + projected.retainSecondaryFailure(secondary); + return projected; }; const projectPrimarySessionError = ( @@ -147,9 +155,11 @@ const projectPrimarySessionError = ( { ...context, retryable: true, - userMessage: `${failure.cause.message}. One session at a time opens a target through a checkpoint directory.`, - remediationAction: - "Wait for that session to close the target, or close it, then repeat this call unchanged. If that session saved Program edits when it closed, the repeated call reports that the checkpoint changed; then reopen the target to restore the saved checkpoint. To analyze the same target concurrently, start this process without REA_GHIDRA_CHECKPOINT_DIR; it then uses a private ephemeral import.", + userMessage: `${failure.cause.message}. Sessions share a checkpointed target; one at a time saves it.`, + remediationAction: ghidraCheckpointSaveWaitRecovery( + failure.cause.wait, + ), + limit: ghidraCheckpointSaveWaitLimit(failure.cause.wait), }, ); // The session's committed profile names the generation it selected, so diff --git a/src/ports/AnalysisProvider.ts b/src/ports/AnalysisProvider.ts index c238ef91b75..ceeb7607581 100644 --- a/src/ports/AnalysisProvider.ts +++ b/src/ports/AnalysisProvider.ts @@ -15,6 +15,7 @@ import type { AnalysisCapabilityUnavailableError } from "../domain/analysisError import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js"; import type { JsonValue } from "../domain/jsonValue.js"; import type { Result } from "../domain/result.js"; +import type { EngineCloseReport } from "../domain/engineCloseReport.js"; import type { Evidence, EvidenceAuthority, @@ -305,14 +306,22 @@ export interface AnalysisClient extends AnalysisOperationPort { reuseReadiness?(): "ready" | "blocked" | "unknown"; /** Current operational health for the active provider bridge. */ operationHealthSnapshot?(): ProviderOperationHealth | undefined; - /** Close owned resources and retain failed cleanup for a later retry. */ + /** + * What closing now would report as engine state released unsaved, without + * closing. Only a close reports it, so other transitions refuse to release it. + */ + unsavedCloseReport?(): EngineCloseReport | null; + /** + * Close owned resources and retain failed cleanup for a later retry. A + * report names engine state the close released without persisting it. + */ close( options?: Pick & { readonly retainDocument?: boolean; /** Report each owned cleanup failure as soon as its owner observes it. */ readonly onCleanupFailure?: (failure: AnalysisError) => void; }, - ): Promise>; + ): Promise>; } /** Per-client identity allocated before any provider side effect starts. */ diff --git a/src/process/OwnedLease.test.ts b/src/process/OwnedLease.test.ts index 24b44bb3e52..3812c785841 100644 --- a/src/process/OwnedLease.test.ts +++ b/src/process/OwnedLease.test.ts @@ -1,11 +1,12 @@ import { execFile } from "node:child_process"; -import { createConnection, Server } from "node:net"; +import { createConnection, createServer, Server } from "node:net"; import { promisify } from "node:util"; import { mkdtemp, rm } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest"; import { phaseGate } from "../../tests/support/lifecycleHarness.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; import { AnalysisCleanupLease } from "../resources/AnalysisCleanupLease.js"; import { ArtifactResourceScope } from "../resources/ArtifactResourceScope.js"; import { HopperStartError } from "../hopper/HopperErrors.js"; @@ -554,3 +555,67 @@ describe.skipIf(process.platform === "win32")( ); }, ); + +describe.skipIf(process.platform === "win32")( + "an owner that accepts and does not answer", + () => { + const silentOwner = async () => { + const directory = await createTestTempDirectory("rea-silent-owner-"); + const identity = { test: "silent-owner" }; + const socketPath = join( + directory, + `${sha256Hex(JSON.stringify(identity)).slice(0, 32)}.sock`, + ); + const server = createServer((socket) => { + socket.resume(); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(socketPath, () => resolve()); + }); + onTestFinished( + () => + new Promise((resolve) => { + server.close(() => resolve()); + }), + ); + return { directory, identity }; + }; + + it("stops when the caller budget is shorter than the owner-response timeout", async () => { + const { directory, identity } = await silentOwner(); + const started = performance.now(); + const reasons: string[] = []; + await expect( + acquireOwnedLease({ + identity, + directory, + runId: "contender", + probe: { timeoutMs: 40 }, + failure: (reason) => { + if (reason.kind === "owner_unverified") reasons.push(reason.reason); + return new Error(reason.kind); + }, + }), + ).rejects.toThrow("owner_unverified"); + expect(performance.now() - started).toBeLessThan(220); + expect(reasons).toEqual(["owner response timed out"]); + }); + + it("stops when the caller aborts the probe", async () => { + const { directory, identity } = await silentOwner(); + const controller = new AbortController(); + const started = performance.now(); + const pending = acquireOwnedLease({ + identity, + directory, + runId: "contender", + probe: { signal: controller.signal }, + failure: (reason) => new Error(reason.kind), + }); + setTimeout(() => controller.abort(), 30); + await expect(pending).rejects.toThrow("owner_unverified"); + expect(performance.now() - started).toBeLessThan(220); + }); + }, +); diff --git a/src/process/OwnedLease.ts b/src/process/OwnedLease.ts index 742fe87d6d3..0c6713cfab5 100644 --- a/src/process/OwnedLease.ts +++ b/src/process/OwnedLease.ts @@ -55,6 +55,25 @@ export type LeaseFailureFactory = ( cause?: unknown, ) => Error; +/** How long an owner may take to answer before the probe reports it unverified. */ +export const LEASE_OWNER_RESPONSE_TIMEOUT_MS = 250; + +/** Reason on `owner_unverified` when that probe budget elapses with no identity. */ +export const LEASE_OWNER_RESPONSE_TIMED_OUT = "owner response timed out"; + +/** Reason on `owner_unverified` when the caller's signal stops the probe. */ +export const LEASE_OWNER_PROBE_ABORTED = "owner probe aborted"; + +/** + * A caller's bound on the owner-identity probe. The probe never waits longer + * than `LEASE_OWNER_RESPONSE_TIMEOUT_MS`; a shorter `timeoutMs` is that + * caller's own deadline. `signal` ends the probe when the caller stops. + */ +export interface LeaseOwnerProbe { + readonly signal?: AbortSignal; + readonly timeoutMs?: number; +} + /** Recovery finalization retains its operation outcome and every failed owner. */ export class OwnedLeaseCleanupFailure extends ArtifactReaderFailure { override readonly cleanupLeases; @@ -86,6 +105,7 @@ export const acquireOwnedLease = async (input: { readonly directory: string; readonly failure: LeaseFailureFactory; readonly resources?: ArtifactResourceScope | undefined; + readonly probe?: LeaseOwnerProbe; }): Promise => { const produced = new WeakSet(); const cleanupCauses = new WeakMap(); @@ -109,6 +129,7 @@ export const acquireOwnedLease = async (input: { fail, false, resources, + input.probe, ); if (typeof acquisition !== "string") return acquisition; } @@ -122,6 +143,7 @@ export const acquireOwnedLease = async (input: { fail, true, resources, + input.probe, ); if (typeof acquisition !== "string") return acquisition; @@ -138,7 +160,14 @@ export const acquireOwnedLease = async (input: { let primary: unknown; let failed = false; try { - recovered = await tryAcquireLease(socketPath, owner, fail, true, resources); + recovered = await tryAcquireLease( + socketPath, + owner, + fail, + true, + resources, + input.probe, + ); if (recovered === "stale") await rm(socketPath, { force: true }); if (typeof recovered === "string") recovered = await tryAcquireLease( @@ -147,6 +176,7 @@ export const acquireOwnedLease = async (input: { fail, true, resources, + input.probe, ); if (typeof recovered === "string") throw fail({ kind: "unrecoverable" }); } catch (cause: unknown) { @@ -219,6 +249,7 @@ const tryAcquireLease = async ( fail: (failure: LeaseFailure, cause?: unknown) => Error, securePath: boolean, resources: ArtifactResourceScope, + probe?: LeaseOwnerProbe, ): Promise => { const connections = new Set(); const server = createServer((socket) => { @@ -233,7 +264,7 @@ const tryAcquireLease = async ( // alive; process exit leaves a stale socket that later acquirers recover. server.unref(); if (!(await bind(server, socketPath))) { - const existingOwner = await readOwner(socketPath, fail); + const existingOwner = await readOwner(socketPath, fail, probe); return typeof existingOwner === "string" ? existingOwner : { acquired: false, owner: existingOwner }; @@ -382,24 +413,42 @@ const sendOwner = (socket: Socket, owner: LeaseOwner): void => { const readOwner = ( socketPath: string, fail: (failure: LeaseFailure, cause?: unknown) => Error, + probe?: LeaseOwnerProbe, ): Promise => new Promise((resolveOwner, rejectOwner) => { const socket = createConnection(socketPath); socket.setEncoding("utf8"); let response = ""; let settled = false; + let timer: NodeJS.Timeout | undefined; + const timeoutMs = Math.min( + LEASE_OWNER_RESPONSE_TIMEOUT_MS, + probe?.timeoutMs ?? LEASE_OWNER_RESPONSE_TIMEOUT_MS, + ); + const stopWaiting = (): void => { + clearTimeout(timer); + probe?.signal?.removeEventListener("abort", onAbort); + }; const reject = (reason: string, cause?: unknown): void => { if (settled) return; settled = true; - clearTimeout(timer); + stopWaiting(); socket.destroy(); rejectOwner(fail({ kind: "owner_unverified", reason }, cause)); }; - const timer = setTimeout(() => reject("owner response timed out"), 250); + const onAbort = (): void => { + reject(LEASE_OWNER_PROBE_ABORTED, probe?.signal?.reason); + }; + if (probe?.signal?.aborted === true) { + reject(LEASE_OWNER_PROBE_ABORTED, probe.signal.reason); + return; + } + timer = setTimeout(() => reject(LEASE_OWNER_RESPONSE_TIMED_OUT), timeoutMs); + probe?.signal?.addEventListener("abort", onAbort, { once: true }); const finish = (owner: LeaseOwner | "missing" | "stale"): void => { if (settled) return; settled = true; - clearTimeout(timer); + stopWaiting(); socket.destroy(); resolveOwner(owner); }; diff --git a/src/process/capture/ProcessCaptureError.ts b/src/process/capture/ProcessCaptureError.ts index 25f41d9d93f..224ee67cdbc 100644 --- a/src/process/capture/ProcessCaptureError.ts +++ b/src/process/capture/ProcessCaptureError.ts @@ -25,6 +25,7 @@ import { primaryAnalysisError, type AnalysisErrorOptions, } from "../../domain/analysisErrorBase.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import type { PartialProcessCaptureObservation, ProcessCaptureCleanupReport, @@ -122,6 +123,51 @@ export class ProcessCaptureError extends AnalysisError { } } +/** + * One `retryCleanup` promise rejects with one error, so overlapping closes + * observe that same instance. A close's completed facts have to live on a + * follower: writing them onto the shared error makes every close report them. + * The follower stays incomplete while this error's cleanup does. + */ +export const processCaptureFailureForClose = ( + error: AnalysisError, +): AnalysisError => { + if (!(error instanceof ProcessCaptureError)) return error; + const reported = new ProcessCaptureError(error.message, { + cleanupPrimary: error, + ...(error.cause === undefined ? {} : { cause: error.cause }), + ...(error.userMessage === undefined + ? {} + : { userMessage: error.userMessage }), + ...(error.userCategory === undefined + ? {} + : { userCategory: error.userCategory }), + reason: error.reason, + ...(error.executionFailure === undefined + ? {} + : { executionFailure: error.executionFailure }), + ...(error.cleanup === undefined ? {} : { cleanup: error.cleanup }), + ...(error.cleanupReport === undefined + ? {} + : { cleanupReport: error.cleanupReport }), + ...(error.partialObservation === undefined + ? {} + : { partialObservation: error.partialObservation }), + ...(error.capturedOutput === undefined + ? {} + : { capturedOutput: error.capturedOutput }), + ...(error.retryable ? { retryable: true } : {}), + }); + // The follower completes when this cleanup does. It is not either source, + // so composition records that dependency on the follower. + return analysisErrorWithCleanupDependencies( + error, + error, + "close_binary", + () => reported, + ); +}; + /** Return one non-recursive, domain-neutral summary of an execution failure. */ export const describeProcessCaptureExecutionFailure = ( failure: unknown, diff --git a/src/providers/AnalysisClientCleanup.test.ts b/src/providers/AnalysisClientCleanup.test.ts index 2184d9ebc08..764d2ef32c6 100644 --- a/src/providers/AnalysisClientCleanup.test.ts +++ b/src/providers/AnalysisClientCleanup.test.ts @@ -222,3 +222,36 @@ it("retains the latest close options across concurrent close() calls", async () await Promise.all([acquiring, close1, close2]); expect(seenOptions).toEqual([options2]); }); + +it("keeps the client's own close advice and limit on the retained close failure", async () => { + const advice = "Close again to discard the unsaved edits."; + const limit = { + control_kind: "environment", + environment: "REA_FIXTURE_WAIT_MS", + effective_value: 100, + unit: "ms", + minimum: 50, + maximum: 1_000, + default_value: 500, + applies_at: "next_startup", + } as const; + const refused = new ProviderCleanupError( + "fixture", + ["client"], + {}, + { remediationAction: advice, limit }, + ); + let closes = 0; + const creation = new AnalysisClientCreation("fixture", async () => ({ + execute: clientClosingWith(refused).execute, + close: async () => ((closes += 1) === 1 ? err(refused) : ok(null)), + })); + expect((await creation.acquire("open")).ok).toBe(true); + const closed = await creation.close(); + if (closed.ok) throw new Error("the refused close unexpectedly succeeded"); + expect(closed.error).toMatchObject({ remediationAction: advice }); + const projected = projectAnalysisError(closed.error); + expect(projected.remediation.action).toContain(advice); + expect(projected.details?.limit).toEqual(limit); + expect(await creation.close()).toEqual(ok(null)); +}); diff --git a/src/providers/AnalysisClientCleanup.ts b/src/providers/AnalysisClientCleanup.ts index ffa64548e0c..dbe75a3195c 100644 --- a/src/providers/AnalysisClientCleanup.ts +++ b/src/providers/AnalysisClientCleanup.ts @@ -5,6 +5,7 @@ import { type AnalysisCleanupReleaseClaim, } from "../domain/analysisErrorBase.js"; import type { AnalysisClient } from "../ports/AnalysisProvider.js"; +import type { EngineCloseReport } from "../domain/engineCloseReport.js"; /** Close one provider client and normalize unexpected adapter rejection. */ export const closeAnalysisClient = async ( @@ -12,7 +13,7 @@ export const closeAnalysisClient = async ( providerId: string, options: Parameters[0] = {}, closeRejectionRelease?: AnalysisCleanupReleaseClaim, -): Promise> => { +): Promise> => { // Nested/composite clients report failures before their final result settles. // Own notification identity for this close attempt, including the fallback // for clients that only return or reject with their cleanup failure. @@ -22,7 +23,7 @@ export const closeAnalysisClient = async ( reported.add(failure); options.onCleanupFailure?.(failure); }; - let result: Result; + let result: Result; try { result = await client.close({ ...options, diff --git a/src/providers/AnalysisClientCreation.ts b/src/providers/AnalysisClientCreation.ts index a87f41431b8..8a10e72dc80 100644 --- a/src/providers/AnalysisClientCreation.ts +++ b/src/providers/AnalysisClientCreation.ts @@ -25,6 +25,18 @@ import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCle import { err, ok, type Result } from "../domain/result.js"; import { SharedStartupAttempt } from "../process/SharedStartupAttempt.js"; import { closeAnalysisClient } from "./AnalysisClientCleanup.js"; +import { + retainCloseOutcome, + type EngineCloseReport, +} from "../domain/engineCloseReport.js"; + +interface ClientLease { + readonly client: AnalysisClient; + readonly lease: AnalysisCleanupLease; + /** The releasing close's report until a release outcome takes it. */ + report?: EngineCloseReport | null; + failure?: AnalysisError; +} /** Own deferred client creation while callers wait independently and close joins it. */ export class AnalysisClientCreation { @@ -40,14 +52,10 @@ export class AnalysisClientCreation { * The close owner of one exact client, and the failure its last close * produced. External cleanup can settle that failure without the lease. */ - #clientLease: - | { - readonly client: AnalysisClient; - readonly lease: AnalysisCleanupLease; - failure?: AnalysisError; - } + #clientLease: ClientLease | undefined; + #closing: + | Promise> | undefined; - #closing: Promise> | undefined; #closeOptions: Parameters[0]; constructor( @@ -219,7 +227,7 @@ export class AnalysisClientCreation { close( options?: Parameters[0], - ): Promise> { + ): Promise> { this.#closed = true; this.#closeOptions = options; this.#attempt?.close(); @@ -233,17 +241,24 @@ export class AnalysisClientCreation { ? undefined : inspections.error; const closed = await this.#releaseClient(this.#closeOptions); + // What the client's close completed stays with this close's outcome. if (!closed.ok && inspectionFailure !== undefined) return err( - analysisErrorWithCleanupDependencies( - closed.error, - inspectionFailure, - "create_analysis_client", + retainCloseOutcome( + analysisErrorWithCleanupDependencies( + closed.error, + inspectionFailure, + "create_analysis_client", + ), + closed, ), ); if (!closed.ok) return closed; - if (inspectionFailure !== undefined) return err(inspectionFailure); - return this.#failure?.cleanupIncomplete ? err(this.#failure) : ok(null); + if (inspectionFailure !== undefined) + return err(retainCloseOutcome(inspectionFailure, closed)); + return this.#failure?.cleanupIncomplete + ? err(retainCloseOutcome(this.#failure, closed)) + : closed; }) .finally(() => { this.#closing = undefined; @@ -253,27 +268,35 @@ export class AnalysisClientCreation { async #releaseClient( options: Parameters[0], - ): Promise> { + ): Promise> { if (this.#client === undefined) return ok(null); const client = this.#client; if (options !== undefined) this.#closeOptions = options; if (this.#clientLease?.client !== client) this.#clientLease = undefined; - this.#clientLease ??= { - client, - lease: new AnalysisCleanupLease(async () => { - const result = await closeAnalysisClient( - client, - this.providerId, - this.#closeOptions, - ); - if (!result.ok) throw result.error; - }), - }; + // The lease owns release; the report of the close that released the + // client is handed to one release outcome. + if (this.#clientLease === undefined) { + const created: ClientLease = { + client, + lease: new AnalysisCleanupLease(async () => { + const result = await closeAnalysisClient( + client, + this.providerId, + this.#closeOptions, + ); + if (!result.ok) throw result.error; + created.report = result.value; + }), + }; + this.#clientLease = created; + } const entry = this.#clientLease; const clientLease = entry.lease; try { await clientLease.release(); - return ok(null); + const report = entry.report ?? null; + entry.report = null; + return ok(report); } catch (cause: unknown) { const failure = new ProviderCleanupError( this.providerId, @@ -287,7 +310,20 @@ export class AnalysisClientCreation { ? { client_close_failure: projectAnalysisError(cause) } : {}), }, - { cause, operation: "create_analysis_client" }, + { + cause, + operation: "create_analysis_client", + // The client knows what its retained close needs; keep that advice + // and the control that stopped the close on the failure the caller + // reads. + ...(cause instanceof ProviderAdapterError && + cause.remediationAction !== undefined + ? { remediationAction: cause.remediationAction } + : {}), + ...(cause instanceof AnalysisError && cause.limit !== undefined + ? { limit: cause.limit } + : {}), + }, ); if (cause instanceof AnalysisError && cause.hasCleanupOwner) { failure.bindCleanupResourceOwner({ @@ -307,7 +343,11 @@ export class AnalysisClientCreation { } clientLease.bindCleanupError(failure); entry.failure = failure; - return err(failure); + return err( + cause instanceof AnalysisError + ? retainCloseOutcome(failure, err(cause)) + : failure, + ); } } } diff --git a/src/providers/DeferredAnalysisClient.ts b/src/providers/DeferredAnalysisClient.ts index 8917097f703..5ab4dad6b31 100644 --- a/src/providers/DeferredAnalysisClient.ts +++ b/src/providers/DeferredAnalysisClient.ts @@ -5,6 +5,7 @@ import type { ProviderRequestActivitySnapshot, } from "../ports/AnalysisProvider.js"; import type { ProviderOperationHealth } from "../domain/providerOperationHealth.js"; +import type { EngineCloseReport } from "../domain/engineCloseReport.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { closedAnalysisClientError, @@ -79,5 +80,9 @@ export class DeferredAnalysisClient implements AnalysisClient { return this.#creation.ownedClient?.operationHealthSnapshot?.(); } + unsavedCloseReport(): EngineCloseReport | null { + return this.#creation.ownedClient?.unsavedCloseReport?.() ?? null; + } + close: AnalysisClient["close"] = (options) => this.#creation.close(options); } diff --git a/src/server/serviceToolBindings.ts b/src/server/serviceToolBindings.ts index fb146c617bc..bd64e23c28f 100644 --- a/src/server/serviceToolBindings.ts +++ b/src/server/serviceToolBindings.ts @@ -679,13 +679,11 @@ const SERVICE_TOOL_BINDINGS = { await reportOperationEnd(progress, "close_binary", closed.ok); return closed; } - const closing = close( - () => - session.closeWithSnapshot(snapshotPath, input.overwrite, { - progress, - cleanupRetry: CLOSE_RETRY, - }), - (receipt) => receipt, + const closing = close(() => + session.closeWithSnapshot(snapshotPath, input.overwrite, { + progress, + cleanupRetry: CLOSE_RETRY, + }), ); await reportOperationStart( progress, diff --git a/src/server/sessionLifecycle.test.ts b/src/server/sessionLifecycle.test.ts new file mode 100644 index 00000000000..1e489f4759e --- /dev/null +++ b/src/server/sessionLifecycle.test.ts @@ -0,0 +1,101 @@ +import { expect, it } from "vitest"; + +import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; +import type { EngineCloseReport } from "../domain/engineCloseReport.js"; +import { err, ok } from "../domain/result.js"; +import { silentLogger } from "../logger.js"; +import type { PartialProcessCaptureObservation } from "../domain/process/processCapture.js"; +import { ProcessCaptureError } from "../process/capture/ProcessCaptureError.js"; +import { closeWithProcessResources } from "./sessionLifecycle.js"; + +const discarded = { + checkpoint: { + status: "discarded", + reason: "superseded", + directory: "/checkpoints", + }, +} as const satisfies EngineCloseReport; + +it("reports a discard on the close that released the edits, not on a close sharing its cleanup failure", async () => { + const cleanup = new ProcessCaptureError( + "Process capture cleanup remains incomplete: denied", + { + reason: "cleanup_incomplete", + executionFailure: "denied", + cleanup: { + reason: "denied", + resources: ["process_capture_resources"], + }, + }, + ); + let release: () => void = () => undefined; + const started = new Promise((resolve) => { + release = resolve; + }); + const close = closeWithProcessResources({ + logger: silentLogger, + closeProcessResources: () => started.then(() => err(cleanup)), + }); + const releasing = close(async () => ok(discarded)); + const other = close(async () => ok(null)); + release(); + const [released, untouched] = await Promise.all([releasing, other]); + if (released.ok || untouched.ok) + throw new Error("shared cleanup failure was not reported"); + expect(projectAnalysisError(released.error)).toMatchObject({ + code: "cleanup_incomplete", + recovery: { kind: "retry_cleanup", operation: "close_binary" }, + details: { + execution_failure: "denied", + resources: ["process_capture_resources"], + partial_observation: discarded, + }, + }); + expect(projectAnalysisError(untouched.error)).toMatchObject({ + code: "cleanup_incomplete", + recovery: { kind: "retry_cleanup", operation: "close_binary" }, + details: { + execution_failure: "denied", + resources: ["process_capture_resources"], + }, + }); + expect( + projectAnalysisError(untouched.error).details?.partial_observation, + ).toBeUndefined(); + expect(cleanup.partialObservation).toBeUndefined(); + expect(released.error).not.toBe(untouched.error); +}); + +it("keeps a process capture's collected facts on the close that reports them", async () => { + const captured = { + scenario_id: "cap-kept", + } as unknown as PartialProcessCaptureObservation; + const cleanup = new ProcessCaptureError( + "Process capture cleanup remains incomplete: denied", + { + reason: "cleanup_incomplete", + executionFailure: "denied", + partialObservation: captured, + cleanup: { + reason: "denied", + resources: ["process_capture_resources"], + }, + }, + ); + const close = closeWithProcessResources({ + logger: silentLogger, + closeProcessResources: async () => err(cleanup), + }); + const closed = await close(async () => ok(discarded)); + if (closed.ok) throw new Error("shared cleanup failure was not reported"); + expect(projectAnalysisError(closed.error)).toMatchObject({ + code: "cleanup_incomplete", + details: { + partial_observation: { + checkpoint: discarded.checkpoint, + cleanup_observation: { scenario_id: "cap-kept" }, + }, + }, + }); + expect(cleanup.partialObservation).toEqual({ scenario_id: "cap-kept" }); +}); diff --git a/src/server/sessionLifecycle.ts b/src/server/sessionLifecycle.ts index 634069f214b..838e71f69ef 100644 --- a/src/server/sessionLifecycle.ts +++ b/src/server/sessionLifecycle.ts @@ -2,14 +2,15 @@ import type { Logger } from "pino"; import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js"; import { - retainSavedAnalysisSnapshot, - type SavedAnalysisSnapshot, -} from "../domain/savedAnalysisSnapshot.js"; + retainCloseOutcome, + type CloseValue, +} from "../domain/engineCloseReport.js"; import { err, ok, type Result } from "../domain/result.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import type { AnalysisCleanupRetry } from "../domain/analysisErrorRecovery.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; +import { processCaptureFailureForClose } from "../process/capture/ProcessCaptureError.js"; import { errorMessage } from "../kernel/errorMessage.js"; import { ArtifactReaderFailure, @@ -50,16 +51,16 @@ const retainedProcessCleanup = (error: AnalysisError): AnalysisError => /** * Close the session together with the process-capture resources it owns. * Both settle; a failed resource cleanup is kept for the next close_binary, - * and a saved snapshot stays reported when only the resources failed. + * and what the session close completed (a saved snapshot, engine state + * released unsaved) stays reported when only the resources failed. */ export const closeWithProcessResources = ({ logger, closeProcessResources, }: Pick) => - async ( + async ( closeSession: () => Promise>, - savedSnapshot?: (value: Value) => SavedAnalysisSnapshot, ): Promise> => { const [sessionClose, resourceClose] = await Promise.allSettled([ closeResult(closeSession), @@ -85,9 +86,9 @@ export const closeWithProcessResources = const resources = resourceClose.value; if (!closed.ok) { if (resources.ok) return closed; - const combined = analysisErrorWithCleanupDependencies( - closed.error, - resources.error, + const combined = retainCloseOutcome( + analysisErrorWithCleanupDependencies(closed.error, resources.error), + closed, ); // The session offers a retry only after retiring its target; a failed // save keeps that target open and needs its own recovery first. @@ -98,11 +99,14 @@ export const closeWithProcessResources = ); } if (resources.ok) return closed; - const retained = retainedProcessCleanup(resources.error); + // The session closed: its snapshot and released-engine facts stay true. + // Those facts are this close's. The cleanup error is shared with any + // other close awaiting the same retry, so they are attached to a follower. return err( - savedSnapshot === undefined - ? retained - : retainSavedAnalysisSnapshot(retained, savedSnapshot(closed.value)), + retainCloseOutcome( + retainedProcessCleanup(processCaptureFailureForClose(resources.error)), + closed, + ), ); }; diff --git a/tests/boundary/mcp/closeBinaryCheckpointDiscardMcp.test.ts b/tests/boundary/mcp/closeBinaryCheckpointDiscardMcp.test.ts new file mode 100644 index 00000000000..07fd0799fed --- /dev/null +++ b/tests/boundary/mcp/closeBinaryCheckpointDiscardMcp.test.ts @@ -0,0 +1,244 @@ +import { dirname, join } from "node:path"; + +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import type { CallToolResult } from "@modelcontextprotocol/client"; +import { expect, it, vi } from "vitest"; + +import { toolContract } from "../../../src/contracts/toolContracts.js"; +import { + retainCloseOutcome, + type EngineCloseReport, +} from "../../../src/domain/engineCloseReport.js"; +import { err, ok } from "../../../src/domain/result.js"; +import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js"; +import { connectGhidraMcp } from "./ghidraMcpHarness.js"; +import type { AnalysisProvider } from "../../../src/ports/AnalysisProvider.js"; +import { createServer } from "../../../src/server/createServer.js"; +import { + createBinarySessionTargets, + createCacheProvider, + createTestBinarySession, +} from "../../fixtures/binarySession.js"; +import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { ProcessCaptureResourceScope } from "../../../src/process/capture/ProcessCaptureLifecycle.js"; + +const discarded: EngineCloseReport = { + checkpoint: { + status: "discarded", + reason: "superseded", + directory: "/checkpoints/target", + }, +}; + +/** An engine whose next close releases edits a superseded save refused. */ +const discardingProvider = (): AnalysisProvider => { + const provider = createCacheProvider([]); + return { + ...provider, + createClient: (...args) => { + const client = provider.createClient(...args); + let reported = false; + return { + ...client, + unsavedCloseReport: () => (reported ? null : discarded), + close: () => { + const report = reported ? null : discarded; + reported = true; + return Promise.resolve(ok(report)); + }, + }; + }, + }; +}; + +it("reports a close that released refused checkpoint edits, with and without a snapshot", async () => { + const [target] = await createBinarySessionTargets(); + const session = createTestBinarySession(discardingProvider()); + const server = createServer({ kind: "session", session }); + const client = new Client( + { name: "close-binary-discard", version: "1" }, + { jsonSchemaValidator: createMcpSchemaValidation() }, + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + const call = async (name: string, arguments_: Record) => { + const result = await client.callTool({ name, arguments: arguments_ }); + expect(result.isError, JSON.stringify(result.content)).not.toBe(true); + return result.structuredContent; + }; + const closeResult = (value: unknown) => + toolContract("close_binary").outputSchema.parse(value).result; + try { + await server.connect(serverTransport); + await client.connect(clientTransport); + // The engine starts with the first analysis, not at open. + await call("open_binary", { path: target }); + await call("address_name", { address: "0x1000" }); + expect(closeResult(await call("close_binary", {}))).toEqual(discarded); + + // A snapshot saved before the close keeps its receipt beside the report. + await call("open_binary", { path: target }); + await call("address_name", { address: "0x1000" }); + const snapshot = join(dirname(target), "snapshot.json"); + expect( + closeResult(await call("close_binary", { snapshot_path: snapshot })), + ).toMatchObject({ path: snapshot, ...discarded }); + } finally { + await Promise.allSettled([client.close(), server.close(), session.close()]); + } +}); + +it("keeps an ordinary close result null", async () => { + const [target] = await createBinarySessionTargets(); + const session = createTestBinarySession(createCacheProvider([])); + const server = createServer({ kind: "session", session }); + const client = new Client( + { name: "close-binary-null", version: "1" }, + { jsonSchemaValidator: createMcpSchemaValidation() }, + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + try { + await server.connect(serverTransport); + await client.connect(clientTransport); + await client.callTool({ name: "open_binary", arguments: { path: target } }); + const closed = await client.callTool({ + name: "close_binary", + arguments: {}, + }); + expect(closed.structuredContent).toEqual({ result: null }); + } finally { + await Promise.allSettled([client.close(), server.close(), session.close()]); + } +}); + +const connected = async (provider: AnalysisProvider) => { + const targets = await createBinarySessionTargets(); + const session = createTestBinarySession(provider); + const server = createServer({ kind: "session", session }); + const client = new Client( + { name: "close-binary-discard-paths", version: "1" }, + { jsonSchemaValidator: createMcpSchemaValidation() }, + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + const call = async (name: string, arguments_: Record) => + (await client.callTool({ name, arguments: arguments_ })) as CallToolResult; + return { + targets, + call, + dispose: () => + Promise.allSettled([client.close(), server.close(), session.close()]), + }; +}; + +it("refuses to replace a session whose edits would be released unsaved, until close_binary reports it", async () => { + const { targets, call, dispose } = await connected(discardingProvider()); + const [first, second] = targets; + try { + expect((await call("open_binary", { path: first })).isError).not.toBe(true); + expect( + (await call("address_name", { address: "0x1000" })).isError, + ).not.toBe(true); + const refused = await call("open_binary", { path: second }); + expect(refused.isError).toBe(true); + expect(parseMcpToolError(refused).error).toMatchObject({ + code: "capability_unavailable", + remediation: { + action: expect.stringMatching(/^Call close_binary first/), + }, + }); + // The refused open kept the session and its engine. + expect( + (await call("address_name", { address: "0x1000" })).isError, + ).not.toBe(true); + const closed = await call("close_binary", {}); + expect( + toolContract("close_binary").outputSchema.parse(closed.structuredContent) + .result, + ).toEqual(discarded); + expect((await call("open_binary", { path: second })).isError).not.toBe( + true, + ); + } finally { + await dispose(); + } +}); + +it("reports released edits on a close whose process-capture cleanup fails", async () => { + const { targets, call, dispose } = await connected(discardingProvider()); + const cleanup = vi + .spyOn(ProcessCaptureResourceScope.prototype, "retryCleanup") + .mockRejectedValueOnce(new Error("Process cleanup failed")); + try { + await call("open_binary", { path: targets[0] }); + await call("address_name", { address: "0x1000" }); + const failed = await call("close_binary", {}); + expect(failed.isError).toBe(true); + expect( + parseMcpToolError(failed).error.details?.partial_observation, + ).toEqual(discarded); + cleanup.mockRestore(); + const retried = await call("close_binary", {}); + expect(retried.structuredContent).toEqual({ result: null }); + } finally { + cleanup.mockRestore(); + await dispose(); + } +}); + +it("reports a GhidraProvider close's discard through its deferred client, on success and on a cleanup failure", async () => { + const closes = [ + // The JVM stopped and released the edits, then a runtime root remained. + err( + retainCloseOutcome( + new ProviderCleanupError("ghidra", ["/runtime/root"], { + reason: "runtime root removal denied", + }), + discarded, + ), + ), + ok(null), + ok(discarded), + ]; + const harness = await connectGhidraMcp( + "close-binary-ghidra-discard", + undefined, + { + close: () => Promise.resolve(closes.shift() ?? ok(null)), + }, + ); + const call = (name: string, arguments_: Record) => + harness.mcp.callTool({ + name, + arguments: arguments_, + }) as Promise; + try { + // The engine starts with the first analysis, not at open. + expect( + (await call("address_name", { address: "0x401000" })).isError, + ).not.toBe(true); + const failed = await call("close_binary", {}); + expect(failed.isError).toBe(true); + expect( + parseMcpToolError(failed).error.details?.partial_observation, + ).toEqual(discarded); + // The retry releases the rest and does not report the discard again. + expect((await call("close_binary", {})).structuredContent).toEqual({ + result: null, + }); + + await call("open_binary", { path: process.execPath }); + await call("address_name", { address: "0x401000" }); + const closed = await call("close_binary", {}); + expect( + toolContract("close_binary").outputSchema.parse(closed.structuredContent) + .result, + ).toEqual(discarded); + } finally { + await harness.close(); + } +}); diff --git a/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts b/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts index febc5cd8427..b5f1a7202a2 100644 --- a/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts +++ b/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts @@ -2,8 +2,15 @@ import { once } from "node:events"; import { afterEach, expect, it, vi } from "vitest"; import { waitFor } from "../../../support/testWait.js"; import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; -import { createHash } from "node:crypto"; -import { access, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { createHash, randomUUID } from "node:crypto"; +import { + access, + chmod, + readFile, + readdir, + rm, + writeFile, +} from "node:fs/promises"; import { join } from "node:path"; import { ArtifactResourceScope } from "../../../../src/resources/ArtifactResourceScope.js"; @@ -11,13 +18,42 @@ import { createAnalysisProfile } from "../../../../src/domain/analysisProfile.js import { GhidraClient } from "../../../../src/ghidra/GhidraClient.js"; import type { BridgeMaxReplyBytes } from "../../../../src/config/bridgeMaxReplyBytes.js"; import { ConfigurationError } from "../../../../src/domain/configurationErrors.js"; -import { resolveGhidraCheckpoint } from "../../../../src/ghidra/GhidraCheckpoint.js"; +import { + GhidraCheckpoint, + GhidraCheckpointSupersededError, + resolveGhidraCheckpoint, +} from "../../../../src/ghidra/GhidraCheckpoint.js"; +import { err } from "../../../../src/domain/result.js"; +import { ProviderCleanupError } from "../../../../src/domain/providerCleanupError.js"; +import { + GhidraLaunchError, + type GhidraLauncher, +} from "../../../../src/ghidra/GhidraLauncher.js"; import { GhidraFixtureLauncher } from "./ghidraClient.fixture.js"; +import type { GhidraCheckpointSaveWait } from "../../../../src/config/ghidraCheckpointSaveWait.js"; +import { acquireOwnedLease } from "../../../../src/process/OwnedLease.js"; +import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js"; +import { projectSessionError } from "../../../../src/ghidra/GhidraSessionErrorProjection.js"; vi.mock("node:fs/promises", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, rm: vi.fn(actual.rm) }; }); +vi.mock("../../../../src/process/OwnedLease.js", async (importOriginal) => { + const actual = + await importOriginal< + typeof import("../../../../src/process/OwnedLease.js") + >(); + return { ...actual, acquireOwnedLease: vi.fn(actual.acquireOwnedLease) }; +}); +const restoreLeases = async () => { + const actual = await vi.importActual< + typeof import("../../../../src/process/OwnedLease.js") + >("../../../../src/process/OwnedLease.js"); + vi.mocked(acquireOwnedLease) + .mockReset() + .mockImplementation(actual.acquireOwnedLease); +}; const clients: GhidraClient[] = [], launchers: GhidraFixtureLauncher[] = []; @@ -27,6 +63,7 @@ afterEach(async () => { "node:fs/promises", ); vi.mocked(rm).mockReset().mockImplementation(actual.rm); + await restoreLeases(); for (const launcher of launchers.splice(0)) for (const child of launcher.processes) if (child.connected) child.send("release_checkpoint"); @@ -97,6 +134,46 @@ async function fixture( return { root, selection, launcher, client, targetPath, sha256 }; } +/** Another session on the same target, selecting the checkpoint as it is now. */ +async function peer( + f: Awaited>, + launcher: GhidraLauncher = fixtureLauncher(), + checkpointSaveWait?: GhidraCheckpointSaveWait, +) { + const selection = await resolveGhidraCheckpoint( + f.root, + f.sha256, + profile, + new ArtifactResourceScope(), + ); + const client = new GhidraClient({ + launcher, + targetPath: f.targetPath, + targetSha256: f.sha256, + providerVersion: "12.1.4", + profileDigest: profile.digest, + checkpoint: selection, + startupTimeoutMs: 10_000, + ...(checkpointSaveWait === undefined ? {} : { checkpointSaveWait }), + }); + clients.push(client); + return { client, selection }; +} +const packed = async (root: string, contents: string) => { + const path = join(root, `${randomUUID()}.gzf`); + await writeFile(path, contents); + return path; +}; +function fixtureLauncher() { + const launcher = new GhidraFixtureLauncher("checkpoint"); + launchers.push(launcher); + return launcher; +} +const rename = (client: GhidraClient) => + client.callTool("set_address_name", { address: "0x1000", name: "changed" }); +const programs = async (directory: string) => + (await readdir(directory)).filter((name) => name.endsWith(".gzf")); + it.skipIf(process.platform === "win32")( "saves completed initial analysis, leaves an unchanged checkpoint alone, and releases its lease", async () => { @@ -213,35 +290,542 @@ it.skipIf(process.platform === "win32")( ); it.skipIf(process.platform === "win32")( - "does not release a Program or its lease before its final checkpoint acknowledges", + "keeps a Program until its final checkpoint acknowledges while another session restores the same target", async () => { const f = await fixture("checkpoint_hold_close"); expect((await f.client.start()).ok).toBe(true); - await f.client.callTool("set_address_name", { - address: "0x1000", - name: "changed", - }); + await rename(f.client); const closing = f.client.close(); await f.launcher.checkpointHold.reached(closing, "final checkpoint"); expect(f.launcher.processes[0]!.exitCode).toBeNull(); - const selection = await resolveGhidraCheckpoint( - f.root, - f.sha256, - profile, - new ArtifactResourceScope(), + // The stalled save holds no lease a reader needs: a second session + // restores the still-current generation and answers queries. + const other = await peer(f); + expect((await other.client.start()).ok).toBe(true); + expect((await other.client.callTool("list_documents", {})).ok).toBe(true); + expect(other.client.checkpointRestore()?.sha256).toBe( + createHash("sha256").update("fixture checkpoint initial").digest("hex"), ); - const other = new GhidraClient({ - launcher: f.launcher, - targetPath: f.targetPath, - targetSha256: f.sha256, - providerVersion: "12.1.4", - profileDigest: profile.digest, - checkpoint: selection, - }); - clients.push(other); - expect((await other.start()).ok).toBe(false); f.launcher.processes[0]!.send("release_checkpoint"); expect((await closing).ok).toBe(true); + // The reader made no edits, so its close publishes nothing. + const published = await readFile( + join(f.selection.directory, "current.json"), + "utf8", + ); + expect(JSON.parse(published)).toMatchObject({ + source: { kind: "retained" }, + }); + expect((await other.client.close()).ok).toBe(true); + expect( + await readFile(join(f.selection.directory, "current.json"), "utf8"), + ).toBe(published); + }, +); + +it.skipIf(process.platform === "win32")( + "lets two sessions analyze an unseen target at once and publishes its initial checkpoint once", + async () => { + const f = await fixture(); + const other = await peer(f); + const [first, second] = await Promise.all([ + f.client.start(), + other.client.start(), + ]); + expect(first.ok).toBe(true); + expect(second.ok).toBe(true); + expect(f.client.checkpointRestore()).toBeNull(); + expect(other.client.checkpointRestore()).toBeNull(); + const manifest = join(f.selection.directory, "current.json"); + const published = await readFile(manifest, "utf8"); + expect(JSON.parse(published)).toMatchObject({ + source: { kind: "initial-analysis" }, + }); + expect(await programs(f.selection.directory)).toHaveLength(1); + expect((await f.client.callTool("list_documents", {})).ok).toBe(true); + expect((await other.client.callTool("list_documents", {})).ok).toBe(true); + expect((await f.client.close()).ok).toBe(true); + expect((await other.client.close()).ok).toBe(true); + expect(await readFile(manifest, "utf8")).toBe(published); + expect(await programs(f.selection.directory)).toHaveLength(1); + }, +); + +it.skipIf(process.platform === "win32")( + "refuses the later of two edited saves, keeps its session live, then discards on the next close", + async () => { + const f = await fixture(); + expect((await f.client.start()).ok).toBe(true); + const stale = await peer(f); + expect((await stale.client.start()).ok).toBe(true); + expect((await rename(f.client)).ok).toBe(true); + expect((await rename(stale.client)).ok).toBe(true); + expect((await f.client.close()).ok).toBe(true); + const manifest = join(f.selection.directory, "current.json"); + const published = await readFile(manifest, "utf8"); + const files = (await readdir(f.selection.directory)).sort(); + + const refused = await stale.client.close(); + if (refused.ok) throw new Error("the stale save unexpectedly succeeded"); + expect(refused.error.cause).toBeInstanceOf(GhidraCheckpointSupersededError); + expect(refused.error.cause).toMatchObject({ stage: "save" }); + expect(refused.error.diagnostics).toMatchObject({ + reason: expect.stringMatching(/were not saved.*Closing the target again/), + }); + expect(refused.error).toMatchObject({ + remediationAction: expect.stringMatching( + /edits were not saved.*Closing the target again discards/, + ), + }); + expect(await readFile(manifest, "utf8")).toBe(published); + expect((await readdir(f.selection.directory)).sort()).toEqual(files); + // Non-destructive: the refused session still answers from its Program. + expect(stale.client.isReady()).toBe(true); + expect((await stale.client.callTool("list_documents", {})).ok).toBe(true); + + // The refusal is permanent for this generation, so the next close + // releases the session without another export or publication, and says + // that it released the edits unsaved. + expect(await stale.client.close()).toEqual({ + ok: true, + value: { + checkpoint: { + status: "discarded", + reason: "superseded", + directory: f.selection.directory, + }, + }, + }); + // The discard is reported once, by the close that released the edits. + expect(await stale.client.close()).toEqual({ ok: true, value: null }); + expect(await readFile(manifest, "utf8")).toBe(published); + expect((await readdir(f.selection.directory)).sort()).toEqual(files); + expect(refused.error.cleanupResources).toEqual([]); + for (const launcher of launchers) + for (const root of launcher.runtimeRoots) + await expect(access(root)).rejects.toThrow(); + // A reopened session restores the winner's generation. + const reopened = await peer(f); + expect(reopened.selection.state.kind).toBe("retained"); + expect((await reopened.client.start()).ok).toBe(true); + }, +); + +it.skipIf(process.platform === "win32")( + "discards on the next close when a refused save's lease release also failed", + async () => { + const f = await fixture(); + expect((await f.client.start()).ok).toBe(true); + const stale = await peer(f); + expect((await stale.client.start()).ok).toBe(true); + expect((await rename(f.client)).ok).toBe(true); + expect((await rename(stale.client)).ok).toBe(true); + expect((await f.client.close()).ok).toBe(true); + const manifest = join(f.selection.directory, "current.json"); + const published = await readFile(manifest, "utf8"); + const leases = await vi.importActual< + typeof import("../../../../src/process/OwnedLease.js") + >("../../../../src/process/OwnedLease.js"); + vi.mocked(acquireOwnedLease).mockImplementationOnce(async (input) => { + const result = await leases.acquireOwnedLease(input); + if (!result.acquired) return result; + let failed = false; + return { + acquired: true, + lease: { + ...result.lease, + release: async () => { + if (!failed) { + failed = true; + throw new Error("controlled lease release failure"); + } + await result.lease.release(); + }, + }, + }; + }); + const refused = await stale.client.close(); + if (refused.ok) throw new Error("the stale save unexpectedly succeeded"); + // Still the refusal, with the lease failure reported beside it. + expect(refused.error.cause).toBeInstanceOf(GhidraCheckpointSupersededError); + expect(refused.error).toMatchObject({ + remediationAction: expect.stringMatching(/edits were not saved/), + diagnostics: { + carried_cleanup_failure: expect.objectContaining({ + code: expect.any(String), + }), + }, + }); + expect(stale.client.unsavedCloseReport()).toMatchObject({ + checkpoint: { status: "discarded" }, + }); + // The refusal was recorded, so the next close discards instead of + // attempting the impossible save again. + expect(await stale.client.close()).toEqual({ + ok: true, + value: { + checkpoint: { + status: "discarded", + reason: "superseded", + directory: f.selection.directory, + }, + }, + }); + expect(await readFile(manifest, "utf8")).toBe(published); + }, +); + +it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( + "reports released-unsaved edits on the close whose later cleanup fails, and not again on its retry", + async () => { + const f = await fixture(); + expect((await f.client.start()).ok).toBe(true); + const launcher = fixtureLauncher(); + const stale = await peer(f, launcher); + expect((await stale.client.start()).ok).toBe(true); + expect((await rename(f.client)).ok).toBe(true); + expect((await rename(stale.client)).ok).toBe(true); + expect((await f.client.close()).ok).toBe(true); + expect((await stale.client.close()).ok).toBe(false); + expect(stale.client.unsavedCloseReport()).toMatchObject({ + checkpoint: { status: "discarded" }, + }); + // The JVM stops, releasing the edits, and then the runtime root cannot + // be removed: that failure is the close that released them. + const runtimeRoot = launcher.runtimeRoots[0] ?? ""; + await chmod(runtimeRoot, 0o500); + try { + const failed = await stale.client.close(); + if (failed.ok) throw new Error("the runtime root removal succeeded"); + expect(projectAnalysisError(failed.error)).toMatchObject({ + code: "cleanup_incomplete", + details: { + partial_observation: { + checkpoint: { + status: "discarded", + reason: "superseded", + directory: f.selection.directory, + }, + }, + }, + }); + expect(stale.client.unsavedCloseReport()).toBeNull(); + } finally { + await chmod(runtimeRoot, 0o700); + } + expect(await stale.client.close()).toEqual({ ok: true, value: null }); + }, +); + +it.skipIf(process.platform === "win32")( + "reports an initial analysis superseded by another session's edits as a reopen, not as lost edits", + async () => { + const f = await fixture(); + // Another session publishes an initial checkpoint and then edits while + // this session is still analyzing the unseen target. + const analyzing = fixtureLauncher(); + const launcher: GhidraLauncher = { + launch: async (session) => { + const writer = new GhidraCheckpoint( + f.selection, + new ArtifactResourceScope(), + ); + await writer.admit("writer"); + await writer.publish( + await packed(f.root, "initial by another session"), + ); + await writer.publish(await packed(f.root, "edited by another session")); + return analyzing.launch(session); + }, + }; + const late = await peer(f, launcher); + const started = await late.client.start(); + if (started.ok) throw new Error("the superseded initial save succeeded"); + expect(started.error.cause).toBeInstanceOf(GhidraCheckpointSupersededError); + expect(started.error.cause).toMatchObject({ stage: "restore" }); + const projected = projectAnalysisError( + projectSessionError("list_documents", started.error, { + limits: { ghidraStartupTimeoutMs: 10_000 }, + programName: undefined, + source: "owned-checkpoint", + }), + ); + expect(projected).toMatchObject({ + code: "capability_unavailable", + retryable: false, + }); + expect(projected.message).toMatch(/reopen the target/); + expect(projected.message).not.toMatch( + /edits were not saved|again discards/, + ); + // It holds no caller edits, so nothing is reported as released unsaved + // and nothing blocks the reopen the refusal asks for. + expect(late.client.unsavedCloseReport()).toBeNull(); + expect(await late.client.close()).toEqual({ ok: true, value: null }); + const reopened = await peer(f); + expect((await reopened.client.start()).ok).toBe(true); + expect(reopened.client.checkpointRestore()?.sha256).toBe( + createHash("sha256").update("edited by another session").digest("hex"), + ); + }, +); + +it.skipIf(process.platform === "win32")( + "keeps a startup lease-release failure visible beside a superseded initial analysis", + async () => { + const f = await fixture(); + const analyzing = fixtureLauncher(); + const launcher: GhidraLauncher = { + launch: async (session) => { + const writer = new GhidraCheckpoint( + f.selection, + new ArtifactResourceScope(), + ); + await writer.admit("writer"); + await writer.publish( + await packed(f.root, "initial by another session"), + ); + await writer.publish(await packed(f.root, "edited by another session")); + // The late session's own publication lease then fails to release once. + const leases = await vi.importActual< + typeof import("../../../../src/process/OwnedLease.js") + >("../../../../src/process/OwnedLease.js"); + vi.mocked(acquireOwnedLease).mockImplementationOnce(async (input) => { + const result = await leases.acquireOwnedLease(input); + if (!result.acquired) return result; + let failed = false; + return { + acquired: true, + lease: { + ...result.lease, + release: async () => { + if (!failed) { + failed = true; + throw new Error("controlled lease release failure"); + } + await result.lease.release(); + }, + }, + }; + }); + return analyzing.launch(session); + }, + }; + const late = await peer(f, launcher); + const started = await late.client.start(); + if (started.ok) throw new Error("the superseded initial save succeeded"); + expect(started.error.cause).toBeInstanceOf(GhidraCheckpointSupersededError); + // The release failure stays on the startup failure, through the one + // accessor every consumer uses, rather than being dropped. + expect(started.error.cleanupFailure?.cause).toMatchObject({ + message: "controlled lease release failure", + }); + expect((await late.client.close()).ok).toBe(true); + }, +); + +it.skipIf(process.platform === "win32")( + "reports a close that waited out another session's publication with its save-wait limit", + async () => { + const f = await fixture(); + const wait = { waitMs: 100, source: "setting" } as const; + const writer = await peer(f, fixtureLauncher(), wait); + expect((await writer.client.start()).ok).toBe(true); + expect((await rename(writer.client)).ok).toBe(true); + vi.mocked(acquireOwnedLease).mockResolvedValue({ + acquired: false, + owner: { runId: "publisher", processId: 4242 }, + }); + const busy = await writer.client.close(); + await restoreLeases(); + if (busy.ok) throw new Error("the close did not wait for the lease"); + expect(projectAnalysisError(busy.error)).toMatchObject({ + code: "cleanup_incomplete", + remediation: { + action: expect.stringMatching(/^Wait for that session's save/), + }, + details: { + limit: { + control_kind: "environment", + environment: "REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS", + effective_value: 100, + }, + }, + }); + // Contention is retryable: the next close saves the edits. + expect((await writer.client.close()).ok).toBe(true); + expect( + JSON.parse( + await readFile(join(f.selection.directory, "current.json"), "utf8"), + ), + ).toMatchObject({ source: { kind: "retained" } }); + }, +); + +it.skipIf(process.platform === "win32").each([false, true])( + "reports a restore whose packed Program was superseded during launch as a reopen (restore cleanup failed=%s)", + async (cleanupFailed) => { + // The private copy's descriptor close also failed; a later retry released it. + const restoreCleanup = new ProviderCleanupError( + "ghidra", + ["restored-program.gzf"], + { reason: "controlled descriptor close failure" }, + ).bindCleanupReleaseClaim({ cleanupReleased: true }); + const f = await fixture(); + expect((await f.client.start()).ok).toBe(true); + expect((await f.client.close()).ok).toBe(true); + // The launcher's private copy finds the file removed by a publication + // that completed after this session's admission. + const launcher: GhidraLauncher = { + launch: async (session) => { + const writer = new GhidraCheckpoint( + stale.selection, + new ArtifactResourceScope(), + ); + await writer.admit("writer"); + const edited = join(f.root, "edited.gzf"); + await writeFile(edited, "edited by another session"); + await writer.publish(edited); + await expect(access(session.packedProgram!.path)).rejects.toThrow(); + return err( + new GhidraLaunchError( + "Ghidra checkpoint changed before its private import; reopen the target.", + { + checkpointRestoreFailed: true, + ...(cleanupFailed ? { cleanupFailure: restoreCleanup } : {}), + }, + ), + ); + }, + }; + const stale = await peer(f, launcher); + const started = await stale.client.start(); + if (started.ok) throw new Error("the superseded restore succeeded"); + expect(started.error.kind).toBe("checkpoint"); + expect(started.error.cause).toBeInstanceOf(GhidraCheckpointSupersededError); + expect(started.error.cause).toMatchObject({ stage: "restore" }); + // The reopen explanation keeps the launcher's restore cleanup failure. + if (cleanupFailed) + expect(started.error.cleanupFailure).toBe(restoreCleanup); + else expect(started.error.cleanupFailure).toBeUndefined(); + expect((await stale.client.close()).ok).toBe(true); + const reopened = await peer(f); + expect((await reopened.client.start()).ok).toBe(true); + expect(reopened.client.checkpointRestore()?.sha256).toBe( + createHash("sha256").update("edited by another session").digest("hex"), + ); + }, +); + +it.skipIf(process.platform === "win32")( + "keeps a failed manifest read beside the launch error it was explaining", + async () => { + const f = await fixture(); + expect((await f.client.start()).ok).toBe(true); + expect((await f.client.close()).ok).toBe(true); + const manifestClose = new ProviderCleanupError("ghidra", ["current.json"], { + reason: "manifest descriptor close failed", + }); + const explain = vi + .spyOn(GhidraCheckpoint.prototype, "supersededRestore") + .mockRejectedValueOnce(manifestClose); + const launcher: GhidraLauncher = { + launch: async () => + err( + new GhidraLaunchError( + "Ghidra checkpoint changed before its private import; reopen the target.", + { checkpointRestoreFailed: true }, + ), + ), + }; + const stale = await peer(f, launcher); + const started = await stale.client.start(); + explain.mockRestore(); + if (started.ok) throw new Error("the restore explanation succeeded"); + expect(started.error.kind).toBe("start"); + expect(started.error.cleanupFailure).toBe(manifestClose); + expect(started.error.cause).not.toBeInstanceOf( + GhidraCheckpointSupersededError, + ); + }, +); + +it.skipIf(process.platform === "win32")( + "retries startup after a manifest read that owns no cleanup", + async () => { + const f = await fixture(); + expect((await f.client.start()).ok).toBe(true); + expect((await f.client.close()).ok).toBe(true); + const unreadable = new ConfigurationError( + "checkpoint directory unreadable", + { + settings: [ + { + setting: "REA_GHIDRA_CHECKPOINT_DIR", + constraint: "directory unreadable", + }, + ], + }, + ); + const explain = vi + .spyOn(GhidraCheckpoint.prototype, "supersededRestore") + .mockRejectedValue(unreadable); + let launches = 0; + const launcher: GhidraLauncher = { + launch: async () => { + launches += 1; + return err( + new GhidraLaunchError( + "Ghidra checkpoint changed before its private import; reopen the target.", + { checkpointRestoreFailed: true }, + ), + ); + }, + }; + const stale = await peer(f, launcher); + const first = await stale.client.start(); + const second = await stale.client.start(); + explain.mockRestore(); + if (first.ok || second.ok) + throw new Error("the manifest read was treated as a successful start"); + expect(first.error.kind).toBe("start"); + expect(first.error.cleanupFailure).toBeUndefined(); + expect(first.error.secondaryFailures).toContain(unreadable); + expect(second.error.secondaryFailures).toContain(unreadable); + expect(launches).toBe(2); + }, +); + +it.skipIf(process.platform === "win32")( + "keeps a launch failure after a restored copy even when another session saved meanwhile", + async () => { + const f = await fixture(); + expect((await f.client.start()).ok).toBe(true); + expect((await f.client.close()).ok).toBe(true); + // The private copy succeeded; a later launch stage fails while another + // session publishes. That failure is not a superseded restore. + const launcher: GhidraLauncher = { + launch: async () => { + const writer = new GhidraCheckpoint( + stale.selection, + new ArtifactResourceScope(), + ); + await writer.admit("writer"); + const edited = join(f.root, "edited.gzf"); + await writeFile(edited, "edited by another session"); + await writer.publish(edited); + return err(new GhidraLaunchError("controlled JVM start failure")); + }, + }; + const stale = await peer(f, launcher); + const started = await stale.client.start(); + if (started.ok) throw new Error("the failed launch succeeded"); + expect(started.error.kind).toBe("start"); + expect(started.error.message).toContain("controlled JVM start failure"); + expect(started.error.cause).not.toBeInstanceOf( + GhidraCheckpointSupersededError, + ); + expect((await stale.client.close()).ok).toBe(true); }, ); @@ -320,6 +904,65 @@ it.skipIf(process.platform === "win32")( }, ); +it + .skipIf(process.platform === "win32") + .each([ + "while the save polls the lease", + "as soon as the close starts", + ] as const)( + "ends a graceful close's wait for another session's lease when a cancellation forces a stop %s", + async (timing) => { + const f = await fixture("checkpoint_hang_tool"); + // The wait would otherwise outlast this test by minutes. + const waiting = await peer(f, f.launcher, { + waitMs: 600_000, + source: "setting", + }); + expect((await waiting.client.start()).ok).toBe(true); + expect((await rename(waiting.client)).ok).toBe(true); + const controller = new AbortController(); + const active = waiting.client.callTool( + "list_documents", + {}, + { signal: controller.signal }, + ); + await waitFor(() => + expect(f.launcher.requests).toContain("list_documents"), + ); + vi.mocked(acquireOwnedLease) + .mockClear() + .mockResolvedValue({ + acquired: false, + owner: { runId: "publisher", processId: 4242 }, + }); + const closing = waiting.client.close(); + // Either the export finished and the save is polling the publisher's + // lease, or the forced stop arrives before the save has started at all. + if (timing === "while the save polls the lease") + await waitFor(() => + expect(vi.mocked(acquireOwnedLease).mock.calls.length).toBeGreaterThan( + 1, + ), + ); + const started = Date.now(); + controller.abort(new Error("caller stopped waiting")); + const [cancelled, closed] = await Promise.all([active, closing]); + await restoreLeases(); + expect(Date.now() - started).toBeLessThan(10_000); + expect(cancelled).toMatchObject({ ok: false }); + // The graceful close did not publish; the forced stop released the session. + expect(closed).toMatchObject({ ok: false }); + expect( + JSON.parse( + await readFile(join(f.selection.directory, "current.json"), "utf8"), + ), + ).toMatchObject({ source: { kind: "initial-analysis" } }); + const child = f.launcher.processes.at(-1)!; + if (child.exitCode === null && child.signalCode === null) + await once(child, "exit"); + }, +); + it.skipIf(process.platform === "win32")( "stops the process when a caller cancels during a graceful close stalled on its checkpoint", async () => { diff --git a/tests/boundary/providers/ghidra/ghidraClient.fixture.ts b/tests/boundary/providers/ghidra/ghidraClient.fixture.ts index b231a9efa36..fe1340fb138 100644 --- a/tests/boundary/providers/ghidra/ghidraClient.fixture.ts +++ b/tests/boundary/providers/ghidra/ghidraClient.fixture.ts @@ -22,6 +22,7 @@ type FixtureMode = | "checkpoint_hold_startup" | "checkpoint_hold_close" | "checkpoint_hold_close_hang_tool" + | "checkpoint_hang_tool" | "unicode_search" | "reject_first_connection" | "reject_all_connections" diff --git a/tests/boundary/providers/ghidra/ghidraLauncher.test.ts b/tests/boundary/providers/ghidra/ghidraLauncher.test.ts index 7efd12a6c51..97ed6390df6 100644 --- a/tests/boundary/providers/ghidra/ghidraLauncher.test.ts +++ b/tests/boundary/providers/ghidra/ghidraLauncher.test.ts @@ -1663,7 +1663,8 @@ describe("Ghidra checkpoint restore", () => { }, { resourceScope: createTestArtifactResourceScope() }, ); - expect(tampered.ok).toBe(false); + if (tampered.ok) throw new Error("the tampered restore launched"); + expect(tampered.error).toMatchObject({ checkpointRestoreFailed: true }); expect(spawned).toHaveLength(1); }, ); diff --git a/tests/composition/analysis-sessions/binarySessionCleanupRetry.test.ts b/tests/composition/analysis-sessions/binarySessionCleanupRetry.test.ts index 19061f70a04..1266c7c5c08 100644 --- a/tests/composition/analysis-sessions/binarySessionCleanupRetry.test.ts +++ b/tests/composition/analysis-sessions/binarySessionCleanupRetry.test.ts @@ -535,3 +535,54 @@ it("lets an unowned close failure read the later successful close", async () => expect((await session.close()).ok).toBe(true); expect(failed.error.cleanupIncomplete).toBe(false); }); + +it("reports released-unsaved edits on a close whose session file cleanup fails", async () => { + const [first] = await createBinarySessionTargets(); + const cache = createCacheProvider([]); + const discarded = { + checkpoint: { + status: "discarded", + reason: "superseded", + directory: "/checkpoints/target", + }, + } as const; + let released = false; + const provider: AnalysisProvider = { + ...cache, + createClient: (...arguments_) => ({ + ...cache.createClient(...arguments_), + close: async () => { + const report = released ? null : discarded; + released = true; + return resultOk(report); + }, + }), + }; + const session = createTestBinarySession(provider); + let releaseFile = false; + onTestFinished(async () => { + releaseFile = true; + await session.close(); + }); + expect((await session.open(first)).ok).toBe(true); + expect((await session.execute("address_name", {})).ok).toBe(true); + session.resourceScope.retain( + { + close: async () => { + if (!releaseFile) throw new Error("retained descriptor close denied"); + }, + cleanupResources: ["session-file"], + }, + "session-file", + ); + // The engine closes, releasing its edits; the session's own file does not. + const closed = await session.close({ cleanupRetry: CLOSE_RETRY }); + if (closed.ok) throw new Error("Expected retained file cleanup"); + expect(projectAnalysisError(closed.error).details).toMatchObject({ + partial_observation: discarded, + }); + releaseFile = true; + expect(await session.close({ cleanupRetry: CLOSE_RETRY })).toEqual( + resultOk(null), + ); +}); diff --git a/tests/composition/analysis-sessions/compositeProvider.test.ts b/tests/composition/analysis-sessions/compositeProvider.test.ts index 181f104cf79..1f012038021 100644 --- a/tests/composition/analysis-sessions/compositeProvider.test.ts +++ b/tests/composition/analysis-sessions/compositeProvider.test.ts @@ -6,6 +6,7 @@ import { } from "../../fixtures/binarySession.js"; import { CompositeProvider } from "../../../src/application/binary/CompositeProvider.js"; import type { + AnalysisClient, AnalysisOperation, AnalysisProvider, CapabilityDescriptor, @@ -13,7 +14,10 @@ import type { } from "../../../src/ports/AnalysisProvider.js"; import { createAnalysisExecution } from "../../../src/ports/AnalysisProvider.js"; import type { BinaryTarget } from "../../../src/domain/binaryTargetTypes.js"; -import { ok } from "../../../src/domain/result.js"; +import { err, ok } from "../../../src/domain/result.js"; +import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; +import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js"; +import type { EngineCloseReport } from "../../../src/domain/engineCloseReport.js"; import { createStubHopperProject } from "../../fixtures/hopperProjectFile.js"; const target: BinaryTarget = { @@ -56,6 +60,39 @@ describe("composite analysis provider", () => { expect(starts).toEqual(["hopper", "native"]); }); + it("reports a child's released-unsaved edits on the close that a sibling's cleanup fails", async () => { + const discarded: EngineCloseReport = { + checkpoint: { + status: "discarded", + reason: "superseded", + directory: "/checkpoints/target", + }, + }; + const starts: string[] = []; + const ghidra = provider("ghidra", "analyze_function", starts, [ + ok(discarded), + ]); + const sibling = provider("hopper", "address_name", starts, [ + err( + new ProviderCleanupError("hopper", ["hopper-document"], { + reason: "controlled sibling cleanup failure", + }), + ), + ]); + const client = new CompositeProvider([ghidra, sibling]).createClient( + target, + ); + await client.execute("analyze_function", {}); + await client.execute("address_name", {}); + const failed = await client.close(); + if (failed.ok) throw new Error("the sibling cleanup failure was lost"); + // The released child is skipped on retry, so this failure must say so. + expect(projectAnalysisError(failed.error).details).toMatchObject({ + partial_observation: discarded, + }); + expect(await client.close()).toEqual(ok(null)); + }); + it("rejects ambiguous provider routes", () => { const hopper = provider("hopper", "address_name", []); expect( @@ -253,6 +290,8 @@ const provider = ( id: string, operation: Exclude, starts: string[], + /** Close outcomes in order; ok(null) after they run out. */ + closes: Awaited>[] = [], ): AnalysisProvider => { const identity: ProviderIdentity = { id, name: id, version: "1" }; return { @@ -263,7 +302,7 @@ const provider = ( return { execute: async (called) => ok(createAnalysisExecution(`${id}:${called}`, identity)), - close: async () => ok(null), + close: async () => closes.shift() ?? ok(null), }; }, }; diff --git a/tests/fixtures/fakeGhidra.mjs b/tests/fixtures/fakeGhidra.mjs index 9ed380f8c05..d4943d19586 100644 --- a/tests/fixtures/fakeGhidra.mjs +++ b/tests/fixtures/fakeGhidra.mjs @@ -222,7 +222,8 @@ const handleRequest = (socket, server, request, state) => { } // A tool that never answers, so a caller is still active during close. if ( - state.mode === "checkpoint_hold_close_hang_tool" && + (state.mode === "checkpoint_hold_close_hang_tool" || + state.mode === "checkpoint_hang_tool") && request.method === "list_documents" ) return;