diff --git a/packages/agent/src/runtime/runtime-parts/runtime-compaction.ts b/packages/agent/src/runtime/runtime-parts/runtime-compaction.ts index 2e00378..0b0429a 100644 --- a/packages/agent/src/runtime/runtime-parts/runtime-compaction.ts +++ b/packages/agent/src/runtime/runtime-parts/runtime-compaction.ts @@ -1,5 +1,6 @@ import { lstat, stat } from "node:fs/promises"; import { join } from "node:path"; +import { untilAborted } from "../../core/abort.ts"; import { AgentError } from "../../core/errors.ts"; import type { AgentRuntime, ContextEstimate } from "../../core/types.ts"; import type { CompactionState } from "../../extensions/compaction.ts"; @@ -40,6 +41,7 @@ export function createCompactionOperations({ if (error.code === "ENOENT") return undefined; throw error; }); + request.signal.throwIfAborted(); // A remembered filename legitimately has no JSONL until the first model turn, and pi writes // a header when it opens such a file; a session with no bytes has no context to warn about. if (!info?.isFile() || info.size === 0) return undefined; @@ -47,10 +49,10 @@ export function createCompactionOperations({ if (cached && cached.size === info.size && cached.mtimeMs === info.mtimeMs) return cached.value; const running = estimating.get(file); - if (running) return running; + if (running) return untilAborted(running, request.signal); + // Cancel each caller's wait independently; the file read is shared by the other callers. const task = (async () => { const { pi } = await buildRuntime(); - request.signal.throwIfAborted(); const manager = pi.SessionManager.open(file, sessionDir, homeDir); // The compaction scheduler measures this same projection, so the hint compares against // the line at which the agent would really start organizing context. @@ -69,13 +71,9 @@ export function createCompactionOperations({ // One entry per started topic; dropping the oldest bounds the map in a long-lived brain. if (estimates.size > 64) estimates.delete(estimates.keys().next().value as string); return value; - })(); + })().finally(() => estimating.delete(file)); estimating.set(file, task); - try { - return await task; - } finally { - estimating.delete(file); - } + return untilAborted(task, request.signal); }, async compactHistory(request) { const { pi, runtime } = await buildRuntime(); diff --git a/packages/agent/test/context-estimate-cancellation.test.ts b/packages/agent/test/context-estimate-cancellation.test.ts new file mode 100644 index 0000000..fe7614b --- /dev/null +++ b/packages/agent/test/context-estimate-cancellation.test.ts @@ -0,0 +1,73 @@ +import { mkdtemp, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, it, vi } from "vitest"; +import type { RuntimeContext } from "../src/runtime/runtime.ts"; +import { createCompactionOperations } from "../src/runtime/runtime-parts/runtime-compaction.ts"; +import { sessionPaths } from "../src/runtime/runtime-parts/runtime-shared.ts"; + +vi.mock("../src/runtime/runtime-parts/runtime-shared.ts", () => ({ sessionPaths: vi.fn() })); +vi.mock("node:fs/promises", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, stat: vi.fn(actual.stat) }; +}); + +it.each(["first", "second"] as const)("cancels only the %s caller", async (cancelled) => { + vi.clearAllMocks(); + const dir = await mkdtemp(join(tmpdir(), "pibot-context-estimate-")); + const file = join(dir, "session.jsonl"); + let release: (() => void) | undefined; + const ready = new Promise((resolve) => { + release = resolve; + }); + const open = vi.fn(() => ({ getBranch: () => [] })); + const runtime = { + pi: { SessionManager: { open }, buildSessionProjection: () => ({ messages: [] }) }, + }; + const buildRuntime = vi.fn(async () => { + await ready; + return runtime; + }); + const first = { controller: new AbortController(), failed: vi.fn() }; + const second = { controller: new AbortController(), failed: vi.fn() }; + const cancelledCaller = cancelled === "first" ? first : second; + const activeCaller = cancelled === "first" ? second : first; + const reason = new Error("caller cancelled"); + + try { + await writeFile(file, "{}\n"); + vi.mocked(sessionPaths).mockResolvedValue(file); + const estimate = createCompactionOperations({ + dataDir: dir, + buildRuntime, + } as unknown as RuntimeContext).estimateContext; + if (!estimate) throw new Error("Missing context estimator"); + const start = (caller: typeof first) => + estimate({ + botId: "bot", + sessionFile: file, + signal: caller.controller.signal, + }).catch(caller.failed); + + const firstResult = start(first); + await vi.waitFor(() => expect(buildRuntime).toHaveBeenCalledOnce()); + const secondResult = start(second); + await vi.waitFor(() => expect(stat).toHaveBeenCalledTimes(2)); + await Promise.all(vi.mocked(stat).mock.results.map((result) => result.value)); + cancelledCaller.controller.abort(reason); + await vi.waitFor(() => expect(cancelledCaller.failed).toHaveBeenCalledWith(reason)); + + release?.(); + const [firstEstimate, secondEstimate] = await Promise.all([firstResult, secondResult]); + expect(cancelled === "first" ? secondEstimate : firstEstimate).toEqual({ + tokens: 0, + model: undefined, + }); + expect(activeCaller.failed).not.toHaveBeenCalled(); + expect(buildRuntime).toHaveBeenCalledOnce(); + expect(open).toHaveBeenCalledOnce(); + } finally { + release?.(); + await rm(dir, { recursive: true, force: true }); + } +});