Documentation
¶
Overview ¶
Package store holds context-guru's cross-call state behind one interface so both hosts (bifrost proxy, AuthBridge plugin) share it. v1 ships an in-memory TTL+LRU backend; SQLite/Redis slot in behind the same interface when a durable or multi-replica deployment is real (see the design doc, D5).
It carries three things keyed by session:
- Rewind: cache_key -> original bytes, so Offload components are reversible (the expand(id) tool loop resolves originals from here).
- Sticky: the set of content ids already reduced on prior turns, so a component can keep its output byte-stable across turns (cache stability).
- per-session token/metric rollups (added with metrics in P0/P5).
Index ¶
- Constants
- Variables
- func IdleExitFloor(o Options) time.Duration
- func PutStash(s Store, key string, payload []byte) bool
- func StashRoom(s Store, size int) bool
- func ValidateIdleExit(d time.Duration, o Options) error
- type FrozenLoser
- type Memory
- func (m *Memory) DisableSlidingTTLForTest()
- func (m *Memory) FrozenLossStats() (dropped, repaired int64)
- func (m *Memory) FrozenLost(key string) bool
- func (m *Memory) Get(key string) ([]byte, bool)
- func (m *Memory) MarkSticky(session, id string)
- func (*Memory) Persists() bool
- func (m *Memory) Put(key string, payload []byte)
- func (m *Memory) PutStash(key string, payload []byte) bool
- func (m *Memory) SetClock(now func() time.Time)
- func (m *Memory) StashRoom(size int) bool
- func (m *Memory) StashStats() StashStat
- func (m *Memory) StashedKeysForTest() []string
- func (m *Memory) Sticky(session string) map[string]struct{}
- type Nop
- type Options
- type StashStat
- type Stasher
- type Store
Constants ¶
const ( FrozenPrefix = "cg:frz:" // mask / failed_run freeze decisions ResultPrefix = "cg:res:" // extract_llm's replayed result (projection + summary, one key) LenPrefix = "cg:len:" // apply's prev-turn message count (the MaxCachedIdx boundary) // XResultPrefix is extract_llm's CROSS-session result namespace. Pinned for the same // reason ResultPrefix is: every entry is a model call already paid for, and the store's // default cap is 1,000 entries shared with the unpinned expand stashes — which are the // large payloads, so they evict the cheap keys that would have avoided a call. XResultPrefix = "cg:xres:" // TTLPrefix and SeenPrefix are apply's two cold-decision records. Losing either makes a // WARM prefix read cold, which is the cache-destructive direction: TTLPrefix narrows a // session that asked for the 1h tier back to 5m, and SeenPrefix drops the evidence that // another session id touched the same content-keyed entry. Both are refreshed on every // turn, so the sliding TTL keeps an active session's records alive; the pin is only // against LRU pressure from a busy proxy. TTLPrefix = "cg:ttl:" // longest cache lifetime this session has ever asked for SeenPrefix = "cg:seen:" // last activity under a content-derived session id )
Key namespaces whose entries are a component's FROZEN decision — the replacement text it must replay on every later turn to keep an already-cached message byte-identical (see components/offload/state.go), plus the small per-session trackers the cache-safety machinery itself depends on.
Entries under these prefixes are PINNED: exempt from LRU eviction, because losing one is not a cache miss, it is a cache-DESTRUCTIVE event — the message flips representation inside the provider's cached prefix and the whole suffix is re-written at 11.5x the read price. They are small (a marker line, a compacted projection, an integer), still honor the sliding TTL, and the exemption is capped at half the entry cap so a pathological session can never pin the whole cache.
The prefixes are declared by their OWNERS (components/offload, apply) and passed in via Options.PinPrefixes — the store must not know what a component names its keys.
The rewind stashes are NOT in this list and never can be (their keys are bare marker ids — see Stasher), which used to mean they were "fully evictable". That was the bug in #187: this cache kept "that output was dropped" while evicting "here is what it was", so the reversibility guarantee degraded exactly as the pipeline removed more. They now have their own reserve, claimed through PutStash and bounded by stashCap.
const DefaultMaxEntries = 5000
DefaultMaxEntries is the store's default entry cap.
It was 1,000, and that was the quantity #187 was measured against: ONE process-wide store serves every concurrent session (cmd/context-guru-proxy builds it once), and each reversible removal writes FIVE entries — the payload, cg:own:, cg:xseen:, and two pinned decision records (cg:res:, cg:xres:). So a 1,000-entry cache held roughly 1/5 of half its slots' worth of payloads while the decisions naming them were pinned, and iteration 024's arm B — hundreds of removals across eight concurrent workers — overran it by an order of magnitude. 5,000 puts the cap in the same order as the observed volume; PutStash's refusal is what makes overrunning it visible rather than silent, so this number does not have to be right, only sane.
Entry count is a PROXY for memory, and a poor one for the payloads: pinned decisions and the bookkeeping flags are tiny, a stashed payload is a whole tool output. That is why the reserve carries its own BYTE budget (DefaultStashMaxBytes) rather than leaving max_entries to mean two unrelated things — this constant now bounds only how many entries the cache tracks, and stash_max_bytes bounds what they cost.
const DefaultStashMaxBytes = 256 << 20
DefaultStashMaxBytes bounds the rewind reserve's memory: 256 MiB.
The arithmetic it comes from, so an operator can redo it with their own numbers: the reserve holds at most stashCap() = max_entries/2 = 2,500 payloads, and a payload is one tool output. Real agent traffic in this repo's own corpus runs tens of kilobytes per output (the measured examples in extract_llm's comments are a 26k-token access log and a ~7k-token file read), so 2,500 × ~100 KB ≈ 250 MB is the entry cap's worth at the large end of ordinary. 256 MiB is therefore the point where the two budgets bind at roughly the same time for ordinary payloads — and the byte budget binds FIRST, as it should, for a workload whose outputs are bigger than that.
It is sane rather than measured, exactly like max_entries, and for the same reason: what makes a wrong value safe is that overrunning it REFUSES removals and says so (stash_refused), instead of quietly making them irreversible.
const DefaultTTL = 10000 * time.Second
DefaultTTL is the store's default (sliding) entry lifetime. Terminal-Bench tasks averaged 1975s of wall clock and run up to 4h, so the old 1800s default expired live frozen decisions mid-task; ~2.8h covers a long-horizon task's idle gaps (test suites, training runs) with the sliding refresh doing the rest.
Variables ¶
var DefaultPinPrefixes = []string{FrozenPrefix, ResultPrefix, LenPrefix, XResultPrefix, TTLPrefix, SeenPrefix}
DefaultPinPrefixes is the shipped set of key namespaces whose loss is cache-destructive. Callers that build their own Store may pass a different set; the zero value means "none", so a host that opts out simply gets plain TTL+LRU.
Functions ¶
func IdleExitFloor ¶ added in v0.1.1
IdleExitFloor is the shortest idle-exit threshold that is not destructive.
Process exit WIPES this store: rewind stashes, frozen decisions, `cg:len:`. A frozen decision that dies mid-session is the 11.5x cache-WRITE regression that FrozenLost exists to detect — the session's next turn re-creates the whole prefix at write prices instead of reading it. So an idle-exit threshold shorter than the store's own entry lifetime turns a convenience feature into a cost regression that looks like the proxy misbehaving.
2x the TTL, with a 1h absolute floor. Twice, not once, because the TTL is a SLIDING window: an entry touched just before the idle clock started still has a full TTL ahead of it, so 1x can expire live state. The 1h term covers a config that sets a tiny ttl_seconds (a test rig, or an operator trimming memory) where 2x would collapse to seconds and the threshold would be shorter than the keep-alive's own ping window.
With the default TTL of 10000s the floor is ~5h34m, so the installer's 24h default clears it comfortably; a 30-minute threshold is refused at startup rather than documented.
func PutStash ¶ added in v0.1.1
PutStash writes a rewind payload through the Stasher capability when the store has it, and reports whether the payload is retained. A store without the capability keeps the legacy behavior: an ordinary Put, reported as retained.
func StashRoom ¶ added in v0.1.1
StashRoom reports whether a new payload of size bytes would be admitted. A store without the Stasher capability has no reserve to exhaust, so it always has room — the same direction PutStash degrades in.
func ValidateIdleExit ¶ added in v0.1.1
ValidateIdleExit checks an idle-exit threshold against IdleExitFloor. Zero or negative means the watchdog is off, which is always valid — a gateway or eval-containers deployment must never self-terminate, so off is the default and the only way to a self-killing proxy is to ask for one.
The message says WHICH of the floor's two terms produced the number, and offers only remediations that actually lower it. An earlier version did neither: it credited the floor to "2x the store's entry lifetime" even when the 1h term was the binding one (with ttl_seconds: 30 it printed a 1h floor attributed to 2x30s), and it advised raising ttl_seconds — which raises the floor, so an operator who followed it got the same refusal with a larger number. Startup-fatal messages are the only evidence anyone gathers, so being exactly right here matters more than it looks.
Types ¶
type FrozenLoser ¶ added in v0.1.1
type FrozenLoser interface {
// FrozenLost reports whether a frozen entry under key existed and was dropped.
FrozenLost(key string) bool
}
FrozenLoser is an OPTIONAL Store capability: reporting that a frozen decision under key was dropped (TTL expiry / pin cap) rather than never taken. A bare Get miss cannot tell those apart, and they call for opposite behavior — "never frozen" means obey the tail gate, "was frozen, now lost" means re-derive the same bytes so the cached prefix does not flip. Stores that don't implement it degrade to the legacy indistinguishable behavior.
type Memory ¶
type Memory struct {
// contains filtered or unexported fields
}
Memory is an in-memory Store: a TTL+LRU cache for rewind payloads plus a bounded per-session sticky-id set. The TTL is SLIDING (refreshed on Get), and the default (DefaultTTL) is sized past a long-horizon agent task rather than mirroring headroom's 1800s CCR store: a frozen compaction that dies mid-task is a cache-destructive event, not a saving.
func NewMemory ¶
NewMemory builds an in-memory store. Zero/negative option fields fall back to defaults (DefaultTTL, DefaultMaxEntries, 100 sessions of sticky sets).
func (*Memory) DisableSlidingTTLForTest ¶ added in v0.1.1
func (m *Memory) DisableSlidingTTLForTest()
DisableSlidingTTLForTest restores the old write-only expiry (and un-pins frozen entries) so a test can measure what the previous behavior cost. For TESTS only.
func (*Memory) FrozenLossStats ¶ added in v0.1.1
FrozenLossStats returns how many frozen decisions this store has DROPPED since start (TTL expiry, or eviction) and how many of those were later re-Put — restored to the store, so a replay can land again instead of the message flipping.
Counted per DROP EVENT, not per distinct key: one key that expires, is re-frozen, and expires again contributes 2 drops and 1 repair. That is the intended reading — each event is a separate opportunity for a flip — but it means dropped−repaired is a running balance (marks still outstanding), not a total of distinct broken keys. A repeat drop of an already-marked key is not double-counted while its mark is outstanding.
func (*Memory) FrozenLost ¶ added in v0.1.1
FrozenLost reports whether a frozen entry under key existed and was dropped (TTL expiry or the pin cap) — the "was frozen, now lost" signal. See FrozenLoser.
func (*Memory) MarkSticky ¶
func (*Memory) PutStash ¶ added in v0.1.1
PutStash stores a rewind payload under its marker key and reports whether it is retained. See Stasher for why the store cannot recognise these keys on its own, and why the boolean is the point.
The policy, and the property it is chosen for: a live stash is NEVER evicted to make room for a new one. Under the old plain-Put behavior the guarantee decayed as the pipeline succeeded — every extra removal both consumed a slot and added a pinned decision, so more compaction meant more BROKEN promises. Refusing instead moves that pressure onto the removals not yet made: promises already outstanding stay good however long the run gets, and the mechanism declines new work rather than doing it irreversibly. Capacity becomes a configured quantity (max_entries) and exhaustion becomes a counter, in exchange for reversibility no longer being load-dependent.
func (*Memory) SetClock ¶ added in v0.1.1
SetClock replaces the store's time source. For TESTS only — TTL behavior over a multi-hour agent session is not testable in real time, and the freeze lifetime is exactly what this store gets wrong when it's wrong.
func (*Memory) StashRoom ¶ added in v0.1.1
StashRoom reports whether a NEW payload of size bytes would be admitted right now: a free entry slot under both the reserve cap and the shared exempt budget, and enough of the byte budget left. It reclaims what the TTL has released first, exactly as PutStash does, so the answer is not stale — a probe that said "full" on the strength of payloads that expired hours ago would skip work the store would in fact have taken.
It claims nothing. See Stasher.StashRoom for why a probe exists at all.
func (*Memory) StashStats ¶ added in v0.1.1
StashStats reports the rewind reserve against both of its budgets.
Refused is the operator-facing number, and it is deliberately upstream of expand_unresolved_missing: that counter only moves when the AGENT asks for content and is told it is gone, so a run could exhaust the reserve for an hour and read as healthy until something happened to request an expand. This one moves at the moment the budget binds.
Reading Live/Capacity against Bytes/MaxBytes is what tells an operator WHICH budget bound, and so which knob to turn: entries near capacity with bytes far from the budget means raise max_entries; the reverse means raise stash_max_bytes (or reduce what the pipeline removes).
func (*Memory) StashedKeysForTest ¶ added in v0.1.1
StashedKeysForTest lists the keys the reserve currently holds. For TESTS only: a test that needs to act on a specific payload cannot recompute its key without duplicating the component's hashing, and a duplicate would pass while the real key drifted.
type Nop ¶
type Nop struct{}
Nop is a Store that persists nothing: Put discards, Get/Sticky always miss. Used when the store is disabled — the expand loop resolves nothing and lossy offloads become irreversible, which is why they must use marker_mode: off.
func (Nop) MarkSticky ¶
func (Nop) PutStash ¶ added in v0.1.1
PutStash retains nothing, so it reports nothing retained. Reachable only if a caller skips effectiveMode (which already degrades a full marker to off when !Persists()), and the answer is the same either way: do not advertise reversibility.
type Options ¶
type Options struct {
// Enabled toggles the state store. nil/absent => on (backward-compatible).
// false => no store: reversibility is off, so offload components must run
// marker_mode: off (a full-marker offload would leave dangling markers).
Enabled *bool `yaml:"enabled"`
TTLSeconds int `yaml:"ttl_seconds"`
// PinPrefixes are key namespaces whose entries are exempt from LRU eviction because
// losing one is cache-destructive rather than merely a miss (see FrozenPrefix). nil =>
// DefaultPinPrefixes. Not a yaml knob: it is a code-level property of the key layout,
// not something an operator should be tuning.
PinPrefixes []string `yaml:"-"`
MaxEntries int `yaml:"max_entries"`
// StashMaxBytes caps the rewind reserve in BYTES. Zero => DefaultStashMaxBytes. See
// Memory.stashBytes for why this namespace is budgeted in bytes and the rest in entries.
StashMaxBytes int64 `yaml:"stash_max_bytes"`
MaxSessions int `yaml:"max_sessions"`
}
Options configures a Memory store; the zero value yields sane defaults. yaml tags let it drop straight into the config file's store: block.
func (Options) EffectiveTTL ¶ added in v0.1.1
EffectiveTTL is the entry lifetime this Options actually yields, defaulting included.
Exported and used by NewMemory itself rather than duplicated, because a second copy of "zero means DefaultTTL" is exactly the drift that would matter: IdleExitFloor sizes a process's whole lifetime off this number, and a floor computed from a different default than the store runs with is a floor that protects nothing.
type StashStat ¶ added in v0.1.1
type StashStat struct {
Live int // payloads held right now
Capacity int // the reserve's entry cap (stashCap)
Bytes int64 // what those payloads cost
MaxBytes int64 // the reserve's byte budget
// Refused counts payloads PutStash DECLINED — removals not made, rather than removals
// made irreversibly. Expired counts payloads the TTL reclaimed, which is the only way a
// stash leaves now that LRU pressure cannot evict one.
Refused int64
Expired int64
}
StashStat is the rewind reserve's state, reported as a struct because the reserve now has two budgets and returning six positional values invites the caller to mix them up.
type Stasher ¶ added in v0.1.1
type Stasher interface {
// PutStash stores a rewind payload under key and reports whether it is now retained.
// Refreshing a payload already present always succeeds — a live entry must never be
// refused, or a replay of an already-stamped marker would flip that message's bytes.
PutStash(key string, payload []byte) bool
// StashRoom reports whether a NEW payload of size bytes would be admitted right now.
// It is a probe, not a reservation: it claims nothing, and a PutStash after it can
// still refuse (another goroutine took the slot). It exists for the one caller shape
// that cannot recover from a refusal cheaply — a component that must PAY A MODEL CALL
// to produce the text whose marker the payload backs. summarize's call was measured at
// ~57k prompt tokens, and under a saturated reserve it was paid and thrown away on
// every turn. Asking first turns that into a skip.
StashRoom(size int) bool
}
Stasher is an OPTIONAL Store capability: writing a REWIND PAYLOAD — the original bytes behind a <<cg:HASH>> marker — under its own reserved budget, and reporting whether the payload was actually retained.
It exists because a rewind payload cannot be recognised from its key. The pin namespaces below all carry a "cg:" prefix, but a stash key IS the marker id: a bare lowercase-hex content hash the model reads out of the request and hands back to the expand tool (see expand.Marker). Prefixing it would rewrite every marker's bytes, and marker bytes sit inside the provider's cached prefix — so the only way for the store to tell a payload from any other entry is for the writer to say so. That is this method.
The RETURN VALUE is the load-bearing half. Before it, a payload was written with Put and then evicted as the least-recently-used entry of a cache whose pinned half held the DECISIONS referring to it, so a removal advertised as reversible (a marker was stamped) became irreversible with nothing reported — issue #187. false now means "this payload is NOT stored", and the caller's contract is to not advertise reversibility: refuse the removal and leave the content verbatim. See components/offload.commitMark.
Stores that do not implement it degrade to the legacy behavior (Put, always "retained"), which is why writers go through the PutStash helper rather than asserting at each site.
type Store ¶
type Store interface {
// Put stashes an original payload under key with the store's default TTL.
Put(key string, payload []byte)
// Get returns a stashed payload; ok=false if absent or expired.
Get(key string) (payload []byte, ok bool)
// Sticky returns the per-session set of already-reduced content ids.
Sticky(session string) map[string]struct{}
// MarkSticky records that id was reduced in this session.
MarkSticky(session, id string)
// Persists reports whether Put actually retains payloads. false (the Nop
// store) means offloads cannot be made reversible, so a full marker_mode must
// degrade to an irreversible drop rather than leave an unresolvable marker.
Persists() bool
}
Store is the interface components and adapters depend on. Implementations must be safe for concurrent use — one instance serves all requests.