Skip to content

fix(openai): cache system prompts on GPT-6.2 Astra and Sol - #201094

Merged
roboclaw-bot merged 5 commits into
mainfrom
fix/responses-uncached-instructions
Nov 19, 2026
Merged

roboclaw-bot merged 5 commits into
mainfrom
fix/responses-uncached-instructions

Conversation

@obviyus

@obviyus obviyus commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

gpt-6.2-astra never caches the Responses instructions field. Input items and tools cache normally, and gpt-6-astra / gpt-6.1-sol cache instructions. On native OpenAI Responses, OpenClaw sends the system prompt in instructions (usesInstructionsField in openai-responses-payload-policy.ts). So on gpt-6.2-astra the full system prompt is billed as plain input on every request. On a real Gateway turn that is about 9.5k plain tokens per request (measured below).

Controlled API replays with the same body:

  • System text in instructions: 0 written, 0 read on every try.
  • The same text as an input message: written once, then fully read.

Solution

  • New model capability compat.cachesInstructions (default true). The OpenAI catalog sets it to false on gpt-6.2-astra. supportsInstructions still means "the route accepts the field". The new capability means "the model caches it". The payload policy uses instructions only when both are true. In all other cases the prompt goes into input, which is the path that already exists for routes without instructions.
  • Placement (openai-responses-replay-messages-internal.ts): the system item now goes directly after the compaction item (or compacted window), not before it. OpenAI drops input that comes before a compaction item, and server compaction absorbs a developer item placed before it. Layout: [compaction, developer(system), tail…]. Without compaction: [developer(system), …]. Provider-style and Azure routes, which always embed the prompt, use the same rule.
  • Continuation needs no new code. The item belongs to the stored input prefix:
    • The same prompt continues the chain. The delta does not resend the item, because previous_response_id carries it.
    • A changed, added or removed prompt changes the prefix. Continuation then returns history_changed, and the request is a full replay with no previous_response_id. It carries only the new item, so the model never sees two system prompts.
    • Prompt updates that arrive as appended instruction messages keep the chain. The pinned system prompt stays the same.
  • /responses/compact on native OpenAI still receives the prompt as instructions, which keeps the prompt out of the retained window. Without this, the next replay would send the old prompt from the window and the current one. The item carries a symbol marker (RESPONSES_SYSTEM_PROMPT). The marker never reaches the wire.
  • Context-usage accounting found the embedded prompt by checking input[0]. After compaction, input[0] is the compaction item, so accounting now uses the marker.
  • The Responses image sanitizer rebuilt each mutable input item from its string keys, which dropped symbol markers before the compact call and accounting read them. The new compact test found this. The sanitizer now copies with a spread, so the markers stay on the copy. The V2 compaction step that restored only RESPONSES_RETAINED_USER after sanitation is removed.
  • Docs: the cachesInstructions row in custom-providers, plus one paragraph in prompt-caching (OpenAI section).

Evidence

Red/green (ocx test)

  • openai-responses-uncached-instructions.integration.test.ts (real HTTP/SSE loopback, unmocked SDK, native route):
    • capability missing → instructions (green on base and head, default unchanged)
    • capability false → no instructions, developer item first, delta has no developer item, changed prompt → full replay with only the new item (red on base, green on head)
    • after a compaction item the developer item comes next (red on base, green on head)
    • continuation decision: same prompt continues; changed / removed / added prompt → history_changed (a missing prompt never matches a present one)
  • openai-responses-compaction-replay.test.ts: provider-style replay puts the prompt after the compaction item (red on base, green on head)
  • openai-responses-client.compact.test.ts: compact body keeps the prompt in instructions for both models

Real route, isolated scratch Gateway (env -i, random port, real openai/gpt-6.2-astra, responsesCompactThreshold: 28000)

The same 6-turn chat ran on the merge base (6a8eb5a93234) and on this head (3a600ca; rerun on 18cb195 matched: plain 119–220, cacheRead 17,949 / 40,421 on turns 5/6, rules held). Turn 4 pastes about 15k tokens, which crosses server compaction. The workspace rules are: end every reply with ZEBRA-17, and answer REFUSED when asked for the secret word. Provider usage per request:

Turn base plain input base cacheRead head plain input head cacheRead
1 (cold) 9,475 0 119 0 (write 17,943)
2 9,475 8,583 119 17,943
3 9,475 8,796 119 18,158
4 (+15k paste, compacts) 9,475 8,992 119 18,354
5 (first after compaction) 9,569 8,583 208 17,943
6 9,576 31,045 211 40,409
  • Plain (neither read nor written) input per request: ~9.5k → ~120–210. The system prompt moves from plain to cached.
  • Wire shapes (from OPENCLAW_DEBUG_MODEL_PAYLOAD=summary). Base: instructions present on every request. Head: no instructions field, and the input begins with message:developer. After compaction, base sends compaction,message:user,… and head sends compaction,message:developer,message:user,….
  • Rules held on both sides before and after compaction (turns 2 and 5: REFUSED + ZEBRA-17, all turns end with ZEBRA-17).

Real previous_response_id chain with a prompt change (openai-responses-uncached-instructions.live.test.ts, real gpt-6.2-astra)

Request previous_response_id developer items cacheRead reply
prompt A no [A] 0 Hi! ALPHA-1
prompt A yes [] (delta) 2,128 7. ALPHA-1
prompt B (A rule removed) no (full replay) [B] 0 4. BRAVO-2

The rule that exists only in B is followed. The rule from A, which B removed, is no longer applied.

Gates

  • pnpm tsgo:core, pnpm check:test-types
  • ocx test on packages/ai/src/transports, packages/ai/src/providers, packages/model-catalog-core, extensions/openai, config/model-registry schema tests
  • oxlint + oxfmt on changed files, git diff --check
  • Local ClawSweeper review (gpt-6.1-sol, normal speed) on 18cb195: complete, "patch is correct", zero findings
  • pnpm static:validators:gen, pnpm config:schema:gen, pnpm config:docs:gen (regenerated outputs committed)

Impact / risks

  • Only models whose catalog sets cachesInstructions: false change wire shape (today only gpt-6.2-astra).
  • Placement after compaction also applies to routes that always embed the prompt (Azure, provider-style replay). Before this change those routes put the prompt before the compaction item, where OpenAI drops it.
  • Accepted edge case: a payload hook that rebuilds input items from JSON loses the marker. The compact call then sends the prompt in input, and context-usage falls back to the conservative local estimate. Both are visible and recoverable.
  • Authority of a developer item vs instructions was equal on a small probe (12/12 vs 12/12). This is not a proof for every prompt.

…-astra

gpt-6.2-astra never caches the Responses `instructions` field, so the whole
system prompt was billed as plain input on every request. A new model
capability, `compat.cachesInstructions: false`, makes the transport send the
same prompt as a developer input item, which the provider caches.

The item goes directly after the last compaction item (OpenAI drops input
that comes before it). It stays in the stored prefix, so continuation deltas
do not repeat it and a changed prompt forces a full replay with only the new
item. The compact endpoint still receives the prompt as `instructions`, and
context-usage accounting finds the item by a marker instead of position.

Co-authored-by: obviyus <[email protected]>
@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling extensions: openai size: M labels Nov 18, 2026
The Responses image sanitizer rebuilt every mutable input item from its
string keys, which dropped the symbol markers that later request stages
read. The system-prompt marker was lost before the compact call and
context-usage accounting, so the compact call sent the prompt in input.
Copy the item with a spread so the markers stay on the copy, and remove
the V2 compaction step that restored only the retained-user marker.

Co-authored-by: obviyus <[email protected]>
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 18, 2026
@obviyus
obviyus marked this pull request as ready for review November 18, 2026 09:07
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 18, 2026
@clawsweeper

clawsweeper Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

The PR adds a model capability that moves uncached system instructions into cacheable Responses input while preserving compaction and continuation behavior.

Example: A repeated Gateway turn uses openai/gpt-6.2-astra with roughly 9,500 tokens of system instructions.

  • Before: The supplied baseline results show about 9,475 plain input tokens per request.
  • After: The supplied head results show about 119–220 plain input tokens, with the system prompt cached and its rules preserved after compaction.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused implementation has strong fresh-setup behavior evidence, with existing-state upgrade validation still outstanding and one redundant test group.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Users repeatedly pay plain-input rates for a large system prompt that the selected model can cache when sent as input.
Reason: Measured recurring savings justify the focused change, and the maintainer-authored PR supplies direction for the optional capability.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep this PR open: it addresses measured excess input billing, retains meaningful unique work, and is maintainer-authored; no definite introduced correctness bug was found.

Priority: P2
Reviewed head: 18cb1952b430657c1bdee5ee6e362fe5ec9a4ba5

Before merge

  • Complete next step - The PR author should resolve GitHub's reported merge conflict on the branch.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Low-value test packages/ai/src/transports/openai-responses-uncached-instructions.integration.test.ts: Remove or replace the final hand-built continuation table: it bypasses the changed capability and serializer and passes with the original defect; exercise prompt addition/removal through the existing transport helper if those cases need coverage.
  • Missing end-to-end proof: Supply a latest-stable-to-head upgrade run preserving existing model settings and a compacted conversation, then verify a successful cached follow-up; redact credentials and non-public endpoints.
