sqlite-graph-memory 0.3.7__tar.gz → 0.3.9__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/.gitignore +1 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/CHANGELOG.md +29 -1
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/PKG-INFO +22 -6
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/README.md +21 -5
- sqlite_graph_memory-0.3.9/docs/memory-compare-2026-11.md +83 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/eval/build_gold.py +32 -6
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/eval/run_ablation.py +95 -34
- sqlite_graph_memory-0.3.9/plugin/README.md +24 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/pyproject.toml +1 -1
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/src/sqlite_graph_memory/__init__.py +1 -1
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/src/sqlite_graph_memory/brain_ask.py +102 -9
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/src/sqlite_graph_memory/doctor.py +61 -13
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/src/sqlite_graph_memory/index_notes.py +3 -1
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/src/sqlite_graph_memory/ppr.py +33 -1
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/src/sqlite_graph_memory/vault_stats.py +121 -35
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_bench.py +58 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_brain_ask.py +107 -0
- sqlite_graph_memory-0.3.9/tests/test_doctor.py +189 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_eval.py +199 -6
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_llms_txt.py +17 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_ppr.py +17 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_vault_stats.py +111 -0
- sqlite_graph_memory-0.3.7/tests/test_doctor.py +0 -94
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/CITATION.cff +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/LICENSE +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/bench/README.md +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/bench/requirements.txt +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/docs/RELEASING.md +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/docs/bitemporal.md +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/docs/demo.gif +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/docs/demo.sh +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/eval/run_eval.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/examples/README.md +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/examples/claude-code-stop-hook.json +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/examples/mcp-config.json +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/requirements.txt +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/src/sqlite_graph_memory/mcp_server.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/src/sqlite_graph_memory/onnx_backend.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/src/sqlite_graph_memory/schema.sql +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/src/sqlite_graph_memory/turnstate_hook.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/src/sqlite_graph_memory/turnstate_show.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_changelog_released.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_feedback_link.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_incremental_index.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_index_notes.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_index_notes_dotfiles.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_mcp_script_mode.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_mcp_server.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_onnx_backend.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_optional_extra.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_rerank_default.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_rerank_flag_eval.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_star_prompt.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_turnstate_hook.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_turnstate_show.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_uvx_python_pin.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_version_consistent.py +0 -0
- {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.9}/tests/test_version_flag.py +0 -0
|
@@ -4,7 +4,35 @@ What shipped, in plain words. Entries below v0.1.3 were written on 2026-09-05 fr
|
|
|
4
4
|
release notes that already existed — the file itself did not exist until then, so those three are
|
|
5
5
|
recorded after the fact rather than backdated to look contemporaneous.
|
|
6
6
|
|
|
7
|
-
##
|
|
7
|
+
## v0.3.9 - 2026-11-14
|
|
8
|
+
|
|
9
|
+
**Plugin moved to `plugin/` with a locked runtime.** The Claude plugin directory refuses a PyPI version as a pin, so the plugin now starts the server with `uv run --locked` from its own folder, where `uv.lock` pins `sqlite-graph-memory[lite]` and every dependency by hash, with Intel Mac, Apple Silicon, Linux and Windows resolved separately (onnxruntime 1.32 has no Intel Mac wheel). The directory now checks only that folder, not the whole repo. Install command unchanged; plugins need `uv`. The server starts as `uv run --locked ${CLAUDE_PLUGIN_ROOT}/server.py`, a launcher whose `server.py.lock` pins everything (Intel Macs held at onnxruntime 1.23.2) and which maps the plugin option `CLAUDE_PLUGIN_OPTION_INDEX_DIR` to `BRAIN_INDEX_DIR`.
|
|
10
|
+
|
|
11
|
+
**Claude Code plugin.** `.claude-plugin/plugin.json` and `marketplace.json` make the repo installable with `/plugin install sqlite-graph-memory --marketplace tonydzi/sqlite-graph-memory`. It registers the same stdio server on `[lite]` (ONNX, no torch), asks for the index folder once, and keeps telemetry in the plugin's data folder. Checked 2026-11-12: `claude plugin validate . --strict` passes; installed into an empty `CLAUDE_CONFIG_DIR`, `claude mcp list` reports the server connected and `memory_recall` answers over a five-note synthetic folder.
|
|
12
|
+
|
|
13
|
+
**`sgm-doctor`: four edge-case fixes from review.** Thanks @Kaap10 (#110): imports `brain_ask` lazily so a missing or broken NumPy prints a plain-words `[FAIL]` instead of an unhandled traceback; marks missing transitive dependencies of `sentence-transformers` as `[FAIL]` rather than a missing extra warning; isolates custom `HF_HUB_CACHE` / `HF_HOME` directories without mixing in default caches and respects `XDG_CACHE_HOME`; and validates index `.npy` array shape against metadata chunks so truncated or 0-byte index files report `[FAIL]` (closes #107).
|
|
14
|
+
|
|
15
|
+
**Credits that predate the credit gate.** `scripts/credit_gate.py` checks merges since 2026-10-19, so two earlier outside contributions were never named here: @HeaTTap wrote the first tests for `looks_like_entity()` and `_links_in()` (#6, shipped in bench-v0.1), and @Deva4287 corrected the README test status (#7, same release). Recorded now so the changelog names every outside author.
|
|
16
|
+
|
|
17
|
+
**Recall: the PPR lane resolves `[[folder/note]]` and `[[note.md]]` links.** `ppr.build()` now normalises a wikilink target the way the 1-hop lane does, so `SGM_PPR=1` and the graph hop count the same edges instead of the PageRank lane silently dropping folder-qualified and `.md` targets. Thanks @bfs2021 (#108), who picked up #103.
|
|
18
|
+
|
|
19
|
+
**Docs: the Stop-hook ledger is telemetry, not a recall input.** `README.md` and `FOR-ROBOTS.md` now say where the per-turn ledger is introduced that recall never reads it, so past turns do not change what `brain_ask.py` or the MCP server return, and the crash-safety note no longer implies the Stop-hook sits on the recall path. Thanks @dbdefault (#112), who picked up #105.
|
|
20
|
+
|
|
21
|
+
## v0.3.8 - 2026-11-10
|
|
22
|
+
|
|
23
|
+
Five of the six entries below came from one outside contributor in one week. Thank you, @Jason-Vaughan.
|
|
24
|
+
|
|
25
|
+
**Bench: `mempalace` row.** MemPalace 3.11.0 with its defaults (`miner.mine()` projects mode, ChromaDB default embedder, `search_memories(n_results=20)`, no LLM) under the shared extractive answer floor. R@5 0.82, answer 0.42; it never abstains on the 22 questions with no answer in the vault (0.00). Self-reported for now: the adapter needs no API key, so it can join the CI reproduce job.
|
|
26
|
+
|
|
27
|
+
**Bench: `plain-rag` reference row.** Dense cosine-only baseline (`multilingual-e5-base` over 1200-char chunks, `topk=60`, no graph hop and no cross-encoder reranker) reproduced in CI, isolating what reranking and wikilink expansion change on `memory-bench`. Thanks @Jason-Vaughan (#91), who picked up #21.
|
|
28
|
+
|
|
29
|
+
**Recall: `superseded_by` links still resolve when the entity gate fires.** A short entity-shaped query (like a project title) that hits an outdated note now still follows its frontmatter `superseded_by` target in `expand_1hop` while keeping general wikilink expansion gated off. Thanks @Jason-Vaughan (#94), who picked up #93.
|
|
30
|
+
|
|
31
|
+
**`sgm-ask` and `eval/run_ablation.py`: `--pool` override for the dense candidate pool.** `--pool N` (or `BRAIN_TOPK_RETRIEVE=N`) overrides `TOPK_RETRIEVE` without changing the 60-note default, and `DEFAULT_GRID` adds `topk-15` so pool-size sweeps can be compared across vaults. Thanks @Jason-Vaughan (#97), who picked up #92.
|
|
32
|
+
|
|
33
|
+
**`eval/run_ablation.py`: gate, neighbour-admission and rank-churn columns.** Each ablation cell now reports `gate_rate`, `hop_applied_rate` and `rank_churn` alongside the retrieval metrics, separating queries where the entity gate suppressed the hop from queries where neighbours entered and reordered the top-12 without moving single-note gold at rank 1. Thanks @Jason-Vaughan (#95), who picked up #93.
|
|
34
|
+
|
|
35
|
+
**`eval/build_gold.py`: short `heading` question class.** Adds a fifth class built from short markdown headings (`<= 5` words) so `looks_like_entity` is exercised on short heading queries in `run_eval.py` and `run_ablation.py`. Because `rnd.shuffle(notes)` runs once before the class pools are sliced, the four existing classes pick the exact same questions for a given seed and older gold sets and published numbers still reproduce (only `heading` is new); on a vault with no qualifying short headings, `heading` is simply empty (0 questions, omitted from the printed class counts and eval tables, no crash). Thanks @Jason-Vaughan (#96), who picked up #93.
|
|
8
36
|
|
|
9
37
|
## v0.3.7 - 2026-11-05
|
|
10
38
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: sqlite-graph-memory
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.9
|
|
4
4
|
Summary: Associative memory for LLM agents: Graph RAG over a folder of markdown notes, in one SQLite file, with no server to run.
|
|
5
5
|
Project-URL: Homepage, https://github.com/tonydzi/sqlite-graph-memory
|
|
6
6
|
Project-URL: Repository, https://github.com/tonydzi/sqlite-graph-memory
|
|
@@ -62,6 +62,10 @@ misses by following the links between your notes. It is an MCP server and a CLI
|
|
|
62
62
|
folder of markdown, Obsidian vaults included: `pip install`, point it at the folder, and
|
|
63
63
|
Claude Code, Cursor, Codex or any other MCP client can recall from it.
|
|
64
64
|
|
|
65
|
+
It fits [Andrej Karpathy's LLM Wiki pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f) (April 2026), where an agent maintains an interlinked markdown wiki and a search tool over the pages is the first helper he suggests adding: sgm is that search layer, read-only, and it follows your `[[wikilinks]]` as a graph. Independent project, not affiliated with or endorsed by him.
|
|
66
|
+
|
|
67
|
+
This package is layers 4 and 5 of a larger memory design (always-loaded instructions, auto memory, curated vault, verbatim originals, retrieval, turn ledger). The whole picture and a step-by-step install for you or your agent: [MEMORY.md in the starter kit](https://github.com/tonydzi/second-brain-starter-kit/blob/master/MEMORY.md) ([по-русски](https://github.com/tonydzi/second-brain-starter-kit/blob/master/MEMORY.ru.md)).
|
|
68
|
+
|
|
65
69
|

|
|
66
70
|
|
|
67
71
|
**Your agent forgets everything between sessions, and plain vector search gives it back
|
|
@@ -91,6 +95,14 @@ Then point your client at the server. Use the absolute path of that index folder
|
|
|
91
95
|
|
|
92
96
|
**Claude Code**
|
|
93
97
|
|
|
98
|
+
As a plugin (asks for the index folder on install, Claude Code 2.1.275 or later):
|
|
99
|
+
|
|
100
|
+
```
|
|
101
|
+
/plugin install sqlite-graph-memory --marketplace tonydzi/sqlite-graph-memory
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Or register the server by hand:
|
|
105
|
+
|
|
94
106
|
```bash
|
|
95
107
|
claude mcp add sqlite-graph-memory -e BRAIN_INDEX_DIR=$HOME/.sgm-index -- uvx --python 3.12 --with 'sqlite-graph-memory[lite]' sqlite-graph-memory
|
|
96
108
|
```
|
|
@@ -225,7 +237,8 @@ For a single-user agent over a markdown knowledge base, all three are overkill:
|
|
|
225
237
|
No extraction pass, and edge quality beats anything a model would mine.
|
|
226
238
|
- **SQLite is enough** — the only things worth persisting are derived state (a per-turn
|
|
227
239
|
ledger) and telemetry, and both are defined in [`schema.sql`](src/sqlite_graph_memory/schema.sql).
|
|
228
|
-
One file, stdlib driver, zero ops.
|
|
240
|
+
One file, stdlib driver, zero ops. The ledger is telemetry, not memory: recall never reads it,
|
|
241
|
+
so past turns do not change what `brain_ask.py` or the MCP server return.
|
|
229
242
|
- **Measure before adding a stage.** The pilot shipped a cross-encoder reranker from day one;
|
|
230
243
|
measured later, it lowered recall on long queries (our 184-question gold set: body nDCG@12
|
|
231
244
|
0.640 reranked vs 0.815 dense; DolphinBench Riley slice, 1000 sessions: R@5 0.48 vs 0.61).
|
|
@@ -257,6 +270,8 @@ markdown notes (with [[wikilinks]])
|
|
|
257
270
|
(ask, summary, files, tools, commands, decisions)
|
|
258
271
|
to SQLite (turns). 0 LLM tokens, pure stdlib.
|
|
259
272
|
turnstate_show.py = read-only viewer.
|
|
273
|
+
Off the recall path: nothing in recall
|
|
274
|
+
reads this table.
|
|
260
275
|
```
|
|
261
276
|
|
|
262
277
|
[`schema.sql`](src/sqlite_graph_memory/schema.sql) documents both tables. The graph is **not** materialized in SQL:
|
|
@@ -274,9 +289,9 @@ an edge table only when hop depth or corpus size demands it.
|
|
|
274
289
|
lookups ("NotebookLM"): a name's card links to everything, so the hop pulls in noise.
|
|
275
290
|
The heuristic in `brain_ask.py` is deliberately conservative, and switches the graph off
|
|
276
291
|
only for name-shaped queries.
|
|
277
|
-
- **Crash-safety as a policy.** The graph hop (`brain_ask.py`)
|
|
278
|
-
(`turnstate_hook.py`)
|
|
279
|
-
|
|
292
|
+
- **Crash-safety as a policy.** The graph hop (`brain_ask.py`) is wrapped, so a failure
|
|
293
|
+
degrades recall to vector-only. The Stop-hook (`turnstate_hook.py`) is wrapped too, but it
|
|
294
|
+
sits off the recall path: a failure costs one ledger row and nothing else.
|
|
280
295
|
A memory layer must never make the agent worse than having no memory layer.
|
|
281
296
|
- **Measure, don't believe.** `--ab` runs both pipelines on every real query and logs how
|
|
282
297
|
many notes the graph promoted into the top-N, to `ab_recall` in [`schema.sql`](src/sqlite_graph_memory/schema.sql).
|
|
@@ -319,7 +334,8 @@ Run any of them on a base install and they tell you which extra is missing rathe
|
|
|
319
334
|
raising `ModuleNotFoundError` — that path is covered by `tests/test_optional_extra.py`.
|
|
320
335
|
|
|
321
336
|
To enable the per-turn ledger in Claude Code, register the Stop hook (the exact block is
|
|
322
|
-
`examples/claude-code-stop-hook.json`, which calls `sgm-turnstate-hook`), then
|
|
337
|
+
`examples/claude-code-stop-hook.json`, which calls `sgm-turnstate-hook`), then read it back with
|
|
338
|
+
`sgm-turnstate-show`. The ledger records what each turn did; recall never reads it.
|
|
323
339
|
|
|
324
340
|
```bash
|
|
325
341
|
sgm-turnstate-show --stats
|
|
@@ -7,6 +7,10 @@ misses by following the links between your notes. It is an MCP server and a CLI
|
|
|
7
7
|
folder of markdown, Obsidian vaults included: `pip install`, point it at the folder, and
|
|
8
8
|
Claude Code, Cursor, Codex or any other MCP client can recall from it.
|
|
9
9
|
|
|
10
|
+
It fits [Andrej Karpathy's LLM Wiki pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f) (April 2026), where an agent maintains an interlinked markdown wiki and a search tool over the pages is the first helper he suggests adding: sgm is that search layer, read-only, and it follows your `[[wikilinks]]` as a graph. Independent project, not affiliated with or endorsed by him.
|
|
11
|
+
|
|
12
|
+
This package is layers 4 and 5 of a larger memory design (always-loaded instructions, auto memory, curated vault, verbatim originals, retrieval, turn ledger). The whole picture and a step-by-step install for you or your agent: [MEMORY.md in the starter kit](https://github.com/tonydzi/second-brain-starter-kit/blob/master/MEMORY.md) ([по-русски](https://github.com/tonydzi/second-brain-starter-kit/blob/master/MEMORY.ru.md)).
|
|
13
|
+
|
|
10
14
|

|
|
11
15
|
|
|
12
16
|
**Your agent forgets everything between sessions, and plain vector search gives it back
|
|
@@ -36,6 +40,14 @@ Then point your client at the server. Use the absolute path of that index folder
|
|
|
36
40
|
|
|
37
41
|
**Claude Code**
|
|
38
42
|
|
|
43
|
+
As a plugin (asks for the index folder on install, Claude Code 2.1.275 or later):
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
/plugin install sqlite-graph-memory --marketplace tonydzi/sqlite-graph-memory
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Or register the server by hand:
|
|
50
|
+
|
|
39
51
|
```bash
|
|
40
52
|
claude mcp add sqlite-graph-memory -e BRAIN_INDEX_DIR=$HOME/.sgm-index -- uvx --python 3.12 --with 'sqlite-graph-memory[lite]' sqlite-graph-memory
|
|
41
53
|
```
|
|
@@ -170,7 +182,8 @@ For a single-user agent over a markdown knowledge base, all three are overkill:
|
|
|
170
182
|
No extraction pass, and edge quality beats anything a model would mine.
|
|
171
183
|
- **SQLite is enough** — the only things worth persisting are derived state (a per-turn
|
|
172
184
|
ledger) and telemetry, and both are defined in [`schema.sql`](src/sqlite_graph_memory/schema.sql).
|
|
173
|
-
One file, stdlib driver, zero ops.
|
|
185
|
+
One file, stdlib driver, zero ops. The ledger is telemetry, not memory: recall never reads it,
|
|
186
|
+
so past turns do not change what `brain_ask.py` or the MCP server return.
|
|
174
187
|
- **Measure before adding a stage.** The pilot shipped a cross-encoder reranker from day one;
|
|
175
188
|
measured later, it lowered recall on long queries (our 184-question gold set: body nDCG@12
|
|
176
189
|
0.640 reranked vs 0.815 dense; DolphinBench Riley slice, 1000 sessions: R@5 0.48 vs 0.61).
|
|
@@ -202,6 +215,8 @@ markdown notes (with [[wikilinks]])
|
|
|
202
215
|
(ask, summary, files, tools, commands, decisions)
|
|
203
216
|
to SQLite (turns). 0 LLM tokens, pure stdlib.
|
|
204
217
|
turnstate_show.py = read-only viewer.
|
|
218
|
+
Off the recall path: nothing in recall
|
|
219
|
+
reads this table.
|
|
205
220
|
```
|
|
206
221
|
|
|
207
222
|
[`schema.sql`](src/sqlite_graph_memory/schema.sql) documents both tables. The graph is **not** materialized in SQL:
|
|
@@ -219,9 +234,9 @@ an edge table only when hop depth or corpus size demands it.
|
|
|
219
234
|
lookups ("NotebookLM"): a name's card links to everything, so the hop pulls in noise.
|
|
220
235
|
The heuristic in `brain_ask.py` is deliberately conservative, and switches the graph off
|
|
221
236
|
only for name-shaped queries.
|
|
222
|
-
- **Crash-safety as a policy.** The graph hop (`brain_ask.py`)
|
|
223
|
-
(`turnstate_hook.py`)
|
|
224
|
-
|
|
237
|
+
- **Crash-safety as a policy.** The graph hop (`brain_ask.py`) is wrapped, so a failure
|
|
238
|
+
degrades recall to vector-only. The Stop-hook (`turnstate_hook.py`) is wrapped too, but it
|
|
239
|
+
sits off the recall path: a failure costs one ledger row and nothing else.
|
|
225
240
|
A memory layer must never make the agent worse than having no memory layer.
|
|
226
241
|
- **Measure, don't believe.** `--ab` runs both pipelines on every real query and logs how
|
|
227
242
|
many notes the graph promoted into the top-N, to `ab_recall` in [`schema.sql`](src/sqlite_graph_memory/schema.sql).
|
|
@@ -264,7 +279,8 @@ Run any of them on a base install and they tell you which extra is missing rathe
|
|
|
264
279
|
raising `ModuleNotFoundError` — that path is covered by `tests/test_optional_extra.py`.
|
|
265
280
|
|
|
266
281
|
To enable the per-turn ledger in Claude Code, register the Stop hook (the exact block is
|
|
267
|
-
`examples/claude-code-stop-hook.json`, which calls `sgm-turnstate-hook`), then
|
|
282
|
+
`examples/claude-code-stop-hook.json`, which calls `sgm-turnstate-hook`), then read it back with
|
|
283
|
+
`sgm-turnstate-show`. The ledger records what each turn did; recall never reads it.
|
|
268
284
|
|
|
269
285
|
```bash
|
|
270
286
|
sgm-turnstate-show --stats
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Agent memory, measured: Mem0, Zep's Graphiti, MemPalace and seven others (November 2026)
|
|
2
|
+
|
|
3
|
+
*Mycroft here, Anton's synthetic AI cofounder. I ran these measurements and wrote this page; Anton reviewed it and is accountable for it.*
|
|
4
|
+
|
|
5
|
+
**The short answer.** In the local configurations we could run, a plain dense-retrieval baseline found the right note at least as often as every memory system we tried. Their LLM extraction modes (Mem0 `infer=True`, Graphiti end to end) are not in that comparison, see section 4. Where the systems clearly differ is what they do when the answer is missing, and what they do when a fact changes.
|
|
6
|
+
|
|
7
|
+
Everything below is retrieval, not end-to-end answer quality. Each section says what was measured, on what, and with which model.
|
|
8
|
+
|
|
9
|
+
## 1. Public bench: 202 synthetic notes, 91 questions
|
|
10
|
+
|
|
11
|
+
The vault and the questions are in [`bench/`](../bench/README.md). 22 of the 91 questions have no answer in the vault, on purpose. Full table and per-class breakdown: [`bench/LEADERBOARD.md`](../bench/LEADERBOARD.md).
|
|
12
|
+
|
|
13
|
+
| system | right note in top 5 | stays silent when the answer is absent |
|
|
14
|
+
|---|---:|---:|
|
|
15
|
+
| plain RAG (e5-base chunks, reference) | 0.93 | 0.18 |
|
|
16
|
+
| sqlite-graph-memory, vector only | 0.88 | 0.45 |
|
|
17
|
+
| Mem0 OSS 2.2.1, local, `infer=False`, nomic-embed-text | 0.87 | 0.14 |
|
|
18
|
+
| fidelis 0.2.0 | 0.86 | 0.18 |
|
|
19
|
+
| sqlite-graph-memory, vector + wikilink graph | 0.85 | 0.45 |
|
|
20
|
+
| MemPalace 3.11.0, defaults, no LLM | 0.82 | 0.00 |
|
|
21
|
+
| BM25 (reference) | 0.77 | 0.36 |
|
|
22
|
+
| TangleClaw-style hybrid | 0.77 | 0.45 |
|
|
23
|
+
| second-brain | 0.76 | 0.00 |
|
|
24
|
+
| SQLite FTS5 (reference) | 0.76 | 0.00 |
|
|
25
|
+
|
|
26
|
+
What I take from it:
|
|
27
|
+
|
|
28
|
+
- The baseline won. None of the memory layers on top of embeddings bought retrieval on this vault. Our own two rows on the board were run with the cross-encoder reranker on; without it our dense search scores 0.93, the same as plain RAG (section 2).
|
|
29
|
+
- "Stays silent" is the share of the 22 unanswerable questions where the adapter returned no answer. Most adapters share one rule: answer with the best-overlapping sentence of the top notes, abstain only when nothing comes back or no sentence shares a content word. So this column mostly measures whether a system returns nothing when nothing fits, not a tuned refusal. It is still the weak column for everyone. Three systems answered all 22 unanswerable questions. The best any system did was decline 45% of them.
|
|
30
|
+
- Graph expansion helps one class and hurts another: it lifts two-note "bridge" questions and drops paraphrased ones (per-class table in the leaderboard). Both of our rows ran with the same reranker, so this graph-vs-vector difference is like for like.
|
|
31
|
+
|
|
32
|
+
## 2. Our own notes: 40 real notes, 24 answerable questions
|
|
33
|
+
|
|
34
|
+
Same embedder for every row where possible (`intfloat/multilingual-e5-base`). The notes are private, so only the counts are published. Counts are out of 24: right note at rank 1 / in top 5 / in top 10.
|
|
35
|
+
|
|
36
|
+
| row | @1 | @5 | @10 | LLM calls to index |
|
|
37
|
+
|---|---:|---:|---:|---:|
|
|
38
|
+
| sqlite-graph-memory, dense, no reranker | 19 | 23 | 24 | 0 |
|
|
39
|
+
| sqlite-graph-memory with the cross-encoder reranker (as it was in production) | 17 | 21 | 24 | 0 |
|
|
40
|
+
| Mem0 OSS 2.2.1, `infer=False` | 19 | 23 | 24 | 0 |
|
|
41
|
+
| Anima Labs connectome (Jina embeddings) | 17 | 23 | 23 | 0 |
|
|
42
|
+
| SQLite FTS5 | 15 | 21 | 21 | 0 |
|
|
43
|
+
|
|
44
|
+
Two findings came out of this:
|
|
45
|
+
|
|
46
|
+
- **Mem0 without extraction behaved like dense search here.** In this run Mem0 `infer=False` was given the same e5 embedder and the same 1200-character chunks, and it returned the same rank counts with the same single miss. (On the public bench its row uses a different embedder, nomic-embed-text, so the two tables are not the same comparison.) The gap we first saw between Mem0 and us was our own reranker.
|
|
47
|
+
- **Our reranker was hurting us.** The cross-encoder (`mmarco-mMiniLMv2-L12`) cost two notes at rank 1 and two in the top 5 here. On 24 questions that alone is noise, so the decision rests on the 91-question bench as well, where it cut recall@5 from 0.93 to 0.88 (about three of 69 answerable questions; no significance test). It still helped two-note bridge questions. It is now off by default (release 0.3.7, `--rerank` brings it back).
|
|
48
|
+
|
|
49
|
+
A tempting result did not survive: on these 24 questions a fusion of dense and reranked lists scored 24 of 24. On the larger bench it was worse than plain dense. One small set proves nothing.
|
|
50
|
+
|
|
51
|
+
## 3. Facts that change over time
|
|
52
|
+
|
|
53
|
+
Retrieval is not where Mem0 and Zep claim their edge. They use an LLM to turn text into facts with validity dates. So I tested the part they are built for, on a toy history: a hotel room whose guest changes four times, then a late fact, then a retraction ("that guest never existed, it was a typo").
|
|
54
|
+
|
|
55
|
+
| system | who was there on date X | late fact | retraction restores the previous guest |
|
|
56
|
+
|---|---|---|---|
|
|
57
|
+
| a 302-line event log (`fact_history.py`, ours, 0 LLM calls) | 4 of 4 | yes | yes |
|
|
58
|
+
| Graphiti 0.31.2 core (Zep's open engine), temporal invalidation with a perfect judge, no LLM | 4 of 4 | yes | no: the old edge already has an end date, and there is no "retract" operation |
|
|
59
|
+
| Mem0 OSS 2.2.1 | not run on this history; in a separate one-fact check, old and new both stayed active ("coffee" and "tea since 2 Nov") | not measured | not measured |
|
|
60
|
+
|
|
61
|
+
This is one hand-built history with clean, ordered events, not a benchmark; same-timestamp and out-of-order corrections were not tested, and the event log takes structured events, so it skips the text-to-fact step that Graphiti and Mem0 exist to do. Why the log passes the retraction: it never stores an end date. It computes "what was true on date X" from the list of events at read time, so removing an event changes the answer.
|
|
62
|
+
|
|
63
|
+
## 4. What I could not measure, and why
|
|
64
|
+
|
|
65
|
+
- **Graphiti end to end and Mem0 with `infer=True`.** Both need an LLM that returns strict JSON on every write. A local Qwen3-4B returned the JSON schema instead of data and timed out twice. GLM-5.3 through a subscription extracted one of 40 episodes cleanly. That is a model problem, not a Graphiti or Mem0 problem, and I have no fair number for either yet.
|
|
66
|
+
- **Zep Cloud and the Mem0 managed platform.** Not measured. Mem0's README says its headline LoCoMo and LongMemEval numbers come from the managed platform, not the open SDK.
|
|
67
|
+
- **Answer quality.** Every number here is "did the right note come back". LoCoMo-style judged answers are a different test.
|
|
68
|
+
- **MemPalace beyond defaults.** Only the default candidate strategy; `union` and the `--llm` init mode were not tried.
|
|
69
|
+
|
|
70
|
+
## Reproduce
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
git clone https://github.com/tonydzi/sqlite-graph-memory && cd sqlite-graph-memory
|
|
74
|
+
python bench/run.py --system bm25 # stdlib only, about a second
|
|
75
|
+
python bench/run.py --system mempalace # needs: pip install mempalace
|
|
76
|
+
python bench/run.py --system mem0-local # needs Ollama, see bench/adapters/mem0_local.py
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Every row on the public board has its adapter in `bench/adapters/`. Section 2 uses private notes and section 3 uses an internal script, so those two are reported, not reproducible from this repo.
|
|
80
|
+
|
|
81
|
+
Adapters for other systems are welcome: [`bench/CONTRIBUTING.md`](../bench/CONTRIBUTING.md). A maintainer answers within 48 hours.
|
|
82
|
+
|
|
83
|
+
Anton Dzyatkovskiy · github.com/tonydzi
|
|
@@ -6,9 +6,10 @@ A note's own title should retrieve that note. Its first paragraph should retriev
|
|
|
6
6
|
The notes it `[[links]]` to are the neighbours a human decided are related. Nobody has to
|
|
7
7
|
label anything, and no LLM is called — this script is pure file work plus the index meta.
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
Five question classes, each probing a different part of the pipeline:
|
|
10
10
|
|
|
11
11
|
title query = the note's title -> gold = that note (name lookup)
|
|
12
|
+
heading query = a short markdown heading -> gold = that note (heading lookup)
|
|
12
13
|
body query = its first paragraph -> gold = that note (theme lookup)
|
|
13
14
|
bridge query = its first paragraph -> gold = its [[link]] TARGETS (the graph)
|
|
14
15
|
temporal query = an outdated note's title -> gold = its replacement (see below)
|
|
@@ -41,8 +42,10 @@ from collections import Counter
|
|
|
41
42
|
from pathlib import Path
|
|
42
43
|
|
|
43
44
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
|
|
45
|
+
from sqlite_graph_memory.brain_ask import looks_like_entity # noqa: E402
|
|
44
46
|
from sqlite_graph_memory.index_notes import iter_notes # noqa: E402
|
|
45
47
|
|
|
48
|
+
FENCED_CODE_RX = re.compile(r'(?:```[\s\S]*?```|~~~[\s\S]*?~~~)')
|
|
46
49
|
WIKILINK_RX = re.compile(r'\[\[([^\]\|#]+)(?:[|#][^\]]*)?\]\]')
|
|
47
50
|
CYRILLIC_RX = re.compile(r'[а-яё]', re.I)
|
|
48
51
|
|
|
@@ -86,6 +89,22 @@ def note_title(fm, body, path):
|
|
|
86
89
|
return strip_markup(t)[:200]
|
|
87
90
|
|
|
88
91
|
|
|
92
|
+
def note_heading(body):
|
|
93
|
+
"""First short (<= 5 words) markdown heading in `body` that triggers looks_like_entity.
|
|
94
|
+
|
|
95
|
+
Prefers `##`..`######` subheadings over `#` H1 headings so notes with section headings
|
|
96
|
+
contribute non-title queries; fenced code blocks are ignored, and frontmatter titles are
|
|
97
|
+
not used as headings.
|
|
98
|
+
"""
|
|
99
|
+
clean = FENCED_CODE_RX.sub('', body or '')
|
|
100
|
+
sub = [strip_markup(m.group(1))[:200] for m in re.finditer(r'(?m)^#{2,6}\s+(.+)$', clean)]
|
|
101
|
+
h1 = [strip_markup(m.group(1))[:200] for m in re.finditer(r'(?m)^#\s+(.+)$', clean)]
|
|
102
|
+
for h in sub + h1:
|
|
103
|
+
if len(h) >= 4 and 1 <= len(h.split()) <= 5 and looks_like_entity(h):
|
|
104
|
+
return h
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
|
|
89
108
|
def first_paragraph(body, minlen=100, maxlen=400):
|
|
90
109
|
"""First real prose paragraph: no headings, tables, code fences or blockquotes.
|
|
91
110
|
|
|
@@ -121,7 +140,7 @@ def indexed_stems(index_dir):
|
|
|
121
140
|
|
|
122
141
|
|
|
123
142
|
def read_notes(notes_dir, stems, folders=None):
|
|
124
|
-
"""Every indexed note, parsed into the fields the
|
|
143
|
+
"""Every indexed note, parsed into the fields the five classes need."""
|
|
125
144
|
root = Path(notes_dir)
|
|
126
145
|
paths = []
|
|
127
146
|
# The indexer's own walk: hidden files and dirs, conflict copies and BRAIN_INDEX_HIDDEN
|
|
@@ -142,7 +161,8 @@ def read_notes(notes_dir, stems, folders=None):
|
|
|
142
161
|
sup_m = WIKILINK_RX.findall(sup) if sup else []
|
|
143
162
|
sup = sup_m[0].strip().lower() if sup_m else (sup.strip().lower() if sup else None)
|
|
144
163
|
notes.append({'stem': p.stem.lower(), 'folder': (p.relative_to(root).parts[:-1] or ('',))[0],
|
|
145
|
-
'title': note_title(fm, body, p), '
|
|
164
|
+
'title': note_title(fm, body, p), 'heading': note_heading(body),
|
|
165
|
+
'para': first_paragraph(body),
|
|
146
166
|
'links': links, 'sup': sup if sup in stems else None})
|
|
147
167
|
return notes
|
|
148
168
|
|
|
@@ -163,13 +183,19 @@ def build_gold(notes, n_per_class, seed):
|
|
|
163
183
|
notes = list(notes)
|
|
164
184
|
rnd.shuffle(notes)
|
|
165
185
|
pools = {'title': [n for n in notes if len(n['title']) >= 8],
|
|
186
|
+
'heading': [n for n in notes if n.get('heading')],
|
|
166
187
|
'body': [n for n in notes if n['para']],
|
|
167
188
|
'bridge': [n for n in notes if n['para'] and len(n['links']) >= 2],
|
|
168
189
|
'temporal': [n for n in notes if n['sup']]}
|
|
169
190
|
gold = []
|
|
170
|
-
for cls in ('title', 'body', 'bridge', 'temporal'):
|
|
191
|
+
for cls in ('title', 'heading', 'body', 'bridge', 'temporal'):
|
|
171
192
|
for n in pools[cls][:n_per_class]:
|
|
172
|
-
|
|
193
|
+
if cls in ('body', 'bridge'):
|
|
194
|
+
q = n['para']
|
|
195
|
+
elif cls == 'heading':
|
|
196
|
+
q = n['heading']
|
|
197
|
+
else:
|
|
198
|
+
q = n['title']
|
|
173
199
|
if cls == 'bridge':
|
|
174
200
|
g, dropped = n['links'][:BRIDGE_MAX_GOLD], max(0, len(n['links']) - BRIDGE_MAX_GOLD)
|
|
175
201
|
elif cls == 'temporal':
|
|
@@ -217,7 +243,7 @@ def main():
|
|
|
217
243
|
print(' ! %d bridge questions had more than %d links; the rest were cut, because '
|
|
218
244
|
'Recall@12 has only 12 slots' % (cut, BRIDGE_MAX_GOLD))
|
|
219
245
|
print(' classes %s · languages %s' % (dict(counts), dict(Counter(g['lang'] for g in gold))))
|
|
220
|
-
for cls in ('title', 'body', 'bridge', 'temporal'):
|
|
246
|
+
for cls in ('title', 'heading', 'body', 'bridge', 'temporal'):
|
|
221
247
|
if counts[cls] < 20:
|
|
222
248
|
print(' ! %s: only %d questions — too few to judge a change by; treat as a smoke test'
|
|
223
249
|
% (cls, counts[cls]))
|
|
@@ -12,6 +12,19 @@ Axes swept per cell:
|
|
|
12
12
|
topk dense-retrieve candidate pool size (brain_ask.TOPK_RETRIEVE)
|
|
13
13
|
entity_gate on/off: suppress the hop on entity/name-shaped queries (looks_like_entity)
|
|
14
14
|
|
|
15
|
+
Per cell/class, the summary also reports:
|
|
16
|
+
gate_rate share of queries where this cell's entity_gate fired (query-shape
|
|
17
|
+
only — computed even on hops=0 cells, where it has no effect)
|
|
18
|
+
hop_applied_rate share of queries where expand_1hop actually admitted >=1 new
|
|
19
|
+
candidate. A metric can be unchanged between an entity-gate-on and
|
|
20
|
+
an entity-gate-off cell for two very different reasons — the gate
|
|
21
|
+
firing, or the hop firing but adding nothing the reranker needed
|
|
22
|
+
(issue #93) — and only hop_applied_rate tells those apart.
|
|
23
|
+
rank_churn share of queries where this cell's top-12 differs at all from the
|
|
24
|
+
0-hop baseline's, for the same query. A single-note gold pins
|
|
25
|
+
rank #1 regardless of what fills ranks 2..12, so delta_ndcg can
|
|
26
|
+
read 0.0 while the hop still reordered the rest of the page.
|
|
27
|
+
|
|
15
28
|
The dense embedding and its similarity scores are computed ONCE per query (the model
|
|
16
29
|
load and the encode() call are the expensive parts) and reused across every cell: a
|
|
17
30
|
cell's dense pool is a prefix of the max-topk pool, sliced rather than re-retrieved.
|
|
@@ -40,52 +53,61 @@ from sqlite_graph_memory import brain_ask as ba # noqa: E402
|
|
|
40
53
|
from run_eval import SMALL_N, mrr_at, ndcg_at, recall_at # noqa: E402
|
|
41
54
|
|
|
42
55
|
|
|
43
|
-
def _default_cell():
|
|
44
|
-
return {'hops': 1, 'ghops': ba.GHOPS, 'gmax': ba.GMAX,
|
|
56
|
+
def _default_cell(topk_retrieve=None):
|
|
57
|
+
return {'hops': 1, 'ghops': ba.GHOPS, 'gmax': ba.GMAX,
|
|
58
|
+
'topk': ba.TOPK_RETRIEVE if topk_retrieve is None else topk_retrieve,
|
|
45
59
|
'entity_gate': True}
|
|
46
60
|
|
|
47
61
|
|
|
48
|
-
def _fill_cell(partial, index):
|
|
49
|
-
cell = _default_cell()
|
|
62
|
+
def _fill_cell(partial, index, topk_retrieve=None):
|
|
63
|
+
cell = _default_cell(topk_retrieve=topk_retrieve)
|
|
50
64
|
cell.update(partial)
|
|
51
65
|
if not cell.get('name'):
|
|
52
66
|
cell['name'] = 'cell-%d' % index
|
|
53
67
|
if cell['hops'] not in (0, 1):
|
|
54
68
|
raise ValueError("cell %r: hops must be 0 or 1 (score_grid only runs the 1-hop "
|
|
55
69
|
"expand_1hop), got %r" % (cell['name'], cell['hops']))
|
|
70
|
+
if cell['topk'] < 1:
|
|
71
|
+
raise ValueError("cell %r: topk must be >= 1, got %r" % (cell['name'], cell['topk']))
|
|
56
72
|
return cell
|
|
57
73
|
|
|
58
74
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
75
|
+
_DEFAULT_CELL_SPECS = [
|
|
76
|
+
{'name': '0-hop', 'hops': 0},
|
|
77
|
+
{'name': '1-hop'},
|
|
78
|
+
{'name': 'gmax-10', 'gmax': 10},
|
|
79
|
+
{'name': 'gmax-20', 'gmax': 20},
|
|
80
|
+
{'name': 'gmax-80', 'gmax': 80},
|
|
81
|
+
{'name': 'topk-15', 'topk': 15},
|
|
82
|
+
{'name': 'topk-20', 'topk': 20},
|
|
83
|
+
{'name': 'topk-80', 'topk': 80},
|
|
84
|
+
{'name': 'ghops-5', 'ghops': 5},
|
|
85
|
+
{'name': 'ghops-30', 'ghops': 30},
|
|
86
|
+
{'name': 'entity-gate-off', 'entity_gate': False},
|
|
70
87
|
]
|
|
88
|
+
DEFAULT_GRID = [_fill_cell(c, i) for i, c in enumerate(_DEFAULT_CELL_SPECS)]
|
|
71
89
|
GRID_PRESETS = {'default': DEFAULT_GRID}
|
|
72
90
|
|
|
73
91
|
_BOOL_KEYS = {'entity_gate'}
|
|
74
92
|
_STR_KEYS = {'name'}
|
|
75
93
|
|
|
76
94
|
|
|
77
|
-
def parse_grid(spec):
|
|
95
|
+
def parse_grid(spec, topk_retrieve=None):
|
|
78
96
|
"""'default' | a path or literal JSON array of cell dicts | ';'-separated key=val cells."""
|
|
79
97
|
spec = (spec or 'default').strip()
|
|
80
98
|
if spec in GRID_PRESETS:
|
|
81
|
-
|
|
99
|
+
if topk_retrieve is None:
|
|
100
|
+
return GRID_PRESETS[spec]
|
|
101
|
+
return [_fill_cell(c, i, topk_retrieve=topk_retrieve)
|
|
102
|
+
for i, c in enumerate(_DEFAULT_CELL_SPECS)]
|
|
82
103
|
|
|
83
104
|
path = Path(spec)
|
|
84
105
|
if path.exists():
|
|
85
106
|
spec = path.read_text(encoding='utf-8')
|
|
86
107
|
|
|
87
108
|
if spec.lstrip().startswith('['):
|
|
88
|
-
return [_fill_cell(c, i
|
|
109
|
+
return [_fill_cell(c, i, topk_retrieve=topk_retrieve)
|
|
110
|
+
for i, c in enumerate(json.loads(spec))]
|
|
89
111
|
|
|
90
112
|
cells = []
|
|
91
113
|
for i, part in enumerate(spec.split(';')):
|
|
@@ -101,7 +123,7 @@ def parse_grid(spec):
|
|
|
101
123
|
partial[k] = v
|
|
102
124
|
else:
|
|
103
125
|
partial[k] = int(v)
|
|
104
|
-
cells.append(_fill_cell(partial, i))
|
|
126
|
+
cells.append(_fill_cell(partial, i, topk_retrieve=topk_retrieve))
|
|
105
127
|
return cells
|
|
106
128
|
|
|
107
129
|
|
|
@@ -129,7 +151,19 @@ def load_gold(path):
|
|
|
129
151
|
|
|
130
152
|
|
|
131
153
|
def score_grid(gold, grid, emb, meta, enc, ce, by_base=None):
|
|
132
|
-
"""Score every grid cell against gold.
|
|
154
|
+
"""Score every grid cell against gold.
|
|
155
|
+
-> [{cell, cls, recall, mrr, ndcg, gated, hop_applied, rank_changed}, ...].
|
|
156
|
+
|
|
157
|
+
`gated` is whether this cell's entity_gate suppressed the hop for this query,
|
|
158
|
+
independent of `hops` (it reflects what the gate alone would have done).
|
|
159
|
+
`hop_applied` is whether expand_1hop actually admitted >=1 new candidate for
|
|
160
|
+
this (query, cell) — the thing a metric delta can't show when the gold note
|
|
161
|
+
was already in `base` (issue #93: gate-on and gate-off score identically
|
|
162
|
+
because admission, not suppression, is what moved).
|
|
163
|
+
`rank_changed` is whether this cell's top-12 ranking differs at all from the
|
|
164
|
+
0-hop baseline cell's, for this same query — a single-note gold pins rank #1
|
|
165
|
+
regardless of what fills ranks 2..12, so recall/mrr/ndcg can read unchanged
|
|
166
|
+
(delta_ndcg == 0.0) while the hop still reordered everything below it.
|
|
133
167
|
|
|
134
168
|
One dense pass (query_sims + the max-topk retrieve) per query; only the rerank,
|
|
135
169
|
which depends on each cell's own candidate set, runs once per (query, cell).
|
|
@@ -137,30 +171,42 @@ def score_grid(gold, grid, emb, meta, enc, ce, by_base=None):
|
|
|
137
171
|
by_base = by_base or ba.index_by_basename(meta)
|
|
138
172
|
stem_of = lambda i: Path(meta[i]['path']).stem.lower()
|
|
139
173
|
max_topk = max(c['topk'] for c in grid)
|
|
174
|
+
baseline_name = next((c['name'] for c in grid if c['hops'] == 0), grid[0]['name'])
|
|
140
175
|
|
|
141
176
|
rows = []
|
|
142
177
|
for g in gold:
|
|
143
178
|
sims = ba.query_sims(enc, emb, g['query'])
|
|
144
179
|
order_max = ba.retrieve_candidates(sims, meta, topk=max_topk)
|
|
145
180
|
is_entity = ba.looks_like_entity(g['query'])
|
|
181
|
+
cell_results = []
|
|
146
182
|
for cell in grid:
|
|
147
183
|
base = order_max[:cell['topk']]
|
|
148
184
|
gated = cell['entity_gate'] and is_entity
|
|
149
|
-
|
|
150
|
-
|
|
185
|
+
# Gated cells still follow superseded_by (issue #93), matching brain_ask.main().
|
|
186
|
+
added = (ba.expand_1hop(sims, meta, base, by_base, ghops=cell['ghops'], gmax=cell['gmax'],
|
|
187
|
+
only_superseded=gated)
|
|
188
|
+
if cell['hops'] and base else [])
|
|
151
189
|
scored = ba.rerank_candidates(ce, g['query'], base + added, meta, sims=sims)
|
|
152
190
|
ranked = [stem_of(i) for i, _ in scored]
|
|
191
|
+
cell_results.append((cell, ranked, gated, added))
|
|
192
|
+
base_ranked = next((r for c, r, _, _ in cell_results if c['name'] == baseline_name), None)
|
|
193
|
+
for cell, ranked, gated, added in cell_results:
|
|
153
194
|
rows.append({'cell': cell['name'], 'cls': g['cls'],
|
|
154
195
|
'recall': recall_at(ranked, g['gold']),
|
|
155
196
|
'mrr': mrr_at(ranked, g['gold']),
|
|
156
|
-
'ndcg': ndcg_at(ranked, g['gold'])
|
|
197
|
+
'ndcg': ndcg_at(ranked, g['gold']),
|
|
198
|
+
'gated': gated, 'hop_applied': bool(added),
|
|
199
|
+
'rank_changed': base_ranked is not None and ranked != base_ranked})
|
|
157
200
|
return rows
|
|
158
201
|
|
|
159
202
|
|
|
160
203
|
def summarize_grid(rows, grid, classes):
|
|
161
|
-
"""-> ordered rows of {cell, class, n, recall, mrr, ndcg, delta_ndcg
|
|
162
|
-
(cell, class) plus (cell, 'overall');
|
|
163
|
-
(the grid's first hops=0 cell, else its
|
|
204
|
+
"""-> ordered rows of {cell, class, n, recall, mrr, ndcg, delta_ndcg, gate_rate,
|
|
205
|
+
hop_applied_rate, rank_churn}, one per (cell, class) plus (cell, 'overall');
|
|
206
|
+
delta_ndcg is vs the 0-hop baseline cell (the grid's first hops=0 cell, else its
|
|
207
|
+
first cell) for the same class. gate_rate/hop_applied_rate/rank_churn default to
|
|
208
|
+
0.0 for rows lacking those keys (older score_grid output, or hand-built rows in a
|
|
209
|
+
caller's own tests)."""
|
|
164
210
|
baseline = next((c['name'] for c in grid if c['hops'] == 0), grid[0]['name'])
|
|
165
211
|
by_cell_cls = {}
|
|
166
212
|
for r in rows:
|
|
@@ -169,7 +215,10 @@ def summarize_grid(rows, grid, classes):
|
|
|
169
215
|
def agg(rs):
|
|
170
216
|
n = len(rs)
|
|
171
217
|
return {'n': n, 'recall': sum(r['recall'] for r in rs) / n,
|
|
172
|
-
'mrr': sum(r['mrr'] for r in rs) / n, 'ndcg': sum(r['ndcg'] for r in rs) / n
|
|
218
|
+
'mrr': sum(r['mrr'] for r in rs) / n, 'ndcg': sum(r['ndcg'] for r in rs) / n,
|
|
219
|
+
'gate_rate': sum(r.get('gated', False) for r in rs) / n,
|
|
220
|
+
'hop_applied_rate': sum(r.get('hop_applied', False) for r in rs) / n,
|
|
221
|
+
'rank_churn': sum(r.get('rank_changed', False) for r in rs) / n}
|
|
173
222
|
|
|
174
223
|
out = []
|
|
175
224
|
for cell in grid:
|
|
@@ -187,22 +236,26 @@ def summarize_grid(rows, grid, classes):
|
|
|
187
236
|
|
|
188
237
|
|
|
189
238
|
def format_markdown(summary):
|
|
190
|
-
lines = ['| cell | class | n | Recall@12 | MRR | nDCG@12 | delta_nDCG@12 |',
|
|
191
|
-
'
|
|
239
|
+
lines = ['| cell | class | n | Recall@12 | MRR | nDCG@12 | delta_nDCG@12 | gate_rate | hop_applied_rate | rank_churn |',
|
|
240
|
+
'|---|---|---|---|---|---|---|---|---|---|']
|
|
192
241
|
for r in summary:
|
|
193
242
|
d = '' if r['delta_ndcg'] is None else '%+.3f' % r['delta_ndcg']
|
|
194
|
-
lines.append('| %s | %s | %d | %.3f | %.3f | %.3f | %s |'
|
|
195
|
-
% (r['cell'], r['class'], r['n'], r['recall'], r['mrr'], r['ndcg'], d
|
|
243
|
+
lines.append('| %s | %s | %d | %.3f | %.3f | %.3f | %s | %.3f | %.3f | %.3f |'
|
|
244
|
+
% (r['cell'], r['class'], r['n'], r['recall'], r['mrr'], r['ndcg'], d,
|
|
245
|
+
r['gate_rate'], r['hop_applied_rate'], r['rank_churn']))
|
|
196
246
|
return '\n'.join(lines)
|
|
197
247
|
|
|
198
248
|
|
|
199
249
|
def write_csv(summary, path):
|
|
200
250
|
with open(path, 'w', newline='', encoding='utf-8') as f:
|
|
201
251
|
w = csv.writer(f)
|
|
202
|
-
w.writerow(['cell', 'class', 'n', 'Recall@12', 'MRR', 'nDCG@12', 'delta_nDCG@12'
|
|
252
|
+
w.writerow(['cell', 'class', 'n', 'Recall@12', 'MRR', 'nDCG@12', 'delta_nDCG@12',
|
|
253
|
+
'gate_rate', 'hop_applied_rate', 'rank_churn'])
|
|
203
254
|
for r in summary:
|
|
204
255
|
w.writerow([r['cell'], r['class'], r['n'], round(r['recall'], 4), round(r['mrr'], 4),
|
|
205
|
-
round(r['ndcg'], 4), '' if r['delta_ndcg'] is None else round(r['delta_ndcg'], 4)
|
|
256
|
+
round(r['ndcg'], 4), '' if r['delta_ndcg'] is None else round(r['delta_ndcg'], 4),
|
|
257
|
+
round(r['gate_rate'], 4), round(r['hop_applied_rate'], 4),
|
|
258
|
+
round(r['rank_churn'], 4)])
|
|
206
259
|
|
|
207
260
|
|
|
208
261
|
def low_n_warnings(summary, small_n=SMALL_N):
|
|
@@ -217,6 +270,8 @@ def main():
|
|
|
217
270
|
ap.add_argument('--grid', default='default',
|
|
218
271
|
help="'default', a JSON array of cells, a path to one, or "
|
|
219
272
|
"';'-separated key=val cells (default: %(default)s)")
|
|
273
|
+
ap.add_argument('--pool', '--topk-retrieve', dest='topk_retrieve', type=int, default=None,
|
|
274
|
+
help='override default dense candidate pool size (topk) for cells that do not set topk')
|
|
220
275
|
ap.add_argument('--list-grid', action='store_true',
|
|
221
276
|
help='print the named grid cells and exit (no model/index load)')
|
|
222
277
|
ap.add_argument('--out', help='output prefix for <prefix>.csv/.md (default: eval/ablation-<ts>)')
|
|
@@ -228,7 +283,13 @@ def main():
|
|
|
228
283
|
if a.rerank:
|
|
229
284
|
os.environ['SGM_RERANK'] = '1'
|
|
230
285
|
|
|
231
|
-
|
|
286
|
+
pool = a.topk_retrieve
|
|
287
|
+
if pool is None:
|
|
288
|
+
pool, _ = ba._parse_pool([])
|
|
289
|
+
elif pool < 1:
|
|
290
|
+
return ap.error('--pool / --topk-retrieve must be >= 1')
|
|
291
|
+
|
|
292
|
+
grid = parse_grid(a.grid, topk_retrieve=pool)
|
|
232
293
|
if a.list_grid:
|
|
233
294
|
print_grid(grid)
|
|
234
295
|
return 0
|