Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions packages/agent/src/runtime/runtime-parts/runtime-compaction.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -40,17 +41,18 @@ 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;
const cached = estimates.get(file);
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.
Expand All @@ -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();
Expand Down
73 changes: 73 additions & 0 deletions packages/agent/test/context-estimate-cancellation.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof import("node:fs/promises")>();
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<void>((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 });
}
});
Loading