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
+62 -1
View File
@@ -38,6 +38,9 @@ CREATE TABLE IF NOT EXISTS conflicts (
id INTEGER PRIMARY KEY, node INTEGER, rel TEXT, value_a TEXT, value_b TEXT,
edge_a INTEGER, edge_b INTEGER, note TEXT
);
CREATE TABLE IF NOT EXISTS edge_vectors (
edge_id INTEGER PRIMARY KEY, model TEXT, text_hash TEXT, vec BLOB
);
CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_node, rel);
CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(norm_name);
"""
@@ -68,6 +71,7 @@ def stem(word: str) -> str:
@dataclass
class EdgeView:
eid: int
src: str
rel: str
dst: str
@@ -257,11 +261,68 @@ class KnowledgeStore:
conflict = self.db.execute(
"SELECT 1 FROM conflicts WHERE edge_a=? OR edge_b=?", (eid, eid)).fetchone()
views.append(EdgeView(
src=sname, rel=rel, dst=dstv, quote=quote, url=url,
eid=eid, src=sname, rel=rel, dst=dstv, quote=quote, url=url,
ref_date=rd, corroboration=cor, preferred=bool(pref),
conflict=bool(conflict)))
# ---- membership queries (LIST path) --------------------------------------
def set_edge_vector(self, edge_id: int, model: str, text_hash: str,
vec: list[float]) -> None:
"""Cache one edge's vector, keyed by (edge_id, model, text_hash):
switching models (or the edge text changing) invalidates cleanly —
the probe re-embeds, the stale row is replaced. Append-only law is
kept for QUOTES and EDGES; vectors are a derived cache, upserted."""
import struct
blob = struct.pack(f"{len(vec)}f", *vec)
self.db.execute(
"INSERT OR REPLACE INTO edge_vectors(edge_id, model, text_hash, vec) "
"VALUES(?,?,?,?)", (edge_id, model, text_hash, blob))
self.db.commit()
def semantic_probe(self, qvec: list[float], tau: float = 0.45,
limit: int = 20) -> list[EdgeView]:
"""Semantic retrieval: cosine rank ALL edges with a cached vector
(for the current model) against the question vector, keep >= tau.
nomic does not separate 'facts about the same entity' from 'facts
that answer the question' (calibration: spouse 0.67) — the semantic
layer RANKS and surfaces vocabulary the lexical probe cannot see
('Prime Minister' vs 'President'), the JUDGE still decides. At
hundreds of edges brute force over cached blobs is instant."""
import struct
from .embeddings import cosine as _cos
out: list[EdgeView] = []
rows = self.db.execute(
"SELECT v.edge_id, v.vec FROM edge_vectors v").fetchall()
scored: list[tuple[float, EdgeView]] = []
for eid, blob in rows:
n = len(blob) // 4
vec = struct.unpack(f"{n}f", blob)
d = _cos(qvec, vec)
if d < tau:
continue
ev = self._edge_view_by_id(eid)
if ev is not None:
scored.append((d, ev))
scored.sort(key=lambda t: -t[0])
return [ev for _, ev in scored[:limit]]
def _edge_view_by_id(self, eid: int) -> EdgeView | None:
e = self.db.execute(
"SELECT e.id, e.rel, e.dst_value, e.dst_node, e.ref_date, e.corroboration, "
"e.preferred, e.retracted, q.verbatim, q.url, n.norm_name "
"FROM edges e JOIN quotes q ON q.id=e.quote_id "
"JOIN nodes n ON n.id=e.src_node WHERE e.id=?", (eid,)).fetchone()
if not e:
return None
conflict = self.db.execute(
"SELECT 1 FROM conflicts WHERE edge_a=? OR edge_b=?", (eid, eid)).fetchone()
(eid_, rel, dstv, dstn, rd, cor, pref, retr, quote, url, sname) = e
return EdgeView(
eid=eid, src=sname, rel=rel, dst=dstv, quote=quote, url=url,
ref_date=rd, corroboration=cor, preferred=bool(pref),
conflict=bool(conflict))
def member_sets(self) -> list[str]:
"""Distinct set names that have membership edges (rel='member_of')."""
rows = self.db.execute(