Skip to content
Source
Sign inSign up
TanStack/ai

ai-bedrock: a Converse stream that ends without messageStop finishes as a clean stop #2306

Opentuboihirokidesu(GitHub profile, opens in a new tab) opened this issue 1 comment

TanStack AI version

@tanstack/ai 1.8.0, @tanstack/ai-bedrock 1.4.1 (the same code is on main)

Framework/Library version

Node.js 26.13.1, server-side chat(), no framework

Describe the bug and the steps to reproduce it

When a Bedrock ConverseStream ends before messageStop (for example, the connection drops or a proxy closes the response mid-stream), chat() treats the cut-off response as complete. It closes any tool call that is still open with its partial input, then emits RUN_FINISHED with finishReason: 'stop'. The caller can't tell that the response was cut off, and the tool call comes out with truncated arguments that aren't valid JSON (#1582 shows where that can lead on replay).

At the end of the stream, processConverseStream emits TOOL_CALL_END for every tool call that never got a contentBlockStop, and then falls back to finishReason ?? 'stop', whether or not a messageStop arrived.

Expected: unless the request was aborted, a RUN_ERROR (for example with code incomplete-stream) that keeps the partial text, and no TOOL_CALL_END for a tool call whose input never finished. #2042 added this for @tanstack/ai-anthropic, #2124 for @tanstack/ai-gemini, and @tanstack/openai-base has had it since #1604.

The script overrides the protected sendStream seam, as the adapter's own tests do, so no AWS credentials or network are needed:

npm install @tanstack/ai@1.8.0 @tanstack/ai-bedrock@1.4.1
node repro.mjs
import { chat } from '@tanstack/ai'
import { BedrockConverseTextAdapter } from '@tanstack/ai-bedrock'

// A ConverseStream that is cut off while a tool call's input is still streaming:
// no contentBlockStop for the tool block, no messageStop, no metadata.
const events = [
  { messageStart: { role: 'assistant' } },
  { contentBlockDelta: { contentBlockIndex: 0, delta: { text: 'Let me clean that up.' } } },
  { contentBlockStop: { contentBlockIndex: 0 } },
  { contentBlockStart: { contentBlockIndex: 1, start: { toolUse: { toolUseId: 'tooluse_1', name: 'delete_files' } } } },
  { contentBlockDelta: { contentBlockIndex: 1, delta: { toolUse: { input: '{"path": "/data/repo' } } } },
]

class CutStreamAdapter extends BedrockConverseTextAdapter {
  async sendStream() {
    return (async function* () {
      yield* events
    })()
  }
}

const adapter = new CutStreamAdapter({ region: 'us-east-1' }, 'anthropic.claude-sonnet-4-5-20250929-v1:0')

for await (const chunk of chat({
  adapter,
  messages: [{ role: 'user', content: 'Clean up /data/repo' }],
  threadId: 'repro',
})) {
  const { args, finishReason } = chunk.metadata?.tanstack ?? {}
  console.log(chunk.type, args ?? finishReason ?? '')
}

Output:

RUN_STARTED
TEXT_MESSAGE_START
TEXT_MESSAGE_CONTENT
TOOL_CALL_START
TOOL_CALL_ARGS
TOOL_CALL_END {"path": "/data/repo
TEXT_MESSAGE_END
RUN_FINISHED stop

Screenshots or Videos (Optional)

No response

Do you intend to try to help solve this bug with your own PR?

No, because I do not have time to dig into it

Terms & Code of Conduct

  • I agree to follow this project's Code of Conduct
  • I understand that if my bug cannot be reliable reproduced in a debuggable environment, it will probably not be fixed and this issue may even be closed.
  1. tanstack-source added labelsbug

  2. github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer

  3. tanstack-sourcecommented

    Reproduced on main (7ba3926).

    Result

    A ConverseStream that stops before messageStop ends the run with RUN_FINISHED and finishReason: 'stop'. The open tool call is closed with its partial input, and no RUN_ERROR arrives.

    The exact event list from the cut stream:

    RUN_STARTED
    TEXT_MESSAGE_START
    TEXT_MESSAGE_CONTENT "Let me clean that up."
    TOOL_CALL_START tooluse_1 delete_files
    TOOL_CALL_ARGS "{\"path\": \"/data/repo"
    TOOL_CALL_END   (args: {"path": "/data/repo)
    TEXT_MESSAGE_END
    RUN_FINISHED    finishReason: stop

    A completed stream with contentBlockStop, messageStop: tool_use and metadata still gives RUN_FINISHED with finishReason: tool_calls, which is correct.

    Suspected files

    • packages/ai-bedrock/src/converse/stream-processor.ts: the drain loop at lines 317-328 emits TOOL_CALL_END for every tool call that never got contentBlockStop. Line 364 falls back to finishReason ?? 'stop', whatever happened to the stream. There is no check for a missing messageStop.
    • packages/ai-bedrock/src/adapters/converse-text.ts: chatStream (line 295) only turns thrown errors into RUN_ERROR. processConverseStream never throws for a cut stream, so this path is not reached.
    • packages/ai-bedrock/tests/converse/stream-processor.test.ts (lines 287-300, 459-478) asserts the current behavior: the drain emits TOOL_CALL_END and RUN_FINISHED after a stream with no contentBlockStop and no messageStop. These two tests fix the bug that the issue reports.
    • docs/chat/streaming.md (lines 199-201) documents incomplete-stream for OpenAI, OpenRouter and Anthropic. It has no Bedrock entry, which matches the missing code.

    How I ran it

    The sandbox had no node_modules, and pnpm install failed on this host: SQLite cannot open a WAL journal here (no /dev/shm). I patched the two journal_mode pragmas in the installed pnpm and its worker outside the checkout, then installed with pnpm install --filter @tanstack/ai-bedrock... --frozen-lockfile. The @tanstack/ai, @tanstack/ai-utils, @tanstack/ai-event-client and @tanstack/openai-base packages had to be built first, because the tests import their dist.

    The repro file is new and no other file changed. It uses the protected sendStream seam, so it needs no AWS credentials or network.

    Repro

    Path: packages/ai-bedrock/tests/converse/incomplete-stream.test.ts Command: cd packages/ai-bedrock && ../../node_modules/.bin/vitest run tests/converse/incomplete-stream.test.ts

    import { describe, expect, it } from 'vitest'
    import { chat } from '@tanstack/ai'
    import { BedrockConverseTextAdapter } from '../../src/adapters/converse-text'
    import type {
      ConverseStreamCommandInput,
      ConverseStreamOutput,
    } from '@aws-sdk/client-bedrock-runtime'
    import type { StreamChunk } from '@tanstack/ai'
    
    const model = 'us.amazon.nova-pro-v1:0'
    
    type Fixture = { [K in keyof ConverseStreamOutput]?: unknown }
    
    /** A ConverseStream cut off mid tool call: no contentBlockStop, no messageStop. */
    const cutEvents: Array<Fixture> = [
      { messageStart: { role: 'assistant' } },
      {
        contentBlockDelta: {
          contentBlockIndex: 0,
          delta: { text: 'Let me clean that up.' },
        },
      },
      { contentBlockStop: { contentBlockIndex: 0 } },
      {
        contentBlockStart: {
          contentBlockIndex: 1,
          start: { toolUse: { toolUseId: 'tooluse_1', name: 'delete_files' } },
        },
      },
      {
        contentBlockDelta: {
          contentBlockIndex: 1,
          delta: { toolUse: { input: '{"path": "/data/repo' } },
        },
      },
    ]
    
    /** The same stream, completed: tool block closed, messageStop, metadata. */
    const completeEvents: Array<Fixture> = [
      ...cutEvents,
      { contentBlockStop: { contentBlockIndex: 1 } },
      { messageStop: { stopReason: 'tool_use' } },
      { metadata: { usage: { inputTokens: 5, outputTokens: 6, totalTokens: 11 } } },
    ]
    
    class StubAdapter extends BedrockConverseTextAdapter<typeof model> {
      events: Array<Fixture> = []
    
      protected override async sendStream(
        _input: ConverseStreamCommandInput,
      ): Promise<AsyncIterable<ConverseStreamOutput>> {
        const events = this.events
        return (async function* () {
          for (const event of events) yield event as ConverseStreamOutput
        })()
      }
    }
    
    /** Runs `chat()` on the canned Converse stream and gives back every chunk. */
    async function run(events: Array<Fixture>): Promise<Array<StreamChunk>> {
      const adapter = new StubAdapter({ apiKey: 'k' }, model)
      adapter.events = events
      const chunks: Array<StreamChunk> = []
      for await (const chunk of chat({
        adapter,
        threadId: 'repro',
        messages: [{ role: 'user', content: 'Clean up /data/repo' }],
      })) {
        chunks.push(chunk)
      }
      return chunks
    }
    
    describe('Bedrock Converse stream that ends without messageStop', () => {
      it('ends the run with an incomplete-stream RUN_ERROR', async () => {
        const chunks = await run(cutEvents)
        expect(chunks.at(-1)).toMatchObject({
          type: 'RUN_ERROR',
          code: 'incomplete-stream',
        })
        expect(chunks.some((chunk) => chunk.type === 'RUN_FINISHED')).toBe(false)
      })
    
      it('does not close a tool call whose input never finished', async () => {
        const chunks = await run(cutEvents)
        expect(chunks.some((chunk) => chunk.type === 'TOOL_CALL_END')).toBe(false)
      })
    
      it('keeps the partial text', async () => {
        const chunks = await run(cutEvents)
        expect(
          chunks.some(
            (chunk) =>
              chunk.type === 'TEXT_MESSAGE_CONTENT' &&
              chunk.delta === 'Let me clean that up.',
          ),
        ).toBe(true)
      })
    
      it('still finishes a stream that sent messageStop', async () => {
        const chunks = await run(completeEvents)
        const last = chunks.at(-1)
        expect(last?.type).toBe('RUN_FINISHED')
        expect(
          (last?.metadata as { tanstack?: { finishReason?: string } } | undefined)
            ?.tanstack?.finishReason,
        ).toBe('tool_calls')
        expect(chunks.some((chunk) => chunk.type === 'TOOL_CALL_END')).toBe(true)
      })
    })

    Output (end):

     ❯  @tanstack/ai-bedrock  tests/converse/incomplete-stream.test.ts (4 tests | 2 failed) 61ms
         × ends the run with an incomplete-stream RUN_ERROR 43ms
         × does not close a tool call whose input never finished 7ms
         ✓ keeps the partial text 4ms
         ✓ still finishes a stream that sent messageStop 5ms
    
     FAIL   @tanstack/ai-bedrock  tests/converse/incomplete-stream.test.ts > Bedrock Converse stream that ends without messageStop > ends the run with an incomplete-stream RUN_ERROR
    AssertionError: expected { type: 'RUN_FINISHED', …(4) } to match object { type: 'RUN_ERROR', …(1) }
    (5 matching properties omitted from actual)
    
    - Expected
    + Received
    
      {
    -   "code": "incomplete-stream",
    -   "type": "RUN_ERROR",
    +   "type": "RUN_FINISHED",
      }
    
     ❯ tests/converse/incomplete-stream.test.ts:77:27
    
     FAIL   @tanstack/ai-bedrock  tests/converse/incomplete-stream.test.ts > Bedrock Converse stream that ends without messageStop > does not close a tool call whose input never finished
    AssertionError: expected true to be false // Object.is equality
    
    - Expected
    + Received
    
    - false
    + true
    
     ❯ tests/converse/incomplete-stream.test.ts:86:68
    
     Test Files  1 failed (1)
          Tests  2 failed | 2 passed (4)

    TanStack Source bot, investigate agent

  4. github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author

  5. github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: maintainer

Sign in to join this conversation.