Skip to content

fix(spend-logs): keep provider-signed reasoning whole so previous_response_id replay stops answering 400 - #53753

Open
rhea-tk wants to merge 25 commits into
BerriAI:mainfrom
rhea-tk:litellm_responses_replay_full_reasoning_signature
Open

rhea-tk wants to merge 25 commits into
BerriAI:mainfrom
rhea-tk:litellm_responses_replay_full_reasoning_signature

Conversation

@rhea-tk

@rhea-tk rhea-tk commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

Following up on a previous response with Claude or Gemini thinking used to fail with a 400, because the gateway cut the long signature the provider needs when it saved the first response. Now it saves those signatures whole so the follow-up works

/walkthrough: What the PR adds

/walkthrough: What breaks

Details

TLDR

Problem this solves:

  • previous_response_id follow-ups on Claude or Gemini thinking answer 400
  • Spend logs cut the signatures that the replay sends back
  • Several tool calls in one turn are replayed twice, also a 400

How it solves it:

  • The stored response keeps provider-signed fields whole
  • Signed fields cut in older rows or saved requests are left out of the replay
  • Each tool call is replayed once, next to its outputs

User Flow

Before: a developer who chains Claude or Gemini thinking turns through the Responses API gets a 400 on the second turn

  1. They send POST https://litellm-domain/v1/responses with "reasoning": {"effort": "high"} to a Claude or Gemini model
  2. It answers 200 with a reasoning item, the answer, and an id like resp_...
  3. They send POST https://litellm-domain/v1/responses with previous_response_id set to that id and a new question or tool outputs
  4. It answers 400 with Invalid `signature` in `thinking` block from Claude or Invalid value at 'contents[1].parts[1].thought_signature' from Gemini

After: the same follow-up answers 200 and builds on the first turn

  1. They repeat steps 1 to 3 of Before
  2. It answers 200 with an answer that uses the first turn, and a third chained turn works too
Decisions

What is saved whole. On the rows of /v1/responses calls that LiteLLM serves through chat completions, signed Claude thinking blocks (text included, since Claude checks the signature against it), redacted_thinking.data, reasoning.encrypted_content, Gemini thought_signature, thought_signatures and response_thought_signature, and tool call ids that carry __thought__ are cut at 1 MiB instead of 2,048 characters. The new MAX_STRING_LENGTH_PROVIDER_SIGNED_IN_DB env var sets that limit, and a larger MAX_STRING_LENGTH_PROMPT_IN_DB wins. A smaller one does not lower it, so an operator who lowered the prompt limit to keep rows small sets the new variable too. Letting any set prompt limit bound signed fields was ruled out, because an operator who raised it would then have every signature past their limit cut again, and the follow-up would lose the earlier turn's reasoning. Letting only a lowered one bound them would make limits of 2,047 and 2,048 behave differently. Rows grow by the size of those fields. Token redaction still applies. I ruled out only dropping cut reasoning at replay (the model loses context and Claude wants the signed block on tool turns), raising MAX_STRING_LENGTH_PROMPT_IN_DB (grows every field of every row), no cap at all (one row could hold any amount of thinking), and a separate store (a schema change for a few fields)

Severe caveat, for the owner to sign off. An operator who lowered MAX_STRING_LENGTH_PROMPT_IN_DB to keep spend-log rows small gets bigger rows for /v1/responses calls served through chat completions after upgrading. Setting MAX_STRING_LENGTH_PROVIDER_SIGNED_IN_DB to the same value keeps today's rows, and those follow-ups answer 400 again. At a 500-character limit a stored Claude thinking response grew from 4,939 to 8,102 characters and its follow-up went from 400 to 200. GCS Pub/Sub with gcs_pub_sub_use_v1 ships the same row, not verified because the QA project has no Pub/Sub access. SPEND_LOGS_URL exports nothing on either side, since its client is never set. The options are to ship as is, to let a set MAX_STRING_LENGTH_PROMPT_IN_DB bound signed fields unless MAX_STRING_LENGTH_PROVIDER_SIGNED_IN_DB is also set, or to not ship. I recommend shipping as is, for the reason above

Only rows LiteLLM replays. Chat completions and /v1/messages rows keep the 2,048 cut, because only previous_response_id reads rows back and those routes never answer with a response id to continue from. Native Responses API routes such as OpenAI and Azure keep it too, because the provider stores those conversations and LiteLLM never replays their rows. A row counts as served through chat completions when its logged response is chat-shaped, the same test the latest_turn spend-log mode already uses to keep a replayed turn's whole request. A session that mixes routes replays a chat or messages turn without its signed reasoning, the same as today. Keeping it whole on every route would grow rows that nothing reads back and that exporters such as GCS Pub/Sub ship as they are

What stays bounded. The saved request. Replay rebuilds the assistant turn from the saved response, so reasoning a client resends in its own input and then continues by id is left out of the replay, and no longer answers 400. With message logging off, rows keep today's storage, and compaction blocks are stored as before

Rows from before this change. A signed field that was cut, or masked by token redaction, is left out of the replay with one warning, and a cut signed tool call id is trimmed to the part before __thought__. A value counts as cut only where the cut marker sits exactly where the writer cuts. Rows from v1.77.3-stable to v1.82.0-stable carry an older marker, which is recognised too

Tool outputs. Gemini puts its signature inside the tool call id, so an output is matched to its call by the exact id first, then by the part before __thought__. The same match finds the call in an earlier turn when a compaction item starts the replay

