compaction-usage.test.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import type {
  2. AgentMessage,
  3. CompactionSummaryMessage,
  4. } from "@earendil-works/pi-agent-core";
  5. import type { AssistantMessage } from "@earendil-works/pi-ai";
  6. import type { PiBeforeLlmCallHookInput } from "@mavis/agent-core/pi-turn-runner";
  7. import { describe, expect, it, vi } from "vitest";
  8. import { ContextManager } from "../src/manager.js";
  9. import { BpeTokenEstimator } from "../src/token-estimator.js";
  10. const estimator = new BpeTokenEstimator();
  11. function assistant(tokens = 180_100, timestamp = 10): AssistantMessage {
  12. return {
  13. role: "assistant",
  14. content: [{ type: "text", text: "Retained reply." }],
  15. api: "anthropic-messages",
  16. provider: "test",
  17. model: "test",
  18. stopReason: "stop",
  19. timestamp,
  20. usage: {
  21. input: tokens - 100,
  22. output: 100,
  23. cacheRead: 0,
  24. cacheWrite: 0,
  25. totalTokens: tokens,
  26. cost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0, total: 3 },
  27. },
  28. };
  29. }
  30. function user(content = "Continue."): AgentMessage {
  31. return { role: "user", content, timestamp: 10 };
  32. }
  33. function summary(timestamp = 20): CompactionSummaryMessage {
  34. return {
  35. role: "compactionSummary",
  36. summary: "Small summary.",
  37. tokensBefore: 180_100,
  38. timestamp,
  39. };
  40. }
  41. function input(messages: AgentMessage[]): PiBeforeLlmCallHookInput {
  42. return {
  43. sessionId: "synthetic-session",
  44. turnId: "synthetic-turn",
  45. phase: "iteration",
  46. messages,
  47. canonicalMessages: messages,
  48. thinkingLevel: "off",
  49. model: {
  50. id: "test",
  51. name: "test",
  52. api: "anthropic-messages",
  53. provider: "test",
  54. baseUrl: "https://example.invalid",
  55. reasoning: false,
  56. input: ["text"],
  57. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  58. contextWindow: 128_000,
  59. maxTokens: 1024,
  60. },
  61. };
  62. }
  63. function history(): AgentMessage[] {
  64. return [
  65. user("Old request."),
  66. assistant(),
  67. user("Old follow-up."),
  68. assistant(),
  69. user("Latest request."),
  70. assistant(),
  71. ];
  72. }
  73. describe("compaction usage provenance", () => {
  74. it("locally counts a restored legacy summary and retained pre-compaction reply", () => {
  75. const messages = JSON.parse(JSON.stringify([summary(), assistant()]));
  76. const estimate = estimator.estimateContextTokens(messages);
  77. expect(estimate.tokens).toBe(estimator.estimateMessages(messages));
  78. expect(estimate.tokens).toBeLessThan(100);
  79. expect(estimate.lastUsageIndex).toBeNull();
  80. expect(messages[1].usage.totalTokens).toBe(180_100);
  81. });
  82. it("uses fresh legacy usage and estimates only its trailing messages", () => {
  83. const messages = [summary(), assistant(), assistant(2100, 21), user()];
  84. expect(estimator.estimateContextTokens(messages)).toMatchObject({
  85. tokens: 2100 + estimator.estimateMessage(messages[3]!),
  86. usageTokens: 2100,
  87. lastUsageIndex: 2,
  88. });
  89. });
  90. it.each([undefined, NaN, 20])(
  91. "rejects legacy usage with ambiguous timestamp %s",
  92. (timestamp) => {
  93. const retained = { ...assistant(), timestamp } as AgentMessage;
  94. expect(
  95. estimator.estimateContextTokens([summary(), retained]).lastUsageIndex,
  96. ).toBeNull();
  97. },
  98. );
  99. it("does not trust any usage when the latest legacy summary lacks a timestamp", () => {
  100. const messages = [
  101. assistant(),
  102. { role: "compactionSummary", summary: "Restored." },
  103. assistant(2100, 30),
  104. ];
  105. expect(
  106. estimator.estimateContextTokens(messages as AgentMessage[])
  107. .lastUsageIndex,
  108. ).toBeNull();
  109. });
  110. it("leaves uncompacted usage and unsuccessful-response filtering unchanged", () => {
  111. const messages = [
  112. user(),
  113. assistant(2100),
  114. { ...assistant(), stopReason: "error" as const },
  115. { ...assistant(), stopReason: "aborted" as const },
  116. ];
  117. expect(estimator.estimateContextTokens(messages)).toMatchObject({
  118. usageTokens: 2100,
  119. lastUsageIndex: 1,
  120. tokens: 2100 + estimator.estimateMessages(messages.slice(2)),
  121. });
  122. });
  123. it("uses the latest summary boundary and counts an unanchored trailing window", () => {
  124. const messages = [
  125. summary(1),
  126. assistant(),
  127. { ...summary(20), keptMessageCount: 2 },
  128. user(),
  129. assistant(180_100, 50),
  130. { ...assistant(2000, 51), stopReason: "error" as const },
  131. user(),
  132. ];
  133. expect(estimator.estimateContextTokens(messages)).toEqual({
  134. tokens: estimator.estimateMessages(messages),
  135. usageTokens: 0,
  136. trailingTokens: estimator.estimateMessages(messages),
  137. lastUsageIndex: null,
  138. });
  139. messages.push(assistant(2100, 20), user());
  140. expect(estimator.estimateContextTokens(messages)).toMatchObject({
  141. tokens: 2100 + estimator.estimateMessage(messages[8]!),
  142. lastUsageIndex: 7,
  143. });
  144. });
  145. it.each([-1, 0.5, Infinity, 100])(
  146. "falls back locally for an unusable retained count %s",
  147. (keptMessageCount) => {
  148. const messages = [
  149. { ...summary(), keptMessageCount },
  150. assistant(2100, 30),
  151. ];
  152. expect(
  153. estimator.estimateContextTokens(messages).lastUsageIndex,
  154. ).toBeNull();
  155. },
  156. );
  157. it("recounts replacements, skips the next checkpoint, and retains historical usage across restore", async () => {
  158. const generateSummary = vi.fn(async () => "Small summary.");
  159. const committed = vi.fn();
  160. const options = {
  161. settings: { keepRecentTokens: 1 },
  162. summaryGenerator: { generateSummary },
  163. nowMs: () => 5,
  164. observer: { onCompactionCommitted: committed },
  165. };
  166. const original = history();
  167. const before = structuredClone(original);
  168. const decision = await new ContextManager(options).checkpoint(
  169. input(original),
  170. );
  171. expect(decision.type).toBe("replaceMessages");
  172. if (decision.type !== "replaceMessages")
  173. throw new Error("Expected compaction");
  174. expect(decision.metadata.tokensBefore).toBe(180_100);
  175. expect(decision.metadata.tokensAfter).toBe(
  176. estimator.estimateMessages(decision.messages),
  177. );
  178. expect(decision.metadata.tokensAfter).toBeLessThan(100);
  179. expect(committed).toHaveBeenCalledWith(
  180. expect.objectContaining({ tokensAfter: decision.metadata.tokensAfter }),
  181. );
  182. expect(original).toEqual(before);
  183. expect(decision.messages[1]).toEqual(original[5]);
  184. expect(decision.metadata.keptMessages).toEqual([original[5]]);
  185. const restored: AgentMessage[] = JSON.parse(
  186. JSON.stringify(decision.messages),
  187. );
  188. const manager = new ContextManager(options);
  189. // Enough messages for trigger evaluation, with no new provider usage yet.
  190. const next = await manager.checkpoint(input([...restored, user(), user()]));
  191. expect(next).toEqual({
  192. type: "skip",
  193. reason: "context_manager_below_threshold",
  194. });
  195. expect(generateSummary).toHaveBeenCalledTimes(1);
  196. // Explicit provenance also works when the clock moved backwards or ties the summary.
  197. expect(
  198. estimator.estimateContextTokens([...restored, assistant(2100, 5)]),
  199. ).toMatchObject({
  200. usageTokens: 2100,
  201. lastUsageIndex: 2,
  202. });
  203. expect(
  204. estimator.estimateContextTokens([...restored, assistant(2100, 1)]),
  205. ).toMatchObject({
  206. usageTokens: 2100,
  207. lastUsageIndex: 2,
  208. });
  209. });
  210. it("invalidates fresh usage again on a subsequent compaction", async () => {
  211. const manager = new ContextManager({
  212. settings: { keepRecentTokens: 1 },
  213. summaryGenerator: { generateSummary: async () => "Small summary." },
  214. nowMs: () => 20,
  215. });
  216. const first = await manager.checkpoint(input(history()));
  217. if (first.type !== "replaceMessages")
  218. throw new Error("Expected compaction");
  219. const second = await manager.checkpoint(
  220. input([...first.messages, ...history()]),
  221. );
  222. if (second.type !== "replaceMessages")
  223. throw new Error("Expected second compaction");
  224. expect(second.metadata.tokensBefore).toBe(180_100);
  225. expect(second.metadata.tokensAfter).toBeLessThan(100);
  226. expect(
  227. estimator.estimateContextTokens(second.messages).lastUsageIndex,
  228. ).toBeNull();
  229. });
  230. it("preserves the remote counter decision and payload after compaction", async () => {
  231. const countContextTokens = vi
  232. .fn()
  233. .mockResolvedValueOnce({ tokens: 190_000, source: "remote_count_tokens" })
  234. .mockResolvedValueOnce({ tokens: 40, source: "remote_count_tokens" });
  235. const onTriggerEvaluated = vi.fn();
  236. const manager = new ContextManager({
  237. settings: { keepRecentTokens: 1 },
  238. tokenCounter: { countContextTokens },
  239. observer: { onTriggerEvaluated },
  240. summaryGenerator: { generateSummary: async () => "Small summary." },
  241. });
  242. const decision = await manager.checkpoint(input(history()));
  243. if (decision.type !== "replaceMessages")
  244. throw new Error("Expected compaction");
  245. expect(decision.metadata.tokensBefore).toBe(190_000);
  246. expect(decision.metadata.tokensAfter).toBeLessThan(100);
  247. const nextInput = {
  248. ...input([...decision.messages, user(), user()]),
  249. apiKey: "synthetic-test-key",
  250. headers: { "x-test": "synthetic" },
  251. systemPrompt: "Test system.",
  252. tools: [],
  253. };
  254. expect(await manager.checkpoint(nextInput)).toEqual({
  255. type: "skip",
  256. reason: "context_manager_below_threshold",
  257. });
  258. expect(countContextTokens).toHaveBeenLastCalledWith(
  259. expect.objectContaining({
  260. messages: nextInput.messages,
  261. apiKey: nextInput.apiKey,
  262. headers: nextInput.headers,
  263. systemPrompt: nextInput.systemPrompt,
  264. tools: nextInput.tools,
  265. }),
  266. );
  267. expect(onTriggerEvaluated).toHaveBeenLastCalledWith(
  268. expect.objectContaining({
  269. tokens: 40,
  270. source: "remote_count_tokens",
  271. shouldCompact: false,
  272. }),
  273. );
  274. });
  275. });