Documentation
¶
Overview ¶
Package memory provides the exact-hit judgment memory for the Embed→Judge stack: validated judgment.Choice, judgment.Score, and judgment.Noul results cached under four-part keys (tenant, schema, primitive, request fingerprint) and evicted after caller-configured lifetimes by github.com/jellydator/ttlcache/v3.
Lookup is exact-match only: an entry is shared when the tenant, schema version, primitive, and fingerprint of the lookup key are all identical to the stored key. Semantic near-duplicate routing is out of scope. The store does not coalesce concurrent misses for one key; callers that need fill coalescing should provide it around the store.
The zero value is not usable; construct with New. New starts one background goroutine that evicts expired entries; stop it with Close. Results are trusted as validated: pass them through the judgment package's ValidateChoice, ValidateScore, and ValidateNoul before storing.
Index ¶
- Constants
- Variables
- func FingerprintChoice(request judgment.ChoiceRequest) string
- func FingerprintNoul(request judgment.NoulRequest) string
- func FingerprintScore(request judgment.ScoreRequest) string
- type Hit
- type HitKind
- type Key
- type Metrics
- type Option
- type Primitive
- type PutOption
- type SemanticConfig
- type SemanticMetrics
- type SemanticStore
- func (s *SemanticStore) Close() error
- func (s *SemanticStore) GetChoice(ctx context.Context, key Key, rawInput string) (judgment.Choice, Hit, error)
- func (s *SemanticStore) GetNoul(ctx context.Context, key Key, rawInput string) (judgment.Noul, Hit, error)
- func (s *SemanticStore) GetScore(ctx context.Context, key Key, rawInput string) (judgment.Score, Hit, error)
- func (s *SemanticStore) Metrics() SemanticMetrics
- func (s *SemanticStore) PutChoice(ctx context.Context, key Key, rawInput string, result judgment.Choice, ...) error
- func (s *SemanticStore) PutNoul(ctx context.Context, key Key, rawInput string, result judgment.Noul, ...) error
- func (s *SemanticStore) PutScore(ctx context.Context, key Key, rawInput string, result judgment.Score, ...) error
- type Store
- func (s *Store) Close() error
- func (s *Store) Delete(key Key)
- func (s *Store) GetChoice(key Key) (judgment.Choice, bool)
- func (s *Store) GetNoul(key Key) (judgment.Noul, bool)
- func (s *Store) GetScore(key Key) (judgment.Score, bool)
- func (s *Store) Len() int
- func (s *Store) Metrics() Metrics
- func (s *Store) PutChoice(key Key, result judgment.Choice, opts ...PutOption) error
- func (s *Store) PutNoul(key Key, result judgment.Noul, opts ...PutOption) error
- func (s *Store) PutScore(key Key, result judgment.Score, opts ...PutOption) error
Examples ¶
Constants ¶
const DefaultSemanticThreshold = 0.92
DefaultSemanticThreshold applies when SemanticConfig.Threshold is unset.
Variables ¶
var ErrInvalidKey = errors.New("judgment/memory: invalid cache key")
ErrInvalidKey reports a Put key that cannot identify a judgment: a blank tenant, schema, or fingerprint, or a primitive that is unknown or does not match the stored result type.
Functions ¶
func FingerprintChoice ¶
func FingerprintChoice(request judgment.ChoiceRequest) string
FingerprintChoice returns a deterministic SHA-256 fingerprint of the complete choice request: task, options (ID and description, in order), and context entries (in order). Identical requests fingerprint identically; any difference yields a different fingerprint. The request itself is not validated.
func FingerprintNoul ¶
func FingerprintNoul(request judgment.NoulRequest) string
FingerprintNoul returns a deterministic SHA-256 fingerprint of the complete noul request: question and context entries (in order).
func FingerprintScore ¶
func FingerprintScore(request judgment.ScoreRequest) string
FingerprintScore returns a deterministic SHA-256 fingerprint of the complete score request: task, target, and context entries (in order).
Types ¶
type Hit ¶
type Hit struct {
Kind HitKind
// Similarity is the winning cosine similarity for HitSemantic.
Similarity float32
}
Hit reports how a lookup resolved. A miss is the zero Hit.
type Key ¶
type Key struct {
// Tenant isolates one customer or deployment's judgments.
Tenant string
// Schema versions the judging pipeline; changing prompts, models, or
// option sets bumps the schema and invalidates older entries.
Schema string
// Primitive is the judgment primitive the entry holds.
Primitive Primitive
// Fingerprint identifies the exact request content, typically from
// FingerprintChoice, FingerprintScore, or FingerprintNoul.
Fingerprint string
}
Key identifies one cacheable judgment. Entries are shared only when Tenant, Schema, Primitive, and Fingerprint are all identical.
type Option ¶
type Option func(*config)
Option configures a Store at construction.
func WithCapacity ¶
WithCapacity limits the store to at most limit entries, evicting the least recently used entry when full. Zero (the default) is unlimited.
func WithDisableTouchOnHit ¶
func WithDisableTouchOnHit() Option
WithDisableTouchOnHit stops hits from extending an entry's lifetime.
type Primitive ¶
type Primitive string
Primitive names which judgment primitive a cached entry holds.
type PutOption ¶
type PutOption func(*putConfig)
PutOption tunes one insertion.
func WithEntryTTL ¶
WithEntryTTL caches this judgment for the given lifetime instead of the store default. Non-positive lifetimes are ignored.
type SemanticConfig ¶
type SemanticConfig struct {
// Embedder embeds judgment inputs for semantic comparison.
Embedder embedding.Embedder
// Model identifies the embedding space; Dim must be positive and
// must match every embedded vector.
Model embedding.ModelRef
// Threshold is the minimum cosine similarity for a semantic hit.
// Zero means the 0.92 default.
Threshold float64
}
SemanticConfig wires the semantic layer. Embedder and Model.Dim are required; Threshold is optional and defaults to 0.92.
type SemanticMetrics ¶
type SemanticMetrics struct {
ExactHits uint64
SemanticHits uint64
Misses uint64
Insertions uint64
}
SemanticMetrics counts SemanticStore activity.
type SemanticStore ¶
type SemanticStore struct {
// contains filtered or unexported fields
}
SemanticStore is a judgment cache that answers both exact fingerprint hits and semantic matches. Entries whose inputs embed near a stored vector (cosine similarity at or above the configured threshold within the same tenant, schema, and primitive scope) reuse the cached judgment without calling a provider.
The embedder is injected and stays caller-owned; the store performs no network or provider I/O of its own beyond that embedder call.
func NewSemantic ¶
func NewSemantic(cfg SemanticConfig, opts ...Option) (*SemanticStore, error)
NewSemantic creates a SemanticStore and starts its background eviction goroutine, which exits when Close is called. Cache behavior (TTL, capacity, touch-on-hit) reuses the Store options; TTL must be positive.
func (*SemanticStore) Close ¶
func (s *SemanticStore) Close() error
Close stops the background eviction goroutine. It is idempotent.
func (*SemanticStore) GetChoice ¶
func (s *SemanticStore) GetChoice(ctx context.Context, key Key, rawInput string) (judgment.Choice, Hit, error)
GetChoice returns the cached choice for key: an exact fingerprint hit first, then a semantic match for rawInput within the same scope.
func (*SemanticStore) GetNoul ¶
func (s *SemanticStore) GetNoul(ctx context.Context, key Key, rawInput string) (judgment.Noul, Hit, error)
GetNoul returns the cached noul with GetChoice's resolution rules.
func (*SemanticStore) GetScore ¶
func (s *SemanticStore) GetScore(ctx context.Context, key Key, rawInput string) (judgment.Score, Hit, error)
GetScore returns the cached score with GetChoice's resolution rules.
func (*SemanticStore) Metrics ¶
func (s *SemanticStore) Metrics() SemanticMetrics
Metrics returns cumulative lookup and insertion counters.
func (*SemanticStore) PutChoice ¶
func (s *SemanticStore) PutChoice(ctx context.Context, key Key, rawInput string, result judgment.Choice, opts ...PutOption) error
PutChoice caches result under key, embedding rawInput for later semantic comparison. Keys must carry PrimitiveChoice.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is an exact-hit judgment cache backed by ttlcache.
func New ¶
New creates a Store and starts its background eviction goroutine, which exits when Close is called.
Example ¶
store, err := New(WithTTL(10 * time.Minute))
if err != nil {
fmt.Println("new store:", err)
return
}
defer store.Close()
request := judgment.ChoiceRequest{
Task: "route the incoming request",
Options: []judgment.Option{{ID: "search"}, {ID: "summarize"}},
}
key := Key{
Tenant: "acme",
Schema: "router.v2",
Primitive: PrimitiveChoice,
Fingerprint: FingerprintChoice(request),
}
result := judgment.Choice{
Selected: "search",
Distribution: []judgment.OptionProbability{
{Option: "search", Probability: 0.7},
{Option: "summarize", Probability: 0.3},
},
}
if err := store.PutChoice(key, result); err != nil {
fmt.Println("put:", err)
return
}
if hit, ok := store.GetChoice(key); ok {
fmt.Println("cache hit:", hit.Selected)
}
Output: cache hit: search
func (*Store) Close ¶
Close stops the background eviction goroutine. Entries stay readable until they expire lazily. Close is idempotent and always returns nil.
func (*Store) GetChoice ¶
GetChoice returns the cached choice for key. ok is false when no entry exists, the entry expired, or the entry holds another primitive. Unless disabled, a hit extends the entry's lifetime.
func (*Store) PutChoice ¶
PutChoice caches result under key with the store default lifetime unless an entry lifetime is given. Keys must carry PrimitiveChoice.