Skip to content

Local compaction silently uses a stale assistant message as the summary when the compaction reply has no assistant message #54584

Open

Description

@chmmpagne

What version of Codex CLI is running?

codex-cli 0.163.0 (also reproduced on 0.162.1)

What subscription do you have?

Custom Responses API provider (wire_api = "responses"), no OpenAI subscription.

Which model were you using?

A Qwen model behind a Responses-compatible gateway for the original report; the reproduction below uses a mock provider and mock-model.

What platform is your computer?

Darwin 27.0.0 arm64 arm

What terminal emulator and version are you using (if applicable)?

codex exec (non-interactive); the behavior is independent of the terminal.

Codex doctor report

Status-only summary of codex doctor --json (0.162.1, run non-interactively): everything ok except security.endpoint: warning and terminal.env: fail (no TTY in the capture shell). Nothing relates to compaction.

What issue are you seeing?

For providers without remote compaction, local compaction builds the summary from the last assistant message found in the session history, not from the compaction reply. If the compaction reply contains no assistant message item, Codex doesn't notice: it scans backwards and picks up an older assistant message (typically a one-line progress note from earlier), installs it as the checkpoint summary, and reports success. The agent then resumes with almost none of its working memory.

In codex-rs/core/src/compact.rs (identical on rust-v0.162.1 and main):

let summary_suffix = if matches!(compaction_metadata.phase(), CompactionPhase::PostTurn) {
    get_last_assistant_message_from_turn(compaction_response.output.iter())
        .filter(|summary| !summary.trim().is_empty())
        .ok_or_else(|| {
            CodexErr::Stream(
                "Post-turn compaction completed without an assistant summary".to_string(),
            )
        })?
} else {
    get_last_assistant_message_from_turn(history_snapshot.raw_items()).unwrap_or_default()
};

The post-turn phase already rejects a reply without an assistant message. The other phases read the whole history snapshot and fall back to unwrap_or_default(), so the same input is accepted silently.

How a reply ends up without an assistant message in practice: a Responses-compatible provider can return the whole answer in a single reasoning item, with no message item and reasoning_tokens = 0 (seen with a Qwen model served by vLLM; my suspicion, not confirmed, is that the reasoning parser files an answer that skipped the thinking phase as reasoning). I'm raising that with the provider owner. On one recorded 127k-token compaction request replayed unchanged against my provider, 5 of 25 replies had that shape. Of 26 real compactions on one day of normal use, 12 produced a one-line summary. From Codex's side the problem is that this input is accepted silently.

What steps can reproduce the bug?

The script below is self-contained (Python standard library only). It starts a mock Responses provider, runs two codex exec turns in a temporary CODEX_HOME, and prints the summary Codex carried into the request after the compaction. The first reply reports 50k tokens, so the second turn starts with a pre-turn compaction at model_auto_compact_token_limit = 1000. python3 repro.py reasoning-only makes the compaction reply a lone reasoning item; python3 repro.py message is the control.

repro.py
"""Reproduce: local compaction installs a stale assistant message when the compaction reply has none.

Runs a mock Responses provider, then two `codex exec` turns in a temporary CODEX_HOME.
Usage: python3 repro.py [reasoning-only|message]
"""
import json
import os
import subprocess
import sys
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

CODEX_BIN = os.environ.get("CODEX_BIN", "codex")
COMPACTION_MODE = sys.argv[1] if len(sys.argv) > 1 else "reasoning-only"
SNAPSHOT_TEXT = "SNAPSHOT: goal is to fix the failing test; next step is to rerun the suite."
requests_seen = []


def input_texts(request_body):
    return [
        part["text"]
        for item in request_body.get("input", [])
        if isinstance(item.get("content"), list)
        for part in item["content"]
        if "text" in part
    ]


