mirror of
https://github.com/morluto/rea.git
synced 2026-11-29 01:46:39 +00:00
* fix(ghidra): report a held checkpoint lease as retryable contention * fix(ghidra): let sessions share a checkpointed target Sessions restore a checkpoint into private projects without a lease. The socket lease is held only while one session publishes, and publication is a compare-and-set on the source that session started from, so a later save is refused instead of overwriting another session's edits. Addresses #14834. Stacked on #14844. * feat(ghidra): bound the checkpoint save wait with a launch control REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS replaces the fixed 30 s wait for another session's checkpoint publication. Default 30000 ms, floor 50 ms (one lease poll), maximum 600000 ms. The value is parsed when REA starts and fixed for a session when its checkpoint owner is constructed. It is a restart-only launch control in the numeric limit registry, not a runtime analysis setting, so the MCP tool catalog is unchanged. The busy refusal names the control, the applied value, its source and the range, and binds them as an environment limit. An invalid value is reported by doctor and registration validation and refuses only a checkpointed Ghidra session. * fix(ghidra): keep checkpoint save waits and refusals accurate - Poll again when a lease probe races the owner's release or another waiter's stale-socket recovery instead of failing the save with configuration_invalid. - Release the publication lease even when a staging or superseded file removal fails, so a retained cleanup does not block other saves. - Report an initial analysis overtaken by another session's edits as a superseded restore (reopen) rather than as refused edits. - Carry the save-wait details.limit onto a busy close_binary, through AnalysisClientCreation, and document the close-time shape. * fix(ghidra): report discarded checkpoint edits and end a forced close's save wait A session whose checkpoint save was refused because another session published first releases its edits on the next close_binary. That close now reports it: the result carries checkpoint {status: "discarded", reason: "superseded", directory}, alongside the snapshot receipt when snapshot_path was given. Only the close that releases the Program reports it, so a failed cleanup keeps the refusal and its retry reports instead. AnalysisClient.close returns an optional EngineCloseReport that the composite client, BinarySession close and closeWithSnapshot carry to the close_binary contract; an ordinary close keeps result null. A graceful close's final save did not observe a forced stop while it waited for another session's publication lease, so a cancelled request escalating the close could block for the whole save wait (up to ten minutes). The escalation now aborts that wait. The abort covers only the lease wait, the save's cancellation cutoff; once the lease is held the bounded publication completes, so a committed save is never reported as failed. The busy refusal's recovery and the installation guide now state that REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS cannot make an MCP client wait longer: that client's request deadline is separate and unknown to REA. The refusal keeps its environment details.limit. * fix(ghidra): tell a contention retry to reopen once the owner saved edits A session that waited for a checkpoint lease keeps the generation it selected, so after the owner saves Program edits and closes, repeating the call cannot succeed. Report that outcome as a typed superseded failure with reopen recovery instead of a checkpoint-directory configuration error, and say so in the busy recovery. * fix(ghidra): report both failures when checkpoint file removal and lease release fail retryCleanup rethrew a lease release failure before the saved removal failure became part of the error, so callers saw only the lease. A release failure alongside a removal failure is now reported with it: one ProviderCleanupError names both reasons, keeps the pending files and the retained lease as cleanup resources, and carries both causes. A lone release failure keeps its own error. * fix(ghidra): keep close facts and launch causes through composed failures Completed close facts were dropped wherever a later failure was composed. A released engine's discard report and a saved snapshot receipt are now carried by one owner, retainCloseOutcome, which every close composition calls on its outermost error with the outcomes it composed: the composite client when a sibling fails after a child released its edits, the session when file, candidate or bundle cleanup fails after the provider closed, the process-capture close wrapper, and the Ghidra client when cleanup fails after its JVM stopped. The report rides the failure as partial_observation.checkpoint and is not repeated by the retry. This replaces retainSavedAnalysisSnapshot and the close wrapper's snapshot extractor. Only close_binary reports edits released unsaved, so open_binary of another target, opening app resources, reset_investigation and external mutations now refuse with capability_unavailable while a client reports them through the new AnalysisClient.unsavedCloseReport, instead of releasing them silently. A launch failure was replaced by a superseded-restore error whenever another session had saved meanwhile. The launcher now records whether the failure happened while restoring the checkpoint, and only that failure is explained as superseded; any other keeps its cause, output and diagnostics. The busy recovery now says that a repeated call can report a superseded checkpoint when the other session's save changed it. * fix(ghidra): deliver the discard report through GhidraProvider and keep refusals typed GhidraProvider wraps its client in DeferredAnalysisClient, whose AnalysisClientCreation released the client through a cleanup lease and returned ok(null), so the real close_binary path dropped the discard report. The lease entry now keeps the releasing close's report and hands it to one release outcome; a failed release, a failed inspection cleanup and a retained creation failure carry it through retainCloseOutcome. The GhidraProvider client does the same when native AOT cleanup also fails. A boundary test drives close_binary through GhidraProvider. A forced close could still publish when its stop arrived while the lease was being acquired. Acquiring the lease is now the cancellation cutoff: publish checks the lease signal right after it and stops, and cleanup releases the lease. A refused save whose cleanup also failed was wrapped into a generic adapter error, so the client missed the refusal and kept the staged file for another impossible save. The checkpoint now keeps its typed refusal primary and unwrapped, carrying the cleanup failure on it; the client records the discard and reports the cleanup failure in diagnostics. * fix(ghidra): report released edits only for refused saves and keep startup cleanup failures A superseded initial analysis (stage restore) set the same refused-save flag as a refused edit, so its stopped JVM became a released-unsaved report: the session claimed discarded edits it never had, and open_binary refused the reopen its own error asked for. The refusal now states whether it refused edits (GhidraCheckpointSupersededError.refusesEdits, true only for a save), and the client records a discard only from that fact. Any refusal still discards its staged file. The cleanup failure a checkpoint refusal carries was read at close but not by the startup session failure factory. Ghidra lifecycle errors that carry a cleanup failure are now recognized by one guard, isGhidraCleanupCarrier, used by bindGhidraSessionFailure and the close error alike; the close diagnostic is renamed carried_cleanup_failure since it covers every carrier.
589 lines
20 KiB
TypeScript
589 lines
20 KiB
TypeScript
import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
import { expect, it, onTestFinished, vi } from "vitest";
|
|
|
|
import {
|
|
AnalysisCleanupLease,
|
|
AnalysisCleanupLeaseGroup,
|
|
} from "../../../src/resources/AnalysisCleanupLease.js";
|
|
import type {
|
|
AnalysisClient,
|
|
AnalysisProvider,
|
|
} from "../../../src/ports/AnalysisProvider.js";
|
|
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
|
|
import { HopperStartError } from "../../../src/hopper/HopperErrors.js";
|
|
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
|
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
|
|
import { err, ok as resultOk } from "../../../src/domain/result.js";
|
|
import {
|
|
createFixtureProviderIdentity,
|
|
observed as ok,
|
|
} from "../../fixtures/analysisExecution.js";
|
|
import {
|
|
createBinarySessionTargets,
|
|
createCacheProvider,
|
|
createDeferred,
|
|
createTestBinarySession,
|
|
} from "../../fixtures/binarySession.js";
|
|
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
|
import { awaitAcknowledgement } from "../../fixtures/lifecycleAcknowledgement.js";
|
|
|
|
const CLOSE_RETRY = { operation: "close_binary" } as const;
|
|
|
|
const retryFixture = async (
|
|
execute: AnalysisClient["execute"] = () => Promise.resolve(ok(null)),
|
|
onClose?: () => void,
|
|
) => {
|
|
const parent = await createTestTempDirectory("rea-session-cleanup-retry-");
|
|
const runtime = join(parent, "owned-runtime");
|
|
const document = join(parent, "retained-document");
|
|
await mkdir(runtime);
|
|
await writeFile(join(runtime, "observation"), "owned observation");
|
|
await writeFile(document, "caller-retained document");
|
|
const targets = await createBinarySessionTargets();
|
|
let allowed = false;
|
|
let created = 0;
|
|
const runIds: string[] = [];
|
|
const cleanupError = new ProviderCleanupError("fixture", [runtime], {
|
|
reason: "owned runtime removal denied",
|
|
leftover_paths: [runtime],
|
|
});
|
|
const cleanupLease = new AnalysisCleanupLease(
|
|
() => rm(runtime, { recursive: true, force: true }),
|
|
[runtime],
|
|
);
|
|
new AnalysisCleanupLeaseGroup(cleanupError, [cleanupLease]);
|
|
const client: AnalysisClient = {
|
|
execute,
|
|
operationHealthSnapshot: () => ({
|
|
state: "unreachable",
|
|
stage: "connection",
|
|
retryAction: "restart_provider",
|
|
exitCode: null,
|
|
requests: [],
|
|
}),
|
|
close: async (options) => {
|
|
onClose?.();
|
|
if (!allowed) return err(cleanupError);
|
|
await cleanupLease.release();
|
|
if (options?.retainDocument !== true) await rm(document, { force: true });
|
|
return resultOk(null);
|
|
},
|
|
};
|
|
const session = createTestBinarySession((_target, _profile, context) => {
|
|
if (context === undefined) throw new Error("missing analysis run context");
|
|
runIds.push(context.runId);
|
|
created += 1;
|
|
return created === 1
|
|
? {
|
|
...client,
|
|
runtimeLineageSnapshots: () => [
|
|
{
|
|
provider: createFixtureProviderIdentity(),
|
|
observation: {
|
|
status: "unavailable" as const,
|
|
observedAt: "2026-10-16T00:00:00Z",
|
|
runId: context.runId,
|
|
launcherPid: 123,
|
|
processGroupId: 123,
|
|
reason: "fixture lineage unavailable",
|
|
},
|
|
},
|
|
],
|
|
}
|
|
: {
|
|
execute: () => Promise.resolve(ok(null)),
|
|
close: () => Promise.resolve(resultOk(null)),
|
|
};
|
|
});
|
|
onTestFinished(async () => {
|
|
allowed = true;
|
|
await session.close();
|
|
});
|
|
return {
|
|
session,
|
|
targets,
|
|
runtime,
|
|
document,
|
|
cleanupError,
|
|
runIds,
|
|
allowCleanup: () => {
|
|
allowed = true;
|
|
},
|
|
created: () => created,
|
|
};
|
|
};
|
|
|
|
it.each(["close", "switch", "open after close"] as const)(
|
|
"retries owned cleanup before completing %s",
|
|
async (transition) => {
|
|
const fixture = await retryFixture();
|
|
const {
|
|
session,
|
|
targets: [first, second],
|
|
runtime,
|
|
cleanupError,
|
|
} = fixture;
|
|
expect((await session.open(first)).ok).toBe(true);
|
|
const attempt = () =>
|
|
transition === "close" ? session.close() : session.open(second);
|
|
const initial =
|
|
transition === "switch" ? await attempt() : await session.close();
|
|
expect(initial).toEqual(
|
|
transition === "switch"
|
|
? {
|
|
ok: false,
|
|
error: cleanupError,
|
|
targetAtCompletion: null,
|
|
providerIdAtCompletion: null,
|
|
selection: { kind: "none" },
|
|
}
|
|
: err(cleanupError),
|
|
);
|
|
expect(session.activeTarget()).toBeUndefined();
|
|
expect(await session.status()).toMatchObject({
|
|
open: false,
|
|
cleanup_pending: true,
|
|
analysis_run: {
|
|
run_id: fixture.runIds[0],
|
|
process_lineage: {
|
|
status: "snapshots",
|
|
snapshots: [
|
|
{ observation: { reason: "fixture lineage unavailable" } },
|
|
],
|
|
},
|
|
},
|
|
provider_operation_health: { state: "unreachable", stage: "connection" },
|
|
});
|
|
expect(await session.execute("address_name", {})).toMatchObject({
|
|
ok: false,
|
|
});
|
|
await access(runtime);
|
|
|
|
expect(await attempt()).toEqual(
|
|
transition === "close"
|
|
? err(cleanupError)
|
|
: {
|
|
ok: false,
|
|
error: cleanupError,
|
|
targetAtCompletion: null,
|
|
providerIdAtCompletion: null,
|
|
selection: { kind: "none" },
|
|
},
|
|
);
|
|
expect(await session.status()).toMatchObject({
|
|
analysis_run: { run_id: fixture.runIds[0] },
|
|
});
|
|
expect(fixture.created()).toBe(1);
|
|
await access(runtime);
|
|
|
|
fixture.allowCleanup();
|
|
expect((await attempt()).ok).toBe(true);
|
|
expect(await session.status()).toMatchObject({ cleanup_pending: false });
|
|
await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(fixture.created()).toBe(transition === "close" ? 1 : 2);
|
|
expect(await session.status()).toMatchObject({
|
|
analysis_run:
|
|
transition === "close"
|
|
? null
|
|
: {
|
|
run_id: fixture.runIds[1],
|
|
process_lineage: { status: "not_observed" },
|
|
},
|
|
});
|
|
expect(new Set(fixture.runIds).size).toBe(fixture.created());
|
|
},
|
|
);
|
|
|
|
it("offers a caller's close retry only while the session retains its cleanup", async () => {
|
|
const fixture = await retryFixture();
|
|
expect((await fixture.session.open(fixture.targets[0])).ok).toBe(true);
|
|
// One-shot callers name no retry and therefore receive none.
|
|
const oneShot = await fixture.session.close();
|
|
if (oneShot.ok) throw new Error("Expected retained cleanup");
|
|
expect(projectAnalysisError(oneShot.error)).not.toHaveProperty("recovery");
|
|
|
|
const offered = await fixture.session.close({ cleanupRetry: CLOSE_RETRY });
|
|
if (offered.ok) throw new Error("Expected retained cleanup");
|
|
expect(projectAnalysisError(offered.error)).toMatchObject({
|
|
code: "cleanup_incomplete",
|
|
recovery: { kind: "retry_cleanup", operation: "close_binary" },
|
|
details: { resources: [fixture.runtime] },
|
|
});
|
|
|
|
fixture.allowCleanup();
|
|
expect((await fixture.session.close({ cleanupRetry: CLOSE_RETRY })).ok).toBe(
|
|
true,
|
|
);
|
|
expect(projectAnalysisError(fixture.cleanupError)).not.toHaveProperty(
|
|
"recovery",
|
|
);
|
|
});
|
|
|
|
it("offers a close retry after a saved snapshot but not after a failed save", async () => {
|
|
const [first] = await createBinarySessionTargets();
|
|
const parent = await createTestTempDirectory("rea-snapshot-close-retry-");
|
|
const failedSave = join(parent, "failed-save.json");
|
|
const savedPath = join(parent, "saved.json");
|
|
const cache = createCacheProvider([]);
|
|
let allowed = false;
|
|
const cleanupError = new ProviderCleanupError("fixture", ["runtime"], {
|
|
reason: "runtime removal denied",
|
|
});
|
|
const provider: AnalysisProvider = {
|
|
...cache,
|
|
createClient: (...arguments_) => ({
|
|
...cache.createClient(...arguments_),
|
|
close: async () => (allowed ? resultOk(null) : err(cleanupError)),
|
|
}),
|
|
};
|
|
const session = createTestBinarySession(provider);
|
|
onTestFinished(async () => {
|
|
allowed = true;
|
|
await session.close();
|
|
});
|
|
expect((await session.open(first)).ok).toBe(true);
|
|
// The composite route creates the provider client on first use.
|
|
expect((await session.execute("address_name", {})).ok).toBe(true);
|
|
|
|
// A retained session file owner shows the offer does not follow pending
|
|
// cleanup alone: the failed save keeps the target open.
|
|
let releaseFile = false;
|
|
session.resourceScope.retain(
|
|
{
|
|
close: async () => {
|
|
if (!releaseFile) throw new Error("retained descriptor close denied");
|
|
},
|
|
cleanupResources: [failedSave],
|
|
},
|
|
failedSave,
|
|
);
|
|
const saveFailure = new ProviderCleanupError("rea", [failedSave], {
|
|
reason: "snapshot descriptor close denied",
|
|
});
|
|
const write = vi
|
|
.spyOn(session, "writeAnalysisSnapshot")
|
|
.mockResolvedValueOnce(err(saveFailure));
|
|
onTestFinished(() => write.mockRestore());
|
|
expect(
|
|
await session.closeWithSnapshot(failedSave, false, {
|
|
cleanupRetry: CLOSE_RETRY,
|
|
}),
|
|
).toEqual(err(saveFailure));
|
|
expect(projectAnalysisError(saveFailure)).not.toHaveProperty("recovery");
|
|
expect(await session.status()).toMatchObject({
|
|
open: true,
|
|
cleanup_pending: true,
|
|
});
|
|
|
|
releaseFile = true;
|
|
const closed = await session.closeWithSnapshot(savedPath, false, {
|
|
cleanupRetry: CLOSE_RETRY,
|
|
});
|
|
if (closed.ok) throw new Error("Expected retained provider cleanup");
|
|
expect(projectAnalysisError(closed.error)).toMatchObject({
|
|
code: "cleanup_incomplete",
|
|
recovery: { kind: "retry_cleanup", operation: "close_binary" },
|
|
details: {
|
|
resources: ["runtime"],
|
|
partial_observation: { saved_snapshot: { bytes: expect.any(Number) } },
|
|
},
|
|
});
|
|
await access(savedPath);
|
|
allowed = true;
|
|
expect((await session.close({ cleanupRetry: CLOSE_RETRY })).ok).toBe(true);
|
|
expect(await session.status()).toMatchObject({ cleanup_pending: false });
|
|
});
|
|
|
|
it.each(["provider failure", "caller cancellation"] as const)(
|
|
"retains the failed startup candidate and its %s through cleanup retry",
|
|
async (outcome) => {
|
|
const controller = new AbortController();
|
|
const reason = { stage: "startup health" };
|
|
const startupFailure = new HopperStartError();
|
|
const fixture = await retryFixture(async () => {
|
|
if (outcome === "provider failure") return err(startupFailure);
|
|
controller.abort(reason);
|
|
return ok(null);
|
|
});
|
|
const result = await fixture.session.open(fixture.targets[0], {
|
|
signal: controller.signal,
|
|
});
|
|
if (result.ok) throw new Error("Expected startup to fail");
|
|
expect(result.error).toMatchObject({
|
|
cleanupIncomplete: true,
|
|
cleanupResources: [fixture.runtime],
|
|
diagnostics:
|
|
outcome === "provider failure"
|
|
? {
|
|
primary_error: projectAnalysisError(startupFailure),
|
|
cleanup_error: projectAnalysisError(fixture.cleanupError),
|
|
}
|
|
: { primary_error: { code: "cancelled" } },
|
|
});
|
|
if (outcome === "caller cancellation") {
|
|
expect(result.error.cleanupPrimary).toBeInstanceOf(
|
|
AnalysisCancelledError,
|
|
);
|
|
expect(result.error.cleanupPrimary?.cause).toBe(reason);
|
|
}
|
|
expect(fixture.session.activeTarget()).toBeUndefined();
|
|
expect(await fixture.session.status()).toMatchObject({
|
|
open: false,
|
|
cleanup_pending: true,
|
|
analysis_run: {
|
|
run_id: fixture.runIds[0],
|
|
process_lineage: { status: "snapshots" },
|
|
},
|
|
});
|
|
|
|
fixture.allowCleanup();
|
|
expect((await fixture.session.close()).ok).toBe(true);
|
|
await expect(access(fixture.runtime)).rejects.toMatchObject({
|
|
code: "ENOENT",
|
|
});
|
|
expect(result.error.cleanupIncomplete).toBe(false);
|
|
if (outcome === "caller cancellation") {
|
|
expect(result.error.cleanupPrimary?.cause).toBe(reason);
|
|
expect(projectAnalysisError(result.error).code).toBe("cancelled");
|
|
}
|
|
},
|
|
);
|
|
|
|
it("keeps cancellation as the primary when previous-client retirement fails after abort", async () => {
|
|
const controller = new AbortController();
|
|
const reason = { phase: "binary-retirement" };
|
|
const fixture = await retryFixture(undefined, () => controller.abort(reason));
|
|
expect((await fixture.session.open(fixture.targets[0])).ok).toBe(true);
|
|
const result = await fixture.session.open(fixture.targets[1], {
|
|
signal: controller.signal,
|
|
});
|
|
if (result.ok) throw new Error("Expected cancelled retirement");
|
|
expect(result.error.cleanupIncomplete).toBe(true);
|
|
expect(result.error.cleanupPrimary).toMatchObject({
|
|
_tag: "AnalysisCancelledError",
|
|
});
|
|
expect(result.error.cleanupPrimary?.cause).toBe(reason);
|
|
expect(await fixture.session.status()).toMatchObject({
|
|
open: false,
|
|
cleanup_pending: true,
|
|
});
|
|
fixture.allowCleanup();
|
|
expect((await fixture.session.close()).ok).toBe(true);
|
|
expect(fixture.cleanupError.cleanupIncomplete).toBe(false);
|
|
expect(result.error.cleanupIncomplete).toBe(false);
|
|
expect(projectAnalysisError(result.error)).toMatchObject({
|
|
code: "cancelled",
|
|
});
|
|
expect(result.error.cleanupPrimary?.cause).toBe(reason);
|
|
});
|
|
|
|
it.each([
|
|
{ initial: true, retry: undefined, retained: true },
|
|
{ initial: undefined, retry: true, retained: true },
|
|
{ initial: true, retry: false, retained: false },
|
|
])(
|
|
"applies the document retention choice across cleanup attempts: %j",
|
|
async ({ initial, retry, retained }) => {
|
|
const fixture = await retryFixture();
|
|
const close = (choice: boolean | undefined) =>
|
|
fixture.session.close(
|
|
choice === undefined ? {} : { retainProviderDocuments: choice },
|
|
);
|
|
expect((await fixture.session.open(fixture.targets[0])).ok).toBe(true);
|
|
expect(await close(initial)).toEqual(err(fixture.cleanupError));
|
|
fixture.allowCleanup();
|
|
expect((await close(retry)).ok).toBe(true);
|
|
await expect(access(fixture.runtime)).rejects.toMatchObject({
|
|
code: "ENOENT",
|
|
});
|
|
if (retained)
|
|
expect(await readFile(fixture.document, "utf8")).toBe(
|
|
"caller-retained document",
|
|
);
|
|
else
|
|
await expect(access(fixture.document)).rejects.toMatchObject({
|
|
code: "ENOENT",
|
|
});
|
|
},
|
|
);
|
|
|
|
it("keeps failed restoration resources available for a close retry", async () => {
|
|
const parent = await createTestTempDirectory("rea-restore-cleanup-retry-");
|
|
const runtime = join(parent, "restore-runtime");
|
|
await mkdir(runtime);
|
|
await writeFile(join(runtime, "observation"), "restore observation");
|
|
const [first, second] = await createBinarySessionTargets();
|
|
let created = 0;
|
|
let allowed = false;
|
|
const runIds: string[] = [];
|
|
const session = createTestBinarySession((_target, _profile, context) => {
|
|
if (context === undefined) throw new Error("missing analysis run context");
|
|
runIds.push(context.runId);
|
|
const index = ++created;
|
|
return {
|
|
execute: () =>
|
|
Promise.resolve(index === 1 ? ok(null) : err(new HopperStartError())),
|
|
close: async () => {
|
|
if (index !== 3) return resultOk(null);
|
|
if (!allowed)
|
|
throw new ProviderCleanupError("fixture", [runtime], {
|
|
reason: "restoration cleanup denied",
|
|
});
|
|
await rm(runtime, { recursive: true, force: true });
|
|
return resultOk(null);
|
|
},
|
|
};
|
|
});
|
|
onTestFinished(async () => {
|
|
allowed = true;
|
|
await session.close();
|
|
});
|
|
expect((await session.open(first)).ok).toBe(true);
|
|
expect(await session.open(second)).toMatchObject({
|
|
ok: false,
|
|
error: { cleanupIncomplete: true, cleanupResources: [runtime] },
|
|
});
|
|
expect(session.activeTarget()).toBeUndefined();
|
|
expect(await session.status()).toMatchObject({
|
|
open: false,
|
|
cleanup_pending: true,
|
|
analysis_run: { run_id: runIds[2] },
|
|
});
|
|
expect(new Set(runIds).size).toBe(3);
|
|
allowed = true;
|
|
expect((await session.close()).ok).toBe(true);
|
|
await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
|
|
it("does not start a replacement cancelled while pending cleanup completes", async () => {
|
|
const parent = await createTestTempDirectory("rea-cancel-cleanup-retry-");
|
|
const runtime = join(parent, "owned-runtime");
|
|
await mkdir(runtime);
|
|
await writeFile(join(runtime, "observation"), "owned observation");
|
|
const [first, second] = await createBinarySessionTargets();
|
|
const entered = createDeferred<void>();
|
|
const release = createDeferred<void>();
|
|
let allowed = false;
|
|
let created = 0;
|
|
const session = createTestBinarySession(() => {
|
|
const index = ++created;
|
|
return {
|
|
execute: () => Promise.resolve(ok(null)),
|
|
close: async () => {
|
|
if (index !== 1) return resultOk(null);
|
|
if (!allowed)
|
|
return err(
|
|
new ProviderCleanupError("fixture", [runtime], {
|
|
reason: "cleanup denied",
|
|
}),
|
|
);
|
|
entered.resolve();
|
|
await release.promise;
|
|
await rm(runtime, { recursive: true, force: true });
|
|
return resultOk(null);
|
|
},
|
|
};
|
|
});
|
|
onTestFinished(async () => {
|
|
allowed = true;
|
|
release.resolve();
|
|
await session.close();
|
|
});
|
|
expect((await session.open(first)).ok).toBe(true);
|
|
expect((await session.close()).ok).toBe(false);
|
|
allowed = true;
|
|
const controller = new AbortController();
|
|
const opening = session.open(second, { signal: controller.signal });
|
|
await awaitAcknowledgement(entered.promise, opening, "session cleanup retry");
|
|
controller.abort();
|
|
release.resolve();
|
|
expect(await opening).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisCancelledError" },
|
|
});
|
|
expect(created).toBe(1);
|
|
await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
|
|
it("lets an unowned close failure read the later successful close", async () => {
|
|
const [first] = await createBinarySessionTargets();
|
|
let allowed = false;
|
|
const session = createTestBinarySession(() => ({
|
|
execute: () => Promise.resolve(ok(null)),
|
|
close: () =>
|
|
Promise.resolve(
|
|
allowed
|
|
? resultOk(null)
|
|
: err(
|
|
new ProviderCleanupError("fixture", ["owned-runtime"], {
|
|
reason: "cleanup denied",
|
|
}),
|
|
),
|
|
),
|
|
}));
|
|
onTestFinished(async () => {
|
|
allowed = true;
|
|
await session.close();
|
|
});
|
|
expect((await session.open(first)).ok).toBe(true);
|
|
const failed = await session.close();
|
|
if (failed.ok) throw new Error("Expected retained close failure");
|
|
expect(failed.error.hasCleanupOwner).toBe(false);
|
|
expect(failed.error.cleanupIncomplete).toBe(true);
|
|
allowed = true;
|
|
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),
|
|
);
|
|
});
|