Skip to content

fix(agents): send session_id affinity header to ChatGPT Responses backend - #100233

Merged
obviyus merged 3 commits into
openclaw:mainfrom
Marvinthebored:fix/responses-session-affinity-header
Jul 7, 2026
Merged

obviyus merged 3 commits into
openclaw:mainfrom
Marvinthebored:fix/responses-session-affinity-header

Conversation

@Marvinthebored

@Marvinthebored Marvinthebored commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #100232

Problem

The agent-runtime OpenAI Responses transport (createOpenAIResponsesClient →
buildOpenAIClientHeaders) never sends a session_id header. The ChatGPT backend
(chatgpt.com/backend-api) routes requests by session_id — codex-cli sends it on every
request (thread id), and OpenClaw's own SSE/WS provider path (openai-chatgpt-responses.ts)
already sets it. Without it, each HTTP request from a session can land on a different
backend machine, whose local prompt cache doesn't hold the session's prefix.

Observed on live traffic (gpt-5.5, ChatGPT OAuth): cold-write streaks and interleaved cache
lineages
— cached_tokens alternating between two values (e.g. ~28k and ~57k) across
consecutive turns of one session, i.e. two machines each holding a different partial prefix.
Aggregate TRUE cache hit rate ~47-56% vs codex-cli's ~92-96% on the same account/model.

Fix

buildOpenAIClientHeaders() takes an optional sessionId; when
usesNativeOpenAICodexResponsesBackend(model) and no session_id was set by
caller/turn headers (caller-wins preserved), it adds session_id: <sessionId>. Threaded
from options?.sessionId at the single Responses-client call site. Scoped strictly to the
native ChatGPT/Codex backend — api.openai.com and proxy endpoints are untouched.

Measurements (12 identical prompts per leg, fresh session each, same account/hour)

Config TRUE hit% = cache_read/(cache_read+input)
stock 56.0%
+ this fix (as a dist hot-patch) 81.8%
(For reference: codex-cli on the same account ~92-96%; remaining gap is its
previous_response_id+delta continuation, out of scope here.)

A separate controlled A/B (identical tool-call sequences, same session shape) comparing
stock vs. the combined local fix set measured 45.9% → 92.0% TRUE hit rate — 6.5x fewer
uncached input tokens for identical work (stock session 3017333e: 466,088 uncached input
tokens; fixed session b97d343e: 71,478). This isolates the session_id header's own
contribution (56.0% → 81.8%, table above) from an additional byte-stable-prefix fix tracked
separately in a follow-up PR.

Also adds a NOTE comment (no behavior change) at the WS websocketRequestId fallback in
openai-chatgpt-responses.ts, which mints a fresh random id per request when
options.sessionId is absent — forfeiting affinity on that transport; worth a follow-up.

Tests

4 unit tests: header present iff native backend + sessionId; absent without sessionId;
absent for openai-responses/api.openai.com; caller-supplied session_id not overwritten.
Typecheck (run-tsgo.mjs -p tsconfig.core.json) clean. (Vitest currently fails to launch
on this dev box for unrelated toolchain reasons — rolldown native binding; tests were
written against the existing patterns in openai-transport-stream.test.ts.)

Reported-by: @Peetiegonzalez
cc: @Peetiegonzalez

What Problem This Solves

The ChatGPT Responses backend (chatgpt.com/backend-api) routes HTTP requests by session_id.
buildOpenAIClientHeaders() never sent one, so consecutive requests from the same OpenClaw
session could land on different backend machines, each holding a different partial prompt-cache
prefix — visible as interleaved cache lineages and cold-write streaks on live traffic. codex-cli
(external reference client) and OpenClaw's own WS/SSE path already send this header; only the
HTTP Responses transport used by the openclaw agent runtime was missing it. See "Problem" above
for the full mechanism and code path.

Evidence

Measured, not estimated: 12 identical prompts per leg, fresh session each, same account and same
hour, ChatGPT-OAuth gpt-5.5, TRUE hit% = cache_read / (cache_read + input) computed from each
call's provider usage fields.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jul 5, 2026
@clawsweeper

clawsweeper Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 6, 2026, 11:05 PM ET / 03:05 UTC.

Summary
Threads options.sessionId into native ChatGPT Responses header construction, adds a generated session_id header when callers have not supplied one, adds focused header tests, and notes the sibling WebSocket fallback.

PR surface: Source +21, Tests +118. Total +139 across 3 files.

Reproducibility: yes. for a source-level reproduction: current main has options.sessionId available but does not pass it into native ChatGPT Responses default header construction. The linked live artifact also shows after-fix ChatGPT-OAuth cache behavior, though I did not rerun live ChatGPT traffic.

