Skip to content

perf(session): reuse the provider's prompt cache across a project's sessions - #1066

Merged
Aayam Bansal (aayambansal) merged 8 commits into
mainfrom
performance/kv-caching
Nov 15, 2026
Merged

Aayam Bansal (aayambansal) merged 8 commits into
mainfrom
performance/kv-caching

Conversation

@KB-syntheticsciences

Copy link
Copy Markdown
Collaborator

What does this PR do, and why?

A new session got no prompt-cache reuse from the model provider on its first call. The system prompt carried per-session details (session ID, working or scratch folder, connected folders, budget, checks), so its bytes differed between sessions, and the provider's cache missed on everything after them, tool definitions included.

This PR keeps the system prompt and tool definitions identical across a project's sessions and moves the session's own facts into a labelled <session-context> block on the first message.

  • Rules stay in the system prompt; facts move out. Anything the agent must obey stays in the system prompt: environment rules, and harness rules through a new env.lines rules output. SystemPrompt.environment() now returns { rules, session }.
  • The block is sent once, as first built. It is stored in SessionTraceStore.sessionContext (sent, latest, head). Later prompts resend the stored copy, so the cached prefix doesn't move.
  • Changes are announced, not rewritten. When session details change mid-chat (a folder connected, a different time budget), a durable harness message says "Session details changed. These replace the ones at the start of the conversation:" followed by the new details.
  • Compaction. After compaction the details are refreshed and anchored to the first user message after the summary.
  • Restart fix found on the way. Acceptance checks and named deliverables stated in the first request were silently lost when the local server restarted. They are now re-read from the first request (harness/first-request.ts).

Measured with real prompts:

  • A new Claude session in the same project reads about 14,600 cached tokens on its first call, instead of none.
  • Managed DeepSeek new sessions were 98% cached in 2 of 3 runs.
  • Qwen and Kimi were already about 99% cached without explicit cache markers. Gemini markers cost about 15% more, so no markers were added for those models.
  • Time to first token barely changes at around 15K tokens of prompt. The gain is mostly cost.

Linked issue

Performance work, no issue.

How did you verify it?

  • Deep CI on the branch: run 43678139575, green. Attempt 1 hit a known-flaky Windows test (util/lock-coordination.test.ts).
  • Locally on Bun 1.3.14: format and typecheck pass; UI 399, workspace 1300, SDK 31 and docs 10 tests pass. Backend session, tool and agent tests: 1625 pass. The 63 failures are environment-only (sandbox and kernel) and identical on main.
  • Live runs comparing cache reads per call before and after, on Claude, DeepSeek, Qwen, Kimi and Gemini, using the session database's token counts.
  • Behaviour checks: the agent follows rules from the system prompt, acknowledges session facts from the block, and picks up the "Session details changed" note.

Checklist

  • bun run check: format, typecheck, UI, workspace, SDK and docs tests locally; backend through deep CI
  • ./tooling/repo/generate.ts not needed (no server route changes)
  • CHANGELOG.md has an Unreleased entry
  • Docs: docs/notes/opencode-core-for-science.md updated
  • No version bumps

Providers cache a prompt only up to its first difference. The <env> block
names the session (its ID, scratch folder, connected folders, budget) and
sat ~4K tokens into the system prompt, so a new session re-read everything
after it: the rest of the system prompt and, for chat templates that render
tools after the system text (DeepSeek, Qwen, Kimi via OpenRouter), all ~9K
tokens of tool definitions. Claude's only system cache marker sat after it,
so a new Claude session reused nothing.

The environment is now joined to the start of the first user message
(SystemPrompt.withEnvironment), keeping a plain-text message a plain string.
The system prompt and tools are byte-identical across a project's sessions;
the environment is rebuilt the same each step, so a session's own prefix
stays stable. Compaction's shared path carries the same environment to keep
its prefix, and the context estimate still counts it.

Measured on the captured request (same provider): a new session's first call
reused 0-24% of the prompt with the old layout and 99% with the session
lines in the user message (DeepSeek); Claude reused nothing before.
…session facts

The previous commit moved the whole <env> block, rules included, into the
first user message as plain text. Rules there carry less weight than system
instructions, and nothing marked them as coming from OpenScience.

SystemPrompt.environment now returns two parts. The system prompt keeps the
rules and project facts: model, project, access mode, platform, date and
knowledge cutoff, and the rules about folders, Results and paths, plus a line
telling the agent that this session's details arrive in a <session-context>
block from OpenScience, not from the user. That block, on the first user
message, carries only the session's facts: Session ID, working folder or
scratch, connected folders and the harness env lines. It is not a
<system-reminder>, which stays reserved for harness instructions in the
system prompt (enforced by the delegation and native-provider tests).

Checked with real prompts on Claude Haiku, Kimi K3 and DeepSeek flash: no
path leak in a greeting, the real session ID and folder when asked, the
access mode stated correctly, and new files in Session scratch as the rules
say (DeepSeek: 10/14 vs 7/14 before the move; it is inconsistent either way).
New sessions in one project read ~14.6K cached tokens on their first call.
…onment parts

Review findings on the environment split:

- The budget, acceptance and deliverables lines carried instructions ("keep
  improving it", "must pass", "produce anything else the request asks for")
  and sat in the session block on the user message. The env.lines hook now
  has a `rules` output: each unit puts its figures in `lines` (session
  block) and the instruction about them in `rules` (system prompt), the
  latter only when the unit is active.
- SystemPrompt.environment returns a named { rules, session } instead of a
  positional pair, and takes the units' { lines, rules }; withEnvironment is
  now withSessionContext, and compaction's remembered field sessionContext,
  since they carry only the session's facts.
- Stale test title and comments ("compute stays in <env>") and the <env>
  fixture in the helper tests now match the <session-context> block.
The <session-context> block was rebuilt on every request from state that
changes during a session (connected folders, a new deadline), so a change
silently rewrote the first user message: the agent's earliest message
changed under it and the whole conversation was re-read uncached.

The block as first built is now kept per session (SessionTraceStore
sessionContext.sent) and always sent on the first user message, so the
cached prefix never changes. When a freshly built block differs from the
last one told, it is told once as a durable harness message ("Session
details changed. These replace the ones at the start of the conversation:")
and recorded as latest, the same way a change in the offered tools is
announced (Toolset.notice).
…a restart

HarnessState lives in memory. The acceptance contract and the deliverables
are read only from the session's first request, in that message's hook, so
a process that restarted mid-session never read them again: their session
details, their rules and their end-of-turn checks silently disappeared.

Each unit now marks its state seeded, from the first request's own hook as
before or, failing that, from the stored transcript the first time its
env.lines or loop.before_finish hook runs (firstRequest: the first user
message with text the person typed; none for a worker), like the cost unit
reseeds spend.
The block on the first user message is kept as first sent, and a later
change is told once as a durable notice. Compaction replaces the head that
block rode, and may summarize the notice away, so the conversation would
again start with the original details (an old folder list or budget).

The kept block now records the message it rides (head). When the request's
first user message is a different one, as after compaction, the current
details are recorded and sent; the new prefix is written fresh anyway. The
summary request itself still rides the turn's own block, so its prefix is
unchanged.
@vercel

vercel Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
openscience Ready Ready Preview Nov 15, 2026 4:54pm UTC

Request Review

# Conflicts:
#	CHANGELOG.md
#	backend/cli/src/session/prompt.ts
@aayambansal
Aayam Bansal (aayambansal) merged commit 40d8e07 into main Nov 15, 2026
10 checks passed
@KB-syntheticsciences
KB (KB-syntheticsciences) deleted the performance/kv-caching branch November 15, 2026 17:27

This branch was successfully deployed

1 active deployment
Preview — ad3a26ea Deployed Nov 15, 2026 by vercel[bot]
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