research(knowledge): semantic KG retrieval + question-blind extraction

Implements his design (RESEARCH-semantic-kg.md) on the research branch:

1. EMBEDDINGS (knowledge/embeddings.py): local ollama /api/embed,
   nomic-embed-text 768d — the only proven endpoint (ollama.com has
   NO embeddings API). Honest failure: EmbedderDown -> lexical probe
   fallback, never a dead run.

2. SEMANTIC PROBE: edge_vectors cache in the store (keyed edge_id +
   model + text_hash; upsert, last model wins), cosine rank over all
   cached edges, tau=0.45 from real calibration (rivers 0.49-0.52 must
   pass; cross-question Pedro-vs-rivers 0.35-0.38 must not). Hybrid
   _probe: lexical UNION semantic, dedup by eid. EdgeView gains eid.

3. QUESTION-BLIND EXTRACTION: ExtractSignature loses 'question' and
   stop_table — it receives ENTITIES only (from TRANSLATE + evidence
   + proper nouns) and transcribes their facts, capped per chunk
   (max_facts_per_chunk=12). Facts cache vectors at ingest. The KG
   fattens per-entity, reusable across questions (his cacheability
   argument).

4. STOP MOVES TO THE SKIM: SkimTableSignature decides per table from
   caption+header+row count+first rows (one LLM call per page) BEFORE
   any extraction spend; tables that literally name an entity skip the
   call. The extractor itself never judges relevance.

VERIFIED: knowledge suite 8/8 (semantic.py new 4/4: lexical-missed edge
surfaced, hybrid dedup, embedder-down degradation, cache upsert;
tablefrags adapted: skim kills tables pre-extract). floop suite 9/9.
Live E2E (glm): semantic probe fires live (+1 lexical-missed edge);
blind extractor ingests 12-fact chunks; Pedro run answers 'himself'
(3rd gov succeeded his 2nd — a reading trap, NOT a retrieval failure;
INIT degraded honestly on garbage); rivers run burned budget on
fan-out ROUTE calls (22x2) — both findings logged as open work on the
research doc, not regressions of this PR.
This commit is contained in:
2026-10-23 08:44:36 +02:00
parent 1a4f25bc84
commit 872d4b9d42
7 changed files with 542 additions and 103 deletions
+168
View File
@@ -0,0 +1,168 @@
"""Semantic KG retrieval tests (research/semantic-kg).
Laws under test:
1. semantic_probe ranks cached edge vectors by cosine and keeps >= tau:
the 'President' question surfaces the 'Prime Minister' edge the LEXICAL
probe cannot see (no shared stems) — calibration 0.71 vs cross-ques
noise 0.35-0.38, tau=0.45.
2. The hybrid _probe: lexical UNION semantic, dedup by edge id — the
same edge never enters twice.
3. Honest degradation: embedder down -> lexical rows only, never a dead
run (_embed_ok flips, the log says it).
4. Vectors are a cache keyed (edge_id, model, text_hash): switching the
model invalidates — the stale vector is replaced, not mixed.
5. EdgeView carries eid (dedup key between the two probes).
Network: the embed() calls are monkeypatched with scripted vectors —
the test runs offline.
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
import knowledge.embeddings as emb
from knowledge.expert import KnowledgeConfig, KnowledgeExpert
from knowledge.store import KnowledgeStore
def make_store(tmp: str) -> KnowledgeStore:
return KnowledgeStore(f"{tmp}/kg.sqlite")
def _add_fact(store: KnowledgeStore, src: str, rel: str, dst: str,
quote: str) -> int:
doc = store.add_document(url="http://x/" + src, title=src,
fetched_at="2026-10-22", sha256="sha" + src)
qid = store.add_quote(doc, quote, "http://x/" + src, "2026-10-22")
return store.add_edge(src, rel, dst, qid)
def test_semantic_probe_surfaces_lexical_miss():
"""The Pedro case: 'President before' shares NO stems with 'prime
minister of Spain' — the lexical probe misses it, the semantic one
must surface it (this is the long search his run paid)."""
import tempfile
store = make_store(tempfile.mkdtemp())
e1 = _add_fact(store, "Pedro Sanchez", "position",
"Prime Minister of Spain", "he has been the prime "
"minister of Spain since 2018")
e2 = _add_fact(store, "Po", "length", "652 km", "the Po is 652 km long")
# scripted vectors: PM-edge close to the question, Po-edge far away
q_vec = [1.0, 0.0, 0.0]
pm_vec = [0.92, 0.39, 0.0]
po_vec = [0.0, 0.2, 0.98]
store.set_edge_vector(e1, "test-model", "h1", pm_vec)
store.set_edge_vector(e2, "test-model", "h2", po_vec)
hits = store.semantic_probe(q_vec, tau=0.45)
assert any("Prime Minister" in (h.dst or "") for h in hits), hits
assert all("652" not in (h.dst or "") for h in hits), hits
print("ok: semantic probe surfaces the lexical-missed edge (PM of Spain)")
def test_hybrid_probe_dedups():
"""Lexical UNION semantic with dedup by edge id: an edge found by both
probes appears once. The lexical hit keeps its position; the semantic
fills the tail."""
import tempfile
store = make_store(tempfile.mkdtemp())
e1 = _add_fact(store, "Po", "length", "652 km", "the Po is 652 km long")
e2 = _add_fact(store, "Pedro Sanchez", "position",
"Prime Minister of Spain", "prime minister since 2018")
store.set_edge_vector(e1, "m", "h1", [1.0, 0.0])
store.set_edge_vector(e2, "m", "h2", [1.0, 0.1])
expert = KnowledgeExpert.__new__(KnowledgeExpert)
expert.cfg = KnowledgeConfig()
expert.store = store
expert.streams = None
expert._embed_ok = True
expert._qvec_cache = {}
expert._log = lambda *a, **k: None
orig_embed = emb.embed
try:
def fake_embed(texts, model=None, url=None, timeout=60):
vecs = {"Who was the President before Pedro Sanchez?": [0.95, 0.31],
"Po | length | 652 km": [1.0, 0.0],
"Pedro Sanchez | position | Prime Minister of Spain": [1.0, 0.1]}
return [vecs[t] for t in texts]
from knowledge import expert as expert_mod
expert_mod.embed = fake_embed # the module's imported name
rows = expert._probe("Who was the President before Pedro Sanchez?",
["pedro", "president"])
eids = [r.eid for r in rows]
assert len(eids) == len(set(eids)), f"dupes in hybrid probe: {rows}"
# lexical hit (Po) present; semantic-only hit (PM) also present
assert any(r.src == "po" for r in rows), rows
assert any("Prime Minister" in (r.dst or "") for r in rows), rows
print("ok: hybrid probe — lexical UNION semantic, dedup by eid")
finally:
from knowledge import expert as expert_mod
expert_mod.embed = orig_embed
del expert_mod
def test_embedder_down_degrades():
"""Embedder down: _embed_ok flips, the probe returns the lexical rows
alone, and nothing raises — the run stays alive (offline fallback)."""
import tempfile
store = make_store(tempfile.mkdtemp())
_add_fact(store, "Po", "length", "652 km", "the Po is 652 km long")
expert = KnowledgeExpert.__new__(KnowledgeExpert)
expert.cfg = KnowledgeConfig()
expert.store = store
expert.streams = None
expert._embed_ok = True
expert._qvec_cache = {}
notes = []
expert._log = lambda text, think=False: notes.append(text)
from knowledge import expert as expert_mod
orig = expert_mod.embed
def boom(texts, model=None, url=None, timeout=60):
raise emb.EmbedderDown("endpoint down")
expert_mod.embed = boom
try:
rows = expert._probe("length of the Po river?", ["river", "length"])
assert rows and rows[0].src == "po", rows
assert expert._embed_ok is False
assert any("disabled" in n for n in notes), notes
# second call: no embed attempt at all (cache of the failure)
rows2 = expert._probe("length of the Po river?", ["river", "length"])
assert rows2
print("ok: embedder down -> lexical degradation, run alive")
finally:
expert_mod.embed = orig
def test_vector_cache_invalidates_by_model():
"""Keyed (edge_id, model, text_hash): a new model replaces the stale
row — the probe never mixes vectors of two models."""
import tempfile
store = make_store(tempfile.mkdtemp())
eid = _add_fact(store, "Po", "length", "652 km", "the Po is 652 km")
store.set_edge_vector(eid, "model-a", "h1", [1.0, 0.0])
store.set_edge_vector(eid, "model-b", "h1", [0.0, 1.0])
# question along model-b's direction (the LAST upserted vector): the
# edge hits; along model-a's old direction it must NOT (replaced)
hits_b = store.semantic_probe([0.0, 1.0], tau=0.9)
assert hits_b and hits_b[0].eid == eid, hits_b
hits_a = store.semantic_probe([1.0, 0.0], tau=0.9)
assert not hits_a, f"stale model-a vector still live: {hits_a}"
import sqlite3
rows = store.db.execute(
"SELECT model, vec FROM edge_vectors WHERE edge_id=?", (eid,)).fetchall()
assert len(rows) == 1 and rows[0][0] == "model-b", f"upsert failed: {rows}"
print("ok: vector cache upserts (one row per edge; last model wins)")
if __name__ == "__main__":
test_semantic_probe_surfaces_lexical_miss()
test_hybrid_probe_dedups()
test_embedder_down_degrades()
test_vector_cache_invalidates_by_model()
print("\nsemantic kg tests passed")