{"modulePath":"github.com/memcode-ai/memcode","version":"v0.56.16","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package membench\n\nPackage membench evaluates memcode's session-memory retrieval against public conversational-memory benchmarks (LongMemEval, LoCoMo) with ZERO model calls.\n\nEach benchmark question's chat history is ingested as real .memcode session logs (one events.jsonl per benchmark session, timestamps preserved), then retrieval adapters rank content for the question and are scored against the benchmark's own evidence labels (answer\\_session\\_ids / evidence dia\\_ids). Metrics: recall@k and nDCG@k. The point is to measure the retrieval layer exactly as the product exercises it, before any answer-mode run.\n\n## Functions\n\n```go\nfunc CacheDir() string\n```\nCacheDir is where datasets and retrieval logs live; never committed.\n\n```go\nfunc GenerateFacts(ds *Dataset, limit int) error\n```\nGenerateFacts extracts facts for every session in the first \\`limit\\` questions' haystacks (0 = all) and attaches them to the SessionDocs in place. Identical sessions across overlapping haystacks generate once; results persist in a content-addressed cache so reruns are free.\n\n```go\nfunc Ingest(root string, docs []SessionDoc) error\n```\nIngest writes each benchmark session as a real .memcode session log: .memcode/sessions/\\\u003cSessionDoc.ID\u003e/events.jsonl via the production sessionlog.Writer, with Record.TS carrying the benchmark timestamps and the file mtime pinned to the session time (recency ordering in sessionlog is mtime-based). Turn identity rides Record.Slug — unused by real chat sessions and excluded from Search's match haystack, so it labels without polluting retrieval.\n\n## Types\n\n```go\ntype Adapter interface {\n\tName() string\n\tRank(root string, q Question, docs []SessionDoc, k int) ([]string, error)\n}\n```\nAdapter ranks turns for a question over an ingested root and returns turn IDs, best first. The scorer aggregates turns to sessions when the dataset is session-granular.\n\n```go\nfunc Adapters(name string) []Adapter\n```\nAdapters returns the named adapter set (\"all\" = every adapter).\n\n```go\ntype BM25Adapter struct {\n\t// Time-aware scoring (the bm25+time adapter is this struct with TimeAware\n\t// set): explicit date cues in the question define a window that boosts\n\t// in-window turns and dampens out-of-window ones, and knowledge-update\n\t// questions get a recency tiebreak so the latest version of a changed\n\t// fact outranks the original.\n\tTimeAware bool\n\t// V2 layers the accuracy work on top: light stemming, bigram matching,\n\t// category-aware query expansion, and relative-date windows. Kept as a\n\t// flag so v1 numbers stay reproducible for the before/after table.\n\tV2 bool\n}\n```\nBM25Adapter tokenizes the question and every ingested turn and ranks turns by BM25. Reads the turns back from the ingested session logs (not the in-memory dataset) so the whole file pipeline is exercised.\n\n```go\nfunc (a BM25Adapter) Name() string\n```\n\n```go\nfunc (a BM25Adapter) Rank(root string, q Question, docs []SessionDoc, k int) ([]string, error)\n```\n\n```go\ntype Dataset struct {\n\tName      string\n\tGran      Granularity\n\tQuestions []Question\n}\n```\nDataset is a fully parsed benchmark.\n\n```go\nfunc Load(name, dataPath string) (*Dataset, error)\n```\nLoad fetches (or reads from cache / an explicit path) and parses a dataset. Supported names: \"longmemeval-s\", \"locomo\".\n\n```go\nfunc SplitQuestions(ds *Dataset, split string) (*Dataset, error)\n```\nSplitQuestions carves a tune/holdout split by question index parity so knob tuning (\"even\") never reads the reporting set (\"odd\"). \"all\"/\"\" is identity.\n\n```go\ntype Fact struct {\n\tFact     string   `json:\"fact\"`\n\tEntities []string `json:\"entities\"`\n\tSource   string   `json:\"source,omitempty\"` // benchmark turn id the fact is drawn from\n}\n```\nFact is one extracted atomic fact attached to a SessionDoc.\n\n```go\ntype Granularity int\n```\nGranularity of the ranked unit a dataset is scored at.\n\n```go\nconst (\n\tBySession Granularity = iota\n\tByTurn\n)\n```\n\n```go\ntype HybridAdapter struct {\n\tHybridWeight float64\n\t// contains filtered or unexported fields\n}\n```\nHybridAdapter blends the v2 lexical score with embedding cosine similarity: score = bm25/bm25max + HybridWeight\\*cosine. Turns are read back from the ingested logs like every other adapter.\n\n```go\nfunc NewHybridAdapter() (*HybridAdapter, error)\n```\nNewHybridAdapter fails fast when no embedding key is configured.\n\n```go\nfunc (h *HybridAdapter) Name() string\n```\n\n```go\nfunc (h *HybridAdapter) Rank(root string, q Question, docs []SessionDoc, k int) ([]string, error)\n```\n\n```go\ntype LegacyAdapter struct{}\n```\nLegacyAdapter is the stub that stands in when the binary is built WITHOUT \\`-tags membench\\`: the real pre-2026-07-25 substring scan (legacy.go) is bench-only history and must not ship in release binaries. The type keeps the exported surface (Adapters, cmd/bench) compiling; running it says why it isn't available instead of silently benching nothing.\n\n```go\nfunc (LegacyAdapter) Name() string\n```\n\n```go\nfunc (LegacyAdapter) Rank(root string, q Question, docs []SessionDoc, k int) ([]string, error)\n```\n\n```go\ntype ProductAdapter struct {\n\tVariant string\n\tOpts    *sessionlog.RankingOptions\n}\n```\nProductAdapter runs the production session-search code path exactly as the memcode{session,search} tool runs it. Since the Phase B promotion this is the ranked search; the pre-promotion substring behavior lives on as LegacyAdapter for the before/after table. Opts installs a ranking-feature variant (via Prepare, before workers spawn) so the ablation table isolates each layer's lift; nil keeps whatever is installed.\n\n```go\nfunc (a ProductAdapter) Name() string\n```\n\n```go\nfunc (a ProductAdapter) Prepare()\n```\n\n```go\nfunc (ProductAdapter) Rank(root string, q Question, _ []SessionDoc, k int) ([]string, error)\n```\n\n```go\ntype QAResult struct {\n\tDataset  string\n\tAdapter  string\n\tModel    string\n\tTotal    int\n\tCorrect  int\n\tByType   map[string][2]int // type -\u003e {correct, total}\n\tFailures []string          // question ids judged incorrect (capped)\n}\n```\nQAResult aggregates answer-mode accuracy.\n\n```go\nfunc RunQA(ds *Dataset, ad Adapter, workDir string, limit, topK int) (*QAResult, error)\n```\nRunQA answers questions with retrieval-trimmed context and judges them. topK is how many retrieved sessions ride the prompt.\n\n```go\nfunc (r *QAResult) Accuracy() float64\n```\n\n```go\nfunc (r *QAResult) Render() string\n```\n\n```go\ntype Question struct {\n\tID       string\n\tType     string\n\tText     string\n\tAnswer   string // gold answer text (QA mode)\n\tDate     time.Time\n\tGold     map[string]bool\n\tHaystack []SessionDoc\n\tGran     Granularity // stamped from the dataset by Run; adapters may branch on it\n}\n```\nQuestion is one scored instance. Gold holds the evidence ids at the benchmark's native granularity: session ids for LongMemEval, dia ids for LoCoMo. Haystack is the history visible to this question.\n\n```go\ntype QuestionResult struct {\n\tQuestionID string\n\tType       string\n\tRanked     []string\n\tRecallAtK  map[int]float64\n\tNDCGAtK    map[int]float64\n}\n```\nQuestionResult is the scored outcome for one question under one adapter.\n\n```go\ntype RunResult struct {\n\tDataset   string\n\tAdapter   string\n\tQuestions int\n\tSkipped   int // no-evidence questions (abstention / adversarial)\n\tRecall    map[int]float64\n\tNDCG      map[int]float64\n\tByType    map[string]typeAgg\n\tPerQ      []QuestionResult\n}\n```\nRunResult aggregates one adapter's scores over a dataset.\n\n```go\nfunc Run(ds *Dataset, ad Adapter, workDir string, limit int, keep bool) (*RunResult, error)\n```\nRun ingests each question's haystack into a throwaway .memcode root, ranks with the adapter, and scores against the gold labels. Workers bound the ingest cost; every root is deleted unless keep is set.\n\n```go\nfunc (r *RunResult) Render() string\n```\nRender prints the result table.\n\n```go\nfunc (r *RunResult) WriteLog(dir string) (string, error)\n```\nWriteLog persists per-question ranked ids for later parity runs against the benchmarks' own scoring scripts.\n\n```go\ntype SessionDoc struct {\n\tID    string\n\tTS    time.Time\n\tTurns []Turn\n\tFacts []Fact\n}\n```\nSessionDoc is one benchmark chat session. Facts are attached by GenerateFacts and ingested as KindFacts records, mirroring what the product's cognition loop appends to real sessions.\n\n```go\ntype Turn struct {\n\tRole     string // \"user\" | \"assistant\"\n\tText     string\n\tID       string\n\tEvidence bool\n}\n```\nTurn is one benchmark utterance. ID is the benchmark's identity for the turn (LongMemEval: \"\\\u003csession\u003e#\\\u003cidx\u003e\"; LoCoMo: the dia\\_id) and rides the ingested Record so ranked results map straight back to evidence labels.\n\n","path":"github.com/memcode-ai/memcode/internal/membench","name":"membench","synopsis":"Package membench evaluates memcode's session-memory retrieval against public conversational-memory benchmarks (LongMemEval, LoCoMo) with ZERO model calls.","isRedistributable":true}
