Skip to content

fix(agents): check for unclosed content blocks at stream finalization (ENG-19233) - #177

Merged
william-antoline-boon merged 2 commits into
boonfrom
william-antoline-boon/eng-19233-stream-unclosed-content-block
Sep 2, 2026
Merged

william-antoline-boon merged 2 commits into
boonfrom
william-antoline-boon/eng-19233-stream-unclosed-content-block

Conversation

@william-antoline-boon

@william-antoline-boon william-antoline-boon commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Anthropic/Bedrock stream finalization only checked that message_stop/messageStop was received (sawMessageStop). It never verified that every content block opened via content_block_start/contentBlockStart was also closed with a matching content_block_stop/contentBlockStop before treating the turn as a successful completion.

A stream that sends the terminal event while a block (e.g. a tool_use whose JSON never finished streaming) is still open was accepted as done. The persisted assistant message ends up self-contradictory (e.g. stopReason: "toolUse" with no matching toolCall in content), which can permanently poison a session — a resumed/retried turn built on top of a broken parent always re-fails.

This is "Shape B" from the truncated-stream incident doc (docs/incidents/2026-08-19-opus-4-8-truncated-sse-streams.md), which found message_stop present in 136 of 138 analyzed truncated turns — meaning the earlier sawMessageStop-only fix (ENG-18472) could not have caught most of them. A real fleet instance (ENG-18913, Loenbro) had a session stuck in this exact state for 11 days.

Why This Change Was Made

  • src/agents/anthropic-transport-stream.ts already tracked open blocks in a blockIndexes map (set on start, deleted on stop) but never read it for leftovers at finalization.
  • extensions/amazon-bedrock/stream.runtime.ts (the direct-to-Bedrock path, independent implementation) had the identical gap via its own per-block .index tracking.
  • Both checks are placed after the existing abort/error/refusal checks, not before: a refusal or abort can legitimately leave a block open, and those already throw a more specific, useful error message that must not be masked by a generic "unclosed content block" error. Caught this ordering bug myself via a pre-existing Bedrock refusal test during development.
  • The Anthropic check scans blocks (the actual content array) directly rather than trusting blockIndexes.size, because a duplicate content_block_start reusing a wire index (no content_block_stop in between) can silently overwrite the map entry for the first block, letting a single later content_block_stop clear the map to size 0 while the first block is still genuinely open. Caught and fixed after adversarial code review; regression test included.
  • New error messages are registered in src/agents/embedded-agent-helpers/failover-matches.ts's ERROR_PATTERNS.timeout bucket (alongside the existing sawMessageStop pattern) so they classify as failover-eligible and retry through the fallback chain instead of dead-ending the turn.

User Impact

  • A truncated/malformed stream that leaves a content block open now correctly fails over to a fallback model/provider instead of silently persisting a broken, unresumable assistant message.
  • No behavior change for healthy streams, refusals, or aborts — all covered by regression tests.

Evidence

  • New tests (TDD — watched each fail for the right reason before implementing the fix):
    • src/agents/anthropic-transport-stream.test.ts: throws when message_stop arrives with an unclosed content block, throws when a duplicate content_block_start orphans an earlier block
    • extensions/amazon-bedrock/stream.runtime.test.ts: throws when messageStop arrives with an unclosed content block (plus fixed a pre-existing test fixture that was missing a contentBlockStop event — unrealistic vs. real Bedrock behavior, which would have false-failed once this check landed)
    • src/agents/embedded-agent-helpers.isbillingerrormessage.test.ts: two new classifyFailoverReason assertions for the new error messages
  • Full scoped suite: 260/260 tests pass (anthropic-transport-stream.test.ts 82, stream.runtime.test.ts 23, embedded-agent-helpers.isbillingerrormessage.test.ts 155)
  • oxfmt/oxlint clean on all touched files
  • tsgo core + extensions, prod and test tsconfigs: zero type errors
  • Independent adversarial review (4 parallel finder angles + verifier) run against the diff; the one surviving finding (the duplicate-content_block_start blind spot above) was fixed and covered by a new regression test before this PR was opened

Linear: https://linear.app/getboon/issue/ENG-19233/openclaw-stream-finalization-doesnt-check-for-unclosed-content-blocks


Summary by cubic

Fixes ENG-19233 by making Anthropic and direct Bedrock streams reject message_stop/messageStop when any content block remains open. Previously, these truncated streams were saved as successful turns; they now fail with a timeout-class error and retry through the fallback chain instead of persisting broken session state.

