Documentation
¶
Overview ¶
Package embedmemo memoizes embedding vectors by exact input bytes so a text that has already been embedded is never embedded again.
WHY THIS EXISTS (two payoffs, the second larger than the first):
Embedding is a pure function of (model, text), so recomputing it is pure waste. Where that recomputation actually happens, stated narrowly because two earlier drafts of this list were wrong:
- The kNN pre-filter embeds every request input. Repeat inputs are real (the ledger's duplicate-input rate is what T2-A's identity fields exist to measure), so this is the genuine source — but it is OFF unless knn_prefilter_enabled, which is false by default. - The shadow-label drain calls Similar per item, so identical summary text recurring WITHIN a run hits. Its Embed path is also gated on knn_prefilter_enabled.
Deliberately NOT claimed, both corrected after review: - Exemplar selection does not embed at all. internal/exemplars retrieves lexically (tokenise + an inverted index) and contains no embedder. - The drain does NOT "re-embed the same stored inputs on every run". shadow.Drain is destructive — it renames the queue to .draining, reads it, and removes the claim — so each run consumes a FRESH item set. Only a crash-recovered claim replays. Nor does it re-score a shared reference set: Similar compares each item's own entry and escalation summaries.
Being accurate about this matters more than the feature looking good: a false claim about which paths are covered is worse than a shorter list.
The bigger win is not the compute, it is the SWAP. Every seat on this fleet carries ttl=300, the embedder included, so the first embed after a >5-minute idle gap pays a cold model load (~1-2 s) before it computes anything. A memo hit skips the HTTP call entirely, which means it skips the swap — on the request path, where that latency is most visible.
Exact bytes, deliberately — no normalization ¶
The obvious "improvement" here is to normalize the key (trim, collapse whitespace, casefold) for a higher hit rate. This package does NOT do that, and the omission is load-bearing: normalization makes two DIFFERENT texts share one key, so the memo would hand back a vector computed for a different string. For a cache of a semantic quantity that is a silent correctness bug — the retrieved neighbours would be wrong and nothing would report it.
Namespaces: how a wrong-model answer is made structurally impossible ¶
Every key, counter and prune-order entry is scoped to a NAMESPACE derived from (embedderID, epoch). Switching embedders therefore cannot serve the previous model's vectors — not because a check happens to run, but because the two models address disjoint keyspaces and disjoint counters. Epoch is the manual lever for the one case an id cannot see: a model re-quantized or re-trained and republished under an unchanged name.
A namespace also records the DIMENSION of the first vector stored in it. A later vector of a different dimension proves the model changed behind a stable id, which is reported rather than silently mixed into a cosine routine.
Failure policy ¶
Every failure degrades to a plain pass-through call to the real embedder, and every failure is COUNTED and reportable. A memo that cannot open its file, cannot read, or reads something malformed must never turn into a failed embed — it was only ever an optimisation. But it must never look healthy either: the difference between "idle" and "broken" is exactly what the reporting surfaces exist to show. Errors from the underlying embedder are never stored (a cached error would be permanent).
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrDisabled is returned by Open when the caller passed an empty path. ErrDisabled = errors.New("embedmemo: disabled (empty path)") // ErrNoStore reports that the memo file does not exist yet — nothing has been // embedded on this machine. Distinct from a lock failure, because "empty" and // "cannot look" are different answers. ErrNoStore = errors.New("embedmemo: no store file yet") // ErrIdentityMismatch is returned by Shared when a caller asks for a path that // is already open under a DIFFERENT embedder id or epoch. Returning the // existing handle would silently serve another model's vectors. ErrIdentityMismatch = errors.New("embedmemo: store already open under a different embedder id/epoch") )
Functions ¶
func CloseShared ¶
func CloseShared() error
CloseShared flushes and closes every shared memo, returning the first error encountered.
EVERY BINARY THAT MAY OPEN A MEMO MUST CALL THIS ON SHUTDOWN. Flush is the only writer of the persisted hit/miss totals, so a process that exits without it leaves them at zero — and the reporting surfaces then state, in the one number the Phase 0.4 gate reads, that a memo serving thousands of hits was "never consulted".
Flush is attempted even when Close later fails, and a Flush error never prevents the Close — leaking a file lock would lock out the next process.
func FlushShared ¶
func FlushShared() error
FlushShared persists every shared memo's counters WITHOUT closing them.
For long-running processes: a shutdown-only flush bounds the loss to the whole process lifetime, and this one can run for weeks. A `kill -9` (or any exit that skips defers) then destroys every hit counter accumulated since start, and the hit-rate gate reads a fabricated zero. Calling this periodically bounds the loss to one interval.
Types ¶
type Memo ¶
type Memo struct {
// contains filtered or unexported fields
}
Memo is a bbolt-backed embedding memo. A nil *Memo is valid and behaves as a pass-through, so callers never need a nil check before Wrap.
func Open ¶
Open opens (creating if needed) the memo db at path.
A bolt open failure is a normal, expected condition (another process holds the file), so callers should treat the error as "run without a memo", not fatal.
func OpenReadOnly ¶
OpenReadOnly opens an EXISTING memo for inspection only.
For read-only reporting paths (the loupe), which document a hard constraint that they must never contend with a live MCP server. bbolt still takes a shared lock that an exclusive read-write handle blocks, so this CAN fail while the server runs — the point is that it fails FAST and legibly instead of stalling a full second and returning a lock error the caller has to interpret.
func Shared ¶
Shared opens (once per identity) and returns the process-wide memo. Callers must NOT Close the returned Memo — its lifetime is the process's. Use CloseShared from the owning binary's shutdown path.
func (*Memo) EmbedderID ¶
EmbedderID reports the model this handle is bound to (used by Shared to refuse a mismatched reuse rather than silently serving another model's namespace).
func (*Memo) Flush ¶
Flush persists the session hit/miss counters into this namespace's totals.
On failure the counters are RESTORED rather than lost. Swapping them to zero before the write meant a failed flush (disk full at shutdown) silently deleted a month of hits and made the next report show a hit rate LOWER than reality — a fabricated measurement, not merely a missing one.
func (*Memo) Stats ¶
Stats returns the counters, or an error if the store could not be read. The error is returned rather than swallowed so a reporting surface cannot publish "available, 0 vectors, never consulted" for a store it failed to read — which would turn a read fault into a confident claim of emptiness.
type Stats ¶
type Stats struct {
EmbedderID string `json:"embedder_id"`
Epoch string `json:"epoch,omitempty"`
Dim int `json:"dim,omitempty"`
// Distinct counts only vectors in the LIVE namespace. Counting the whole file
// would keep growing across epoch bumps (which orphan without deleting) and
// stop describing the memo actually in use.
Distinct int `json:"distinct"`
// Lifetime* INCLUDE the current session — see Flush. Making the two halves
// agree on a time base is deliberate: a consumer adding Lifetime+Session
// would otherwise double-count some fields and not others.
LifetimeHits int64 `json:"lifetime_hits"`
LifetimeMisses int64 `json:"lifetime_misses"`
LifetimeStores int64 `json:"lifetime_stores"`
SessionHits int64 `json:"session_hits"`
SessionMisses int64 `json:"session_misses"`
SessionStores int64 `json:"session_stores"`
// Fault counters, split so "the store is failing every write" is
// distinguishable from "a few records were corrupt". Published by every
// reporting surface: an unpublished fault counter is not a fault signal.
ErrorsDecode int64 `json:"errors_decode"`
ErrorsRead int64 `json:"errors_read"`
ErrorsWrite int64 `json:"errors_write"`
DimMismatches int64 `json:"dim_mismatches"`
// CountUnderflows records an impossible bookkeeping state: a counter asked to
// go below zero, or a live-entry count so large no configuration could produce
// it. Clamping without counting would erase the evidence of the bug that
// produced it. Deliberately NOT counted: a count merely above the current cap,
// which is what lowering embed_memo_max_entries legitimately produces.
CountUnderflows int64 `json:"count_underflows"`
// LastFault is the most recent human-readable fault with its remediation.
LastFault string `json:"last_fault,omitempty"`
// ForeignNamespaces/ForeignVectors describe entries this handle can never
// reach (a prior embedder id or epoch). They are not deleted, so without this
// a store at its size cap reports "0 vectors stored".
ForeignNamespaces int `json:"foreign_namespaces,omitempty"`
ForeignVectors int `json:"foreign_vectors,omitempty"`
// FileBytes is the store's on-disk size. bbolt never shrinks after a prune,
// so this is a high-water mark and the only honest capacity signal.
FileBytes int64 `json:"file_bytes,omitempty"`
// HitRate is nil when nothing has been looked up. It is deliberately a
// pointer and not a bare 0.0: publishing "0% hit rate" for a memo that has
// never been consulted reports a measured failure where there is no
// measurement at all.
HitRate *float64 `json:"hit_rate"`
}
Stats reports this session's counters plus the persisted totals for THIS namespace.
Distinct is the live entry count and Total the lifetime lookups, which together are the ratio Phase 0.4 asks for: the memo's own bookkeeping IS the distinct/total instrument.