Skip to content

armgit / rea

Public Imported from GitHub
0

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

fix(kuna): share and bound single-function decompile runs (#4045)

Kaoru0822670ad6bd96d8
diff --git a/docs/kuna-provider.md b/docs/kuna-provider.md
index 0550f9cf5..b6b4dd79b 100644
--- a/docs/kuna-provider.md
+++ b/docs/kuna-provider.md
@@ -44,6 +44,7 @@ The first analysis request in a session looks for this target's export in the ca
- **Cold cache:**
- REA starts `kuna decompile-project` in the background on a private copy of the target.
- Meanwhile, pseudocode comes from one `kuna decompile --addr` run, and listings from `kuna functions --json`.
+ - Requests for the same function share one run; it stops when its last waiting request is cancelled. Each run analyzes the whole image again in its own process, so one REA process runs at most as many at once as the host has cores beyond `REA_KUNA_JOBS` (at least one). Further requests wait in order, and a waiting request is answered from the export if it finishes first.
- Assembly and data names wait for the export; progress notifications report the wait every ten seconds.
- A single-function answer says so in its limitations. It lacks the export's whole-program prototypes, so a later request can return different text for the same function.
diff --git a/src/kuna/KunaProvider.ts b/src/kuna/KunaProvider.ts
index 4f79acab2..d6582c231 100644
--- a/src/kuna/KunaProvider.ts
+++ b/src/kuna/KunaProvider.ts
@@ -30,6 +30,7 @@ import {
kunaCapabilities,
} from "./KunaProviderCapabilities.js";
import { KUNA_COMMAND_REMEDIATION, KUNA_PROVIDER_ID } from "./KunaRelease.js";
+import { KunaRunSlots } from "./KunaRunSlots.js";
import { KunaSessionClient } from "./KunaSessionClient.js";
/** Architectures REA verified Kuna on: x86-64 and AArch64 ELF and Mach-O, plus ARM Thumb. */
@@ -47,18 +48,23 @@ export class KunaProvider implements AnalysisProviderCandidate {
readonly #environment: Readonly<NodeJS.ProcessEnv>;
readonly #platform: NodeJS.Platform;
readonly #launcher: KunaProcessLauncher | undefined;
+ readonly #singleFunctionRuns: number | undefined;
#cache: KunaProjectCache | undefined;
+ #runSlots: KunaRunSlots | undefined;
constructor(
environment: Readonly<NodeJS.ProcessEnv>,
options: {
readonly platform?: NodeJS.Platform;
readonly launcher?: KunaProcessLauncher;
+ /** Test seam for concurrent single-function runs; production derives it from the host. */
+ readonly singleFunctionRuns?: number;
} = {},
) {
this.#platform = options.platform ?? process.platform;
this.#environment = snapshotEnvironment(environment, this.#platform);
this.#launcher = options.launcher;
+ this.#singleFunctionRuns = options.singleFunctionRuns;
}
identity() {
@@ -208,6 +214,7 @@ export class KunaProvider implements AnalysisProviderCandidate {
};
return new KunaSessionClient(target, profile, {
cache: this.#projectCache(configuration.value),
+ runSlots: this.#singleFunctionSlots(configuration.value),
environment: this.#environment,
...(this.#launcher === undefined ? {} : { launcher: this.#launcher }),
});
@@ -221,4 +228,13 @@ export class KunaProvider implements AnalysisProviderCandidate {
});
return this.#cache;
}
+
+ /** One admission pool per provider, so concurrent sessions share the host's cores. */
+ #singleFunctionSlots(configuration: KunaConfiguration): KunaRunSlots {
+ this.#runSlots ??=
+ this.#singleFunctionRuns === undefined
+ ? KunaRunSlots.forHost(configuration.jobs)
+ : new KunaRunSlots(this.#singleFunctionRuns);
+ return this.#runSlots;
+ }
}
diff --git a/src/kuna/KunaRunSlots.ts b/src/kuna/KunaRunSlots.ts
new file mode 100644
index 000000000..e82c311eb
--- /dev/null
+++ b/src/kuna/KunaRunSlots.ts
@@ -0,0 +1,60 @@
+import { availableParallelism } from "node:os";
+
+/** Releases one admitted run's slot; later calls do nothing. */
+export type KunaRunRelease = () => void;
+
+/**
+ * Process-wide admission for single-function `kuna decompile` runs.
+ *
+ * Each run analyzes the whole image again in its own process tree, which held
+ * about 360 MiB resident and close to one core on a 200 KiB Mach-O. These runs only
+ * happen while the project export builds, so they share the cores its
+ * `--jobs` workers leave free, and requests beyond that wait in FIFO order.
+ */
+export class KunaRunSlots {
+ readonly #capacity: number;
+ #active = 0;
+ readonly #waiting: (() => void)[] = [];
+
+ constructor(capacity: number) {
+ this.#capacity = Math.max(1, capacity);
+ }
+
+ /** Slots for the cores an export with `jobs` workers leaves on this host. */
+ static forHost(jobs: number): KunaRunSlots {
+ return new KunaRunSlots(availableParallelism() - jobs);
+ }
+
+ /** Wait for a slot; undefined when the signal aborts first. */
+ acquire(signal: AbortSignal): Promise<KunaRunRelease | undefined> {
+ if (signal.aborted) return Promise.resolve(undefined);
+ if (this.#active < this.#capacity) {
+ this.#active += 1;
+ return Promise.resolve(this.#release());
+ }
+ return new Promise((resolve) => {
+ const grant = () => {
+ signal.removeEventListener("abort", onAbort);
+ this.#active += 1;
+ resolve(this.#release());
+ };
+ const onAbort = () => {
+ const index = this.#waiting.indexOf(grant);
+ if (index !== -1) this.#waiting.splice(index, 1);
+ resolve(undefined);
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ this.#waiting.push(grant);
+ });
+ }
+
+ #release(): KunaRunRelease {
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ this.#active -= 1;
+ this.#waiting.shift()?.();
+ };
+ }
+}
diff --git a/src/kuna/KunaSessionClient.ts b/src/kuna/KunaSessionClient.ts
index 2c64975eb..d62d039b9 100644
--- a/src/kuna/KunaSessionClient.ts
+++ b/src/kuna/KunaSessionClient.ts
@@ -60,6 +60,7 @@ import {
} from "./KunaProviderCapabilities.js";
import { KUNA_PROVIDER_ID } from "./KunaRelease.js";
import { KUNA_FUNCTION_TEXT_BYTES } from "./KunaLimits.js";
+import type { KunaRunRelease, KunaRunSlots } from "./KunaRunSlots.js";
import {
KunaProjectReader,
type KunaProjectFileSpan,
@@ -81,6 +82,21 @@ interface InventoryIndex {
readonly byName: ReadonlyMap<string, readonly KunaInventoryFunction[]>;
}
+/** A queued single-function request found the export finished first. */
+const EXPORT_READY = Symbol("kuna-export-ready");
+
+type SingleFunctionOutcome =
+ | Result<string, AnalysisError>
+ | typeof EXPORT_READY;
+
+/** One single-function run that every request for its address shares. */
+interface SingleFunctionRun {
+ readonly outcome: Promise<SingleFunctionOutcome>;
+ /** Stops the run once every waiter has left. */
+ readonly controller: AbortController;
+ waiters: number;
+}
+
interface Answer {
readonly result: JsonValue;
readonly source: AnswerSource | null;
@@ -150,6 +166,9 @@ export class KunaSessionClient implements AnalysisClient {
readonly #cache: KunaProjectCache;
readonly #environment: Readonly<NodeJS.ProcessEnv>;
readonly #launcher: KunaProcessLauncher | undefined;
+ readonly #runSlots: KunaRunSlots;
+ /** Single-function runs in flight, by entry address. */
+ readonly #singleFunctionRuns = new Map<string, SingleFunctionRun>();
/** Owns background work: aborting it cancels this session's export interest. */
readonly #session = new AbortController();
/** Requests and shared readers retain their resources until their work settles. */
@@ -190,6 +209,7 @@ export class KunaSessionClient implements AnalysisClient {
profile: AnalysisProfileCommitment | undefined,
dependencies: {
readonly cache: KunaProjectCache;
+ readonly runSlots: KunaRunSlots;
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly launcher?: KunaProcessLauncher;
},
@@ -197,6 +217,7 @@ export class KunaSessionClient implements AnalysisClient {
this.#target = target;
this.#profile = profile;
this.#cache = dependencies.cache;
+ this.#runSlots = dependencies.runSlots;
this.#environment = dependencies.environment;
this.#launcher = dependencies.launcher;
}
@@ -644,52 +665,177 @@ export class KunaSessionClient implements AnalysisClient {
installation: KunaInstallation,
options: ExecutionOptions,
): Promise<Result<Omit<Answer, "locations">, AnalysisError>> {
- for (let attempt = 0; this.#reader !== undefined; attempt += 1) {
+ for (let recovered = false; ;) {
const reader = this.#reader;
- try {
- const text = await reader.pseudocode(entry.address, operation);
- if (!text.ok) return text;
- return ok({
- ...text.value,
- source: { kind: "project-export", project: reader.project },
- });
- } catch (cause: unknown) {
- if (!isMissing(cause) || attempt !== 0) throw cause;
- this.#invalidateProject(reader);
- await this.#startProject(installation);
+ if (reader !== undefined) {
+ try {
+ const text = await reader.pseudocode(entry.address, operation);
+ if (!text.ok) return text;
+ return ok({
+ ...text.value,
+ source: { kind: "project-export", project: reader.project },
+ });
+ } catch (cause: unknown) {
+ if (!isMissing(cause) || recovered) throw cause;
+ recovered = true;
+ this.#invalidateProject(reader);
+ await this.#startProject(installation);
+ continue;
+ }
}
+ const outcome = await this.#joinSingleFunction(
+ operation,
+ entry.address,
+ installation,
+ options.signal,
+ );
+ if (outcome === EXPORT_READY) continue;
+ if (!outcome.ok) return outcome;
+ const exportFailure = await this.#settledExportFailure();
+ return ok({
+ result: outcome.value,
+ source: { kind: "single-function" },
+ limitations: [
+ KUNA_SINGLE_FUNCTION_LIMITATION,
+ ...(exportFailure === undefined
+ ? []
+ : [
+ `The project export failed, so later requests also use single-function runs: ${exportFailure}`,
+ ]),
+ ],
+ });
}
+ }
+
+ /**
+ * Wait for this address's shared single-function run, starting it when none
+ * is in flight. A caller's cancellation stops only its own wait while others
+ * still wait; the last waiter stops the run and receives how it ended,
+ * including cleanup it could not prove.
+ */
+ #joinSingleFunction(
+ operation: string,
+ address: string,
+ installation: KunaInstallation,
+ signal: AbortSignal | undefined,
+ ): Promise<SingleFunctionOutcome> {
+ if (cancelled(signal))
+ return Promise.resolve(err(new AnalysisCancelledError(operation)));
+ let run = this.#singleFunctionRuns.get(address);
+ if (run === undefined) {
+ const controller = new AbortController();
+ const created: SingleFunctionRun = {
+ controller,
+ waiters: 0,
+ outcome: this.#own(
+ this.#singleFunction(
+ operation,
+ address,
+ installation,
+ AbortSignal.any([this.#session.signal, controller.signal]),
+ ).catch((cause: unknown) => err(failure(operation, cause))),
+ ),
+ };
+ this.#singleFunctionRuns.set(address, created);
+ void created.outcome.then(() => {
+ if (this.#singleFunctionRuns.get(address) === created)
+ this.#singleFunctionRuns.delete(address);
+ });
+ run = created;
+ }
+ const shared = run;
+ shared.waiters += 1;
+ return new Promise((resolve) => {
+ let waiting = true;
+ const leave = () => {
+ waiting = false;
+ shared.waiters -= 1;
+ };
+ const onAbort = () => {
+ if (!waiting) return;
+ leave();
+ if (shared.waiters > 0) {
+ resolve(err(new AnalysisCancelledError(operation)));
+ return;
+ }
+ // A run whose waiters all left winds down; a new request starts afresh.
+ if (this.#singleFunctionRuns.get(address) === shared)
+ this.#singleFunctionRuns.delete(address);
+ shared.controller.abort();
+ };
+ signal?.addEventListener("abort", onAbort, { once: true });
+ void shared.outcome.then((outcome) => {
+ signal?.removeEventListener("abort", onAbort);
+ if (waiting) leave();
+ resolve(outcome);
+ });
+ });
+ }
+
+ /** One `kuna decompile --addr` run, admitted by the provider's run slots. */
+ async #singleFunction(
+ operation: string,
+ address: string,
+ installation: KunaInstallation,
+ signal: AbortSignal,
+ ): Promise<SingleFunctionOutcome> {
const workspace = await this.#ensureWorkspace();
if (!workspace.ok) return workspace;
- const run = await runKunaCommand({
- installation,
- arguments: ["decompile", workspace.value.input, entry.address, "--addr"],
- workspace: workspace.value.root.path,
- operation,
- timeoutMs: installation.configuration.functionTimeoutMs,
- reportedTimeoutMs: installation.configuration.functionTimeoutMs,
- outputBytes: KUNA_FUNCTION_TEXT_BYTES,
- signal: options.signal ?? this.#session.signal,
- launcher: this.#launcher,
- });
- if (run.kind === "retained") {
- this.#retained.push({ error: run.error, owner: run.owner });
- return err(run.error);
+ const admitted = await this.#admitSingleFunction(signal);
+ if (admitted === EXPORT_READY) return admitted;
+ if (admitted === undefined)
+ return err(new AnalysisCancelledError(operation));
+ try {
+ const run = await runKunaCommand({
+ installation,
+ arguments: ["decompile", workspace.value.input, address, "--addr"],
+ workspace: workspace.value.root.path,
+ operation,
+ timeoutMs: installation.configuration.functionTimeoutMs,
+ reportedTimeoutMs: installation.configuration.functionTimeoutMs,
+ outputBytes: KUNA_FUNCTION_TEXT_BYTES,
+ signal,
+ launcher: this.#launcher,
+ });
+ if (run.kind === "retained") {
+ this.#retained.push({ error: run.error, owner: run.owner });
+ return err(run.error);
+ }
+ if (run.kind === "failed") return err(run.error);
+ return ok(run.snapshot.stdout.text.replace(/\n+$/u, ""));
+ } finally {
+ admitted();
}
- if (run.kind === "failed") return err(run.error);
- const exportFailure = await this.#settledExportFailure();
- return ok({
- result: run.snapshot.stdout.text.replace(/\n+$/u, ""),
- source: { kind: "single-function" },
- limitations: [
- KUNA_SINGLE_FUNCTION_LIMITATION,
- ...(exportFailure === undefined
- ? []
- : [
- `The project export failed, so later requests also use single-function runs: ${exportFailure}`,
- ]),
- ],
- });
+ }
+
+ /**
+ * A run slot, or EXPORT_READY when the export this session builds finishes
+ * first; the export then answers without another Kuna process.
+ */
+ async #admitSingleFunction(
+ signal: AbortSignal,
+ ): Promise<KunaRunRelease | undefined | typeof EXPORT_READY> {
+ const yielded = new AbortController();
+ const slot = this.#runSlots.acquire(
+ AbortSignal.any([signal, yielded.signal]),
+ );
+ const project = this.#project;
+ const exported =
+ project === undefined
+ ? undefined
+ : project.then((built) =>
+ built.ok && this.#reader !== undefined
+ ? EXPORT_READY
+ : new Promise<never>(() => undefined),
+ );
+ const admitted = await (exported === undefined
+ ? slot
+ : Promise.race([slot, exported]));
+ if (admitted !== EXPORT_READY) return admitted;
+ yielded.abort();
+ // A slot granted in the same turn is returned rather than leaked.
+ void slot.then((release) => release?.());
+ return EXPORT_READY;
}
async #assemblyText(
diff --git a/tests/boundary/providers/kuna/fakeKuna.ts b/tests/boundary/providers/kuna/fakeKuna.ts
index 0195cb9d3..697e99f69 100644
--- a/tests/boundary/providers/kuna/fakeKuna.ts
+++ b/tests/boundary/providers/kuna/fakeKuna.ts
@@ -29,6 +29,8 @@ export interface FakeKunaBehavior {
/** Extra C comment bytes inside each exported body, for buffered-read capacity. */
readonly cPadding?: number;
readonly decompile?: "ok" | "hang";
+ /** Milliseconds one `decompile --addr` run takes before printing. */
+ readonly decompileDelayMs?: number;
/** Milliseconds `functions --json` takes before printing. */
readonly inventoryDelayMs?: number;
/** Milliseconds the export takes before writing its files. */
@@ -45,7 +47,7 @@ const SCRIPT = String.raw`
const fs = require("node:fs");
const path = require("node:path");
const behavior = JSON.parse(fs.readFileSync(__filename + ".json", "utf8"));
-fs.appendFileSync(__filename + ".calls", JSON.stringify({ pid: process.pid, argv: process.argv.slice(2), home: process.env.HOME, xdg: process.env.XDG_CACHE_HOME, path: process.env.PATH ?? null }) + "\n");
+fs.appendFileSync(__filename + ".calls", JSON.stringify({ pid: process.pid, at: Date.now(), argv: process.argv.slice(2), home: process.env.HOME, xdg: process.env.XDG_CACHE_HOME, path: process.env.PATH ?? null }) + "\n");
const args = process.argv.slice(2);
const functions = behavior.functions ?? [{ name: "main", addr: "0x1000" }, { name: "helper", addr: "0x1040" }];
const hang = () => setInterval(() => {}, 1000);
@@ -95,7 +97,10 @@ if (args[0] === "--version") {
const fn = functions.find((candidate) => candidate.addr === args[2]);
if (behavior.decompile === "hang") hang();
else if (fn === undefined) { process.stderr.write("error: no function at " + args[2] + "\n"); process.exit(1); }
- else process.stdout.write("int " + fn.name + "(void) // single-function\n{\n return 0;\n}\n");
+ else setTimeout(() => {
+ process.stdout.write("int " + fn.name + "(void) // single-function\n{\n return 0;\n}\n");
+ fs.appendFileSync(__filename + ".exits", JSON.stringify({ pid: process.pid, at: Date.now() }) + "\n");
+ }, behavior.decompileDelayMs ?? 0);
} else {
process.stderr.write("unexpected command\n");
process.exit(2);
@@ -125,6 +130,8 @@ export const fakeKunaCalls = async (
): Promise<
readonly {
readonly pid: number;
+ /** Epoch milliseconds when the invocation started. */
+ readonly at: number;
readonly argv: readonly string[];
readonly home: string;
readonly xdg: string;
@@ -137,3 +144,19 @@ export const fakeKunaCalls = async (
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as never);
};
+
+/** When each completed single-function run finished, by process id. */
+export const fakeKunaExits = async (
+ path: string,
+): Promise<ReadonlyMap<number, number>> => {
+ const text = await readFile(`${path}.exits`, "utf8").catch(() => "");
+ return new Map(
+ text
+ .split("\n")
+ .filter((line) => line.length > 0)
+ .map((line) => {
+ const { pid, at } = JSON.parse(line) as { pid: number; at: number };
+ return [pid, at];
+ }),
+ );
+};
diff --git a/tests/boundary/providers/kuna/kunaInstallation.test.ts b/tests/boundary/providers/kuna/kunaInstallation.test.ts
index 51bc52450..dfd7b3e29 100644
--- a/tests/boundary/providers/kuna/kunaInstallation.test.ts
+++ b/tests/boundary/providers/kuna/kunaInstallation.test.ts
@@ -40,6 +40,7 @@ it("identifies a caller-selected kuna by version and digest", async () => {
expect(await fakeKunaCalls(kuna)).toEqual([
{
pid: expect.any(Number),
+ at: expect.any(Number),
argv: ["--version"],
home: join(root, "cache", "home"),
xdg: join(root, "cache", "home", ".cache"),
diff --git a/tests/boundary/providers/kuna/kunaSessionFixture.ts b/tests/boundary/providers/kuna/kunaSessionFixture.ts
index 36f904c11..c498c5f08 100644
--- a/tests/boundary/providers/kuna/kunaSessionFixture.ts
+++ b/tests/boundary/providers/kuna/kunaSessionFixture.ts
@@ -28,6 +28,7 @@ export const session = async (
behavior: FakeKunaBehavior = {},
environment: Readonly<Record<string, string>> = {},
launcher?: KunaProcessLauncher,
+ singleFunctionRuns?: number,
) => {
const root = await createTestTempDirectory(prefix);
const kuna = await writeFakeKuna(root, { functions: FUNCTIONS, ...behavior });
@@ -47,6 +48,7 @@ export const session = async (
{
platform: process.platform,
...(launcher === undefined ? {} : { launcher }),
+ ...(singleFunctionRuns === undefined ? {} : { singleFunctionRuns }),
},
);
const profile = await provider.resolveAnalysisProfile(target);
diff --git a/tests/boundary/providers/kuna/kunaSingleFunctionRuns.test.ts b/tests/boundary/providers/kuna/kunaSingleFunctionRuns.test.ts
new file mode 100644
index 000000000..ddedc4873
--- /dev/null
+++ b/tests/boundary/providers/kuna/kunaSingleFunctionRuns.test.ts
@@ -0,0 +1,129 @@
+import { expect, it as test } from "vitest";
+
+import { fakeKunaCalls, fakeKunaExits } from "./fakeKuna.js";
+import { run, session } from "./kunaSessionFixture.js";
+
+const it = test.skipIf(process.platform === "win32");
+
+const decompilesOf = async (kuna: string) =>
+ (await fakeKunaCalls(kuna)).filter(({ argv }) => argv[0] === "decompile");
+
+it("shares one single-function run among concurrent requests for one entry", async () => {
+ const { kuna, open } = await session("rea-kuna-single-shared-", {
+ project: "hang",
+ decompileDelayMs: 300,
+ });
+ const client = open();
+ try {
+ const answers = await Promise.all(
+ ["main", "main", "0x1000"].map((procedure) =>
+ run(client, "procedure_pseudo_code", { procedure }),
+ ),
+ );
+ for (const answer of answers)
+ expect(answer).toMatchObject({
+ result: "int main(void) // single-function\n{\n return 0;\n}",
+ rawResult: { source: { kind: "single-function" } },
+ });
+ expect(await decompilesOf(kuna)).toHaveLength(1);
+ } finally {
+ expect(await client.close()).toEqual({ ok: true, value: null });
+ }
+});
+
+it("keeps a shared run for the callers still waiting when one cancels", async () => {
+ const { kuna, open } = await session("rea-kuna-single-cancel-", {
+ project: "hang",
+ decompileDelayMs: 500,
+ });
+ const client = open();
+ const caller = new AbortController();
+ try {
+ const leaving = client.execute(
+ "procedure_pseudo_code",
+ { procedure: "main" },
+ { signal: caller.signal },
+ );
+ const staying = run(client, "procedure_pseudo_code", { procedure: "main" });
+ await expect.poll(() => decompilesOf(kuna)).toHaveLength(1);
+ caller.abort();
+ expect(await leaving).toMatchObject({
+ ok: false,
+ error: { _tag: "AnalysisCancelledError" },
+ });
+ expect((await staying).rawResult).toMatchObject({
+ source: { kind: "single-function" },
+ });
+ const [call] = await decompilesOf(kuna);
+ expect((await fakeKunaExits(kuna)).has(call?.pid ?? 0)).toBe(true);
+ expect(await decompilesOf(kuna)).toHaveLength(1);
+ } finally {
+ caller.abort();
+ expect(await client.close()).toEqual({ ok: true, value: null });
+ }
+});
+
+it("admits no more concurrent single-function runs than its slots", async () => {
+ const { kuna, open } = await session(
+ "rea-kuna-single-slots-",
+ { project: "hang", decompileDelayMs: 200 },
+ {},
+ undefined,
+ 1,
+ );
+ const client = open();
+ try {
+ await Promise.all(
+ ["main", "parse"].map((procedure) =>
+ run(client, "procedure_pseudo_code", { procedure }),
+ ),
+ );
+ const [first, second] = [...(await decompilesOf(kuna))].sort(
+ (left, right) => left.at - right.at,
+ );
+ const exits = await fakeKunaExits(kuna);
+ expect(first).toBeDefined();
+ expect(second).toBeDefined();
+ // The second run starts only after the first one's process finished.
+ expect(second?.at).toBeGreaterThanOrEqual(exits.get(first?.pid ?? 0) ?? 0);
+ } finally {
+ expect(await client.close()).toEqual({ ok: true, value: null });
+ }
+});
+
+it("answers a queued request from the export once it finishes first", async () => {
+ const { kuna, open } = await session(
+ "rea-kuna-single-yield-",
+ { delayMs: 400, decompile: "hang" },
+ {},
+ undefined,
+ 1,
+ );
+ const client = open();
+ const holder = new AbortController();
+ try {
+ // This run holds the only slot until its caller leaves.
+ const holding = client.execute(
+ "procedure_pseudo_code",
+ { procedure: "main" },
+ { signal: holder.signal },
+ );
+ await expect.poll(() => decompilesOf(kuna)).toHaveLength(1);
+ const queued = await run(client, "procedure_pseudo_code", {
+ procedure: "parse",
+ });
+ expect(queued).toMatchObject({
+ result: "int parse(void)\n{\n return 1;\n}",
+ rawResult: { source: { kind: "project-export" } },
+ });
+ expect(await decompilesOf(kuna)).toHaveLength(1);
+ holder.abort();
+ expect(await holding).toMatchObject({
+ ok: false,
+ error: { _tag: "AnalysisCancelledError" },
+ });
+ } finally {
+ holder.abort();
+ expect(await client.close()).toEqual({ ok: true, value: null });
+ }
+});