Repeated calls. Before, replay could make a stored call a second time, once from storage and once from the process memory or the client. A message that holds only calls the nearest assistant message made once, and that are still unanswered, is now left out when every call in it is a repeat, unless a user, developer or system message comes in between. A call the client sends back is a repeat when it has the same tool and the same arguments, read as JSON, or arguments storage no longer holds. A copy that storage itself cut is a repeat by its id and tool. A call the worker remembers is a repeat by its id alone, because that memory is keyed by the call id and may hold another conversation's call. A call sent back with other arguments or another tool is sent as the client sent it, as before. Ids name the same call when they are equal or when one has lost its __thought__ part, a tool name may have lost its namespace before __, and calls of one turn that share the part before __thought__ are sent as before. A message that says anything more (text, reasoning, cache_control, a new call) stays as sent, and what follows it in that turn is what it was before this change. When storage cut a call's arguments, the kept call gets them back from a repeat, the client's or the remembered one, but only if the stored text is exactly what the writer would have cut from them. When storage holds {} because message logging is off, only a call the client sends back fills it. On a route that builds Anthropic Messages or Bedrock Converse requests, every call keeps the arguments storage holds, because Claude checks a signed turn against the whole conversation before it, and whole arguments that only one worker remembers would make the next turn on another worker answer 400. On other routes, a turn whose stored thinking carries a signature (Databricks Claude, say) keeps them too, because the provider checks that turn against what it signed. Gemini signs the call instead of its thinking and accepts arguments that differ from the signed call, so a Gemini turn takes whole arguments from a repeat, as before this change. The route is read from its provider config, not the model name, so every Bedrock Converse model keeps them, Nova and Llama included. A Converse deployment often names Claude by an inference profile ARN or an alias that no name check can read, and a missed Claude answers 400. A non-Claude Converse model then sees the stored cut copy, as any model does when neither the worker nor the client has the whole call. Storing arguments whole was ruled out, since it has no size bound. Left as before: a repeat of a cut call that the client spelled another way, arguments that token redaction masked, and a custom tool call whose input does not survive litellm's own wrapping

Known gaps. With a first prompt over 2,048 characters, 1 of 5 routes (Vertex Claude) still answers 400, before and after, because the stored prompt is cut and Vertex binds the thinking to it. A Claude route, or a turn made with signed thinking, sees call arguments over 2,048 characters cut. With message logging off, a Claude tool output on the third turn answers 400, before and after, and so does a Claude turn after a compaction item, which before failed one turn earlier. Gemini answers 400, before and after, when arguments were cut inside a JSON escape and the worker does not remember the call. A Claude turn whose stored arguments were cut inside a JSON escape answers 400 too, as 1 of 8 Vertex Claude runs did. Web search encrypted_content, long visible answers and very small limits are not touched here

No PR to build on. None of the open PRs on this symptom fixes the spend-log cut. #44137 checks base64 on Gemini replay, #43435 keeps Gemini text signatures, #41590 shortens long item ids, #38337 maps ids across providers and #38333 rejects a mangled signature

This is an LLM translation fix, so a paired PR takes it to lts/1.108.x

Relevant issues

Fixes #42201

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: d5cf8d2. QA ran on e4562b9. Changes since QA: the limit getters name their env vars literally, and a test pins its clock. Proof remains valid because the getters read the same variables and defaults. Verification: spend tracking and responses unit tests, env-key docs check

Both legs ran the same curl scripts on real providers (claude-sonnet-5-5 on Anthropic, Vertex and Bedrock, gemini-3.8-flash on Google AI Studio and Vertex) with 2 uvicorn workers, one Postgres and no Redis. Every log is in this gist.

Case Before After
Follow-up, streamed third turn 400 on 4 of 4 200 on 4 of 4
Streamed first turn 400 on 4 of 4 200 on 4 of 4
Tool output, third turn 400 on 4 of 4 200 on 4 of 4
Three tool calls in one turn 400 on 4 of 4 200 on 4 of 4
Calls sent again with outputs 400 on 4 of 4 200 on 4 of 4
Arguments over 2,048 characters 400 on 4 of 4 200 on 4 of 4
History resent, then an id 400 on 3 of 4 200 on 4 of 4
First prompt over 2,048 characters 400 on 4 of 4 400 on 1 of 4
Bedrock Claude, nine shapes 400 on 7 of 9 200 on 9 of 9
Rows stored before the upgrade 400 on 2 of 2 200 on 2 of 2
Reporter's SDK script, two prompts 400 on 1 of 2 200 on 2 of 2
More setups
Case Before After
History resent, no id 200 on 4 of 4 200 on 4 of 4
Two proxies taking turns 400 on 2 of 2 200 on 2 of 2
Rows stored by v1.82.0-stable 400 on 2 of 2 200 on 2 of 2
Two proxies, cut arguments and resent calls 400 on 2 of 2 200 on 4 of 4
Long call made without thinking, then thinking, two proxies 400 on 3 of 4 400 on 1 of 8
Spend ledger off 400 on 2 of 2 200 on 2 of 2
Token redaction on 400 on 2 of 2 200 on 2 of 2
Message logging off, follow-up 400 on 1 of 2 200 on 2 of 2
Message logging off, Claude tool turn 3 400 400
Message logging off, compaction, then Claude 500 at turn 2 400 at turn 4
Gemini search plus a tool 400 200
Compaction item, other model 500 200
Chat and messages spend rows signature cut signature cut
Storage limits

Each row is one turn's spend log, read back through /spend/logs, then a previous_response_id follow-up. A cut signature is left out of the replay, so that follow-up still answers 200

Setup Stored signature Follow-up
Default limits, Claude 2,336 chars, whole 200
Default limits, Claude streamed 2,476 chars, whole 200
MAX_STRING_LENGTH_PROMPT_IN_DB=1000, Claude 2,064 chars, whole 200
Both limits 1000, Claude 1,246 chars, cut 200
Default limits, GPT native Responses 2,293 chars, cut 200
Same GPT turn on main 2,293 chars, cut 200
Merged with main, and input tokens

