memory

package
v0.16.1 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 13 Imported by: 0

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

Examples

Constants

View Source
const DefaultSemanticThreshold = 0.92

DefaultSemanticThreshold applies when SemanticConfig.Threshold is unset.

Variables

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

type HitKind int

HitKind classifies a SemanticStore lookup.

const (
	// HitNone reports a miss.
	HitNone HitKind = iota
	// HitExact reports an exact fingerprint hit.
	HitExact
	// HitSemantic reports a similarity-threshold hit.
	HitSemantic
)

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 Metrics

type Metrics struct {
	Insertions uint64
	Updates    uint64
	Hits       uint64
	Misses     uint64
	Evictions  uint64
}

Metrics reports lifetime store counters.

type Option

type Option func(*config)

Option configures a Store at construction.

func WithCapacity

func WithCapacity(limit uint64) Option

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.

func WithTTL

func WithTTL(lifetime time.Duration) Option

WithTTL sets the default lifetime of cached judgments. It is required and must be positive; entries otherwise live forever in memory.

type Primitive

type Primitive string

Primitive names which judgment primitive a cached entry holds.

const (
	// PrimitiveChoice marks a cached judgment.Choice.
	PrimitiveChoice Primitive = "choice"
	// PrimitiveScore marks a cached judgment.Score.
	PrimitiveScore Primitive = "score"
	// PrimitiveNoul marks a cached judgment.Noul.
	PrimitiveNoul Primitive = "noul"
)

func (Primitive) Valid

func (p Primitive) Valid() bool

Valid reports whether p is one of the defined judgment primitives.

type PutOption

type PutOption func(*putConfig)

PutOption tunes one insertion.

func WithEntryTTL

func WithEntryTTL(lifetime time.Duration) PutOption

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.

func (*SemanticStore) PutNoul

func (s *SemanticStore) PutNoul(ctx context.Context, key Key, rawInput string, result judgment.Noul, opts ...PutOption) error

PutNoul caches result under key, embedding rawInput. Keys must carry PrimitiveNoul.

func (*SemanticStore) PutScore

func (s *SemanticStore) PutScore(ctx context.Context, key Key, rawInput string, result judgment.Score, opts ...PutOption) error

PutScore caches result under key, embedding rawInput. Keys must carry PrimitiveScore.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is an exact-hit judgment cache backed by ttlcache.

func New

func New(opts ...Option) (*Store, error)

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

func (s *Store) Close() error

Close stops the background eviction goroutine. Entries stay readable until they expire lazily. Close is idempotent and always returns nil.

func (*Store) Delete

func (s *Store) Delete(key Key)

Delete removes the entry for key, whether or not it has expired.

func (*Store) GetChoice

func (s *Store) GetChoice(key Key) (judgment.Choice, bool)

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

func (s *Store) GetNoul(key Key) (judgment.Noul, bool)

GetNoul returns the cached gate answer for key with GetChoice's miss rules.

func (*Store) GetScore

func (s *Store) GetScore(key Key) (judgment.Score, bool)

GetScore returns the cached score for key with GetChoice's miss rules.

func (*Store) Len

func (s *Store) Len() int

Len reports the number of unexpired entries.

func (*Store) Metrics

func (s *Store) Metrics() Metrics

Metrics returns the store's lifetime counters.

func (*Store) PutChoice

func (s *Store) PutChoice(key Key, result judgment.Choice, opts ...PutOption) error

PutChoice caches result under key with the store default lifetime unless an entry lifetime is given. Keys must carry PrimitiveChoice.

func (*Store) PutNoul

func (s *Store) PutNoul(key Key, result judgment.Noul, opts ...PutOption) error

PutNoul caches result under key. Keys must carry PrimitiveNoul.

func (*Store) PutScore

func (s *Store) PutScore(key Key, result judgment.Score, opts ...PutOption) error

PutScore caches result under key. Keys must carry PrimitiveScore.

Jump to

Keyboard shortcuts

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