From 1c0bda87956e21883df3f26af681d5e0be78265c Mon Sep 17 00:00:00 2001 From: agooll <141763834+agooll@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:08:30 +0800 Subject: [PATCH 1/2] fix(agent): isolate cancellation of shared context estimates Keep the per-session estimate running for other callers when an individual request is cancelled. Signed-off-by: agooll <141763834+agooll@users.noreply.github.com> --- .../runtime-parts/runtime-compaction.ts | 14 ++--- .../context-estimate-cancellation.test.ts | 61 +++++++++++++++++++ 2 files changed, 67 insertions(+), 8 deletions(-) create mode 100644 packages/agent/test/context-estimate-cancellation.test.ts diff --git a/packages/agent/src/runtime/runtime-parts/runtime-compaction.ts b/packages/agent/src/runtime/runtime-parts/runtime-compaction.ts index 2e00378c..0b0429ac 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 00000000..97cc212f --- /dev/null +++ b/packages/agent/test/context-estimate-cancellation.test.ts @@ -0,0 +1,61 @@ +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([0, 1])("cancels only caller %i while sharing one context estimate", async (cancelled) => { + vi.clearAllMocks(); + const dir = await mkdtemp(join(tmpdir(), "pibot-context-estimate-")); + const file = join(dir, "session.jsonl"); + const ready = Promise.withResolvers>>(); + const open = vi.fn(() => ({ getBranch: () => [] })); + const buildRuntime = vi.fn(() => ready.promise); + const runtime = { + pi: { SessionManager: { open }, buildSessionProjection: () => ({ messages: [] }) }, + }; + const controllers = [new AbortController(), new AbortController()]; + const reason = new Error("caller cancelled"); + const settled = [vi.fn(), vi.fn()]; + + try { + await writeFile(file, "{}\n"); + vi.mocked(sessionPaths).mockResolvedValue(file); + const estimate = createCompactionOperations({ + dataDir: dir, + buildRuntime, + } as unknown as RuntimeContext).estimateContext; + const start = (index: number) => + estimate?.({ + botId: "bot", + sessionFile: file, + signal: controllers[index].signal, + }).catch(settled[index]); + + const first = start(0); + await vi.waitFor(() => expect(buildRuntime).toHaveBeenCalledOnce()); + const second = start(1); + await vi.waitFor(() => expect(stat).toHaveBeenCalledTimes(2)); + await Promise.all(vi.mocked(stat).mock.results.map((result) => result.value)); + controllers[cancelled].abort(reason); + await vi.waitFor(() => expect(settled[cancelled]).toHaveBeenCalledWith(reason)); + + ready.resolve(runtime as unknown as Awaited>); + const results = await Promise.all([first, second]); + expect(results[1 - cancelled]).toEqual({ tokens: 0, model: undefined }); + expect(settled[1 - cancelled]).not.toHaveBeenCalled(); + expect(buildRuntime).toHaveBeenCalledOnce(); + expect(open).toHaveBeenCalledOnce(); + } finally { + ready.resolve(runtime as unknown as Awaited>); + await rm(dir, { recursive: true, force: true }); + } +}); From 8b2889776e965b1219cdf9097e47c7670321df1f Mon Sep 17 00:00:00 2001 From: agooll <141763834+agooll@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:05:28 +0800 Subject: [PATCH 2/2] test(agent): typecheck the context cancellation fixture Signed-off-by: agooll <141763834+agooll@users.noreply.github.com> --- .../context-estimate-cancellation.test.ts | 48 ++++++++++++------- 1 file changed, 30 insertions(+), 18 deletions(-) diff --git a/packages/agent/test/context-estimate-cancellation.test.ts b/packages/agent/test/context-estimate-cancellation.test.ts index 97cc212f..fe7614b7 100644 --- a/packages/agent/test/context-estimate-cancellation.test.ts +++ b/packages/agent/test/context-estimate-cancellation.test.ts @@ -12,19 +12,27 @@ vi.mock("node:fs/promises", async (importOriginal) => { return { ...actual, stat: vi.fn(actual.stat) }; }); -it.each([0, 1])("cancels only caller %i while sharing one context estimate", async (cancelled) => { +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"); - const ready = Promise.withResolvers>>(); + let release: (() => void) | undefined; + const ready = new Promise((resolve) => { + release = resolve; + }); const open = vi.fn(() => ({ getBranch: () => [] })); - const buildRuntime = vi.fn(() => ready.promise); const runtime = { pi: { SessionManager: { open }, buildSessionProjection: () => ({ messages: [] }) }, }; - const controllers = [new AbortController(), new AbortController()]; + 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"); - const settled = [vi.fn(), vi.fn()]; try { await writeFile(file, "{}\n"); @@ -33,29 +41,33 @@ it.each([0, 1])("cancels only caller %i while sharing one context estimate", asy dataDir: dir, buildRuntime, } as unknown as RuntimeContext).estimateContext; - const start = (index: number) => - estimate?.({ + if (!estimate) throw new Error("Missing context estimator"); + const start = (caller: typeof first) => + estimate({ botId: "bot", sessionFile: file, - signal: controllers[index].signal, - }).catch(settled[index]); + signal: caller.controller.signal, + }).catch(caller.failed); - const first = start(0); + const firstResult = start(first); await vi.waitFor(() => expect(buildRuntime).toHaveBeenCalledOnce()); - const second = start(1); + const secondResult = start(second); await vi.waitFor(() => expect(stat).toHaveBeenCalledTimes(2)); await Promise.all(vi.mocked(stat).mock.results.map((result) => result.value)); - controllers[cancelled].abort(reason); - await vi.waitFor(() => expect(settled[cancelled]).toHaveBeenCalledWith(reason)); + cancelledCaller.controller.abort(reason); + await vi.waitFor(() => expect(cancelledCaller.failed).toHaveBeenCalledWith(reason)); - ready.resolve(runtime as unknown as Awaited>); - const results = await Promise.all([first, second]); - expect(results[1 - cancelled]).toEqual({ tokens: 0, model: undefined }); - expect(settled[1 - cancelled]).not.toHaveBeenCalled(); + 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 { - ready.resolve(runtime as unknown as Awaited>); + release?.(); await rm(dir, { recursive: true, force: true }); } });