Agent review details

How this fits together

The shared Responses transport converts agent prompts and conversation checkpoints into provider requests, then records replies, continuation state, and measured context usage.

flowchart LR
A[Agent context] --> B[Catalog compatibility]
B --> C[Responses payload policy]
A --> D[Replay serializer]
C --> D
D --> E[OpenAI Responses transport]
E --> F[Reply and usage]
F --> A
Loading

Technical review

Best possible solution:

Retain the shared-policy repair and establish stable-upgrade compatibility before landing it.

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

Current main demonstrably sends this model's system prompt through instructions, and the supplied real-provider baseline/head measurements establish the billing consequence; this review ran no target code.

Is this the best way to solve the issue?

The capability belongs in the existing catalog and payload-policy owners, with checkpoint ordering, compact-endpoint extraction, and symbol preservation forming one coherent repair.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 1fc5296cba84.

Provenance checked

  • System-prompt placement and continuation changes intended behavior with a stated reason (e1a2f77: Top-level instructions prevented changing system text from invalidating the stored input prefix; the new model-specific caching evidence explains accepting full replay when embedded instructions change.)
  • Shared replay ordering and prompt preparation keeps the original intent (17eb646: The replay consolidation established one serializer, while later work preserved prepared prompt bytes and runtime-context anchoring; the patch retains those owners and moves checkpoint emission ahead of the prompt.)
  • Compact endpoint prompt exclusion keeps the original intent (77e2261: Native OpenAI compact requests keep instructions outside the retained window; extracting the marked prompt preserves this contract for the new input representation.)
  • V2 retained-user metadata through sanitation keeps the original intent (52200cf: V2 compaction retains only serializer-marked authored users; preserving symbols in the shared sanitizer replaces the special restoration step without removing that distinction.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +17, Tests +237, Docs +2, Generated +6. Total +262 across 25 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 15 83 66 +17
Tests 5 249 12 +237
Docs 2 2 0 +2
Config 0 0 0 0
Generated 3 9 3 +6
Other 0 0 0 0
Total 25 343 81 +262

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Public configuration addition 1 optional model capability compat.cachesInstructions defaults to the previous behavior when omitted and changes prompt placement when explicitly false.

Labels

Label changes:

  • add P2: Repeated system-prompt billing affects one explicitly selected model without preventing agent operation.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: Repeated system-prompt billing affects one explicitly selected model without preventing agent operation.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 18, 2026, 4:23 AM ET / 09:23 UTC.

@openclaw-barnacle openclaw-barnacle Bot removed the gateway Gateway runtime label Nov 18, 2026
@roboclaw-bot
roboclaw-bot enabled auto-merge (squash) November 18, 2026 23:03
@roboclaw-bot roboclaw-bot changed the title fix(openai): send the system prompt as a cached input item on gpt-6.2-astra fix(openai): cache system prompts on GPT-6.2 Astra and Sol Nov 18, 2026
Baseline-Refresh: 5f89d3995ea22e5416ab75d4e7d61b66b0019132
Co-authored-by: steipete <[email protected]>
@obviyus

obviyus commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Measurement for the cachesInstructions: false flag on gpt-6.2-sol (added in b187603). It had no measurement before.

Same body sent twice, 3 s apart. Direct POST /v1/responses, store: false, one fixed prompt_cache_key per shape. Body: about 13k tokens of system text, 8 tools, about 13k tokens of history, and a short user turn. The system text is either in instructions or in a leading developer input item. 2 trials per shape. gpt-6.2-astra was run in the same session as a control.

Columns: input_tokens / cached_tokens / cache_write_tokens / uncached (input − cached − write).

Model Shape Request 1 Request 2
gpt-6.2-sol instructions 34,494 / 0 / 21,360 / 13,134 34,494 / 21,360 / 0 / 13,134
gpt-6.2-sol instructions (trial 2) 34,814 / 0 / 21,461 / 13,353 34,814 / 21,461 / 0 / 13,353
gpt-6.2-sol developer item 34,494 / 0 / 34,491 / 3 34,494 / 34,491 / 0 / 3
gpt-6.2-sol developer item (trial 2) 34,814 / 0 / 34,811 / 3 34,814 / 34,811 / 0 / 3
gpt-6.2-astra instructions 34,792 / 0 / 21,662 / 13,130 34,792 / 21,662 / 0 / 13,130
gpt-6.2-astra developer item 34,792 / 0 / 34,789 / 3 34,792 / 34,789 / 0 / 3

Result: gpt-6.2-sol behaves like gpt-6.2-astra. The instructions tokens are never written to or read from the cache (about 13.1k–13.4k uncached on every request). The same text as a developer item is written once and then read in full. The flag on gpt-6.2-sol is correct.

This comment adds evidence only. No commits on this PR were changed.

Baseline-Refresh: 17108c014ffaccf5fab1bc16f30e00ba24b4fde9
Co-authored-by: steipete <[email protected]>
@roboclaw-bot
roboclaw-bot merged commit c5d0e00 into main Nov 19, 2026
123 checks passed
@roboclaw-bot
roboclaw-bot deleted the fix/responses-uncached-instructions branch November 19, 2026 10:30
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Merged via squash.

roboclaw-bot pushed a commit that referenced this pull request Nov 19, 2026
* fix(openai): send the system prompt as a cached input item on gpt-6.2-astra

gpt-6.2-astra never caches the Responses `instructions` field, so the whole
system prompt was billed as plain input on every request. A new model
capability, `compat.cachesInstructions: false`, makes the transport send the
same prompt as a developer input item, which the provider caches.

The item goes directly after the last compaction item (OpenAI drops input
that comes before it). It stays in the stored prefix, so continuation deltas
do not repeat it and a changed prompt forces a full replay with only the new
item. The compact endpoint still receives the prompt as `instructions`, and
context-usage accounting finds the item by a marker instead of position.

Co-authored-by: obviyus <[email protected]>

* fix(ai): keep request provenance markers through image sanitation

The Responses image sanitizer rebuilt every mutable input item from its
string keys, which dropped the symbol markers that later request stages
read. The system-prompt marker was lost before the compact call and
context-usage accounting, so the compact call sent the prompt in input.
Copy the item with a spread so the markers stay on the copy, and remove
the V2 compaction step that restored only the retained-user marker.

Co-authored-by: obviyus <[email protected]>

* fix(openai): cache native Responses prompts on Astra and Sol only

Co-authored-by: steipete <[email protected]>

---------

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>
(cherry picked from commit c5d0e00)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 20, 2026
…201094)

