Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(doctor): propagate Kuna cancellation and preserve partial observations (#5241)

Liu Jied532b1812391
diff --git a/docs/kuna-provider.md b/docs/kuna-provider.md
index 0a37b98c8..05e5a633b 100644
--- a/docs/kuna-provider.md
+++ b/docs/kuna-provider.md
@@ -13,6 +13,14 @@ rea doctor --provider kuna
Select it explicitly with `--provider kuna`, MCP's `open_binary.provider_id: "kuna"`, or `REA_ANALYSIS_PROVIDER=kuna`. With Kuna and another provider configured for the same target, `auto` reports `ambiguous` instead of choosing one.
+Ordinary readiness cancellation returns `cancelled` (CLI SIGINT/SIGTERM exits
+130/143); an earlier recorded timeout or physical failure keeps its diagnostic.
+Completed version, hash and script observations remain in `kuna_installation`
+with `status: "partial"` and `completed_hash` when available. Typed errors carry
+this in `details.diagnostics`; doctor cleanup checks carry it in their `details`.
+Omitted fields remain unobserved; availability remains unknown until readiness
+completes. Cleanup retries keep both the observations and the exact file owner.
+
| Setting | Default | Meaning |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `REA_KUNA_COMMAND` | none (required) | Absolute path of the `kuna` executable. |
diff --git a/src/doctorRuntime.ts b/src/doctorRuntime.ts
index 2b3c1e1c0..54c320bd8 100644
--- a/src/doctorRuntime.ts
+++ b/src/doctorRuntime.ts
@@ -63,6 +63,7 @@ export const createSystemDoctorHost = (
),
await inspectKunaProvider(environment, process.platform, {
fileCloseResources,
+ signal: inspectionSignal,
}),
],
linuxDemoRuntimeCheck: () =>
diff --git a/src/kuna/KunaCommand.ts b/src/kuna/KunaCommand.ts
index b4cc5a3de..283a9aae7 100644
--- a/src/kuna/KunaCommand.ts
+++ b/src/kuna/KunaCommand.ts
@@ -31,6 +31,7 @@ import type {
} from "../process/ProviderProcess.js";
import {
kunaChildEnvironment,
+ kunaInstallationFailureDiagnostics,
type KunaInstallation,
} from "./KunaInstallation.js";
import type { KunaDeadline } from "./KunaConfiguration.js";
@@ -99,21 +100,23 @@ export const kunaFileCleanupError = (
failure: RegularFileCleanupFailure,
operation: string,
): AnalysisError => {
- const cleanup = new ProviderCleanupError(
- KUNA_PROVIDER_ID,
- [failure.path],
- { reason: message(failure.cleanupCause) },
- { cause: failure, operation },
- );
+ const diagnostics = kunaInstallationFailureDiagnostics(failure);
const cancellation = regularFileCancellation(failure);
if (cancellation !== undefined)
return new AnalysisCancelledError(operation, {
cause: cancellation.reason,
+ diagnostics,
cleanup: {
reason: message(failure.cleanupCause),
resources: [failure.path],
},
});
+ const cleanup = new ProviderCleanupError(
+ KUNA_PROVIDER_ID,
+ [failure.path],
+ { reason: message(failure.cleanupCause), ...diagnostics },
+ { cause: failure, operation },
+ );
if (failure.outcome.kind === "completed") return cleanup;
const primaryCause = failure.outcome.cause;
const primary =
@@ -121,6 +124,7 @@ export const kunaFileCleanupError = (
? primaryCause
: new ProviderAdapterError(KUNA_PROVIDER_ID, operation, {
cause: primaryCause,
+ diagnostics,
userMessage: `Kuna ${operation} failed: ${message(primaryCause)}`,
});
return analysisErrorWithCleanupFailure(primary, cleanup, operation);
diff --git a/src/kuna/KunaDoctor.ts b/src/kuna/KunaDoctor.ts
index 8a89b4e4a..7c6e8b184 100644
--- a/src/kuna/KunaDoctor.ts
+++ b/src/kuna/KunaDoctor.ts
@@ -9,8 +9,11 @@ import type {
import { readKunaConfiguration } from "./KunaConfiguration.js";
import type { FileCloseResourceOwner } from "../application/AnalysisProvider.js";
import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
+import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import {
inspectKunaInstallation,
+ kunaInstallationCancellation,
+ kunaInstallationFailureDiagnostics,
type KunaReadinessFailure,
} from "./KunaInstallation.js";
import {
@@ -37,6 +40,7 @@ export const inspectKunaProvider = async (
platform: NodeJS.Platform = process.platform,
options: {
readonly fileCloseResources: FileCloseResourceOwner;
+ readonly signal?: AbortSignal;
},
): Promise<DoctorProviderInspection> => {
let installation: Awaited<ReturnType<typeof inspectKunaInstallation>>;
@@ -44,9 +48,18 @@ export const inspectKunaProvider = async (
installation = await inspectKunaInstallation(environment, {
platform,
fileCloseResources: options.fileCloseResources,
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
});
} catch (cause: unknown) {
- if (!(cause instanceof RegularFileCleanupFailure)) throw cause;
+ if (!(cause instanceof RegularFileCleanupFailure)) {
+ const cancellation = kunaInstallationCancellation(cause);
+ if (cancellation !== undefined)
+ throw new AnalysisCancelledError("doctor", {
+ cause: cancellation.reason,
+ diagnostics: cancellation.diagnostics,
+ });
+ throw cause;
+ }
return {
id: KUNA_PROVIDER_ID,
configured: environment.REA_KUNA_COMMAND !== undefined,
@@ -61,7 +74,10 @@ export const inspectKunaProvider = async (
detail: `Kuna installation inspection could not confirm file cleanup: ${cause instanceof Error ? cause.message : String(cause)}`,
remediation: null,
classification: "config_drift",
- details: { cleanup_incomplete: true },
+ details: {
+ cleanup_incomplete: true,
+ ...kunaInstallationFailureDiagnostics(cause),
+ },
},
],
};
diff --git a/src/kuna/KunaInstallation.ts b/src/kuna/KunaInstallation.ts
index 5c6604627..aedab42f6 100644
--- a/src/kuna/KunaInstallation.ts
+++ b/src/kuna/KunaInstallation.ts
@@ -1,9 +1,12 @@
-import { assertRegularFileActive } from "../filesystem/RegularFile.js";
+import {
+ assertRegularFileActive,
+ RegularFileOperationCancelled,
+} from "../filesystem/RegularFile.js";
import { constants } from "node:fs";
import { access, realpath, stat } from "node:fs/promises";
import { join } from "node:path";
-import type { JsonValue } from "../domain/jsonValue.js";
+import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js";
@@ -14,12 +17,14 @@ import {
import type { FileCloseResourceOwner } from "../application/AnalysisProvider.js";
import {
RegularFileCleanupFailure,
+ RegularFileCancelled,
regularFileCancellation,
withOwnedRegularFile,
} from "../filesystem/OwnedRegularFile.js";
import {
execFileOutput,
execFileOutputFailure,
+ ExecFileOutputCancelledError,
} from "../process/ExecFileOutput.js";
import {
readKunaConfiguration,
@@ -75,6 +80,39 @@ export interface KunaInstallationOptions {
readonly fileCloseResources: FileCloseResourceOwner;
}
+/** Cancellation facts normalized by the installation inspection that observed them. */
+interface KunaInstallationCancellation {
+ readonly reason: unknown;
+ readonly diagnostics?: Readonly<Record<string, JsonValue>>;
+}
+
+// Annotations follow the exact failure's lifetime. Descriptor ownership stays
+// with the supplied resource scope, independently of this weak metadata.
+const installationFailureDiagnostics = new WeakMap<
+ Error,
+ Readonly<Record<string, JsonValue>>
+>();
+
+export const kunaInstallationFailureDiagnostics = (
+ cause: unknown,
+): Readonly<Record<string, JsonValue>> | undefined =>
+ cause instanceof Error
+ ? installationFailureDiagnostics.get(cause)
+ : undefined;
+
+/** Consumers project the owner's facts without reinterpreting generic file outcomes. */
+export const kunaInstallationCancellation = (
+ cause: unknown,
+): KunaInstallationCancellation | undefined => {
+ const cancellation = regularFileCancellation(cause);
+ if (cancellation === undefined) return undefined;
+ const diagnostics = kunaInstallationFailureDiagnostics(cause);
+ return {
+ reason: cancellation.reason,
+ ...(diagnostics === undefined ? {} : { diagnostics }),
+ };
+};
+
/** One installation inspection's file owners and their originating errors. */
export interface KunaFileCloseScope {
readonly owner: FileCloseResourceOwner;
@@ -150,6 +188,7 @@ export const inspectKunaInstallation = async (
: { setting: configuration.error.setting }),
});
const { command } = configuration.value;
+ assertRegularFileActive(options.signal);
let executable: string;
try {
@@ -162,7 +201,6 @@ export const inspectKunaInstallation = async (
{ command },
);
} catch (cause: unknown) {
- assertRegularFileActive(options.signal);
return failure(
"executable_missing",
`Cannot execute REA_KUNA_COMMAND ${command}: ${message(cause)}. ${KUNA_COMMAND_REMEDIATION}`,
@@ -170,6 +208,8 @@ export const inspectKunaInstallation = async (
);
}
+ assertRegularFileActive(options.signal);
+
const deadline = options.probeTimeoutMs ?? VERSION_PROBE_TIMEOUT_MS;
let stdout: string;
try {
@@ -182,7 +222,8 @@ export const inspectKunaInstallation = async (
...(options.signal === undefined ? {} : { signal: options.signal }),
}));
} catch (cause: unknown) {
- assertRegularFileActive(options.signal);
+ if (cause instanceof ExecFileOutputCancelledError)
+ throw new RegularFileOperationCancelled(cause.cause);
const output = execFileOutputFailure(cause);
return failure(
"version_unresolved",
@@ -208,6 +249,11 @@ export const inspectKunaInstallation = async (
let fingerprint: { readonly sha256: string; readonly bytes: number };
let script: boolean;
+ const observed: {
+ phase: "fingerprint" | "shebang";
+ completed_hash?: { readonly sha256: string; readonly bytes: number };
+ script?: boolean;
+ } = { phase: "fingerprint" };
try {
({ fingerprint, script } = await options.fileCloseResources.run(
async () => {
@@ -216,20 +262,57 @@ export const inspectKunaInstallation = async (
retainFailedClose: (owner) =>
options.fileCloseResources.retain(owner, executable),
});
+ observed.completed_hash = fingerprint;
+ assertRegularFileActive(options.signal);
+ observed.phase = "shebang";
const script = await startsWithShebang(
executable,
options.fileCloseResources,
+ options.signal,
);
+ observed.script = script;
assertRegularFileActive(options.signal);
return { fingerprint, script };
},
));
} catch (cause: unknown) {
+ const cancellation = regularFileCancellation(cause);
if (
- cause instanceof RegularFileCleanupFailure ||
- regularFileCancellation(cause) !== undefined
- )
+ cause instanceof Error &&
+ (cause instanceof RegularFileCleanupFailure || cancellation !== undefined)
+ ) {
+ const outcome =
+ cause instanceof RegularFileCancelled ||
+ cause instanceof RegularFileCleanupFailure
+ ? cause.outcome
+ : undefined;
+ const completed =
+ outcome?.kind === "completed" ? outcome.value : undefined;
+ const completedHash =
+ observed.completed_hash ??
+ (observed.phase === "fingerprint" && outcome?.kind === "completed"
+ ? jsonValueSchema.parse(completed)
+ : undefined);
+ const completedScript =
+ observed.script ??
+ (observed.phase === "shebang" && typeof completed === "boolean"
+ ? completed
+ : undefined);
+ installationFailureDiagnostics.set(cause, {
+ kuna_installation: {
+ status: "partial",
+ command,
+ executable,
+ version,
+ verified: version === KUNA_VERIFIED_VERSION,
+ ...(completedHash === undefined
+ ? {}
+ : { completed_hash: completedHash }),
+ ...(completedScript === undefined ? {} : { script: completedScript }),
+ },
+ });
throw cause;
+ }
return failure(
"executable_missing",
`Cannot fingerprint ${executable}: ${message(stableFileHashCause(cause))}`,
@@ -250,11 +333,13 @@ export const inspectKunaInstallation = async (
const startsWithShebang = (
path: string,
fileCloseResources: FileCloseResourceOwner,
+ signal?: AbortSignal,
): Promise<boolean> =>
withOwnedRegularFile(
path,
{
symlinks: "follow",
+ ...(signal === undefined ? {} : { signal }),
retainFailedClose: (owner) => fileCloseResources.retain(owner, path),
},
async (handle) => {
diff --git a/src/kuna/KunaProvider.ts b/src/kuna/KunaProvider.ts
index a66c5b7a4..02f6ca8db 100644
--- a/src/kuna/KunaProvider.ts
+++ b/src/kuna/KunaProvider.ts
@@ -15,10 +15,7 @@ import {
} from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { err, ok } from "../domain/result.js";
-import {
- RegularFileCleanupFailure,
- regularFileCancellation,
-} from "../filesystem/OwnedRegularFile.js";
+import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import {
kunaFileCleanupError,
@@ -31,6 +28,7 @@ import {
import {
createKunaFileCloseScope,
inspectKunaInstallation,
+ kunaInstallationCancellation,
} from "./KunaInstallation.js";
import { KunaProjectCache } from "./KunaProjectCache.js";
import {
@@ -193,7 +191,7 @@ export class KunaProvider implements AnalysisProviderCandidate {
fileCloseResources: fileCloseScope.owner,
});
} catch (cause: unknown) {
- const cancellation = regularFileCancellation(cause);
+ const cancellation = kunaInstallationCancellation(cause);
if (
!(cause instanceof RegularFileCleanupFailure) &&
cancellation !== undefined
@@ -201,6 +199,7 @@ export class KunaProvider implements AnalysisProviderCandidate {
return err(
new AnalysisCancelledError("kuna:profile", {
cause: cancellation.reason,
+ diagnostics: cancellation.diagnostics,
}),
);
if (!(cause instanceof RegularFileCleanupFailure)) throw cause;
diff --git a/src/kuna/KunaSessionClient.ts b/src/kuna/KunaSessionClient.ts
index cc75416f4..a95d4845d 100644
--- a/src/kuna/KunaSessionClient.ts
+++ b/src/kuna/KunaSessionClient.ts
@@ -44,6 +44,7 @@ import { kunaFunctionDeadline } from "./KunaConfiguration.js";
import {
createKunaFileCloseScope,
inspectKunaInstallation,
+ kunaInstallationCancellation,
type KunaInstallation,
} from "./KunaInstallation.js";
import {
@@ -76,10 +77,7 @@ import {
type KunaProjectFileSpan,
} from "./KunaProjectReader.js";
import { kunaUnavailable } from "./KunaUnavailable.js";
-import {
- RegularFileCleanupFailure,
- regularFileCancellation,
-} from "../filesystem/OwnedRegularFile.js";
+import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { kunaQueryFailureForCaller } from "./KunaQueryErrors.js";
@@ -1410,7 +1408,7 @@ export class KunaSessionClient implements AnalysisClient {
);
return ok(inspected.value);
} catch (cause: unknown) {
- const cancellation = regularFileCancellation(cause);
+ const cancellation = kunaInstallationCancellation(cause);
if (
!(cause instanceof RegularFileCleanupFailure) &&
cancellation !== undefined
@@ -1418,6 +1416,7 @@ export class KunaSessionClient implements AnalysisClient {
return err(
new AnalysisCancelledError("health", {
cause: cancellation.reason,
+ diagnostics: cancellation.diagnostics,
}),
);
if (!(cause instanceof RegularFileCleanupFailure))
diff --git a/tests/boundary/cli/doctorCancellation.test.ts b/tests/boundary/cli/doctorCancellation.test.ts
index 6b8c861da..7904d0aa5 100644
--- a/tests/boundary/cli/doctorCancellation.test.ts
+++ b/tests/boundary/cli/doctorCancellation.test.ts
@@ -11,40 +11,57 @@ import {
type OwnedProcessGroup,
} from "../../../src/process/ProcessOwnership.js";
-cliTest.skipIf(!["darwin", "linux"].includes(process.platform)).for([
- ["SIGINT", 130],
- ["SIGTERM", 143],
-] as const)(
- "doctor preserves %s after logging and joined prerequisite cleanup",
- async ([signal, expected], { processes }) => {
+cliTest.skipIf(!["darwin", "linux"].includes(process.platform)).for(
+ (["jadx", "kuna"] as const).flatMap((provider) =>
+ (
+ [
+ ["SIGINT", 130],
+ ["SIGTERM", 143],
+ ] as const
+ ).map(([signal, expected]) => ({
+ provider,
+ signal,
+ expected,
+ })),
+ ),
+)(
+ "doctor preserves $signal for $provider after logging and joined prerequisite cleanup",
+ async ({ provider, signal, expected }, { processes }) => {
const root = await createTestTempDirectory("rea-doctor-cancel-");
const jdk = join(root, "jdk");
const jar = join(root, "engine.jar");
const ready = join(root, "ready.json");
+ const release = join(root, "release");
await mkdir(join(jdk, "bin"), { recursive: true });
await mkdir(join(root, "home"));
await writeJadxJarInventory(jar);
- // No JVM/engine runs. Announce only the selected JADX module-listing probe;
- // informational Ghidra checks can call the same configured executable first.
+ // No real provider runs. Announce only the selected prerequisite probe;
+ // informational Ghidra checks can call the same configured Java first.
+ const executable =
+ provider === "kuna" ? join(root, "kuna") : join(jdk, "bin", "java");
+ const probeArgument = provider === "kuna" ? "--version" : "--list-modules";
await writeFile(
- join(jdk, "bin", "java"),
+ executable,
`#!${process.execPath}
-if (!process.argv.slice(2).includes("--list-modules")) process.exit(7);
+if (!process.argv.slice(2).includes(${JSON.stringify(probeArgument)})) process.exit(7);
require("node:fs").writeFileSync(${JSON.stringify(ready)}, JSON.stringify({pid: process.pid, runId: process.env.REA_PROCESS_RUN_ID}));
process.on("SIGTERM", () => {});
+setInterval(() => { if (require("node:fs").existsSync(${JSON.stringify(release)})) process.exit(0); }, 25).unref();
setTimeout(() => process.exit(99), 20000);
`,
{ mode: 0o700 },
);
const child = processes.spawn(
process.execPath,
- [resolve("scripts/rea.mjs"), "doctor", "--provider", "jadx", "--json"],
+ [resolve("scripts/rea.mjs"), "doctor", "--provider", provider, "--json"],
{
env: {
PATH: process.env.PATH,
HOME: join(root, "home"),
- JAVA_HOME: jdk,
- REA_JADX_MCP_JAR: jar,
+ JAVA_HOME: provider === "jadx" ? jdk : join(root, "missing-jdk"),
+ ...(provider === "jadx"
+ ? { REA_JADX_MCP_JAR: jar }
+ : { REA_KUNA_COMMAND: executable }),
GHIDRA_INSTALL_DIR: join(root, "missing-ghidra"),
REA_LOG_LEVEL: "silent",
},
@@ -80,27 +97,42 @@ setTimeout(() => process.exit(99), 20000);
const observed = z
.strictObject({
pid: z.number().int().positive(),
- runId: z.string().uuid(),
+ runId: z.string().uuid().optional(),
})
.parse(JSON.parse(await readFile(ready, "utf8")));
- ownership = {
- leaderPid: observed.pid,
- processGroupId: observed.pid,
- runId: observed.runId,
- };
+ if (provider === "jadx") {
+ if (observed.runId === undefined)
+ throw new Error("Missing JADX run token");
+ ownership = {
+ leaderPid: observed.pid,
+ processGroupId: observed.pid,
+ runId: observed.runId,
+ };
+ }
child.kill(signal);
await expect
.poll(() => child.exitCode, { timeout: 10_000 })
.not.toBeNull();
const result = await closed;
expect(JSON.parse(stdout)).toMatchObject({ code: "cancelled" });
- const groups = await observeOwnedProcessGroups(ownership.runId, [
- ownership.processGroupId,
- ]);
- expect(groups.get(ownership.processGroupId)).toEqual({ state: "empty" });
+ if (ownership !== undefined) {
+ const groups = await observeOwnedProcessGroups(ownership.runId, [
+ ownership.processGroupId,
+ ]);
+ expect(groups.get(ownership.processGroupId)).toEqual({
+ state: "empty",
+ });
+ } else {
+ // Kuna's version probe uses a joined direct execFile child, without a
+ // detached run-token group. Do not invent a group owner from its PID.
+ expect(() => process.kill(observed.pid, 0)).toThrowError(
+ expect.objectContaining({ code: "ESRCH" }),
+ );
+ }
expect(result, stderr).toEqual({ code: expected, signal: null });
} finally {
try {
+ await writeFile(release, "release");
if (ownership !== undefined)
expect((await cleanupOwnedProcessGroup(ownership)).cleaned).toBe(
true,
diff --git a/tests/boundary/providers/kuna/kunaDoctor.test.ts b/tests/boundary/providers/kuna/kunaDoctor.test.ts
index 0e63a81f1..a5124f235 100644
--- a/tests/boundary/providers/kuna/kunaDoctor.test.ts
+++ b/tests/boundary/providers/kuna/kunaDoctor.test.ts
@@ -5,7 +5,10 @@ import { expect, it as test } from "vitest";
import { inspectKunaProviderOwned as inspectKunaProvider } from "./kunaFileCloseOwner.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
-import { writeFakeKuna } from "./fakeKuna.js";
+import { fakeKunaCalls, writeFakeKuna } from "./fakeKuna.js";
+import { createSystemDoctorHost } from "../../../../src/doctorRuntime.js";
+import { AnalysisCancelledError } from "../../../../src/domain/analysisErrorCore.js";
+import { STARTUP_OWNER_CLOSED } from "../../../../src/process/SharedStartupAttempt.js";
const it = test.skipIf(process.platform === "win32");
@@ -134,3 +137,112 @@ it("reports a cache root REA cannot create under its nearest existing parent", a
detail: expect.stringContaining("not a directory"),
});
});
+
+const doctorEnvironment = (root: string, kuna: string): NodeJS.ProcessEnv => ({
+ HOME: root,
+ PATH: "",
+ JAVA_HOME: join(root, "missing-jdk"),
+ GHIDRA_INSTALL_DIR: join(root, "missing-ghidra"),
+ REA_KUNA_COMMAND: kuna,
+ REA_KUNA_CACHE_DIR: join(root, "cache"),
+});
+
+// Exercise the production composition, not just Kuna's installation helper:
+// both the caller signal and the host's own close signal must reach the probe.
+it.each(["caller", "host"] as const)(
+ "cancels and joins the composed Kuna doctor probe on %s cancellation",
+ async (source) => {
+ const root = await createTestTempDirectory("rea-kuna-doctor-cancel-");
+ const gate = join(root, "release-version");
+ const kuna = await writeFakeKuna(root, {
+ version: { stdout: "kuna 1.833\n", gate },
+ });
+ const controller = new AbortController();
+ const reason = { request: "cancel Kuna doctor" };
+ const host = createSystemDoctorHost(
+ doctorEnvironment(root, kuna),
+ controller.signal,
+ );
+ let settled = false;
+ const inspection = host.providerInspections!().then(
+ () => {
+ settled = true;
+ return undefined;
+ },
+ (cause: unknown) => {
+ settled = true;
+ return cause;
+ },
+ );
+ let closing: ReturnType<NonNullable<typeof host.close>> | undefined;
+ try {
+ await expect.poll(async () => (await fakeKunaCalls(kuna)).length).toBe(1);
+ const probe = (await fakeKunaCalls(kuna))[0];
+ if (probe === undefined) throw new Error("Missing Kuna version probe");
+ expect(probe.argv).toEqual(["--version"]);
+ if (source === "caller") controller.abort(reason);
+ else closing = host.close!();
+ // The unreleased probe normally waits for its ten-second deadline.
+ await expect.poll(() => settled, { timeout: 2_000 }).toBe(true);
+ const failure = await inspection;
+ expect(failure).toBeInstanceOf(AnalysisCancelledError);
+ if (!(failure instanceof AnalysisCancelledError))
+ throw new Error("Expected Kuna inspection cancellation");
+ expect(failure.operation).toBe("doctor");
+ expect(failure.cause).toBe(
+ source === "caller" ? reason : STARTUP_OWNER_CLOSED,
+ );
+ // Cancellation only settles once execFile has reaped its direct child.
+ expect(() => process.kill(probe.pid, 0)).toThrowError(
+ expect.objectContaining({ code: "ESRCH" }),
+ );
+ await closing;
+ expect(await fakeKunaCalls(kuna)).toHaveLength(1);
+ } finally {
+ await writeFile(gate, "release");
+ await inspection;
+ await closing;
+ await host.close!();
+ }
+ },
+);
+
+it("does not launch the composed Kuna probe for an already cancelled caller", async () => {
+ const root = await createTestTempDirectory("rea-kuna-doctor-preabort-");
+ const kuna = await writeFakeKuna(root);
+ const controller = new AbortController();
+ controller.abort({ request: "cancel before inspection" });
+ const host = createSystemDoctorHost(
+ doctorEnvironment(root, kuna),
+ controller.signal,
+ );
+ try {
+ await expect(host.providerInspections!()).rejects.toBeDefined();
+ expect(await fakeKunaCalls(kuna)).toEqual([]);
+ } finally {
+ await host.close!();
+ }
+});
+
+it("keeps a healthy composed Kuna inspection when the caller stays active", async () => {
+ const root = await createTestTempDirectory("rea-kuna-doctor-active-");
+ const kuna = await writeFakeKuna(root);
+ const host = createSystemDoctorHost(
+ doctorEnvironment(root, kuna),
+ new AbortController().signal,
+ );
+ try {
+ expect(await host.providerInspections!()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: "kuna",
+ available: true,
+ providerVersion: "1.833",
+ }),
+ ]),
+ );
+ expect(await fakeKunaCalls(kuna)).toHaveLength(1);
+ } finally {
+ await host.close!();
+ }
+});
diff --git a/tests/boundary/providers/kuna/kunaHashOwnerPropagation.test.ts b/tests/boundary/providers/kuna/kunaHashOwnerPropagation.test.ts
index b09c1e15d..616e51aad 100644
--- a/tests/boundary/providers/kuna/kunaHashOwnerPropagation.test.ts
+++ b/tests/boundary/providers/kuna/kunaHashOwnerPropagation.test.ts
@@ -1,4 +1,12 @@
-import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
+import {
+ chmod,
+ mkdir,
+ readFile,
+ realpath,
+ symlink,
+ writeFile,
+} from "node:fs/promises";
+import { createHash } from "node:crypto";
import { join } from "node:path";
import { afterEach, expect, it, vi } from "vitest";
@@ -16,6 +24,9 @@ const injected = vi.hoisted(() => ({
failCloseReadStage: undefined as "fingerprint" | "shebang" | undefined,
failReadStage: undefined as "fingerprint" | "shebang" | undefined,
abortOnReadFailure: undefined as (() => void) | undefined,
+ abortOnClose: undefined as
+ | { stage: "fingerprint" | "shebang"; abort: () => void }
+ | undefined,
handles: [] as import("node:fs/promises").FileHandle[],
}));
@@ -27,6 +38,7 @@ afterEach(async () => {
injected.failCloseReadStage = undefined;
injected.failReadStage = undefined;
injected.abortOnReadFailure = undefined;
+ injected.abortOnClose = undefined;
for (const handle of injected.handles.splice(0))
if (handle.fd >= 0) await handle.close();
});
@@ -45,16 +57,19 @@ vi.mock("../../../../src/filesystem/RegularFile.js", async (importOriginal) => {
const failNextClose = injected.failNextClose;
const failCloseReadStage = injected.failCloseReadStage;
const failReadStage = injected.failReadStage;
+ const abortOnClose = injected.abortOnClose;
if (
!failNextClose &&
!injected.holdCloseFailures &&
!failCloseReadStage &&
- !failReadStage
+ !failReadStage &&
+ !abortOnClose
)
return handle;
injected.failNextClose = false;
let readStageMatched = false;
let failedClose = false;
+ let abortCloseMatched = false;
return {
get fd() {
return handle.fd;
@@ -67,6 +82,11 @@ vi.mock("../../../../src/filesystem/RegularFile.js", async (importOriginal) => {
length: number,
position: number,
) => {
+ if (
+ (abortOnClose?.stage === "fingerprint" && length > 2) ||
+ (abortOnClose?.stage === "shebang" && length === 2)
+ )
+ abortCloseMatched = true;
if (
(failReadStage === "fingerprint" && length > 2) ||
(failReadStage === "shebang" && length === 2)
@@ -83,6 +103,7 @@ vi.mock("../../../../src/filesystem/RegularFile.js", async (importOriginal) => {
},
close: async () => {
injected.closeCalls += 1;
+ if (abortCloseMatched) abortOnClose?.abort();
if (
(failNextClose && !failedClose) ||
(readStageMatched && !failedClose) ||
@@ -628,3 +649,128 @@ it.skipIf(process.platform === "win32")(
}
},
);
+
+it.skipIf(process.platform === "win32").each(
+ (["doctor", "profile", "health"] as const).flatMap((consumer) =>
+ (["fingerprint", "shebang"] as const).flatMap((stage) =>
+ [false, true].map((closeRefusal) => ({
+ consumer,
+ stage,
+ closeRefusal,
+ })),
+ ),
+ ),
+)(
+ "preserves completed installation facts for $consumer during $stage close, refusal=$closeRefusal",
+ async ({ consumer, stage, closeRefusal }) => {
+ const fixture = await session("rea-kuna-completed-installation-cancel-");
+ const bytes = await readFile(fixture.kuna);
+ const executable = await realpath(fixture.kuna);
+ const command =
+ consumer === "doctor"
+ ? join(fixture.root, "selected-kuna")
+ : fixture.kuna;
+ if (consumer === "doctor") await symlink(fixture.kuna, command);
+ const fingerprint = {
+ sha256: createHash("sha256").update(bytes).digest("hex"),
+ bytes: bytes.length,
+ };
+ const controller = new AbortController();
+ const reason = { request: "cancel completed Kuna installation read" };
+ const resources = new ArtifactResourceScope();
+ const fileCloseResources: FileCloseResourceOwner = {
+ retain: (owner, resource) =>
+ resources.retain({
+ kind: "lease",
+ resource,
+ lease: { release: () => owner.close() },
+ }),
+ run: (operation) => resources.run(operation),
+ };
+ const client = consumer === "health" ? fixture.open() : undefined;
+ injected.abortOnClose = { stage, abort: () => controller.abort(reason) };
+ injected.failCloseReadStage = closeRefusal ? stage : undefined;
+ let failure: AnalysisError | undefined;
+ try {
+ let diagnostics: AnalysisError["diagnostics"];
+ if (consumer === "doctor") {
+ await inspectKunaProvider(
+ {
+ REA_KUNA_COMMAND: command,
+ REA_KUNA_CACHE_DIR: fixture.cacheRoot,
+ },
+ process.platform,
+ { fileCloseResources, signal: controller.signal },
+ ).then(
+ (inspection) => {
+ expect(closeRefusal).toBe(true);
+ expect(inspection.checks[0]).toMatchObject({
+ code: "cleanup_incomplete",
+ });
+ diagnostics = inspection.checks[0]?.details;
+ },
+ (cause: unknown) => {
+ if (!(cause instanceof AnalysisError)) throw cause;
+ failure = cause;
+ },
+ );
+ } else {
+ const result =
+ consumer === "profile"
+ ? await fixture.provider.resolveAnalysisProfile(fixture.target, {
+ fileCloseResources,
+ signal: controller.signal,
+ })
+ : await client!.execute(
+ "health",
+ {},
+ { signal: controller.signal },
+ );
+ if (result.ok) throw new Error("Expected installation cancellation");
+ failure = result.error;
+ }
+ if (failure !== undefined) {
+ expect(failure).toMatchObject({
+ _tag: "AnalysisCancelledError",
+ cleanupIncomplete: closeRefusal,
+ });
+ expect(failure.cause).toBe(reason);
+ diagnostics = failure.diagnostics;
+ expect(projectAnalysisError(failure)).toMatchObject({
+ code: closeRefusal ? "cleanup_incomplete" : "cancelled",
+ details: {
+ ...(closeRefusal ? { execution_failure: "cancelled" } : {}),
+ diagnostics: {
+ kuna_installation: {
+ status: "partial",
+ completed_hash: fingerprint,
+ },
+ },
+ },
+ });
+ }
+ expect(diagnostics).toMatchObject({
+ kuna_installation: {
+ status: "partial",
+ command,
+ executable,
+ version: "1.833",
+ completed_hash: fingerprint,
+ ...(stage === "shebang" ? { script: true } : {}),
+ },
+ });
+ if (stage === "fingerprint")
+ expect(diagnostics?.["kuna_installation"]).not.toHaveProperty("script");
+ expect(injected.handles.some((handle) => handle.fd >= 0)).toBe(
+ closeRefusal,
+ );
+ } finally {
+ injected.abortOnClose = undefined;
+ injected.failCloseReadStage = undefined;
+ await resources.close();
+ if (client !== undefined) expect((await client.close()).ok).toBe(true);
+ expect(failure?.cleanupIncomplete ?? false).toBe(false);
+ expect(injected.handles.every((handle) => handle.fd < 0)).toBe(true);
+ }
+ },
+);
diff --git a/tests/boundary/providers/kuna/kunaInstallation.test.ts b/tests/boundary/providers/kuna/kunaInstallation.test.ts
index 6e5401dd5..c4f7b42cb 100644
--- a/tests/boundary/providers/kuna/kunaInstallation.test.ts
+++ b/tests/boundary/providers/kuna/kunaInstallation.test.ts
@@ -1,9 +1,16 @@
import { createHash } from "node:crypto";
-import { chmod, readFile, realpath, symlink } from "node:fs/promises";
+import {
+ chmod,
+ readFile,
+ realpath,
+ symlink,
+ writeFile,
+} from "node:fs/promises";
import { join } from "node:path";
import { expect, it as test } from "vitest";
+import { kunaInstallationCancellation } from "../../../../src/kuna/KunaInstallation.js";
import { readKunaConfiguration } from "../../../../src/kuna/KunaConfiguration.js";
import { inspectKunaInstallationOwned as inspectKunaInstallation } from "./kunaFileCloseOwner.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
@@ -219,3 +226,106 @@ it("stops a version probe that ignores SIGTERM instead of waiting on it", async
const pid = (await fakeKunaCalls(kuna))[0]?.pid ?? 0;
expect(() => process.kill(pid, 0)).toThrow();
}, 20_000);
+
+it("keeps a version deadline ahead of cancellation during its joined stop", async () => {
+ const root = await createTestTempDirectory("rea-kuna-deadline-first-");
+ const command = join(root, "probe.cjs");
+ const stopped = join(root, "stopped");
+ const release = join(root, "release");
+ await (
+ await import("node:fs/promises")
+ ).writeFile(
+ command,
+ `#!${process.execPath}
+const fs = require("node:fs");
+process.on("SIGTERM", () => fs.writeFileSync(${JSON.stringify(stopped)}, "timeout stop"));
+const gate = setInterval(() => {
+ if (fs.existsSync(${JSON.stringify(release)})) { clearInterval(gate); process.exit(0); }
+}, 5);
+setTimeout(() => process.exit(9), 10000).unref();
+`,
+ { mode: 0o700 },
+ );
+ const controller = new AbortController();
+ const pending = inspectKunaInstallation(
+ {
+ REA_KUNA_COMMAND: command,
+ REA_KUNA_CACHE_DIR: join(root, "cache"),
+ },
+ { signal: controller.signal, probeTimeoutMs: 1000 },
+ );
+ const outcome = pending.then(
+ (value) => ({ kind: "result" as const, value }),
+ (cause: unknown) => ({ kind: "thrown" as const, cause }),
+ );
+ try {
+ await expect
+ .poll(
+ () =>
+ readFile(stopped).then(
+ () => true,
+ () => false,
+ ),
+ { timeout: 5000 },
+ )
+ .toBe(true);
+ controller.abort({ request: "late doctor cancellation" });
+ await writeFile(release, "release");
+ expect(await outcome).toMatchObject({
+ kind: "result",
+ value: {
+ ok: false,
+ error: {
+ code: "version_unresolved",
+ diagnostics: { deadline_ms: 1000, killed: true },
+ },
+ },
+ });
+ } finally {
+ await writeFile(release, "release");
+ await outcome;
+ }
+});
+
+it("retains an admitted lookup failure when cancellation arrives during settlement", async () => {
+ const root = await createTestTempDirectory("rea-kuna-lookup-failure-");
+ const command = join(root, "missing-kuna");
+ const controller = new AbortController();
+ const pending = inspectKunaInstallation(
+ {
+ REA_KUNA_COMMAND: command,
+ REA_KUNA_CACHE_DIR: join(root, "cache"),
+ },
+ { signal: controller.signal },
+ );
+ controller.abort({ request: "cancel in-flight lookup" });
+ const outcome = await pending.then(
+ (value) => ({ kind: "result" as const, value }),
+ (cause: unknown) => ({ kind: "thrown" as const, cause }),
+ );
+ expect(outcome).toMatchObject({
+ kind: "result",
+ value: {
+ ok: false,
+ error: { code: "executable_missing", diagnostics: { command } },
+ },
+ });
+});
+
+it("preserves an already-cancelled caller before admitting a lookup", async () => {
+ const root = await createTestTempDirectory("rea-kuna-preabort-lookup-");
+ const controller = new AbortController();
+ const reason = { request: "cancel before lookup" };
+ controller.abort(reason);
+ const cause: unknown = await inspectKunaInstallation(
+ {
+ REA_KUNA_COMMAND: join(root, "missing-kuna"),
+ REA_KUNA_CACHE_DIR: join(root, "cache"),
+ },
+ { signal: controller.signal },
+ ).then(
+ () => undefined,
+ (error: unknown) => error,
+ );
+ expect(kunaInstallationCancellation(cause)?.reason).toBe(reason);
+});
diff --git a/tests/boundary/providers/kuna/kunaInstallationLifetime.test.ts b/tests/boundary/providers/kuna/kunaInstallationLifetime.test.ts
index ed70d6d0f..8ae23a75d 100644
--- a/tests/boundary/providers/kuna/kunaInstallationLifetime.test.ts
+++ b/tests/boundary/providers/kuna/kunaInstallationLifetime.test.ts
@@ -1,4 +1,3 @@
-import { regularFileCancellation } from "../../../../src/filesystem/OwnedRegularFile.js";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
const gates = vi.hoisted(() => {
@@ -63,7 +62,10 @@ vi.mock("../../../../src/filesystem/RegularFile.js", async (importOriginal) => {
import { ArtifactResourceScope } from "../../../../src/artifacts/ArtifactResourceScope.js";
import type { FileCloseResourceOwner } from "../../../../src/application/AnalysisProvider.js";
-import { inspectKunaInstallation } from "../../../../src/kuna/KunaInstallation.js";
+import {
+ inspectKunaInstallation,
+ kunaInstallationCancellation,
+} from "../../../../src/kuna/KunaInstallation.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { writeFakeKuna } from "./fakeKuna.js";
import { session } from "./kunaSessionFixture.js";
@@ -138,7 +140,7 @@ it
const failure: unknown = await inspection.catch(
(cause: unknown) => cause,
);
- const cancellation = regularFileCancellation(failure);
+ const cancellation = kunaInstallationCancellation(failure);
expect(cancellation).toBeDefined();
expect(cancellation?.reason).toBe(controller.signal.reason);
await expect(cleanup).resolves.toBeUndefined();