Skip to content

fix(responses): keep reasoning item IDs consistent across streaming events - #51243

Merged
joshua-berri merged 4 commits into
mainfrom
litellm_fix_responses_reasoning_identity_47881
Nov 11, 2026
Merged

joshua-berri merged 4 commits into
mainfrom
litellm_fix_responses_reasoning_identity_47881

Conversation

@joshua-berri

@joshua-berri joshua-berri commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

  • Keeps reasoning item IDs consistent across streaming events and completed responses, preventing duplicate entries in clients that track items by ID
  • Preserves encrypted-content routing and existing item-reference compatibility across HTTP, WebSocket, completion bridges, and Rust handling
  • Adds regression tests and verified before/after flows
Details

TLDR

Problem this solves:

  • One reasoning item appeared under two different IDs
  • ID-keyed clients stored and replayed both copies

How it solves it:

  • Encode reasoning IDs from the first streamed event
  • Encode item references on reasoning delta events consistently
  • Share encoding across HTTP, WebSocket and completions bridges
  • Keep Rust response encoding compatible with Python

Intentional product change: With encrypted-content affinity enabled, reasoning and compaction items carry encoded IDs before ciphertext arrives, including items returned without ciphertext. This keeps event correlation and ID-only deployment affinity consistent

User Flow

Before, the client stores two copies of one reasoning item

  1. Enable encrypted-content affinity and send POST http://localhost:4882/v1/responses with streaming and encrypted reasoning enabled
  2. Observe raw rs_ IDs on item events and encitem_ IDs in the completed response
  3. Merge output by ID and replay the two stored items on the next turn
  4. The duplicate-rejecting fixture returns HTTP 400, while the current live OpenAI provider accepts both copies

After, the client stores one reasoning item

  1. Enable encrypted-content affinity and send POST http://localhost:4881/v1/responses with streaming and encrypted reasoning enabled
  2. Observe one matching encitem_ ID on item events, reasoning deltas and the completed response
  3. Merge output by ID and replay the one stored item on the next turn
  4. The duplicate-rejecting fixture and current live OpenAI provider return HTTP 200

Relevant issues

Fixes #47881

Pre-Submission checklist

  • I have added meaningful tests
  • Affected tests and callers passed on Devin at the exact source commit, following the requested remote verification workflow
  • My PR passes all applicable CI/CD checks
  • My PR's scope is isolated to reasoning item identity and compatibility
  • Every automated review on the latest commit has finished and actionable findings are resolved

Screenshots / Proof of Fix

Baseline deb7697a8e515671774b3ccda6dd6d67123e41cc, head 8e536f868b7298e8b457d7f98bce7ebfccfc696f

Independent Devin verification used source checkouts at both SHAs, two proxy workers and dedicated Redis instances. Both runs logged two started worker processes, with no reload worker-count exception. No tracked source was changed by the verifier

Before (deb7697)

HTTP and completions bridge

  1. Run the client below against the baseline proxy on port 4882, with its Redis configuration using port 6882
  2. The live HTTP stream reports raw IDs on added, summary and done events, then an encoded ID for the same item in the completed response
  3. The ID-keyed store contains two reasoning items. The live provider returns 200, while the same ID-keyed client against the issue's duplicate-rejecting upstream fixture returns 400
output_item.added / reasoning_summary_* / output_item.done: rs_
response.completed: encitem_
distinct ids: 2
id-keyed store size: 2
live turn 2 HTTP: 200
fixture upstream ids: ['rs_fixture123', 'rs_fixture123']
fixture turn 2 HTTP: 400

WebSocket

With the baseline source proxy serving port 4882, run the complete live_ws_two_turn.py client embedded below

PROXY_URL=http://127.0.0.1:4882 python live_ws_two_turn.py ws-baseline gpt-reasoning

Observed output, with variable IDs truncated