* fix(openai): send the system prompt as a cached input item on gpt-6.2-astra

gpt-6.2-astra never caches the Responses `instructions` field, so the whole
system prompt was billed as plain input on every request. A new model
capability, `compat.cachesInstructions: false`, makes the transport send the
same prompt as a developer input item, which the provider caches.

The item goes directly after the last compaction item (OpenAI drops input
that comes before it). It stays in the stored prefix, so continuation deltas
do not repeat it and a changed prompt forces a full replay with only the new
item. The compact endpoint still receives the prompt as `instructions`, and
context-usage accounting finds the item by a marker instead of position.

Co-authored-by: obviyus <[email protected]>

* fix(ai): keep request provenance markers through image sanitation

The Responses image sanitizer rebuilt every mutable input item from its
string keys, which dropped the symbol markers that later request stages
read. The system-prompt marker was lost before the compact call and
context-usage accounting, so the compact call sent the prompt in input.
Copy the item with a spread so the markers stay on the copy, and remove
the V2 compaction step that restored only the retained-user marker.

Co-authored-by: obviyus <[email protected]>

* fix(openai): cache native Responses prompts on Astra and Sol only

Co-authored-by: steipete <[email protected]>

---------

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
…ncached (#202372) (#202720)

* fix(openai): embed system prompt in input on ChatGPT Responses when uncached (#202372)

* test(openai): claim provider state for cached continuation

Share the conversation provider-state claim across the three fixture turns so the regression exercises reusable WebSocket continuation and changed-prompt replay.

Co-authored-by: RomneyDa <[email protected]>

* test(openai): align compaction prompt placement by transport

Keep the managed transport instructions contract and assert native ChatGPT developer input when cachesInstructions is false. Preserve full normal-versus-compaction request equality.

Co-authored-by: RomneyDa <[email protected]>

---------

Co-authored-by: tideclaw-bot <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 8b17822)

Release adaptation: use stable's existing sessionId-keyed WebSocket continuation in the regression fixture. The main-only #203568 writer scope is unnecessary on this branch; the three-turn continuation/replay assertions and the upstream production request builder are unchanged.

Companion disposition: #201094 is present-equivalent at stable 7750bb3 (compat type, catalog and managed Responses transport). #203568 is not applicable to stable's transport ownership and is not imported. Existing cache/replay sibling tests require no changes. No later same-path or issue-reference follow-ups. Prior beta.3 deferral does not apply to this expressly requested stable pick.

Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: openai P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants