Skip to content

fix(router): send /v1/messages message_start live during thinking when retries are on - #54319

Merged
mateo-berri merged 17 commits into
BerriAI:mainfrom
ellisc42:litellm_messages_stream_lifecycle_live_on_retry
Nov 25, 2026
Merged

mateo-berri merged 17 commits into
BerriAI:mainfrom
ellisc42:litellm_messages_stream_lifecycle_live_on_retry

Conversation

@ellisc42

@ellisc42 ellisc42 commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

Streaming /v1/messages requests with thinking used to get only keepalive pings until the model started writing, so hard prompts sat for minutes with no message_start. The gateway now passes message_start through right away and still retries a stream dropped before any content, with one message_start

Details

TLDR

Problem this solves:

  • With default retries, message_start waits for the first content delta

How it solves it:

  • message_start goes out live when only a retry can take over and the request has no thread
  • Block starts and deltas still wait for content
  • A retry drops its own message_start, and logs keep the id the client saw

Intentional product change: a retry rejected after message_start ends as 200 plus event: error

User Flow

Before: Claude Code gets no first byte until the model starts writing, minutes on a hard prompt

  1. Run claude --model claude-sonnet-5-5 --effort max --debug-file debug.log with ANTHROPIC_BASE_URL=http://localhost:4000 and default router settings
  2. Send a prompt the model thinks hard about
  3. debug.log shows first byte after the whole thinking time

After: the first byte comes right away, like a direct provider call

  1. Run the same command and send the same prompt
  2. debug.log shows first byte after a couple of seconds
  3. A stream dropped before content is retried, and Claude Code shows one normal answer

Relevant issues

Fixes #38689 from v1.106.0 on, since its v1.98.0 report predates this hold

Affected release

Regression in v1.106.0 (#44276)

Linear ticket

Resolves LIT-10251

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Last updated: 02a828c. QA ran on 72e09a6 and its merge base 4f61996, and the two id cases ran again on 02a828c. Changes since QA: SDK callbacks log the client's id. Proof stands because no frame changed. Verification: id integration tests pass

Each leg ran 2-worker proxies from its tree and Claude Code v2.1.299 in its TUI. Claude Code rows show first bytes, other rows show message_start. Only mock rows skip a real provider

Case Before After
Claude Code, hard thinking, Bedrock 748ms, 432606ms 1893ms, 3125ms
Claude Code, dropped once 1921ms, 3638ms, one answer 2392ms, 2584ms, one answer
Thread create then continue, dropped once 200 then 200, "41" 200 then 200, "41"
Anthropic, hard thinking, curl 161.31s 4.21s
Bedrock, hard thinking, curl 160.94s 2.21s
Bedrock, Agent SDK 424.63s 1.64s
Anthropic, dropped once, curl 1 message_start 1 message_start
Anthropic, dropped once, Agent SDK ok ok
Anthropic, Agent SDK ok ok
gpt-5.6 bridged, curl ok ok
Anthropic, every attempt dropped, curl 200, message_start at 6.62s, then error 200, message_start at 0.84s, then error
Anthropic, dropped then 529, curl 529 at 3.80s 200, message_start at 0.73s, then error
Fallback, mock, curl held, 20.40s held, 20.36s
Fallback, mock, Agent SDK ok ok
Context-window fallback, mock, curl held, 20.96s held, 20.39s
Mock, 20s thinking, curl 20.02s 0.03s
Dropped once, spend row and SDK Router callback client's id on both client's id on both
Shared setup (proxy start, config, client scripts)

Env vars: LITELLM_MASTER_KEY, ANTHROPIC_API_KEY, OPENAI_API_KEY, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN. The client exports LITELLM_KEY as the master key

.venv/bin/litellm --config config.yaml --port <port> --num_workers 2 --timeout_worker_healthcheck 60
model_list:
  - model_name: claude-sonnet-5-5
    litellm_params:
      model: bedrock/us.anthropic.claude-sonnet-5-5
      aws_region_name: us-east-1
  - model_name: claude-sonnet-5-5-direct
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: claude-sonnet-5-5-flaky
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: http://127.0.0.1:<relay port>
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: claude-haiku-5-5
    litellm_params:
      model: anthropic/claude-haiku-5-5
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: claude-haiku-5-5
    litellm_params:
      model: anthropic/claude-haiku-5-5
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: gpt-5.6
    litellm_params:
      model: openai/gpt-5.6
      api_key: os.environ/OPENAI_API_KEY
  - model_name: mock-claude
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: http://127.0.0.1:<mock port>
      api_key: sk-mock
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY

The thread proxy's config has only claude-sonnet-5-5-flaky plus general_settings.coordination_redis: {host: 127.0.0.1, port: <redis port>}, since thread owners live in each worker's memory without Redis. $QA is the QA scratch directory

The fallback proxy's config has mock-claude and a mock-claude-backup copy of it, plus router_settings: {fallbacks: [{mock-claude: [mock-claude-backup]}]}. The context-window proxy's config is the same with context_window_fallbacks in place of fallbacks

The spend case's proxy runs the main config with DATABASE_URL set to a Postgres database of its own

stamp.py prints the time of each event line the client receives

import json
import sys
import time

start = time.monotonic()
for line in sys.stdin:
    line = line.rstrip("\n")
    if line.startswith("HTTP/"):
        print(f"{time.monotonic() - start:7.2f}s  {line.strip()}", flush=True)
    elif line.startswith("event:"):
        print(f"{time.monotonic() - start:7.2f}s  {line}", flush=True)
    elif line.startswith("data:") and '"message_start"' in line:
        message = json.loads(line[5:]).get("message", {})
        print(f"{time.monotonic() - start:7.2f}s    message.id={message.get('id')}", flush=True)
    elif line.startswith("data:") and '"error"' in line:
        print(f"{time.monotonic() - start:7.2f}s    {line[:200]}", flush=True)

drop_relay.py <port> https://api.anthropic.com forwards to Anthropic. After GET /arm?times=N&fail=M, it cuts the next N streams right before their first content_block_delta, so each of those attempts dies after message_start, and then answers the next M requests with a 529 overloaded_error without calling Anthropic. A bare GET /arm cuts one stream

import socket
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse

import httpx

PORT = int(sys.argv[1])
UPSTREAM = sys.argv[2].rstrip("/")
LOCK = threading.Lock()
COUNTER = {"requests": 0, "armed": 0, "fail": 0}
HOP = {"host", "content-length", "connection", "accept-encoding", "transfer-encoding"}


class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def log_message(self, fmt: str, *args: object) -> None:
        sys.stderr.write(f"{fmt % args}\n")

    def write_chunk(self, data: bytes) -> None:
        self.wfile.write(f"{len(data):x}\r\n".encode() + data + b"\r\n")
        self.wfile.flush()

    def do_GET(self) -> None:
        query = parse_qs(urlparse(self.path).query)
        with LOCK:
            COUNTER["armed"] = int(query.get("times", ["1"])[0])
            COUNTER["fail"] = int(query.get("fail", ["0"])[0])
        self.send_response(200)
        self.send_header("content-length", "6")
        self.end_headers()
        self.wfile.write(b"armed\n")

    def do_POST(self) -> None:
        body = self.rfile.read(int(self.headers.get("content-length", "0")))
        with LOCK:
            COUNTER["requests"] += 1
            number = COUNTER["requests"]
            drop = COUNTER["armed"] > 0
            fail = not drop and COUNTER["fail"] > 0
            COUNTER["armed"] = max(COUNTER["armed"] - 1, 0)
            COUNTER["fail"] = COUNTER["fail"] - 1 if fail else COUNTER["fail"]
        if fail:
            payload = b'{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}'
            self.send_response(529)
            self.send_header("content-type", "application/json")
            self.send_header("content-length", str(len(payload)))
            self.end_headers()
            self.wfile.write(payload)
            sys.stderr.write(f"request {number}: answered 529 overloaded_error without calling upstream\n")
            return
        headers = {**{k: v for k, v in self.headers.items() if k.lower() not in HOP}, "accept-encoding": "identity"}
        with httpx.Client(timeout=300) as client, client.stream("POST", UPSTREAM + self.path, content=body, headers=headers) as upstream:
            self.send_response(upstream.status_code)
            self.send_header("content-type", upstream.headers.get("content-type", "application/json"))
            self.send_header("transfer-encoding", "chunked")
            self.end_headers()
            seen = b""
            for data in upstream.iter_raw():
                cut = (seen + data).find(b"event: content_block_delta") if drop else -1
                if cut != -1:
                    data = data[: max(cut - len(seen), 0)]
                if data:
                    self.write_chunk(data)
                seen += data
                if drop and (cut != -1 or b"event: content_block_start" in seen):
                    sys.stderr.write(f"request {number}: upstream sent message_start and content_block_start, dropping the connection before any content delta\n")
                    self.connection.shutdown(socket.SHUT_RDWR)
                    self.connection.close()
                    return
            sys.stderr.write(f"request {number}: relayed whole stream\n")
            self.wfile.write(b"0\r\n\r\n")
            self.wfile.flush()


ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()

sdk_stream.py <base url> <model> [prompt] runs a Claude Agent SDK query (claude-agent-sdk 0.2.188) with adaptive thinking at effort max and prints each stream event's time

import asyncio
import os
import sys
import tempfile
import time

from claude_agent_sdk import ClaudeAgentOptions, query
from claude_agent_sdk.types import ResultMessage, StreamEvent

BASE_URL = sys.argv[1]
MODEL = sys.argv[2]
PROMPT = sys.argv[3] if len(sys.argv) > 3 else (
    "Without using any tools, count the integers between 1 and 3000 that are prime and whose digits sum to a prime. "
    "Verify your count carefully, then answer with just the number."
)


async def main() -> None:
    config_dir = tempfile.mkdtemp(prefix="sdk-claude-")
    options = ClaudeAgentOptions(
        model=MODEL,
        max_turns=1,
        tools=[],
        setting_sources=[],
        include_partial_messages=True,
        thinking={"type": "adaptive"},
        effort=os.environ.get("EFFORT", "max"),
        cwd=config_dir,
        env={
            "ANTHROPIC_BASE_URL": BASE_URL,
            "ANTHROPIC_API_KEY": os.environ["LITELLM_KEY"],
            "ANTHROPIC_DEFAULT_HAIKU_MODEL": MODEL,
            "CLAUDE_CONFIG_DIR": config_dir,
            "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
        },
    )
    start = time.monotonic()
    seen: set[str] = set()
    deltas: dict[int, int] = {}
    print(f"claude-agent-sdk query model={MODEL} base_url={BASE_URL}", flush=True)
    async for message in query(prompt=PROMPT, options=options):
        elapsed = time.monotonic() - start
        if isinstance(message, StreamEvent):
            event = message.event
            kind = event.get("type", "?")
            if kind == "message_start":
                print(f"{elapsed:7.2f}s  stream event: message_start id={event['message']['id']}", flush=True)
            elif kind == "content_block_start":
                print(f"{elapsed:7.2f}s  stream event: content_block_start ({event['content_block']['type']})", flush=True)
            elif kind == "content_block_delta":
                deltas[event["index"]] = deltas.get(event["index"], 0) + 1
                label = f"{event['index']}:{event['delta']['type']}"
                if label not in seen:
                    seen.add(label)
                    print(f"{elapsed:7.2f}s  stream event: first {event['delta']['type']}", flush=True)
            elif kind == "content_block_stop":
                print(f"{elapsed:7.2f}s  stream event: content_block_stop ({deltas.get(event['index'], 0)} deltas in block)", flush=True)
            else:
                print(f"{elapsed:7.2f}s  stream event: {kind}", flush=True)
        elif isinstance(message, ResultMessage):
            print(f"{elapsed:7.2f}s  result: is_error={message.is_error} answer={message.result!r}", flush=True)


asyncio.run(main())

mock_anthropic.py <port> think sends message_start, a thinking content_block_start and a ping at once, waits 20s, then the deltas and message_stop

import json
import os
import socket
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

PORT = int(sys.argv[1])
MODE = sys.argv[2] if len(sys.argv) > 2 else "think"
THINK_SECONDS = float(os.environ.get("THINK_SECONDS", "20"))
LOCK = threading.Lock()
COUNTER = {"requests": 0}


def frame(event: str, data: dict) -> bytes:
    return f"event: {event}\ndata: {json.dumps(data)}\n\n".encode()


def message_start(msg_id: str) -> bytes:
    return frame(
        "message_start",
        {
            "type": "message_start",
            "message": {
                "id": msg_id,
                "type": "message",
                "role": "assistant",
                "model": "claude-sonnet-5-5",
                "content": [],
                "stop_reason": None,
                "stop_sequence": None,
                "usage": {"input_tokens": 12, "output_tokens": 1},
            },
        },
    )


def opening(msg_id: str) -> list[bytes]:
    return [
        message_start(msg_id),
        frame(
            "content_block_start",
            {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": "", "signature": ""}},
        ),
        frame("ping", {"type": "ping"}),
    ]


def rest() -> list[bytes]:
    return [
        frame("content_block_delta", {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "Thinking it over."}}),
        frame("content_block_delta", {"type": "content_block_delta", "index": 0, "delta": {"type": "signature_delta", "signature": "c2lnbmF0dXJl"}}),
        frame("content_block_stop", {"type": "content_block_stop", "index": 0}),
        frame("content_block_start", {"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}}),
        frame("content_block_delta", {"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "Hello."}}),
        frame("content_block_stop", {"type": "content_block_stop", "index": 1}),
        frame("message_delta", {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": None}, "usage": {"output_tokens": 9}}),
        frame("message_stop", {"type": "message_stop"}),
    ]


class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def log_message(self, fmt: str, *args: object) -> None:
        sys.stderr.write(f"{time.strftime('%H:%M:%S')} {fmt % args}\n")

    def write_chunk(self, data: bytes) -> None:
        self.wfile.write(f"{len(data):x}\r\n".encode() + data + b"\r\n")
        self.wfile.flush()

    def do_POST(self) -> None:
        body = self.rfile.read(int(self.headers.get("content-length", "0")))
        with LOCK:
            COUNTER["requests"] += 1
            number = COUNTER["requests"]
        sys.stderr.write(f"request {number} path={self.path} stream={json.loads(body or b'{}').get('stream')}\n")
        self.send_response(200)
        self.send_header("content-type", "text/event-stream")
        self.send_header("transfer-encoding", "chunked")
        self.end_headers()
        msg_id = f"msg_mock_{number}"
        for chunk in opening(msg_id):
            self.write_chunk(chunk)
        if MODE == "drop_first" and number % 2 == 1:
            time.sleep(2)
            self.connection.shutdown(socket.SHUT_RDWR)
            self.connection.close()
            sys.stderr.write(f"request {number} dropped before first content delta\n")
            return
        time.sleep(THINK_SECONDS if MODE == "think" else 3)
        for chunk in rest():
            self.write_chunk(chunk)
        self.wfile.write(b"0\r\n\r\n")
        self.wfile.flush()


ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()

Before (4f61996)

Claude Code, hard thinking prompt on Bedrock

  1. Start the proxy from this leg's tree with the config under Shared setup
  2. Run ANTHROPIC_BASE_URL=http://127.0.0.1:<port> ANTHROPIC_AUTH_TOKEN=$LITELLM_KEY ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-haiku-5-5 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 claude --model claude-sonnet-5-5 --effort max --debug-file $QA/out_base/cc_hard.debug.log
  3. Send Without using any tools, count the integers between 1 and 3000 that are prime and whose digits sum to a prime. Verify your count carefully, then answer with just the number.
  4. Grep the debug log

before hard

$ grep -n 'API:timing\|API:request\|first byte\|Stream started\|message_start' $QA/out_base/cc_hard.debug.log | head -40
175:2026-11-25T03:16:36.590Z [DEBUG] [API:timing] dispatching to firstParty model=claude-haiku-5-5
177:2026-11-25T03:16:36.592Z [DEBUG] [API:timing] dispatching to firstParty model=claude-sonnet-5-5
183:2026-11-25T03:16:37.338Z [DEBUG] Stream started - received first chunk
184:2026-11-25T03:16:37.338Z [DEBUG] [API:timing] first byte after 748ms
193:2026-11-25T03:17:06.593Z [WARN] Slow first byte: no stream chunk 30.0s after request sent (attempt 1)
215:2026-11-25T03:23:49.197Z [DEBUG] Stream started - received first chunk
216:2026-11-25T03:23:49.197Z [DEBUG] [API:timing] first byte after 432606ms

Claude Code, dropped once

Steps and output
  1. Run ANTHROPIC_BASE_URL=http://127.0.0.1:<port> ANTHROPIC_AUTH_TOKEN=$LITELLM_KEY ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-haiku-5-5 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 claude --model claude-sonnet-5-5-flaky --effort max --debug-file $QA/out_base/cc_drop.debug.log
  2. Run curl -s http://127.0.0.1:<relay port>/arm, so the relay cuts the next stream after content_block_start and before any delta
  3. Send Answer in one short sentence: why is the sky blue?

before drop

$ grep -n 'API:timing\|API:request\|first byte\|Stream started\|message_start' $QA/out_base/cc_drop.debug.log | head -40
175:2026-11-25T03:15:23.207Z [DEBUG] [API:timing] dispatching to firstParty model=claude-haiku-5-5
177:2026-11-25T03:15:23.210Z [DEBUG] [API:timing] dispatching to firstParty model=claude-sonnet-5-5-flaky
182:2026-11-25T03:15:25.126Z [DEBUG] Stream started - received first chunk
183:2026-11-25T03:15:25.126Z [DEBUG] [API:timing] first byte after 1921ms
184:2026-11-25T03:15:26.845Z [DEBUG] Stream started - received first chunk
185:2026-11-25T03:15:26.845Z [DEBUG] [API:timing] first byte after 3638ms
$ tail -n +18 <relay log> | grep '^request '
request 8: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 9: relayed whole stream

Thread create then continue, dropped once

Output
$ curl -s http://127.0.0.1:21964/arm && curl -sN -D - http://127.0.0.1:21514/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'anthropic-beta: message-threads-2026-08-12' -H 'content-type: application/json' -d '{"model":"claude-sonnet-5-5-flaky","max_tokens":1024,"stream":true,"thread":{"type":"create"},"messages":[{"role":"user","content":"Remember the number 41. Reply with just ok."}]}' | tee $QA/out_base/thread_create.sse | python3 bin/stamp.py
armed
   3.77s  HTTP/1.1 200 OK
   3.77s  event: message_start
   3.77s    message.id=msg_011ChNvLZcQZdB485mrtGWHX
   3.77s  event: content_block_start
   3.77s  event: ping
   3.77s  event: content_block_delta
   3.77s  event: content_block_stop
   3.77s  event: message_delta
   3.77s  event: message_stop
$ tail -n +23 relay.log
request 10: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 11: relayed whole stream
$ id=$(grep -m1 '"message_start"' $QA/out_base/thread_create.sse | grep -o 'msg_[A-Za-z0-9]*' | head -1); echo previous_message_id=$id
previous_message_id=msg_011ChNvLZcQZdB485mrtGWHX
$ curl -sN -D - http://127.0.0.1:21514/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'anthropic-beta: message-threads-2026-08-12' -H 'content-type: application/json' -d '{"model":"claude-sonnet-5-5-flaky","max_tokens":1024,"stream":true,"thread":{"type":"continue","previous_message_id":"msg_011ChNvLZcQZdB485mrtGWHX"},"messages":[{"role":"user","content":"Which number did I ask you to remember? Reply with just the number."}]}' | tee $QA/out_base/thread_continue.sse | python3 bin/stamp.py
   1.53s  HTTP/1.1 200 OK
   1.53s  event: message_start
   1.53s    message.id=msg_011ChNvLg84LsV7j1VSqYA81
   1.53s  event: content_block_start
   1.53s  event: ping
   1.53s  event: content_block_delta
   1.53s  event: content_block_stop
   1.53s  event: message_delta
   1.53s  event: message_stop
$ grep -o '"text": *"[^"]*"' $QA/out_base/thread_continue.sse | head -3
"text":""
"text":"41"

Other cases

curl and Agent SDK cases
Anthropic, hard thinking, curl
$ curl -sN -D - http://127.0.0.1:20667/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5-5-direct","max_tokens":32000,"stream":true,"thinking":{"type":"adaptive"},"output_config":{"effort":"max"},"messages":[{"role":"user","content":"Without using any tools, count the integers between 1 and 3000 that are prime and whose digits sum to a prime. Verify your count carefully, then answer with just the number."}]}' | python3 bin/stamp.py
  16.03s  HTTP/1.1 200 OK
  16.03s  event: ping
  30.87s  event: ping
  45.87s  event: ping
  60.87s  event: ping
  75.87s  event: ping
  90.87s  event: ping
 105.87s  event: ping
 120.87s  event: ping
 135.87s  event: ping
 150.87s  event: ping
 150.87s  event: ping
 161.31s  event: message_start
 161.31s    message.id=msg_011ChNvMFYEpURe4AkoaDE2J
 161.31s  event: content_block_start
 161.31s  event: ping
 161.31s  event: content_block_delta
 161.31s  event: content_block_delta
 161.34s  event: content_block_stop
 161.34s  event: message_delta
 161.34s  event: message_stop
Bedrock, hard thinking, curl
$ curl -sN -D - http://127.0.0.1:20667/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5-5","max_tokens":32000,"stream":true,"thinking":{"type":"adaptive"},"output_config":{"effort":"max"},"messages":[{"role":"user","content":"Without using any tools, count the integers between 1 and 3000 that are prime and whose digits sum to a prime. Verify your count carefully, then answer with just the number."}]}' | python3 bin/stamp.py
  15.75s  HTTP/1.1 200 OK
  15.75s  event: ping
  30.48s  event: ping
  45.48s  event: ping
  60.48s  event: ping
  75.48s  event: ping
  90.48s  event: ping
 105.48s  event: ping
 120.48s  event: ping
 120.48s  event: ping
 135.48s  event: ping
 150.48s  event: ping
 150.48s  event: ping
 160.94s  event: message_start
 160.94s    message.id=msg_bdrk_ugnt576dfpi6rwxw6fum6pv5wuniq35cm2pu2snhi64tazzwcpja
 160.94s  event: content_block_start
 160.94s  event: content_block_delta
 161.08s  event: content_block_delta
 161.08s  event: content_block_stop
 161.08s  event: message_delta
 161.09s  event: message_stop
Bedrock, Agent SDK
$ sdkvenv/bin/python -I bin/sdk_stream.py http://127.0.0.1:20667 claude-sonnet-5-5
claude-agent-sdk query model=claude-sonnet-5-5 base_url=http://127.0.0.1:20667
  38.98s  stream event: ping
  48.98s  stream event: ping
  68.98s  stream event: ping
  78.98s  stream event: ping
  98.99s  stream event: ping
 108.99s  stream event: ping
 128.99s  stream event: ping
 138.99s  stream event: ping
 158.99s  stream event: ping
 168.99s  stream event: ping
 188.99s  stream event: ping
 198.99s  stream event: ping
 218.99s  stream event: ping
 229.00s  stream event: ping
 249.00s  stream event: ping
 259.00s  stream event: ping
 279.00s  stream event: ping
 289.00s  stream event: ping
 309.00s  stream event: ping
 319.00s  stream event: ping
 339.00s  stream event: ping
 349.00s  stream event: ping
 369.00s  stream event: ping
 379.00s  stream event: ping
 399.01s  stream event: ping
 409.01s  stream event: ping
 424.63s  stream event: message_start id=msg_bdrk_6rqmr6otzckbwvykxkfzhgx7qg6ac3ufflk7b362xhz7lyyf6tqa
 424.63s  stream event: content_block_start (thinking)
 424.63s  stream event: first thinking_delta
 424.98s  stream event: first signature_delta
 424.98s  stream event: content_block_stop (2 deltas in block)
 424.98s  stream event: content_block_start (text)
 424.98s  stream event: first text_delta
 424.98s  stream event: content_block_stop (2 deltas in block)
 424.98s  stream event: message_delta
 424.99s  stream event: message_stop
 425.00s  result: is_error=False answer='**222**'
Anthropic, dropped once, curl
$ curl -s http://127.0.0.1:21964/arm && curl -sN -D - http://127.0.0.1:20667/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5-5-flaky","max_tokens":4096,"stream":true,"thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"Answer in one short sentence: why is the sky blue?"}]}' | python3 bin/stamp.py
armed
   2.52s  HTTP/1.1 200 OK
   2.52s  event: message_start
   2.52s    message.id=msg_011ChNwJb1JXFW8TaoD4tkNP
   2.52s  event: content_block_start
   2.52s  event: ping
   2.52s  event: content_block_delta
   2.84s  event: content_block_delta
   2.84s  event: content_block_delta
   2.84s  event: content_block_delta
   2.84s  event: content_block_delta
   2.84s  event: content_block_delta
   2.84s  event: content_block_delta
   2.84s  event: content_block_delta
   2.84s  event: content_block_delta
   2.84s  event: content_block_delta
   2.84s  event: content_block_delta
   2.87s  event: content_block_delta
   2.90s  event: content_block_delta
   3.36s  event: content_block_delta
   3.36s  event: content_block_delta
   3.36s  event: content_block_delta
   3.38s  event: content_block_stop
   3.38s  event: message_delta
   3.38s  event: message_stop
$ tail -n +30 relay.log
request 13: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 14: relayed whole stream
Anthropic, dropped once, Agent SDK
$ curl -s http://127.0.0.1:21964/arm && sdkvenv/bin/python -I bin/sdk_stream.py http://127.0.0.1:20667 claude-sonnet-5-5-flaky 'Answer in one short sentence: why is the sky blue?'
armed
claude-agent-sdk query model=claude-sonnet-5-5-flaky base_url=http://127.0.0.1:20667
   3.06s  stream event: message_start id=msg_011ChNwJugxAbj2KqwAr3rcG
   3.06s  stream event: content_block_start (thinking)
   3.06s  stream event: first thinking_delta
   3.33s  stream event: first signature_delta
   3.33s  stream event: content_block_stop (3 deltas in block)
   3.33s  stream event: content_block_start (text)
   3.33s  stream event: first text_delta
   3.95s  stream event: content_block_stop (10 deltas in block)
   3.95s  stream event: message_delta
   3.96s  stream event: message_stop
   3.97s  result: is_error=False answer="Air molecules scatter sunlight's shorter blue wavelengths far more strongly than its longer red ones (Rayleigh scattering), so blue light reaches your eyes from all over the sky."
$ tail -n +35 relay.log
request 15: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 16: relayed whole stream
Anthropic, Agent SDK
$ sdkvenv/bin/python -I bin/sdk_stream.py http://127.0.0.1:20667 claude-sonnet-5-5-direct 'Answer in one short sentence: why is the sky blue?'
claude-agent-sdk query model=claude-sonnet-5-5-direct base_url=http://127.0.0.1:20667
   1.38s  stream event: message_start id=msg_011ChNwK9sEwNZKUVxbEawEN
   1.38s  stream event: content_block_start (thinking)
   1.38s  stream event: first thinking_delta
   1.38s  stream event: first signature_delta
   1.38s  stream event: content_block_stop (2 deltas in block)
   1.38s  stream event: content_block_start (text)
   1.38s  stream event: first text_delta
   2.14s  stream event: content_block_stop (14 deltas in block)
   2.15s  stream event: message_delta
   2.15s  stream event: message_stop
   2.16s  result: is_error=False answer='The sky is blue because air molecules scatter shorter blue wavelengths of sunlight much more strongly than longer red ones (Rayleigh scattering), sending blue light to your eyes from every direction.'
gpt-5.6 bridged, curl
$ curl -sN -D - http://127.0.0.1:20667/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"gpt-5.6","max_tokens":2048,"stream":true,"messages":[{"role":"user","content":"Answer in one short sentence: why is the sky blue?"}]}' | python3 bin/stamp.py
   1.09s  HTTP/1.1 200 OK
   1.09s  event: message_start
   1.09s    message.id=msg_8f3c588f-b8ed-470f-bdc4-b2424836aaea
   1.09s  event: content_block_start
   1.09s  event: content_block_delta
   1.23s  event: content_block_delta
   1.23s  event: content_block_delta
   1.23s  event: content_block_delta
   1.23s  event: content_block_delta
   1.23s  event: content_block_delta
   1.23s  event: content_block_delta
   1.23s  event: content_block_delta
   1.23s  event: content_block_delta
   1.23s  event: content_block_delta
   1.23s  event: content_block_delta
   1.23s  event: content_block_delta
   1.23s  event: content_block_delta
   1.23s  event: content_block_delta
   1.23s  event: content_block_delta
   1.23s  event: content_block_delta
   1.27s  event: content_block_stop
   1.36s  event: message_delta
   1.36s  event: message_stop
Anthropic, every attempt dropped, curl
$ curl -s 'http://127.0.0.1:21964/arm?times=10' && curl -sN -D - http://127.0.0.1:20667/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5-5-flaky","max_tokens":4096,"stream":true,"thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"Answer in one short sentence: why is the sky blue?"}]}' | python3 bin/stamp.py; curl -s 'http://127.0.0.1:21964/arm?times=0'
armed
   6.62s  HTTP/1.1 200 OK
   6.62s  event: message_start
   6.62s    message.id=msg_011ChP56UPmm9143gu2bZX6k
   6.62s  event: content_block_start
   6.62s  event: ping
   6.94s  event: error
   6.94s    data: {"type": "error", "error": {"type": "api_error", "message": "Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>"}}
armed
$ tail -n +3 relay.log
request 1: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 2: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 3: upstream sent message_start and content_block_start, dropping the connection before any content delta
Anthropic, dropped then 529, curl
$ curl -s 'http://127.0.0.1:21964/arm?times=1&fail=10' && curl -sN -D - http://127.0.0.1:20667/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5-5-flaky","max_tokens":4096,"stream":true,"thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"Answer in one short sentence: why is the sky blue?"}]}' | python3 bin/stamp.py; curl -s 'http://127.0.0.1:21964/arm?times=0&fail=0'
armed
   3.80s  HTTP/1.1 529
armed
$ tail -n +2 relay.log
request 1: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 2: answered 529 overloaded_error without calling upstream
request 3: answered 529 overloaded_error without calling upstream
Fallback, mock, curl
$ curl -sN -D - http://127.0.0.1:27172/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"mock-claude","max_tokens":4096,"stream":true,"thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"hi"}]}' | python3 bin/stamp.py
  15.56s  HTTP/1.1 200 OK
  15.56s  event: ping
  20.40s  event: message_start
  20.40s    message.id=msg_mock_7
  20.40s  event: content_block_start
  20.40s  event: ping
  20.40s  event: content_block_delta
  20.40s  event: content_block_delta
  20.40s  event: content_block_stop
  20.40s  event: content_block_start
  20.40s  event: content_block_delta
  20.40s  event: content_block_stop
  20.40s  event: message_delta
  20.40s  event: message_stop
Fallback, mock, Agent SDK
$ sdkvenv/bin/python -I bin/sdk_stream.py http://127.0.0.1:27172 mock-claude hi
claude-agent-sdk query model=mock-claude base_url=http://127.0.0.1:27172
[claude-code:unrecognized_model] {"model":"mock-claude","query_source":"sdk"}
  20.65s  stream event: message_start id=msg_mock_8
  20.65s  stream event: content_block_start (thinking)
  20.65s  stream event: first thinking_delta
  20.65s  stream event: first signature_delta
  20.65s  stream event: content_block_stop (2 deltas in block)
  20.65s  stream event: content_block_start (text)
  20.65s  stream event: first text_delta
  20.65s  stream event: content_block_stop (1 deltas in block)
  20.66s  stream event: message_delta
  20.66s  stream event: message_stop
  20.67s  result: is_error=False answer='Hello.'
Context-window fallback, mock, curl
$ curl -sN -D - http://127.0.0.1:31419/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"mock-claude","max_tokens":4096,"stream":true,"thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"hi"}]}' | python3 bin/stamp.py
  16.31s  HTTP/1.1 200 OK
  16.31s  event: ping
  20.96s  event: message_start
  20.96s    message.id=msg_mock_10
  20.96s  event: content_block_start
  20.96s  event: ping
  20.96s  event: content_block_delta
  20.96s  event: content_block_delta
  20.96s  event: content_block_stop
  20.96s  event: content_block_start
  20.96s  event: content_block_delta
  20.96s  event: content_block_stop
  20.96s  event: message_delta
  20.96s  event: message_stop
Mock, 20s thinking, curl
$ curl -sN -D - http://127.0.0.1:20667/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"mock-claude","max_tokens":4096,"stream":true,"thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"hi"}]}' | python3 bin/stamp.py
  15.03s  HTTP/1.1 200 OK
  15.03s  event: ping
  20.02s  event: message_start
  20.02s    message.id=msg_mock_9
  20.02s  event: content_block_start
  20.02s  event: ping
  20.02s  event: content_block_delta
  20.02s  event: content_block_delta
  20.02s  event: content_block_stop
  20.02s  event: content_block_start
  20.02s  event: content_block_delta
  20.02s  event: content_block_stop
  20.02s  event: message_delta
  20.02s  event: message_stop
Anthropic, dropped once, spend row, curl

The whole output is in a gist. Its last line:

{"rows":1,"request_ids":["msg_011ChPL6Ma1Kkbjbqgtrykq3"],"status":["success"],"total_tokens":[79]}
SDK Router, dropped once, callback id

Whole output

message_start ids the caller got: ['msg_011ChPXQ5rF4rWfKTiNNqFfP']
ids the success callback logged: ['msg_011ChPXQ5rF4rWfKTiNNqFfP']

After (72e09a6)

Claude Code, hard thinking prompt on Bedrock

  1. Same steps as Before, on this leg's proxy

after hard

$ grep -n 'API:timing\|API:request\|first byte\|Stream started\|message_start' $QA/out_head/cc_hard.debug.log | head -40
175:2026-11-25T08:45:22.129Z [DEBUG] [API:timing] dispatching to firstParty model=claude-haiku-5-5
177:2026-11-25T08:45:22.131Z [DEBUG] [API:timing] dispatching to firstParty model=claude-sonnet-5-5
183:2026-11-25T08:45:24.021Z [DEBUG] Stream started - received first chunk
184:2026-11-25T08:45:24.021Z [DEBUG] [API:timing] first byte after 1893ms
185:2026-11-25T08:45:25.254Z [DEBUG] Stream started - received first chunk
186:2026-11-25T08:45:25.255Z [DEBUG] [API:timing] first byte after 3125ms

Claude Code, dropped once

Steps and output
  1. Same steps as Before, on this leg's proxy

after drop

$ grep -n 'API:timing\|API:request\|first byte\|Stream started\|message_start' $QA/out_head/cc_drop.debug.log | head -40
175:2026-11-25T08:43:08.903Z [DEBUG] [API:timing] dispatching to firstParty model=claude-haiku-5-5
177:2026-11-25T08:43:08.906Z [DEBUG] [API:timing] dispatching to firstParty model=claude-sonnet-5-5-flaky
182:2026-11-25T08:43:11.292Z [DEBUG] Stream started - received first chunk
183:2026-11-25T08:43:11.293Z [DEBUG] [API:timing] first byte after 2392ms
184:2026-11-25T08:43:11.488Z [DEBUG] Stream started - received first chunk
185:2026-11-25T08:43:11.488Z [DEBUG] [API:timing] first byte after 2584ms
request 31: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 32: relayed whole stream

Thread create then continue, dropped once

Output
$ curl -s http://127.0.0.1:22337/arm && curl -sN -D - http://127.0.0.1:31730/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'anthropic-beta: message-threads-2026-08-12' -H 'content-type: application/json' -d '{"model":"claude-sonnet-5-5-flaky","max_tokens":1024,"stream":true,"thread":{"type":"create"},"messages":[{"role":"user","content":"Remember the number 41. Reply with just ok."}]}' | tee $QA/out_head/thread_create.sse | python3 bin/stamp.py
armed
   4.92s  HTTP/1.1 200 OK
   4.92s  event: message_start
   4.92s    message.id=msg_011ChPMLCdW8JpMgYQQb1unW
   4.92s  event: content_block_start
   4.92s  event: ping
   4.92s  event: content_block_delta
   4.92s  event: content_block_stop
   4.93s  event: message_delta
   4.93s  event: message_stop
$ tail -n +86 relay.log
request 33: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 34: relayed whole stream
$ id=$(grep -m1 '"message_start"' $QA/out_head/thread_create.sse | grep -o 'msg_[A-Za-z0-9]*' | head -1); echo previous_message_id=$id
previous_message_id=msg_011ChPMLCdW8JpMgYQQb1unW
$ curl -sN -D - http://127.0.0.1:31730/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'anthropic-beta: message-threads-2026-08-12' -H 'content-type: application/json' -d '{"model":"claude-sonnet-5-5-flaky","max_tokens":1024,"stream":true,"thread":{"type":"continue","previous_message_id":"msg_011ChPMLCdW8JpMgYQQb1unW"},"messages":[{"role":"user","content":"Which number did I ask you to remember? Reply with just the number."}]}' | tee $QA/out_head/thread_continue.sse | python3 bin/stamp.py
   2.22s  HTTP/1.1 200 OK
   2.22s  event: message_start
   2.22s    message.id=msg_011ChPMLMptfH2PQquxvKBsz
   2.22s  event: content_block_start
   2.22s  event: ping
   2.22s  event: content_block_delta
   2.22s  event: content_block_stop
   2.22s  event: message_delta
   2.22s  event: message_stop
$ grep -o '"text": *"[^"]*"' $QA/out_head/thread_continue.sse | head -3
"text":""
"text":"41"

Other cases

curl and Agent SDK cases
Anthropic, hard thinking, curl
$ curl -sN -D - http://127.0.0.1:22604/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5-5-direct","max_tokens":32000,"stream":true,"thinking":{"type":"adaptive"},"output_config":{"effort":"max"},"messages":[{"role":"user","content":"Without using any tools, count the integers between 1 and 3000 that are prime and whose digits sum to a prime. Verify your count carefully, then answer with just the number."}]}' | python3 bin/stamp.py
   4.21s  HTTP/1.1 200 OK
   4.21s  event: message_start
   4.21s    message.id=msg_011ChPMR4T1ycQBK3HJpJdKh
  19.21s  event: ping
  34.17s  event: ping
  49.17s  event: ping
  64.17s  event: ping
  64.17s  event: ping
  79.17s  event: ping
  94.17s  event: ping
  94.17s  event: ping
 109.17s  event: ping
 124.17s  event: ping
 139.17s  event: ping
 154.17s  event: ping
 154.17s  event: ping
 169.17s  event: ping
 175.90s  event: content_block_start
 175.90s  event: ping
 175.90s  event: content_block_delta
 175.96s  event: content_block_delta
 175.97s  event: content_block_stop
 175.97s  event: message_delta
 175.97s  event: message_stop
Bedrock, hard thinking, curl
$ curl -sN -D - http://127.0.0.1:22604/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5-5","max_tokens":32000,"stream":true,"thinking":{"type":"adaptive"},"output_config":{"effort":"max"},"messages":[{"role":"user","content":"Without using any tools, count the integers between 1 and 3000 that are prime and whose digits sum to a prime. Verify your count carefully, then answer with just the number."}]}' | python3 bin/stamp.py
   2.21s  HTTP/1.1 200 OK
   2.21s  event: message_start
   2.21s    message.id=msg_bdrk_weyzjjbc7yyx244rnhm2apqikhlobgdknp52lu7hyvebwgijfdoq
  17.21s  event: ping
  31.77s  event: ping
  46.77s  event: ping
  61.77s  event: ping
  76.77s  event: ping
  91.77s  event: ping
 106.77s  event: ping
 121.77s  event: ping
 136.77s  event: ping
 151.77s  event: ping
 151.77s  event: ping
 156.75s  event: content_block_start
 156.75s  event: content_block_delta
 156.94s  event: content_block_delta
 156.94s  event: content_block_stop
 156.94s  event: message_delta
 156.94s  event: message_stop
Bedrock, Agent SDK
$ sdkvenv/bin/python -I bin/sdk_stream.py http://127.0.0.1:22604 claude-sonnet-5-5
claude-agent-sdk query model=claude-sonnet-5-5 base_url=http://127.0.0.1:22604
   1.64s  stream event: message_start id=msg_bdrk_gj4lwlyg6k4cfm674xpcutzqz6ybfv6kl2wyzriwwkjgygemn6bq
  21.65s  stream event: ping
  31.65s  stream event: ping
  51.65s  stream event: ping
  61.65s  stream event: ping
  81.66s  stream event: ping
  91.66s  stream event: ping
 111.66s  stream event: ping
 121.66s  stream event: ping
 141.66s  stream event: ping
 151.66s  stream event: ping
 171.67s  stream event: ping
 181.67s  stream event: ping
 201.67s  stream event: ping
 211.67s  stream event: ping
 231.67s  stream event: ping
 241.67s  stream event: ping
 261.67s  stream event: ping
 271.68s  stream event: ping
 291.68s  stream event: ping
 301.68s  stream event: ping
 321.68s  stream event: ping
 331.68s  stream event: ping
 351.68s  stream event: ping
 361.68s  stream event: ping
 381.69s  stream event: ping
 391.69s  stream event: ping
 393.82s  stream event: content_block_start (thinking)
 393.82s  stream event: first thinking_delta
 393.94s  stream event: first signature_delta
 393.95s  stream event: content_block_stop (2 deltas in block)
 393.95s  stream event: content_block_start (text)
 393.95s  stream event: first text_delta
 393.95s  stream event: content_block_stop (1 deltas in block)
 393.96s  stream event: message_delta
 393.96s  stream event: message_stop
 393.98s  result: is_error=False answer='**222**'
Anthropic, dropped once, curl
$ curl -s http://127.0.0.1:22337/arm && curl -sN -D - http://127.0.0.1:22604/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5-5-flaky","max_tokens":4096,"stream":true,"thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"Answer in one short sentence: why is the sky blue?"}]}' | python3 bin/stamp.py
armed
   0.82s  HTTP/1.1 200 OK
   0.82s  event: message_start
   0.82s    message.id=msg_011ChPNLks68DaBw2G38hp8y
   2.64s  event: content_block_start
   2.64s  event: ping
   2.64s  event: content_block_delta
   2.68s  event: content_block_delta
   2.71s  event: content_block_delta
   2.74s  event: content_block_delta
   3.35s  event: content_block_delta
   3.35s  event: content_block_delta
   3.35s  event: content_block_delta
   3.35s  event: content_block_delta
   3.35s  event: content_block_delta
   3.35s  event: content_block_delta
   3.35s  event: content_block_delta
   3.35s  event: content_block_delta
   3.35s  event: content_block_delta
   3.36s  event: content_block_stop
   3.36s  event: message_delta
   3.36s  event: message_stop
$ tail -n +98 relay.log
request 38: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 39: relayed whole stream
Anthropic, dropped once, Agent SDK
$ curl -s http://127.0.0.1:22337/arm && sdkvenv/bin/python -I bin/sdk_stream.py http://127.0.0.1:22604 claude-sonnet-5-5-flaky 'Answer in one short sentence: why is the sky blue?'
armed
claude-agent-sdk query model=claude-sonnet-5-5-flaky base_url=http://127.0.0.1:22604
   1.36s  stream event: message_start id=msg_011ChPNM6ATRa4vnH8RDAoBj
   3.25s  stream event: content_block_start (text)
   3.25s  stream event: first text_delta
   4.14s  stream event: content_block_stop (16 deltas in block)
   4.14s  stream event: message_delta
   4.14s  stream event: message_stop
   4.15s  result: is_error=False answer='The sky is blue because molecules in the atmosphere scatter shorter blue wavelengths of sunlight much more strongly than longer red wavelengths (Rayleigh scattering), sending blue light to our eyes from every direction.'
$ tail -n +103 relay.log
request 40: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 41: relayed whole stream
Anthropic, Agent SDK
$ sdkvenv/bin/python -I bin/sdk_stream.py http://127.0.0.1:22604 claude-sonnet-5-5-direct 'Answer in one short sentence: why is the sky blue?'
claude-agent-sdk query model=claude-sonnet-5-5-direct base_url=http://127.0.0.1:22604
   1.07s  stream event: message_start id=msg_011ChPNMThGJvbhtnTJRrNCP
   1.39s  stream event: content_block_start (thinking)
   1.39s  stream event: first thinking_delta
   1.82s  stream event: first signature_delta
   1.82s  stream event: content_block_stop (3 deltas in block)
   1.82s  stream event: content_block_start (text)
   1.82s  stream event: first text_delta
   2.21s  stream event: content_block_stop (12 deltas in block)
   2.22s  stream event: message_delta
   2.22s  stream event: message_stop
   2.23s  result: is_error=False answer="Air molecules scatter sunlight's shorter blue wavelengths far more than its longer red ones (Rayleigh scattering), so blue light reaches your eyes from every direction in the sky."
gpt-5.6 bridged, curl
$ curl -sN -D - http://127.0.0.1:22604/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"gpt-5.6","max_tokens":2048,"stream":true,"messages":[{"role":"user","content":"Answer in one short sentence: why is the sky blue?"}]}' | python3 bin/stamp.py
   0.80s  HTTP/1.1 200 OK
   0.80s  event: message_start
   0.80s    message.id=msg_fb6c52a4-5f07-41d0-9964-fe21f5c4a90e
   1.50s  event: content_block_start
   1.50s  event: content_block_delta
   1.62s  event: content_block_delta
   1.62s  event: content_block_delta
   1.63s  event: content_block_delta
   1.63s  event: content_block_delta
   1.63s  event: content_block_delta
   1.63s  event: content_block_delta
   1.63s  event: content_block_delta
   1.63s  event: content_block_delta
   1.70s  event: content_block_delta
   1.70s  event: content_block_delta
   1.70s  event: content_block_delta
   1.70s  event: content_block_delta
   1.70s  event: content_block_delta
   1.70s  event: content_block_delta
   1.70s  event: content_block_delta
   1.70s  event: content_block_delta
   1.70s  event: content_block_delta
   1.78s  event: content_block_stop
   1.93s  event: message_delta
   1.93s  event: message_stop
Anthropic, every attempt dropped, curl
$ curl -s 'http://127.0.0.1:22337/arm?times=10' && curl -sN -D - http://127.0.0.1:22604/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5-5-flaky","max_tokens":4096,"stream":true,"thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"Answer in one short sentence: why is the sky blue?"}]}' | python3 bin/stamp.py; curl -s 'http://127.0.0.1:22337/arm?times=0'
armed
   0.84s  HTTP/1.1 200 OK
   0.84s  event: message_start
   0.84s    message.id=msg_011ChPNSMFCHafztkhYVoooB
   4.61s  event: content_block_start
   4.61s  event: ping
   4.65s  event: error
   4.65s    data: {"type": "error", "error": {"type": "api_error", "message": "Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>"}}
armed
$ tail -n +108 relay.log
request 42: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 43: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 44: upstream sent message_start and content_block_start, dropping the connection before any content delta
Anthropic, dropped then 529, curl
$ curl -s 'http://127.0.0.1:22337/arm?times=1&fail=10' && curl -sN -D - http://127.0.0.1:22604/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5-5-flaky","max_tokens":4096,"stream":true,"thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"Answer in one short sentence: why is the sky blue?"}]}' | python3 bin/stamp.py; curl -s 'http://127.0.0.1:22337/arm?times=0&fail=0'
armed
   0.73s  HTTP/1.1 200 OK
   0.73s  event: message_start
   0.73s    message.id=msg_011ChPNSgxcAcHXRB2KFgNd9
   3.25s  event: error
   3.25s    data: {"type": "error", "error": {"type": "overloaded_error", "message": "litellm.InternalServerError: AnthropicError - {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overl
armed
$ tail -n +116 relay.log
request 45: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 46: answered 529 overloaded_error without calling upstream
request 47: answered 529 overloaded_error without calling upstream
Fallback, mock, curl
$ curl -sN -D - http://127.0.0.1:20529/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"mock-claude","max_tokens":4096,"stream":true,"thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"hi"}]}' | python3 bin/stamp.py
  15.51s  HTTP/1.1 200 OK
  15.51s  event: ping
  20.36s  event: message_start
  20.36s    message.id=msg_mock_25
  20.36s  event: content_block_start
  20.36s  event: ping
  20.36s  event: content_block_delta
  20.36s  event: content_block_delta
  20.36s  event: content_block_stop
  20.36s  event: content_block_start
  20.36s  event: content_block_delta
  20.36s  event: content_block_stop
  20.36s  event: message_delta
  20.36s  event: message_stop
Fallback, mock, Agent SDK
$ sdkvenv/bin/python -I bin/sdk_stream.py http://127.0.0.1:20529 mock-claude hi
claude-agent-sdk query model=mock-claude base_url=http://127.0.0.1:20529
[claude-code:unrecognized_model] {"model":"mock-claude","query_source":"sdk"}
  20.87s  stream event: message_start id=msg_mock_26
  20.87s  stream event: content_block_start (thinking)
  20.87s  stream event: first thinking_delta
  20.87s  stream event: first signature_delta
  20.87s  stream event: content_block_stop (2 deltas in block)
  20.87s  stream event: content_block_start (text)
  20.87s  stream event: first text_delta
  20.87s  stream event: content_block_stop (1 deltas in block)
  20.88s  stream event: message_delta
  20.88s  stream event: message_stop
  20.89s  result: is_error=False answer='Hello.'
Context-window fallback, mock, curl
$ curl -sN -D - http://127.0.0.1:20696/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"mock-claude","max_tokens":4096,"stream":true,"thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"hi"}]}' | python3 bin/stamp.py
  15.66s  HTTP/1.1 200 OK
  15.66s  event: ping
  20.39s  event: message_start
  20.39s    message.id=msg_mock_24
  20.39s  event: content_block_start
  20.39s  event: ping
  20.39s  event: content_block_delta
  20.39s  event: content_block_delta
  20.39s  event: content_block_stop
  20.39s  event: content_block_start
  20.39s  event: content_block_delta
  20.39s  event: content_block_stop
  20.39s  event: message_delta
  20.39s  event: message_stop
Mock, 20s thinking, curl
$ curl -sN -D - http://127.0.0.1:22604/v1/messages -H "x-api-key: $LITELLM_KEY" -H 'content-type: application/json' -d '{"model":"mock-claude","max_tokens":4096,"stream":true,"thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"hi"}]}' | python3 bin/stamp.py
   0.03s  HTTP/1.1 200 OK
   0.03s  event: message_start
   0.03s    message.id=msg_mock_27
  15.03s  event: ping
  20.02s  event: content_block_start
  20.02s  event: ping
  20.02s  event: content_block_delta
  20.02s  event: content_block_delta
  20.02s  event: content_block_stop
  20.02s  event: content_block_start
  20.02s  event: content_block_delta
  20.02s  event: content_block_stop
  20.02s  event: message_delta
  20.02s  event: message_stop
Anthropic, dropped once, spend row, curl

The whole output is in a gist. Its last line:

{"rows":1,"request_ids":["msg_011ChPMPHU3kdaxkGmXPXWiq"],"status":["success"],"total_tokens":[79]}

After (02a828c)

Two id cases
Anthropic, dropped once, spend row, curl

The whole output is in a gist. Its last line:

{"rows":1,"request_ids":["msg_011ChPanLBR2SRhMxcNJSF4g"],"status":["success"],"total_tokens":[95]}
SDK Router, dropped once, callback id

sdk_router_ids.py streams through a litellm.Router with num_retries=1 and a success callback, against the relay that cuts attempt 1 before content

$ curl -s http://127.0.0.1:22337/arm && .venv/bin/python $QA/bin/sdk_router_ids.py http://127.0.0.1:22337
armed
message_start ids the caller got: ['msg_011ChPacyd9HuHqPFV6hGanP']
ids the success callback logged: ['msg_011ChPacyd9HuHqPFV6hGanP']
$ grep -E '^request (54|55):' relay.log
request 54: upstream sent message_start and content_block_start, dropping the connection before any content delta
request 55: relayed whole stream

QA observations

  • Claude Code ignores pings when timing first byte
  • Both legs end 200 plus error when every attempt drops
  • That error carries raw aiohttp text on both legs, pre-existing

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • A retry rejected after message_start ends as 200 plus event: error, so the Anthropic SDK skips its own retry
  • After a retry the client keeps attempt 1's message_start and headers, so x-litellm-attempted-retries reads 0
  • Fallback settings still hold message_start, tracked in a follow-up
  • With LITELLM_RUST_FIRST on, the Rust gateway still holds message_start, tracked in a follow-up

Low

  • Only Anthropic retries after a live message_start ran live
  • The fallback rows use a mock upstream
  • CI runs the six changed integration files only on main, and they passed locally
Decisions

What goes out early. Frames wait for the first content delta while a retry or fallback could take over. Pings go out live as on base, and a ping that shares a read with a held block start stays held with it, as on base. message_start goes out live when only a retry can take over and the request has no thread

Threads. A request with thread keeps the old hold. Anthropic stores only the message of the attempt that answers, and the next continue names the id the client saw, so a live message_start from a cut attempt would make that continue answer 404. Rejected: mapping the cut id to the retry's id in MessageThreadOwnership, which only works with that hook on and a store shared by every replica

Block starts. content_block_start still waits for the first delta. A retry can open a different block (text where attempt 1 opened thinking, or a new tool id), so a live block start could leave the client with two starts at one index

Status. Once message_start goes out the status is 200, so a retry that then fails ends as 200 plus event: error, the way Anthropic answers once its own message_start is out. The Anthropic SDK retries on a status, never on that frame, so it no longer retries the request itself. Before, a retry that also dropped already ended that way, and only one rejected with an error status kept it. A group whose only retry setting is a model_group_retry_policy that does not cover a dropped stream also goes live, so a drop there ends as 200 plus event: error where base answered 500, the same as num_retries: 0 on both. Rejected: holding message_start for the first 15s, which keeps the status a little longer but leaves the bug, and going live only when the policy names a drop's error class, which keeps the thinking delay in those groups to keep a 500 that num_retries: 0 never sends

Forced by the ask. The internal ticket asks for message_start as soon as the provider sends it, with a later drop still retried and only one message_start. Once that frame is out the status, the headers and the message_start fields can no longer change, so the 200 status, attempt 1's id, model and usage, and retry headers that read no retry follow from the ask

Rejected. Capping the hold adds a fixed delay. Any fallback setting keeps message_start held, context_window_fallbacks for the group, order levels and weighted failover inside one model group included, since the ticket covers the default settings and a fallback can answer from another model

After a retry. The client keeps attempt 1's message_start, so its id, model and usage come from the cut attempt, and with prompt caching that usage shows a cache write where the retry read the cache. Headers go out with that first frame, before any retry, so they match a stream with no retry, x-litellm-attempted-retries reading 0, no x-litellm-max-retries, and x-litellm-response-duration-ms stopping at message_start. The spend row and success callbacks take the id the client saw, on the proxy and the SDK Router alike, so /spend/logs?request_id= with that id finds it, while its usage stays the retry's like message_delta. When the retry lands on another deployment of the group, x-litellm-model-id names the cut one and the spend row the one that answered. A later request that sends attempt 1's id as diagnostics.previous_message_id gets Anthropic's 200 with a previous_message_not_found note. Rejected: dropping x-litellm-attempted-retries or adding x-litellm-max-retries on live streams, since both change what a stream with no retry sends and neither can report a retry that has not happened yet

Whole frames. Only a stream whose message_start can go out live is read as whole SSE frames, kept together per upstream read with message_start on its own, so a split message_start never goes out half and a ping keeps base's place next to the block start it came with. Rejected: one frame at a time, which sent that ping ahead of the held block start. Held streams keep base's raw reads, so a ping that shares a read with message_start stays held with it and the status waits as on base. Content detection reads the held bytes plus the current read, so a content_block_delta split across reads still sends the stream on at once

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
Bugbot summary

[!NOTE]
High Risk
Changes core Anthropic streaming retry semantics, client-visible SSE timing/status, and billing/message-id attribution—high blast radius for router and proxy users.

Overview
Fixes a regression where streaming /v1/messages held message_start until the first content delta whenever retries or fallbacks could still take over, so clients (e.g. Claude Code) saw only pings for long stretches during thinking.

wrap_anthropic_stream now sends message_start and keepalive frames live when only a same-group retry can take over and the request has no thread; other lifecycle frames stay buffered until content commits the stream. Threaded requests and any fallback-capable policy still hold the full preamble. On retry, the gateway drops the retry’s message_start, replays content as whole SSE frames where needed, and records the message id the client already saw in logging/spend via record_streamed_anthropic_message_id.

Supporting changes wire litellm_logging_obj through native stream wrappers, add sse_frames_by_read / read-aware framing, and expose context_window_fallback on Rust StreamPolicy (separate from generic fallbacks).

Reviewed by Cursor Bugbot for commit 02a828c. Bugbot is set up for automated code reviews on this repo. Configure here.

…y can take over

With the router's default retries and no fallback, message_start and
content_block_start were held until the first content delta, so a long
thinking pass showed the client nothing but the proxy's keepalive ping.
They now go out as soon as the provider sends them, and a retry before
content drops its repeat of the frames already sent. A fallback or a
refusal fallback keeps the hold.
…an take over

With default num_retries, every lifecycle frame waited for the first content delta, so a long thinking pass showed the client nothing but the 15 s keepalive ping. Now message_start, plus any ping or SSE comment in front of it, goes out as soon as the provider sends it whenever only a same-group retry can take over

Block starts and every other pre-content frame stay held, because a retry's first block can differ from the first attempt's (adaptive thinking can open text where the first attempt opened thinking, and redacted_thinking carries new data each time). A retry or a context-window fallback drops its own message_start and then sends its frames unchanged, so the client sees one message_start and a valid frame sequence. A fallback, refusal fallback, order level, or weighted failover left keeps the full hold, and so does a stream whose first frame is not recognized
…am_lifecycle_live_on_retry

# Conflicts:
#	litellm/router_rust/invoke/streaming.py
@veria-ai

veria-ai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@greptile-apps

greptile-apps Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The reviewed changes appear safe to merge.

Summary

The PR sends message_start immediately when only a retry can take over and the request has no thread. Block starts still wait for content, and retries suppress their duplicate message_start.

The latest changes expose the stream's logger so SDK success callbacks keep the id the client received. Added tests cover ordinary streams, cache misses, and agentic hooks. No new actionable issues were found. The earlier split-event and spend-row lookup findings are fixed.

  • Retry-only message streams send one start early and continue with retry content.

Reviews (10) · Last reviewed commit: "fix(messages): carry the call's logger o..." · Reviewed by Greptile

Comment thread litellm/router_rust/invoke/streaming.py Resolved
A request with a message thread keeps the old hold, so the client sees the message id of the attempt that answers and its next continue finds the thread. Also types two test literals and the guardrail initializer lookup so the basedpyright count stops flipping between runs.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

Comment thread litellm/router_rust/invoke/streaming.py Resolved
@codecov

codecov Bot commented Nov 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

…an answer the stream

A context_window_fallbacks list for the stream's group can take over after a retry fails, so the stream policy now reports it and message_start waits for content as before. streaming.py also reuses the shared SSE frame terminators.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

Comment thread litellm/router_rust/invoke/streaming.py Resolved
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 02a828c. Configure here.

@mateo-berri mateo-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Intermittent ~16.7s time-to-first-byte (TTFB) on streaming Anthropic /v1/messages requests, not reproducible against Bedrock directly

2 participants