Files
magpie/internal/memembed/memembed_test.go
T
yetone d77eb6d236 memory: search by meaning, on a small model on this computer
A memory search now finds what means the same in other words or another
language ("什么时候上线" finds "Releases go out on Tuesdays"), for the
MCP server's memory_search and the Library's Memory tab alike. It is off
until switched on under Memory → Search by meaning, since it downloads
paraphrase-multilingual-MiniLM-L12-v2 (Xenova's int8 ONNX, ~135 MB,
pinned revision, size and sha256 checked); switched off, the model is
deleted.

- internal/pii/guard: the BERT code runs the embedder too (LoadEmbedder,
  mean pooling; the tokenizer reads 250,002 pieces and WhitespaceSplit).
  Its vectors match ONNX Runtime's int8 to cosine >= 0.995 and are no
  further from fp32 than ORT's own; testdata carries both.
- internal/memembed: the switch, the download, vectors.bin keyed by each
  memory's sha256 (read once, again when the text changes, a cut-short
  file read as none), Keep reading in the backend, the model let go after
  10 minutes unused.
- internal/memory: memory.Semantic fuses the meaning ranking with the word
  ranking by reciprocal rank; a tie goes to the nearer in meaning, since
  a first word hit may hold one common word ("when do we release" had
  "Never delete images when..." first). Near 0.30 / Within 0.15 come from
  97 real memories and 16 queries, half Chinese for English memories:
  12 of 16 sought found with ~4 others each. Rank searches without noting
  memories used.
- GUI: the Search by meaning row (download %, memories read, failures),
  and the tab's search lists what the backend ranked first
  (POST /api/memory/rank), then word matches. zh, zh-TW, ja, de.
- docs/subsystems/memory.md: the section, out of "Not built yet".

Why not multilingual-e5-small, which this was built on first: run for
real, its cosines sat at 0.78-0.89 for everything, and a Chinese search
ranked Chinese memories over the English one it meant. e5-small, e5-base
and MiniLM were compared in ONNX Runtime on the same 97 memories; MiniLM
put the sought one first 9 of 16 and in the top 3 12 of 16, with the
rest at a median cosine of 0.16.

Run before the rebases (mote, on origin/main as of the work):
- gofmt -l internal/ clean; go vet of memembed, memory, pii/..., gui,
  library; GOOS=linux and GOOS=windows vet of memembed and pii/guard.
- MAGPIE_EMBED_DIR=~/models/pml go test -run Embedder ./internal/pii/guard:
  7 texts (CJK, full width, emoji, digits before runs of spaces) at
  0.9962-1.0000 with ORT int8.
- go test memembed, memory, memdistill, pii/..., library, browsermcp.
- Linux (magpie-desktop, -tags nogui, mote's disk was full): go test
  memembed, memory, pii/guard, gui (461s), cli (1228s, past the default
  10m timeout, so -timeout 30m); gateway -run 'MemoryMCP|OwnMCP'.
- Rebased on origin/main 3ebb1ba2c, on mote at this tree: gofmt -l
  internal/ clean; go vet of memembed, memory, pii/..., library, gui,
  gateway, and GOOS=linux and GOOS=windows vet of the first four; go
  test memembed, memory, pii/..., library, browsermcp (Embedder test on
  ~/models/pml); gateway -run 'MemoryMCP|OwnMCP'; cli -run
  'Settings|Parity|Budget'.
- Rebased again on origin/main 5d6935b11 (title bar, cli parity,
  account export, provider catalog): go vet of gui and cli; go test -run
  'Settings|Parity|Budget' of cli and gui, ok with the Bark test fix two
  commits up (TestSettingsSaveKeepsWhatItDoesNotSend, red on main).
- GUI on mote, this commit plus the next (90f4a377b, which fixes
  library-bar-more for #5982): every library-*.test.cjs, i18n-keys and
  i18n-en-no-cjk, BROWSER=chromium and webkit, 701/702 each. The red is
  library-loading's tab list, which has no "Claude plugins" (6af54dc9a)
  and is red alone at origin/main faffb1e95 (#5997). library-bili's
  webkit saved count times out about 1 run in 3, on main too (#6015).
- A real switch-on: the pinned files downloaded from Hugging Face and
  checked in 11s, 5 memories read; 什么时候上线, 端口被占用怎么办, 清理磁盘,
  回复用什么语言 and "when do we release" each find their memory first.
  缩进用什么 finds nothing (0.23 to the tabs memory, under Near).
- Broken by hand: without the tie rule, TestSearchFindsByMeaning's new
  case is red (images first).

Not run: the whole Go suite and the whole GUI suite; go test of
internal/gui and the whole of internal/cli after the rebases (WSL kept
restarting, and they passed on Linux before).
2026-11-11 04:14:58 +08:00

195 lines
5.9 KiB
Go

package memembed
import (
"context"
"math"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"github.com/yetone/magpie/internal/memory"
"github.com/yetone/magpie/internal/pii/guard"
"github.com/yetone/magpie/internal/testenv"
)
func TestMain(m *testing.M) { testenv.Main(m) }
// fake reads a text as the topics it names, in either language: what a
// real model does for a search across languages, without its 135 MB.
type fake struct{ calls atomic.Int32 }
var topics = [][]string{
{"release", "ship", "上线", "发布"},
{"tabs", "indent", "缩进"},
{"port", "端口"},
}
func (f *fake) Embed(text string) []float32 {
f.calls.Add(1)
v := make([]float32, guard.EmbedDim)
v[len(v)-1] = 0.5 // something in common, as real texts have
for i, words := range topics {
for _, w := range words {
if strings.Contains(strings.ToLower(text), w) {
v[i] = 1
}
}
}
var sq float64
for _, x := range v {
sq += float64(x) * float64(x)
}
for i := range v {
v[i] /= float32(math.Sqrt(sq))
}
return v
}
// sandbox points memembed and memory at a folder of the test's own, with
// the model's files on disk at their sizes (sparse) and a fake model.
func sandbox(t *testing.T, installed bool) *fake {
t.Helper()
d := t.TempDir()
oldRoot, oldState, oldMem, oldLoad := Root, StatePath, memory.Path, loadModel
Root = func() string { return filepath.Join(d, "model") }
StatePath = func() string { return filepath.Join(d, "memory-semantic.json") }
memory.Path = func() string { return filepath.Join(d, "memory.json") }
f := &fake{}
loadModel = func(string) (embedder, error) { return f, nil }
t.Cleanup(func() {
Root, StatePath, memory.Path, loadModel = oldRoot, oldState, oldMem, oldLoad
unload()
store.mu.Lock()
store.v = nil
store.mu.Unlock()
})
if installed {
if err := os.MkdirAll(dir(), 0o755); err != nil {
t.Fatal(err)
}
for _, p := range files {
path := filepath.Join(dir(), filepath.Base(p.path))
if err := os.WriteFile(path, nil, 0o644); err != nil {
t.Fatal(err)
}
if err := os.Truncate(path, p.size); err != nil {
t.Fatal(err)
}
}
b := []byte(`{"on":true}`)
if err := os.WriteFile(StatePath(), b, 0o600); err != nil {
t.Fatal(err)
}
}
return f
}
func save(t *testing.T, text, status string) *memory.Memory {
t.Helper()
k, sc := memory.Fact, memory.Global
m, _, err := memory.Save(memory.Input{Text: &text, Kind: &k, Scope: &sc, Status: &status}, memory.FromUser, nil, nil)
if err != nil {
t.Fatal(err)
}
return m
}
func ids(hs []memory.Hit) []string {
out := []string{}
for _, h := range hs {
out = append(out, h.Text)
}
return out
}
// A search finds what means the same in other words and another language,
// beside what holds its words; switched off, by words alone.
func TestSearchFindsByMeaning(t *testing.T) {
sandbox(t, true)
save(t, "Releases go out on Tuesdays", memory.Active)
save(t, "Use tabs, never spaces", memory.Active)
save(t, "A busy port is someone else's", memory.Active)
hits, err := memory.Search(memory.Query{Text: "什么时候上线"})
if err != nil || len(hits) != 1 || hits[0].Text != "Releases go out on Tuesdays" {
t.Fatalf("%v %v", ids(hits), err)
}
// found both ways ahead of found one way: "never" is in one, and
// both mean 缩进
save(t, "Indent Go files with tabs", memory.Active)
hits, _ = memory.Search(memory.Query{Text: "never 缩进"})
if got := ids(hits); len(got) != 2 || got[0] != "Use tabs, never spaces" || got[1] != "Indent Go files with tabs" {
t.Fatalf("%v", got)
}
// one common word ranks as high as the nearest in meaning; the nearer
// in meaning goes first, though the other is newer
save(t, "Never delete images when freeing disk space", memory.Active)
hits, _ = memory.Search(memory.Query{Text: "when do we release"})
if got := ids(hits); len(got) != 2 || got[0] != "Releases go out on Tuesdays" {
t.Fatalf("%v", got)
}
if err := Set(false); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(Root()); !os.IsNotExist(err) {
t.Fatalf("the model is still there: %v", err)
}
if hits, _ := memory.Search(memory.Query{Text: "什么时候上线"}); len(hits) != 0 {
t.Fatalf("off, by meaning: %v", ids(hits))
}
}
// Index reads what a search can return and has no vector for its text:
// once, again when its text changes, and the old text's vector goes. The
// vectors are kept on disk, and a file cut short is read as none.
func TestIndexReadsOnce(t *testing.T) {
f := sandbox(t, true)
a := save(t, "Releases go out on Tuesdays", memory.Active)
save(t, "Use tabs", memory.Candidate)
save(t, "Old port rule", memory.Archived)
if n, err := Index(context.Background()); err != nil || n != 2 {
t.Fatalf("%d %v", n, err)
}
if n, _ := Index(context.Background()); n != 0 || f.calls.Load() != 2 {
t.Fatalf("read again: %d, %d calls", n, f.calls.Load())
}
text := "Releases go out on Wednesdays"
if _, err := memory.Edit(a.ID, memory.Input{Text: &text}, true); err != nil {
t.Fatal(err)
}
if n, _ := Index(context.Background()); n != 1 {
t.Fatalf("edited: %d", n)
}
if st := Now(); st.Read != 2 || st.Of != 2 || !st.On || !st.Installed {
t.Fatalf("%+v", st)
}
path := filepath.Join(dir(), "vectors.bin")
if got := len(readVecs(path)); got != 2 {
t.Fatalf("on disk: %d", got)
}
b, _ := os.ReadFile(path)
if err := os.WriteFile(path, b[:len(b)-1], 0o644); err != nil {
t.Fatal(err)
}
if got := len(readVecs(path)); got != 0 {
t.Fatalf("cut short: %d", got)
}
}
// With the model not on disk, or a switch file that can't be read, a
// search is by words and nothing is loaded.
func TestNotThereIsWords(t *testing.T) {
f := sandbox(t, false)
save(t, "Releases go out on Tuesdays", memory.Active)
if hits, _ := memory.Search(memory.Query{Text: "上线"}); len(hits) != 0 || f.calls.Load() != 0 {
t.Fatalf("%v, %d calls", ids(hits), f.calls.Load())
}
if err := os.WriteFile(StatePath(), []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
if On() {
t.Fatal("a broken switch file is on")
}
}