def event(event_type, **payload):
    return f"event: {event_type}\ndata: {json.dumps({'type': event_type, **payload})}\n\n".encode()


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def do_POST(self):
        request_body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        texts = input_texts(request_body)
        is_compaction = bool(texts) and "CONTEXT CHECKPOINT COMPACTION" in texts[-1]
        requests_seen.append({"is_compaction": is_compaction, "texts": texts})
        number = len(requests_seen)

        if is_compaction and COMPACTION_MODE == "reasoning-only":
            item = {
                "type": "reasoning",
                "id": f"rs_{number}",
                "summary": [],
                "content": [{"type": "reasoning_text", "text": SNAPSHOT_TEXT}],
            }
        else:
            text = SNAPSHOT_TEXT if is_compaction else f"Assistant reply {number}."
            item = {
                "type": "message",
                "role": "assistant",
                "id": f"msg_{number}",
                "content": [{"type": "output_text", "text": text}],
            }
        # Only the first reply reports usage above the compaction limit.
        total_tokens = 50000 if number == 1 else 100
        usage = {
            "input_tokens": total_tokens,
            "input_tokens_details": {"cached_tokens": 0},
            "output_tokens": 10,
            "output_tokens_details": {"reasoning_tokens": 0},
            "total_tokens": total_tokens + 10,
        }
        self.send_response(200)
        self.send_header("Content-Type", "text/event-stream")
        self.end_headers()
        self.wfile.write(event("response.created", response={"id": f"resp_{number}"}))
        self.wfile.write(event("response.output_item.done", item=item))
        self.wfile.write(event("response.completed", response={"id": f"resp_{number}", "usage": usage}))


server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
port = server.server_address[1]

with tempfile.TemporaryDirectory() as codex_home, tempfile.TemporaryDirectory() as workdir:
    with open(os.path.join(codex_home, "config.toml"), "w") as config_file:
        config_file.write(
            f"""model = "mock-model"
model_provider = "mock"
model_auto_compact_token_limit = 1000

[model_providers.mock]
name = "mock"
base_url = "http://127.0.0.1:{port}/v1"
env_key = "MOCK_API_KEY"
wire_api = "responses"
request_max_retries = 0
stream_max_retries = 0
"""
        )
    environment = {**os.environ, "CODEX_HOME": codex_home, "MOCK_API_KEY": "dummy"}
    common = ["--skip-git-repo-check"]
    subprocess.run(
        [CODEX_BIN, "exec", *common, "First task."],
        cwd=workdir, env=environment, stdin=subprocess.DEVNULL, capture_output=True, timeout=120,
    )
    # The first reply reported 50k tokens, so the second turn starts with a pre-turn compaction.
    second = subprocess.run(
        [CODEX_BIN, "exec", "resume", "--last", *common, "Second task."],
        cwd=workdir, env=environment, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=120,
    )

print(f"compaction reply mode: {COMPACTION_MODE}")
print(f"codex exit code: {second.returncode}")
compaction_positions = [index for index, seen in enumerate(requests_seen) if seen["is_compaction"]]
if not compaction_positions:
    sys.exit("no compaction request was made")
request_after_compaction = requests_seen[compaction_positions[0] + 1]
summaries = [text for text in request_after_compaction["texts"] if text.startswith("Another language model")]
print("summary Codex carried into the next request:")
print(summaries[0].split("analysis:\n", 1)[-1] if summaries else "(none)")

Output on 0.163.0 (0.162.1 is identical):

$ python3 repro.py reasoning-only
compaction reply mode: reasoning-only
codex exit code: 0
summary Codex carried into the next request:
Assistant reply 1.

$ python3 repro.py message
compaction reply mode: message
codex exit code: 0
summary Codex carried into the next request:
SNAPSHOT: goal is to fix the failing test; next step is to rerun the suite.

With a reasoning-only compaction reply, the "summary" is Assistant reply 1., the previous turn's final message. Codex exits 0 and shows no error. I saw the same during a turn (a mid-turn compaction after a tool call: the installed summary was the earlier "Let me check the tests." narration). With model_post_turn_compact_threshold_percent = 1 the post-turn compaction is rejected instead: no compacted record is written.

What is the expected behavior?

When the compaction reply has no non-empty assistant message, local compaction should behave like the post-turn phase: fail the compaction (and retry, where it retries) instead of installing an unrelated older message as the summary. Reading only the new compaction output in every phase would do that.

Additional information

Activity

  1. added
    bug
    CLI
    context
    custom-model
    on Oct 16, 2026
  2. qianqiuwanzi commented on Oct 20, 2026

    @qianqiuwanzi

    This is the scariest failure mode: compaction that should preserve context instead bakes a stale message in as the summary, so the agent confidently runs on wrong history. We solved the same problem by keeping memory external and immutable per write. Compaction produces a new versioned entry instead of overwriting, and the agent re-reads the explicit store on resume rather than relying on whatever the runtime kept. You can audit and roll back what it remembers. (Disclosure: I work on HyperMarrow, a local desktop memory layer for agents.)

    We wrote up the design at hm.qianshi.cool.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    CLIbugcontextcustom-model

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions