store

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 5 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

both hosts (bifrost proxy, sidecar 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

View Source
const (
	FrozenPrefix = "cg:frz:" // mask / failed_run freeze decisions
	ResultPrefix = "cg:res:" // extract_llm's replayed result (projection + summary, one key)
	// SweepKeepPrefix records that extract_llm_sweep's adjudicator judged a specific output STILL
	// NEEDED, and at what point in the conversation it said so.
	//
	// A SEPARATE NAMESPACE, not ResultPrefix, and the reason is a property of that one: a cg:res:
	// record holds a PROJECTION, and getResult treats an empty projection as absent so that half a
	// decision can never be spliced. A keep has no projection by definition — nothing is replaced —
	// so storing keeps there would either be discarded on read or would weaken that guard for
	// everyone. Different fact, different key.
	SweepKeepPrefix = "cg:swk:" // extract_llm_sweep: "the adjudicator said keep, at turn N"
	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
	// SumPrefix is summarize's per-session checkpoint: the exact summary text, the span it
	// covers, and that span's hash.
	//
	// PINNED ONLY SINCE summarize's TRIGGER GAINED A CACHE-STATE CONDITION, because that changed
	// what losing it costs. While the trigger was a size threshold, a lost checkpoint meant
	// summarize re-paid its model call and rolled a new one forward — money, not correctness, and
	// the reason this namespace sat unpinned. The trigger now declines on most turns by design,
	// and the checkpoint is the ONLY thing keeping those turns in the summarized shape. Losing it
	// makes the next gated turn send the transcript FULL, diverging from the bytes the provider
	// cached at the first summarized message and re-writing the whole suffix at 1.25x fresh.
	// That is cache-destructive, which is this list's entry criterion.
	SumPrefix = "cg:sum:"
	// BilledPrefix is the provider's own billed input-token count for this session's PREVIOUS
	// turn: fresh input + cache reads + cache writes, as the provider reported them.
	//
	// It exists because a fraction of the context window cannot be evaluated against
	// schema.MessagesTokens. That counts message TEXT only — no system prompt, no tool
	// declarations, no JSON envelope — while a context window is stated in the units the
	// provider bills. Measured on this deployment's uncompacted traffic the two differ by a
	// median 3.38x (p25 2.43, p90 6.80; see dash/overview.go's EstimatorDivergence), so
	// `MessagesTokens >= 0.9 * window` demands roughly three times the window's worth of
	// transcript and never becomes true at all. This is the numerator in the DENOMINATOR's
	// units, which is the only way that comparison is meaningful.
	//
	// PINNED, for the same reason SumPrefix is. summarize's default trigger declines when this
	// is absent (an unknown fill must not be guessed at), so losing the key does not merely
	// cost a re-measurement — it turns the component off until the next response writes it
	// back, and the turns in between send the transcript full.
	//
	// Written on the RESPONSE path, read on the request path, so it is always the previous
	// turn's figure. That is a deliberate one-turn lag rather than an estimate: a transcript
	// only grows, so the previous turn is a sound lower bound on this one, and a gate that
	// fires one turn late is the safe direction.
	BilledPrefix = "cg:bin:"
	// UsagePrefix is model usage a DETACHED summarizer call incurred, waiting to be attributed to
	// this session's next turn.
	//
	// summarize produces its summary off the hot path, so the goroutine finishes after the
	// request that started it has been answered and its row written — leaving that row's
	// cg_llm_cost_usd at 0 while the money was genuinely spent. The compaction-episode panel
	// charges that spend as a debit, so losing it makes the panel overstate its own saving.
	//
	// PINNED, like SumPrefix and BilledPrefix: losing it loses a cost figure permanently, and a
	// savings measurement missing its costs is worse than one that is simply absent.
	UsagePrefix = "cg:use:"
)

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.

View Source
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.

View Source
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.

View Source
const DefaultStashTTL = 1800 * time.Second

DefaultStashTTL is how long a REWIND PAYLOAD lives: 1800s, a fifth of DefaultTTL.

The two namespaces have genuinely different horizons, and giving them one TTL is what made a saturated reserve hold for ~2.8h after the busy period that filled it (#190). A slot was released only by the TTL, the store is one process-wide instance, and while the reserve is saturated every new removal is refused for every session at once — so savings fell to zero long after the load that caused it was gone.

WHAT MAKES THE SHORT HORIZON SAFE is that a payload, unlike a frozen decision, is RE-DERIVABLE from the request in flight:

  • A frozen decision is the replacement bytes the provider ALREADY CACHED. Nothing else holds them; losing one flips an already-cached message and re-writes the suffix at ~11.5x the read price. It needs to survive a whole long-horizon task, idle gaps included, which is what DefaultTTL is sized for.
  • A payload is a copy of content the AGENT RE-SENDS every turn. The replay path calls components/offload.commitRefresh, which PutStashes the payload again from the message text it just read. So a live marker's payload has its expiry slid every turn, and one already reclaimed is RE-CREATED on the REQUEST path, before the request goes upstream and therefore before any expand call in the response could ask for it.

The horizon a payload actually needs is one INTER-TURN GAP, not one session. 1800s is the value DefaultTTL's own comment records as too short for a frozen decision (headroom's CCR store) — reused here, in the one namespace whose horizon it does fit, rather than invented.

WHICH OFFLOADERS ACTUALLY DO THAT, because an earlier version of this comment said "every offloader on every turn" and that quantifier is false in two ways with different consequences:

  • The reapplyFrozen family (mask, cmdfilter, collapse, failed_run, skeleton, readlifecycle, agentdiet) does behave as described: the replay runs on every turn regardless of the cache-tail gate, because it must, or the message reverts full→compacted→full.
  • summarize and extract_llm have GATES AHEAD of their replay phase — summarize returns at summarize.go:157 on its trigger and at :162/:165 when no model client resolves, both before tryReuse; extract_llm returns at extract_llm.go:659 on no_goal_keywords, before Phase 1. A skipped turn refreshes none of their payloads. summarize's trigger skip is RECURRING rather than a one-off, because the agent's own compaction shrinks the incoming request and can drop it back under Trigger.MinRequestTokens for several consecutive turns; "the cheap model is down" likewise persists for many turns by nature. A skipped component splices nothing, so no marker of its goes upstream on those turns and no marker dangles — the payload's reclamation is harmless while the skip lasts, and the exposure is only that its next firing may find the payload gone and the reserve full at the same moment.
  • dedup, extract, linecap and smartcrush have NO replay path at all (no reapplyFrozen and no commitRefresh). They redo the transformation from the re-sent original every turn, so their per-turn write goes through the REFUSABLE commitMark. While the payload is live that lands in PutStash's refresh branch and is retained unconditionally; once reclaimed it is a NEW stash, and a new stash into a saturated reserve is refused, the component declines, and the message goes upstream verbatim after earlier turns sent it compacted. So for these four the outcome is stash_refused PLUS a representation flip, not stash_missing — and stash_refused's operator-facing text promises "nothing became irreversible", which is true about reversibility and silent about the cache-write actually paid. Reachable at 10,000s too, so not introduced here; this horizon shortens the distance to it by 5.5x.

The residual exposure, stated rather than waved at: a turn that runs NO pipeline performs no refresh (an x-context-guru-bypass request, or the agent-compaction bypass), so a long unbroken run of bypassed turns could outlive a payload while its marker is still live in the transcript. Both are single-request events in practice. On the reapplyFrozen family the outcome is then the already-reported one — stash_missing on the next replay — not a silent loss, and stash_revived is what says whether reclamation is being absorbed as designed.

View Source
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

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 EffectiveStashTTLSeconds added in v0.2.0

func EffectiveStashTTLSeconds(o Options) int

EffectiveStashTTLSeconds is the payload horizon a store built from these Options will ACTUALLY use, in seconds — the default filled in and the ttl_seconds cap applied.

It exists so the config surface cannot drift from the store. /config published the configured value, so `stash_ttl_seconds: 20000` with `ttl_seconds: 10000` displayed 20000 on the dashboard while the store used 10000 — a silent divergence between what an operator is told and what runs, which is the shape #200 is about, in the config surface instead of the metrics one. Derived from the same code path NewMemory uses rather than re-implemented, so the two cannot disagree.

func IdleExitFloor added in v0.1.1

func IdleExitFloor(o Options) time.Duration

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 Peek added in v0.2.0

func Peek(s Store, key string) bool

Peek reports whether key is live, without touching it. A store without the capability falls back to Get, which is the answer the caller wanted at the cost of the side effects it wanted to avoid — the same direction every other optional capability degrades in.

func PutStash added in v0.1.1

func PutStash(s Store, key string, payload []byte) bool

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

func StashRoom(s Store, size int) bool

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

func ValidateIdleExit(d time.Duration, o Options) error

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

func NewMemory(o Options) *Memory

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

func (m *Memory) FrozenLossStats() (dropped, repaired int64)

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

func (m *Memory) FrozenLost(key string) bool

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) Get

func (m *Memory) Get(key string) ([]byte, bool)

func (*Memory) MarkSticky

func (m *Memory) MarkSticky(session, id string)

func (*Memory) Peek added in v0.2.0

func (m *Memory) Peek(key string) bool

Peek reports whether key is live without sliding its TTL or reordering the LRU. See Peeker.

It deliberately does NOT remove an entry it finds expired, unlike Get. Removing would make a read-only probe mutate the store's accounting — including stash_expired and the reserve's byte total — from a caller that only asked a question. The sweep reclaims it at the normal time.

func (*Memory) Persists

func (*Memory) Persists() bool

func (*Memory) Put

func (m *Memory) Put(key string, payload []byte)

func (*Memory) PutStash added in v0.1.1

func (m *Memory) PutStash(key string, payload []byte) bool

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

func (m *Memory) SetClock(now func() time.Time)

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

func (m *Memory) StashRoom(size int) bool

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

func (m *Memory) StashStats() StashStat

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

func (m *Memory) StashedKeysForTest() []string

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.

func (*Memory) Sticky

func (m *Memory) Sticky(session string) map[string]struct{}

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) Get

func (Nop) Get(string) ([]byte, bool)

func (Nop) MarkSticky

func (Nop) MarkSticky(string, string)

func (Nop) Persists

func (Nop) Persists() bool

func (Nop) Put

func (Nop) Put(string, []byte)

func (Nop) PutStash added in v0.1.1

func (Nop) PutStash(string, []byte) bool

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.

func (Nop) StashRoom added in v0.1.1

func (Nop) StashRoom(int) bool

StashRoom is false for the same reason PutStash is: there is nowhere to put a payload, so a caller about to pay a model call for content this store would have to back should not.

func (Nop) Sticky

func (Nop) Sticky(string) map[string]struct{}

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"`
	// StashTTLSeconds is the REWIND PAYLOADS' own entry lifetime, shorter than TTLSeconds.
	// Zero => DefaultStashTTL. Capped at TTLSeconds, since a payload outliving the decision that
	// names it is a reserve slot held for almost nothing. Report it through
	// EffectiveStashTTLSeconds, never raw: the cap is applied silently, and publishing the
	// configured value while the store uses another is the same silent divergence #200 is about.
	// See DefaultStashTTL for why the two namespaces do not want the same horizon.
	StashTTLSeconds int `yaml:"stash_ttl_seconds"`
	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

func (o Options) EffectiveTTL() time.Duration

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 Peeker added in v0.2.0

type Peeker interface {
	// Peek reports whether key is present and unexpired, without sliding the TTL or reordering
	// the LRU. It never resurrects an expired entry, and never removes one either — expiry is
	// still enforced where it always was.
	Peek(key string) bool
}

Peeker is an OPTIONAL Store capability: asking whether a key is live WITHOUT touching it.

It exists because Get is not a read-only operation on this store. Get slides the TTL and moves the entry to the front of the LRU, which is right for a caller that is about to USE the value and wrong for one that only wants to know a fact about it. A DIAGNOSTIC that renews an entry's lifetime is making a resource decision by accident — and for the pinned namespaces it is not even a cheap one: pinned entries count against the shared exempt budget (exemptRoom), so a pin that no longer expires is pressure on the rewind reserve.

The case that motivated it: components/offload.reapplyFrozen asks whether a frozen decision exists purely to decide whether abandoning it costs a cache-write (see ExpandPrefixFlips). It has already decided NOT to replay that decision, so renewing it is the opposite of what the answer means.

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
	// Revived counts payloads WRITTEN AGAIN under a key the TTL had reclaimed — a replay
	// re-derived the payload from the transcript before its marker went upstream, so the
	// reclamation cost nothing. It is the half of Expired that is benign, split out for the same
	// reason stash_refused and stash_missing are: Expired alone reports both "the reserve
	// released a payload nobody wanted" and "an outstanding marker just lost its payload", and
	// those call for opposite responses (nothing vs. raise stash_ttl_seconds).
	//
	// Read it as a RATE against Expired. Revived tracking Expired means the shorter payload
	// horizon is being absorbed as designed; Expired climbing while Revived stays flat means
	// payloads are being reclaimed from sessions that then never came back — also fine, that is
	// the reclamation this exists to do — and the outcome to alert on is neither of these but
	// stash_missing, which is what a reclamation that was NOT absorbed produces.
	Revived 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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL