Skip to content

feat(offload): extract_llm_ride, a batched triage that rides the session's prompt cache - #475

Closed
OsherElhadad wants to merge 18 commits into
mainfrom
feat/extract-cache-ride
Closed

OsherElhadad wants to merge 18 commits into
mainfrom
feat/extract-cache-ride

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

What

Adds extract_llm_ride, an offload component that judges many tool outputs in one model call that reads the session's own prompt cache, and a house_ride preset that adds it to house.

The call goes to the request's own model and route. The question is appended to the body the session last sent upstream (the existing prefix asker), so the transcript is a cache read and the call pays for the instruction, a short inventory and the answer. For each candidate output the model returns one of:

  • keep
  • extract: a shorter version made of lines copied from the output
  • park: set the output aside behind a handle

Behaviour

  • Every removal is stashed behind a marker that the expand tool restores.
  • Decisions are stored per session thread and replayed byte-identically on later turns, so the session's own cache is rewritten at most once per decision. A kept output is remembered for keep_recheck_turns.
  • An extract is accepted only if it is at most extract_max_ratio of the original and at least min_verbatim of its lines occur in the original.
  • Triggers (any one fires; min_turns_between limits the rate): pending size, pending count, context-fill band, pre-expiry window. Candidates not in the stored prefix are not offered.
  • econ (default on) applies only removals that repay the cache rewrite they force within horizon_turns.
  • instruction_role: auto, user or system. A system message is sent only where the stored body ends on a user message; otherwise a user turn is sent.
  • A call that did not read the cache is recorded, discarded, and backs the session off. There is no content-copying fallback.
  • Each call is one extraction_calls row (cache read and write, fresh, output, cost, latency, accepted, rejection). strategy is ride_user or ride_system; gate_reason carries trigger, item count and instruction tokens. No schema change.

Apply modes and anchor

  • apply_mode: immediate (default) applies the answer on the turn it arrives.
  • apply_mode: cold asks while the prefix is warm and stores the answer per thread. It applies the answer on a request that rewrites the cache anyway (the entry expired, or the client compacted the transcript), or earlier when the removal is expected to repay one rewrite (early_apply). calibrated_horizon credits a removal for the expected remaining requests.
  • anchor: true (with cold mode) places a cache breakpoint on the assistant turn before the first edited tool result when an earlier request ended exactly at the preceding message and a breakpoint slot is free (cap 4, counting the client's). The prefix up to that entry is then a cache read and only the tail is rewritten.
  • The ask replays the session request's anthropic-beta header.

Changes

  • components/offload/extract_ride.go (+ tests), registered as extract_llm_ride with form fields.
  • internal/extract/ride.go: ask, parser, grounding check.
  • components.RolePrefixAsker, cheapmodel.Anthropic.CompletePrefixedAs, proxy asker AskAs: optional role for the appended message. Existing callers are unchanged.
  • house_ride preset, docs (presets table, advanced-offload).

Tests

Unit tests for parsing, grounding, apply/replay, role, trigger and cooldown, the cached-prefix boundary, the non-riding call, affordability pruning, and the commit-gate table. Checked end to end against a live gateway through a local proxy: the extraction call reads the session prefix from cache, and the next main turn is a cache hit.

Not in this PR: keep-alive scheduling (#404), summarizer changes.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Review of 475. Fresh worktree: go vet clean; go test of components, internal, config and proxy-adjacent packages passes (dash/proxy full-suite failures are the load-dependent SQLITE_BUSY flakes that also fail on origin/main). Opt-in: only the new house_ride preset and the explicitly named component use it; no existing preset changes. Attribution and privacy checks clean.

Claim check 1: the ask's request prefix is unchanged up to the last breakpoint. Holds for the request body. I wrote a throwaway test (not committed) with a body carrying model, thinking, tool_choice, system with a 1h breakpoint, tools, and a tool_result breakpoint on the last stored message, run through insertAskMessageAs for both roles: every top-level field other than messages is byte-identical, every stored message's raw JSON is identical, exactly one message is appended, and it carries no cache_control. The stored body is the forwarded body (proxy.go:1678 puts body, not preBody). CompletePrefixedAs then changes only max_tokens and removes stream, neither of which is cache key material; thinking is never touched. Caveats that no offline test can close: (a) the messages array is re-joined from raw messages, so inter-message whitespace in the stored JSON can change; the cache is keyed on rendered content, so this is harmless, but "byte-identical" is true per message, not per whole JSON text. (b) The ask sends only content-type, anthropic-version and auth; any anthropic-beta header the session sent is not forwarded. Pre-existing for the sweep's asker, but ride makes it a hot path: a session on a beta that changes the cache namespace or a 1M-context beta would not ride (or would 400). The not-ridden discard plus back-off handles the cost, but please state this in the docs and consider forwarding the stored request's anthropic-beta. (c) The live end-to-end check in the PR text is the only evidence for the cache read itself.

Claim check 2: applied decisions are replayed byte-identically. Holds. Both paths go through rideApply with the same content, stored Projected text and tryMark, and the park path through sweepDrop; the decision is keyed "ride:"+ContentKey in the session store. TestRideDecisionsAreFrozenAndReplayedByteIdentically compares message text of both an extract and a park across turns and checks no second ask, and it fails if the replay text differs. Limit: the guarantee lasts only while the store entry lives; on eviction the original returns and the cache busts once (same as the sweep).

Findings (all non-blocking)

  1. prefixask.go: AskAs was inserted between CoversSpan's doc comment and CoversSpan, so that comment now documents AskAs and CoversSpan has none. Move AskAs above the comment.
  2. config.go (~line 704): the house_ride comment and preset were inserted in the middle of the housellm block; housellm's long comment now sits above house_ride. Move house_ride above that comment.
  3. extract.GroundedExtract exempts every line starting with "SUMMARY:", but the contract allows one first line. A reply with many SUMMARY: lines passes grounding with ungrounded content. Exempt only the first line.
  4. BuildRideAsk puts each candidate's head line (tool output text, truncated, single line) into the instruction, which under role=system is an operator-role message. Low impact since the model already reads the output, but a crafted first line can address the triage. Consider stripping "[" and quote characters from Head or sending it as JSON-escaped.
  5. ask(): any error (timeout, 429) sets ridden=false and backs off 15 turns, same as a full-price miss. Probably intended; say so in the field hint, or limit the 15-turn back-off to ride_not_cache_read.
  6. Add the prefix-unchanged test above to the PR (I can send the file); it is the only test that would fail if someone changes insertAskMessageAs to rewrite or reorder stored messages.

@OsherElhadad OsherElhadad added the ready-to-merge Program PR approved by the reviewer, CI green; needs maintainer approval label Oct 12, 2026
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Review follow-ups pushed (3 commits on the branch).

  • anthropic-beta: the stash now keeps the session request's anthropic-beta header and both Ask and AskAs replay it unchanged (empty when the session had none). Tests: TestCompletePrefixedForwardsTheSessionBeta (cheapmodel), TestPrefixAskReplaysTheSessionsBetaHeader (proxy, through the stash). Docs note added.
  • Comment placement in prefixask.go and config.go fixed.
  • SUMMARY: exemption applies to the first line only.
  • Candidate head lines are neutralised (brackets, quotes, backticks) before entering the instruction.
  • The 15-turn back-off now applies only to calls that completed without reading the cache; other failures keep the ordinary cooldown (hint and docs say so).
  • Added TestInsertAskMessagePreservesStoredPrefix (fields other than messages, each stored message and the cache_control marker unchanged; one message appended without cache_control, both roles).

Test status (host under heavy load, load average above 25): go test of components/..., config, internal/..., cmd/... passes. The full ./proxy package run fails on two tests, TestTheRepairChargesTheRestoredTokensOnce and TestFeedbackMailCannotInjectHeaders; both pass when run alone, and the reviewer saw the same load-dependent failures on origin/main. An earlier full run also hit two dashboard-emitter timing tests that pass alone.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Re-review of 4e3d052 (3 new commits). All six findings are addressed: AskAs and house_ride are now above the right comments, the SUMMARY: exemption is first-line only, head lines are neutralised (brackets, quotes, newlines), the 15-turn back-off applies only to a completed call that did not read the cache, the stored session's anthropic-beta header is replayed on the ask, and prefix-unchanged tests cover both roles. gofmt, vet and the components, internal and config tests are clean; the beta and role tests pass.

Notes, not blocking: (1) the beta replay changes Ask for every existing caller of the prefix asker (sweep, summarizer), not only ride; the PR text says existing callers are unchanged, please correct that line. (2) The two proxy tests you named (TestTheRepairChargesTheRestoredTokensOnce, TestFeedbackMailCannotInjectHeaders) pass in isolation on both this branch and origin/main; their failures in the full suite are load-dependent and are not touched by this diff.

Keeping ready-to-merge.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Re-review of 5757801 (the ride anchor, apply modes and economic gate added since my first approval, plus the TTL fixes). Checked: the anchor now takes the TTL of the last mark in prompt order (computed by apply from the raw body, tools then system then messages) and is skipped when the request is a one-hour tier and the last mark cannot be read; the wire test TestRideAnchorKeepsTheTTLOrderWhenTheClientAsksForOneHour covers all-1h, system-1h/last-5m and all-5m clients and asserts no 1h mark follows a 5m mark, at most four breakpoints and an anchor with the expected TTL. I confirmed it fails when the TTL line is neutralised (turn 11, 1h after 5m), and passes as pushed. Entry validity is now an exact span hash over every message field plus the 270 s limit, and entries are forgotten on a cold request. gofmt and vet clean; tests for apply, components, internal, config and the proxy ride/prefix/ask tests pass; attribution clean. One residual, not blocking: a client that places a 1h mark in the middle of the transcript after a 5m last mark would still see the 5m anchor before it; Claude Code does not mark mid-history, but if you want it airtight take the minimum TTL over all marks after the anchor position instead of the last mark only. Approved; ready-to-merge restored.

@OsherElhadad OsherElhadad added the ready-to-merge Program PR approved by the reviewer, CI green; needs maintainer approval label Oct 12, 2026
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Re-review of 53e020d (four commits since 5757801: entry hash made representation-independent, force_apply, research scripts removed from the PR, mixed-tier rule plus tokenizer-unit gate costs). gofmt and vet clean; tests for apply, components, internal, config pass; attribution clean; the removed replay scripts are gone from the diff. The anchor TTL now follows the message marks' tier (all-1h gives 1h, all-5m gives 5m, mixed gives no anchor, otherwise the last mark), and the entry hash ignores string versus one-block representation while still covering tool calls and non-text parts.

Two notes, neither blocking. (1) The two new mid-transcript wire cases do not discriminate: with the mixed-tier guard in anchorAt neutralised the test still passes, also when I moved the mid-transcript 1h mark to after the anchor position (the mark sits on the first message in the test, before any possible anchor, so a 5m anchor is valid there anyway). The guard is conservative and harmless, but the claim 'mixed tiers: no anchor' is not pinned by a test; build a case where the 1h mark follows the anchor position and assert that the anchor is absent, or drop the guard. (2) force_apply is described as an analysis knob that applies every held decision whatever it costs; it is opt-in but it is a spend switch in production config. Either keep it out of the form fields (settable only in YAML) or say in the hint that it is for offline replay only. Approved; ready-to-merge stays.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Re-review of e887e84. Both notes are addressed: TestRideAnchorIsAbsentWhenAOneHourMarkFollowsItsPosition fails when the mixed-tier guard is neutralised (turn 11: 1h after 5m on the wire) and passes as pushed, with a control row that must anchor; the force_apply hint now says offline replay only. gofmt, vet and the apply, components and config tests pass. ready-to-merge stays.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review (APPROVE) at e887e84, delta since 53e020d. (Posted as a comment: GitHub does not allow approving from the author account.)

  • The new wire test pins the mixed-tier guard: it passes as pushed, and fails at turn 11 ("a 1h mark follows a 5m mark on the wire") when the guard is disabled. Both earlier non-blocking notes are addressed (the force_apply hint now says offline replay only).
  • gofmt clean, go vet clean on apply and components/offload. go test ./... passes; two timing-sensitive tests (proxy dashboard latency budget, one components/offload run) failed once under host load and passed on rerun; neither file is touched by this PR.
  • Commit is by Osher-Elhadad with a sign-off and no extra trailers.

Approved. Not merging.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: APPROVE at 60cbab0. (Posted as a comment: GitHub does not let the author account approve.)

  • Merge d27a4c5. It had no conflicts. 60cbab0 only adds the new beta argument ("") to two s.put calls in proxy/thread_test.go. The code otherwise matches e887e84, which I approved earlier.
  • Checks. gofmt and go vet are clean. go test passes for ./apply, ./components/offload, ./config and ./proxy. CI is green. It merges cleanly with #474 and #500.
  • Attribution. The merge commit d27a4c5 has no Signed-off-by line; DCO passes, and a squash merge with an explicit subject and body produces a signed-off commit anyway. The other commits are signed off with no AI attribution.

Osher-Elhadad added 14 commits October 15, 2026 11:06
…ion's prompt cache

Adds extract_llm_ride and the house_ride preset. One call per firing turn asks the
request's own model, over the cached prefix the session last sent, to keep, extract or
park each candidate tool output. Removals stay behind expand markers and decisions are
frozen and replayed byte-identically. Triggers: pending size, pending count, context
fill, pre-expiry. The instruction goes as a mid-conversation system message on models
that accept it, else a user turn; a call that did not read the cache is discarded.

Signed-off-by: Osher-Elhadad <[email protected]>
…view follow-ups

Forward the stored request's anthropic-beta header on prefix asks, sanitise candidate head
lines in the instruction, limit the 15-turn back-off to calls that completed without reading
the cache, and add prefix-unchanged and beta-forwarding tests.

Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>
…request or when the rewrite is repaid

Signed-off-by: Osher-Elhadad <[email protected]>
… test with cachesplit in the pipeline

Signed-off-by: Osher-Elhadad <[email protected]>
… system prompt and tools

Signed-off-by: Osher-Elhadad <[email protected]>
…alidity by prefix hash over all message fields; forget entries after a cold request

Signed-off-by: Osher-Elhadad <[email protected]>
…ever represented, plus every non-text part)

Signed-off-by: Osher-Elhadad <[email protected]>
Osher-Elhadad added 4 commits October 15, 2026 11:06
…tiers: no anchor); gate costs in tokenizer units only

Signed-off-by: Osher-Elhadad <[email protected]>
…position; mark force_apply offline-only

The new wire case places a one-hour mark on a tool result after where the anchor would sit (one system mark, so a slot is free) and fails when the mixed-tier guard in anchorAt is removed. The force_apply hint now says it is for offline replay only.

Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad
OsherElhadad force-pushed the feat/extract-cache-ride branch from 60cbab0 to 6d81c41 Compare October 15, 2026 11:16

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-check: APPROVE at 6d81c41. Rebased onto today's main as a linear series, and git range-diff shows all 18 commits identical to the approved 60cbab0's. The s.put arity fix that lived in the old merge commit is no longer needed, or is carried by the rebase: build-test compiles and passes. The old unsigned merge commit d27a4c5 is gone. CI is green. This approval covers 6d81c41.

@amiddavid

Copy link
Copy Markdown
Collaborator

Closing: main already has the same mechanism.

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

Labels

ready-to-merge Program PR approved by the reviewer, CI green; needs maintainer approval

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants