diff --git a/CHANGELOG.md b/CHANGELOG.md index 55702a1..6a3dd04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ recorded after the fact rather than backdated to look contemporaneous. **`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. +**`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. + ## v0.3.7 - 2026-11-05 **Recall: the cross-encoder rerank is off by default.** `sgm-ask`, the MCP tool and `eval/run_eval.py` now order candidates by dense e5 similarity; `--rerank` or `SGM_RERANK=1` brings the cross-encoder back. Measured before the change: on our 184-question gold set the reranker cut body nDCG@12 from 0.815 to 0.640, and on DolphinBench data (Riley, 50 tests, 1000 sessions) Recall@5 fell from 0.61 to 0.48; it still helped short title-style queries. Dense recall is also faster on CPU (about 0.04 s against 2.8 s per query on that slice). `rerank_candidates()` takes `sims=` and keeps dense order when no cross-encoder is passed. diff --git a/eval/build_gold.py b/eval/build_gold.py index e3f85f7..a7cf5b8 100644 --- a/eval/build_gold.py +++ b/eval/build_gold.py @@ -6,9 +6,10 @@ The notes it `[[links]]` to are the neighbours a human decided are related. Nobody has to label anything, and no LLM is called — this script is pure file work plus the index meta. -Four question classes, each probing a different part of the pipeline: +Five question classes, each probing a different part of the pipeline: title query = the note's title -> gold = that note (name lookup) + heading query = a short markdown heading -> gold = that note (heading lookup) body query = its first paragraph -> gold = that note (theme lookup) bridge query = its first paragraph -> gold = its [[link]] TARGETS (the graph) temporal query = an outdated note's title -> gold = its replacement (see below) @@ -41,8 +42,10 @@ class simply comes out empty and `run_eval.py` says so instead of pretending. from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src')) +from sqlite_graph_memory.brain_ask import looks_like_entity # noqa: E402 from sqlite_graph_memory.index_notes import iter_notes # noqa: E402 +FENCED_CODE_RX = re.compile(r'(?:```[\s\S]*?```|~~~[\s\S]*?~~~)') WIKILINK_RX = re.compile(r'\[\[([^\]\|#]+)(?:[|#][^\]]*)?\]\]') CYRILLIC_RX = re.compile(r'[а-яё]', re.I) @@ -86,6 +89,22 @@ def note_title(fm, body, path): return strip_markup(t)[:200] +def note_heading(body): + """First short (<= 5 words) markdown heading in `body` that triggers looks_like_entity. + + Prefers `##`..`######` subheadings over `#` H1 headings so notes with section headings + contribute non-title queries; fenced code blocks are ignored, and frontmatter titles are + not used as headings. + """ + clean = FENCED_CODE_RX.sub('', body or '') + sub = [strip_markup(m.group(1))[:200] for m in re.finditer(r'(?m)^#{2,6}\s+(.+)$', clean)] + h1 = [strip_markup(m.group(1))[:200] for m in re.finditer(r'(?m)^#\s+(.+)$', clean)] + for h in sub + h1: + if len(h) >= 4 and 1 <= len(h.split()) <= 5 and looks_like_entity(h): + return h + return None + + def first_paragraph(body, minlen=100, maxlen=400): """First real prose paragraph: no headings, tables, code fences or blockquotes. @@ -121,7 +140,7 @@ def indexed_stems(index_dir): def read_notes(notes_dir, stems, folders=None): - """Every indexed note, parsed into the fields the four classes need.""" + """Every indexed note, parsed into the fields the five classes need.""" root = Path(notes_dir) paths = [] # 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): sup_m = WIKILINK_RX.findall(sup) if sup else [] sup = sup_m[0].strip().lower() if sup_m else (sup.strip().lower() if sup else None) notes.append({'stem': p.stem.lower(), 'folder': (p.relative_to(root).parts[:-1] or ('',))[0], - 'title': note_title(fm, body, p), 'para': first_paragraph(body), + 'title': note_title(fm, body, p), 'heading': note_heading(body), + 'para': first_paragraph(body), 'links': links, 'sup': sup if sup in stems else None}) return notes @@ -163,13 +183,19 @@ def build_gold(notes, n_per_class, seed): notes = list(notes) rnd.shuffle(notes) pools = {'title': [n for n in notes if len(n['title']) >= 8], + 'heading': [n for n in notes if n.get('heading')], 'body': [n for n in notes if n['para']], 'bridge': [n for n in notes if n['para'] and len(n['links']) >= 2], 'temporal': [n for n in notes if n['sup']]} gold = [] - for cls in ('title', 'body', 'bridge', 'temporal'): + for cls in ('title', 'heading', 'body', 'bridge', 'temporal'): for n in pools[cls][:n_per_class]: - q = n['para'] if cls in ('body', 'bridge') else n['title'] + if cls in ('body', 'bridge'): + q = n['para'] + elif cls == 'heading': + q = n['heading'] + else: + q = n['title'] if cls == 'bridge': g, dropped = n['links'][:BRIDGE_MAX_GOLD], max(0, len(n['links']) - BRIDGE_MAX_GOLD) elif cls == 'temporal': @@ -217,7 +243,7 @@ def main(): print(' ! %d bridge questions had more than %d links; the rest were cut, because ' 'Recall@12 has only 12 slots' % (cut, BRIDGE_MAX_GOLD)) print(' classes %s · languages %s' % (dict(counts), dict(Counter(g['lang'] for g in gold)))) - for cls in ('title', 'body', 'bridge', 'temporal'): + for cls in ('title', 'heading', 'body', 'bridge', 'temporal'): if counts[cls] < 20: print(' ! %s: only %d questions — too few to judge a change by; treat as a smoke test' % (cls, counts[cls])) diff --git a/tests/test_eval.py b/tests/test_eval.py index dadf6e7..7139c44 100644 --- a/tests/test_eval.py +++ b/tests/test_eval.py @@ -28,7 +28,8 @@ sys.path.insert(0, str(ROOT / 'eval')) from build_gold import (build_gold, first_paragraph, indexed_stems, # noqa: E402 - lang_of, read_notes) + lang_of, note_heading, read_notes) +from sqlite_graph_memory.brain_ask import looks_like_entity # noqa: E402 from run_eval import mrr_at, ndcg_at, recall_at, SMALL_N # noqa: E402 import run_ablation # noqa: E402 from run_ablation import (DEFAULT_GRID, format_markdown, low_n_warnings, # noqa: E402 @@ -100,7 +101,8 @@ def _vault(tmp_path): '\n\nSee [[beta]] and [[gamma]] for the rest.\n', encoding='utf-8') (tmp_path / 'beta.md').write_text('---\ntitle: "Beta the second note"\n---\n\n' + PARA + '\n', encoding='utf-8') - (tmp_path / 'gamma.md').write_text('# Gamma the third note\n\n' + PARA + '\n', encoding='utf-8') + (tmp_path / 'gamma.md').write_text('# Gamma the third note\n\n## Gamma Overview\n\n' + PARA + '\n', + encoding='utf-8') (tmp_path / 'old-rule.md').write_text( '---\ntitle: "Old rule about backups"\nsuperseded_by: "[[beta]]"\n---\n\n' + PARA + '\n', encoding='utf-8') @@ -128,10 +130,92 @@ def test_every_class_is_built_from_the_right_note(tmp_path): bridge_alpha = next(g for g in by_cls['bridge'] if g['src'] == 'alpha') assert bridge_alpha['gold'] == ['beta', 'gamma'] # the wikilinks ARE the answer + heading_gamma = next(g for g in by_cls['heading'] if g['src'] == 'gamma') + assert heading_gamma['query'] == 'Gamma Overview' + assert looks_like_entity(heading_gamma['query']) + assert heading_gamma['gold'] == ['gamma'] + assert all(g['src'] != 'alpha' for g in by_cls['heading']) # frontmatter title without body # is not a heading + temporal = next(iter(by_cls['temporal'])) assert temporal['src'] == 'old-rule' and temporal['gold'] == ['beta'] +def test_heading_class_prefers_subheadings_ignores_code_fences_and_unrelated_links(tmp_path): + """Issue #93 PR 3: short heading queries (<= 5 words) target their source note, not unrelated links.""" + vault = _vault(tmp_path) + (vault / 'alpha.md').write_text( + '---\ntitle: "Alpha the first note"\n---\n\n' + '```python\n# NotAHeading\n```\n\n' + '## Backup Schedule\n\n' + PARA + '\n\nSee [[beta]] and [[gamma]] for the rest.\n', + encoding='utf-8') + (vault / 'beta.md').write_text( + '---\ntitle: "Beta the second note"\n---\n\n# Project Avocet\n\n' + PARA + '\n', + encoding='utf-8') + gold = build_gold(read_notes(vault, INDEXED), n_per_class=10, seed=1) + headings = [g for g in gold if g['cls'] == 'heading'] + assert headings + for g in headings: + assert 1 <= len(g['query'].split()) <= 5 + assert looks_like_entity(g['query']) + assert 'NotAHeading' not in g['query'] + assert g['gold'] == [g['src']] + assert g['gold_truncated'] == 0 + + by_src = {g['src']: g for g in headings} + assert by_src['alpha']['query'] == 'Backup Schedule' + assert by_src['alpha']['gold'] == ['alpha'] # source note, not unrelated [[beta]] / [[gamma]] + assert by_src['beta']['query'] == 'Project Avocet' + assert by_src['beta']['gold'] == ['beta'] + + # Prove entity_gate bites on a build_gold-generated heading question in run_ablation.score_grid + meta, emb = _linked_vault(tmp_path) + heading_q = [{'query': by_src['alpha']['query'], 'cls': 'heading', 'gold': ['friend']}] + grid = parse_grid('hops=1,topk=1,gmax=10,entity_gate=1,name=gated;' + 'hops=1,topk=1,gmax=10,entity_gate=0,name=ungated') + rows = score_grid(heading_q, grid, emb, meta, _FakeEncoder(), _FakeReranker()) + by_cell = {r['cell']: r for r in rows} + assert by_cell['gated']['recall'] == 0.0 + assert by_cell['ungated']['recall'] == 1.0 + + +def test_heading_class_empty_when_no_qualifying_headings_and_existing_classes_reproduce_for_seed(tmp_path): + """A vault with no qualifying short headings produces an empty heading class (no crash), + and the four existing classes pick the exact same questions for a given seed.""" + vault = _vault(tmp_path) + notes_with_headings = read_notes(vault, INDEXED) + gold_with = build_gold(notes_with_headings, n_per_class=10, seed=42) + + # Strip body headings from every note (leaving frontmatter titles or >5-word headings only). + (vault / 'beta.md').write_text( + '---\ntitle: "Beta the second note"\n---\n\n' + '## Why this heading is deliberately much longer than five words\n\n' + PARA + '\n', + encoding='utf-8') + (vault / 'gamma.md').write_text( + '---\ntitle: "Gamma the third note"\n---\n\n' + PARA + '\n', + encoding='utf-8') + notes_no_headings = read_notes(vault, INDEXED) + gold_without = build_gold(notes_no_headings, n_per_class=10, seed=42) + + assert [g for g in gold_without if g['cls'] == 'heading'] == [] + # The four existing classes reproduce identically for the same seed. + assert [g for g in gold_with if g['cls'] != 'heading'] == gold_without + + # CLI prints the remaining classes cleanly and exits 0 without crashing. + index = tmp_path / 'index' + index.mkdir() + (index / '_brain_e5_meta.pkl').write_bytes(pickle.dumps( + [{'path': str(vault / (s + '.md')), 'title': s, 'snippet': PARA, 'date': ''} + for s in sorted(INDEXED)])) + out = tmp_path / 'gold-no-headings.jsonl' + env = {**dict(__import__('os').environ), 'BRAIN_INDEX_DIR': str(index)} + r = subprocess.run([sys.executable, str(ROOT / 'eval' / 'build_gold.py'), str(vault), + '--seed', '42', '--out', str(out)], + capture_output=True, text=True, env=env) + assert r.returncode == 0, r.stderr + assert 'classes {' in r.stdout and "'heading'" not in r.stdout + + + def test_a_note_outside_the_index_never_becomes_a_question_or_an_answer(tmp_path): vault = _vault(tmp_path) (vault / 'alpha.md').write_text( @@ -229,7 +313,7 @@ def test_build_gold_cli_writes_a_frozen_file(tmp_path): '--out', str(out)], capture_output=True, text=True, env=env) assert r.returncode == 0, r.stderr rows = [json.loads(l) for l in out.read_text(encoding='utf-8').splitlines() if l.strip()] - assert {r_['cls'] for r_ in rows} == {'title', 'body', 'bridge', 'temporal'} + assert {r_['cls'] for r_ in rows} == {'title', 'heading', 'body', 'bridge', 'temporal'} assert all(r_['gold'] for r_ in rows)