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
+34 -16
View File
@@ -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():