WS T1 added id: rs_
WS T1 item-scoped ids: rs_
WS T1 done id: rs_
WS T1 completed ids: encitem_
WS id-keyed store size: 2 distinct ids: ['enc', 'rs']
WS T2 outcome: completed

After (8e536f8)

HTTP and completions bridge

  1. Run the same client against the head proxy on port 4881, with Redis port 6881
  2. Added, summary, done and completed events all carry the same encoded ID
  3. The ID-keyed store contains one reasoning item. The live provider and duplicate-rejecting fixture both return 200
output_item.added / reasoning_summary_* / output_item.done / response.completed: encitem_
distinct ids: 1
id-keyed store size: 1
live turn 2 HTTP: 200
fixture upstream ids: ['rs_fixture123']
fixture turn 2 HTTP: 200

WebSocket

With source commit 8e536f868b7298e8b457d7f98bce7ebfccfc696f serving port 4881, run the same client

PROXY_URL=http://127.0.0.1:4881 python live_ws_two_turn.py ws-head gpt-reasoning

Observed output, with variable IDs truncated

WS T1 added id: encitem_
WS T1 item-scoped ids: encitem_
WS T1 done id: encitem_
WS T1 completed ids: encitem_
WS id-keyed store size: 1 distinct ids: ['enc']
WS T2 outcome: completed

The live Anthropic completions bridge and WebSocket path show the same two-IDs-to-one-ID change. Six ID-only replay requests remained pinned to the originating deployment at both SHAs. Non-streaming output still carries encoded IDs. Ciphertext can differ between provider events, so identity comparisons use IDs

Executed HTTP and bridge verification client and configuration

Set OPENAI_API_KEY, ANTHROPIC_API_KEY, LITELLM_MASTER_KEY, LITELLM_SALT_KEY and DATABASE_URL in the environment. Install the frozen proxy-dev and e2e-dev environment and rebuild the source package for each tested SHA

Save this as config_47881.yaml. The baseline run used the same model configuration with Redis port 6882

model_list:
  - model_name: gpt-reasoning
    litellm_params: {model: openai/gpt-5.6, api_key: os.environ/OPENAI_API_KEY, api_base: https://api.openai.com/v1}
    model_info: {id: dep-a-47881}
  - model_name: gpt-reasoning
    litellm_params: {model: openai/gpt-5.6, api_key: os.environ/OPENAI_API_KEY, api_base: https://api.openai.com/v1}
    model_info: {id: dep-b-47881}
  - model_name: claude-bridge
    litellm_params: {model: anthropic/claude-opus-5-5, api_key: os.environ/ANTHROPIC_API_KEY, use_chat_completions_api: true}
    model_info: {id: dep-bridge-47881}
router_settings:
  optional_pre_call_checks: ["encrypted_content_affinity"]
  redis_host: 127.0.0.1
  redis_port: 6881
general_settings:
  coordination_redis: {host: 127.0.0.1, port: 6881}
  master_key: os.environ/LITELLM_MASTER_KEY
litellm_settings:
  drop_params: true

redis-server --port 6881 --save "" --appendonly no --daemonize yes
LITELLM_LOCAL_MODEL_COST_MAP=True python litellm/proxy/proxy_cli.py --config config_47881.yaml --port 4881 --num_workers 2 --detailed_debug --reload --use_v2_migration_resolver

Save the exact executed client below as compact_verify.py. Run PROXY_URL=http://127.0.0.1:4881 python compact_verify.py gpt-reasoning and repeat with claude-bridge. For the baseline, use its port 4882

"""Compact #47881 check. Env: PROXY_URL, LITELLM_MASTER_KEY. Usage: python compact_verify.py <model>
T1 streamed Responses -> ids seen at output_item.added / reasoning_summary_* / output_item.done / response.completed,
then T2 replays an id-keyed store (one input item per distinct id) and reports its size and HTTP status."""
import json, os, sys, httpx
P, H = os.environ["PROXY_URL"].rstrip("/"), {"Authorization": f"Bearer {os.environ['LITELLM_MASTER_KEY']}"}
base = {"model": sys.argv[1], "store": False, "include": ["reasoning.encrypted_content"],
        "reasoning": {"effort": "high", "summary": "auto"}, "max_output_tokens": 1500}
q = "A farmer has 17 sheep; all but 9 run away. Then he buys twice as many as remain. Reason carefully and answer."
ids, items = {}, []
with httpx.stream("POST", f"{P}/v1/responses", json={**base, "stream": True, "input": q}, headers=H, timeout=180) as r:
    for line in r.iter_lines():
        if not line.startswith("data:"):
            continue
        ev = json.loads(line[5:])
        t, item = ev.get("type", ""), ev.get("item") or {}
        if t in ("response.output_item.added", "response.output_item.done") and item.get("type") == "reasoning":
            ids.setdefault(t, set()).add(item["id"]); items.append(item)
        elif t.startswith("response.reasoning_summary"):
            ids.setdefault("reasoning_summary_*", set()).add(ev["item_id"])
        elif t == "response.completed":
            for o in ev["response"]["output"]:
                if o["type"] == "reasoning":
                    ids.setdefault(t, set()).add(o["id"]); items.append(o)
kind = lambda i: "encitem_" if i.startswith("encitem_") else "rs_"
print({k: sorted({kind(i) for i in v}) for k, v in ids.items()}, "distinct ids:", len({i["id"] for i in items}))
store = {i["id"]: i for i in items}  # id-keyed client store
t2 = httpx.post(f"{P}/v1/responses", headers=H, timeout=180,
                json={**base, "input": [*store.values(), {"role": "user", "content": "Reply with just the final number."}]})
print("id-keyed store size:", len(store), "T2 HTTP:", t2.status_code, (t2.text[:160] if t2.status_code != 200 else ""))
Executed WebSocket and item-reference clients

Executed scripts, verbatim (only env var names; the scripts print id prefixes only, no ciphertext). Both ran unchanged at baseline (:4882) and head 8e536f8 (:4881).

live_ws_two_turn.py (run: PROXY_URL=http://127.0.0.1:4881 python live_ws_two_turn.py <outdir> gpt-reasoning):

"""Responses WebSocket two-turn id-correlation client. env: PROXY_URL, LITELLM_MASTER_KEY. argv: <outdir> [model]"""
import asyncio, json, os, sys
import websockets

PROXY = os.environ.get("PROXY_URL", "http://127.0.0.1:4881").replace("http", "ws", 1)
MODEL = sys.argv[2] if len(sys.argv) > 2 else "gpt-reasoning"
OUT = sys.argv[1]
os.makedirs(OUT, exist_ok=True)
PROMPT = os.environ.get("WS_PROMPT", "A farmer has 17 sheep; all but 9 run away. Then he buys twice as many as remain. Reason carefully and answer.")
BASE = {"store": False, "include": ["reasoning.encrypted_content"], "reasoning": {"effort": "high", "summary": "auto"}, "max_output_tokens": 1500}


def kind(i):
    return "enc" if i.startswith("encitem_") else ("rs" if i.startswith("rs_") else "other")


async def turn(ws, inp, tag):
    await ws.send(json.dumps({"type": "response.create", "input": inp, **BASE}))
    events, items = [], {}
    while True:
        ev = json.loads(await ws.recv())
        events.append(ev)
        t = ev.get("type", "")
        if t in ("response.output_item.added", "response.output_item.done") and ev["item"].get("type") == "reasoning":
            items[t] = ev["item"]
        if t.startswith("response.reasoning") and ev.get("item_id"):
            items.setdefault("item_scoped_ids", set()).add(ev["item_id"])
        if t == "response.completed":
            items["completed"] = [o for o in ev["response"]["output"] if o.get("type") == "reasoning"]
            break
        if t in ("error", "response.failed", "response.incomplete"):
            items["error"] = ev
            break
    json.dump(events, open(f"{OUT}/{tag}_events.json", "w"), default=list, indent=1)
    return items


async def main():
    hdr = {"Authorization": f"Bearer {os.environ['LITELLM_MASTER_KEY']}"}
    async with websockets.connect(f"{PROXY}/v1/responses?model={MODEL}", additional_headers=hdr, max_size=None) as ws:
        t1 = await turn(ws, [{"role": "user", "content": PROMPT}], "t1")
        if "error" in t1:
            print("T1 error:", json.dumps(t1["error"])[:300]); return
        added, done, completed = t1.get("response.output_item.added"), t1.get("response.output_item.done"), t1["completed"]
        scoped = sorted(t1.get("item_scoped_ids", set()))
        print("WS T1 added id      :", added and (kind(added["id"]), added["id"][:30]), "enc_content_at_added:", bool(added and added.get("encrypted_content")))
        print("WS T1 item-scoped ids:", [(kind(i), i[:30]) for i in scoped])
        print("WS T1 done id       :", done and (kind(done["id"]), done["id"][:30]))
        print("WS T1 completed ids :", [(kind(o["id"]), o["id"][:30]) for o in completed])
        streamed = [i for i in (added, done) if i]
        keyed = {i["id"]: i for i in (*streamed, *completed)}
        print("WS id-keyed store size:", len(keyed), "distinct ids:", sorted({kind(k) for k in keyed}))
        replay = [{k: v for k, v in it.items() if k in ("type", "id", "summary", "encrypted_content")} for it in keyed.values()]
        hist = [{"role": "user", "content": PROMPT}, *replay, {"role": "user", "content": "Now add 1 to that."}]
        t2 = await turn(ws, hist, "t2")
        if "error" in t2:
            print("WS T2 outcome: error", json.dumps(t2["error"])[:400])
        else:
            print("WS T2 outcome: completed, reasoning ids:", [(kind(o["id"]), o["id"][:30]) for o in t2["completed"]], "done==completed:",
                  t2.get("response.output_item.done", {}).get("id") == (t2["completed"][0]["id"] if t2["completed"] else None))

asyncio.run(main())

Output baseline | head:

WS T1 added id      : ('rs', 'rs_02c3…') enc_content_at_added: True  |  ('enc', 'encitem_bGl0…') enc_content_at_added: True
WS T1 item-scoped ids: [('rs', …)]   |  [('enc', …)]
WS T1 done id       : ('rs', …)      |  ('enc', …)
WS T1 completed ids : [('enc', …)]   |  [('enc', …)]
WS id-keyed store size: 2 distinct ids: ['enc', 'rs']  |  1 distinct ids: ['enc']
WS T2 outcome: completed  |  completed

live_item_reference.py (run: PROXY_URL=... LITELLM_MASTER_KEY=... REPS=6 python live_item_reference.py gpt-reasoning <outdir>):

"""Does item_reference-only input (id, no encrypted_content) pin the deployment?
Env: PROXY_URL, LITELLM_MASTER_KEY. Args: <proxy model alias> <out dir>.
Turn 1 is a streamed Responses call with store=true so the provider can resolve item_reference later.
Each replay variant is repeated N times and the serving deployment (x-litellm-model-id) is recorded."""
import json, os, sys, uuid, httpx

PROXY = os.environ["PROXY_URL"].rstrip("/")
KEY = os.environ["LITELLM_MASTER_KEY"]
MODEL = sys.argv[1]
OUT = sys.argv[2]
N = int(os.environ.get("REPS", "6"))
os.makedirs(OUT, exist_ok=True)
H = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}
BASE = {"model": MODEL, "store": True, "include": ["reasoning.encrypted_content"],
        "reasoning": {"effort": "high", "summary": "auto"}, "max_output_tokens": 1500}
NONCE = uuid.uuid4().hex[:8]
MID_HDR = "x-litellm-model-id"


def post(body, stream=False):
    with httpx.Client(timeout=180) as c:
        r = c.post(f"{PROXY}/v1/responses", headers=H, json=body)
    return r


def san(s):
    return s[:40] + "..." if isinstance(s, str) and len(s) > 40 else s


t1 = post({**BASE, "stream": True, "input": f"[{NONCE}] How many r letters are in strawberry and in raspberry? Think it through carefully, then answer in one line."})
events = [json.loads(l[6:]) for l in t1.text.splitlines() if l.startswith("data: ") and l[6:].strip() not in ("", "[DONE]")]
from collections import Counter
print("turn1 http", t1.status_code, dict(Counter(e.get("type") for e in events)))
if t1.status_code != 200 or not events:
    print(t1.text[:1500]); sys.exit(2)
done_items = [e["item"] for e in events if e.get("type") == "response.output_item.done" and e["item"].get("type") == "reasoning"]
completed = next(e for e in events if e.get("type") == "response.completed")["response"]
comp_reasoning = [o for o in completed["output"] if o.get("type") == "reasoning"]
t1_info = {
    "http": t1.status_code, "model_id_header": t1.headers.get(MID_HDR),
    "response_id": completed["id"], "done_reasoning_id": done_items[0]["id"], "completed_reasoning_id": comp_reasoning[0]["id"],
    "done_has_encrypted_content": "encrypted_content" in done_items[0] and bool(done_items[0]["encrypted_content"]),
}
print("turn1:", json.dumps({k: san(v) if k != "http" else v for k, v in t1_info.items()}))
json.dump(t1_info, open(f"{OUT}/turn1.json", "w"), indent=1)
RAW_ID = t1_info["done_reasoning_id"]
ENC_ID = t1_info["completed_reasoning_id"]
RESP_ID = t1_info["response_id"]
FOLLOW = f"[{NONCE}] Now in one short sentence, why are sunsets red?"


def ref(i):
    return {"type": "item_reference", "id": i}


VARIANTS = {
    "R0_control_no_markers": {"input": FOLLOW},
    "R1_itemref_encitem_id_no_prev": {"input": [ref(ENC_ID), {"role": "user", "content": FOLLOW}]},
    "R2_itemref_raw_rs_id_no_prev": {"input": [ref(RAW_ID), {"role": "user", "content": FOLLOW}]},
    "R3_itemref_encitem_id_with_prev": {"input": [ref(ENC_ID), {"role": "user", "content": FOLLOW}], "previous_response_id": RESP_ID},
    "R4_itemref_raw_rs_id_with_prev": {"input": [ref(RAW_ID), {"role": "user", "content": FOLLOW}], "previous_response_id": RESP_ID},
    "R5_prev_only_plain_input": {"input": FOLLOW, "previous_response_id": RESP_ID},
}
results = {"turn1": t1_info, "variants": {}}
for name, extra in VARIANTS.items():
    runs = []
    for _ in range(N):
        r = post({**BASE, "stream": False, **extra})
        err = None
        if r.status_code != 200:
            try:
                err = r.json()
            except Exception:
                err = r.text[:300]
        runs.append({"http": r.status_code, "model_id": r.headers.get(MID_HDR), "error": san(json.dumps(err)) if err else None})
    mids = sorted({x["model_id"] for x in runs})
    codes = sorted({x["http"] for x in runs})
    results["variants"][name] = {"request_shape": {k: (v if k != "input" else ("<str>" if isinstance(v, str) else [san(x.get("id")) if x.get("type") == "item_reference" else "<user msg>" for x in v])) for k, v in extra.items()},
                                 "runs": runs, "distinct_model_ids": mids, "http_codes": codes,
                                 "pinned_to_turn1": mids == [t1_info["model_id_header"]]}
    print(f"{name}: http={codes} model_ids={mids} pinned_to_turn1={results['variants'][name]['pinned_to_turn1']} first_error={runs[0]['error']}")
json.dump(results, open(f"{OUT}/report.json", "w"), indent=1)

Head output (RAW_ID is the done id, which is encitem_ at head so R2/R4 equal R1/R3; at baseline R2 was raw rs_ and not pinned):

R0_control_no_markers: http=[200] model_ids=['dep-a-47881', 'dep-b-47881'] pinned_to_turn1=False
R1_itemref_encitem_id_no_prev: http=[200] model_ids=['dep-a-47881'] pinned_to_turn1=True
R2_itemref_raw_rs_id_no_prev: http=[200] model_ids=['dep-a-47881'] pinned_to_turn1=True
R3_itemref_encitem_id_with_prev: http=[400] model_ids=['dep-a-47881'] pinned_to_turn1=True   # provider "Duplicate item"
R4_itemref_raw_rs_id_with_prev: http=[400] model_ids=['dep-a-47881'] pinned_to_turn1=True
R5_prev_only_plain_input: http=[200] model_ids=['dep-a-47881', 'dep-b-47881'] pinned_to_turn1=False

Bridge: live_bridge_rust.py claude-bridge <outdir> both is the same request body as compact_verify.py with model: claude-bridge, recording added/done/scoped/completed reasoning ids and encrypted_content presence.

Regression checks

At head, the four changed unit files pass 630 tests. Running those head tests against baseline source produces eight failures in the new identity and affinity regressions, with 622 passing

pytest tests/unit/responses/test_streaming_iterator.py tests/unit/responses/test_responses_websocket_all_providers.py tests/unit/responses/litellm_completion_transformation/test_streaming_iterator_transformation.py tests/unit/router_utils/pre_call_checks/test_encrypted_content_affinity_check.py
pytest tests/unit/responses tests/unit/rust_bridge/test_detectors.py tests/unit/proxy/response_api_endpoints tests/unit/router_utils/pre_call_checks
cd litellm-rust && cargo test -p litellm-inference-responses

The broader caller selection passes 3,100 tests, and the Rust crate passes 80 tests. Canonical source/test Ruff, formatting, strict-rule, type-discipline, test-quality, OpenAPI docs and basedpyright budget gates all pass against the merge base in the frozen remote environment

Python changed executable-line coverage is 77/77, or 100%, with no uncovered branches originating on changed lines. New and changed utility functions are fully branch-covered. The larger existing _process_chunk and _wrap_response_event functions retain unchanged uncovered branches, at 81.8% and 84.6% branch coverage respectively. These numbers are distinct from repository-wide coverage. The current-tip unit workflow passed all 56 jobs. Codecov reports all modified coverable lines covered in its PR report

Rust instrumented coverage at the same head hits 11/11 changed executable lines and all 27 LLVM regions on those lines. The affected file has 241/248 lines covered, with seven pre-existing misses. The instrumented crate run passes 80 tests. Stable Rust 1.98.0 rejects the nightly-only branch instrumentation flag, so Rust branch-counter coverage is unavailable and is not reported as passing

rustup component add llvm-tools
cargo install cargo-llvm-cov --version 0.9.1 --locked
cd litellm-rust
cargo llvm-cov -p litellm-inference-responses --no-report
cargo llvm-cov report -p litellm-inference-responses --lcov --output-path lcov.info

Type

Bug Fix

Caveats

Medium

  • Existing histories with duplicate records are not deduplicated
  • CI is complete at 8e536f868b7298e8b457d7f98bce7ebfccfc696f, with 121 checks passed and five integration suites failed. All 56 unit jobs passed. Seven integration suites passed, while five suites contain 11 unrelated failures, classified using logs, source inspection and the paired execution results below
  • SDK failed waiting for router re-indexing before the reader starts. Management and management-replica each failed one offline build with missing cached maturin and two launcher child-command checks. Providers failed on an extra total_spend field in the unchanged auto-router session response. Extensions failed chat guardrail finish_reason, S3 chat-log delivery, and OTEL chat attribute-shedding assertions. None exercises the changed Responses handling
  • Full integration results and logs remain failed and are outside this ticket under the scope rule. No checks or branch protection were waived
  • Codecov reports all modified coverable lines covered and is advisory for this workflow

Greptile reviewed 8e536f868b7298e8b457d7f98bce7ebfccfc696f with confidence 5/5 and no findings after the WebSocket proof was added. Cursor Bugbot and Veria completed with no new issues on the same commit. The addressed WebSocket proof thread is resolved

Low

  • Current OpenAI accepts duplicates that the fixture rejects
  • Rust-served Responses is unavailable at these SHAs by design
  • Baseline and head retain existing Python test warnings
  • Rust branch counters require a compiler outside the pinned toolchain

Integration failure comparison

The focused comparison ran the eight unique cases behind the 11 CI failures. The three configuration cases ran in both management modes. Direct baseline deb7697a8e515671774b3ccda6dd6d67123e41cc and PR head 8e536f868b7298e8b457d7f98bce7ebfccfc696f produced identical results, six failed and five passed across the 11 executions. No candidate-only failure was observed

CI failure Baseline versus PR head Attribution evidence
Launcher child-command checks, four failures across two modes Same failures on both Expected child command list, observed empty list
Router concurrent upsert, one failure Same failure on both Re-indexing wait exceeded 10 seconds
Auto-router session, one failure Same failure on both Extra total_spend field rejected by unchanged assertion
Offline OpenAPI build, two failures Passed on both CI log explicitly reports uncached maturin==1.15.0 with networking disabled. Devin cache contains it
Chat guardrail finish reason, one failure Passed on direct baseline and head. Failed on both exact CI main-parent and merge Newer main copies finish_reason in ModelResponseIterator, producing content_filter where test expects stop
S3 delivery, one failure Passed on both CI timeout was not reproduced. Remains a CI-only failure in unchanged chat logging behavior
OTEL attribute shedding, one failure Passed on both CI assertion was not reproduced. Remains a CI-only failure in unchanged chat telemetry behavior

CI tested merge e0126e01d4c7b52ba11ef38563c990b07960017a, whose parents are main b63656a5de6a95487d2f4826e2cbe4cccca0d02e and the PR head. The merge diff against its main parent contains exactly this PR's eight files. The guardrail case failed with assert 'content_filter' == 'stop' on both that main parent and merge

Both direct commits used native extensions built from their matching source. The additional main-parent and merge runs reused the corresponding extensions only after verifying identical Rust trees. Commands used tests/integration/run.py <group> --results <directory> <exact node IDs> with the canonical integration environment and suite worker counts. Suites were limited to the failing cases, with no source edits or test weakening

The paired environment used PostgreSQL 14 and Redis 8.10, while CI used PostgreSQL 16 and Redis 7. It did not apply CI's egress iptables guard. These differences limit conclusions about CI-only timing and telemetry failures. Seven failed CI executions were reproduced without this PR, two are explicit missing-cache failures, and two did not reproduce in either paired run. This supports the unrelated classification but does not claim every CI failure was reproduced on baseline

Integration comparison commands

Run in each source checkout after provisioning the disposable integration database and matching native extension. Database passwords below are the test harness defaults, not production credentials

cd <checkout>; export PATH=$PWD/.venv/bin:$PATH PYTHONPATH=$PWD:$PWD/tests:$PWD/tests/e2e
export DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:5432/circle_test REDIS_HOST=127.0.0.1 REDIS_PORT=6379
export LITELLM_MASTER_KEY=sk-$(openssl rand -hex 16) LITELLM_SALT_KEY=sk-integration-salt LITELLM_MODE=PRODUCTION
export LITELLM_LOCAL_MODEL_COST_MAP=True STORE_MODEL_IN_DB=True AWS_EC2_METADATA_DISABLED=true DO_NOT_TRACK=1 UV_OFFLINE=true
export INTEGRATION_SEED=4106601 INTEGRATION_ORDER_SEED=4106601 LITELLM_UI_PATH=$PWD/litellm/proxy/_experimental/out
python -m prisma generate --schema litellm/proxy/schema.prisma
R=tests/integration/run.py
INTEGRATION_WORKERS=2 python $R management --results out/management \
  tests/integration/configuration/test_openapi_docs_gate.py::test_base_counts_imports_native_extension_from_detached_worktree \
  "tests/integration/configuration/test_rust_forward.py::test_the_python_child_is_started_with_the_supervisors_own_command[LITELLM]" \
  "tests/integration/configuration/test_rust_forward.py::test_the_python_child_is_started_with_the_supervisors_own_command[GATEWAY]"
INTEGRATION_WORKERS=1 python $R sdk --results out/sdk \
  tests/integration/sdk/test_router_concurrent_deployment_delete_sdk.py::test_completion_reaches_its_deployment_while_another_thread_upserts_an_earlier_one
INTEGRATION_WORKERS=4 python $R providers --results out/providers \
  tests/integration/routing/test_auto_router_management.py::test_auto_router_session_tracks_key_scoped_spend_and_bounds_long_session_ids
INTEGRATION_WORKERS=4 python $R extensions --results out/extensions \
  tests/integration/observability/test_guardrail_effects.py::test_chat_pre_call_denial_streams_content_filter \
  tests/integration/observability/test_s3_v2_upload_fanout.py::test_s3_v2_slow_sink_ramps_concurrency_and_drains_the_backlog \
  tests/integration/observability/test_langfuse_otel_metadata_destinations.py::test_otel_v2_langfuse_identity_sheds_before_any_message_attribute
# replica repeat of the 3 configuration cases (CI management-replica):
python .circleci/scripts/prepare_replica_roles.py
INTEGRATION_PROXY_DATABASE_URL=postgresql://litellm_writer:litellm-writer@127.0.0.1:5432/circle_test \
INTEGRATION_PROXY_READ_REPLICA_URL=postgresql://litellm_reader:litellm-reader@127.0.0.1:5432/circle_test \
INTEGRATION_WORKERS=2 python $R management --results out/management-replica <same 3 configuration node IDs>

Final Attestation

  • The tests check the intended behavior and edge cases. Current-tip verification and reviews are complete, with the unrelated CI failures and Rust branch-instrumentation limitation disclosed above

@veria-ai

veria-ai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review

@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@veria-ai Please review 8e536f8 for consistent reasoning item IDs across streaming, WebSocket, and bridge responses, including deployment affinity compatibility

@greptile-apps

greptile-apps Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

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

Summary

This PR keeps reasoning item IDs consistent across streamed events and completed Responses output.

  • Reasoning items keep one ID across streamed Responses events.

Reviews (2) · Last reviewed commit: "fix(responses): use immutable affinity i..." · Reviewed by Greptile

Comment thread litellm/responses/streaming_iterator.py Resolved

@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 8e536f8. Configure here.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review

@codspeed

codspeed Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 2 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 43 untouched benchmarks


Comparing litellm_fix_responses_reasoning_identity_47881 (8e536f8) with main (b63656a)

Open in CodSpeed

@codecov

codecov Bot commented Nov 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@joshua-berri
joshua-berri merged commit 82471d4 into main Nov 11, 2026
132 of 138 checks passed
@joshua-berri
joshua-berri deleted the litellm_fix_responses_reasoning_identity_47881 branch November 11, 2026 23:49

This branch was previously deployed

1 inactive deployment
integration-license — 8e536f86 Deployed Nov 11, 2026 by joshua-berri via integration cost #178
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: encrypted_content_affinity gives one streamed Responses item two IDs, so clients replay duplicate reasoning items

2 participants