Repository navigation
fix(agents): keep tool_use and toolResult together when splitting messages - #58849
Conversation
🔒 Aisle Security AnalysisWe found 2 potential security issue(s) in this PR:
1. 🟡 Potential Denial of Service via stalled chunk splitting when toolResult lacks/mismatches tool call ID
DescriptionIn However, if a
This can lead to context overflow / repeated API failures and elevated CPU/memory due to oversized compaction/summarization attempts (a practical application-level DoS if transcripts can contain malformed tool results, e.g., from corrupted session history or buggy integrations). Vulnerable code: } else if (message.role === "toolResult" && pendingToolCallIds.size > 0) {
const resultId = extractToolResultId(message);
if (resultId) {
pendingToolCallIds.delete(resultId);
}
// ... splitting depends on pendingToolCallIds.size === 0
}RecommendationMake pending tracking fail-open when encountering malformed/unmatched tool results so compaction can still split and enforce budgets. Options (choose one):
} else if (message.role === "toolResult" && pendingToolCallIds.size > 0) {
const resultId = extractToolResultId(message);
if (!resultId) {
// Malformed toolResult; don't let it block chunking indefinitely.
pendingToolCallIds.clear();
} else {
pendingToolCallIds.delete(resultId);
}
// existing post-clear split check...
}
Also consider logging when this fallback triggers so corrupted transcripts can be detected and repaired upstream. 2. 🟡 Tool call/result pairing can be broken by chunk splitting when non-tool messages intervene
DescriptionIn
Because the codebase explicitly acknowledges that session files can have tool results displaced (see Vulnerable code: } else {
// Any non-assistant, non-toolResult message clears pending tracking,
// since tool results should directly follow their assistant turn.
pendingToolCallIds = new Set();
}RecommendationDo not clear Safer options:
Example adjustment: } else if (message.role === "toolResult" && pendingToolCallIds.size > 0) {
const resultId = extractToolResultId(message);
if (resultId) pendingToolCallIds.delete(resultId);
// ... existing split-after-consumed logic ...
} else if (message.role === "assistant") {
// ... existing assistant handling ...
} else {
// Keep pending tool call IDs across user/system/annotation messages
// because toolResults may be displaced.
// pendingToolCallIds unchanged.
}
Also add a regression test where an intervening Analyzed PR: #58849 at commit Last updated on: 2026-04-01T08:56:40Z |
Greptile SummaryThis PR fixes a real bug in The core logic in
These two tests must be updated to reflect the corrected split behavior before merging. Confidence Score: 4/5Not safe to merge until the two broken existing pruneHistoryForContextShare tests are fixed. The fix itself is logically correct and addresses the root cause of orphaned tool_use/toolResult splits. However, at least two pre-existing tests in the pruneHistoryForContextShare suite have assertions written to observe the OLD buggy behavior where orphaned tool_results landed in the kept chunk. With the new fix those tool_results stay in the dropped chunk alongside their assistant message, causing the orphan-count assertions to fail. Until those tests are updated the PR cannot be merged without a red CI. src/agents/compaction.test.ts — the two pruneHistoryForContextShare tests at lines 218–250 and 279–319 need their orphan-count assertions updated to reflect the new behavior.
|
613eb05 to
123ebe6
Compare
The |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 123ebe6086
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
123ebe6 to
f533339
Compare
f533339 to
e272368
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e2723683f8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
obviyus
left a comment
There was a problem hiding this comment.
Reviewed latest changes; landing now.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a2831fee53
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| pendingToolCallIds = | ||
| stopReason === "aborted" || stopReason === "error" | ||
| ? new Set() | ||
| : new Set(toolCalls.map((t) => t.id)); |
There was a problem hiding this comment.
Clear stale pending tool-call IDs when results are missing
This still deadlocks splitting for incomplete non-aborted tool turns: if an assistant includes tool calls with stopReason like "toolUse"/"stop" but no matching toolResult is ever present (for example from a partially persisted turn), pendingToolCallIds never clears, so the split gate is disabled for the rest of the pass and splitMessagesByTokenShare can return a single chunk even when far over budget. pruneHistoryForContextShare then exits early on chunks.length <= 1, leaving oversized history unpruned. Fresh evidence in this patch is that pending IDs are only reset for "aborted"/"error", so unresolved non-aborted tool calls remain stuck.
Useful? React with 👍 / 👎.
a2831fe to
17a3539
Compare
obviyus
left a comment
There was a problem hiding this comment.
Reviewed latest changes; landing now.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 17a3539cd4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| pendingToolCallIds.size === 0 && | ||
| chunks.length < normalizedParts - 1 && | ||
| currentTokens > targetTokens | ||
| ) { | ||
| chunks.push(current); | ||
| current = []; |
There was a problem hiding this comment.
Preserve a split point when toolResult is the final message
This post-toolResult split only runs after appending the result, so when the first over-budget point occurs on the last message of the list, the function can still return a single chunk. In transcripts like [older messages..., assistant(toolCall), toolResult] where currentTokens stays under target until that final toolResult, the pre-split at the loop top is blocked by pending tool IDs and this branch clears current at end-of-loop, leaving pruneHistoryForContextShare with chunks.length <= 1 and no way to drop over-budget older history.
Useful? React with 👍 / 👎.
…@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 (openclaw#58849) (thanks @openperf) * fix: avoid stalled compaction splits on aborted tool calls (openclaw#58849) (thanks @openperf) --------- Co-authored-by: Ayaan Zaidi <[email protected]>
…@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 (openclaw#58849) (thanks @openperf) * fix: avoid stalled compaction splits on aborted tool calls (openclaw#58849) (thanks @openperf) --------- Co-authored-by: Ayaan Zaidi <[email protected]>
…@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 (openclaw#58849) (thanks @openperf) * fix: avoid stalled compaction splits on aborted tool calls (openclaw#58849) (thanks @openperf) --------- Co-authored-by: Ayaan Zaidi <[email protected]>
…@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 (openclaw#58849) (thanks @openperf) * fix: avoid stalled compaction splits on aborted tool calls (openclaw#58849) (thanks @openperf) --------- Co-authored-by: Ayaan Zaidi <[email protected]>
…@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 (openclaw#58849) (thanks @openperf) * fix: avoid stalled compaction splits on aborted tool calls (openclaw#58849) (thanks @openperf) --------- Co-authored-by: Ayaan Zaidi <[email protected]>
…@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 (openclaw#58849) (thanks @openperf) * fix: avoid stalled compaction splits on aborted tool calls (openclaw#58849) (thanks @openperf) --------- Co-authored-by: Ayaan Zaidi <[email protected]>
…@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 (openclaw#58849) (thanks @openperf) * fix: avoid stalled compaction splits on aborted tool calls (openclaw#58849) (thanks @openperf) --------- Co-authored-by: Ayaan Zaidi <[email protected]>
Summary
splitMessagesByTokenShareinsrc/agents/compaction.tssplits message arrays purely by token count. This can cause a split to land exactly between anassistantmessage containing atool_useblock and its correspondingtoolResultmessage. This results in chunks with orphaned tool calls or orphaned tool results, which are rejected by strict APIs (like Anthropic) duringsummarizeInStages.currentTokens + messageTokens > targetTokens) did not consider the semantic boundary between tool calls and their results. It blindly cut the array, breaking the invariant that atoolResultmust immediately follow its matchingassistantturn.pendingToolCallIdsset to track tool call boundaries during the iteration. When anassistantmessage contains tool calls, the split is deferred until all matchingtoolResultmessages are consumed. This guarantees thattool_useandtoolResultpairs are never separated into different chunks.src/agents/compaction.ts: Added boundary tracking logic insplitMessagesByTokenShare.src/agents/compaction.test.ts: Added two regression tests to verify thattool_useandtoolResultpairs (including multiple results for a single assistant turn) stay in the same chunk.chunkMessagesByMaxTokens(which operates on messages that have already had tool result details stripped), and did not change the downstream repair logic insession-transcript-repair.ts.Reproduction
summarizeInStages.splitMessagesByTokenSharecuts the history into chunks. If the token boundary falls right after theassistanttool call but before thetoolResult, the resulting chunk sent to the LLM for summarization contains an orphanedtool_use, causing an API rejection (e.g., "unexpected tool_use_id").Risk / Mitigation
splitMessagesByTokenShareis a soft-split for summarization parts. The actual summarization call (summarizeChunks) already useschunkMessagesByMaxTokensas a hard limit and strips tool result details before sending to the LLM, so a slightly larger logical chunk here will not cause context window overflows.Change Type (select all)
Scope (select all touched areas)
Linked Issue/PR
Fixes #58836