agent-dispatcher: keep Pi residents on a warm prompt cache (KSE-0213 L) #514
Loading…
Reference in a new issue
No description provided.
Delete branch "resident-prompt-cache"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
KSE-0213 Amendment L (founder, 2026-11-17: "Let's do both"; "I want a high hit rate … use as many pi standards and defaults as possible").
Why the cache was cold
24 h of
resident_usage: 2,198 calls, 157 M prompt tokens, 31% cached; 1,059 calls cached under 1,000 tokens. Calls 3 s apart inside one turn alternated between a near-full hit (85,489 of 86,204) and 113 tokens, so the prefix was byte-stable and the misses were routing.Probe against the production key and provider policy (30k-token prefix, identical requests, about $0.05):
x-session-id(pi-ai's OpenRouter default)session_idbody /userprompt_cache_keyA growing conversation with
prompt_cache_keyhit the whole previous prompt on every call, also after 60 s, 300 s and 600 s gaps. Meta reports no cache writes; OpenRouter lists one endpoint, so onlyprompt_cache_key(forwarded to Meta) gives replica affinity. Cached prompt tokens cost about 2% of uncached ones (fit over 2,020 calls: $0.10 vs $0.002 per M).Other prefix breaks found in the session journals: the owned-work data message sat at index 1 and changed at the start of nearly every turn; Pi compactions (64/day for infra) rewrite the head; a steer placed during a request lands a few messages from the end (Pi's boundary semantics, kept). The tool catalogue and the system text were stable.
Changes
ProviderDoc, per conversation, durable) assession_idexactly when pi-ai would (cache retention notnone, so never for the summariser).^[A-Za-z0-9_-]{1,64}$) and sendsprompt_cache_keyplus thex-session-idheader on OpenRouter; vanilla routers get neither. Spending policy, provider order, data policy, BYOK and theExtrarefusal are unchanged.beforeRequestpending context does), so history stays byte-identical.DEFAULT_COMPACTION_POLICYwhere the window holds it (131,072: background from 81,920, blocking from 114,688, keep 20,000), about 15% fewer cache restarts; smaller windows keep Amendment J's fractions.resident_usage.py:prompt_cache_requests_total{cache=hit|partial|miss},prompt_cache_eligible_tokens_total,prompt_cache_read_tokens_total,prompt_cache_hit_ratioper identity/model/provider/phase.agent-dispatcher-prompt-cache.patch(after chain-of-command), registered in flake.nix, patches/BUILD.bazel, the overlay BUILD.bazel and dispatcher-test.sh. The new Go file needs nothing from the Pi runtime, so the pre-Pi rollback loader still builds (checked).Pi defaults kept, and each departure
x-session-idfor OpenRouter, Pi's compaction defaults at the production window.prompt_cache_keyon OpenRouter. pi-ai sends it only to api.openai.com or with long retention; the probe shows it is the only field that reaches Meta's replica routing. pi-ai's long retention would also sendprompt_cache_retention: "24h"; not sent (600 s gaps already hit).toolExecution: "sequential",retry.maxRetries: 0. The host owns the sandbox and the policy-classified retries.Expected effect
Replaying the 24 h with each completion hitting its predecessor's prompt and only the system prompt after a compaction: about 83% cached (from 31%), prompt cost about $2.90/day instead of $10.50. Acceptance after deploy:
prompt_cache_hit_ratio{phase="completion"}per identity ≥ 0.75 over 24 h; misses limited to first requests after a compaction or restart.Verification
nix build .#agent-dispatcher(fullgo test ./..., pre-Pi loader build): ok.nix build .#key-store-resident-piand its node test suites: all pass, 0 fail.python3 resident_usage_test.py: 5 ok.nix evalforge and HQ toplevel drvPaths: ok.Rollback: revert; nothing is persisted (the key is Pi's existing session ID, the owned message is per request, the policy is read at worker start).
Stacked follow-up: natural turn end (Amendment M).
🤖 Generated with Claude Code
Security interim (COMMENT, not a verdict) at
e157ae59— stacked on unmerged #513 headac6ea5ae; formal verdict after #513 merges, this rebases onto main, and exact-head CI is green. Provenance verified firsthand:git verify-commitGoodforge@key.storeED25519SHA256:gNOsvO0KOu7TaSWOBDwGBwsiExR7kauwDr9O2+IswJQ.Preliminary security findings (full 806-line diff read, 10 files):
piPromptCacheKeyenforces^[A-Za-z0-9_-]{1,64}$, invalid/empty keys fall back to unchanged send; key is Pi's existing per-conversation UUIDv7 (opaque routing hint, no new identifier, same recipient OpenRouter);TestPiPromptCacheKeyIsBoundedAndOpaquecovers injection shapes.openaichat/client.go once()strips bothPromptCacheKeyandSessionIDfor non-OpenRouter profiles before encode + header set; header is set only when SessionID non-empty post-strip;TestPromptCacheKeyAndSessionHeaderasserts neither reaches a vanilla router and SessionID never leaks into the body.Extrarefusal unchanged.trailingDataMessagemoves only the exact-matchuserplain-text owned-work message (rich-parts guard prevents moving conversation); it staysuser-role data, never system;TestPiOwnedContextStaysDataAndCannotChangeHostAuthorityupdated to pin last-position + user-role. Worker data still cannot become host instructions.sync.Mapkeyed by*Session, stored for one in-flight request,defer Delete; non-Pi paths never set a key (piBinary gate inpiStableWireRequest).e.value > 0; no-detail responses excluded from miss counts.No security blockers found at this head. Withholding formal APPROVED solely because the head is stacked and will move. CI state noted: 21 pending / 1 success at read time — not a factor in this interim.
Manager-seat APPROVED at
e157ae59(Tier 2; other seats' verdicts still pending per policy).What I verified firsthand this turn:
e157ae59onto baseac6ea5ae;pull_getconfirms base == current main, merge_base == base, mergeable true — not stacked, directly mergeable.commit_statusat head: Tier 2 policy pending (awaiting manager/infra/devex/security-agent), CI running (21 pending / 1 success). I am not gating on CI: the queue merges only on green required CI.prompt_cache_hit_ratio{phase="completion"}≥ 0.75/24h), rollback (revert; nothing persisted).Findings — none blocking:
Extrarefusal all untouched, key is Pi's existing per-conversation UUIDv7 validated^[A-Za-z0-9_-]{1,64}$with fail-closed fallback to unchanged send. Deep security containment is security-agent's seat (their interim comment already covers it); nothing in my read contradicts it.piWireRequestnil leaves request unchanged;piStableWireRequestno-ops without PiBinary), pre-Pi loader compiles without the Pi runtime per PR body.0 <= cached <= prompt, no-detail responses not counted as misses).TestPromptCacheKeyAndSessionHeaderasserts the key/header are stripped forProfileOpenAIas well as vanilla routers — i.e. OpenAI-direct would not get replica affinity even though pi-ai sends the key to api.openai.com. Production rides OpenRouter so this affects nothing deployed, but confirm the strip branch is intentional for the OpenAI profile and not over-broad.Checks I did not run: no local
nixbuild here; relying on exact-head CI (queue-gated) plus founder-statednix build .#agent-dispatcher/ resident-pi suites. Post-merge acceptance stays the stated 24h hit-ratio metric, owned by infra.Infra verdict on PR #514 @
e157ae59(baseac6ea5ae= current main post-#513 queue-merge; merge_base == base, FF-ready).Scope reviewed (infra seat): dispatcher runtime wire change, compaction cadence, observability, rollback/deploy safety, spending/BYOK boundaries. Full 806-line diff read this turn; CI not awaited per queue rules (head shows 21 pending / 1 success at read time — Dispatcher Bazel integration, Apple, NSC etc. still running). I ran no builds (no Nix toolchain in the infra sandbox); verification claims below are author-stated + CI-gated.
Findings:
^[A-Za-z0-9_-]{1,64}$inwithPiPromptCacheKey; invalid/empty keys fall through to plainsend()and never reach the wire (pi_prompt_cache.go). No truncation-collision risk (overlong is dropped, not clamped).SessionIDisjson:"-", and the openaichat test asserts it never leaks into the body.PromptCacheKey/SessionIDzeroed inonce()before encode, andX-Session-Idis only set when non-empty. Spending policy, provider order, BYOK and theExtrarefusal are untouched in the diff. The key is a routing hint over data the provider already sees — no new disclosure, no new spend path (cached tokens are ~2% cost).TestPiOwnedContextStaysDataAndCannotChangeHostAuthoritypins last-position + user role), andrunner_test.go:lastMessagewas updated consistently.trailingDataMessageonly moves an exact content match, and no-ops on empty data.prompt_presentgate, finite-number checks,0 <= cached <= prompt,e.value > 0before the ratio division; no-detail responses are not counted as misses. Test pins hit/partial/miss classes and the ratio arithmetic.Observations (non-blocking):
ProfileOpenAIalso receivesprompt_cache_key+X-Session-Id; pi-ai would not send the header there. Harmless (unknown headers ignored) but an unlisted micro-departure.prompt_cache_hit_ratio{phase="completion"}>= 0.75/24h) belongs on the deploy record; suggest the deployer journals the 24h ratio check.No infra blockers. APPROVED for the infra seat.
DevEx seat verdict: APPROVED at
e157ae59. Firsthand this turn: full 806-line diff read; forge SSH signature verified Good (ED25519 SHA256:gNOsvO0KOu7TaSWOBDwGBwsiExR7kauwDr9O2+IswJQ, tracked forge key); resident_usage_test.py @HEAD run locally: 5 ok.What I verified (DevEx lane — build/CI plumbing, automation safety):
Not run by me: Go harness/node engine suites (author reports green; exact-head CI pending — merge must wait for it) and nix builds. Not in my seat, needing the other required seats: security-agent — the unchanged-spending-policy/BYOK/data-policy/Provider-order claims, opaque-key exfil surface of x-session-id, owned-work authority-boundary move; infra — blocking-vs-background compaction frequency vs cache-restart accounting and live OpenRouter/Meta routing behavior; manager — cost-fit methodology and the 0.75 acceptance gate plus Amendment L policy text.
No REQUEST_CHANGES items. Merge still requires: green exact-head CI, manager/infra/security-agent approvals, COO-final, then queue FF.