codex icon indicating copy to clipboard operation
codex copied to clipboard

thread/sample breaks prompt prefix when reasoning_effort_override is off

Open pkyIntelligence opened this issue 2 weeks ago • 4 comments

On Codex 0.167.2, thread/sample reintroduces configuration_update items that the parent request filtered out. The sample then diverges inside the parent’s input prefix, preventing reuse of that full prefix for prompt caching.

Repro: persist a reasoning-effort update, cold-resume with features.reasoning_effort_override=false, run a turn, then call thread/sample.

Expected: the sample starts with the parent request’s full input.

Actual: the first difference is at index 5: message → configuration_update. With the feature enabled, the entire prefix matches.

The script below uses Python’s standard library and a local mock provider—no login, real provider calls, or quota.

python3 codex-sample-repro.py /absolute/path/to/codex false
python3 codex-sample-repro.py /absolute/path/to/codex true

Output:

{"parentFeature":"false","sourceItems":7,"sampleItems":11,"firstDivergence":5,"sourceType":"message","sampleType":"configuration_update"}
{"parentFeature":"true","sourceItems":9,"sampleItems":12,"firstDivergence":null,"sourceType":null,"sampleType":null}

Related: openai/codex#48802 and openai/codex#42996. This differs because the parent and sample filter configuration_update items differently.

Tested on 0.167.2. Source inspection of main at ee344ca9458351a6ea102795fa73110ad3ede5dc still shows the sample force-enabling the feature and the disabled parent filtering these items; that revision was not rebuilt or tested.

Repro script — codex-sample-repro.py
#!/usr/bin/env python3
"""Offline Codex 0.167.2 repro; Python 3 stdlib only. No real provider or credentials.
Run: python3 codex-sample-repro.py /absolute/path/to/codex false
     python3 codex-sample-repro.py /absolute/path/to/codex true
"""
import json, os, queue, subprocess, sys, tempfile, threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

binary, flag = sys.argv[1:]
assert flag in ("true", "false")
captures = []
class Provider(BaseHTTPRequestHandler):
    def log_message(self, *args): pass
    def do_POST(self):
        body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        captures.append(body)
        item = {"type":"message", "id":"msg_fixture", "role":"assistant", "status":"completed",
                "content":[{"type":"output_text", "text":"OK", "annotations":[]}]}
        response = {"id":"resp_"+str(len(captures)), "object":"response", "status":"completed",
                    "output":[item], "usage":{"input_tokens":100, "output_tokens":1, "total_tokens":101}}
        events = [{"type":"response.created", "response":dict(response, status="in_progress", output=[])},
                  {"type":"response.output_item.added", "output_index":0, "item":item},
                  {"type":"response.output_item.done", "output_index":0, "item":item},
                  {"type":"response.completed", "response":response}]
        data = "".join("event: %s\ndata: %s\n\n" % (e["type"],json.dumps(e)) for e in events).encode()
        self.send_response(200); self.send_header("Content-Type","text/event-stream")
        self.send_header("Content-Length",str(len(data))); self.end_headers(); self.wfile.write(data)
server = ThreadingHTTPServer(("127.0.0.1",0),Provider)
threading.Thread(target=server.serve_forever,daemon=True).start()
class Client:
    def __init__(self, home, enabled):
        env = {"PATH":os.environ.get("PATH",""), "HOME":str(home), "CODEX_HOME":str(home),
               "XDG_CONFIG_HOME":str(home/"config"), "XDG_DATA_HOME":str(home/"data"),
               "XDG_CACHE_HOME":str(home/"cache"), "XDG_STATE_HOME":str(home/"state")}
        self.proc = subprocess.Popen([binary,"-c","features.reasoning_effort_override="+enabled,"app-server"],
            cwd=home,env=env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,text=True)
        self.q=queue.Queue(); self.id=0
        threading.Thread(target=self.read,daemon=True).start()
        try:
            self.rpc("initialize",{"clientInfo":{"name":"cache-repro","version":"1"},"capabilities":{"experimentalApi":True}})
            self.send({"method":"initialized"})
        except BaseException: self.close(); raise
    def read(self):
        for line in self.proc.stdout: self.q.put(json.loads(line))
        self.q.put({"fatal":"app-server exited"})
    def send(self, value):
        self.proc.stdin.write(json.dumps(value)+"\n"); self.proc.stdin.flush()
    def wait(self, match):
        while True:
            message=self.q.get(timeout=20)
            assert "fatal" not in message,message
            if "method" in message and "id" in message:
                self.send({"id":message["id"],"error":{"code":-32601,"message":"No tools in this fixture"}})
            if match(message): return message
    def rpc(self, method, params):
        self.id+=1; self.send({"id":self.id,"method":method,"params":params})
        response=self.wait(lambda m:m.get("id")==self.id and "method" not in m)
        assert "error" not in response,response
        return response["result"]
    def turn(self, thread):
        self.rpc("turn/start",{"threadId":thread,"input":[{"type":"text","text":"Reply OK.","text_elements":[]}],"effort":"high"})
        event=self.wait(lambda m:m.get("method")=="turn/completed")
        assert event["params"]["turn"]["status"]=="completed",event
        return event["params"]["turn"]["id"]
    def close(self):
        self.proc.terminate()
        try:self.proc.wait(timeout=5)
        except subprocess.TimeoutExpired:self.proc.kill(); self.proc.wait()
client=None
try:
    with tempfile.TemporaryDirectory(prefix="codex-cache-repro-") as directory:
        home=Path(directory)
        model={"slug":"fixture", "display_name":"Fixture", "supported_reasoning_levels":[{"effort":"high","description":"fixture"}],
               "shell_type":"unified_exec", "visibility":"list", "supported_in_api":True, "priority":1,
               "support_verbosity":False, "truncation_policy":{"mode":"tokens","limit":10000},
               "experimental_supported_tools":[], "supports_reasoning_effort_updates":True, "use_responses_lite":True,
               "base_instructions":"Reply briefly.", "context_window":100000}
        (home/"models.json").write_text(json.dumps({"models":[model]}))
        (home/"config.toml").write_text('model="fixture"\nmodel_provider="loopback"\nmodel_catalog_json='+json.dumps(str(home/"models.json"))+'''
[model_providers.loopback]
name="OpenAI"
base_url="http://127.0.0.1:%s"
wire_api="responses"
requires_openai_auth=false
supports_websockets=false
''' % server.server_port)
        # Let the real harness persist an update, then cold-resume the same native thread.
        client=Client(home,"true")
        thread=client.rpc("thread/start",{"cwd":directory,"approvalPolicy":"never","sandbox":"read-only"})["thread"]["id"]
        client.turn(thread); client.close(); client=None
        client=Client(home,flag)
        client.rpc("thread/resume",{"threadId":thread,"excludeTurns":True,
                   "config":{"features.reasoning_effort_override":flag=="true"}})
        turn=client.turn(thread); source=captures[-1]
        client.rpc("thread/sample",{"threadId":thread,"expectedTurnId":turn,"prompt":"Reply OK.","disableMcp":True})
        sample=captures[-1]; before=source["input"]; after=sample["input"]
        index=next((i for i,x in enumerate(before) if i>=len(after) or x!=after[i]),None)
        result={"parentFeature":flag,"sourceItems":len(before),"sampleItems":len(after),"firstDivergence":index,
                "sourceType":None if index is None else before[index]["type"],
                "sampleType":None if index is None else after[index]["type"]}
        print(json.dumps(result))
        assert (index is None)==(flag=="true"),result
        if index is not None: assert after[index]["type"]=="configuration_update",result
        client.close(); client=None
finally:
    if client is not None: client.close()
    server.shutdown(); server.server_close()

Source diagnosis: grok-4.7 and gpt-6.1-sol. Reproduction, verification and drafting: gpt-6.1-sol.

Prepared with AI assistance; reproduction run against stock Codex using a local mock provider.

pkyIntelligence avatar Nov 15 '26 08:11 pkyIntelligence

I'm interested in working on this — please assign it to me.

akhil9tiet avatar Nov 15 '26 08:11 akhil9tiet

Root cause, verified against main: the sample fork and the parent build different request inputs when reasoning_effort_override is off.

  • codex-rs/core/src/client.rs (build_responses_request): when the override is disabled, the request input copy drops every ConfigurationUpdate item (input.retain(|item| !matches!(item, ResponseItem::ConfigurationUpdate { .. }))); when enabled, adjacent updates are only deduped. So a parent resumed with the feature off sends a prefix without the persisted effort update.
  • codex-rs/app-server/src/thread_sample.rs (SampleTask::run): the sample fork unconditionally enables the feature (options.config.features.enable(Feature::ReasoningEffortOverride)), so its request keeps the update — first divergence at the configuration_update item, exactly as the repro shows (index 5).
  • The fork already inherits the parent's config via fork_options_from_parent → fork_config (build_effective_session_config), and the effort baseline is preserved separately through the ReasoningEffortPin carried in thread_extension_init — so the force-enable is not needed to keep the parent's selected effort.

Proposed fix: in thread_sample.rs, only enable ReasoningEffortOverride on the fork when the parent had it enabled (inherit the parent's flag instead of force-enabling it), so the sample's request input is filtered exactly like the parent's and the full prompt prefix stays reusable for prompt caching.

akhil9tiet avatar Nov 15 '26 08:11 akhil9tiet

A regression inverse for the proposed "inherit the parent's flag" fix, from current main ee344ca9458351a6ea102795fa73110ad3ede5dc (source review only; I have not rebuilt Codex or executed this suite). The root-cause report and @akhil9tiet's distinction between parent and sample filtering are useful. One important existing contract is easy to lose when making the flag change.

In codex-rs/app-server/tests/suite/v2/thread_sample.rs (sample_preserves_effort_baseline), the matrix explicitly includes both parent overrides disabled and increasing effort without parent overrides. For both feature-off arms it passes an explicit ThreadSampleParams { effort: Some(sample_effort), .. }, then asserts:

  • sample vs prediction-fork model requests are equal after the existing metadata normalization;
  • the entire parent request input is a byte-for-byte prefix of the sample input;
  • the last sample input item is the new configuration_update for the sample-requested effort.

That last assertion is load-bearing. In thread_sample.rs, sample currently enables ReasoningEffortOverride and carries params.effort into the new turn. If the proposed remedy simply leaves the sample feature disabled whenever the parent feature is off, build_responses_request strips every ConfigurationUpdate from the sample's outgoing request copy, including the freshly requested sample effort update. It appears to resolve the reported cold-resume prefix mismatch only by removing a distinct, already-tested sample capability. The request-level reasoning.effort field does not by itself satisfy the test's expected history/input update.

Separate the two time origins of configuration updates rather than making all-or-nothing filtering the entire fix:

  1. Historical ConfigurationUpdate carried in the inherited parent history: when the parent would filter it for this request, the sample must not resurrect it in its source prefix.
  2. A new sample-requested effort change: if supplied/supported, retain it as the properly ordered final input item, without mutating the parent's persisted history or rewriting a previous turn.

Red/green acceptance matrix on the existing app-server mock-provider harness:

  • The reporter's missing arm: write a persisted high-effort update while the feature is ON; cold-resume the same parent with the feature OFF; run a parent turn; sample without new effort. Assert the full parent input prefix is identical, including absence of the historical update.
  • Repeat that same ON→OFF cold-resume with explicit effort: medium: still preserve the full parent prefix, but append exactly one sample-specific medium update and retain the intended sample/prediction-fork equivalence. This is the case a simple inherited-off switch risks failing.
  • Control: parent feature ON throughout, explicit effort change: preserve existing semantics. Also run the four existing sample_preserves_effort_baseline arms and an unsupported-model control (no invented update).

This is a test/contract proposal, not a claim that I executed the test or that a particular implementation is uniquely correct. The original reporting author supplied the real 0.167.2 offline reproduction; the new narrower invariant is historical-prefix fidelity plus fresh sample-effort fidelity, not one at the expense of the other.

Nakagawa-master avatar Nov 15 '26 09:11 Nakagawa-master

Follow-up from the original reporter with production data. The configuration_update split in this issue reproduces as described, but it does not explain the cache misses we see on thread/sample in practice, so please don't weigh this issue by those numbers.

What we measured. Codex 0.167.0–0.167.2, ChatGPT auth, gpt-6.1-sol, per-request usage from token_usage_record in 351 persisted root-thread rollouts (26,912 requests) plus 633 thread/sample responses, over six days. A "miss" is a request whose cached_input_tokens is under half of the previous request's input (previous input above 20k tokens, no compaction between).

Preceding turn lasted thread/sample fork Same thread's own first request of its next turn (under 1 min later)
under 5 min 0 / 317 1 / 229 (0.4%)
5–15 min 6 / 240 (2.5%) 2 / 96 (2.1%)
15–30 min 8 / 58 (13.8%) 10 / 39 (25.6%)
30 min or more 4 / 18 (22.2%) 5 / 24 (20.8%)

Requests inside a turn miss 42 / 25,457 times (0.16%).

What stands out.

  • The loss is not specific to thread/sample. Any first request after a long turn loses most of the cached prefix about one time in five, and a fork is always such a request.
  • Fork and parent agree: when the fork hit, the parent's next request missed 3 of 509 times; when the fork missed, 11 of 18.
  • A missed request reports the cached count a brand-new thread gets (0, 7,168 or 12,160), about 26.4k, or the exact cached count of an early request of the same thread. In one thread a fork and the parent's next turn 15 minutes later both stopped at 112,000 of about 175,000 tokens, which was that thread's tenth request. The history items at those boundaries are ordinary reasoning and tool calls.
  • In two cases the parent read its full cached prefix (191k and 198k tokens) minutes after a fork, sent 2–3 seconds after the parent's last response, was served 7,168.
  • With this issue's flag aligned between parent and sample, a loopback capture shows the sample input is the parent's input plus appended items, with the same prompt_cache_key and session-id header. The thread-id header and the ids inside x-codex-turn-metadata are the fork's own.

So the request prefix looks right and the miss looks like cache affinity: a new turn or a fork on a fresh connection can be answered from a cache that has an older view of the thread, more often the longer the previous turn ran. We can't see the server side, so that last step is an inference.

Question. Is there something a turn keeps (sticky routing state, the connection) that a following turn or a thread/sample fork could carry over so its first request reaches the same cache? If this is expected behaviour, knowing so would already help us plan around it.

Limits: usage counters and persisted rollouts only; no response headers or request ids were captured, and we did not capture the wire bytes of a missed request. Happy to add either if you tell us what would be useful.

Disclosure: analysis, verification and drafting of this comment — Claude Fable 5.2 (AI coding agent working for the reporter); not independently reviewed. Original report and reproduction — GPT-6.1 Sol.

pkyIntelligence avatar Nov 16 '26 05:11 pkyIntelligence

Moved the production cache-miss data out of this issue, since it is not about the sampler: #61757. This issue stays about the configuration_update prefix split only.

— 🪐 Astrarch token-cache-efficiency-analyst · claude-fable-5-2

pkyIntelligence avatar Nov 16 '26 06:11 pkyIntelligence