Skip to content

fix: causality inversion and addToolMessage ordering#29

Merged
lyssieth merged 3 commits into
mainfrom
fix-context-window-bugs
Jul 23, 2026
Merged

fix: causality inversion and addToolMessage ordering#29
lyssieth merged 3 commits into
mainfrom
fix-context-window-bugs

Conversation

@lyssieth

@lyssieth lyssieth commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Closes #27 and #28

Summary

  • Buffer ctx.addToolMessage() calls made during tool execution (instead of appending immediately) and flush them into session.pendingToolMessages only after all tool responses in the batch (and after disableNotifications injection), preserving provider-required tool_use/tool_result adjacency.
  • Guard the buffering with a toolMessagesCommitted flag so late addToolMessage RPCs don’t mutate an already-committed history batch; if the tool loop throws, buffered addToolMessage injections are drained in a finally block.
  • Make “latest user message” relocation conditional: the user message is spliced out only when there’s no subsequent assistant/tool-response activity after it, avoiding causality reversal in later loop iterations.
  • Make plugin-side addToolMessage delivery resilient to late arrivals: if the invocation context is already cleaned up, messages are queued (orphanedAddToolMessages) and drained into the next invocation’s ToolContext before executing it.

No security-critical subsystems (path isolation/verification, sandboxing, or parsing/validation) are changed by this update.

@lyssieth lyssieth self-assigned this Jul 22, 2026
@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@lyssieth, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 46 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 2347e9d9-1a2b-433d-b28a-a1e5b676156d

📥 Commits

Reviewing files that changed from the base of the PR and between 28e84e3 and 269f145.

📒 Files selected for processing (2)
  • packages/runtime/src/engine/index.ts
  • packages/runtime/src/plugin/loader.ts
📝 Walkthrough

Walkthrough

Changes

The runtime buffers addToolMessage injections until tool responses and notification messages are queued, preserves late plugin messages for the next invocation, and avoids relocating the latest user message across later model activity.

Runtime message ordering

Layer / File(s) Summary
Buffer late plugin messages
packages/runtime/src/plugin/loader.ts
Late addToolMessage payloads are buffered when invocation context cleanup has occurred and drained before the next tool invocation.
Buffer injected tool messages
packages/runtime/src/engine/index.ts
Tool-context messages are queued temporarily and flushed after tool responses and notification injections, including aborted execution cleanup.
Guard latest-user relocation
packages/runtime/src/engine/index.ts
The latest user message is moved only when no later assistant or tool-response activity is present.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately describes the main ordering fix in the PR.
Linked Issues check ✅ Passed The changes buffer addToolMessage calls and flush them after tool responses, matching issue #27's required adjacency fix.
Out of Scope Changes check ✅ Passed No clear out-of-scope changes; the additional ordering tweak is still tied to the same causality and message-sequence fix.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/runtime/src/engine/index.ts`:
- Around line 129-141: Update runTurn and the buffered pendingAddToolMessages
flow so messages queued by addToolMessage are preserved when a later tool throws
or the turn aborts, including the unknown-tool path and the additional abort
path. Drain the buffer in a finally/error path or persist it to session state
before rethrowing, while retaining the existing normal flush ordering.
- Around line 129-141: Update the tool execution flow in the engine around
pendingAddToolMessages and the tool result commit so fire-and-forget
addToolMessage RPCs are tracked and awaited before flushing or committing
messages. Ensure late calls cannot append after pendingToolMessages has been
moved into session.history; preserve queued messages rather than clearing them
until all outstanding worker calls complete.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 1d05214e-7ef4-430e-a6f0-3d87e59fdae4

📥 Commits

Reviewing files that changed from the base of the PR and between 905b7c8 and 61925c8.

📒 Files selected for processing (1)
  • packages/runtime/src/engine/index.ts

Comment thread packages/runtime/src/engine/index.ts
@lyssieth

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 23, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/runtime/src/engine/index.ts`:
- Around line 706-710: Update the tool-call handling in runTurn so an undefined
registry entry for call.name is processed through the existing execution catch
path instead of being thrown before it. Generate the same fallback error
response used for execution failures, associated with the original call.id, and
preserve normal execution for registered tools.

In `@packages/runtime/src/plugin/loader.ts`:
- Around line 308-315: Update the addToolMessage handling around requireCtx so
orphanedAddToolMessages is used only when the invocationId is a string with no
matching pending context. Avoid catching TypeError or errors from
ctx.addToolMessage; let malformed invocation IDs and message-delivery failures
propagate, while preserving buffering for unknown string invocation IDs.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 1f370425-3afe-48ac-ac63-4c1faaf5c61a

📥 Commits

Reviewing files that changed from the base of the PR and between 61925c8 and 28e84e3.

📒 Files selected for processing (2)
  • packages/runtime/src/engine/index.ts
  • packages/runtime/src/plugin/loader.ts

Comment thread packages/runtime/src/engine/index.ts Outdated
Comment thread packages/runtime/src/plugin/loader.ts
Closes #27, closes #28.

- Buffer addToolMessage calls and flush after all tool responses to
  preserve tool_use/tool_result adjacency (OAI/Anthropic invariant).
- Skip last-user-message splice when assistant/toolResponse activity
  follows it, preventing causality inversion mid-agentic-loop.
- Handle unknown-tool defs inline as error results instead of throwing,
  producing proper toolResponse entries with call.id in history.
- Drain the addToolMessage buffer in a finally block on tool-loop
  errors so messages from earlier tools in the batch are not lost.
- Guard addToolMessage against late calls after session.history commit
  via toolMessagesCommitted flag; late arrivals route to a safe fallback.
- In the plugin loader, narrow the addToolMessage catch to only buffer
  late arrivals (valid string invocationId, no matching context).
  TypeError and addToolMessage-internal errors now propagate.
@lyssieth
lyssieth merged commit 20e0d81 into main Jul 23, 2026
7 checks passed
@lyssieth
lyssieth deleted the fix-context-window-bugs branch July 23, 2026 03:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

addToolMessage injects user messages before tool responses, breaking call/response adjacency

1 participant