GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(session): fix root causes and reconstruction of tool_use/tool_result mismatch (#16749) by altendky · Pull Request #16751 · anomalyco/opencode

Conversation

@altendky

@altendky altendky commented Mar 9, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

Issue for this PR

Closes #16749
Related: #10616, #8377, #2720, #1662, #5750, #2214, #8312, #8010

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

Fixes the root causes and provides a reconstruction-time safety net for the widespread tool_use ids were found without tool_result blocks immediately after error that corrupts sessions and makes them unrecoverable.

The fix is three layers of defense-in-depth, each catching what the previous one misses:

Layer 1 — processor.ts: Tool-error race condition (line 211)

The tool-error handler only processed errors for tools in "running" status. Due to the AI SDK's merged-stream event ordering, tool-error can arrive before tool-call, when the tool is still "pending". The error was silently dropped, leaving the tool in "pending" state to be cleaned up later as "Tool execution aborted" with empty input: {}.

Fix: Accept tool-error for both "running" and "pending" status. Uses Date.now() as start time for pending tools (which don't have a time.start field).

Layer 2 — processor.ts: Recovery step-finish before retry (line 374)

When a stream error interrupts processing before finish-step is reached, or the finish-step handler itself throws, the step boundary is never written. The retry loop's continue creates a new stream whose events are appended to the same DB message without a step-finish/step-start boundary. Both steps' content merges into one message, and toModelMessages() produces a single assistant block with interleaved tool_use/text that the Anthropic API rejects.

Fix: Before continueing the retry loop, scan parts backward for an unclosed step (step-start without a matching step-finish). If found, write a recovery step-finish with reason: "error" and zero tokens/cost. Wrapped in try/catch so recovery failures don't block the retry.

Layer 3 — message-v2.ts: Synthetic step-start injection (line 623)

A reconstruction-time safety net that handles already-corrupted DB data regardless of how step boundaries were lost.

Fix: In toModelMessages(), track whether we've seen a tool part in the current step (sawTool flag). If text or reasoning appears after a tool part without an intervening step-start, inject a synthetic { type: "step-start" } to force the AI SDK to split content into separate assistant+tool blocks.

How layers interact

Layer Where it acts What it prevents
Layer 1 (tool-error race) Stream event handling Silent error drops that leave tools in wrong state
Layer 2 (recovery step-finish) Retry loop, before continue DB corruption at write time — ensures step boundaries are preserved
Layer 3 (synthetic step-start) Message reconstruction Handles already-corrupted DB data + any future edge cases the above layers miss

Real-world evidence

Session ses_32fb35486ffeeJAHmplKU1gB2t, message msg_cd05ba534001gICo48Lsy1NHWp:

part_id                        | type        | tool  | status | error
-------------------------------+-------------+-------+--------+------------------------
prt_cd05bb9ac001...            | step-start  |       |        |
prt_cd05bb9ad001...            | text        |       |        |
prt_cd05bb9f0001...            | tool        | write | error  | Tool execution aborted
                                                                 ← 96 SECOND GAP
prt_cd05d3273001...            | text        |       |        |
prt_cd05d35a8001...            | tool        | write | completed |
prt_cd05f3c5d001...            | step-finish |       |        |
  • The errored tool has input: {} — tool-error was dropped because status was "pending" (Layer 1 root cause)
  • No step-finish/step-start boundary between the two groups (Layer 2 root cause)
  • The 96-second gap is the retry delay

How did you verify your code works?

  • All 20 message-v2 tests pass, 0 failures
  • New test constructs the exact corrupted DB pattern (two merged steps with [step-start, text, tool(error), text, tool(completed)]) and asserts the structural invariant: no text or reasoning part appears after a tool-call part in the same assistant ModelMessage
  • Before the fix: Content types in this message: [text, tool-call, text, tool-call]
  • After the fix: passes (content split into separate blocks)
  • 6 pre-existing compaction test failures unrelated to this change

Files changed

File Change
packages/opencode/src/session/processor.ts Tool-error race fix (accept "pending") + recovery step-finish before retry
packages/opencode/src/session/message-v2.ts Synthetic step-start injection in toModelMessages()
packages/opencode/test/session/message-v2.test.ts Test reproducing corrupted DB interleaving pattern

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

johnnymo87 and irvinggarcia79 reacted with thumbs up emoji
All reactions
  • 👍 2 reactions
@altendky
test: reproduce missing step boundary causing tool_use/tool_result mi…
3e9c4d1
…smatch (anomalyco#16749)

Add failing test demonstrating that when step-finish/step-start parts are
missing (due to retryable stream errors), toModelMessages produces a single
assistant block with interleaved tool-call and text parts. Currently fails
with: Content types in this message: [text, tool-call, text, tool-call].
@github-actions github-actions Bot added needs:compliance This means the issue will auto-close after 2 hours. needs:issue labels Mar 9, 2026
@github-actions

github-actions Bot commented Mar 9, 2026

Copy link
Copy Markdown
Contributor

Thanks for your contribution!

This PR doesn't have a linked issue. All PRs must reference an existing issue.

Please:

  1. Open an issue describing the bug/feature (if one doesn't exist)
  2. Add Fixes #<number> or Closes #<number> to this PR description

See CONTRIBUTING.md for details.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@github-actions

github-actions Bot commented Mar 9, 2026

Copy link
Copy Markdown
Contributor

The following comment was made by an LLM, it may be inaccurate:

Found related PRs that may address similar issues:

  1. PR fix(core): repair interleaved text/tool-call parts in assistant messages #14456: "fix(core): repair interleaved text/tool-call parts in assistant messages"

    • fix(core): repair interleaved text/tool-call parts in assistant messages #14456
    • Related because it directly addresses the interleaved text/tool-call parts problem mentioned in this PR
  2. PR fix: handle dangling tool_use blocks for LiteLLM proxy compatibility #8497: "fix: handle dangling tool_use blocks for LiteLLM proxy compatibility"

    • fix: handle dangling tool_use blocks for LiteLLM proxy compatibility #8497
    • Related as it deals with tool_use/tool_result mismatches in message handling

These PRs may already be working on fixes for the issues this test case is reproducing. Check if they've been merged or if there's overlap in the solution approaches.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@altendky
altendky marked this pull request as draft March 9, 2026 13:02
@altendky
fix(session): inject synthetic step-start when tool/text parts are in…
0ae5109
…terleaved due to missing step boundaries

When the finish-step handler throws during a retryable error, step-finish for
step 1 and step-start for step 2 are never saved. Both steps' content merges
into one DB message without boundaries. On replay, convertToModelMessages()
produces a single assistant block with interleaved tool_use/text, which the
Anthropic API rejects.

Fix: track whether we've seen a tool part in the current step. If text or
reasoning appears after a tool part without an intervening step-start, inject
a synthetic step-start to force the AI SDK to split content into separate
blocks.
@altendky altendky changed the title test: reproduce missing step boundary causing tool_use/tool_result mismatch (#16749) fix(session): inject synthetic step-start when tool/text parts are interleaved (#16749) Mar 9, 2026
@altendky
altendky marked this pull request as ready for review March 9, 2026 13:12
@github-actions github-actions Bot removed needs:compliance This means the issue will auto-close after 2 hours. needs:issue labels Mar 9, 2026
@github-actions

github-actions Bot commented Mar 9, 2026

Copy link
Copy Markdown
Contributor

Thanks for updating your PR! It now meets our contributing guidelines. 👍

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@altendky
Merge branch 'dev' into test/missing-step-boundary-interleaving
1c25929
@altendky
altendky marked this pull request as draft March 11, 2026 00:03
@altendky altendky changed the title fix(session): inject synthetic step-start when tool/text parts are interleaved (#16749) fix(session): fix root causes and reconstruction of tool_use/tool_result mismatch (#16749) Mar 11, 2026
@altendky
altendky marked this pull request as ready for review March 11, 2026 00:50
This was referenced Mar 11, 2026
📊 Bản tin hàng ngày công cụ AI CLI 2026-03-11 compasify/agents-radar#25
Open
📊 AI CLI 工具社区动态日报 2026-03-11 DenisZheng/agents-radar#7
Closed
📊 AI CLI Tools Digest 2026-03-11 DenisZheng/agents-radar#8
Closed
@altendky
Merge branch 'dev' into test/missing-step-boundary-interleaving
d9a49c2
@github-actions github-actions Bot mentioned this pull request Mar 13, 2026
fix: filter empty content blocks for Bedrock provider #17381
Closed
3 of 6 tasks
altendky added 5 commits March 16, 2026 17:05
@altendky
Merge branch 'dev' into test/missing-step-boundary-interleaving
2644edd
@altendky
Merge branch 'dev' into test/missing-step-boundary-interleaving
4304196
@altendky
Merge branch 'dev' into test/missing-step-boundary-interleaving
da4bb11
@altendky
Merge branch 'dev' into test/missing-step-boundary-interleaving
22027ef
@altendky
Merge branch 'dev' into test/missing-step-boundary-interleaving
30fa606
@altendky
altendky marked this pull request as draft March 21, 2026 02:16
altendky added 3 commits March 20, 2026 22:33
@altendky
Merge branch 'dev' into test/missing-step-boundary-interleaving
eba5393
@altendky
Merge branch 'dev' into test/missing-step-boundary-interleaving
612eb8a
@altendky
Merge branch 'dev' into test/missing-step-boundary-interleaving
e295e87
This was referenced Jul 28, 2026
Build failed for v1.18.8 johnnymo87/opencode-patched#29
Open
Build failed for v1.18.9 johnnymo87/opencode-patched#30
Open
Build failed for v1.18.10 johnnymo87/opencode-patched#31
Open
Build failed for v1.18.11 johnnymo87/opencode-patched#32
Open
Build failed for v1.18.12 johnnymo87/opencode-patched#34
Open
This was referenced Aug 4, 2026
Build failed for v1.18.13 johnnymo87/opencode-patched#35
Open
Build failed for v1.18.14 johnnymo87/opencode-patched#37
Open
Build failed for v1.18.15 johnnymo87/opencode-patched#38
Open
Build failed for v1.18.16 johnnymo87/opencode-patched#39
Open
@github-actions github-actions Bot mentioned this pull request Aug 13, 2026
Build failed for v1.18.18 johnnymo87/opencode-patched#41
Closed
@xlight xlight mentioned this pull request Aug 27, 2026
feat: persist tool continuation state luciferwww/copilot-relay#5
Merged
This was referenced Sep 2, 2026
Build failed for v1.18.26 johnnymo87/opencode-patched#45
Open
Build failed for v1.18.27 johnnymo87/opencode-patched#46
Open
Build failed for v1.18.28 johnnymo87/opencode-patched#48
Open
Build failed for v1.18.29 johnnymo87/opencode-patched#49
Open
This was referenced Sep 9, 2026
Build failed for v1.18.30 johnnymo87/opencode-patched#50
Open
Build failed for v1.18.31 johnnymo87/opencode-patched#51
Open
Build failed for v1.18.31 johnnymo87/opencode-patched#52
Open
This was referenced Sep 22, 2026
Build failed for v1.18.32 johnnymo87/opencode-patched#55
Open
Build failed for v1.18.33 johnnymo87/opencode-patched#57
Open
This was referenced Oct 1, 2026
Build failed for v1.18.34 johnnymo87/opencode-patched#58
Open
Build failed for v1.18.35 johnnymo87/opencode-patched#59
Open
This was referenced Oct 11, 2026
Build failed for v1.19.0 johnnymo87/opencode-patched#60
Open
Build failed for v1.19.1 johnnymo87/opencode-patched#61
Open
Build failed for v1.19.2 johnnymo87/opencode-patched#62
Open
Build failed for v1.19.3 johnnymo87/opencode-patched#63
Open
@opencode-agent opencode-agent Bot mentioned this pull request Oct 20, 2026
Tool parts with state.status "error" still produce orphaned tool_use and permanently wedge the session #57373
Closed
This was referenced Oct 22, 2026
Build failed for v1.19.4 johnnymo87/opencode-patched#65
Open
Build failed for v1.19.5 johnnymo87/opencode-patched#66
Open
@github-actions github-actions Bot mentioned this pull request Nov 17, 2026
Build failed for v1.19.6 johnnymo87/opencode-patched#67
Open
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

No reviews

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Missing step-finish/step-start parts after retryable stream errors cause tool_use/tool_result mismatch

Uh oh!

There was an error while loading. Please reload this page.

6 participants

@altendky @codeg-old @rekram1-node @Hona @Brendonovich @nexxeln
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.