Skip to content

ai/claude-cli: resume one session per conversation and share the system prompt - #981

Open
someonewithpc wants to merge 5 commits into
sashiko-dev:mainfrom
someonewithpc:claude-cli-session-resume-main
Open

someonewithpc wants to merge 5 commits into
sashiko-dev:mainfrom
someonewithpc:claude-cli-session-resume-main

Conversation

@someonewithpc

@someonewithpc someonewithpc commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

The session runner sends a conversation's whole history on every turn, and claude-cli fed that history to a new claude --print as one block of text. The block never matches the prompt cache, so every turn wrote the whole conversation to the cache again and read back only Claude Code's own system prompt. A day of reviews came to 107M tokens written to the cache against 38M read

This series makes claude-cli reuse the cache across turns and across conversations:

  • Resume one session per conversation. claude-cli keeps the Claude Code session that answered a request, keyed by a hash of the messages, the settings that shape the request and the reply. A later request whose history is that request plus its reply runs claude --resume <id> --fork-session in the same directory and sends only the new messages. A request that matches nothing kept starts a new conversation, as before. When Claude Code answers "No conversation found", which it also does for a passing overload, the backoff retries the same session once and a second failure starts over. Any other error keeps its usual class
  • Remove the transcripts. Resuming needs the transcripts that --no-session-persistence turned off, and they hold the patch under review. A session goes after an hour unused, the prompt cache's lifetime, and on exit. Nothing runs on SIGKILL or an OOM kill, so each session directory holds a lock its process keeps and carries the boot id in its name, and creating a claude-cli provider removes the directories whose owner is gone
  • Share the system prompt. Claude Code puts the working directory, the environment and the date in its system prompt, and Sashiko's system prompt went into the first user message, so no two conversations shared a cached prefix. --exclude-dynamic-system-prompt-sections moves Claude Code's changing sections out, and Sashiko's system prompt goes in a file passed with --append-system-prompt-file
  • Check the Claude Code version. These flags need Claude Code 2.1.325, and an older one fails with an unknown option error that says nothing about versions. The provider asks claude --version before its first request and stops with an error naming both versions

Measured from the proxy logs on my instance: with Opus, a resumed turn writes about 5k tokens to the cache and reads about 75k. Three kernel series reviewed before and after resume took 45% to 63% less input per review, counting cache writes at 2x and reads at 0.1x. New conversations were then about 90% of the remaining Opus cache writes, which the system prompt commits go after. With the system prompt commits, the first call of a new Opus conversation writes about 26k tokens to the cache and reads about 34k, against 66k written and 1k read before. That comes from three Sashiko self-reviews on the new build against two on the resume-only build, which reviewed different versions of these patches. Per call, input fell by about 40%

Testing:

  • Each commit passes cargo fmt and cargo clippy on the three feature profiles. cargo test passes at the tip on my machine, apart from 9 tests in reviewer and agy_cli that fail on main too
  • sashiko review --project sashiko --agent with Opus, after the fixes for sashiko-bot's v2 review: nine Low findings and nothing higher. I fixed four: a key kept again without a parent kept its old parent link, a lock test passed without taking the lock, a sweep test locked through a read-only descriptor, and the version tests couldn't tell a passed check from an unknown one. I left five: a final turn sent without tools never resumes, since the tools are part of the key, which only happens on stages that use up their turns. No end-to-end test checks transcript removal, which would need the transcripts path passed through release, forget, keep and expire. Tests leave empty session directories in /tmp. A claude --version that hangs every time holds requests for up to 30s every 10 minutes. And a claude child that outlives a SIGKILLed Sashiko can write a transcript after the sweep removed its directory
  • An earlier version of the resume commits has run on my instance since 2026-11-13

@sashiko-bot

sashiko-bot Bot commented Dec 3, 2026

Copy link
Copy Markdown

Sashiko review

Commit 1/5 — c14a06be ai/claude-cli: resume one Claude Code session per conversation

  • [MEDIUM] src/ai/claude_cli/sessions.rs: when a second resume attempt fails
    on turn 3 or later, ClaudeCliProvider::generate_content_with_binary() calls
    Sessions::forget() and restarts the conversation in a fresh SessionDir.
    Sessions::forget() removes the failed session from SessionMap without
    removing the parent session recorded in map.parents. That parent remains in
    SessionMap holding the old SessionDir and transcripts until the 1-hour idle
    timeout, and if the restarted turn fails before saving a new session, the
    next retry in Sessions::find() matches and resumes the stale parent. Remove
    the parent recorded in map.parents when forgetting a session.

  • [MEDIUM] src/ai/claude_cli.rs and src/ai/claude_cli/sessions.rs:
    ClaudeCliProvider::run_claude() and discard() mishandle transcript cleanup
    on failed resumed turns. First, discard() calls remove_transcript() without
    checking SessionMap::unshared(), so if a resumed call exits 0 with an error
    or malformed reply and reports the parent session_id before forking,
    discard() deletes the kept parent's transcript while the parent stays in
    SessionMap for retry. Second, when claude exits non-zero, run_claude()
    returns via format_cli_exit_error() before checking session_id in the JSON
    output, leaving any forked transcript on disk until the shared SessionDir
    expires. Check SessionMap::unshared() before discarding a transcript, and
    discard any unshared session_id from non-zero JSON output.

Full review and stage logs on sashiko.sashiko.dev

@someonewithpc
someonewithpc force-pushed the claude-cli-session-resume-main branch from 8756c58 to 8451bf6 Compare December 3, 2026 10:54
@someonewithpc

Copy link
Copy Markdown
Contributor Author

Both findings were valid, fixed in the first commit (now 4a2a379):

  • Sessions::forget now also drops the session recorded as the forgotten one's parent, so a retry after a failed restart starts over instead of resuming the stale parent. Test: a_forgotten_session_takes_its_parent_along
  • discard moved onto Sessions and leaves a transcript alone while a kept session has the same id, so a failed resume that reports its parent's session_id no longer deletes the transcript the retry needs. Test: a_discarded_session_keeps_a_kept_sessions_transcript
  • On a non-zero exit, run_claude now reads session_id from the JSON before returning the error and discards that session under the same rule

cargo fmt and cargo clippy on the three feature profiles pass on each commit, and cargo test passes at the tip apart from the 9 reviewer and agy_cli tests that fail on main too. The series is also rebased onto current main

@sashiko-bot

sashiko-bot Bot commented Dec 3, 2026

Copy link
Copy Markdown

Sashiko review — v2

Commit 1/5 — 4a2a3792 ai/claude-cli: resume one Claude Code session per conversation

  • [MEDIUM] src/ai/claude_cli/sessions.rs: Sessions::find() clones the session
    without marking it in-flight and does not refresh map.order. While
    ClaudeCliProvider::run_claude() runs claude --resume --fork-session, a
    concurrent keep_at() or forget() can evict the parent from map.by_key.
    SessionMap::unshared() and Sessions::discard_in() check only map.by_key, so
    release() or discard_in() unlinks the transcript while claude is reading it.
    The resume then fails with No conversation found, wasting a 30s backoff
    retry and losing prompt cache reuse. Pin active transcripts with a reference
    guard and refresh map.order in Sessions::find().

  • [LOW] src/ai/claude_cli/sessions.rs: projects_dir() accepts empty
    CLAUDE_CONFIG_DIR and HOME environment variables instead of treating them as
    unset. With CLAUDE_CONFIG_DIR="", it returns the relative path projects
    rather than falling back to HOME/.claude/projects; with HOME="" and no
    CLAUDE_CONFIG_DIR, it returns .claude/projects instead of None, bypassing
    the warning in transcripts_dir(). Because remove_logged() ignores
    ErrorKind::NotFound, transcript cleanup probes the wrong relative path and
    silently leaves patch transcripts behind. Filter both lookups with
    .filter(|v| !v.is_empty()).

  • [LOW] src/ai/claude_cli/sessions.rs: remove_session_files() drains LIVE_DIRS
    and releases the mutex before deleting directories and transcripts. In
    src/main.rs, exit_on_interrupt() spawns separate tasks for SIGINT, SIGTERM,
    and SIGHUP that each call remove_session_files() and std::process::exit().
    If a second signal arrives while the first caller is mid-cleanup, or during
    exit_dropping_sessions(), the second caller sees an empty LIVE_DIRS and
    exits immediately, leaving remaining session directories and transcripts on
    disk. Hold a cleanup mutex across the deletion loop in
    remove_session_files().

Commit 2/5 — d0abfddd ai/claude-cli: remove the sessions a killed process left behind

  • [MEDIUM] src/ai/claude_cli/sessions.rs: lock_state() opens LOCK_FILE
    read-only with File::open() before calling exclusive try_lock(), while
    take_lock() opens it writable with File::create(). On NFS and other
    filesystems that emulate flock(2) with POSIX fcntl record locks, an
    exclusive lock on a read-only descriptor fails with EBADF or EACCES.
    lock_state() maps every error to Lock::Held, and remove_orphans() skips
    Lock::Held regardless of boot id, so dead session directories and their
    transcripts leak permanently even across reboots. Open the lock file for
    writing with File::options().write(true).open(&path) instead.

  • [MEDIUM] src/ai/claude_cli/sessions.rs: remove_files() deletes root before
    the Claude Code transcripts directory. If a short-lived CLI process exits
    while the detached sweep thread in remove_orphaned_session_files() is
    running, or if the process is killed between the two removals, root is gone
    while its transcripts remain. Because remove_orphans() only sweeps rootless
    transcripts from an earlier boot, same-boot transcripts stay stranded until
    a reboot plus IDLE_LIFETIME. In addition, lock_state() drops the acquired
    lock handle before remove_files() runs, allowing two concurrent sweepers to
    race on the same directory. Remove transcripts before root, and keep the
    lock File inside Lock::Free(File) until remove_files() finishes.

  • [MEDIUM] src/ai/claude_cli/sessions.rs: remove_orphaned_session_files()
    runs remove_orphans() only once per process behind ONCE. When a host
    reboots and the daemon restarts immediately, Reviewer::new() in
    src/reviewer.rs creates the provider once at startup while pre-reboot
    transcripts are still younger than IDLE_LIFETIME (one hour). idle() returns
    false, remove_orphans() skips those transcripts, and no follow-up sweep
    ever runs until the daemon restarts. Schedule a deferred retry when
    earlier-boot transcripts are skipped only because they are not yet idle.

  • [LOW] src/ai/claude_cli/sessions.rs: SessionDir::new() creates root on disk
    before inserting it into LIVE_DIRS, so the concurrent startup sweep in
    remove_orphans() can see in_use_here(&root) as false and then call
    lock_state(&root) after take_lock() renames lock.new to lock. lock_state()
    then opens and closes a second descriptor to root/lock before the second
    in_use_here() check runs. On filesystems where flock uses per-process POSIX
    record locks, closing that descriptor drops SessionDir's lock, letting
    another Sashiko process see Lock::Free and delete the live session
    directory and transcripts mid-conversation. Check in_use_here(&root) after
    symlink_metadata() finds root/lock and before File::open().

  • [LOW] src/ai/claude_cli/sessions.rs: SessionDir::new() logs a warning when
    take_lock() fails without including crate::ai::get_log_prefix(). During
    concurrent daemon reviews, the warning cannot be attributed to a patch and
    stage. Include get_log_prefix() in the warning.

  • [LOW] src/ai/claude_cli/sessions.rs:
    tests::the_sweep_removes_only_what_a_dead_process_left() discards the
    transcripts path for old_live, the only earlier-boot, idle, still-existing
    session directory in the test. Breaking the !root.exists() guard in
    remove_orphans() would delete old_live's transcripts without failing any
    test. Keep that path and assert that it still exists.

Full review and stage logs on sashiko.sashiko.dev

The session runner sends a conversation's whole history on every turn,
and claude-cli fed it to a new claude --print as a single block of text.
That block never matches the prompt cache, so every turn wrote the whole
conversation to the cache again and read only Claude Code's own system
prompt back. In one local review of three patches, calls wrote 58k to
124k tokens each and read 2k, and a day of reviews came to 107M tokens
written against 38M read.

Keep the session that answered a request, keyed by the request's
messages and settings and by the reply it gave. A later request whose
history is that request plus the reply runs claude --resume with
--fork-session in the same directory and sends only the messages after
the reply, with the note about an XML tool call when the reply was one.
Claude Code replays the rest as separate messages, so the cache holds
everything but the new turn. Keying on the reply keeps two conversations
that sent the same request from resuming each other's session. The
session a turn continued stays until the next turn continues the new
one, so a retry of the latest turn resumes the same parent. Claude Code
reports an overload the same way as a lost session, so the first failed
resume of a session is returned as a transient error: the backoff
retries it later and resumes the same session. A request that continues
nothing, or a second failed resume, runs as a new conversation as
before.

Each conversation keeps one temporary directory, because Claude Code
looks sessions up by the directory they ran in. Resuming needs the
transcripts that --no-session-persistence turned off, so the flag goes.
Nothing says when a conversation is over, so a session idle for an hour,
the prompt cache's lifetime, is dropped: a resume would save nothing by
then. Calls look for idle sessions, and so does a task that wakes every
quarter hour and holds the sessions only weakly, so a daemon whose
claude-cli traffic stops still drops them. A forked session's transcript
holds the whole history, so the transcript of a session that leaves the
map goes as soon as no running turn resumes it, and a resumed session
moves to the back of the queue the oldest leave first from. Directories
and transcripts are removed on a blocking thread, and before the exits
that skip destructors, which include a review that ends with findings
and a command or worker that fails. A second signal during that removal
waits for it to finish. A session whose answer could not be read leaves
no turn to resume it, so its transcript goes too.

Signed-off-by: Hugo Sales <hugo@hsal.es>
A session's transcripts hold the patch under review, which is untrusted
text. Sashiko removes them on a normal exit and on the signals it
handles, but nothing runs when the process is killed with SIGKILL or by
the OOM killer, and then they stay in Claude Code's config for good.

Give each session a directory that holds its working directory and a
lock file, which the owning process holds as long as the session lives.
The kernel releases the lock however the process dies, and a lock is
seen the same from every PID namespace that shares the directory, where
a process id would name a different process or none. The directory
name also carries the start of the kernel's boot id.

When a claude-cli provider is created, remove the session directories
this user owns whose lock is free, or that have no lock and an earlier
boot made, with their transcripts. A directory whose lock cannot be
taken still runs its request, and goes after a reboot. Transcripts whose
directory is gone, as after a reboot clears /tmp, go only when the
working directory recorded in them is a session's from an earlier boot
and nothing wrote to them for an hour: Claude Code names a transcripts
directory after its working directory with every other character turned
into a dash, so the name alone could match someone else's, and a config
shared with another host holds that host's live sessions.

Transcripts from an earlier boot written to less than an hour ago, as
after a reboot and a prompt restart, get another sweep once they could
be idle. The sweep runs on a thread of its own, once per process apart
from that retry. It holds a free lock until the directory is gone, so
two sweeps do not race, and removes the transcripts before the
directory, so a sweep killed in between leaves a directory the next one
finds. It skips the directories this process still uses, checked again
once a lock file is found and before it is opened: where flock is
emulated with record locks, which belong to the process, closing a
second descriptor would release this process's own lock. The lock is
opened for writing, which an exclusive record lock needs.

Signed-off-by: Hugo Sales <hugo@hsal.es>
claude-cli passes --json-schema, which Claude Code 2.1.308 has and
older releases do not. An older one fails the first request with an
unknown option error that names the flag and not the version, and the
review stops there with nothing saying an update would fix it.

Ask claude --version before the first request. If the installed
release is older than the one the flags need, fail with a fatal error
naming both versions and the update command. A pass is kept for good. A
refusal is not, so the next request asks again and a daemon sees the
update without a restart. An answer the check cannot read, or no answer
in 30 seconds, lets requests through for ten minutes before it asks
again, so a change in the output format of claude --version does not
block reviews. Only the first 256 bytes of the answer are read. The
probe runs in a process group of its own, as requests do, and a timeout
kills the whole group, so a launcher that left a helper holding the
pipe does not leave it running.

Signed-off-by: Hugo Sales <hugo@hsal.es>
Claude Code puts the working directory, the environment and the date in
its system prompt, and every claude-cli conversation runs in a temporary
directory of its own. No two conversations share a system prompt, so a
new one reads nothing from the prompt cache and writes Claude Code's
whole system prompt again, about 12k tokens on Haiku, before any of
Sashiko's text.

--exclude-dynamic-system-prompt-sections moves those sections into the
first user message. The system prompt is then the same in every
directory, and a second conversation started elsewhere reads it from the
cache. The per-conversation directories stay as they are, since resume
still finds a session by the directory it ran in.

The flag is known to work from Claude Code 2.1.323, so the version the
provider checks for before its first request goes up to that, and the
documentation says so.

Signed-off-by: Hugo Sales <hugo@hsal.es>
claude-cli sends Sashiko's system prompt at the start of the user
message. Claude Code marks a cache breakpoint at the end of its system
prompt and on the last message only, so a new conversation never reads
that text from the cache, even when it starts with the same 35k to 45k
characters as the stage that ran before it. In a local review of one
kernel patch, 17 of 22 conversations had the same system prompt and
every one of them wrote it to the cache again.

Write the system prompt once per conversation to a file next to the
working directory and pass it with --append-system-prompt-file. A file
keeps a long prompt clear of the 128 KiB limit on one argument, and
writing it once means resumed turns that run in parallel never read a
half-written file. The working directory stays empty. The directories
and the file are made on a blocking thread, off the async runtime.
claude --help does not list the flag. It was checked with 2.1.325,
which becomes the minimum version.

On the same review with Haiku, the first calls of new conversations
wrote 632k tokens to the cache instead of 959k, and later conversations
read 24k each of Claude Code's and Sashiko's system prompts. Stages
that start together still miss, since none of them has written the
prefix yet.

Signed-off-by: Hugo Sales <hugo@hsal.es>
@someonewithpc
someonewithpc force-pushed the claude-cli-session-resume-main branch from 8451bf6 to 4f3b7b1 Compare December 3, 2026 13:06
@someonewithpc

Copy link
Copy Markdown
Contributor Author

All nine are fixed in the commits they belong to, now at 4f3b7b1:

  • Resume pins (commit 1): find() now returns the session inside a guard that counts the running turns resuming it, and moves it to the back of the eviction queue. unshared() and discard_in() treat a session a turn still resumes as in use, and the last guard to drop removes the transcript if the session has left the map by then. New test a_resumed_session_keeps_its_transcript_until_the_turn_ends forgets and discards a session mid-turn
  • Empty CLAUDE_CONFIG_DIR or HOME (commit 1): projects_dir() treats an empty value as unset, so HOME="" reaches the warning in transcripts_dir()
  • Second signal during cleanup (commit 1): remove_session_files() keeps LIVE_DIRS locked until it has removed every directory, so a second signal handler waits for it instead of finding the set empty
  • Read-only lock fd (commit 2): lock_state() opens the lock with File::options().write(true)
  • Removal order and racing sweepers (commit 2): remove_files() removes the transcripts before the root, and Lock::Free carries the locked File until remove_files() returns
  • One-shot sweep after a reboot (commit 2): remove_orphans() returns how long until the earlier-boot transcripts it skipped for not being idle could be idle, and the sweep thread sleeps that long and sweeps again. The test checks the returned wait
  • in_use_here race with record locks (commit 2): lock_state() checks in_use_here() after it finds root/lock and before it opens it. take_lock() renames the lock into place only after SessionDir::new() put the directory in LIVE_DIRS, so a named lock means the check sees it
  • Missing log prefix (commit 2): the warning carries get_log_prefix(). Commit 5 moves SessionDir::new() to a blocking thread, so it now runs there inside LOG_CONTEXT.sync_scope() with the caller's prefix
  • Unchecked old_live transcripts (commit 2): the test keeps the path and asserts the transcripts still exist

@EmbeddedAndroid

Copy link
Copy Markdown

Thanks for working on this. I fixed it the same way locally before seeing this PR. Same Linux kernel series reviewed before and after, on claude-cli with a subscription, Opus, list prices:

  • 24 patches: $705 / 140 min -> $134 / 88 min, same findings
  • 6 patches: ~$129 / 28 min -> $26 / 18 min

One more thing: on a subscription the CLI caches with the 1h TTL (2x input). FORCE_PROMPT_CACHING_5M=1 makes it 1.25x, and with resume the next turn almost always lands inside 5 min. parse_usage adds both TTLs into one number, so this doesn't show in the accounting.

Happy to run your branch and post numbers.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants