App-server sessions need stable prompt-cache key support for identical startup context
What version of Codex CLI is running?
0.129.0
Which model were you using?
gpt-5.3-codex-spark
What platform is your computer?
Windows, using Codex app-server through an external multi-session orchestrator.
What issue are you seeing?
Independent fresh Codex app-server sessions do not appear to get full first-turn prompt-cache reuse even when the client sends the same stable startup context byte-for-byte.
From local instrumentation in a multi-session app-server workflow:
- Session A first turn:
11,749input tokens,6,528cached input tokens (~55.6%). - Session B first turn:
11,749input tokens,6,400cached input tokens (~54.5%). - The model-visible first-turn startup prefix sent by the client was byte-identical across both sessions.
- Both sessions were independent fresh Codex app-server threads with different Codex thread IDs.
The likely cause is that Codex currently derives prompt_cache_key from the unique thread id:
https://github.com/openai/codex/blob/872b8b15b38acbcc19457ef96b171819a56206db/codex-rs/core/src/client.rs#L713-L728
That is reasonable for cache reuse within a single long-lived thread, but it prevents app-server clients from intentionally sharing cache for stable startup/base context across multiple independent sessions. This is especially visible for multi-session / multi-agent orchestrators that start several fresh Codex sessions with identical base instructions, developer instructions, project context, and first-turn setup.
I did not find a current app-server option or schema field that lets the client provide a stable prompt cache key or split the cache key for the reusable startup prefix.
This is related to, but more specific than, the broader low-cache-hit issue in #20301. That issue appears to cover general GPT-5.5 cache-hit anomalies; this report is about the app-server architecture using per-thread cache keys for otherwise identical fresh sessions.
What steps can reproduce the bug?
- Start two independent fresh Codex app-server sessions for the same project.
- Use the same model and runtime configuration for both sessions.
- Send the same startup/base/developer/project context in the first turn of each session.
- Confirm locally that the model-visible first-turn prefix is byte-identical across the two sessions.
- Compare
input_tokensandcached_input_tokensfor the first completed turn of each session.
In the observed case, both sessions had exactly 11,749 input tokens, but only about 55% of input tokens were reported as cached, despite the stable prefix being byte-identical.
What is the expected behavior?
App-server clients should have a way to opt into stable prompt-cache reuse for stable startup/base context across independent fresh sessions.
Possible fixes:
- expose a client-provided
prompt_cache_key/ cache namespace for app-server sessions; - allow app-server clients to provide a stable cache key for base/developer/startup context while keeping per-thread state isolated;
- or otherwise avoid tying reusable startup-context caching exclusively to the unique thread id.
The important property is that two independent sessions with identical stable startup context can share cache for that prefix without sharing conversation state.
Additional information
A previous PR appears to have explored passing a prompt cache key when starting Codex, but it was closed without merging: #5949.
Related cache-key propagation work for compaction: #21249.
Related fork prompt-cache-state work: #20909.
If maintainers want private thread/session IDs or uploaded feedback bundles for the two observed sessions, I can provide them separately. I avoided putting those IDs in this public issue body.
Potential duplicates detected. Please review them and close your issue if it is a duplicate.
- #20301
Powered by Codex Action
FWIW, I independently saw the same kind of instability from app-server instrumentation.
In one run with byte-identical reusable context, I saw 25,472 / 25,657 input tokens cached, so about 99.3%. In another comparable run, I saw only 2,432 / 25,657, so about 9.5%. Forked-thread runs were similarly inconsistent: one child turn got 15,744 / 25,327 cached (62.2%), another only 2,432 / 25,327 (9.6%).
So this does not look like just noisy accounting. The cache can clearly work very well, but app-server clients currently cannot make it reliable for identical startup/fork context because the cache key is tied to unique thread ids.
A promptCacheKey/cache namespace option in app-server, or using the shared root/session id for fork families, would be very useful here with a big payoff for multi-agent orchestrators.
Adding production numbers from a multi-session orchestrator, since this hits us hard on the ChatGPT-authenticated backend.
Setup: OpenClaw drives the Codex app-server (codex 0.153.4, gpt-6-astra, ChatGPT login, WebSocket transport) for an internal assistant. Every new conversation, scheduled job and helper run is a fresh app-server thread, and the first request of every thread carries the same ~42k-token prefix (base instructions, ~20 dynamic tool schemas, developer instructions).
Measured over three days (Oct 3–5, 390 fresh threads):
- 349 first requests (89 %) had
cached_input_tokens = 0. - 27 had ~11–12.4k cached (roughly the tool-schema prefix), 14 had more than 20k cached — apparently the few that happened to be routed to a warm machine.
- On a busy weekday (~300 thread starts), thread starts were ~36 % of all uncached input plus output, which is what our weekly usage tracks.
- Within a thread, caching works well: after pauses of up to an hour, ~90 % of the previous context is still served from cache.
What we found in the source: since #44862 the cache affinity follows the session-id header (the root thread id), and only ephemeral root forks inherit the parent's affinity. Ephemeral threads are not persisted, so this does not help conversations that have to be resumed later (see also #44716).
What would solve it for us (either would do):
- a cache-affinity /
promptCacheKeyoption onthread/startandthread/forkthat is applied to bothprompt_cache_keyand thesession-idheader, or - letting persistent forks opt into the parent's affinity (e.g.
inheritCacheAffinity: true), so clients can start conversations from a warm template thread.
We would shard such keys ourselves (per agent, hash mod N) to stay below the ~15 requests/minute overflow guidance. Happy to share more data.
Adding a controlled measurement on the ChatGPT-authenticated backend that isolates the cause and shows a partial workaround.
Setup: codex-cli 0.162.0-alpha.17.2, app-server, gpt-6.1-sol (low effort), ChatGPT sign-in. Every chat sent the same first message on top of an identical ~24k-token startup prefix (base instructions, dynamic tools, strict output schema). Arms were interleaved (A B B A A B B A A B) within a few minutes.
| Arm | First request: input | Cached input | Chats |
|---|---|---|---|
A: thread/fork with experimentalPredictionMode, ephemeral, excludeTurns: true from a warmed base thread |
23,906 | 23,680 (99.1%) | 5/5 |
B: fresh thread/start, byte-identical prompt |
23,870 | 0 | 5/5 |
Arm B chats repeated the exact same prompt seconds apart and never got a cache hit, so reuse follows session affinity rather than identical bytes.
Against a local fake endpoint, the same binary sends the parent thread's id as both prompt_cache_key and the session-id header on prediction-mode forks (while client_metadata keeps the fork's own ids). Plain forks, beforeTurnId forks and fresh threads send their own id in both. That matches the session-header affinity described in #44716 / #44862.
Prediction-mode forks are a workable stopgap for clients that start many short sessions with the same startup context. But they are ephemeral (a restarted app-server can't thread/resume them: "no rollout found"), they need a warm-up turn on a base thread, and the parameter is experimental.
Request: let app-server clients pass a stable cache-affinity key on thread/start (and thread/resume), used for both prompt_cache_key and the session-id header, while keeping the real session identity in metadata. Durable, resumable threads with identical startup context could then reuse the cached prefix the same way prediction forks already do.
Adding a measurement and a minimal patch for this.
Proposal: A prompt_cache_key config key (config.toml, and therefore -c prompt_cache_key=... on codex exec / codex app-server). It would be sent on every model request of every thread in place of the session-derived key.
Core already has the policy. PromptCacheKey::Custom in core/src/thread_manager.rs is honoured by ModelClient::prompt_cache_key. Nothing outside internal callers can set it, though: StartThreadOptions::new always uses PromptCacheKey::default(), and the app-server protocol has no field for it.
Why: We host codex app-server as an agent harness: one agent prompt and one tool set, served to many short conversations, each its own Codex thread. The prefix is byte-identical across those threads. Because Codex keys the cache by its own thread id, every new thread writes the whole prefix again and never reads it.
Measured on 0.164.0 against a Responses-compatible gateway, gpt-6.1-sol, with a ~13.9k-token prefix. Each row is the first call of a fresh thread:
| Key sent | Threads | Cached on first call |
|---|---|---|
| session-derived (default) | 4 | 0 / 13,920 each |
| one configured key | 5 | 0 on the first thread (cache write), 13,917 / 13,920 (100%) on each of the next 4 |
In an earlier run with a 17.6k-token prefix, the first call cost $0.0440 with the default key and $0.0022 with a shared key, about 20x cheaper.
A capture of the request confirms the patched build sends the configured key and keeps session-id unchanged.
Patch: This is the patch we run locally. It adds about 20 lines across config/src/config_toml.rs, core/src/config/mod.rs, core/src/thread_manager.rs and core/config.schema.json:
diff --git a/codex-rs/config/src/config_toml.rs b/codex-rs/config/src/config_toml.rs
index 7f70fb8..5a371d4 100644
--- a/codex-rs/config/src/config_toml.rs
+++ b/codex-rs/config/src/config_toml.rs
@@ -414,6 +414,11 @@ pub struct ConfigToml {
/// `default`, `priority`, or `flex`; legacy `fast` also works).
pub service_tier: Option<String>,
+ /// Optional `prompt_cache_key` sent on every model request of every thread,
+ /// in place of the session-derived key. A host running many threads over one
+ /// prompt prefix sets it so a new thread reads the prefix from the cache.
+ pub prompt_cache_key: Option<String>,
+
/// Base URL for requests to ChatGPT (as opposed to the OpenAI API).
pub chatgpt_base_url: Option<String>,
diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json
index cce71e4..c50ed67 100644
--- a/codex-rs/core/config.schema.json
+++ b/codex-rs/core/config.schema.json
@@ -8192,6 +8192,10 @@
},
"type": "object"
},
+ "prompt_cache_key": {
+ "description": "Optional `prompt_cache_key` sent on every model request of every thread, in place of the session-derived key. A host running many threads over one prompt prefix sets it so a new thread reads the prefix from the cache.",
+ "type": "string"
+ },
"realtime": {
"allOf": [
{
diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs
index 3f6c1cc..57b198c 100644
--- a/codex-rs/core/src/config/mod.rs
+++ b/codex-rs/core/src/config/mod.rs
@@ -645,6 +645,9 @@ pub struct Config {
/// `default` means the user explicitly selected standard routing.
pub service_tier: Option<String>,
+ /// `prompt_cache_key` for every thread in place of the session-derived key.
+ pub prompt_cache_key: Option<String>,
+
/// Model used specifically for review sessions.
pub review_model: Option<String>,
@@ -4454,6 +4457,7 @@ impl Config {
model,
daybreak_enabled: cfg.daybreak.unwrap_or(false),
service_tier,
+ prompt_cache_key: cfg.prompt_cache_key.clone().filter(|key| !key.trim().is_empty()),
review_model,
model_context_window: cfg.model_context_window,
model_auto_compact_token_limit: cfg.model_auto_compact_token_limit,
diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs
index b2d2264..93f1c7e 100644
--- a/codex-rs/core/src/thread_manager.rs
+++ b/codex-rs/core/src/thread_manager.rs
@@ -326,9 +326,14 @@ pub struct StartThreadOptions {
impl StartThreadOptions {
pub fn new(config: Config) -> Self {
+ // A configured key replaces the session-derived one on every thread.
+ let prompt_cache_key = config
+ .prompt_cache_key
+ .clone()
+ .map_or_else(PromptCacheKey::default, PromptCacheKey::Custom);
Self {
config,
- prompt_cache_key: PromptCacheKey::default(),
+ prompt_cache_key,
thread_instructions_provider: None,
allow_provider_model_fallback: false,
initial_history: InitialHistory::New,
It applies to every thread a process starts or resumes, through StartThreadOptions::new. A per-thread promptCacheKey on thread/start and thread/resume would also serve hosts that run several agents in one app-server. We understand external PRs aren't accepted, so this is offered as a reference for the team.
Another data point, from an app-server client that runs one ephemeral thread per request with client dynamicTools (codex-cli 0.167.0 and 0.169.0, ChatGPT login, gpt-5.6-luna):
| request (new thread each time) | input | cached |
|---|---|---|
| no dynamic tools | 3156 | 2048 |
| one dynamic tool, run 1 | 3198 | 0 |
| one dynamic tool, run 2 (byte-identical request) | 3198 | 0 |
| one dynamic tool, 2nd turn in the same thread | 3246 | 3072 |
Captured request bodies differ only in per-request ids and prompt_cache_key (the thread id). With tool_mode: code_mode_only the client tool is declared inside the exec tool description in additional_tools, so the prefix is no longer the shared default one, and a fresh key per thread means it never hits. --enable incremental_exec_tools on 0.169.0 does not change the result.
#55587 added PromptCacheKey::{Custom, Omit} to core's StartThreadOptions. Exposing it on app-server thread/start (e.g. promptCacheKey: string | null) would let clients like this one share the cache across threads for identical tool sets.
Plain thread/fork still uses the fork's own thread id as the cache key on codex-cli 0.170.0. That makes the ask here apply to forks as well as thread/start.
We run an App Server beside the user's Codex session and fork their conversation for one-call side questions. With gpt-6.2-sol and a ChatGPT login, the first turn on each ephemeral fork read:
| Parent | Input | Cached |
|---|---|---|
| Thread active seconds before the fork | 231k | 0 |
| Desktop-app chat | 117k | 0 |
| Same chat, two forks back to back with an identical request | 117k each | 31.6k each |
The fork's second turn read 231k of 245k from cache.
experimentalPredictionMode would fix this, but it refuses (requires a loaded parent) whenever the parent is loaded in another process, such as the desktop app or a terminal client. The other process holds the writer lock, so we can't load it either. A promptCacheKey on thread/fork, or an option to inherit the parent's key, would let a client like ours fork a live session at the cached price.
This was written by Claude Code on behalf of max-sixty
Adding production numbers from another OpenClaw → Codex app-server deployment. The setup is codex-cli 0.172.0, ChatGPT login, gpt-6.2-sol, and a fleet of agents. Each agent's new conversations start a fresh thread with a byte-identical prefix: base and developer instructions, plus a large set of dynamic tools (100k+ tokens for the biggest agent).
Five consecutive days, 2,805 new threads:
| Time since the same agent's previous thread activity | New threads | First request had any cached tokens |
|---|---|---|
| < 1 minute | 2,115 | 11.5 % |
| 1–5 minutes | 242 | 5.8 % |
| 5–30 minutes | 253 | 6.3 % |
| > 30 minutes | 183 | 4.9 % |
- Three out of four new threads start within a minute of another thread of the same agent, so this is not cache expiry.
- When a first request does hit, it covers about 87 % of the input, so the prefix really is reusable.
- First requests of new threads are about 35 % of all uncached input tokens of the fleet.
This matches openclaw/openclaw#192318: on the ChatGPT backend, cache affinity follows the session_id header, not the prompt_cache_key body field. core/src/client.rs derives both from the thread's session id ("ChatGPT derives cache affinity from the Responses session-id header"). ThreadStartParams has no field for either.
So the ask from our side is a client-chosen cache identity on thread/start (and thread/fork): a key that drives both prompt_cache_key and the affinity header, and, where the backend supports it, the cache TTL. PromptCacheKey::Custom and PromptCacheTtl already exist in core; the app-server protocol only needs to expose them.
Drafted with AI assistance; the numbers come from our own rollouts.