Review metrics: 1 noteworthy metric.

  • Generated outbound provider header: 1 added. The PR adds a new default header on native ChatGPT Responses requests, so backend scoping and caller override behavior matter before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #100232
Summary: This PR is the focused candidate fix for the linked native ChatGPT Responses missing session_id affinity header issue; nearby affinity and byte-stability items target different provider paths or companion cache root causes.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster ✨ media proof bonus
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • none.

Risk before merge

  • [P1] Merging intentionally adds a generated outbound session_id header for existing native ChatGPT Responses users; it is scoped to the native chatgpt.com backend and caller session_id overrides win, but it is still a provider wire-behavior change.

Maintainer options:

  1. Land the scoped header default (recommended)
    Accept the native ChatGPT Responses outbound header change because it is backend-gated, caller overrides are preserved, and the linked live proof shows the intended cache-routing improvement.
  2. Pause for broader header parity
    Hold the PR only if maintainers want the native ChatGPT path to align on a wider session-id/thread-id/x-client-request-id design before changing defaults.

Next step before merge

  • No automated repair is identified; the branch is review-clean and needs ordinary maintainer landing once exact-head checks and mergeability are acceptable.

Security
Cleared: The diff changes scoped outbound provider header shaping, tests, and comments; it does not add dependency, workflow, secret, permission, or supply-chain surface.

Review details

Best possible solution:

Land the focused native ChatGPT Responses header fix once exact-head checks and mergeability are acceptable; keep broader provider affinity and byte-stability work in the adjacent items.

Do we have a high-confidence way to reproduce the issue?

Yes for a source-level reproduction: current main has options.sessionId available but does not pass it into native ChatGPT Responses default header construction. The linked live artifact also shows after-fix ChatGPT-OAuth cache behavior, though I did not rerun live ChatGPT traffic.

Is this the best way to solve the issue?

Yes. Threading the existing session id into the native Responses client header builder is the narrowest maintainable fix for this path, and the native-backend gate avoids duplicating broader OpenRouter or Fireworks affinity work.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against e3c40efeb09f.

Label changes

Label justifications:

  • P2: This is a focused provider performance and cost bugfix for one ChatGPT Responses path, with limited blast radius and no core runtime outage.
  • merge-risk: 🚨 compatibility: The PR changes default outbound provider headers for existing native ChatGPT Responses users.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (linked_artifact): Sufficient linked artifact: the PR body links live ChatGPT-OAuth usage data showing TRUE cache hit rate improving from 56.0% to 81.8% with the after-fix header path.
  • proof: sufficient: Contributor real behavior proof is sufficient. Sufficient linked artifact: the PR body links live ChatGPT-OAuth usage data showing TRUE cache hit rate improving from 56.0% to 81.8% with the after-fix header path.
Evidence reviewed

PR surface:

Source +21, Tests +118. Total +139 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 2 23 2 +21
Tests 1 118 0 +118
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 141 2 +139

What I checked:

  • Current-main header gap: On current main, createOpenAIResponsesClient calls buildOpenAIClientHeaders(model, context, optionHeaders, turnHeaders) without the already-available options.sessionId, so the native ChatGPT Responses OpenAI SDK default headers cannot include a session-affinity id. (src/agents/openai-transport-stream.ts:1983, e3c40efeb09f)
  • Patch shape: At the reviewed head, the PR adds sessionId to buildOpenAIClientHeaders, skips injection when a case-insensitive session_id key is already resolved, gates the generated header on usesNativeOpenAICodexResponsesBackend(model), and passes options.sessionId from the Responses transport call site. (src/agents/openai-transport-stream.ts:1912, fcafd490e13e)
  • Regression coverage: The PR adds tests for native ChatGPT Responses header injection, absence without a session id, absence for non-native OpenAI Responses, exact caller override, and differently-cased caller override. (src/agents/openai-transport-stream.test.ts:971, fcafd490e13e)
  • Sibling provider precedent: The package-level ChatGPT Responses path already sets session_id and x-client-request-id from sessionId for SSE requests, supporting a native-backend-specific header fix rather than a broad provider change. (packages/ai/src/providers/openai-chatgpt-responses.ts:1785, e3c40efeb09f)
  • Codex dependency source checked: A fresh sibling Codex checkout shows the Responses HTTP client adds x-client-request-id from thread_id and extends session headers built from session_id and thread_id; the helper currently emits hyphenated session-id and thread-id headers. (../codex/codex-rs/codex-api/src/endpoint/responses.rs:87, 831c14fc39f7)
  • OpenAI SDK header merge contract: The pinned OpenAI Node source builds request headers with client defaultHeaders before per-request options.headers, so generated default headers remain overridable by request headers. (external:openai-node/src/client.ts:1157, 25ab4c686ebb)

Likely related people:

  • steipete: Authored and merged the reusable AI runtime extraction that introduced the package-level ChatGPT Responses provider used here as the local header precedent. (role: recent adjacent contributor; confidence: high; commits: 062f88e3e3af; files: packages/ai/src/providers/openai-chatgpt-responses.ts, src/agents/openai-transport-stream.ts)
  • vincentkoc: Recent history and PR metadata tie Vincent Koc to OpenAI transport hot paths and the provider request policy/caller-wins header behavior this PR preserves. (role: recent area contributor; confidence: high; commits: abd8a46b0a52, 736c6743c1ab; files: src/agents/openai-transport-stream.ts, src/agents/provider-request-config.ts)
  • anyech: Authored the recent native ChatGPT Responses stream fix in the same OpenAI transport area. (role: adjacent feature contributor; confidence: medium; commits: 75141775dbaa; files: src/agents/openai-transport-stream.ts)
  • obviyus: Posted the current maintainer-review/land-prep comment and pushed the comment-only fixup documenting the Codex header naming divergence. (role: reviewer and likely follow-up owner; confidence: medium; commits: fcafd490e13e; files: src/agents/openai-transport-stream.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (5 earlier review cycles)
  • reviewed 2026-07-05T08:55:15.238Z sha e3c599a4f0e8d97567f4eb5e3a9cb9d8b6e3dc45 :: needs real behavior proof before merge. :: [P2] Honor session_id overrides case-insensitively
  • reviewed 2026-07-05T09:00:35.075Z sha e3c599a4f0e8d97567f4eb5e3a9cb9d8b6e3dc45 :: needs real behavior proof before merge. :: [P2] Honor session_id overrides case-insensitively
  • reviewed 2026-07-05T11:25:33.013Z sha e3c599a4f0e8d97567f4eb5e3a9cb9d8b6e3dc45 :: needs changes before merge. :: [P2] Honor session_id overrides case-insensitively
  • reviewed 2026-07-06T00:11:01.186Z sha 4ac8a558b158d3bbf44cf90cd45da354ae166418 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-06T08:32:04.528Z sha d23b811d47613f83f5db6d646ecaeb144a78692e :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jul 5, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Jul 5, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 5, 2026
@Marvinthebored

Copy link
Copy Markdown
Contributor Author

Addressed the review: the generated session_id header injection now checks all resolved header keys case-insensitively before adding one, so a caller-supplied Session_ID/SESSION_ID header is respected instead of coexisting with our generated lowercase key. Added a regression test covering a differently-cased caller header. New head: 4ac8a558b15.

@Marvinthebored

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jul 6, 2026
@obviyus

obviyus commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

Maintainer review + land prep.

Review: bug confirmed on main — buildOpenAIClientHeaders (src/agents/openai-transport-stream.ts) never sent a session-affinity header on the native ChatGPT Responses transport, while the provider path (packages/ai/src/providers/openai-chatgpt-responses.ts) already does. Evidence A/B (81.8% vs codex-runtime reference legs 81.7%/85.8%) is convincing.

Fixup pushed (e02094486d2, comment-only): verified directly against Codex source that current codex-rs sends session-id (hyphen) via build_session_headers (codex-rs/codex-api/src/requests/headers.rs), not session_id. The underscore form is kept — it matches our provider path and the A/B proves the backend honors it — with an inline contract comment documenting the divergence.

The new default outbound header for native ChatGPT Responses users is accepted as a maintainer decision (per ClawSweeper's compat flag). Landing after CI on the new head.

Peetiegonzalez and others added 3 commits July 7, 2026 08:45
…kend

The ChatGPT backend routes requests by session_id (codex-cli sends it); without it each request lands on an arbitrary machine and the prompt cache misses. Measured on live traffic: 56.0% -> 81.8% TRUE cache hit rate (12-turn A/B, identical prompts).
buildOpenAIClientHeaders only skipped generating a session_id header
when the exact lowercase key was already present, so a caller-supplied
Session_ID or SESSION_ID header would end up on the wire alongside our
generated one instead of winning per the caller-wins header contract.
Check all resolved header keys case-insensitively before injecting.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ChatGPT Responses backend: missing session_id affinity header tanks prompt-cache hit rate

3 participants