Skip to content

Commit 08992e1

Browse files
openperfobviyus
andauthored
fix: keep tool calls paired during compaction (#58849) (thanks @openperf)
* fix(compaction): keep tool_use and toolResult together when splitting messages * fix: keep displaced tool results in compaction chunks * fix: keep tool calls paired during compaction (#58849) (thanks @openperf) * fix: avoid stalled compaction splits on aborted tool calls (#58849) (thanks @openperf) --------- Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 7750902 commit 08992e1

3 files changed

Lines changed: 141 additions & 33 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ Docs: https://docs.openclaw.ai
117117
- CLI/skills JSON: route `skills list --json`, `skills info --json`, and `skills check --json` output to stdout instead of stderr so machine-readable consumers receive JSON on the expected stream again. (#60914; fixes #57599; landed from contributor PR #57611 by @Aftabbs) Thanks @Aftabbs.
118118
- Agents/subagents: honor allowlist validation, auth-profile handoff, and session override state when a subagent retries after `LiveSessionModelSwitchError`. (#58178) Thanks @openperf.
119119
- Agents/exec: restore `host=node` routing for node-pinned and `host=auto` sessions, while still blocking sandboxed `auto` sessions from jumping to gateway. (#60788) Thanks @openperf.
120+
- Agents/compaction: keep assistant tool calls and displaced tool results in the same compaction chunk so strict summarization providers stop rejecting orphaned tool pairs. (#58849) Thanks @openperf.
120121

121122
## 2026.4.2
122123

‎src/agents/compaction.test.ts‎

Lines changed: 110 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,15 @@ function makeAssistantToolCall(
2424
timestamp: number,
2525
toolCallId: string,
2626
text = "x".repeat(4000),
27+
stopReason: AssistantMessage["stopReason"] = "stop",
2728
): AssistantMessage {
2829
return makeAgentAssistantMessage({
2930
content: [
3031
{ type: "text", text },
3132
{ type: "toolCall", id: toolCallId, name: "test_tool", arguments: {} },
3233
],
3334
model: "gpt-5.4",
34-
stopReason: "stop",
35+
stopReason,
3536
timestamp,
3637
});
3738
}
@@ -76,6 +77,112 @@ describe("splitMessagesByTokenShare", () => {
7677
const parts = splitMessagesByTokenShare(messages, 3);
7778
expect(parts.flat().map((msg) => msg.timestamp)).toEqual(messages.map((msg) => msg.timestamp));
7879
});
80+
81+
it("keeps tool_use and matching toolResult in the same chunk", () => {
82+
const messages: AgentMessage[] = [
83+
makeMessage(1, 4000),
84+
makeAssistantToolCall(2, "call_split"),
85+
makeToolResult(3, "call_split", "r".repeat(800)),
86+
makeMessage(4, 4000),
87+
];
88+
89+
const parts = splitMessagesByTokenShare(messages, 2);
90+
91+
const chunkWithToolUse = parts.find((chunk) =>
92+
chunk.some((m) => m.role === "assistant" && m.timestamp === 2),
93+
);
94+
const chunkWithToolResult = parts.find((chunk) =>
95+
chunk.some((m) => m.role === "toolResult" && m.timestamp === 3),
96+
);
97+
expect(chunkWithToolUse).toBeDefined();
98+
expect(chunkWithToolResult).toBeDefined();
99+
expect(chunkWithToolUse).toBe(chunkWithToolResult);
100+
expect(parts.flat().length).toBe(messages.length);
101+
});
102+
103+
it("keeps multiple toolResults with their assistant in the same chunk", () => {
104+
const assistant = makeAgentAssistantMessage({
105+
content: [
106+
{ type: "text", text: "x".repeat(4000) },
107+
{ type: "toolCall", id: "call_a", name: "tool_a", arguments: {} },
108+
{ type: "toolCall", id: "call_b", name: "tool_b", arguments: {} },
109+
],
110+
model: "gpt-5.2",
111+
stopReason: "stop",
112+
timestamp: 2,
113+
});
114+
115+
const messages: AgentMessage[] = [
116+
makeMessage(1, 4000),
117+
assistant,
118+
makeToolResult(3, "call_a", "result_a".repeat(200)),
119+
makeToolResult(4, "call_b", "result_b".repeat(200)),
120+
makeMessage(5, 4000),
121+
];
122+
123+
const parts = splitMessagesByTokenShare(messages, 2);
124+
125+
const chunkWithAssistant = parts.find((chunk) =>
126+
chunk.some((m) => m.role === "assistant" && m.timestamp === 2),
127+
)!;
128+
const resultTimestamps = chunkWithAssistant
129+
.filter((m) => m.role === "toolResult")
130+
.map((m) => m.timestamp);
131+
expect(resultTimestamps).toContain(3);
132+
expect(resultTimestamps).toContain(4);
133+
expect(parts.flat().length).toBe(messages.length);
134+
});
135+
136+
it("keeps displaced toolResults with their assistant chunk", () => {
137+
const messages: AgentMessage[] = [
138+
makeMessage(1, 4000),
139+
makeAssistantToolCall(2, "call_split"),
140+
makeMessage(3, 800),
141+
makeToolResult(4, "call_split", "r".repeat(800)),
142+
makeMessage(5, 4000),
143+
];
144+
145+
const parts = splitMessagesByTokenShare(messages, 2);
146+
147+
const chunkWithToolUse = parts.find((chunk) =>
148+
chunk.some((m) => m.role === "assistant" && m.timestamp === 2),
149+
);
150+
const chunkWithToolResult = parts.find((chunk) =>
151+
chunk.some((m) => m.role === "toolResult" && m.timestamp === 4),
152+
);
153+
154+
expect(chunkWithToolUse).toBeDefined();
155+
expect(chunkWithToolUse).toBe(chunkWithToolResult);
156+
});
157+
158+
it("splits after a completed tool_call/result pair when over budget", () => {
159+
const messages: AgentMessage[] = [
160+
makeAssistantToolCall(1, "call_x", "y".repeat(4000)),
161+
makeToolResult(2, "call_x", "r".repeat(4000)),
162+
makeMessage(3, 4000),
163+
];
164+
165+
const parts = splitMessagesByTokenShare(messages, 2);
166+
167+
expect(parts.length).toBe(2);
168+
const chunk1Roles = parts[0].map((m) => m.role);
169+
expect(chunk1Roles).toContain("assistant");
170+
expect(chunk1Roles).toContain("toolResult");
171+
expect(parts.flat().length).toBe(messages.length);
172+
});
173+
174+
it("does not block splits after aborted tool-call assistants", () => {
175+
const messages: AgentMessage[] = [
176+
makeAssistantToolCall(1, "call_abort", "y".repeat(4000), "aborted"),
177+
makeMessage(2, 4000),
178+
makeMessage(3, 4000),
179+
];
180+
181+
const parts = splitMessagesByTokenShare(messages, 2);
182+
183+
expect(parts.length).toBe(2);
184+
expect(parts.flat().length).toBe(messages.length);
185+
});
79186
});
80187

81188
describe("pruneHistoryForContextShare", () => {
@@ -120,17 +227,11 @@ describe("pruneHistoryForContextShare", () => {
120227
});
121228

122229
it("returns droppedMessagesList containing dropped messages", () => {
123-
// Note: This test uses simple user messages with no tool calls.
124-
// When orphaned tool_results exist, droppedMessages may exceed
125-
// droppedMessagesList.length since orphans are counted but not
126-
// added to the list (they lack context for summarization).
127230
const { messages, pruned } = pruneLargeSimpleHistory();
128231

129232
expect(pruned.droppedChunks).toBeGreaterThan(0);
130-
// Without orphaned tool_results, counts match exactly
131233
expect(pruned.droppedMessagesList.length).toBe(pruned.droppedMessages);
132234

133-
// All messages accounted for: kept + dropped = original
134235
const allIds = [
135236
...pruned.droppedMessagesList.map((m) => m.timestamp),
136237
...pruned.messages.map((m) => m.timestamp),
@@ -154,13 +255,8 @@ describe("pruneHistoryForContextShare", () => {
154255
});
155256

156257
it("removes orphaned tool_result messages when tool_use is dropped", () => {
157-
// Scenario: assistant with tool_use is in chunk 1 (dropped),
158-
// tool_result is in chunk 2 (kept) - orphaned tool_result should be removed
159-
// to prevent "unexpected tool_use_id" errors from Anthropic's API
160258
const messages: AgentMessage[] = [
161-
// Chunk 1 (will be dropped) - contains tool_use
162259
makeAssistantToolCall(1, "call_123"),
163-
// Chunk 2 (will be kept) - contains orphaned tool_result
164260
makeToolResult(2, "call_123", "result".repeat(500)),
165261
{
166262
role: "user",
@@ -176,27 +272,18 @@ describe("pruneHistoryForContextShare", () => {
176272
parts: 2,
177273
});
178274

179-
// The orphaned tool_result should NOT be in kept messages
180-
// (this is the critical invariant that prevents API errors)
181275
const keptRoles = pruned.messages.map((m) => m.role);
182276
expect(keptRoles).not.toContain("toolResult");
183-
184-
// The orphan count should be reflected in droppedMessages
185-
// (orphaned tool_results are dropped but not added to droppedMessagesList
186-
// since they lack context for summarization)
187-
expect(pruned.droppedMessages).toBeGreaterThan(pruned.droppedMessagesList.length);
277+
expect(pruned.droppedMessages).toBe(pruned.droppedMessagesList.length);
188278
});
189279

190280
it("keeps tool_result when its tool_use is also kept", () => {
191-
// Scenario: both tool_use and tool_result are in the kept portion
192281
const messages: AgentMessage[] = [
193-
// Chunk 1 (will be dropped) - just user content
194282
{
195283
role: "user",
196284
content: "x".repeat(4000),
197285
timestamp: 1,
198286
},
199-
// Chunk 2 (will be kept) - contains both tool_use and tool_result
200287
makeAssistantToolCall(2, "call_456", "y".repeat(500)),
201288
makeToolResult(3, "call_456", "result"),
202289
];
@@ -208,17 +295,13 @@ describe("pruneHistoryForContextShare", () => {
208295
parts: 2,
209296
});
210297

211-
// Both assistant and toolResult should be in kept messages
212298
const keptRoles = pruned.messages.map((m) => m.role);
213299
expect(keptRoles).toContain("assistant");
214300
expect(keptRoles).toContain("toolResult");
215301
});
216302

217303
it("removes multiple orphaned tool_results from the same dropped tool_use", () => {
218-
// Scenario: assistant with multiple tool_use blocks is dropped,
219-
// all corresponding tool_results should be removed from kept messages
220304
const messages: AgentMessage[] = [
221-
// Chunk 1 (will be dropped) - contains multiple tool_use blocks
222305
makeAgentAssistantMessage({
223306
content: [
224307
{ type: "text", text: "x".repeat(4000) },
@@ -229,7 +312,6 @@ describe("pruneHistoryForContextShare", () => {
229312
stopReason: "stop",
230313
timestamp: 1,
231314
}),
232-
// Chunk 2 (will be kept) - contains orphaned tool_results
233315
makeToolResult(2, "call_a", "result_a"),
234316
makeToolResult(3, "call_b", "result_b"),
235317
{
@@ -246,13 +328,8 @@ describe("pruneHistoryForContextShare", () => {
246328
parts: 2,
247329
});
248330

249-
// No orphaned tool_results should be in kept messages
250331
const keptToolResults = pruned.messages.filter((m) => m.role === "toolResult");
251332
expect(keptToolResults).toHaveLength(0);
252-
253-
// The orphan count should reflect both dropped tool_results
254-
// droppedMessages = 1 (assistant) + 2 (orphaned tool_results) = 3
255-
// droppedMessagesList only has the assistant message
256-
expect(pruned.droppedMessages).toBe(pruned.droppedMessagesList.length + 2);
333+
expect(pruned.droppedMessages).toBe(pruned.droppedMessagesList.length);
257334
});
258335
});

‎src/agents/compaction.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { retryAsync } from "../infra/retry.js";
99
import { createSubsystemLogger } from "../logging/subsystem.js";
1010
import { DEFAULT_CONTEXT_TOKENS } from "./defaults.js";
1111
import { repairToolUseResultPairing, stripToolResultDetails } from "./session-transcript-repair.js";
12+
import { extractToolCallsFromAssistant, extractToolResultId } from "./tool-call-id.js";
1213

1314
const log = createSubsystemLogger("compaction");
1415

@@ -131,9 +132,13 @@ export function splitMessagesByTokenShare(
131132
let current: AgentMessage[] = [];
132133
let currentTokens = 0;
133134

135+
let pendingToolCallIds = new Set<string>();
136+
134137
for (const message of messages) {
135138
const messageTokens = estimateCompactionMessageTokens(message);
139+
136140
if (
141+
pendingToolCallIds.size === 0 &&
137142
chunks.length < normalizedParts - 1 &&
138143
current.length > 0 &&
139144
currentTokens + messageTokens > targetTokens
@@ -145,6 +150,31 @@ export function splitMessagesByTokenShare(
145150

146151
current.push(message);
147152
currentTokens += messageTokens;
153+
154+
if (message.role === "assistant") {
155+
const toolCalls = extractToolCallsFromAssistant(message);
156+
const stopReason = (message as { stopReason?: unknown }).stopReason;
157+
pendingToolCallIds =
158+
stopReason === "aborted" || stopReason === "error"
159+
? new Set()
160+
: new Set(toolCalls.map((t) => t.id));
161+
} else if (message.role === "toolResult" && pendingToolCallIds.size > 0) {
162+
const resultId = extractToolResultId(message);
163+
if (!resultId) {
164+
pendingToolCallIds = new Set();
165+
} else {
166+
pendingToolCallIds.delete(resultId);
167+
}
168+
if (
169+
pendingToolCallIds.size === 0 &&
170+
chunks.length < normalizedParts - 1 &&
171+
currentTokens > targetTokens
172+
) {
173+
chunks.push(current);
174+
current = [];
175+
currentTokens = 0;
176+
}
177+
}
148178
}
149179

150180
if (current.length > 0) {

0 commit comments

Comments
 (0)