From 17f893865d4d8337f7e0bf942c6931a8ce7a08c1 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Sun, 13 Sep 2026 11:06:12 +0800 Subject: [PATCH] fix(memory): rank memories by the query, not by importance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Long-term memory chose its candidates before it looked at the question. Recall listed 400 items by `importance DESC, valid_from DESC`, loaded the vectors belonging to that list, and scored those; extraction did the same with a 200-item pool. Importance is uncorrelated with relevance, so the vector stage could only re-order what importance had already picked, and a memory below the cut was unreachable no matter how well it matched. The capacity cap goes up to 2000, so everything past the 400th most important memory was permanently unrecallable, and `memory_item_embeddings.vector` being a BYTEA blob meant pgvector was never involved. The store now answers "which of this person's memories is this question about": - Migration 000095 (and the SQLite mirror) add `embedding halfvec` plus a `(tenant_id, subject_id, model_id, dims)` index. The column is conditional on the vector extension, so a deployment whose retrieval driver excludes postgres keeps working. No HNSW: an approximate index is filtered after the fact, and one subject holds at most a couple of thousand rows, so exact ordering inside the scope is both correct and a few milliseconds. - `SearchItemsByVector` ranks in SQL over every vector the subject has, with the status, expiry and kind filters joined in so reaching past the candidate list cannot reach past the filters. SQLite and pgvector-less PostgreSQL fall back to scoring in process, still over the whole scope. - Recall fuses the lexical ranking with those hits and grows the candidate pool with matches the pool did not hold, which is what lets the search escape it. The lexical pool is now the capacity cap, so it can no longer be a second, invisible limit under the one that decides what stays active. - Extraction picks the memories it shows the model the same way. This matters more than recall: the memory a new statement contradicts is not reliably an important one, so an importance-ordered window hid exactly the collision that stops a duplicate being written. - Vectors are written to the searchable column in the upsert's transaction; rows predating the column are moved by `SyncVectorColumn` during maintenance, which costs no model calls. The embedding backfill goes from 50 to 200 per run — at 50, a subject at the capacity cap took over a month to become fully searchable. - Traces and logs report `outside_pool`, the number of semantic matches the lexical pool did not contain. It was structurally zero before, so it is the number to watch when asking whether semantic recall does anything. Tests cover whole-scope ranking, the lifecycle and kind filters, pool growth, the pool-size invariant, and extraction seeing a low-importance memory it would otherwise duplicate. A pgvector integration test (WEKNORA_MEMORY_TEST_POSTGRES_DSN) exercises the migration, the halfvec write, the SQL ranking and the column sync. --- internal/application/repository/memory.go | 15 +- .../application/repository/memory_vector.go | 259 ++++++++++++++++++ .../application/service/memory/consolidate.go | 10 + .../application/service/memory/extract.go | 76 +++-- .../service/memory/recall_trace.go | 150 ++++++++-- internal/application/service/memory/search.go | 37 ++- .../application/service/memory/service.go | 22 +- internal/application/service/memory/vector.go | 103 +++---- .../service/memory/vector_postgres_test.go | 130 +++++++++ .../service/memory/vector_scope_test.go | 213 ++++++++++++++ .../application/service/memory/vector_test.go | 13 +- .../migration_sqlite_versioned_schema_test.go | 2 +- internal/types/interfaces/memory.go | 34 +++ internal/types/memory.go | 21 ++ .../000016_memory_vector_search.down.sql | 1 + .../sqlite/000016_memory_vector_search.up.sql | 5 + .../000095_memory_vector_search.down.sql | 11 + .../000095_memory_vector_search.up.sql | 42 +++ 18 files changed, 1006 insertions(+), 138 deletions(-) create mode 100644 internal/application/repository/memory_vector.go create mode 100644 internal/application/service/memory/vector_postgres_test.go create mode 100644 internal/application/service/memory/vector_scope_test.go create mode 100644 migrations/sqlite/000016_memory_vector_search.down.sql create mode 100644 migrations/sqlite/000016_memory_vector_search.up.sql create mode 100644 migrations/versioned/000095_memory_vector_search.down.sql create mode 100644 migrations/versioned/000095_memory_vector_search.up.sql diff --git a/internal/application/repository/memory.go b/internal/application/repository/memory.go index 6ca5c329..c3c2bc97 100644 --- a/internal/application/repository/memory.go +++ b/internal/application/repository/memory.go @@ -3,6 +3,7 @@ package repository import ( "context" "errors" + "sync" "time" "github.com/Tencent/WeKnora/internal/types" @@ -14,6 +15,11 @@ import ( type memoryRepository struct { db *gorm.DB + // Whether the database can rank vectors itself. Probed once, on first use, + // because it depends on a migration that is conditional on pgvector being + // installed and so cannot be decided from the dialect alone. + vectorOnce sync.Once + vectorColumn bool } // NewMemoryRepository creates the long-term memory repository. @@ -499,12 +505,19 @@ func (r *memoryRepository) UpsertItemEmbedding( return nil } } - return tx. + err := tx. Clauses(clause.OnConflict{ Columns: []clause.Column{{Name: "item_id"}}, DoUpdates: clause.AssignmentColumns([]string{"model_id", "dims", "vector", "updated_at"}), }). Create(embedding).Error + if err != nil { + return err + } + // The blob above is what every deployment reads; this is the same + // vector in the type the database can sort by. Written in the same + // transaction so a row is never searchable with a stale vector. + return r.writeVectorColumn(tx, embedding.ItemID, embedding.Vector) }) } diff --git a/internal/application/repository/memory_vector.go b/internal/application/repository/memory_vector.go new file mode 100644 index 00000000..6c8c7059 --- /dev/null +++ b/internal/application/repository/memory_vector.go @@ -0,0 +1,259 @@ +package repository + +import ( + "context" + "sort" + "time" + + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "gorm.io/gorm" +) + +// fallbackVectorScanCap bounds the in-process fallback. +// +// One subject cannot hold more active memories than the workspace capacity +// cap, which tops out in the low thousands, so this is a guard against a +// corrupted scope rather than a real limit: a subject at the cap still gets +// every one of its vectors scored, which is the whole point of the change. +const fallbackVectorScanCap = 5000 + +// vectorColumnReady reports whether the database can do the distance +// arithmetic itself. +// +// Checked once and cached. It is false on SQLite, and false on a PostgreSQL +// deployment that never installed pgvector because its retrieval driver does +// not use it — both of which keep working through the fallback below, just +// with every vector crossing the wire. +func (r *memoryRepository) vectorColumnReady() bool { + r.vectorOnce.Do(func() { + if r.db == nil || r.db.Dialector == nil || r.db.Dialector.Name() != "postgres" { + return + } + r.vectorColumn = r.db.Migrator().HasColumn(&types.MemoryItemEmbedding{}, "embedding") + }) + return r.vectorColumn +} + +// writeVectorColumn keeps the database's own vector type in step with the +// stored blob. Best effort inside the caller's transaction: the blob is the +// source of truth, and a row whose vector column is behind is picked up by +// SyncVectorColumn rather than lost. +func (r *memoryRepository) writeVectorColumn(tx *gorm.DB, itemID string, raw []byte) error { + if !r.vectorColumnReady() || itemID == "" { + return nil + } + literal := types.FormatEmbeddingLiteral(types.DecodeEmbedding(raw)) + if literal == "" { + return nil + } + return tx.Exec( + `UPDATE memory_item_embeddings SET embedding = ?::halfvec WHERE item_id = ?`, + literal, itemID, + ).Error +} + +// vectorHitRow is one (item, distance) pair as the ranking query returns it. +type vectorHitRow struct { + ItemID string + Score float64 +} + +// SearchItemsByVector ranks a subject's whole vector set against one query. +// +// The candidate set is every vector the subject has, not a window of them. +// This is the difference that matters: the previous implementation listed +// items by importance, loaded the vectors belonging to that list, and scored +// those — so relevance could only ever re-order what importance had already +// chosen, and a matching memory outside the window was unreachable. +func (r *memoryRepository) SearchItemsByVector( + ctx context.Context, scope interfaces.MemoryScope, query interfaces.MemoryVectorQuery, +) ([]interfaces.MemoryVectorHit, error) { + if !scope.Valid() || query.ModelID == "" || len(query.Vector) == 0 { + return nil, nil + } + limit := query.Limit + if limit <= 0 { + limit = 20 + } + + var rows []vectorHitRow + var err error + if r.vectorColumnReady() { + rows, err = r.rankInDatabase(ctx, scope, query, limit) + } else { + rows, err = r.rankInProcess(ctx, scope, query, limit) + } + if err != nil { + return nil, err + } + if len(rows) == 0 { + return nil, nil + } + + ids := make([]string, 0, len(rows)) + for _, row := range rows { + if row.Score >= query.MinScore { + ids = append(ids, row.ItemID) + } + } + if len(ids) == 0 { + return nil, nil + } + + // Items are loaded separately rather than joined into the ranking query so + // that neither path has to reproduce the column list of memory_items, and + // so the ranking query stays narrow enough to be read at a glance. + var items []*types.MemoryItem + if err := r.scoped(ctx, scope).Where("id IN ?", ids).Find(&items).Error; err != nil { + return nil, err + } + byID := make(map[string]*types.MemoryItem, len(items)) + for _, item := range items { + byID[item.ID] = item + } + + hits := make([]interfaces.MemoryVectorHit, 0, len(ids)) + for _, row := range rows { + item, ok := byID[row.ItemID] + if !ok { + continue + } + hits = append(hits, interfaces.MemoryVectorHit{Item: item, Score: row.Score}) + } + return hits, nil +} + +// rankInDatabase orders by cosine distance in SQL and returns only the top k. +func (r *memoryRepository) rankInDatabase( + ctx context.Context, scope interfaces.MemoryScope, query interfaces.MemoryVectorQuery, limit int, +) ([]vectorHitRow, error) { + literal := types.FormatEmbeddingLiteral(query.Vector) + if literal == "" { + return nil, nil + } + sql := ` + SELECT e.item_id AS item_id, + 1 - (e.embedding::halfvec <=> ?::halfvec) AS score + FROM memory_item_embeddings e + JOIN memory_items i + ON i.id = e.item_id AND i.tenant_id = e.tenant_id AND i.subject_id = e.subject_id + WHERE e.tenant_id = ? AND e.subject_id = ? + AND e.model_id = ? AND e.dims = ? AND e.embedding IS NOT NULL + AND i.status = ? + AND (i.expires_at IS NULL OR i.expires_at > ?)` + args := []interface{}{ + literal, scope.TenantID, scope.SubjectID, + query.ModelID, len(query.Vector), types.MemoryStatusActive, time.Now(), + } + if len(query.Kinds) > 0 { + sql += ` AND i.kind IN ?` + args = append(args, query.Kinds) + } + // Ordering by the operator rather than by the computed score keeps the + // expression identical to the one an index would be built on. + sql += ` ORDER BY e.embedding::halfvec <=> ?::halfvec LIMIT ?` + args = append(args, literal, limit) + + var rows []vectorHitRow + if err := r.db.WithContext(ctx).Raw(sql, args...).Scan(&rows).Error; err != nil { + return nil, err + } + return rows, nil +} + +// rankInProcess is the portable path: read this subject's vectors and score +// them here. Bounded by the same capacity cap that bounds the subject itself, +// so it still sees everything — it just pays to transfer it. +func (r *memoryRepository) rankInProcess( + ctx context.Context, scope interfaces.MemoryScope, query interfaces.MemoryVectorQuery, limit int, +) ([]vectorHitRow, error) { + type storedVector struct { + ItemID string + Vector []byte + } + sql := ` + SELECT e.item_id AS item_id, e.vector AS vector + FROM memory_item_embeddings e + JOIN memory_items i + ON i.id = e.item_id AND i.tenant_id = e.tenant_id AND i.subject_id = e.subject_id + WHERE e.tenant_id = ? AND e.subject_id = ? + AND e.model_id = ? AND e.dims = ? + AND i.status = ? + AND (i.expires_at IS NULL OR i.expires_at > ?)` + args := []interface{}{ + scope.TenantID, scope.SubjectID, + query.ModelID, len(query.Vector), types.MemoryStatusActive, time.Now(), + } + if len(query.Kinds) > 0 { + sql += ` AND i.kind IN ?` + args = append(args, query.Kinds) + } + sql += ` LIMIT ?` + args = append(args, fallbackVectorScanCap) + + var stored []storedVector + if err := r.db.WithContext(ctx).Raw(sql, args...).Scan(&stored).Error; err != nil { + return nil, err + } + + rows := make([]vectorHitRow, 0, len(stored)) + for _, row := range stored { + vector := types.DecodeEmbedding(row.Vector) + if len(vector) == 0 { + continue + } + rows = append(rows, vectorHitRow{ + ItemID: row.ItemID, + Score: types.CosineSimilarity(query.Vector, vector), + }) + } + sortVectorHitsDesc(rows) + if len(rows) > limit { + rows = rows[:limit] + } + return rows, nil +} + +// sortVectorHitsDesc puts the closest match first. +func sortVectorHitsDesc(rows []vectorHitRow) { + sort.SliceStable(rows, func(i, j int) bool { return rows[i].Score > rows[j].Score }) +} + +// SyncVectorColumn moves already-embedded rows into the database's vector +// type. Rows written before migration 000095 hold only the blob, and a row the +// SQL ranking cannot see is a memory that semantic recall cannot find — so this +// has to drain without waiting for an embedding model to be called again. +func (r *memoryRepository) SyncVectorColumn( + ctx context.Context, scope interfaces.MemoryScope, limit int, +) (int, error) { + if !r.vectorColumnReady() || !scope.Valid() { + return 0, nil + } + if limit <= 0 { + limit = 500 + } + type pending struct { + ItemID string + Vector []byte + } + var rows []pending + err := r.db.WithContext(ctx).Raw(` + SELECT item_id, vector FROM memory_item_embeddings + WHERE tenant_id = ? AND subject_id = ? + AND embedding IS NULL AND vector IS NOT NULL + LIMIT ?`, scope.TenantID, scope.SubjectID, limit).Scan(&rows).Error + if err != nil { + return 0, err + } + moved := 0 + for _, row := range rows { + if err := r.writeVectorColumn(r.db.WithContext(ctx), row.ItemID, row.Vector); err != nil { + logger.Warnf(ctx, "memory: sync vector column failed for %s: %v", row.ItemID, err) + continue + } + moved++ + } + return moved, nil +} diff --git a/internal/application/service/memory/consolidate.go b/internal/application/service/memory/consolidate.go index c14a44cc..93fae776 100644 --- a/internal/application/service/memory/consolidate.go +++ b/internal/application/service/memory/consolidate.go @@ -163,6 +163,16 @@ func (s *Service) reviewStore( // instead of stalling one maintenance pass. s.backfillEmbeddings(ctx, scope, cfg) + // Vectors that exist but predate the database being able to rank them. + // Cheap — no model is called, the numbers are already stored — and until + // it runs, those memories are invisible to the SQL ranking. + if moved, err := s.repo.SyncVectorColumn(ctx, scope, vectorSyncPerRun); err != nil { + logger.Warnf(ctx, "memory: sync vector column failed: %v", err) + } else if moved > 0 { + logger.Infof(ctx, "memory: moved %d vectors into the search column for %s", + moved, scope.SubjectID) + } + if err := s.repo.MarkConsolidated(ctx, scope); err != nil { logger.Warnf(ctx, "memory: mark consolidated failed: %v", err) } diff --git a/internal/application/service/memory/extract.go b/internal/application/service/memory/extract.go index 97d14ec8..df7d2c1e 100644 --- a/internal/application/service/memory/extract.go +++ b/internal/application/service/memory/extract.go @@ -43,9 +43,8 @@ const ( // in-flight claim is stale. Without it, a worker that died between claiming // and running would wedge the subject permanently. extractInFlightGrace = 10 * time.Minute - // extractCandidatePool is how many stored memories are considered before - // narrowing, and extractRelevantCandidates is how many the model actually - // sees. + // extractRelevantCandidates is how many stored memories the extraction + // model is shown. // // Showing everything was the original behaviour and it does not survive a // store of any size: the model has to hold dozens of unrelated notes in @@ -53,7 +52,10 @@ const ( // without bound, and unrelated memories invite spurious update and delete // decisions. mem0 shows 10 by vector similarity, Graphiti at most 15 per // entity — a small, relevant set is the shape that works. - extractCandidatePool = 200 + // + // Which 15 is decided by searching the whole store, not by pre-selecting a + // pool: the memory a new statement duplicates is not reliably one of the + // most important ones. extractRelevantCandidates = 15 // extractShownTopics bounds the tracked subjects shown to the extraction // call. The resolver still considers more; this is about anchoring, not @@ -382,11 +384,10 @@ func (s *Service) Handle(ctx context.Context, task *asynq.Task) error { } func (s *Service) extractSegment(ctx context.Context, scope interfaces.MemoryScope, cfg *types.MemoryConfig, payload types.MemoryExtractPayload, segment transcriptSegment) error { - existing, err := s.repo.ListActiveByKinds(ctx, scope, types.MemoryKinds, extractCandidatePool) + existing, err := s.relevantExisting(ctx, scope, cfg, segment) if err != nil { return fmt.Errorf("load existing memories: %w", err) } - existing = s.narrowToRelevant(ctx, scope, cfg, segment, existing) forgotten, err := s.repo.ListTombstones(ctx, scope, 30) if err != nil { return fmt.Errorf("load memory tombstones: %w", err) @@ -851,21 +852,35 @@ func (s *Service) workspaceChatModelID(ctx context.Context) string { return "" } -// narrowToRelevant cuts the stored memories down to the ones this segment -// could plausibly be about. +// relevantExisting loads the stored memories this segment could plausibly be +// about — the ones the model is shown so it can update or supersede them +// instead of writing a near-duplicate. // -// Falls back to a plain prefix when semantic scoring is unavailable, which is -// still an improvement on showing everything: the list is ordered by importance -// and recency, so the prefix is at least the memories most likely to matter. -func (s *Service) narrowToRelevant( +// The selection is a semantic search over everything the subject has stored. +// It used to list the 200 most important memories and rank those, which put a +// ceiling on what extraction could ever notice: past the 200th memory, a +// statement that contradicted a stored one was invisible, so the model wrote a +// second copy of it and both stayed active. Deduplication cannot be bounded by +// importance, because the memory a new sentence collides with is not +// especially likely to be an important one. +// +// A subject small enough to show in full skips the search: the embedding call +// would decide nothing, and extraction already pays for a model call. +func (s *Service) relevantExisting( ctx context.Context, scope interfaces.MemoryScope, cfg *types.MemoryConfig, segment transcriptSegment, - existing []*types.MemoryItem, -) []*types.MemoryItem { +) ([]*types.MemoryItem, error) { + // One more than fits, so "everything fits" can be told from "there is + // more" without a second query. + existing, err := s.repo.ListActiveByKinds( + ctx, scope, types.MemoryKinds, extractRelevantCandidates+1) + if err != nil { + return nil, err + } if len(existing) <= extractRelevantCandidates { - return existing + return existing, nil } var query strings.Builder @@ -874,26 +889,27 @@ func (s *Service) narrowToRelevant( query.WriteString("\n") } - ranking, _ := s.vectorRanking(ctx, scope, cfg, query.String(), existing) - if len(ranking) == 0 { + hits, skip := s.vectorSearch( + ctx, scope, cfg, query.String(), types.MemoryKinds, extractRelevantCandidates) + if len(hits) == 0 { + // The importance-ordered prefix is the honest fallback: without + // semantic scoring there is nothing to rank by, and the memories most + // likely to matter are the ones this person keeps around. logger.Infof(ctx, - "memory: no semantic ranking available, showing the %d most important of %d memories", - extractRelevantCandidates, len(existing)) - return existing[:extractRelevantCandidates] + "memory: no semantic ranking available (%s), showing the %d most important memories", + skip, extractRelevantCandidates) + return existing[:extractRelevantCandidates], nil } - narrowed := make([]*types.MemoryItem, 0, extractRelevantCandidates) - for _, index := range ranking { - if len(narrowed) >= extractRelevantCandidates { - break - } - if index >= 0 && index < len(existing) && existing[index] != nil { - narrowed = append(narrowed, existing[index]) + relevant := make([]*types.MemoryItem, 0, len(hits)) + for _, hit := range hits { + if hit.Item != nil { + relevant = append(relevant, hit.Item) } } - logger.Infof(ctx, "memory: narrowed %d memories to %d relevant ones for extraction", - len(existing), len(narrowed)) - return narrowed + logger.Infof(ctx, "memory: showing extraction %d memories closest to this segment", + len(relevant)) + return relevant, nil } // callExtractionModel runs the single LLM call in the write path. diff --git a/internal/application/service/memory/recall_trace.go b/internal/application/service/memory/recall_trace.go index dd27efd4..2c728187 100644 --- a/internal/application/service/memory/recall_trace.go +++ b/internal/application/service/memory/recall_trace.go @@ -12,12 +12,16 @@ const recallQueryPreviewRunes = 500 // recallRankingTrace captures how situational items were ranked for one turn. type recallRankingTrace struct { - LexicalHits int - VectorHits int - VectorSkipReason string - FusedCandidates int - Matched int - Mode string + LexicalHits int + VectorHits int + // VectorOutsidePool counts semantic matches the lexical pool did not hold. + // Every one of these was unreachable while candidate selection happened + // before the query was looked at. + VectorOutsidePool int + VectorSkipReason string + FusedCandidates int + Matched int + Mode string } // scopeDisableReason explains why memory is off for this request. Only called @@ -58,6 +62,7 @@ func (s *Service) recallEmptyMeta( "candidate_count": candidateCount, "lexical_hits": rankTrace.LexicalHits, "vector_hits": rankTrace.VectorHits, + "vector_outside": rankTrace.VectorOutsidePool, "vector_skip": rankTrace.VectorSkipReason, "ranking_mode": rankTrace.Mode, "fused_candidates": rankTrace.FusedCandidates, @@ -124,25 +129,117 @@ func selectResidentInterests( return selected, relevant } -// selectRecallWithTrace ranks candidates against the query and returns the -// best ones that fit in maxItems and runeBudget. The budgets are arguments -// rather than constants because the same fusion serves two callers with very -// different economics: a per-turn recall that must stay small, and an -// on-demand search the model paid a tool call for. +// recallSelection is one ranking request. +// +// A struct rather than a parameter list because the two callers differ in more +// than budgets: an on-demand search may return any kind and has nothing to +// exclude, while a turn's recall is restricted to situational kinds and must +// not repeat what the resident block already printed. Both of those now have +// to reach the vector stage, which no longer inherits them from a +// pre-filtered candidate list. +type recallSelection struct { + // Query is what the memories are ranked against. + Query string + // Candidates is the lexically searchable pool, already loaded. + Candidates []*types.MemoryItem + // Kinds bounds what the semantic search may surface. Empty means any kind. + Kinds []string + // ExcludeIDs are memories the caller has already used. + ExcludeIDs map[string]struct{} + // MaxItems and RuneBudget bound the result. + MaxItems int + RuneBudget int +} + +// vectorFanout is how many semantic hits to ask the store for, relative to +// how many items may be returned. +// +// Wider than the output because fusion needs something to fuse: a hit that +// only the vector side likes has to compete with the lexical ranking, and the +// rune budget can skip over several long items before it finds ones that fit. +// Four times the output with a floor keeps that headroom without turning a +// five-item recall into a hundred-row read. +func vectorFanout(maxItems int) int { + limit := maxItems * 4 + if limit < 20 { + limit = 20 + } + return limit +} + +// mergeVectorHits turns semantic hits into a ranking over the candidate pool, +// growing that pool with the matches it did not already contain. +// +// The pool has to grow, or the whole point of searching the store is lost: +// the rankings that fusion combines must address the same slice, so a match +// that only the vector side found needs a place in it. Returns the ranking, +// the pool it addresses, and how many items the search added — the last one +// only so the trace can show it. +func mergeVectorHits( + candidates []*types.MemoryItem, + hits []interfaces.MemoryVectorHit, + excludeIDs map[string]struct{}, +) ([]int, []*types.MemoryItem, int) { + if len(hits) == 0 { + return nil, candidates, 0 + } + indexByID := make(map[string]int, len(candidates)) + for i, item := range candidates { + if item != nil && item.ID != "" { + indexByID[item.ID] = i + } + } + // Copy before appending. The caller's slice may share a backing array with + // the list it was filtered out of, and growing into that would rewrite + // rows nobody asked us to touch. + pool := candidates + copied := false + added := 0 + + ranking := make([]int, 0, len(hits)) + for _, hit := range hits { + if hit.Item == nil || hit.Item.ID == "" { + continue + } + if _, skip := excludeIDs[hit.Item.ID]; skip { + continue + } + if index, ok := indexByID[hit.Item.ID]; ok { + ranking = append(ranking, index) + continue + } + if !copied { + pool = append([]*types.MemoryItem(nil), candidates...) + copied = true + } + pool = append(pool, hit.Item) + index := len(pool) - 1 + indexByID[hit.Item.ID] = index + ranking = append(ranking, index) + added++ + } + return ranking, pool, added +} + +// selectRecallWithTrace ranks memories against the query and returns the best +// ones that fit the request's budgets. +// +// Two rankings are fused. The lexical one scores the supplied pool; the +// semantic one is a search over every vector the subject has, so it can pull +// in a memory the pool never contained. That asymmetry is deliberate: exact +// wording is cheap to match in process, while "which of this person's +// memories is this question about" is the question a vector store exists to +// answer and must not be asked of an arbitrary subset. func (s *Service) selectRecallWithTrace( ctx context.Context, scope interfaces.MemoryScope, cfg *types.MemoryConfig, - query string, - candidates []*types.MemoryItem, - maxItems int, - runeBudget int, + req recallSelection, ) ([]*types.MemoryItem, recallRankingTrace) { trace := recallRankingTrace{} - if len(candidates) == 0 { - trace.Mode = "no_candidates" - return nil, trace - } + query := req.Query + candidates := req.Candidates + maxItems, runeBudget := req.MaxItems, req.RuneBudget _, lexSpan := langfuse.GetManager().StartSpan(ctx, langfuse.SpanOptions{ Name: "memory.recall.lexical", @@ -167,11 +264,18 @@ func (s *Service) selectRecallWithTrace( "vector_enabled": cfg != nil && cfg.VectorRecallEnabled(), }, }) - vector, vectorSkip := s.vectorRanking(vecCtx, scope, cfg, query, candidates) + hits, vectorSkip := s.vectorSearch( + vecCtx, scope, cfg, query, req.Kinds, vectorFanout(maxItems)) + vector, candidates, fetched := mergeVectorHits(candidates, hits, req.ExcludeIDs) trace.VectorHits = len(vector) + trace.VectorOutsidePool = fetched trace.VectorSkipReason = vectorSkip vecOut := map[string]interface{}{ "hits": trace.VectorHits, + // How many matches the lexical pool did not contain. This is the + // number that used to be forced to zero, so it is the one to watch + // when asking whether semantic recall is doing anything. + "outside_pool": fetched, } if vectorSkip != "" { vecOut["skip_reason"] = vectorSkip @@ -180,14 +284,14 @@ func (s *Service) selectRecallWithTrace( if len(vector) == 0 { trace.Mode = "lexical_only" + if len(lexical) == 0 { + trace.Mode = "no_matches" + } matched := takeWithinBudget(lexical, candidates, maxItems, runeBudget) trace.Matched = len(matched) return matched, trace } - if len(vector) > maxItems*2 { - vector = vector[:maxItems*2] - } fused := fuseRankings(lexical, vector) trace.FusedCandidates = len(fused) trace.Mode = "hybrid" diff --git a/internal/application/service/memory/search.go b/internal/application/service/memory/search.go index 309843fe..6e61c5f4 100644 --- a/internal/application/service/memory/search.go +++ b/internal/application/service/memory/search.go @@ -10,14 +10,20 @@ import ( "github.com/Tencent/WeKnora/internal/types/interfaces" ) -// searchCandidatePool bounds how many stored items one search ranks over. +// lexicalPoolSize is how many stored items the lexical ranking scans. // -// It matches the recall pool deliberately. The pool was never what made recall -// miss things — four hundred candidates is more than almost any subject holds -// — the output cap of five items was. Widening the pool here would buy little -// and would put a few thousand embedding reads on a path the user is waiting -// on. -const searchCandidatePool = 400 +// It is the workspace capacity cap, which is the most active memories a +// subject can hold at all — so the pool is no longer a second, invisible limit +// sitting underneath it. It used to be a fixed 400 while the cap goes up to +// 2000, which made every memory past the 400th most important one impossible +// to recall, whatever the question was. +// +// The lexical side is bounded at all only because it scores in process. +// Semantic matching is not bounded by this: it searches the store directly, so +// a large subject is answered by the index rather than by whatever fits here. +func lexicalPoolSize(cfg *types.MemoryConfig) int { + return cfg.EffectiveMaxItems() +} // MemoryAvailable reports whether this request may read memory at all. // @@ -88,7 +94,7 @@ func (s *Service) SearchMemory( limit = types.MemorySearchMaxItems } - candidates, err := s.repo.ListActiveByKinds(searchCtx, scope, types.MemoryKinds, searchCandidatePool) + candidates, err := s.repo.ListActiveByKinds(searchCtx, scope, types.MemoryKinds, lexicalPoolSize(cfg)) if err != nil { logger.Warnf(searchCtx, "memory: load search candidates failed: %v", err) searchSpan.Finish(langfuse.SummarizeMemoryRecallOutput(map[string]interface{}{ @@ -98,8 +104,13 @@ func (s *Service) SearchMemory( return interfaces.MemorySearchResult{Available: true} } - matched, rankTrace := s.selectRecallWithTrace( - searchCtx, scope, cfg, query, candidates, limit, types.MemorySearchRuneBudget) + matched, rankTrace := s.selectRecallWithTrace(searchCtx, scope, cfg, recallSelection{ + Query: query, + Candidates: candidates, + Kinds: types.MemoryKinds, + MaxItems: limit, + RuneBudget: types.MemorySearchRuneBudget, + }) // A searched memory was read by the model just as surely as an injected // one, so it counts as used. Without this the items only reachable through @@ -108,14 +119,16 @@ func (s *Service) SearchMemory( s.touchAsync(searchCtx, scope, matched) logger.Infof(searchCtx, - "memory: search done subject=%s candidates=%d matched=%d mode=%s", - scope.SubjectID, len(candidates), len(matched), rankTrace.Mode) + "memory: search done subject=%s candidates=%d vector_hits=%d outside_pool=%d matched=%d mode=%s", + scope.SubjectID, len(candidates), rankTrace.VectorHits, + rankTrace.VectorOutsidePool, len(matched), rankTrace.Mode) searchSpan.Finish(langfuse.SummarizeMemoryRecallOutput(map[string]interface{}{ "outcome": "ok", "subject_id": scope.SubjectID, "candidate_count": len(candidates), "lexical_hits": rankTrace.LexicalHits, "vector_hits": rankTrace.VectorHits, + "vector_outside": rankTrace.VectorOutsidePool, "vector_skip": rankTrace.VectorSkipReason, "ranking_mode": rankTrace.Mode, "matched_count": len(matched), diff --git a/internal/application/service/memory/service.go b/internal/application/service/memory/service.go index ffe41853..472fe07e 100644 --- a/internal/application/service/memory/service.go +++ b/internal/application/service/memory/service.go @@ -168,7 +168,7 @@ func (s *Service) Recall(ctx context.Context, query string) interfaces.MemoryRec } situational, err := s.repo.ListActiveByKinds(recallCtx, scope, - []string{types.MemoryKindFact, types.MemoryKindTask}, 400) + []string{types.MemoryKindFact, types.MemoryKindTask}, lexicalPoolSize(cfg)) if err != nil { logger.Warnf(recallCtx, "memory: load situational items failed: %v", err) situational = nil @@ -190,8 +190,17 @@ func (s *Service) Recall(ctx context.Context, query string) interfaces.MemoryRec "memory: recall start subject=%s resident=%d candidates=%d block_runes=%d", scope.SubjectID, len(residentItems), len(candidates), len([]rune(block))) - matched, rankTrace := s.selectRecallWithTrace(recallCtx, scope, cfg, query, candidates, - types.MemoryRecallMaxItems, types.MemoryRecallRuneBudget) + matched, rankTrace := s.selectRecallWithTrace(recallCtx, scope, cfg, recallSelection{ + Query: query, + Candidates: candidates, + Kinds: []string{types.MemoryKindFact, types.MemoryKindTask}, + // The semantic search runs over the whole subject, so it can find a + // resident memory the block already printed. Passing the exclusion in + // keeps that from being injected twice. + ExcludeIDs: resident, + MaxItems: types.MemoryRecallMaxItems, + RuneBudget: types.MemoryRecallRuneBudget, + }) prompt := types.WrapMemoryForPrompt(block, types.RenderMemoryRecall(matched)) if prompt == "" { @@ -219,8 +228,10 @@ func (s *Service) Recall(ctx context.Context, query string) interfaces.MemoryRec s.touchAsync(recallCtx, scope, used) logger.Infof(recallCtx, - "memory: recall done subject=%s used=%d matched=%d interest_injected=%d interest_relevant=%d mode=%s prompt_runes=%d", - scope.SubjectID, len(used), len(matched), len(selectedInterests), len(relevantInterests), + "memory: recall done subject=%s used=%d matched=%d outside_pool=%d "+ + "interest_injected=%d interest_relevant=%d mode=%s prompt_runes=%d", + scope.SubjectID, len(used), len(matched), rankTrace.VectorOutsidePool, + len(selectedInterests), len(relevantInterests), rankTrace.Mode, len([]rune(prompt))) recallSpan.Finish(langfuse.SummarizeMemoryRecallOutput(map[string]interface{}{ "outcome": "ok", @@ -230,6 +241,7 @@ func (s *Service) Recall(ctx context.Context, query string) interfaces.MemoryRec "candidate_count": len(candidates), "lexical_hits": rankTrace.LexicalHits, "vector_hits": rankTrace.VectorHits, + "vector_outside": rankTrace.VectorOutsidePool, "vector_skip": rankTrace.VectorSkipReason, "ranking_mode": rankTrace.Mode, "fused_candidates": rankTrace.FusedCandidates, diff --git a/internal/application/service/memory/vector.go b/internal/application/service/memory/vector.go index 0cab4176..f25112a4 100644 --- a/internal/application/service/memory/vector.go +++ b/internal/application/service/memory/vector.go @@ -37,10 +37,18 @@ const ( // slightly lower because the lexical ranking is fused in alongside and can // still rescue an exact-term match the model embedded poorly. minCosine = 0.5 - // vectorCandidateCap bounds how many stored vectors one recall loads. - vectorCandidateCap = 400 // backfillPerRun is how many missing vectors one maintenance pass fills. - backfillPerRun = 50 + // + // Each one costs an embedding call, so this is a rate rather than a batch + // size. It has to outpace what a busy subject accumulates while its model + // is unreachable; at the previous 50 a subject sitting at the capacity cap + // took over a month before semantic recall could see all of it, which in + // practice meant it never could. + backfillPerRun = 200 + // vectorSyncPerRun is how many rows one maintenance pass moves into the + // database's vector type. Far larger than the embedding backfill because + // it makes no model calls: the vector already exists. + vectorSyncPerRun = 2000 ) // embedder resolves the embedding model pinned on this workspace. @@ -177,21 +185,26 @@ func (s *Service) embedAliases( return stat.Aliases } -// vectorRanking scores candidates against a query by cosine similarity and -// returns them best-first. An empty result means semantic scoring was -// unavailable, not that nothing matched — callers fall back rather than -// treating it as an empty match set. skipReason is set when vector recall was -// not attempted or could not run. -func (s *Service) vectorRanking( +// vectorSearch asks the store for the memories closest to the query. +// +// The search runs over every vector the subject has. It used to run over the +// vectors of an already-chosen candidate list, which meant semantic recall +// could only re-order what a plain `ORDER BY importance` had picked — a memory +// that answered the question exactly but sat outside that window was +// unreachable, and no amount of widening the window fixes the ordering being +// blind to the question in the first place. +// +// An empty result means semantic matching was unavailable or found nothing; +// callers fall back to lexical matching rather than treating it as "nothing +// matched". skipReason says which. +func (s *Service) vectorSearch( ctx context.Context, scope interfaces.MemoryScope, cfg *types.MemoryConfig, query string, - candidates []*types.MemoryItem, -) ([]int, string) { - if len(candidates) == 0 { - return nil, "no_candidates" - } + kinds []string, + limit int, +) ([]interfaces.MemoryVectorHit, string) { modelID, ok := s.embedder(ctx, cfg) if !ok { return nil, "vector_disabled" @@ -200,54 +213,21 @@ func (s *Service) vectorRanking( if len(queryVector) == 0 { return nil, "embed_failed" } - - ids := make([]string, 0, len(candidates)) - indexByID := make(map[string]int, len(candidates)) - for i, item := range candidates { - if item == nil || item.ID == "" { - continue - } - ids = append(ids, item.ID) - indexByID[item.ID] = i - if len(ids) >= vectorCandidateCap { - break - } - } - vectors, err := s.repo.ItemEmbeddings(ctx, scope, ids, modelID) + hits, err := s.repo.SearchItemsByVector(ctx, scope, interfaces.MemoryVectorQuery{ + ModelID: modelID, + Vector: queryVector, + Kinds: kinds, + MinScore: minCosine, + Limit: limit, + }) if err != nil { - logger.Warnf(ctx, "memory: load embeddings failed: %v", err) - return nil, "load_embeddings_failed" + logger.Warnf(ctx, "memory: vector search failed: %v", err) + return nil, "vector_search_failed" } - if len(vectors) == 0 { - return nil, "no_stored_vectors" + if len(hits) == 0 { + return nil, "no_vector_matches" } - - type scored struct { - index int - score float64 - } - ranked := make([]scored, 0, len(vectors)) - for _, id := range ids { - vector, ok := vectors[id] - if !ok { - continue - } - similarity := types.CosineSimilarity(queryVector, vector) - if similarity < minCosine { - continue - } - ranked = append(ranked, scored{index: indexByID[id], score: similarity}) - } - sortScoredDesc(ranked, func(i int) float64 { return ranked[i].score }) - - out := make([]int, 0, len(ranked)) - for _, entry := range ranked { - out = append(out, entry.index) - } - if len(out) == 0 { - return nil, "below_similarity_threshold" - } - return out, "" + return hits, "" } // fuseRankings combines two ranked id lists by reciprocal rank fusion. @@ -319,11 +299,6 @@ func (s *Service) backfillEmbeddings( return filled } -// sortScoredDesc sorts in place, highest score first. -func sortScoredDesc[T any](items []T, score func(int) float64) { - sort.SliceStable(items, func(i, j int) bool { return score(i) > score(j) }) -} - // sortStableByIndexScore sorts in place, highest score first, preserving the // original order among ties so a stable input produces a stable output. func sortStableByIndexScore(indexes []int, score func(int) float64) { diff --git a/internal/application/service/memory/vector_postgres_test.go b/internal/application/service/memory/vector_postgres_test.go new file mode 100644 index 00000000..030c5104 --- /dev/null +++ b/internal/application/service/memory/vector_postgres_test.go @@ -0,0 +1,130 @@ +package memory + +import ( + "context" + "os" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/application/repository" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/google/uuid" + "github.com/stretchr/testify/require" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" +) + +// The SQL ranking is the path production takes, and it is the one path the +// SQLite tests cannot reach: halfvec, the distance operator and the join all +// only exist on PostgreSQL. Without this, a change that breaks the query would +// pass every test and fail every real recall. +// +// Opt in with a disposable database that has pgvector installed. +func TestVectorSearchRanksInPostgres(t *testing.T) { + dsn := os.Getenv("WEKNORA_MEMORY_TEST_POSTGRES_DSN") + if dsn == "" { + t.Skip("set WEKNORA_MEMORY_TEST_POSTGRES_DSN to run PostgreSQL integration tests") + } + admin, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Discard}) + require.NoError(t, err) + sqlAdmin, err := admin.DB() + require.NoError(t, err) + defer func() { require.NoError(t, sqlAdmin.Close()) }() + require.NoError(t, admin.Exec(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`).Error) + require.NoError(t, admin.Exec(`CREATE EXTENSION IF NOT EXISTS vector`).Error) + schema := "memory_vec_" + uuid.NewString()[:8] + require.NoError(t, admin.Exec("CREATE SCHEMA "+schema).Error) + defer admin.Exec("DROP SCHEMA " + schema + " CASCADE") + + db, err := gorm.Open( + postgres.Open(dsn+" search_path="+schema+",public"), + &gorm.Config{Logger: logger.Discard}, + ) + require.NoError(t, err) + sqlDB, err := db.DB() + require.NoError(t, err) + defer func() { require.NoError(t, sqlDB.Close()) }() + + require.NoError(t, db.Exec("CREATE TABLE tenants (id BIGINT PRIMARY KEY)").Error) + require.NoError(t, db.Exec("CREATE TABLE messages (id VARCHAR(36) PRIMARY KEY)").Error) + execMemoryMigration(t, db, "../../../../migrations/versioned/000084_memory.up.sql") + execMemoryMigration(t, db, "../../../../migrations/versioned/000094_memory_consistency.up.sql") + // Whole-file exec: the migration is one DO block, so splitting it on + // semicolons the way execMemoryMigration does would cut it apart. + vectorSearchMigration, err := os.ReadFile( + "../../../../migrations/versioned/000095_memory_vector_search.up.sql") + require.NoError(t, err) + require.NoError(t, db.Exec(string(vectorSearchMigration)).Error) + require.True(t, db.Migrator().HasColumn(&types.MemoryItemEmbedding{}, "embedding"), + "the migration has to add the column the ranking sorts by") + + repo := repository.NewMemoryRepository(db) + ctx := context.Background() + scope := interfaces.MemoryScope{TenantID: 7, SubjectID: "alice"} + _, err = repo.EnsureSubject(ctx, scope) + require.NoError(t, err) + + seed := []struct { + content string + kind string + vector []float32 + expires *time.Time + }{ + {content: "回答直接给结论", kind: types.MemoryKindFact, vector: []float32{1, 0, 0}}, + {content: "生产库的连接池配置", kind: types.MemoryKindFact, vector: []float32{0, 1, 0}}, + {content: "本周的评审安排", kind: types.MemoryKindTask, vector: []float32{0.99, 0.1, 0}}, + } + past := time.Now().Add(-time.Hour) + seed[2].expires = &past + + ids := make([]string, 0, len(seed)) + for _, row := range seed { + item := &types.MemoryItem{ + ID: uuid.NewString(), TenantID: scope.TenantID, SubjectID: scope.SubjectID, + Kind: row.kind, Content: row.content, Topic: row.content, + NormalizedKey: row.content, Status: types.MemoryStatusActive, + ValidFrom: time.Now(), ExpiresAt: row.expires, + } + require.NoError(t, repo.SaveItem(ctx, scope, item, "")) + require.NoError(t, repo.UpsertItemEmbedding(ctx, scope, &types.MemoryItemEmbedding{ + ItemID: item.ID, ModelID: "embed-1", + Dims: len(row.vector), Vector: types.EncodeEmbedding(row.vector), + })) + ids = append(ids, item.ID) + } + + // The upsert has to populate the vector column, not only the blob: a row + // the ranking cannot see is a memory recall cannot find. + var ranked int64 + require.NoError(t, db.Table("memory_item_embeddings"). + Where("embedding IS NOT NULL").Count(&ranked).Error) + require.EqualValues(t, len(seed), ranked) + + hits, err := repo.SearchItemsByVector(ctx, scope, interfaces.MemoryVectorQuery{ + ModelID: "embed-1", + Vector: []float32{0.98, 0.2, 0}, + MinScore: minCosine, + Limit: 10, + }) + require.NoError(t, err) + require.Len(t, hits, 1, "the expired task scores highest and still must not be a match") + require.Equal(t, ids[0], hits[0].Item.ID) + require.Greater(t, hits[0].Score, 0.9) + + // A vector written before the column existed still has to become + // searchable, and without spending an embedding call to rediscover a + // number that is already stored. + require.NoError(t, db.Exec( + "UPDATE memory_item_embeddings SET embedding = NULL WHERE item_id = ?", ids[0]).Error) + moved, err := repo.SyncVectorColumn(ctx, scope, 100) + require.NoError(t, err) + require.Equal(t, 1, moved) + hits, err = repo.SearchItemsByVector(ctx, scope, interfaces.MemoryVectorQuery{ + ModelID: "embed-1", Vector: []float32{0.98, 0.2, 0}, MinScore: minCosine, Limit: 10, + }) + require.NoError(t, err) + require.Len(t, hits, 1) + require.Equal(t, ids[0], hits[0].Item.ID) +} diff --git a/internal/application/service/memory/vector_scope_test.go b/internal/application/service/memory/vector_scope_test.go new file mode 100644 index 00000000..071e6269 --- /dev/null +++ b/internal/application/service/memory/vector_scope_test.go @@ -0,0 +1,213 @@ +package memory + +import ( + "fmt" + "strings" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/stretchr/testify/require" +) + +// Semantic recall used to score only the memories a prior `ORDER BY +// importance` had already listed. Importance says nothing about whether a +// memory answers the question, so the ranking could re-order that window but +// never look outside it — a well-matching memory below the cut was +// unreachable, and the only knob available was to make the window bigger. +// +// These tests pin the inverted order: the store is asked which memories are +// closest to the question, over everything it holds. + +func TestVectorSearchRanksTheWholeSubjectNotAListedWindow(t *testing.T) { + svc, tenantRepo, _ := newVectorHarness(t) + ctx := enabledCtx(t, tenantRepo, 1, "alice") + scope := scopeFor(t, ctx) + + // The memory that answers the question is the least important one, so any + // importance-ordered window of size one excludes it. + _, err := svc.Remember(ctx, types.MemoryItem{ + Kind: types.MemoryKindFact, Topic: "回答风格", Content: "回答直接给结论", Importance: 1, + }) + require.NoError(t, err) + _, err = svc.Remember(ctx, types.MemoryItem{ + Kind: types.MemoryKindFact, Topic: "数据库", Content: "生产库的连接池配置", Importance: 5, + }) + require.NoError(t, err) + + window, err := svc.repo.ListActiveByKinds(ctx, scope, []string{types.MemoryKindFact}, 1) + require.NoError(t, err) + require.Len(t, window, 1) + require.Equal(t, "生产库的连接池配置", window[0].Content, + "the window the old implementation scored holds the wrong memory") + + hits, err := svc.repo.SearchItemsByVector(ctx, scope, interfaces.MemoryVectorQuery{ + ModelID: "embed-1", + Vector: []float32{0.98, 0.2, 0}, + Kinds: []string{types.MemoryKindFact}, + MinScore: minCosine, + Limit: 1, + }) + require.NoError(t, err) + require.Len(t, hits, 1) + require.Equal(t, "回答直接给结论", hits[0].Item.Content, + "the search has to see every stored vector, not the ones importance listed") + require.Greater(t, hits[0].Score, minCosine) +} + +// A search that reached past the candidate list would also reach past the +// filters that list applied, which is how a superseded or expired memory gets +// back into an answer. The filters move into the search instead. +func TestVectorSearchHonoursKindAndLifecycleFilters(t *testing.T) { + svc, db, tenantRepo, _ := newVectorHarnessWithDB(t) + ctx := enabledCtx(t, tenantRepo, 1, "alice") + scope := scopeFor(t, ctx) + + _, err := svc.Remember(ctx, types.MemoryItem{ + Kind: types.MemoryKindPreference, Topic: "回答风格", Content: "回答直接给结论", + }) + require.NoError(t, err) + expired, err := svc.Remember(ctx, types.MemoryItem{ + Kind: types.MemoryKindTask, Topic: "待办", Content: "本周要回答直接给结论的评审", + }) + require.NoError(t, err) + require.NoError(t, db.Exec("UPDATE memory_items SET expires_at = ? WHERE id = ?", + time.Now().Add(-time.Hour), expired.ID).Error) + + query := interfaces.MemoryVectorQuery{ + ModelID: "embed-1", + Vector: []float32{0.98, 0.2, 0}, + MinScore: minCosine, + Limit: 10, + } + + all, err := svc.repo.SearchItemsByVector(ctx, scope, query) + require.NoError(t, err) + for _, hit := range all { + require.NotEqual(t, expired.ID, hit.Item.ID, "an expired memory is not a match") + } + require.Len(t, all, 1) + + query.Kinds = []string{types.MemoryKindFact} + none, err := svc.repo.SearchItemsByVector(ctx, scope, query) + require.NoError(t, err) + require.Empty(t, none, "a kind the caller excluded must not come back") +} + +// Fusion combines two rankings over one slice, so a match only the vector side +// found has to be added to that slice. Dropping it instead would make the +// wider search pointless. +func TestMergeVectorHitsGrowsThePoolWithWhatItDidNotHold(t *testing.T) { + inPool := &types.MemoryItem{ID: "a", Content: "已经在候选池里"} + outsidePool := &types.MemoryItem{ID: "b", Content: "候选池没有的记忆"} + excluded := &types.MemoryItem{ID: "c", Content: "常驻块已经写过"} + + // Room to spare, so an append that forgot to copy would overwrite the + // caller's slice rather than allocate. + candidates := make([]*types.MemoryItem, 1, 8) + candidates[0] = inPool + + ranking, pool, added := mergeVectorHits(candidates, + []interfaces.MemoryVectorHit{ + {Item: outsidePool, Score: 0.9}, + {Item: excluded, Score: 0.8}, + {Item: inPool, Score: 0.7}, + }, + map[string]struct{}{"c": {}}, + ) + + require.Equal(t, 1, added) + require.Equal(t, []int{1, 0}, ranking, "best first, addressing the returned pool") + require.Equal(t, []*types.MemoryItem{inPool, outsidePool}, pool) + require.Equal(t, []*types.MemoryItem{inPool}, candidates, + "the caller's slice is not written through") +} + +// The lexical pool was a fixed 400 while the capacity cap goes to 2000, which +// made everything past the 400th most important memory unrecallable. Tying the +// pool to the cap is what removes that second, invisible limit: the cap is +// also what write-time capacity enforcement trims to, so the pool now covers +// every live memory by construction. +func TestLexicalPoolCoversEveryLiveMemory(t *testing.T) { + svc, _, tenantRepo := newMemoryHarness(t) + ctx := enabledCtx(t, tenantRepo, 1, "alice") + cfg := &types.MemoryConfig{ + Enabled: true, WriteMode: types.MemoryWriteAuto, MaxItems: 3, + } + tenantRepo.set(1, cfg) + scope := scopeFor(t, ctx) + + for _, content := range []string{"第一条记忆", "第二条记忆", "第三条记忆", "第四条记忆", "第五条记忆"} { + _, err := svc.Remember(ctx, types.MemoryItem{ + Kind: types.MemoryKindFact, Topic: content, Content: content, + }) + require.NoError(t, err) + } + + active, err := svc.repo.CountActive(ctx, scope) + require.NoError(t, err) + require.GreaterOrEqual(t, int64(lexicalPoolSize(cfg)), active, + "the pool must not be a smaller limit than the one that decides what stays active") +} + +// Extraction decides whether a sentence updates something already stored, so +// the memories it is shown have to be the ones the sentence might collide +// with. Selecting them by importance first — which is what listing a pool did +// — hides exactly the collision that matters: a memory nobody marked important +// gets a second, contradicting copy written next to it, and both stay active. +func TestExtractionSeesTheMemoryItWouldDuplicateEvenWhenUnimportant(t *testing.T) { + svc, tenantRepo, messages, models, enqueuer := newExtractionHarness(t) + ctx := enabledCtx(t, tenantRepo, 1, "alice") + tenantRepo.set(1, &types.MemoryConfig{ + Enabled: true, WriteMode: types.MemoryWriteAuto, + ExtractModelID: "model-1", ExtractDelaySeconds: 1, + EmbeddingModelID: "embed-1", + }) + models.workspaceModels = []*types.Model{ + {ID: "embed-1", Type: types.ModelTypeEmbedding, Status: types.ModelStatusActive}, + } + models.embedder = &stubEmbedder{vectors: map[string][]float32{ + "连接数": {1, 0, 0}, + "生产库": {1, 0, 0}, + }} + models.response = `{"memories":[]}` + + // Enough important memories to fill the window on their own. + for i := 0; i <= extractRelevantCandidates; i++ { + _, err := svc.Remember(ctx, types.MemoryItem{ + Kind: types.MemoryKindFact, Importance: 5, + Topic: fmt.Sprintf("话题%d", i), + Content: fmt.Sprintf("与本次提问无关的第 %d 条记忆", i), + }) + require.NoError(t, err) + } + // The one the next turn contradicts is the least important of the lot, so + // every importance-ordered window excludes it. + _, err := svc.Remember(ctx, types.MemoryItem{ + Kind: types.MemoryKindFact, Importance: 1, + Topic: "生产库", Content: "生产库连接数上限是 200", + }) + require.NoError(t, err) + + messages.set("session-1", []*types.Message{ + userMessage("session-1", "生产库连接数上限昨天调成 500 了", time.Now().Add(-time.Hour)), + }) + svc.ScheduleExtraction(ctx, "session-1", "message-1", "model-1") + drainExtractions(t, svc, enqueuer) + + notes := existingNotesBlock(models.lastPromptContaining("What the user said:")) + require.Contains(t, notes, "生产库连接数上限是 200", + "the model cannot supersede a memory it was never shown") + require.LessOrEqual(t, strings.Count(notes, "\n["), extractRelevantCandidates, + "and it still must not be shown the whole store") +} + +// The fan-out feeds fusion. Asking for exactly as many hits as may be returned +// would leave nothing for the lexical ranking to be weighed against, and the +// rune budget can skip several long items before finding ones that fit. +func TestVectorFanoutLeavesRoomForFusion(t *testing.T) { + require.Equal(t, 20, vectorFanout(types.MemoryRecallMaxItems), + "a five-item recall still needs a usable ranking") + require.Equal(t, 80, vectorFanout(types.MemorySearchMaxItems)) +} diff --git a/internal/application/service/memory/vector_test.go b/internal/application/service/memory/vector_test.go index 02d5f9b6..db01516f 100644 --- a/internal/application/service/memory/vector_test.go +++ b/internal/application/service/memory/vector_test.go @@ -8,6 +8,7 @@ import ( "github.com/Tencent/WeKnora/internal/types" "github.com/stretchr/testify/require" + "gorm.io/gorm" ) // The reason for adding semantic recall at all: a memory the user has since @@ -16,7 +17,15 @@ import ( func newVectorHarness(t *testing.T) (*Service, *stubTenantRepo, *stubModelService) { t.Helper() - svc, _, tenantRepo := newMemoryHarness(t) + svc, _, tenantRepo, models := newVectorHarnessWithDB(t) + return svc, tenantRepo, models +} + +// newVectorHarnessWithDB also hands back the database, for the tests that have +// to arrange a row state no service method produces. +func newVectorHarnessWithDB(t *testing.T) (*Service, *gorm.DB, *stubTenantRepo, *stubModelService) { + t.Helper() + svc, db, tenantRepo := newMemoryHarness(t) models := &stubModelService{ workspaceModels: []*types.Model{ {ID: "embed-1", Type: types.ModelTypeEmbedding, Status: types.ModelStatusActive}, @@ -30,7 +39,7 @@ func newVectorHarness(t *testing.T) (*Service, *stubTenantRepo, *stubModelServic }}, } svc.modelService = models - return svc, tenantRepo, models + return svc, db, tenantRepo, models } func TestARewordedMemoryIsStillFound(t *testing.T) { diff --git a/internal/database/migration_sqlite_versioned_schema_test.go b/internal/database/migration_sqlite_versioned_schema_test.go index 5f858ce4..8dee622d 100644 --- a/internal/database/migration_sqlite_versioned_schema_test.go +++ b/internal/database/migration_sqlite_versioned_schema_test.go @@ -40,7 +40,7 @@ var versionedSQLiteColumns = map[string][]string{ "mcp_tool_approvals": {"enabled"}, // 000091 } -const expectedSQLiteMigrationVersion = 15 +const expectedSQLiteMigrationVersion = 16 func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) { repoRoot := sqliteRepoRoot(t) diff --git a/internal/types/interfaces/memory.go b/internal/types/interfaces/memory.go index eec1083f..f3c25e79 100644 --- a/internal/types/interfaces/memory.go +++ b/internal/types/interfaces/memory.go @@ -20,6 +20,27 @@ func (s MemoryScope) Valid() bool { return s.TenantID > 0 && s.SubjectID != "" } +// MemoryVectorQuery is one semantic lookup over a subject's stored vectors. +type MemoryVectorQuery struct { + // ModelID pins the vector space. Vectors from another model are skipped + // rather than scored, because the distance between them is meaningless. + ModelID string + // Vector is the embedded query. + Vector []float32 + // Kinds restricts which memories may come back. Empty means every kind. + Kinds []string + // MinScore is the cosine floor below which a match is not a match. + MinScore float64 + // Limit is how many hits to return, best first. + Limit int +} + +// MemoryVectorHit is one semantic match and how close it was. +type MemoryVectorHit struct { + Item *types.MemoryItem + Score float64 +} + // MemoryRepository is the storage contract for long-term memory. Every method // takes an explicit scope rather than reading it from ctx, so a background // worker cannot accidentally operate on whatever the ambient context happens @@ -120,6 +141,19 @@ type MemoryRepository interface { // Only vectors produced by modelID are returned: vectors from a different // model are not comparable, so mixing them would score nonsense. ItemEmbeddings(ctx context.Context, scope MemoryScope, itemIDs []string, modelID string) (map[string][]float32, error) + // SearchItemsByVector returns this subject's semantically closest items, + // ranked by the database over every vector it holds. + // + // It replaces "list some items, then score the ones that happened to be + // listed". That order was the bug: candidates were chosen by importance, + // which says nothing about whether an item answers the question, so a + // well-matching memory outside the listed window could not be found at all. + SearchItemsByVector(ctx context.Context, scope MemoryScope, query MemoryVectorQuery) ([]MemoryVectorHit, error) + // SyncVectorColumn copies stored vectors into the database's own vector + // type for rows written before there was one. Returns how many it moved, + // and 0 on a deployment that scores in process. No model calls: the vector + // already exists, only its representation is behind. + SyncVectorColumn(ctx context.Context, scope MemoryScope, limit int) (int, error) // ItemsMissingEmbeddings returns active items that have no vector yet, so a // background pass can fill them in. ItemsMissingEmbeddings(ctx context.Context, scope MemoryScope, modelID string, limit int) ([]*types.MemoryItem, error) diff --git a/internal/types/memory.go b/internal/types/memory.go index c8f39f03..e45586f8 100644 --- a/internal/types/memory.go +++ b/internal/types/memory.go @@ -12,6 +12,7 @@ import ( "math" "regexp" "sort" + "strconv" "strings" "time" "unicode" @@ -1409,6 +1410,26 @@ func DecodeEmbedding(raw []byte) []float32 { return out } +// FormatEmbeddingLiteral renders a vector the way pgvector parses it, so the +// database can do the distance arithmetic instead of shipping every stored +// vector to the application to be scored there. +func FormatEmbeddingLiteral(vector []float32) string { + if len(vector) == 0 { + return "" + } + var b strings.Builder + b.Grow(len(vector) * 8) + b.WriteByte('[') + for i, value := range vector { + if i > 0 { + b.WriteByte(',') + } + b.WriteString(strconv.FormatFloat(float64(value), 'f', -1, 32)) + } + b.WriteByte(']') + return b.String() +} + // CosineSimilarity scores two vectors in [-1, 1]. Mismatched lengths score 0: // vectors from different models are not comparable, and guessing is worse than // declining to answer. diff --git a/migrations/sqlite/000016_memory_vector_search.down.sql b/migrations/sqlite/000016_memory_vector_search.down.sql new file mode 100644 index 00000000..37e37f85 --- /dev/null +++ b/migrations/sqlite/000016_memory_vector_search.down.sql @@ -0,0 +1 @@ +DROP INDEX IF EXISTS idx_mem_emb_search; diff --git a/migrations/sqlite/000016_memory_vector_search.up.sql b/migrations/sqlite/000016_memory_vector_search.up.sql new file mode 100644 index 00000000..6f8e5c83 --- /dev/null +++ b/migrations/sqlite/000016_memory_vector_search.up.sql @@ -0,0 +1,5 @@ +-- Mirror of versioned 000095. SQLite has no vector type, so ranking stays in +-- the application here; what it can share is the index that keeps the read to +-- one subject's vectors instead of the whole table. +CREATE INDEX IF NOT EXISTS idx_mem_emb_search + ON memory_item_embeddings (tenant_id, subject_id, model_id, dims); diff --git a/migrations/versioned/000095_memory_vector_search.down.sql b/migrations/versioned/000095_memory_vector_search.down.sql new file mode 100644 index 00000000..ba25a9c0 --- /dev/null +++ b/migrations/versioned/000095_memory_vector_search.down.sql @@ -0,0 +1,11 @@ +-- Reverse 000095. The BYTEA vector is untouched, so dropping the derived +-- column only sends ranking back into the application. +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM information_schema.tables WHERE table_name = 'memory_item_embeddings' + ) THEN + ALTER TABLE memory_item_embeddings DROP COLUMN IF EXISTS embedding; + DROP INDEX IF EXISTS idx_mem_emb_search; + END IF; +END $$; diff --git a/migrations/versioned/000095_memory_vector_search.up.sql b/migrations/versioned/000095_memory_vector_search.up.sql new file mode 100644 index 00000000..4eb196a6 --- /dev/null +++ b/migrations/versioned/000095_memory_vector_search.up.sql @@ -0,0 +1,42 @@ +-- Migration 000095: move memory vector search into the database. +-- +-- Memory vectors were written as a BYTEA blob and scored in the application, +-- which forced recall to pick its candidates before it knew anything about +-- the question: it listed a few hundred items by importance and only then +-- looked at similarity. Importance is uncorrelated with relevance, so every +-- memory below that cut was unreachable no matter how well it matched. +-- +-- The fix is to let the database rank, which means the vector has to be a +-- vector to it. `embedding` mirrors the BYTEA column; BYTEA stays the source +-- of truth so a deployment without pgvector keeps working unchanged. +-- +-- No HNSW index. An approximate index is filtered after the fact, so a scan +-- restricted to one subject would get its k nearest neighbours from the whole +-- table and then throw nearly all of them away. One subject holds at most a +-- couple of thousand rows, and the scope index below makes exact ordering over +-- that a few milliseconds — correct and fast beats approximate and wrong here. +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.tables WHERE table_name = 'memory_item_embeddings' + ) THEN + RAISE NOTICE '[Migration 000095] memory_item_embeddings absent · skipping'; + RETURN; + END IF; + + -- Deployments whose RETRIEVE_DRIVER excludes postgres run 000002 with + -- app.skip_embedding=true and never create the vector extension. Memory + -- still works there: the repository falls back to scoring in process when + -- this column is missing, which is what the check below leaves behind. + IF NOT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'vector') THEN + RAISE NOTICE '[Migration 000095] vector extension absent · memory keeps scoring in process'; + ELSE + ALTER TABLE memory_item_embeddings ADD COLUMN IF NOT EXISTS embedding halfvec; + RAISE NOTICE '[Migration 000095] memory_item_embeddings.embedding ready'; + END IF; + + -- Useful with or without pgvector: both the SQL ranking and the fallback + -- read every vector of one (subject, model, dims), and nothing else. + CREATE INDEX IF NOT EXISTS idx_mem_emb_search + ON memory_item_embeddings (tenant_id, subject_id, model_id, dims); +END $$;