agent-session-compaction.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. import {
  2. type AssistantMessage,
  3. createAssistantMessageEventStream,
  4. fauxAssistantMessage,
  5. type Model,
  6. } from "@earendil-works/pi-ai";
  7. import { afterEach, describe, expect, it, vi } from "vitest";
  8. import { createHarness, type Harness } from "./harness.ts";
  9. type SessionWithCompactionInternals = {
  10. _checkCompaction: (assistantMessage: AssistantMessage, skipAbortedCheck?: boolean) => Promise<boolean>;
  11. _runAutoCompaction: (reason: "overflow" | "threshold", willRetry: boolean) => Promise<boolean>;
  12. };
  13. function createUsage(totalTokens: number) {
  14. return {
  15. input: totalTokens,
  16. output: 0,
  17. cacheRead: 0,
  18. cacheWrite: 0,
  19. totalTokens,
  20. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  21. };
  22. }
  23. function createAssistant(
  24. harness: Harness,
  25. options: {
  26. stopReason?: AssistantMessage["stopReason"];
  27. errorMessage?: string;
  28. totalTokens?: number;
  29. timestamp?: number;
  30. },
  31. ): AssistantMessage {
  32. const model = harness.getModel();
  33. return {
  34. ...fauxAssistantMessage("", {
  35. stopReason: options.stopReason,
  36. errorMessage: options.errorMessage,
  37. timestamp: options.timestamp,
  38. }),
  39. api: model.api,
  40. provider: model.provider,
  41. model: model.id,
  42. usage: createUsage(options.totalTokens ?? 0),
  43. };
  44. }
  45. function useSummaryStreamFn(harness: Harness, summary: string): () => number {
  46. let callCount = 0;
  47. harness.session.agent.streamFn = (model) => {
  48. callCount++;
  49. const stream = createAssistantMessageEventStream();
  50. queueMicrotask(() => {
  51. const message: AssistantMessage = {
  52. ...fauxAssistantMessage(summary),
  53. api: model.api,
  54. provider: model.provider,
  55. model: model.id,
  56. usage: createUsage(10),
  57. };
  58. stream.push({ type: "done", reason: "stop", message });
  59. });
  60. return stream;
  61. };
  62. return () => callCount;
  63. }
  64. function seedCompactableSession(harness: Harness): void {
  65. const now = Date.now();
  66. harness.sessionManager.appendMessage({
  67. role: "user",
  68. content: [{ type: "text", text: "message to compact" }],
  69. timestamp: now - 1000,
  70. });
  71. harness.sessionManager.appendMessage(
  72. createAssistant(harness, {
  73. stopReason: "stop",
  74. totalTokens: 100,
  75. timestamp: now - 500,
  76. }),
  77. );
  78. harness.session.agent.state.messages = harness.sessionManager.buildSessionContext().messages;
  79. }
  80. describe("AgentSession compaction characterization", () => {
  81. const harnesses: Harness[] = [];
  82. afterEach(() => {
  83. vi.useRealTimers();
  84. vi.restoreAllMocks();
  85. while (harnesses.length > 0) {
  86. harnesses.pop()?.cleanup();
  87. }
  88. });
  89. it("manually compacts using an extension-provided summary", async () => {
  90. const harness = await createHarness({
  91. extensionFactories: [
  92. (pi) => {
  93. pi.on("session_before_compact", async (event) => ({
  94. compaction: {
  95. summary: "summary from extension",
  96. firstKeptEntryId: event.preparation.firstKeptEntryId,
  97. tokensBefore: event.preparation.tokensBefore,
  98. details: { source: "extension" },
  99. },
  100. }));
  101. },
  102. ],
  103. });
  104. harnesses.push(harness);
  105. await harness.session.prompt("one");
  106. await harness.session.prompt("two");
  107. const result = await harness.session.compact();
  108. const compactionEntries = harness.sessionManager.getEntries().filter((entry) => entry.type === "compaction");
  109. expect(result.summary).toBe("summary from extension");
  110. expect(compactionEntries).toHaveLength(1);
  111. expect(harness.session.messages[0]?.role).toBe("compactionSummary");
  112. });
  113. it("throws when compacting without a model", async () => {
  114. const harness = await createHarness();
  115. harnesses.push(harness);
  116. harness.session.agent.state.model = undefined as unknown as Model<any>;
  117. await expect(harness.session.compact()).rejects.toThrow("No model selected");
  118. });
  119. it("throws when compacting without configured auth", async () => {
  120. const harness = await createHarness({ withConfiguredAuth: false });
  121. harnesses.push(harness);
  122. await expect(harness.session.compact()).rejects.toThrow(`No API key found for ${harness.getModel().provider}.`);
  123. });
  124. it("manually compacts with a custom streamFn when registry auth is absent", async () => {
  125. const harness = await createHarness({ withConfiguredAuth: false });
  126. harnesses.push(harness);
  127. seedCompactableSession(harness);
  128. const getStreamCallCount = useSummaryStreamFn(harness, "summary from custom stream");
  129. const result = await harness.session.compact();
  130. expect(result.summary).toBe("summary from custom stream");
  131. expect(getStreamCallCount()).toBe(1);
  132. });
  133. it("auto-compacts with a custom streamFn when registry auth is absent", async () => {
  134. const harness = await createHarness({ withConfiguredAuth: false });
  135. harnesses.push(harness);
  136. seedCompactableSession(harness);
  137. const getStreamCallCount = useSummaryStreamFn(harness, "auto summary from custom stream");
  138. const sessionInternals = harness.session as unknown as SessionWithCompactionInternals;
  139. await sessionInternals._runAutoCompaction("threshold", false);
  140. const compactionEntries = harness.sessionManager.getEntries().filter((entry) => entry.type === "compaction");
  141. expect(compactionEntries).toHaveLength(1);
  142. expect(getStreamCallCount()).toBe(1);
  143. });
  144. it("cancels in-progress manual compaction when abortCompaction is called", async () => {
  145. const harness = await createHarness({
  146. extensionFactories: [
  147. (pi) => {
  148. pi.on("session_before_compact", async (event) => {
  149. return await new Promise<{ cancel: true }>((resolve) => {
  150. event.signal.addEventListener("abort", () => resolve({ cancel: true }), { once: true });
  151. });
  152. });
  153. },
  154. ],
  155. });
  156. harnesses.push(harness);
  157. await harness.session.prompt("one");
  158. await harness.session.prompt("two");
  159. const compactPromise = harness.session.compact();
  160. await new Promise((resolve) => setTimeout(resolve, 0));
  161. harness.session.abortCompaction();
  162. await expect(compactPromise).rejects.toThrow("Compaction cancelled");
  163. });
  164. it("resumes after threshold compaction when only agent-level queued messages exist", async () => {
  165. vi.useFakeTimers();
  166. const harness = await createHarness({
  167. settings: { compaction: { keepRecentTokens: 1 } },
  168. extensionFactories: [
  169. (pi) => {
  170. pi.on("session_before_compact", async (event) => ({
  171. compaction: {
  172. summary: "auto compacted",
  173. firstKeptEntryId: event.preparation.firstKeptEntryId,
  174. tokensBefore: event.preparation.tokensBefore,
  175. details: {},
  176. },
  177. }));
  178. },
  179. ],
  180. });
  181. harnesses.push(harness);
  182. harness.setResponses([fauxAssistantMessage("one"), fauxAssistantMessage("two")]);
  183. await harness.session.prompt("first");
  184. await harness.session.prompt("second");
  185. harness.session.agent.followUp({
  186. role: "custom",
  187. customType: "test",
  188. content: [{ type: "text", text: "queued custom" }],
  189. display: false,
  190. timestamp: Date.now(),
  191. });
  192. const sessionInternals = harness.session as unknown as SessionWithCompactionInternals;
  193. await expect(sessionInternals._runAutoCompaction("threshold", false)).resolves.toBe(true);
  194. });
  195. it("does not retry overflow recovery more than once", async () => {
  196. const harness = await createHarness();
  197. harnesses.push(harness);
  198. const sessionInternals = harness.session as unknown as SessionWithCompactionInternals;
  199. const overflowMessage = createAssistant(harness, {
  200. stopReason: "error",
  201. errorMessage: "prompt is too long",
  202. timestamp: Date.now(),
  203. });
  204. const runAutoCompactionSpy = vi.spyOn(sessionInternals, "_runAutoCompaction").mockResolvedValue(false);
  205. const compactionErrors: string[] = [];
  206. harness.session.subscribe((event) => {
  207. if (event.type === "compaction_end" && event.errorMessage) {
  208. compactionErrors.push(event.errorMessage);
  209. }
  210. });
  211. await sessionInternals._checkCompaction(overflowMessage);
  212. await sessionInternals._checkCompaction({ ...overflowMessage, timestamp: Date.now() + 1 });
  213. expect(runAutoCompactionSpy).toHaveBeenCalledTimes(1);
  214. expect(compactionErrors).toContain(
  215. "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
  216. );
  217. });
  218. it("ignores stale pre-compaction assistant usage on pre-prompt checks", async () => {
  219. const harness = await createHarness();
  220. harnesses.push(harness);
  221. const sessionInternals = harness.session as unknown as SessionWithCompactionInternals;
  222. const staleTimestamp = Date.now() - 10_000;
  223. const staleAssistant = createAssistant(harness, {
  224. stopReason: "stop",
  225. totalTokens: 610_000,
  226. timestamp: staleTimestamp,
  227. });
  228. harness.sessionManager.appendMessage({
  229. role: "user",
  230. content: [{ type: "text", text: "before compaction" }],
  231. timestamp: staleTimestamp - 1000,
  232. });
  233. harness.sessionManager.appendMessage(staleAssistant);
  234. const firstKeptEntryId = harness.sessionManager.getEntries()[0]!.id;
  235. harness.sessionManager.appendCompaction(
  236. "summary",
  237. firstKeptEntryId,
  238. staleAssistant.usage.totalTokens,
  239. undefined,
  240. false,
  241. );
  242. harness.sessionManager.appendMessage({
  243. role: "user",
  244. content: [{ type: "text", text: "after compaction" }],
  245. timestamp: Date.now(),
  246. });
  247. const runAutoCompactionSpy = vi.spyOn(sessionInternals, "_runAutoCompaction").mockResolvedValue(false);
  248. await sessionInternals._checkCompaction(staleAssistant, false);
  249. expect(runAutoCompactionSpy).not.toHaveBeenCalled();
  250. });
  251. it("triggers threshold compaction for error messages using the last successful usage", async () => {
  252. const harness = await createHarness();
  253. harnesses.push(harness);
  254. const sessionInternals = harness.session as unknown as SessionWithCompactionInternals;
  255. const successfulAssistant = createAssistant(harness, {
  256. stopReason: "stop",
  257. totalTokens: 190_000,
  258. timestamp: Date.now(),
  259. });
  260. const errorAssistant = createAssistant(harness, {
  261. stopReason: "error",
  262. errorMessage: "529 overloaded",
  263. timestamp: Date.now() + 1000,
  264. });
  265. harness.session.agent.state.messages = [
  266. { role: "user", content: [{ type: "text", text: "hello" }], timestamp: Date.now() - 1000 },
  267. successfulAssistant,
  268. { role: "user", content: [{ type: "text", text: "retry" }], timestamp: Date.now() + 500 },
  269. errorAssistant,
  270. ];
  271. const runAutoCompactionSpy = vi.spyOn(sessionInternals, "_runAutoCompaction").mockResolvedValue(false);
  272. await sessionInternals._checkCompaction(errorAssistant);
  273. expect(runAutoCompactionSpy).toHaveBeenCalledWith("threshold", false);
  274. });
  275. it("does not trigger threshold compaction for error messages when no prior usage exists", async () => {
  276. const harness = await createHarness();
  277. harnesses.push(harness);
  278. const sessionInternals = harness.session as unknown as SessionWithCompactionInternals;
  279. const errorAssistant = createAssistant(harness, {
  280. stopReason: "error",
  281. errorMessage: "529 overloaded",
  282. timestamp: Date.now(),
  283. });
  284. harness.session.agent.state.messages = [
  285. { role: "user", content: [{ type: "text", text: "hello" }], timestamp: Date.now() - 1000 },
  286. errorAssistant,
  287. ];
  288. const runAutoCompactionSpy = vi.spyOn(sessionInternals, "_runAutoCompaction").mockResolvedValue(false);
  289. await sessionInternals._checkCompaction(errorAssistant);
  290. expect(runAutoCompactionSpy).not.toHaveBeenCalled();
  291. });
  292. it("does not trigger threshold compaction when only kept pre-compaction usage exists", async () => {
  293. const harness = await createHarness();
  294. harnesses.push(harness);
  295. const sessionInternals = harness.session as unknown as SessionWithCompactionInternals;
  296. const preCompactionTimestamp = Date.now() - 10_000;
  297. const keptAssistant = createAssistant(harness, {
  298. stopReason: "stop",
  299. totalTokens: 190_000,
  300. timestamp: preCompactionTimestamp,
  301. });
  302. harness.sessionManager.appendMessage({
  303. role: "user",
  304. content: [{ type: "text", text: "before compaction" }],
  305. timestamp: preCompactionTimestamp - 1000,
  306. });
  307. harness.sessionManager.appendMessage(keptAssistant);
  308. const firstKeptEntryId = harness.sessionManager.getEntries()[0]!.id;
  309. harness.sessionManager.appendCompaction(
  310. "summary",
  311. firstKeptEntryId,
  312. keptAssistant.usage.totalTokens,
  313. undefined,
  314. false,
  315. );
  316. const errorAssistant = createAssistant(harness, {
  317. stopReason: "error",
  318. errorMessage: "529 overloaded",
  319. timestamp: Date.now(),
  320. });
  321. harness.session.agent.state.messages = [
  322. { role: "user", content: [{ type: "text", text: "kept user" }], timestamp: preCompactionTimestamp - 1000 },
  323. keptAssistant,
  324. { role: "user", content: [{ type: "text", text: "new prompt" }], timestamp: Date.now() - 500 },
  325. errorAssistant,
  326. ];
  327. const runAutoCompactionSpy = vi.spyOn(sessionInternals, "_runAutoCompaction").mockResolvedValue(false);
  328. await sessionInternals._checkCompaction(errorAssistant);
  329. expect(runAutoCompactionSpy).not.toHaveBeenCalled();
  330. });
  331. it("does not trigger threshold compaction below the threshold or when disabled", async () => {
  332. const belowThresholdHarness = await createHarness({
  333. settings: { compaction: { enabled: true, reserveTokens: 1000 } },
  334. models: [{ id: "faux-1", contextWindow: 200_000 }],
  335. });
  336. harnesses.push(belowThresholdHarness);
  337. const disabledHarness = await createHarness({ settings: { compaction: { enabled: false } } });
  338. harnesses.push(disabledHarness);
  339. const belowThresholdInternals = belowThresholdHarness.session as unknown as SessionWithCompactionInternals;
  340. const disabledInternals = disabledHarness.session as unknown as SessionWithCompactionInternals;
  341. const belowThresholdSpy = vi.spyOn(belowThresholdInternals, "_runAutoCompaction").mockResolvedValue(false);
  342. const disabledSpy = vi.spyOn(disabledInternals, "_runAutoCompaction").mockResolvedValue(false);
  343. await belowThresholdInternals._checkCompaction(
  344. createAssistant(belowThresholdHarness, { stopReason: "stop", totalTokens: 1_000, timestamp: Date.now() }),
  345. );
  346. await disabledInternals._checkCompaction(
  347. createAssistant(disabledHarness, { stopReason: "stop", totalTokens: 1_000_000, timestamp: Date.now() }),
  348. );
  349. expect(belowThresholdSpy).not.toHaveBeenCalled();
  350. expect(disabledSpy).not.toHaveBeenCalled();
  351. });
  352. });