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:
@@ -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")
|
||||
@@ -71,14 +71,18 @@ def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
|
||||
e._skim_leads = []
|
||||
e._skim_notices = []
|
||||
e._current_goal_terms = []
|
||||
e._extract_entities = []
|
||||
e._embed_ok = True
|
||||
e._qvec_cache = {}
|
||||
return e
|
||||
|
||||
|
||||
def test_process_page_fragments():
|
||||
"""The extract path over table fragments: no-signal frags skip free,
|
||||
STOP_TABLE kills the REST of that table (never other tables), and
|
||||
surviving fragments ingest their rows with containment-checked quotes.
|
||||
Mirrors run G: goal flow, page holds world-rivers + Italy tables."""
|
||||
the TABLE SKIM (question-aware, pre-extraction) kills hopeless tables
|
||||
BEFORE any extract spend, and surviving fragments ingest their rows
|
||||
with containment-checked quotes. Mirrors run G: goal flow, page holds
|
||||
world-rivers + Italy tables."""
|
||||
import tempfile
|
||||
from knowledge.wiki import parse_tables
|
||||
|
||||
@@ -92,18 +96,31 @@ def test_process_page_fragments():
|
||||
wikitext=WIKITEXT_2TABLES)
|
||||
page.tables = parse_tables(WIKITEXT_2TABLES)
|
||||
|
||||
# scripted extractor: world-table parts -> stop_table=True; Italy table -> one Fact
|
||||
# scripted TABLE SKIM: world table not relevant; Italy table relevant
|
||||
class Decision:
|
||||
def __init__(self, idx, relevant, reason=""):
|
||||
self.table_index = idx
|
||||
self.relevant = relevant
|
||||
self.reason = reason
|
||||
|
||||
class SkimOut:
|
||||
def __init__(self, decisions):
|
||||
self.decisions = decisions
|
||||
|
||||
e.skim_tables = lambda question, entities, tables: SkimOut([
|
||||
Decision(1, False, "world rivers, not Italy"),
|
||||
Decision(2, True, "rivers of Italy with flow"),
|
||||
])
|
||||
|
||||
# scripted extractor: facts for whichever table the skim lets through
|
||||
calls = []
|
||||
|
||||
class FakeOut:
|
||||
def __init__(self, facts, stop_table=False):
|
||||
def __init__(self, facts):
|
||||
self.facts = facts
|
||||
self.stop_table = stop_table
|
||||
|
||||
def fake_extract(question, heading, text, _calls=calls):
|
||||
_calls.append((question, heading, text))
|
||||
if "World rivers" in text:
|
||||
return FakeOut([], stop_table=True)
|
||||
def fake_extract(entities, heading, text, _calls=calls):
|
||||
_calls.append((entities, heading, text))
|
||||
if "Rivers of Italy" in text:
|
||||
# quote = the full rendered row context (header + row), verbatim
|
||||
# from the fragment the extractor saw
|
||||
@@ -117,20 +134,21 @@ def test_process_page_fragments():
|
||||
|
||||
q = "What is the total water flow of the three longest rivers of Italy?"
|
||||
kws = e._keywords("What is the water flow of rivers of Italy?")
|
||||
e._extract_entities = ["Italy"]
|
||||
# _process_page signature: (page, question, kws, goal_terms, charge_llm)
|
||||
n = e._process_page(page, question=q, kws=kws,
|
||||
goal_terms=["total", "water", "flow", "italy"],
|
||||
charge_llm=None)
|
||||
goal_terms=["total", "water", "flow", "italy"],
|
||||
charge_llm=None)
|
||||
# the Italy fragment ingested its fact (merged counts edges)
|
||||
rows = store.probe(["italy", "flow"])
|
||||
# probe returns norm_name'd src ('po', not 'Po') — store law
|
||||
assert any(r.dst == "1540 m3/s" and r.src == "po"
|
||||
and r.rel == "Flow at the mouth" for r in rows), rows
|
||||
# STOP_TABLE must have short-circuited table 1 after its FIRST fragment:
|
||||
# at most 1 extract call for table 1 (not 3), plus 1 for the Italy table
|
||||
# the skim must have killed the world table BEFORE extraction: zero
|
||||
# extract calls touch it (parts 1-3 all skipped, zero spend)
|
||||
world_calls = [c for c in calls if "World rivers" in c[2]]
|
||||
assert len(world_calls) == 1, f"STOP_TABLE did not skip parts 2/3: {len(world_calls)} calls"
|
||||
print("ok: extract fragments — STOP_TABLE skips rest of table, facts ingest")
|
||||
assert len(world_calls) == 0, f"skim did not kill table 1 pre-extract: {len(world_calls)} calls"
|
||||
print("ok: table skim kills hopeless tables pre-extract; surviving frags ingest")
|
||||
|
||||
|
||||
def test_prompt_log():
|
||||
|
||||
Reference in New Issue
Block a user