Documentation
¶
Overview ¶
Package cache is a bbolt content-hash cache: identical (task+input+params+ model+grammar) requests return the stored result and skip the model entirely.
Why the handle is lazy (register D-05, 0.121.1) ¶
bbolt takes an EXCLUSIVE file lock for the whole life of a read-write handle, and every harness process used to grab that lock while CONSTRUCTING its pipeline — before knowing whether it would ever run a cacheable task. With one MCP server per session (14 measured 2026-08-25, 21 live 2026-09-14) exactly one process won the primary and every other one immediately created a 32 KB per-process sibling it then never wrote a single entry into: 49 sibling files on the workstation at ~12/h, swept only after 12 h.
The fix is not a lock-free store or a daemon in front of it — it is to stop opening a file nobody asked for. A Cache is now a handle that resolves on FIRST USE; a process that never runs a cacheable task never touches the cache directory at all. What remains:
- Get/Put resolve the handle once, with a short lock Timeout so a held primary costs milliseconds rather than a second.
- Pure-read surfaces take a READ-ONLY handle (NewReader), which never creates a file: not the primary, not a sibling. See resolveReaderLocked for the bbolt locking semantics that force the read-through design.
- A sibling that turns out to be empty is deleted on Close, and a non-empty one makes one bounded attempt to promote its entries into the primary, so a session's work is not stranded in a file nobody else reads.
Index ¶
- Constants
- Variables
- func Key(parts ...string) string
- func SiblingStats(path string) (count int, bytes int64)
- type Cache
- func (c *Cache) Close() error
- func (c *Cache) Configured() string
- func (c *Cache) Count() (int, error)
- func (c *Cache) Fallback() bool
- func (c *Cache) Get(key string) ([]byte, bool)
- func (c *Cache) Mode() Mode
- func (c *Cache) OpenErr() error
- func (c *Cache) Path() string
- func (c *Cache) Put(key string, val []byte) error
- func (c *Cache) WithNotify(f func(mode Mode, path string, err error)) *Cache
- type Mode
Constants ¶
const ( PromotionMaxKeys = 1000 PromotionMaxDuration = 5 * time.Second )
PromotionMaxKeys and PromotionMaxDuration bound the one promotion attempt a non-empty sibling makes on Close. Process exit is not the place for an unbounded copy: a sibling that has accumulated more than this keeps its surplus and is swept on age like any other.
const LockTimeout = 250 * time.Millisecond
LockTimeout is how long an open waits for bbolt's file lock before giving up.
Deliberately short (it was 1 s): with a lazy handle the only opens left are ones that will really use the cache, and a process that has lost the race should reach its sibling — or, for a reader, its miss — in milliseconds rather than stalling a tool call for a second per attempt. bbolt retries the lock every flockRetryTimeout (50 ms), so this is still four or five attempts.
const SiblingMaxAge = time.Hour
SiblingMaxAge is how old a per-process sibling may be before the sweep removes it. Pids are reused on both Windows and Linux, so liveness cannot say whether a sibling's owner is gone — age can.
0.121.1: 12 h -> 1 h. The long window existed to protect a long-lived MCP server's sibling, and that protection is not what keeps a live sibling alive: a sibling a process still holds cannot be removed on Windows (the sweep tolerates EBUSY/EPERM), and on Linux the unlink merely detaches the directory entry while the holder keeps working — and keeps its entries, since Close promotes from the open descriptor, not from the name.
Variables ¶
var ErrEmptyKey = errors.New("cache: empty key")
ErrEmptyKey is what Put answers for an empty key. Key never returns one, so an empty key means "this call has no key": the pipeline uses it to say that a call must not be cached (its params could not be keyed). Put refuses it, so no empty key is ever stored and Get("") is a miss.
var ErrReadOnly = errors.New("cache: handle is read-only")
ErrReadOnly is returned by Put on a handle built with NewReader. A read-only surface that tries to write is a wiring mistake, and the whole point of the read-only path is that it never creates a sibling — so this fails loudly rather than silently opening one.
Functions ¶
func Key ¶
Key derives a stable cache key from the given parts. Distinct part lists give distinct keys: the list [a b] never collides with the single part "a<sep>b" for any separator a caller's text can contain.
The preimage is keyDomain followed by, for each part in order, the part's byte length as an 8-byte big-endian integer and then the part's bytes. A length prefix is self-delimiting, so no byte inside a part can be read as the boundary between two parts, and the empty list, one empty part and two empty parts each have a different preimage. The result is the hex SHA-256 of it.
Why not a separator: the first encoding joined the parts with "\x00", so Key("a", "b") was Key("a\x00b"). One part is arbitrary model input, and a request that forges a boundary could be served another request's cached result. A separator cannot fix that for text that may contain any byte; lengths can.
Changing the encoding changed every key once: entries written under the old one are never looked up again, and the store has no eviction, so they stay in the file as dead weight. The cache is an accelerator, so the only effect of the upgrade is one cold start.
A caller must pass each ingredient as its own part and never build one part by gluing fields together with a separator of its own, which would recreate the same ambiguity one level up. (The one deliberate exception is the video media identity in internal/pipeline: a file digest and numbers glued with "|", none of it caller text.)
func SiblingStats ¶ added in v0.206.0
SiblingStats reports how many per-process siblings of path exist on disk and how many bytes they occupy, INCLUDING this process's own. It is the number the D-05 regression is measured in, so offload_status publishes it: a rising count is the defect coming back, and a count that stays low is the fix holding.
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache is a lazily-resolved handle to the result cache. The zero value is not usable; build one with New, NewReader or Open.
func New ¶ added in v0.206.0
New returns a lazy read-write handle for path. It touches no file until the first Get/Put/Count, except for the stale-sibling sweep below.
The sweep runs at CONSTRUCTION, not at resolve: it is a directory glob and a stat, it takes no lock and creates nothing, and running it here is what keeps the cleanup alive now that most processes never resolve their handle at all. A sweep that only ran on a real open would, after this change, essentially never run.
func NewReader ¶ added in v0.206.0
NewReader returns a lazy READ-THROUGH handle: it never creates a file and never writes one. Use it for surfaces that only report or look up — status, inspection — so that merely asking what the cache holds cannot itself be the thing that litters the cache directory.
func Open ¶
Open opens path read-write eagerly and fails if it cannot. Kept for callers that genuinely need the handle now and want the error now (tests, and any tool whose whole job is the store itself).
func (*Cache) Close ¶
Close releases the handle, and cleans up after a sibling.
An EMPTY sibling is deleted outright: it is the 32 KB file the eager open used to leave behind on every losing process, and keeping it buys nothing. A NON-EMPTY one makes exactly one bounded attempt to promote its entries into the primary — if the primary's lock happens to be free at that moment — and is removed only when every entry made it across. When the primary is still held, the sibling stays exactly as it is and the age sweep eventually takes it.
func (*Cache) Configured ¶ added in v0.206.0
Configured is the cache path this handle was built for, whatever it resolved to.
func (*Cache) Count ¶ added in v0.206.0
Count returns how many entries the cache holds. Note this RESOLVES a lazy handle: it is a question about the store, not about the handle.
Exists so a test can assert "nothing was stored" against the STORE rather than inferring it from a call count — the difference between a real gate test and one that passes because the code under test was never reached.
func (*Cache) Fallback ¶ added in v0.206.0
Fallback reports whether this handle is a per-process sibling rather than the configured, shared file.
func (*Cache) Get ¶
Get returns the stored value and true if present. An unavailable handle — a reader that could reach neither the primary nor a sibling — answers every Get with a miss, which costs a model call and never a wrong result.
func (*Cache) Mode ¶ added in v0.206.0
Mode reports how the handle is backed WITHOUT resolving it: asking a status tool what the cache is doing must not be the call that takes the lock.
func (*Cache) Path ¶ added in v0.206.0
Path is the file this handle actually opened, or "" while it is unopened.
func (*Cache) WithNotify ¶ added in v0.206.0
WithNotify registers a callback invoked once, at resolve time, when the handle lands on anything other than the primary. It exists so the binaries can keep printing the operator note they printed when the open was eager — at the moment it becomes true, instead of at startup when it was merely predicted.
type Mode ¶ added in v0.206.0
type Mode string
Mode names how a handle is backed. It is reported verbatim by offload_status.reuse.result_cache so an operator reading "no cache" can tell the very different reasons apart.
const ( // ModeUnopened is a lazy handle nothing has needed yet. It is NOT a failure: // it is the expected steady state of an MCP server that has served only // status and fleet calls, and it is the state that stops the sibling churn. ModeUnopened Mode = "unopened" // ModePrimary holds the configured file read-write: the shared cache. ModePrimary Mode = "primary" // ModeSibling holds this process's own "<stem>.p<pid><ext>" read-write // because another process holds the primary. Hits are in-process only. ModeSibling Mode = "sibling" // ModeReadOnly holds a file read-only: a read-through reader. Path says which // file it reached (the primary, or this process's own sibling). ModeReadOnly Mode = "readonly" // path, or (for a reader) a primary held by a writer with no sibling to fall // through to. A reader in this mode answers every Get with a miss. ModeUnavailable Mode = "unavailable" )