Repository navigation
ai/claude-cli: resume one session per conversation and share the system prompt - #981
someonewithpc wants to merge 5 commits into
Conversation
Sashiko reviewCommit 1/5 —
|
8756c58 to
8451bf6
Compare
|
Both findings were valid, fixed in the first commit (now 4a2a379):
|
Sashiko review — v2Commit 1/5 —
|
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>
8451bf6 to
4f3b7b1
Compare
|
All nine are fixed in the commits they belong to, now at 4f3b7b1:
|
|
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:
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. |
The session runner sends a conversation's whole history on every turn, and claude-cli fed that history to a new
claude --printas 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 readThis series makes claude-cli reuse the cache across turns and across conversations:
claude --resume <id> --fork-sessionin 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--no-session-persistenceturned 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--exclude-dynamic-system-prompt-sectionsmoves Claude Code's changing sections out, and Sashiko's system prompt goes in a file passed with--append-system-prompt-fileclaude --versionbefore its first request and stops with an error naming both versionsMeasured 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:
cargo fmtandcargo clippyon the three feature profiles.cargo testpasses at the tip on my machine, apart from 9 tests inreviewerandagy_clithat fail on main toosashiko review --project sashiko --agentwith 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 throughrelease,forget,keepandexpire. Tests leave empty session directories in/tmp. Aclaude --versionthat hangs every time holds requests for up to 30s every 10 minutes. And aclaudechild that outlives a SIGKILLed Sashiko can write a transcript after the sweep removed its directory