Rank memory search in SQL instead of rebuilding BM25 in Python

The product path pulled every atom into Python and rebuilt a BM25Okapi
index per query: p50 20.16s over 165,973 atoms. It now runs one SQLite
statement with LIMIT/OFFSET.

- text_index.py: one normalizer for both sides of the index. CJK runs are
  split per character (unicode61 cannot segment them), camelCase and
  separators are split so "search atoms" finds SearchAtoms, latin tokens
  get a prefix match. Rows written before this existed hold raw text in
  atom_fts, so schema v3 rebuilds the index on upgrade.
- retrieval.py: filters (holder / scenario / source / modality / since /
  until / min_trust), a base64 cursor, and reciprocal rank fusion in place
  of the 0.55/0.35/0.10 blend whose graph term was always zero.
- An empty result is {status: "no_match"}, not a bare array.
- Go: search_atoms and compile_context rank through POST /api/search. The
  second Go tokenizer is deleted; two implementations could drift, which
  is what the MCP/HTTP parity requirement forbids.
- db.py passed 500 lines, so the row codec moved to row_codec.py.
- Tooling: installed the repo's own pyright. pyrightconfig.json had no
  exclude and swept the downloaded corpus (1171 errors); with excludes the
  count is 62, all pre-existing (evals 48, profiles 4, training 4,
  ingestion 3, runtime 2, cartridge_assets 1). backend/pyproject.toml
  carried a second [tool.pyright] that shadowed the root config; deleted.
- bench/scale_check.py measures the product search at corpus size. The
  100k-atom p50 number is not written until it is measured on an idle
  machine.

Verification: 112 pytest passed; go build/vet/test clean, gofmt clean;
ruff clean on every touched file; mypy clean on the 14 touched Python
files; repo pyright 62 errors, unchanged per-file ledger.
This commit is contained in:
ZacharyZhang-NY committed 2026-10-07 16:02:40 -04:00
1 parent 3d792417cf
commit 674c88e84e
29 files changed
+1097 -356

No files matched your search

+50
View File
@@ -13,6 +13,8 @@ import (
"net/http"
"strings"
"time"
"github.com/ZacharyZhang-NY/ely-eye/ely-eye-mcp/internal/domain"
)
const maxErrorBody = 4096
@@ -82,3 +84,51 @@ func serverReason(status int, data []byte) string {
}
return trimmed
}
// SearchOptions is one ranked query. Empty optional fields are omitted, so the
// server's own defaults decide rather than a zero value invented here.
type SearchOptions struct {
Query string
Modality string
Holder string
Scenario string
Limit int
}
// SearchResult carries the server's own verdict: "no_match" is a claim about the
// corpus, an empty hit list is not.
type SearchResult struct {
Status string `json:"status"`
Hits []domain.AtomHit `json:"hits"`
NextCursor string `json:"next_cursor"`
}
// Search asks the running server to rank. The ranking lives in one place, so an
// MCP hit cannot disagree with an HTTP or CLI hit for the same query.
func (c *Client) Search(ctx context.Context, options SearchOptions) (*SearchResult, error) {
if strings.TrimSpace(options.Query) == "" {
return nil, errors.New("query is required")
}
body := map[string]any{"query": options.Query}
if options.Limit > 0 {
body["top_k"] = options.Limit
}
filters := map[string]string{}
for key, value := range map[string]string{
"modality": options.Modality,
"holder": options.Holder,
"scenario": options.Scenario,
} {
if value != "" {
filters[key] = value
}
}
if len(filters) > 0 {
body["filters"] = filters
}
var result SearchResult
if err := c.Post(ctx, "/api/search", body, &result); err != nil {
return nil, err
}
return &result, nil
}
+1
View File
@@ -93,6 +93,7 @@ type Atom struct {
type AtomHit struct {
Atom Atom `json:"atom"`
SparseScore float64 `json:"sparse_score"`
DenseScore float64 `json:"dense_score"`
FinalScore float64 `json:"final_score"`
}
@@ -0,0 +1,109 @@
package mcpserver
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/ZacharyZhang-NY/ely-eye/ely-eye-mcp/internal/apiclient"
)
func searchTestServer(t *testing.T, recorded *map[string]any) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/search" {
t.Errorf("path = %q, want /api/search", r.URL.Path)
}
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("request body does not decode: %v", err)
}
*recorded = body
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{
"query": "钥匙",
"status": "hits",
"hits": [{"atom": {"atom_id": "mem-1:text", "source_id": "mem-1", "modality": "text",
"source": "memory://wife/home", "ingested_at": "2026-05-01T12:00:00+00:00",
"holder_id": "wife", "scenario": "home", "text": "钥匙在玄关抽屉"},
"sparse_score": 4.2, "dense_score": 0.0, "final_score": 0.016}],
"next_cursor": null
}`))
}))
}
func TestSearchAsksTheServerToRank(t *testing.T) {
var recorded map[string]any
server := searchTestServer(t, &recorded)
defer server.Close()
s := &Server{api: apiclient.New(server.URL)}
_, out, err := s.searchAtomsTool(context.Background(), nil, SearchAtomsInput{
Query: "钥匙",
Modality: "text",
Holder: "wife",
Scenario: "home",
Limit: 5,
})
if err != nil {
t.Fatalf("searchAtomsTool: %v", err)
}
if len(out.Hits) != 1 || out.Hits[0].Atom.AtomID != "mem-1:text" {
t.Fatalf("hits = %+v, want the server's single hit", out.Hits)
}
if recorded["query"] != "钥匙" {
t.Errorf("query sent = %v, want 钥匙", recorded["query"])
}
if recorded["top_k"] != float64(5) {
t.Errorf("top_k sent = %v, want 5", recorded["top_k"])
}
filters, ok := recorded["filters"].(map[string]any)
if !ok {
t.Fatalf("filters sent = %v, want an object", recorded["filters"])
}
for key, want := range map[string]string{"modality": "text", "holder": "wife", "scenario": "home"} {
if filters[key] != want {
t.Errorf("filters[%s] = %v, want %q", key, filters[key], want)
}
}
}
func TestSearchRefusesAnEmptyQueryBeforeTheNetwork(t *testing.T) {
var recorded map[string]any
server := searchTestServer(t, &recorded)
defer server.Close()
s := &Server{api: apiclient.New(server.URL)}
_, _, err := s.searchAtomsTool(context.Background(), nil, SearchAtomsInput{Query: " "})
if err == nil {
t.Fatal("an empty query reached the server; the tool should refuse it")
}
if recorded != nil {
t.Errorf("the server was called for an empty query: %v", recorded)
}
}
func TestCompileContextPacksWhatTheServerReturned(t *testing.T) {
var recorded map[string]any
server := searchTestServer(t, &recorded)
defer server.Close()
s := &Server{api: apiclient.New(server.URL)}
_, out, err := s.compileContextTool(context.Background(), nil, CompileContextInput{
Question: "钥匙在哪",
Profile: "library_100m",
Limit: 5,
})
if err != nil {
t.Fatalf("compileContextTool: %v", err)
}
if out.Context.CacheTraceID == "" {
t.Error("the packed context has no cache trace id")
}
if !strings.Contains(out.Context.PackedText, "钥匙在玄关抽屉") {
t.Errorf("packed text does not carry the evidence: %q", out.Context.PackedText)
}
}
+14 -5
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"github.com/ZacharyZhang-NY/ely-eye/ely-eye-mcp/internal/apiclient"
"github.com/ZacharyZhang-NY/ely-eye/ely-eye-mcp/internal/contextpack"
"github.com/ZacharyZhang-NY/ely-eye/ely-eye-mcp/internal/domain"
"github.com/modelcontextprotocol/go-sdk/mcp"
@@ -21,8 +22,10 @@ type GetCartridgeInput struct {
}
type SearchAtomsInput struct {
Query string `json:"query" jsonschema:"search query for the Ely-Eye FTS atom index"`
Query string `json:"query" jsonschema:"search query, matched by the server's own ranking"`
Modality string `json:"modality,omitempty" jsonschema:"optional exact modality filter such as text, code, image, pdf_page, pdf_region, video_frame, ui_screenshot"`
Holder string `json:"holder,omitempty" jsonschema:"optional: only this holder's memories may answer"`
Scenario string `json:"scenario,omitempty" jsonschema:"optional: only this scenario, e.g. home or work"`
Limit int `json:"limit,omitempty" jsonschema:"maximum number of atoms to return, capped at 100"`
}
@@ -160,11 +163,17 @@ func (s *Server) getCartridgeTool(ctx context.Context, _ *mcp.CallToolRequest, i
}
func (s *Server) searchAtomsTool(ctx context.Context, _ *mcp.CallToolRequest, input SearchAtomsInput) (*mcp.CallToolResult, SearchAtomsOutput, error) {
hits, err := s.store.SearchAtoms(ctx, input.Query, input.Modality, input.Limit)
result, err := s.api.Search(ctx, apiclient.SearchOptions{
Query: input.Query,
Modality: input.Modality,
Holder: input.Holder,
Scenario: input.Scenario,
Limit: input.Limit,
})
if err != nil {
return nil, SearchAtomsOutput{}, err
}
return nil, SearchAtomsOutput{Hits: contextpack.SummarizeHits(hits, 1200)}, nil
return nil, SearchAtomsOutput{Hits: contextpack.SummarizeHits(result.Hits, 1200)}, nil
}
func (s *Server) fetchAtomTool(ctx context.Context, _ *mcp.CallToolRequest, input FetchAtomInput) (*mcp.CallToolResult, FetchAtomOutput, error) {
@@ -179,11 +188,11 @@ func (s *Server) compileContextTool(ctx context.Context, _ *mcp.CallToolRequest,
if input.Question == "" {
return nil, CompileContextOutput{}, errors.New("question is required")
}
hits, err := s.store.SearchAtoms(ctx, input.Question, "", input.Limit)
hits, err := s.api.Search(ctx, apiclient.SearchOptions{Query: input.Question, Limit: input.Limit})
if err != nil {
return nil, CompileContextOutput{}, err
}
pack := contextpack.Build(input.Question, input.Profile, hits, input.TokenBudget)
pack := contextpack.Build(input.Question, input.Profile, hits.Hits, input.TokenBudget)
return nil, CompileContextOutput{Context: pack}, nil
}
-131
View File
@@ -4,15 +4,11 @@ import (
"context"
"database/sql"
"errors"
"math"
"regexp"
"strings"
"github.com/ZacharyZhang-NY/ely-eye/ely-eye-mcp/internal/domain"
)
var tokenPattern = regexp.MustCompile(`[\p{L}\p{N}_]+`)
func (s *Store) FetchAtom(ctx context.Context, atomID string) (domain.Atom, error) {
if strings.TrimSpace(atomID) == "" {
return domain.Atom{}, errors.New("atom_id is required")
@@ -34,65 +30,6 @@ func (s *Store) FetchAtom(ctx context.Context, atomID string) (domain.Atom, erro
return atom, nil
}
func (s *Store) SearchAtoms(ctx context.Context, query string, modality string, limit int) ([]domain.AtomHit, error) {
matchQuery, err := ftsQuery(query)
if err != nil {
return nil, err
}
if limit <= 0 || limit > 100 {
limit = 24
}
args := []any{matchQuery}
filter := ""
if modality != "" {
filter = "AND a.modality = ?"
args = append(args, modality)
}
args = append(args, limit)
rows, err := s.db.QueryContext(ctx, `
SELECT a.atom_id, a.source_id, a.modality, a.source, a.ingested_at,
COALESCE(a.holder_id, ''), COALESCE(a.origin, ''), COALESCE(a.scenario, ''),
COALESCE(a.event_time, ''), a.text,
COALESCE(a.image_ref, ''), COALESCE(a.layout_json, ''),
a.relations_json, a.trust_json, a.token_equivalent, a.metadata_json,
bm25(atom_fts) AS score
FROM atom_fts
JOIN v_atoms_current a ON a.atom_id = atom_fts.atom_id
WHERE atom_fts MATCH ? `+filter+`
ORDER BY score
LIMIT ?`, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var hits []domain.AtomHit
var bestScore float64
for rows.Next() {
atom, score, err := scanAtomHit(rows)
if err != nil {
return nil, err
}
sparseScore := -score
if math.IsNaN(sparseScore) || math.IsInf(sparseScore, 0) {
sparseScore = 0
}
if sparseScore > bestScore {
bestScore = sparseScore
}
hits = append(hits, domain.AtomHit{Atom: atom, SparseScore: sparseScore, FinalScore: sparseScore})
}
if err := rows.Err(); err != nil {
return nil, err
}
if bestScore > 0 {
for index := range hits {
hits[index].SparseScore = hits[index].SparseScore / bestScore
hits[index].FinalScore = hits[index].SparseScore
}
}
return hits, nil
}
type atomScanner interface {
Scan(dest ...any) error
}
@@ -142,71 +79,3 @@ func scanAtom(scanner atomScanner) (domain.Atom, error) {
}
return atom, nil
}
func scanAtomHit(scanner atomScanner) (domain.Atom, float64, error) {
var atom domain.Atom
var layout string
var relations string
var trust string
var metadata string
var score float64
if err := scanner.Scan(
&atom.AtomID,
&atom.SourceID,
&atom.Modality,
&atom.Source,
&atom.IngestedAt,
&atom.HolderID,
&atom.Origin,
&atom.Scenario,
&atom.EventTime,
&atom.Text,
&atom.ImageRef,
&layout,
&relations,
&trust,
&atom.TokenEquivalent,
&metadata,
&score,
); err != nil {
return domain.Atom{}, 0, err
}
var err error
atom.Layout, err = optionalJSONValue(layout)
if err != nil {
return domain.Atom{}, 0, err
}
atom.Relations, err = requiredJSONValue(relations)
if err != nil {
return domain.Atom{}, 0, err
}
atom.Trust, err = requiredJSONValue(trust)
if err != nil {
return domain.Atom{}, 0, err
}
atom.Metadata, err = requiredJSONValue(metadata)
if err != nil {
return domain.Atom{}, 0, err
}
return atom, score, nil
}
func ftsQuery(query string) (string, error) {
tokens := tokenPattern.FindAllString(strings.ToLower(query), -1)
if len(tokens) == 0 {
return "", errors.New("query must contain searchable text")
}
unique := make([]string, 0, len(tokens))
seen := map[string]bool{}
for _, token := range tokens {
if seen[token] {
continue
}
seen[token] = true
unique = append(unique, `"`+strings.ReplaceAll(token, `"`, `""`)+`"`)
if len(unique) == 16 {
break
}
}
return strings.Join(unique, " OR "), nil
}