Elffuss BraidHub

kikocis/continue public

fix: prune before compacting
Changeset9f1ca54f38956daf834d4a5200e8ae207c2b6a665d403a3b1079ddd0fa63e664
AuthorNate <sestinj@gmail.com> · 2025-08-22 21:48 -07:00
CommitterNate <sestinj@gmail.com> · 2025-08-22 21:48 -07:00
Parentse0c6756e65e2

Browse the files at this changeset

3 files changed

added extensions/cli/src/compaction.infiniteLoop.test.ts +126 −0
@@ -0,0 +1,126 @@
1+import { ChatCompletionMessageParam } from "openai/resources.mjs";
2+import { describe, it, expect, vi } from "vitest";
3+import { ModelConfig } from "@continuedev/config-yaml";
4+import { BaseLlmApi } from "@continuedev/openai-adapters";
5+
6+import { compactChatHistory } from "./compaction.js";
7+import { streamChatResponse } from "./streamChatResponse.js";
8+
9+// Mock the dependencies
10+vi.mock("./streamChatResponse.js", () => ({
11+ streamChatResponse: vi.fn(),
12+}));
13+
14+vi.mock("./util/tokenizer.js", () => ({
15+ countChatHistoryTokens: vi.fn(),
16+ getModelContextLimit: vi.fn(),
17+}));
18+
19+describe("compaction infinite loop prevention", () => {
20+ const mockModel: ModelConfig = {
21+ name: "test-model",
22+ provider: "test",
23+ model: "test-model",
24+ defaultCompletionOptions: {
25+ maxTokens: 1000,
26+ contextLength: 4000,
27+ }
28+ } as ModelConfig;
29+
30+ const mockLlmApi = {} as BaseLlmApi;
31+
32+ it("should not loop infinitely when pruning doesn't reduce history size", async () => {
33+ const { countChatHistoryTokens, getModelContextLimit } = await import("./util/tokenizer.js");
34+ const mockStreamResponse = vi.mocked(streamChatResponse);
35+ const mockCountTokens = vi.mocked(countChatHistoryTokens);
36+ const mockGetContextLimit = vi.mocked(getModelContextLimit);
37+
38+ // Setup mocks
39+ mockGetContextLimit.mockReturnValue(4000);
40+ mockCountTokens.mockReturnValue(5000); // Always too big
41+ mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
42+ callbacks?.onContent?.("Summary");
43+ callbacks?.onContentComplete?.();
44+ return "Summary";
45+ });
46+
47+ // History that can't be pruned further (only system message)
48+ const history: ChatCompletionMessageParam[] = [
49+ { role: "system", content: "System message" },
50+ ];
51+
52+ // This should not hang - it should break out of the loop
53+ const result = await compactChatHistory(history, mockModel, mockLlmApi);
54+
55+ // Should complete successfully even though token count is still too high
56+ expect(result.compactedHistory).toBeDefined();
57+ expect(mockCountTokens).toHaveBeenCalled();
58+ });
59+
60+ it("should not loop infinitely with history ending in assistant message", async () => {
61+ const { countChatHistoryTokens, getModelContextLimit } = await import("./util/tokenizer.js");
62+ const mockStreamResponse = vi.mocked(streamChatResponse);
63+ const mockCountTokens = vi.mocked(countChatHistoryTokens);
64+ const mockGetContextLimit = vi.mocked(getModelContextLimit);
65+
66+ // Setup mocks
67+ mockGetContextLimit.mockReturnValue(4000);
68+ mockCountTokens.mockReturnValue(5000); // Always too big
69+ mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
70+ callbacks?.onContent?.("Summary");
71+ callbacks?.onContentComplete?.();
72+ return "Summary";
73+ });
74+
75+ // History that ends with assistant - pruning won't change it
76+ const history: ChatCompletionMessageParam[] = [
77+ { role: "system", content: "System message" },
78+ { role: "user", content: "Hello" },
79+ { role: "assistant", content: "Hi there" },
80+ ];
81+
82+ // This should not hang
83+ const result = await compactChatHistory(history, mockModel, mockLlmApi);
84+
85+ expect(result.compactedHistory).toBeDefined();
86+ });
87+
88+ it("should successfully prune when pruning actually reduces size", async () => {
89+ const { countChatHistoryTokens, getModelContextLimit } = await import("./util/tokenizer.js");
90+ const mockStreamResponse = vi.mocked(streamChatResponse);
91+ const mockCountTokens = vi.mocked(countChatHistoryTokens);
92+ const mockGetContextLimit = vi.mocked(getModelContextLimit);
93+
94+ // Setup mocks
95+ mockGetContextLimit.mockReturnValue(4000);
96+
97+ // Mock token counting to show reduction after pruning
98+ let callCount = 0;
99+ mockCountTokens.mockImplementation(() => {
100+ callCount++;
101+ if (callCount === 1) return 5000; // Initial too big
102+ if (callCount === 2) return 3000; // After pruning, fits
103+ return 2000; // Subsequent calls
104+ });
105+
106+ mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
107+ callbacks?.onContent?.("Summary");
108+ callbacks?.onContentComplete?.();
109+ return "Summary";
110+ });
111+
112+ // History that can be successfully pruned
113+ const history: ChatCompletionMessageParam[] = [
114+ { role: "system", content: "System message" },
115+ { role: "user", content: "Hello" },
116+ { role: "assistant", content: "Hi there" },
117+ { role: "user", content: "Another question" },
118+ ];
119+
120+ const result = await compactChatHistory(history, mockModel, mockLlmApi);
121+
122+ expect(result.compactedHistory).toBeDefined();
123+ // The function will call countTokens multiple times during the process
124+ expect(mockCountTokens).toHaveBeenCalled();
125+ });
126+});
No newline at the end of the file
added extensions/cli/src/compaction.pruneLastMessage.test.ts +169 −0
@@ -0,0 +1,169 @@
1+import { ChatCompletionMessageParam } from "openai/resources.mjs";
2+import { describe, it, expect } from "vitest";
3+
4+import { pruneLastMessage } from "./compaction.js";
5+
6+describe("pruneLastMessage", () => {
7+ it("should return empty array for empty input", () => {
8+ const result = pruneLastMessage([]);
9+ expect(result).toEqual([]);
10+ });
11+
12+ it("should preserve history ending with assistant message", () => {
13+ const history: ChatCompletionMessageParam[] = [
14+ { role: "system", content: "System" },
15+ { role: "user", content: "Hello" },
16+ { role: "assistant", content: "Hi there" },
17+ ];
18+
19+ const result = pruneLastMessage(history);
20+ expect(result).toEqual(history);
21+ });
22+
23+ it("should preserve history ending with tool message", () => {
24+ const history: ChatCompletionMessageParam[] = [
25+ { role: "system", content: "System" },
26+ { role: "user", content: "Run command" },
27+ { role: "assistant", content: "Running...", tool_calls: [{ id: "1" } as any] },
28+ { role: "tool", content: "Command output", tool_call_id: "1" },
29+ ];
30+
31+ const result = pruneLastMessage(history);
32+ expect(result).toEqual(history);
33+ });
34+
35+ it("should prune user messages at the end", () => {
36+ const history: ChatCompletionMessageParam[] = [
37+ { role: "system", content: "System" },
38+ { role: "user", content: "Hello" },
39+ { role: "assistant", content: "Hi there" },
40+ { role: "user", content: "Another question" },
41+ ];
42+
43+ const result = pruneLastMessage(history);
44+ expect(result).toEqual([
45+ { role: "system", content: "System" },
46+ { role: "user", content: "Hello" },
47+ { role: "assistant", content: "Hi there" },
48+ ]);
49+ });
50+
51+ it("should prune multiple user messages at the end", () => {
52+ const history: ChatCompletionMessageParam[] = [
53+ { role: "system", content: "System" },
54+ { role: "user", content: "Hello" },
55+ { role: "assistant", content: "Hi there" },
56+ { role: "user", content: "Question 1" },
57+ { role: "user", content: "Question 2" },
58+ ];
59+
60+ const result = pruneLastMessage(history);
61+ expect(result).toEqual([
62+ { role: "system", content: "System" },
63+ { role: "user", content: "Hello" },
64+ { role: "assistant", content: "Hi there" },
65+ ]);
66+ });
67+
68+ it("should handle tool call sequences correctly", () => {
69+ const history: ChatCompletionMessageParam[] = [
70+ { role: "system", content: "System" },
71+ { role: "user", content: "Do something" },
72+ { role: "assistant", content: "I'll help", tool_calls: [{ id: "1" } as any] },
73+ { role: "tool", content: "Tool result", tool_call_id: "1" },
74+ { role: "user", content: "Follow up question" },
75+ ];
76+
77+ const result = pruneLastMessage(history);
78+ expect(result).toEqual([
79+ { role: "system", content: "System" },
80+ { role: "user", content: "Do something" },
81+ { role: "assistant", content: "I'll help", tool_calls: [{ id: "1" } as any] },
82+ { role: "tool", content: "Tool result", tool_call_id: "1" },
83+ ]);
84+ });
85+
86+ it("should return only system message when no assistant/tool messages exist", () => {
87+ const history: ChatCompletionMessageParam[] = [
88+ { role: "system", content: "System" },
89+ { role: "user", content: "Hello" },
90+ { role: "user", content: "Another message" },
91+ ];
92+
93+ const result = pruneLastMessage(history);
94+ expect(result).toEqual([
95+ { role: "system", content: "System" },
96+ ]);
97+ });
98+
99+ it("should return empty array when no system message and no assistant/tool messages", () => {
100+ const history: ChatCompletionMessageParam[] = [
101+ { role: "user", content: "Hello" },
102+ { role: "user", content: "Another message" },
103+ ];
104+
105+ const result = pruneLastMessage(history);
106+ expect(result).toEqual([]);
107+ });
108+
109+ it("should handle history with only system message", () => {
110+ const history: ChatCompletionMessageParam[] = [
111+ { role: "system", content: "System" },
112+ ];
113+
114+ const result = pruneLastMessage(history);
115+ expect(result).toEqual([
116+ { role: "system", content: "System" },
117+ ]);
118+ });
119+
120+ it("should handle history with only assistant message", () => {
121+ const history: ChatCompletionMessageParam[] = [
122+ { role: "assistant", content: "Hello" },
123+ ];
124+
125+ const result = pruneLastMessage(history);
126+ expect(result).toEqual([
127+ { role: "assistant", content: "Hello" },
128+ ]);
129+ });
130+
131+ it("should handle complex conversation flow", () => {
132+ const history: ChatCompletionMessageParam[] = [
133+ { role: "system", content: "System" },
134+ { role: "user", content: "Request 1" },
135+ { role: "assistant", content: "Response 1" },
136+ { role: "user", content: "Request 2" },
137+ { role: "assistant", content: "Using tool", tool_calls: [{ id: "1" } as any] },
138+ { role: "tool", content: "Tool result", tool_call_id: "1" },
139+ { role: "assistant", content: "Final response" },
140+ { role: "user", content: "Follow up 1" },
141+ { role: "user", content: "Follow up 2" },
142+ ];
143+
144+ const result = pruneLastMessage(history);
145+ expect(result).toEqual([
146+ { role: "system", content: "System" },
147+ { role: "user", content: "Request 1" },
148+ { role: "assistant", content: "Response 1" },
149+ { role: "user", content: "Request 2" },
150+ { role: "assistant", content: "Using tool", tool_calls: [{ id: "1" } as any] },
151+ { role: "tool", content: "Tool result", tool_call_id: "1" },
152+ { role: "assistant", content: "Final response" },
153+ ]);
154+ });
155+
156+ it("should handle history starting with non-system message", () => {
157+ const history: ChatCompletionMessageParam[] = [
158+ { role: "user", content: "Hello" },
159+ { role: "assistant", content: "Hi" },
160+ { role: "user", content: "Follow up" },
161+ ];
162+
163+ const result = pruneLastMessage(history);
164+ expect(result).toEqual([
165+ { role: "user", content: "Hello" },
166+ { role: "assistant", content: "Hi" },
167+ ]);
168+ });
169+});
No newline at the end of the file
modified extensions/cli/src/compaction.ts +65 −2
@@ -5,6 +5,10 @@
55 import { streamChatResponse } from "./streamChatResponse.js";
66 import { StreamCallbacks } from "./streamChatResponse.types.js";
77 import { logger } from "./util/logger.js";
8+import {
9+ countChatHistoryTokens,
10+ getModelContextLimit,
11+} from "./util/tokenizer.js";
812
913 export const COMPACTION_MARKER = "[COMPACTED HISTORY]";
1014
@@ -41,8 +45,39 @@
4145 "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.",
4246 };
4347
44- // Get the current history for compaction
45- const historyForCompaction = [...chatHistory, compactionPrompt];
48+ // Check if the history with compaction prompt is too long, prune if necessary
49+ let historyToUse = chatHistory;
50+ let historyForCompaction = [...historyToUse, compactionPrompt];
51+
52+ const contextLimit = getModelContextLimit(model);
53+ const maxTokens = model.defaultCompletionOptions?.maxTokens || 0;
54+ const reservedForOutput =
55+ maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35);
56+ const availableForInput = contextLimit - reservedForOutput;
57+
58+ // Check if we need to prune to fit within context
59+ while (
60+ countChatHistoryTokens(historyForCompaction) > availableForInput &&
61+ historyToUse.length > 0
62+ ) {
63+ logger.debug("Compaction history too long, pruning last message", {
64+ tokenCount: countChatHistoryTokens(historyForCompaction),
65+ availableForInput,
66+ historyLength: historyToUse.length,
67+ });
68+ const prunedHistory = pruneLastMessage(historyToUse);
69+
70+ // Break if pruning didn't change the history (prevents infinite loop)
71+ if (prunedHistory.length === historyToUse.length) {
72+ logger.warn(
73+ "Cannot prune history further while maintaining valid conversation structure",
74+ );
75+ break;
76+ }
77+
78+ historyToUse = prunedHistory;
79+ historyForCompaction = [...historyToUse, compactionPrompt];
80+ }
4681
4782 // Stream the compaction response
4883 const controller = new AbortController();
@@ -121,6 +156,34 @@
121156 * @param compactionIndex The index of the compaction message, if any
122157 * @returns The history to send to the LLM
123158 */
159+/**
160+ * Prunes chat history by removing messages from the end while ensuring
161+ * the history ends with either an assistant message or a tool result message
162+ * @param chatHistory The chat history to prune
163+ * @returns The pruned chat history ending with assistant or tool message
164+ */
165+export function pruneLastMessage(
166+ chatHistory: ChatCompletionMessageParam[],
167+): ChatCompletionMessageParam[] {
168+ if (chatHistory.length === 0) {
169+ return chatHistory;
170+ }
171+
172+ const secondToLastIndex = chatHistory.length - 2;
173+ const secondToLastMessage = chatHistory[secondToLastIndex];
174+
175+ if (
176+ secondToLastMessage.role === "assistant" &&
177+ secondToLastMessage.tool_calls?.length
178+ ) {
179+ return chatHistory.slice(0, -2);
180+ } else if (secondToLastMessage.role === "user") {
181+ return chatHistory.slice(0, -2);
182+ }
183+
184+ return chatHistory.slice(0, -1);
185+}
186+
124187 export function getHistoryForLLM(
125188 fullHistory: ChatCompletionMessageParam[],
126189 compactionIndex: number | null,