From 04e35c5d52a5cf49e0291fd1f1aa015fa9963b2f Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Aug 2025 21:48:41 -0700 Subject: [PATCH] fix: prune before compacting --- .../cli/src/compaction.infiniteLoop.test.ts | 126 +++++++++++++ .../src/compaction.pruneLastMessage.test.ts | 169 ++++++++++++++++++ extensions/cli/src/compaction.ts | 67 ++++++- 3 files changed, 360 insertions(+), 2 deletions(-) create mode 100644 extensions/cli/src/compaction.infiniteLoop.test.ts create mode 100644 extensions/cli/src/compaction.pruneLastMessage.test.ts diff --git a/extensions/cli/src/compaction.infiniteLoop.test.ts b/extensions/cli/src/compaction.infiniteLoop.test.ts new file mode 100644 index 000000000..24daf01a9 --- /dev/null +++ b/extensions/cli/src/compaction.infiniteLoop.test.ts @@ -0,0 +1,126 @@ +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import { describe, it, expect, vi } from "vitest"; +import { ModelConfig } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; + +import { compactChatHistory } from "./compaction.js"; +import { streamChatResponse } from "./streamChatResponse.js"; + +// Mock the dependencies +vi.mock("./streamChatResponse.js", () => ({ + streamChatResponse: vi.fn(), +})); + +vi.mock("./util/tokenizer.js", () => ({ + countChatHistoryTokens: vi.fn(), + getModelContextLimit: vi.fn(), +})); + +describe("compaction infinite loop prevention", () => { + const mockModel: ModelConfig = { + name: "test-model", + provider: "test", + model: "test-model", + defaultCompletionOptions: { + maxTokens: 1000, + contextLength: 4000, + } + } as ModelConfig; + + const mockLlmApi = {} as BaseLlmApi; + + it("should not loop infinitely when pruning doesn't reduce history size", async () => { + const { countChatHistoryTokens, getModelContextLimit } = await import("./util/tokenizer.js"); + const mockStreamResponse = vi.mocked(streamChatResponse); + const mockCountTokens = vi.mocked(countChatHistoryTokens); + const mockGetContextLimit = vi.mocked(getModelContextLimit); + + // Setup mocks + mockGetContextLimit.mockReturnValue(4000); + mockCountTokens.mockReturnValue(5000); // Always too big + mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => { + callbacks?.onContent?.("Summary"); + callbacks?.onContentComplete?.(); + return "Summary"; + }); + + // History that can't be pruned further (only system message) + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System message" }, + ]; + + // This should not hang - it should break out of the loop + const result = await compactChatHistory(history, mockModel, mockLlmApi); + + // Should complete successfully even though token count is still too high + expect(result.compactedHistory).toBeDefined(); + expect(mockCountTokens).toHaveBeenCalled(); + }); + + it("should not loop infinitely with history ending in assistant message", async () => { + const { countChatHistoryTokens, getModelContextLimit } = await import("./util/tokenizer.js"); + const mockStreamResponse = vi.mocked(streamChatResponse); + const mockCountTokens = vi.mocked(countChatHistoryTokens); + const mockGetContextLimit = vi.mocked(getModelContextLimit); + + // Setup mocks + mockGetContextLimit.mockReturnValue(4000); + mockCountTokens.mockReturnValue(5000); // Always too big + mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => { + callbacks?.onContent?.("Summary"); + callbacks?.onContentComplete?.(); + return "Summary"; + }); + + // History that ends with assistant - pruning won't change it + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System message" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + ]; + + // This should not hang + const result = await compactChatHistory(history, mockModel, mockLlmApi); + + expect(result.compactedHistory).toBeDefined(); + }); + + it("should successfully prune when pruning actually reduces size", async () => { + const { countChatHistoryTokens, getModelContextLimit } = await import("./util/tokenizer.js"); + const mockStreamResponse = vi.mocked(streamChatResponse); + const mockCountTokens = vi.mocked(countChatHistoryTokens); + const mockGetContextLimit = vi.mocked(getModelContextLimit); + + // Setup mocks + mockGetContextLimit.mockReturnValue(4000); + + // Mock token counting to show reduction after pruning + let callCount = 0; + mockCountTokens.mockImplementation(() => { + callCount++; + if (callCount === 1) return 5000; // Initial too big + if (callCount === 2) return 3000; // After pruning, fits + return 2000; // Subsequent calls + }); + + mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => { + callbacks?.onContent?.("Summary"); + callbacks?.onContentComplete?.(); + return "Summary"; + }); + + // History that can be successfully pruned + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System message" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + { role: "user", content: "Another question" }, + ]; + + const result = await compactChatHistory(history, mockModel, mockLlmApi); + + expect(result.compactedHistory).toBeDefined(); + // The function will call countTokens multiple times during the process + expect(mockCountTokens).toHaveBeenCalled(); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/compaction.pruneLastMessage.test.ts b/extensions/cli/src/compaction.pruneLastMessage.test.ts new file mode 100644 index 000000000..ae9c9866c --- /dev/null +++ b/extensions/cli/src/compaction.pruneLastMessage.test.ts @@ -0,0 +1,169 @@ +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import { describe, it, expect } from "vitest"; + +import { pruneLastMessage } from "./compaction.js"; + +describe("pruneLastMessage", () => { + it("should return empty array for empty input", () => { + const result = pruneLastMessage([]); + expect(result).toEqual([]); + }); + + it("should preserve history ending with assistant message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual(history); + }); + + it("should preserve history ending with tool message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Run command" }, + { role: "assistant", content: "Running...", tool_calls: [{ id: "1" } as any] }, + { role: "tool", content: "Command output", tool_call_id: "1" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual(history); + }); + + it("should prune user messages at the end", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + { role: "user", content: "Another question" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + ]); + }); + + it("should prune multiple user messages at the end", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + { role: "user", content: "Question 1" }, + { role: "user", content: "Question 2" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + ]); + }); + + it("should handle tool call sequences correctly", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Do something" }, + { role: "assistant", content: "I'll help", tool_calls: [{ id: "1" } as any] }, + { role: "tool", content: "Tool result", tool_call_id: "1" }, + { role: "user", content: "Follow up question" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "user", content: "Do something" }, + { role: "assistant", content: "I'll help", tool_calls: [{ id: "1" } as any] }, + { role: "tool", content: "Tool result", tool_call_id: "1" }, + ]); + }); + + it("should return only system message when no assistant/tool messages exist", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + { role: "user", content: "Another message" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + ]); + }); + + it("should return empty array when no system message and no assistant/tool messages", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "user", content: "Hello" }, + { role: "user", content: "Another message" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([]); + }); + + it("should handle history with only system message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + ]); + }); + + it("should handle history with only assistant message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "assistant", content: "Hello" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "assistant", content: "Hello" }, + ]); + }); + + it("should handle complex conversation flow", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Request 1" }, + { role: "assistant", content: "Response 1" }, + { role: "user", content: "Request 2" }, + { role: "assistant", content: "Using tool", tool_calls: [{ id: "1" } as any] }, + { role: "tool", content: "Tool result", tool_call_id: "1" }, + { role: "assistant", content: "Final response" }, + { role: "user", content: "Follow up 1" }, + { role: "user", content: "Follow up 2" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "user", content: "Request 1" }, + { role: "assistant", content: "Response 1" }, + { role: "user", content: "Request 2" }, + { role: "assistant", content: "Using tool", tool_calls: [{ id: "1" } as any] }, + { role: "tool", content: "Tool result", tool_call_id: "1" }, + { role: "assistant", content: "Final response" }, + ]); + }); + + it("should handle history starting with non-system message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi" }, + { role: "user", content: "Follow up" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi" }, + ]); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index c60f814a7..2e40d1486 100644 --- a/extensions/cli/src/compaction.ts +++ b/extensions/cli/src/compaction.ts @@ -5,6 +5,10 @@ import { ChatCompletionMessageParam } from "openai/resources.mjs"; import { streamChatResponse } from "./streamChatResponse.js"; import { StreamCallbacks } from "./streamChatResponse.types.js"; import { logger } from "./util/logger.js"; +import { + countChatHistoryTokens, + getModelContextLimit, +} from "./util/tokenizer.js"; export const COMPACTION_MARKER = "[COMPACTED HISTORY]"; @@ -41,8 +45,39 @@ export async function compactChatHistory( "Please provide a concise summary of our conversation so far, capturing the key context, decisions made, and current state. Format this as a single comprehensive message that preserves all important information needed to continue our work. You do not need to recap the system message, as this will remain.", }; - // Get the current history for compaction - const historyForCompaction = [...chatHistory, compactionPrompt]; + // Check if the history with compaction prompt is too long, prune if necessary + let historyToUse = chatHistory; + let historyForCompaction = [...historyToUse, compactionPrompt]; + + const contextLimit = getModelContextLimit(model); + const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; + const reservedForOutput = + maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35); + const availableForInput = contextLimit - reservedForOutput; + + // Check if we need to prune to fit within context + while ( + countChatHistoryTokens(historyForCompaction) > availableForInput && + historyToUse.length > 0 + ) { + logger.debug("Compaction history too long, pruning last message", { + tokenCount: countChatHistoryTokens(historyForCompaction), + availableForInput, + historyLength: historyToUse.length, + }); + const prunedHistory = pruneLastMessage(historyToUse); + + // Break if pruning didn't change the history (prevents infinite loop) + if (prunedHistory.length === historyToUse.length) { + logger.warn( + "Cannot prune history further while maintaining valid conversation structure", + ); + break; + } + + historyToUse = prunedHistory; + historyForCompaction = [...historyToUse, compactionPrompt]; + } // Stream the compaction response const controller = new AbortController(); @@ -121,6 +156,34 @@ export function findCompactionIndex( * @param compactionIndex The index of the compaction message, if any * @returns The history to send to the LLM */ +/** + * Prunes chat history by removing messages from the end while ensuring + * the history ends with either an assistant message or a tool result message + * @param chatHistory The chat history to prune + * @returns The pruned chat history ending with assistant or tool message + */ +export function pruneLastMessage( + chatHistory: ChatCompletionMessageParam[], +): ChatCompletionMessageParam[] { + if (chatHistory.length === 0) { + return chatHistory; + } + + const secondToLastIndex = chatHistory.length - 2; + const secondToLastMessage = chatHistory[secondToLastIndex]; + + if ( + secondToLastMessage.role === "assistant" && + secondToLastMessage.tool_calls?.length + ) { + return chatHistory.slice(0, -2); + } else if (secondToLastMessage.role === "user") { + return chatHistory.slice(0, -2); + } + + return chatHistory.slice(0, -1); +} + export function getHistoryForLLM( fullHistory: ChatCompletionMessageParam[], compactionIndex: number | null,