Bug Fixes

  • Runs the check after abort, error, and refusal handling so those specific errors remain unchanged.
  • Scans accumulated content blocks directly to catch orphaned blocks even when indexes are reused.
  • Adds regression coverage for truncated tool-use JSON, duplicate block starts, and refusals with open blocks.

Written for commit f98a34b. Summary will update on new commits.

Review in cubic

… (ENG-19233)

message_stop/messageStop alone doesn't prove a turn completed: a content
block opened via content_block_start/contentBlockStart but never closed
(e.g. a tool_use whose JSON was cut off) was accepted as a successful
turn, producing a self-contradictory persisted message (stopReason set,
no matching content block) that can permanently poison a session on
resume/retry. Fixes both the Anthropic client transport and the direct
Bedrock path, and registers the new error with the failover classifier
so it retries through the fallback chain instead of dead-ending.
@claude

claude Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

Claude encountered an error —— View job


I'll analyze this and get back to you.

Add an Anthropic-side test proving a refusal that leaves a content block
open still surfaces the refusal message (not the generic unclosed-block
error), and a Bedrock-side test locking in that the array-scan check is
immune to a duplicate contentBlockStart reusing an index, unlike a
Map-keyed-by-index approach.
@william-antoline-boon
william-antoline-boon merged commit 6a80524 into boon Sep 2, 2026
143 of 144 checks passed
@william-antoline-boon
william-antoline-boon deleted the william-antoline-boon/eng-19233-stream-unclosed-content-block branch September 2, 2026 11:28
@orswn orswn mentioned this pull request Sep 2, 2026
orswn added a commit that referenced this pull request Sep 2, 2026
Version-bump-only release cutting the three commits merged to boon since
v2026.6.11-boon.32: #177 (ENG-19233), #178, and #179 (ENG-19305).

#179 is customer-blocking: a macro-enabled Office file the agent produced or
downloaded was dropped by the host media allowlist, so the chat showed
"Media failed." while the assistant text claimed the file was attached. The
estimating templates are macro-enabled, so their workbook output always took
the failing path. The fix is on boon but no fleet host can run it until a
tagged release exists.

Bumps the gateway plus @openclaw/slack, @openclaw/msteams, and
@openclaw/diagnostics-prometheus to 2026.6.11-boon.33 in lockstep across all 8
manifests, and adds the CHANGELOG entry. No code changes.

The security-fast failure is unrelated to this release: four HIGH fast-uri
advisories were published upstream about an hour before the run, and the same
audit passes on every earlier PR in this stack. No dependency changed here.
convyusboy added a commit that referenced this pull request Sep 3, 2026
…nflicts)

5 feature/fix commits (boon.32, boon.33): confirm-before-act on ambiguous
requests (#175), unclosed content-block detection at stream finalization
(ENG-19233, #177), >384MB PDF handling (#178), macro-enabled Office document
delivery (#179), cron failure-destination recipient validation (#181).

All conflicts were the established package.json/npm-shrinkwrap.json
version-string pattern (kept 2026.6.34-boon.1), plus a new one this round:
origin/boon still pins fast-uri at 3.1.6 across pnpm-workspace.yaml,
pnpm-lock.yaml, and four npm-shrinkwrap.json files (root, acpx, lobster).
This integration branch already carries a deliberate 4.1.2 override from the
original 2026.6.34 sync (documented in the PR description's "Dependency /
security pins" section: the bump was needed because upstream's 6.34-era code
targets fast-uri's 4.x API, not because it's numerically newer) -- the same
"boon hasn't caught up to a pin this branch already needed" situation as the
`tar` override in that same section. Kept 4.1.2 everywhere.

Verified: pnpm tsgo:core:test + tsgo:extensions:test both clean. Targeted
tests across every touched surface (pdf-tool, web-media, mime, cron
delivery-target-validation + cron.validation, anthropic-transport-stream,
concise-interaction-overlay, embedded-agent-helpers, amazon-bedrock stream
runtime, anthropic prompt-overlay, document-extract) -- 303 passing, 0
failures. One unrelated pre-existing failure noted and left alone:
src/gateway/mcp-http.test.ts's "withdraws a closing runtime before drain
without fencing its successor" fails deterministically in this sandboxed
environment with a raw ECONNRESET on a real loopback TCP socket -- neither
mcp-http.ts nor its test file were touched by this merge, so this is an
environment/network-sandboxing artifact, not a regression from this change.
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.

1 participant