claude-code icon indicating copy to clipboard operation
claude-code copied to clipboard

[BUG] Resume sends the # Environment system message empty, so the whole history misses the prompt cache (2.1.326)

Open jullduxster opened this issue 2 weeks ago • 2 comments

Summary

On resume, Claude Code sends the system-role message that carries the # Environment section with no text. Request 1 of the session sent that message with the full section, and it holds a cache breakpoint. So every resumed request differs from messages[1] on: the prompt cache is read only through messages[0], and the whole conversation history after it is written again as cache_creation.

Environment

  • Claude Code 2.1.326 (Claude Desktop, Code tab), Windows 10, model claude-opus-5-5
  • Seen in Desktop sessions; CLI --resume not checked

What the transcript's request records show

The session transcript's api-request / api-request-blob records hold what was sent:

  • Request 1 of a new session: messages[0] is the user message. messages[1] is a system-role message (with output_config.effort) whose single text block is the # Environment section ("You have been invoked in the following environment: ..."; about 11.8k characters here, mostly the additional working directories). cacheControl puts a 1h breakpoint at messages[1].content[0].
  • First request after a resume (a new process): messages[0] is byte-identical, but messages[1] is the system-role message with output_config only and no content.
  • The transcript keeps the environment only as a structured environment attachment (snapshot: workingDirectory, isWorktree, isGitRepo, additionalWorkingDirectories, ...), not as the rendered text. The resume does not re-render it.

Impact

Cache use on the first request after a resume, three sessions on 2026-11-18:

Session Last request before the resume First request after the resume
A read 48,907 read 34,170, wrote 34,828
B read 50,718 read 34,170, wrote 16,651
C (tiny history) read 39,107 read 34,227, wrote 10,441

The read stops at the same boundary every time: the shared prefix through messages[0]. Everything after it is rewritten, so the cost of a resume grows with the length of the conversation. The resumed model also seems to run without its environment section (working directory, platform, extra folders); I inferred that from the empty message and did not test it.

Steps to reproduce

  1. Start a new session and send one prompt; wait for the reply.
  2. End the session's process (in Desktop: archive the session, then unarchive it; in the CLI, presumably quit and claude --resume).
  3. Send another prompt.
  4. Compare the usage of the two replies, and the messages[1] blob of the two api-request records in the transcript.

Expected

The resumed request re-sends the # Environment message byte-identical to request 1 (re-rendered from the stored snapshot, or persisted as sent), so the cached prefix still matches. If the environment really changed, a new environment message is expected, but not an empty one.

Related

  • #67497 and #43657 (closed): resume cache invalidation through system blocks scattered out of messages[0]. This is a separate cause: the environment message's content is dropped.

jullduxster avatar Nov 18 '26 05:11 jullduxster

Clean reproduction (Claude Desktop, Code tab, Claude Code 2.1.326, Windows 10):

  1. New session, one prompt ("Reply with the single word: ok"); wait for the reply.
  2. Archive the session (ends its process), unarchive it, send a second one-word prompt (the reply runs as a resume).
  3. Run the checker below on the session's transcript (~/.claude/projects/<project>/<session-id>.jsonl).

Output (requests 41 s apart):

2026-11-18T05:12:27.900Z  messages=2  Environment text 11834 chars  ->  cache read 39107, wrote 0
2026-11-18T05:13:09.064Z  messages=5  Environment message EMPTY  ->  cache read 34227, wrote 10134

The resumed request re-sends messages[0] byte-identical, but messages[1] (the system-role message that held the # Environment section) has no content, so the cache read stops right after messages[0] and the rest is written again. On longer sessions this rewrite is the whole history (34,828 tokens in one of the sessions in the report above).

Checker: it reads the transcript's api-request / api-request-blob records and prints, for each full request, whether messages[1] carries the Environment text and the cache usage of its reply.

from __future__ import annotations

import json
import sys
from pathlib import Path


def main(argv: list[str]) -> int:
    if len(argv) != 1:
        print("usage: resume_env_check.py TRANSCRIPT.jsonl")
        return 2
    records: list[dict[str, object]] = []
    for line in Path(argv[0]).read_text(encoding="utf-8").splitlines():
        try:
            rec = json.loads(line)
        except json.JSONDecodeError:
            continue
        if isinstance(rec, dict):
            records.append(rec)
    blobs: dict[str, dict[str, object]] = {}
    for rec in records:
        msg = rec.get("message")
        if rec.get("type") == "api-request-blob" and isinstance(rec.get("hash"), str) and isinstance(msg, dict):
            blobs[str(rec["hash"])] = msg
    pending: str | None = None
    for rec in records:
        kind = rec.get("type")
        if kind == "api-request":
            tail = rec.get("tail")
            if not isinstance(tail, list) or len(tail) < 2:
                pending = None  # an incremental request: messages[1] is not re-sent in this record
                continue
            second = blobs.get(str(tail[1]), {})
            if second.get("role") != "system":
                pending = None  # not a full re-send starting with the user message and the Environment message
                continue
            texts = [b.get("text", "") for b in second.get("content", []) if isinstance(b, dict) and b.get("type") == "text"]  # type: ignore[union-attr] -- parsed JSON
            env = next((t for t in texts if isinstance(t, str) and t.startswith("# Environment")), None)
            state = f"Environment text {len(env)} chars" if env is not None else "Environment message EMPTY"
            pending = f"{rec.get('timestamp')}  messages={len(tail)}  {state}"
        elif kind == "assistant" and pending is not None:
            msg = rec.get("message")
            usage = msg.get("usage") if isinstance(msg, dict) else None
            if isinstance(usage, dict):
                print(f"{pending}  ->  cache read {usage.get('cache_read_input_tokens')}, wrote {usage.get('cache_creation_input_tokens')}")
                pending = None
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))

jullduxster avatar Nov 18 '26 05:11 jullduxster

Correction: this report is wrong, and I'm closing it.

The resumed messages[1] is not empty. It is sent as a string (11,651 characters) where request 1 sent a list with one text block (11,834 characters), and the checker in my comment above read only list-shaped content, so it printed "EMPTY". With string content handled, the resumed message carries the whole # Environment block.

The only text difference between the two is a few tool names missing from the deferred-tools listing. A local plugin of mine had substituted those names into request 1's listing. The transcript keeps the engine's own listing, so the resume re-renders the unsubstituted text and the prefix differs from there. That is my plugin's behaviour, not a Claude Code bug.

One thing I have not ruled out is whether the change of shape alone (one-block list on request 1, plain string on resume) changes the cached prefix. If I can show that on its own, I'll file it separately.

Sorry for the noise.

jullduxster avatar Nov 18 '26 05:11 jullduxster