Merged into main at 3e27fc2, the first six cases on all four Claude and Gemini routes answered 200 on 74 of 75 turns (the main-merged-* logs). The other follows up a turn Claude refused, which fails on main too

Claude's follow-up carried 626 input tokens, as the same turns sent straight to Anthropic did (134 without thinking), and its tool output turn carried 1392, again the same as direct

Shared setup with the env vars, config.yaml, proxy start and matrix.zsh

The env vars are ANTHROPIC_API_KEY, GEMINI_API_KEY, VERTEXAI_PROJECT, GOOGLE_APPLICATION_CREDENTIALS, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, LITELLM_MASTER_KEY, LITELLM_SALT_KEY and DATABASE_URL, names only

config.yaml

model_list:
  - model_name: claude-sonnet-5-5
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: gemini-3.8-flash
    litellm_params:
      model: gemini/gemini-3.8-flash
      api_key: os.environ/GEMINI_API_KEY
  - model_name: bedrock-claude-sonnet-5-5
    litellm_params:
      model: bedrock/us.anthropic.claude-sonnet-5-5
      aws_region_name: us-east-1
  - model_name: vertex-claude-sonnet-5-5
    litellm_params:
      model: vertex_ai/claude-sonnet-5-5
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: global
      vertex_credentials: os.environ/GOOGLE_APPLICATION_CREDENTIALS
  - model_name: vertex-gemini-3.8-flash
    litellm_params:
      model: vertex_ai/gemini-3.8-flash
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: global
      vertex_credentials: os.environ/GOOGLE_APPLICATION_CREDENTIALS

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  store_prompts_in_spend_logs: true

Proxy start, from each tree, port 24311 for Before and 26417 for After

python litellm/proxy/proxy_cli.py --config config.yaml --host 127.0.0.1 --port <port> --num_workers 2 --telemetry False --use_v2_migration_resolver --timeout_worker_healthcheck 120

Cases run with zsh matrix.zsh http://127.0.0.1:<port> <out dir> <model> "text stream tool parallel bigargs resend resent mixed long". The other scripts are in the gist

#!/bin/zsh
URLS=(${(s:,:)1})
TURN=0
OUT=$2
MODEL=$3
KINDS=${4:-text tool resent mixed}
TOKENS=${TOKENS:-16000}
mkdir -p $OUT && cd $OUT || exit 1
run() { printf '$ %s\n' "$1"; eval "$1"; }
want() { [[ " $KINDS " == *" $1 "* ]]; }
AUTH='-H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json"'
VIEW='{status, error: (.error.message // null | if . == null then null else tostring | .[0:150] end), in: .usage.input_tokens, cached: .usage.input_tokens_details.cached_tokens, out: .usage.output_tokens, types: [.output[]?.type], signature_chars: ([.output[]? | if .type=="reasoning" then (.encrypted_content // "" | fromjson? | .[]? | .signature? | length) elif .type=="function_call" then (.provider_specific_fields.thought_signature? // "" | length) else empty end] | max), answer: ([.output[]? | select(.type=="message") | .content[0].text] | first | tostring | .[0:50])}'
QUESTION="Count the ordered triples (a, b, c) of positive integers with a*b*c = 720720 and a <= b <= c, and separately the ones with a < b < c. Check both counts with two independent methods before you answer, then reply with only the two numbers."
[[ $MODEL == *gemini* ]] && QUESTION="How many integers from 1 to 2000 are divisible by 3 or 5 but by neither 7 nor 11? Work it out carefully, then reply with only the final number."
REPEAT="Repeat what you answered, digits only."
TOOLS='[{"type":"function","name":"get_weather","description":"Current weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}]'
NOTE_TOOLS='[{"type":"function","name":"save_note","description":"Save a note","parameters":{"type":"object","properties":{"title":{"type":"string"},"text":{"type":"string"}},"required":["title","text"]}}]'
BASE="model: \"$MODEL\", max_output_tokens: $TOKENS, reasoning: {effort: \"high\"}"

next_url() { URL=$URLS[$(( TURN % $#URLS + 1 ))]; TURN=$(( TURN + 1 )); }
post() { next_url; run "curl -s $URL/v1/responses $AUTH -d @$1.json -o $1.out.json -w 'http=%{http_code}\n'"; run "jq -c '$VIEW' $1.out.json"; }
post_stream() {
  next_url
  run "curl -sN $URL/v1/responses $AUTH -d @$1.json -o $1.sse -w 'http=%{http_code}\n'"
  run "{ grep '^data: {' $1.sse | sed 's/^data: //' | jq -c 'select(.type==\"response.completed\") | .response'; grep -v '^data: ' $1.sse | grep '^{' ; } | head -1 > $1.out.json; jq -c '$VIEW' $1.out.json"
}
first() { run "jq -n --arg q '$2' '{$BASE, $3 input: [{role: \"user\", content: \$q}]}' > $1.json"; }
by_id() { run "jq -n --arg prev \"\$(jq -r .id $2.out.json)\" '{$BASE, $3 previous_response_id: \$prev, input: [{role: \"user\", content: \"$REPEAT\"}]}' > $1.json"; }
tool_by_id() { run "jq -n --arg prev \"\$(jq -r .id $2.out.json)\" --arg call \"\$(jq -r '[.output[] | select(.type==\"function_call\")][0].call_id' $2.out.json)\" --argjson tools '$TOOLS' '{$BASE, tools: \$tools, previous_response_id: \$prev, input: [{type: \"function_call_output\", call_id: \$call, output: \"{\\\"city\\\":\\\"Paris\\\",\\\"temp_c\\\":14}\"}]}' > $1.json"; }
by_id_tools() { run "jq -n --arg prev \"\$(jq -r .id $2.out.json)\" --argjson tools '$TOOLS' '{$BASE, tools: \$tools, previous_response_id: \$prev, input: [{role: \"user\", content: \"$REPEAT\"}]}' > $1.json"; }
answered() { [[ $(jq -r '.id // ""' $1.out.json) != "" ]] || { echo "no next turn, $1 answered no response id to continue from"; return 1; }; }
resent() { run "jq -n --slurpfile sent $2.json --slurpfile got $2.out.json '{$BASE, input: (\$sent[0].input + \$got[0].output + [{role: \"user\", content: \"$REPEAT\"}])}' > $1.json"; }

if want text; then
echo "### $MODEL text: turn 1, then turn 2 and a streamed turn 3 continued with previous_response_id"
first text1 "$QUESTION"; post text1
by_id text2 text1; post text2
answered text2 && { by_id text3 text2 "stream: true,"; post_stream text3; }
fi
if want stream; then
echo "### $MODEL stream: streamed turn 1, then turn 2 continued with previous_response_id"
first stream1 "$QUESTION" "stream: true,"; post_stream stream1
by_id stream2 stream1; post stream2
fi
if want tool; then
echo "### $MODEL tool: a tool call, its output, then a third turn, each continued with previous_response_id"
run "jq -n --arg q 'First work out carefully: $QUESTION Then call get_weather for Paris before you answer.' --argjson tools '$TOOLS' '{$BASE, tools: \$tools, input: [{role: \"user\", content: \$q}]}' > tool1.json"; post tool1
tool_by_id tool2 tool1; post tool2
answered tool2 && { by_id_tools tool3 tool2; post tool3; }
fi
if want parallel; then
echo "### $MODEL parallel: three tool calls in one turn, their outputs in one follow-up, then a third turn, each continued with previous_response_id"
run "jq -n --arg q 'First work out carefully: $QUESTION Then call get_weather for Paris, for Rome and for Oslo, all three calls in this one turn, before you answer.' --argjson tools '$TOOLS' '{$BASE, tools: \$tools, input: [{role: \"user\", content: \$q}]}' > parallel1.json"; post parallel1
run "jq -n --arg prev \"\$(jq -r .id parallel1.out.json)\" --argjson calls \"\$(jq -c '[.output[] | select(.type==\"function_call\") | .call_id]' parallel1.out.json)\" --argjson tools '$TOOLS' '{$BASE, tools: \$tools, previous_response_id: \$prev, input: [\$calls[] | {type: \"function_call_output\", call_id: ., output: \"{\\\"temp_c\\\":14}\"}]}' > parallel2.json"; post parallel2
answered parallel2 && { by_id_tools parallel3 parallel2; post parallel3; }
fi
if want bigargs; then
echo "### $MODEL bigargs: two tool calls in one turn with arguments over the stored length limit, their outputs in one follow-up, then a third turn, each continued with previous_response_id"
run "jq -n --arg q 'First work out carefully: $QUESTION Then call save_note two times in this one turn, with title a and with title b. The text of each is the whole numbers from 1 to 700 written out in order, separated by single spaces, none left out.' --argjson tools '$NOTE_TOOLS' '{$BASE, tools: \$tools, input: [{role: \"user\", content: \$q}]}' > bigargs1.json"; post bigargs1
run "jq -c '[.output[] | select(.type==\"function_call\") | .arguments | length]' bigargs1.out.json"
run "jq -n --arg prev \"\$(jq -r .id bigargs1.out.json)\" --argjson calls \"\$(jq -c '[.output[] | select(.type==\"function_call\") | .call_id]' bigargs1.out.json)\" --argjson tools '$NOTE_TOOLS' '{$BASE, tools: \$tools, previous_response_id: \$prev, input: [\$calls[] | {type: \"function_call_output\", call_id: ., output: \"{\\\"saved\\\":true}\"}]}' > bigargs2.json"; post bigargs2
answered bigargs2 && { run "jq -n --arg prev \"\$(jq -r .id bigargs2.out.json)\" --argjson calls \"\$(jq -c '[.output[] | select(.type==\"function_call\") | .call_id]' bigargs2.out.json)\" --argjson tools '$NOTE_TOOLS' '{$BASE, tools: \$tools, previous_response_id: \$prev, input: ([\$calls[] | {type: \"function_call_output\", call_id: ., output: \"{\\\"saved\\\":true}\"}] + [{role: \"user\", content: \"What was the last number you wrote in note b? Digits only.\"}])}' > bigargs3.json"; post bigargs3; }
fi
if want resend; then
echo "### $MODEL resend: three tool calls in one turn, then two follow-ups with previous_response_id that send the calls again with their outputs, all calls first (together) and call by call (each), and a third turn after each"
run "jq -n --arg q 'First work out carefully: $QUESTION Then call get_weather for Paris, for Rome and for Oslo, all three calls in this one turn, before you answer.' --argjson tools '$TOOLS' '{$BASE, tools: \$tools, input: [{role: \"user\", content: \$q}]}' > resend1.json"; post resend1
for shape in together each; do
  ITEMS='$calls + $outs'; [[ $shape == each ]] && ITEMS='([range($calls | length)] | map($calls[.], $outs[.]))'
  run "jq -n --slurpfile got resend1.out.json --argjson tools '$TOOLS' '[\$got[0].output[] | select(.type==\"function_call\")] as \$calls | (\$calls | map({type: \"function_call_output\", call_id: .call_id, output: \"{\\\"temp_c\\\":14}\"})) as \$outs | {$BASE, tools: \$tools, previous_response_id: \$got[0].id, input: ($ITEMS)}' > $shape""2.json"; post $shape""2
  answered $shape""2 && { by_id_tools $shape""3 $shape""2; post $shape""3; }
done
fi
if want resent; then
echo "### $MODEL resent: the same conversation with the history resent and no previous_response_id"
[[ -s text1.out.json ]] || { first text1 "$QUESTION"; post text1; }
resent resent2 text1; post resent2
resent resent3 resent2; post resent3
fi
if want mixed; then
echo "### $MODEL mixed: the history resent on turn 2, then turn 3 continued with previous_response_id"
[[ -s resent2.out.json ]] || { resent resent2 text1; post resent2; }
by_id mixed3 resent2; post mixed3
fi
if want long; then
echo "### $MODEL long: a first message over the stored length limit, then turn 2 and turn 3 continued with previous_response_id"
run "jq -n --arg q '$QUESTION' --arg notes \"\$(jq -rn '[range(1; 161) | \"Note \\(.): the meeting moved to room \\(. * 7).\"] | join(\" \")')\" '{$BASE, input: [{role: \"user\", content: (\$q + \" These notes are only for later: \" + \$notes)}]}' > long1.json"; post long1
by_id long2 long1; post long2
answered long2 && { by_id long3 long2; post long3; }
fi

Before (768ea1b)

Case 1: Claude reasoning, then a previous_response_id follow-up

  1. Turn 1 answers 200 with a reasoning item
  2. Turn 2 sends previous_response_id and answers 400 on the signature
Commands and output
$ jq -n --arg q 'Count the ordered triples (a, b, c) of positive integers with a*b*c = 720720 and a <= b <= c, and separately the ones with a < b < c. Check both counts with two independent methods before you answer, then reply with only the two numbers.' '{model: "claude-sonnet-5-5", max_output_tokens: 16000, reasoning: {effort: "high"},  input: [{role: "user", content: $q}]}' > text1.json
$ curl -s http://127.0.0.1:24311/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d @text1.json -o text1.out.json -w 'http=%{http_code}\n'
http=200
$ jq -c '{status, error: (.error.message // null | if . == null then null else tostring | .[0:150] end), in: .usage.input_tokens, cached: .usage.input_tokens_details.cached_tokens, out: .usage.output_tokens, types: [.output[]?.type], signature_chars: ([.output[]? | if .type=="reasoning" then (.encrypted_content // "" | fromjson? | .[]? | .signature? | length) elif .type=="function_call" then (.provider_specific_fields.thought_signature? // "" | length) else empty end] | max), answer: ([.output[]? | select(.type=="message") | .content[0].text] | first | tostring | .[0:50])}' text1.out.json
{"status":"completed","error":null,"in":88,"cached":0,"out":571,"types":["reasoning","message"],"signature_chars":2200,"answer":"**1218** (a ≤ b ≤ c) and **1212** (a < b < c)"}
$ jq -n --arg prev "$(jq -r .id text1.out.json)" '{model: "claude-sonnet-5-5", max_output_tokens: 16000, reasoning: {effort: "high"},  previous_response_id: $prev, input: [{role: "user", content: "Repeat what you answered, digits only."}]}' > text2.json
$ curl -s http://127.0.0.1:24311/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d @text2.json -o text2.out.json -w 'http=%{http_code}\n'
http=400
$ jq -c '{status, error: (.error.message // null | if . == null then null else tostring | .[0:150] end), in: .usage.input_tokens, cached: .usage.input_tokens_details.cached_tokens, out: .usage.output_tokens, types: [.output[]?.type], signature_chars: ([.output[]? | if .type=="reasoning" then (.encrypted_content // "" | fromjson? | .[]? | .signature? | length) elif .type=="function_call" then (.provider_specific_fields.thought_signature? // "" | length) else empty end] | max), answer: ([.output[]? | select(.type=="message") | .content[0].text] | first | tostring | .[0:50])}' text2.out.json
{"status":null,"error":"litellm.BadRequestError: AnthropicException - {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"messages.1.content.0: Invalid `signat","in":null,"cached":null,"out":null,"types":[],"signature_chars":null,"answer":"null"}
no next turn, text2 answered no response id to continue from

Case 2: every route and turn shape

Results per route

Each cell lists a conversation's answers in order, with input tokens

Turns Claude Gemini Vertex Claude Vertex Gemini Bedrock Claude
question, follow-up 200 (88), 400 200 (44), 400 200 (88), 400 200 (43), 400 200 (88), 400
streamed first turn 200 (88), 400 200 (44), 400 200 (88), 400 200 (43), 400 200 (88), 400
tool call, output 200 (466), 400 200 (102), 400 200 (466), 400 200 (81), 400 200 (466), 400
three calls, outputs 200 (488), 400 200 (117), 400 200 (488), 400 200 (96), 400 200 (488), 400
three calls, then calls sent again with outputs, twice 200 (488), 400, 400 200 (117), 400, 400 200 (488), 400, 400 200 (96), 400, 400 200 (488), 200 (1245), 200 (1295), 200 (1540), 200 (1564)
two calls with long arguments 200 (519), 400 200 (151), 400 200 (519), 400 200 (122), 400 200 (519), 400
history resent, no id 200 (676), 200 (1167) 200 (570), 200 (704) 200 (686), 200 (745) 200 (54), 200 (65) 200 (743), 200 (790)
history resent, then an id 400 200 (769) 400 400 400
first prompt over 2,048 characters 200 (2674), 400 200 (2506), 400 200 (2674), 400 200 (2505), 400 200 (2674), 400

After (e4562b9)

Case 1: Claude reasoning, then a previous_response_id follow-up

Ran again at a70ae31022 with 2,368 and 2,752-character signatures

  1. Turn 1 answers 200 with a reasoning item
  2. Turn 2 sends previous_response_id and answers 200 with the first turn's reasoning in its input tokens
  3. Turn 3 continues from turn 2, streamed, and answers 200
Commands and output
$ jq -n --arg q 'Count the ordered triples (a, b, c) of positive integers with a*b*c = 720720 and a <= b <= c, and separately the ones with a < b < c. Check both counts with two independent methods before you answer, then reply with only the two numbers.' '{model: "claude-sonnet-5-5", max_output_tokens: 16000, reasoning: {effort: "high"},  input: [{role: "user", content: $q}]}' > text1.json
$ curl -s http://127.0.0.1:26417/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d @text1.json -o text1.out.json -w 'http=%{http_code}\n'
http=200
$ jq -c '{status, error: (.error.message // null | if . == null then null else tostring | .[0:150] end), in: .usage.input_tokens, cached: .usage.input_tokens_details.cached_tokens, out: .usage.output_tokens, types: [.output[]?.type], signature_chars: ([.output[]? | if .type=="reasoning" then (.encrypted_content // "" | fromjson? | .[]? | .signature? | length) elif .type=="function_call" then (.provider_specific_fields.thought_signature? // "" | length) else empty end] | max), answer: ([.output[]? | select(.type=="message") | .content[0].text] | first | tostring | .[0:50])}' text1.out.json
{"status":"completed","error":null,"in":88,"cached":0,"out":622,"types":["reasoning","message"],"signature_chars":2368,"answer":"**1218** (a ≤ b ≤ c) and **1212** (a < b < c)"}
$ jq -n --arg prev "$(jq -r .id text1.out.json)" '{model: "claude-sonnet-5-5", max_output_tokens: 16000, reasoning: {effort: "high"},  previous_response_id: $prev, input: [{role: "user", content: "Repeat what you answered, digits only."}]}' > text2.json
$ curl -s http://127.0.0.1:26417/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d @text2.json -o text2.out.json -w 'http=%{http_code}\n'
http=200
$ jq -c '{status, error: (.error.message // null | if . == null then null else tostring | .[0:150] end), in: .usage.input_tokens, cached: .usage.input_tokens_details.cached_tokens, out: .usage.output_tokens, types: [.output[]?.type], signature_chars: ([.output[]? | if .type=="reasoning" then (.encrypted_content // "" | fromjson? | .[]? | .signature? | length) elif .type=="function_call" then (.provider_specific_fields.thought_signature? // "" | length) else empty end] | max), answer: ([.output[]? | select(.type=="message") | .content[0].text] | first | tostring | .[0:50])}' text2.out.json
{"status":"completed","error":null,"in":727,"cached":0,"out":466,"types":["reasoning","message"],"signature_chars":2752,"answer":"1218 1212"}
$ jq -n --arg prev "$(jq -r .id text2.out.json)" '{model: "claude-sonnet-5-5", max_output_tokens: 16000, reasoning: {effort: "high"}, stream: true, previous_response_id: $prev, input: [{role: "user", content: "Repeat what you answered, digits only."}]}' > text3.json
$ curl -sN http://127.0.0.1:26417/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d @text3.json -o text3.sse -w 'http=%{http_code}\n'
http=200
$ { grep '^data: {' text3.sse | sed 's/^data: //' | jq -c 'select(.type=="response.completed") | .response'; grep -v '^data: ' text3.sse | grep '^{' ; } | head -1 > text3.out.json; jq -c '{status, error: (.error.message // null | if . == null then null else tostring | .[0:150] end), in: .usage.input_tokens, cached: .usage.input_tokens_details.cached_tokens, out: .usage.output_tokens, types: [.output[]?.type], signature_chars: ([.output[]? | if .type=="reasoning" then (.encrypted_content // "" | fromjson? | .[]? | .signature? | length) elif .type=="function_call" then (.provider_specific_fields.thought_signature? // "" | length) else empty end] | max), answer: ([.output[]? | select(.type=="message") | .content[0].text] | first | tostring | .[0:50])}' text3.out.json
{"status":"completed","error":null,"in":1210,"cached":0,"out":261,"types":["reasoning","message"],"signature_chars":1684,"answer":"1218 1212\n\nNote: I didn't actually run two truly i"}

Case 2: every route and turn shape

Results per route

Each cell lists a conversation's answers in order, with input tokens

Turns Claude Gemini Vertex Claude Vertex Gemini Bedrock Claude
question, follow-up, streamed third turn 200 (88), 200 (626), 200 (924) 200 (44), 200 (4022), 200 (4190) 200 (88), 200 (656), 200 (719) 200 (43), 200 (3805), 200 (3816) 200 (88), 200 (1308), 200 (1332)
streamed first turn 200 (88), 200 (799) 200 (44), 200 (4761) 200 (88), 200 (697) 200 (43), 200 (4710) 200 (88), 200 (730)
tool call, output, third turn 200 (466), 200 (1392), 200 (1418) 200 (102), 200 (5101), 200 (5255) 200 (466), 200 (1186), 200 (1211) 200 (81), 200 (5041), 200 (5110) 200 (466), 200 (1088), 200 (1114)
three calls, outputs, third turn 200 (488), 200 (1395), 200 (1421) 200 (117), 200 (12208), 200 (12511) 200 (488), 200 (1357), 200 (1383) 200 (96), 200 (7911), 200 (8253) 200 (488), 200 (1330), 200 (1356)
three calls, then calls sent again with outputs, twice, third turns 200 (488), 200 (1385), 200 (1411), 200 (1639), 200 (1663) 200 (117), 200 (15981), 200 (16333), 200 (31905), 200 (16575) 200 (488), 200 (1381), 200 (1407), 200 (1606), 200 (1630) 200 (96), 200 (10837), 200 (10891), 200 (21669), 200 (11003) 200 (488), 200 (1328), 200 (1353), 200 (1553), 200 (1633)
two calls with long arguments 200 (519), 200 (3724), 200 (6588) 200 (151), 200 (10896), 200 (11840) 200 (519), 200 (3825), 200 (4213) 200 (122), 200 (11899), 200 (10859) 200 (519), 200 (3696), 200 (6595)
history resent, no id 200 (626), 200 (840) 200 (847), 200 (1023) 200 (656), 200 (702) 200 (54), 200 (65) 200 (1308), 200 (1332)
history resent, then an id 200 (348) 200 (1094) 200 (180) 200 (1144) 200 (607)
first prompt over 2,048 characters 200 (2674), 200 (1468), 200 (1538) 200 (2506), 200 (6481), 200 (6779) 200 (2674), 400 200 (2505), 200 (5114), 200 (5155) 200 (2674), 200 (1480), 200 (1532)
Also seen, left alone by this PR
  • Vertex Claude still answers 400 after a cut long first prompt
  • Claude sees call arguments over 2,048 characters cut
  • Gemini image follow-ups still 400, image bytes cut
  • A second follow-up from one id replays the first
  • Gemini token counts 500 without the google-genai package
  • WebSocket follow-ups on a new socket lose the user turn
  • A list previous_response_id answers 500, not 400
  • A refused Claude thinking turn's follow-up answers 400
  • Vertex Claude 400s when stored arguments end mid-escape

Type

🐛 Bug Fix

Caveats (if any)

Severe

  • Operators who lowered MAX_STRING_LENGTH_PROMPT_IN_DB get bigger Responses rows served through chat completions, since signed fields stay whole up to 1 MiB
    • Setting MAX_STRING_LENGTH_PROVIDER_SIGNED_IN_DB to the same value keeps today's rows and today's 400s
    • At a 500-character limit a stored Claude response grew from 4,939 to 8,102 characters (sizes)
    • GCS Pub/Sub with gcs_pub_sub_use_v1 ships these rows too, unverified without Pub/Sub access

Medium

  • Gemini tool turns store each signature twice, making a three-call row 311,602 bytes, against 16,809 through chat completions
  • Follow-ups reread all session rows, tested to 5 turns
  • Follow-ups still answer 400 for Vertex Claude after a first prompt over 2,048 characters, Gemini arguments cut inside a JSON escape, and a turn 3 Claude tool output with message logging off
  • Claude, Bedrock Converse and signed-thinking turns replay call arguments over 2,048 characters cut

Low

  • Token redaction drops thinking that holds a token-like string
  • Replay warns per cut or redacted turn on every follow-up
  • The arguments rule reuses the misnamed target_refuses_blank_text
  • Golden recording skips records over 1 MiB
  • The env var's docs went live before the code ships
  • Bugbot did not review, since golden rows holding whole signatures make the diff 4.2 million characters (reply)

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

…onse_id replays it

The spend log writer cut every stored string over 2048 characters, which included Claude thinking
signatures and Gemini thought signatures. The bridge replays those rows for previous_response_id, so
the provider refused the follow-up with a 400

Response rows now keep every field a provider verifies whole, in both the Rust and Python writers.
Stored requests stay bounded. Replay leaves out signed reasoning that a stored row holds cut or
masked, so rows written before this change answer instead of failing
Message redaction leaves Gemini thought signatures, tool call ids that carry one and Responses
encrypted reasoning in the row. Keeping them whole let a follow-up recover content that redaction had
removed, so those rows keep the bound every other string has and replay leaves the cut state out
…d truncation marker

A pre-upgrade Gemini row holds its signature a second time inside the tool call id, so replay now trims
a cut id to the part before the signature. A stored string counts as cut only where the marker sits at
the cut point, so thinking that quotes the marker stays. A list-typed `type` in stored input no longer
stops the replay, and a tool result pairs by id prefix only when one side carries no signature
… signature is lost

Releases through v1.82.0-stable cut stored strings with a marker that has no safeguard note, and replay
did not recognize it, so follow-ups on those rows still answered 400. The warning also fired when only a
tool output's own id was trimmed, which loses nothing
A worker that still remembered a turn's tool calls put one assistant message per call in front of the
tool outputs, after the stored turn that already held them all. Claude refused the doubled calls with a
400, so a thinking turn with parallel calls could not be continued
…and leave marked calls alone

Dropping a repeated call lost the only whole copy of its arguments when the stored call held them cut or
redacted, so the kept call now takes them back. A turn with signed thinking keeps its stored arguments, so
every worker replays the same turn and the signature stays valid

A call the client marked with cache_control or other fields, a call with an empty id and a stored turn that
reuses an id are no longer dropped, and an id that lost its Gemini signature still matches its call

The marker with no safeguard note, from v1.77.3-stable through v1.82.0-stable, is now read only where a
stored value is checked, so the shared marker matches what this release writes
…n Claude continues the turn

A worker that remembered a call sent its whole arguments while a worker that did not sent the stored, cut
ones. Claude answers 400 when the content before its signed thinking changed, so the turn after could not
be continued on another worker. Claude and Bedrock Converse targets now always get what storage holds, as
they did before, and every other target gets the whole arguments
…orage cut them

The process remembers tool calls by id alone, so a call from another conversation with the same id could fill
in a stored empty argument object. A kept call now takes the whole arguments only when the function names match
and the stored text has the start, the end and the skipped count the writer would have cut from them

A resent call that carries more than the bare call no longer keeps the other repeats of its turn in the request,
and a continued request resolves the target's provider only when some arguments would change
…re and drop calls resent together

A resent call that carries text, reasoning or a cache mark becomes the nearest assistant message, so dropping
the bare repeats after it left their outputs with no call, and the request got an invented call to the first
declared tool. A repeat is now dropped only when the nearest kept assistant message still makes its call

A client that sends a turn's calls again in one block got every call twice, which Gemini, Claude with several
calls and strict OpenAI-compatible providers refuse with a 400. A block whose calls are all repeats is now
dropped, and a kept call takes its whole arguments back by what storage cut, whatever its function is named
…e the stored turn made once

A resent call counted as a repeat when its id only started like the stored one, so a call resent under another
signature was dropped, its output matched nothing, and the request got an invented call to the first declared
tool. A resent call is now the stored one only when the ids are equal, or when one of them lost its signature

A stored turn that makes one id twice is left as stored, since the repeat could be either call. Two ids that are
one without their signatures count as one id

Two annotations in the bridge change no behavior and keep the lint and type counts where they were
…the resent one

Calls resent after a system message are sent as before, the same as after a user or developer message, and only the
last two had a row. Two lists are also built without a second for clause
…re the stored ones

A call sent again under a stored id was dropped whatever it said, so an edited call never reached the model. It is
now dropped only when its tool and its JSON arguments are the stored ones, when storage cut the copy, or when the
stored call holds the redaction placeholder, which takes the resent arguments. A namespaced name is the same tool
as its bare name, and a custom tool input that storage cut is recognized inside its JSON wrapper

Each stored call is read once however many copies a turn sends, and stored text longer than any cut of the resent
arguments is skipped before the search for a cut
…nt calls with a place or no name

Main's lint rule flags a type variable declared Final, so the two in the replay module are bare here. The tests now
cover a call resent with its place in the turn, one resent without a name, an id reused after an empty turn, and a
copy whose signature is missing between calls signed otherwise. The timing test is gone because unit tests on main
must not depend on execution speed
@veria-ai

veria-ai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

Reviews

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@greptile-apps

greptile-apps Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5 · Fix the literal redaction-marker check before merging, because it can delete valid signed thinking during replay.RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The behavior changes reach Responses API follow-ups that replay spend-log history.

Fix the literal redaction-marker check before merging, because it can delete valid signed thinking during replay.

Findings

  1. P1 Valid thinking gets deleted ▶

Summary

This PR preserves provider-signed reasoning in stored Responses turns and cleans up replayed tool calls.

  • Responses follow-ups keep provider-signed fields whole in saved turns.
  • Follow-ups skip signed reasoning that storage changed.
  • Responses replays each unanswered tool call once.

The earlier tool-result finding was retracted. In the earlier storage-limit discussion, mateo-berri acknowledged larger rows as a trade-off awaiting owner sign-off, and Greptile withdrew the breaking-marker request.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Provider response] --> B{Responses through chat bridge?}
    B -->|Yes| C[Apply larger signed-field limit]
    B -->|No| D[Apply ordinary string limit]
    C --> E[Store spend row]
    D --> E
    E --> F[Follow-up with previous_response_id]
    F --> G[Remove altered signed state]
    G --> H[Remove repeated tool calls]
    H --> I[Match calls with tool outputs]
    I --> J[Send provider request]
Loading

Reviews (9) · Last reviewed commit: "chore: merge main into litellm_responses..." · Reviewed by Greptile

@codecov

codecov Bot commented Nov 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

…ep signed turns' stored arguments

Signed fields on Responses API spend rows are now kept up to 1 MiB instead of
whole, and chat and messages rows keep the 2,048 cut. Compaction blocks are
stored as before. A replayed turn made with signed thinking keeps the call
arguments storage holds, and the Rust row writer reports the same skipped
count as Python for a negative limit
…signed turns match on every pod

Claude checks a signed thinking block against the whole conversation before it.
A call replayed with the whole arguments one process remembers gave later turns
a history another pod rebuilds from the cut copy in storage, so a third turn on
another pod answered 400. Routes that build Anthropic Messages or Bedrock
Converse requests keep the stored arguments again, decided by the provider
config instead of the model name, and a turn made with signed thinking keeps
them on any route
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…v var names

The env-key docs check only sees literal os.getenv names, so passing the name into the helper hid MAX_STRING_LENGTH_PROMPT_IN_DB and MAX_STRING_LENGTH_PROVIDER_SIGNED_IN_DB from it
@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 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

This PR is too large for Bugbot to review. It changes 1,361 lines and 4,180,891 characters. Split the change into smaller pull requests to get a review.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

1 similar comment
@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

Pass the provider-signed limit to the Rust row builder again after BerriAI#53599 spelled out its arguments, and record BerriAI#53405's two new golden rows with that config key
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

1 similar comment
@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

1 similar comment
@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai



def _is_altered_text(value: object) -> bool:
return isinstance(value, str) and (was_truncated_for_db(value) or REDACTED_BY_LITELM_STRING in value)

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.

P1 Valid thinking gets deleted

_is_altered_text treats a literal REDACTED_BY_LITELM in signed thinking as proof that storage changed it. A model discussing LiteLLM logs can return that text with a valid signature, even with token redaction off. Storage keeps the block intact, but the next previous_response_id replay deletes it. This loses valid reasoning and can break Claude tool-result turns.

Record whether storage actually changed the signed field instead of relying on this substring alone.

Knowledge Base Used: Restore signed thinking blocks and binding errors

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.

This is rare, since it needs the internal marker inside signed reasoning. The merge did not touch this file, so we will weigh it separately

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.

Agreed that this is rare and should be weighed separately from the merge. The merge not changing this file leaves the behavior unchanged; the concern is still a real edge case: at provider_signed_state.py:43, any signed field containing the marker is classified as altered, and replay can then drop an otherwise-valid thinking block even when token redaction did not insert it. I’d treat it as a low-priority correctness issue, not a blocker; recording actual storage alteration would avoid the false positive.

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

1 similar comment
@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

This branch has not been deployed

No deployments
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]: Gemini /v1/responses previous_response_id replays malformed thought_signature and returns TYPE_BYTES Base64 400 without tools

2 participants