From 872d4b9d4252abaea814446f6097b9784a3ef8a3 Mon Sep 17 00:00:00 2001 From: Onibot Date: Fri, 23 Oct 2026 08:44:36 +0200 Subject: [PATCH] research(knowledge): semantic KG retrieval + question-blind extraction MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- code/floop/llm.py | 1 + code/knowledge/embeddings.py | 54 ++++++ code/knowledge/expert.py | 261 ++++++++++++++++++++--------- code/knowledge/extract.py | 48 ++++-- code/knowledge/store.py | 63 ++++++- code/knowledge/tests/semantic.py | 168 +++++++++++++++++++ code/knowledge/tests/tablefrags.py | 50 ++++-- 7 files changed, 542 insertions(+), 103 deletions(-) create mode 100644 code/knowledge/embeddings.py create mode 100644 code/knowledge/tests/semantic.py diff --git a/code/floop/llm.py b/code/floop/llm.py index cf0f573..8e5a35c 100644 --- a/code/floop/llm.py +++ b/code/floop/llm.py @@ -169,6 +169,7 @@ _STAGE_BY_MODULE = { "SelectTableSignature": "SELECT_TABLE", "VerifyCountSignature": "VERIFY_COUNT", "SkimPromoteSignature": "PROMOTE", + "SkimTableSignature": "SKIM_TABLE", } diff --git a/code/knowledge/embeddings.py b/code/knowledge/embeddings.py new file mode 100644 index 0000000..8fe0c85 --- /dev/null +++ b/code/knowledge/embeddings.py @@ -0,0 +1,54 @@ +"""Embedding client for semantic KG retrieval (research/semantic-kg). + +Config: local ollama /api/embed (nomic-embed-text, 768d) — the only +proven endpoint (ollama.com has NO embeddings API: 404 on /v1/embeddings, +401 on /api/embed). Failure is honest: embed() raises EmbedderDown, the +expert degrades to the lexical probe (law: offline fallback, never a +dead run). No API keys in code. +""" +from __future__ import annotations + +import json +import urllib.request +from pathlib import Path + +DEFAULT_MODEL = "nomic-embed-text:latest" +DEFAULT_URL = "http://127.0.0.1:11435/api/embed" + + +class EmbedderDown(Exception): + """The embedding endpoint is unreachable or misbehaving — the caller + degrades to the lexical probe (offline fallback law).""" + + +def embed(texts: list[str], model: str = DEFAULT_MODEL, + url: str = DEFAULT_URL, timeout: int = 60) -> list[list[float]]: + """Batch-embed texts via ollama /api/embed. Raises EmbedderDown on any + transport/format error — honest failure, never fabricated vectors.""" + texts = [t or " " for t in texts] + if not texts: + return [] + payload = json.dumps({"model": model, "input": texts}).encode() + req = urllib.request.Request( + url, data=payload, headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + data = json.load(r) + except Exception as e: # noqa: BLE001 — one honest exception type + raise EmbedderDown(f"{url}: {e}") from e + vecs = data.get("embeddings") + if not vecs or len(vecs) != len(texts): + raise EmbedderDown(f"{url}: expected {len(texts)} vectors, got " + f"{len(vecs) if vecs else 0}") + return vecs + + +def cosine(a: list[float], b: list[float]) -> float: + """Plain cosine — at hundreds of edges numpy brute force is not worth + the dependency.""" + dot = sum(x * y for x, y in zip(a, b)) + na = sum(x * x for x in a) ** 0.5 + nb = sum(y * y for y in b) ** 0.5 + if na == 0 or nb == 0: + return 0.0 + return dot / (na * nb) \ No newline at end of file diff --git a/code/knowledge/expert.py b/code/knowledge/expert.py index d78cdb6..7f8dd6b 100644 --- a/code/knowledge/expert.py +++ b/code/knowledge/expert.py @@ -1,16 +1,21 @@ """The knowledge expert pipeline: KG-first, gather on gap, containment-checked. Per question (one routed knowledge call): - 1. TRANSLATE: question -> retrieval focus (keywords/entities) [LLM, cheap] - 2. KG PROBE: lexical seed match + BFS depth-1 [engine] - 3. gap? -> SEARCH en.wikipedia (official search) [engine] - 4. FETCH top articles, CHUNK by sections [engine] - 5. EXTRACT per chunk (map) with verbatim spans [LLM] - 6. CHECK: containment in FULL text + well-formedness [engine] - 7. MERGE into the store: corroboration / conflicts / supersession [engine] - 8. ANSWER from KG rows (select + one LLM answer call) [LLM] + 1. TRANSLATE: question -> search queries + resolved entities [LLM, cheap] + 2. KG PROBE: hybrid — lexical seeds UNION semantic rank (embeddings)[engine] + 3. gap? -> SEARCH en.wikipedia (official search) [engine] + 4. FETCH top articles, CHUNK by sections; TABLE SKIM decides which + tables deserve extraction (identity + first rows, BEFORE spend)[LLM, 1/page] + 5. EXTRACT per chunk (map), QUESTION-BLIND (entities only) [LLM] + 6. CHECK: containment in FULL text + well-formedness [engine] + 7. MERGE into the store: corroboration / conflicts / supersession + + vector cache for the semantic probe [engine] + 8. ANSWER from KG rows (select + one LLM answer call) [LLM] -Laws: no quote, no edge; no edge, no answer. Every step logged via RunStreams. +Laws: no quote, no edge; no edge, no answer. The extractor never sees the +question (research/semantic-kg): it transcribes facts about ENTITIES — the +question lives in retrieval (skim/ranking/probe) and the judge only. +Every step logged via RunStreams. """ from __future__ import annotations @@ -25,11 +30,12 @@ from .checks import check_candidate, quote_containment from .chunker import chunk_page from .skim import find_quantities, skim_article from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature, - SkimPromoteSignature, TranslateSignature, - VerifyCountSignature) + SkimPromoteSignature, SkimTableSignature, + TranslateSignature, VerifyCountSignature) +from .embeddings import EmbedderDown, embed from .store import KnowledgeStore, norm_name from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert, - tables_as_chunks, format_table_frag, parse_stop_table) + tables_as_chunks, format_table_frag) WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+") @@ -116,6 +122,12 @@ class KnowledgeConfig: skim_harvest: bool = True # opportunistic typed ingestion, zero LLM skim_harvest_max_tables: int = 2 # per article, beyond the LIST answer skim_link_queue: bool = True # goal-region links join the fetch order + # semantic retrieval (research/semantic-kg) + embed_url: str = "http://127.0.0.1:11435/api/embed" + embed_model: str = "nomic-embed-text:latest" + semantic_tau: float = 0.45 # calibration: rivers 0.49-0.52 in, Pedro + # cross-question 0.35-0.38 out, spouse-noise ~0.67 + max_facts_per_chunk: int = 12 # question-blind extraction needs a cap class KnowledgeExpert: @@ -134,8 +146,13 @@ class KnowledgeExpert: self.select_table = dspy.Predict(SelectTableSignature) self.verify_count = dspy.Predict(VerifyCountSignature) self.skim_promote = dspy.Predict(SkimPromoteSignature) + self.skim_tables = dspy.Predict(SkimTableSignature) self._checked = 0 self._merged = 0 + # semantic probe: cached question vector for this call (the probe + # runs after every ingest; embedding the question twice is waste) + self._qvec_cache: dict[str, list[float]] = {} + self._embed_ok = True # flips False on first EmbedderDown; honest # skim notices accumulated this CALL (PR-3): what the fetched # articles contained beyond the current question's answer self._skim_notices: list[str] = [] @@ -148,6 +165,49 @@ class KnowledgeExpert: if self.streams: self.streams.state(text, think=think) + def _qvec(self, question: str) -> list[float] | None: + """Question vector, cached per question text. None = embedder down + (the probe degrades to lexical — offline fallback law, never dead).""" + if not self._embed_ok: + return None + if question in self._qvec_cache: + return self._qvec_cache[question] + try: + v = embed([question], model=self.cfg.embed_model, + url=self.cfg.embed_url)[0] + self._qvec_cache[question] = v + return v + except EmbedderDown as e: + self._embed_ok = False + self._log(f"semantic probe disabled (embedder down): {e}") + return None + + def _probe(self, question: str, seeds: list[str]) -> list: + """HYBRID probe (research/semantic-kg): lexical seeds UNION semantic + rank. The lexical probe keeps exact-vocabulary recall (Po/flow); + the semantic layer surfaces vocabulary the lexical one cannot see + ('President' vs 'Prime Minister', calibration 0.71). Dedup by edge + id; semantic order fills the tail after lexical hits.""" + rows = self.store.probe(seeds) + qv = self._qvec(question) + if qv is None: + return rows + sem = self.store.semantic_probe(qv, tau=self.cfg.semantic_tau) + if not sem: + return rows + seen = {r.eid for r in rows} + added = 0 + for r in sem: + if r.eid in seen: + continue + seen.add(r.eid) + rows.append(r) + added += 1 + if added: + self._log(f"semantic probe: +{added} edges the lexical probe missed " + f"(tau={self.cfg.semantic_tau})", think=True) + return rows + @staticmethod def _keywords(question: str, k: int = 6) -> list[str]: """Deterministic lexical focus: content words of the question (draft).""" @@ -223,6 +283,9 @@ class KnowledgeExpert: self._skim_notices: list[str] = [] self._skim_leads: list[tuple[WikiPage, object]] = [] ev_entities = [e for e in self._expected_entities(evidence or "")][:8] + # the extractor's ENTITIES (research/semantic-kg): TRANSLATE resolves + # them; keywords of the question are the fallback when it returns none + self._extract_entities: list[str] = [] # SEEN-INDEX (PR-2): articles already fetched this RUN — consulted # before network search so a later question pays zero re-fetch if not hasattr(self, "_seen_pages"): @@ -236,15 +299,14 @@ class KnowledgeExpert: or self._is_enumeration(question)) self._log(f"knowledge: question={question[:80]!r} keywords={kws}", think=True) - # 2. KG probe first: question keywords + entities from the machine's - # context (evidence rows) — 'that state' probes as 'france' + # 2. HYBRID KG probe: lexical seeds UNION semantic rank (embeddings) probe_seeds = list(kws) for line in (evidence or "").splitlines(): if ":" in line: val = line.split(":", 1)[1].split("(answers")[0].strip() if val and len(val.split()) <= 4: probe_seeds.extend(val.split()) - rows = self.store.probe(probe_seeds) + rows = self._probe(question, probe_seeds) self._log(f"kg probe ({probe_seeds}): {len(rows)} rows", think=True) # SET GATE (lists): mention rows never answer an enumeration — only a # membership set does. With no set held, the probe result is not @@ -273,6 +335,12 @@ class KnowledgeExpert: if not queries: queries = [" ".join(kws[:3])] entity_terms = [t.strip() for t in (pred.entities or []) if t.strip()][:4] + # the extractor's entities: TRANSLATE's resolved names + evidence + # entities + (fallback) the question's proper nouns — the + # question-blind extractor transcribes facts about THESE + self._extract_entities = list(dict.fromkeys( + e for e in (entity_terms + ev_entities + + sorted(_proper_nouns(question))) if e)) self._log(f"translate -> queries {queries} entities {entity_terms}", think=True) # search ALL queries first; merge + dedupe candidates; rank GLOBALLY @@ -383,12 +451,12 @@ class KnowledgeExpert: "skim": self._skim_notices}} else: answer = self._answer_from_rows( - question, self.store.probe(probe_seeds), charge_llm) + question, self._probe(question, probe_seeds), charge_llm) if answer["value"] and answer["value"].upper() != "UNKNOWN": self._log(f"early exit after {page.title}: " f"{answer['value'][:60]}", think=True) return {**self._audit_ambiguity(question, answer, - self.store.probe(probe_seeds), + self._probe(question, probe_seeds), charge_llm), "source": "knowledge_graph", "stats": {**self._skim_stats(pages), @@ -397,8 +465,8 @@ class KnowledgeExpert: # 5-7. remaining pages already processed inline via _process_page # (early exit); fall through to the final re-probe and answer. - # 8. re-probe (same seeds) and answer from the merged KG - rows = self.store.probe(probe_seeds) + # 8. re-probe (same seeds, hybrid) and answer from the merged KG + rows = self._probe(question, probe_seeds) self._log(f"merged {self._merged}/{self._checked} candidates; re-probe: {len(rows)} rows", think=True) answer = self._answer_from_rows(question, rows, charge_llm) src = "knowledge_graph" if answer["value"].upper() != "UNKNOWN" else "wikipedia_miss" @@ -909,14 +977,22 @@ class KnowledgeExpert: page. Returns number of candidates merged this page. Counters ACCUMULATE on self. - PR-1: chunks are RANKED by skim signals (question terms + goal terms - + quantity-unit patterns) instead of taking the first N in document - order — the Italy run burned its extract slots on tangential chunks - while the discharge table sat later in the document. A chunk without - ANY signal is skipped for free.""" + research/semantic-kg: the extractor is QUESTION-BLIND — it receives + the ENTITIES (from TRANSLATE + evidence + proper nouns) and + transcribes their facts; ranking/gating still uses the question + (the machine's slots are limited — the best-guess chunks get them). + Tables: SkimTableSignature decides BEFORE extraction which tables + deserve fragments (identity + first rows, one call per page); + fragments of rejected tables are skipped with zero extract spend.""" + entities = self._extract_entities or sorted(_proper_nouns(question)) + ent_str = ", ".join(entities[:8]) or "(none named)" chunks = chunk_page(page.text, target=self.cfg.chunk_chars_target, cap=self.cfg.chunk_chars_cap) - gated = [c for c in chunks if self._gate(c, kws)] + # the gate keeps question terms OR entity mentions — a chunk about + # the entity (but in other vocabulary) is exactly what the semantic + # layer exists for; a chunk about neither is noise for both + gated = [c for c in chunks if self._gate(c, kws) + or any(_term_hits(e, c.text) for e in entities)] if goal_terms: from .store import stem @@ -928,15 +1004,45 @@ class KnowledgeExpert: gated.sort(key=rank, reverse=True) capped = gated[: self.cfg.max_chunks_extracted] - # ---- table fragments: the tables seen in this page, as SMALL - # structured pieces for the extractor — never a 22k-char dump (run G, - # call 8/80). Each fragment repeats the header; the extractor can - # STOP_TABLE a hopeless table after reading its identity. The LIST - # answer's own table never re-enters the extract path. - stopped: set[int] = set() + # ---- TABLE SKIM (research/semantic-kg): decide table relevance + # BEFORE paying extraction — identity + first rows, one call per + # page. The LIST answer's own table never enters; tables that name + # an entity are ALWAYS relevant (never skipped by the LLM's word). list_idx = getattr(page, "_list_table_idx", -1) - table_frags = [f for f in tables_as_chunks(page.wikitext) - if f["table_idx"] != list_idx] + table_frags_all = [f for f in tables_as_chunks(page.wikitext) + if f["table_idx"] != list_idx] + stopped: set[int] = set() + if table_frags_all and page.tables: + # deterministic safety net: a table whose caption/headers/first + # rows NAME an entity is relevant, no LLM call needed + def _names_entity(t) -> bool: + surface = " ".join([t.caption or ""] + list(t.header[:6]) + + [r and " ".join(r[:2]) or "" + for r in t.rows[:3]]) + toks = _tokens(surface) + return any(_prop_hit(e, toks) for e in entities) + + undecided = [t for t in page.tables + if t.idx != list_idx and not _names_entity(t)] + if undecided: + rendered = chr(10).join( + f"{t.idx} | {t.caption or '(no caption)'} | " + f"header: {', '.join(t.header[:6]) or '(none)'} | " + f"rows: {t.total_rows} | first rows: " + + " ;; ".join(" | ".join(r) for r in t.rows[:3] if r) + for t in undecided) + if charge_llm: + charge_llm() + pred = self.skim_tables(question=question, + entities=ent_str, tables=rendered) + for d in (pred.decisions or []): + if not d.relevant: + stopped.add(d.table_index) + self._log(f"table skim: table {d.table_index} " + f"({(d.reason or '')[:50]}) — skipped before " + f"extraction", think=True) + table_frags = [f for f in table_frags_all + if f["table_idx"] not in stopped] frag_slots = max(0, self.cfg.max_chunks_extracted - len(capped)) frag_budget = min(frag_slots, len(table_frags)) @@ -948,22 +1054,10 @@ class KnowledgeExpert: for chunk in capped: if charge_llm: charge_llm() - raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text) - for cand in (raw.facts or []): - self._checked += 1 - cand = {"subject": cand.subject, "relation": cand.relation, - "object": cand.object, "quote": cand.quote} - ok, reason = check_candidate(cand, page.text) - if not ok: - self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}") - continue - doc_id = self.store.add_document( - url=page.url, title=page.title, fetched_at=page.fetched_at, - sha256=hashlib.sha256(page.text.encode()).hexdigest()) - qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at) - self.store.add_edge(cand["subject"], cand["relation"], cand["object"], qid) - self._merged += 1 - extracted += 1 + raw = self.extract(entities=ent_str, heading=chunk.heading_path, + text=chunk.text) + for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]: + extracted += self._ingest_candidate(cand, page, containment=page.text) # ---- table fragments (extract path) ----------------------------- from .store import stem as _stem # containment target: prose + ALL table rows (the fragment's rows @@ -987,34 +1081,51 @@ class KnowledgeExpert: if charge_llm: charge_llm() heading = f"== Tables == (table {frag['table_idx']}, part {frag['part']}/{frag['of']})" - raw = self.extract(question=question, heading=heading, text=text) - if raw.stop_table: - stopped.add(frag["table_idx"]) - self._log(f"extractor STOP_TABLE: table {frag['table_idx']} " - f"({frag['caption'][:40]!r}) not relevant — " - f"skipping {frag['of'] - frag['part']} remaining parts", - think=True) - continue - for cand in (raw.facts or []): - self._checked += 1 - # containment against prose + FULL table text: the fragment is - # rendered from the same rows, so quotes verify honestly - cand = {"subject": cand.subject, "relation": cand.relation, - "object": cand.object, "quote": cand.quote} - ok, reason = check_candidate(cand, containment) - if not ok: - self._log(f"frag candidate rejected ({reason}): " - f"{cand.get('subject', '')[:40]}") - continue - doc_id = self.store.add_document( - url=page.url, title=page.title, fetched_at=page.fetched_at, - sha256=hashlib.sha256(page.text.encode()).hexdigest()) - qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at) - self.store.add_edge(cand["subject"], cand["relation"], cand["object"], qid) - self._merged += 1 - extracted += 1 + raw = self.extract(entities=ent_str, heading=heading, text=text) + for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]: + extracted += self._ingest_candidate(cand, page, containment=containment) return self._merged + def _ingest_candidate(self, cand, page: WikiPage, containment: str) -> int: + """Containment-check one typed Fact, merge it, cache its vector. + Returns 1 when merged, 0 otherwise. Shared by the prose and table- + fragment extract paths (research/semantic-kg).""" + self._checked += 1 + cand = {"subject": cand.subject, "relation": cand.relation, + "object": cand.object, "quote": cand.quote} + ok, reason = check_candidate(cand, containment) + if not ok: + self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}") + return 0 + doc_id = self.store.add_document( + url=page.url, title=page.title, fetched_at=page.fetched_at, + sha256=hashlib.sha256(page.text.encode()).hexdigest()) + qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at) + eid = self.store.add_edge(cand["subject"], cand["relation"], + cand["object"], qid) + self._merged += 1 + if eid is not None: + self._cache_edge_vector(eid, cand["subject"], cand["relation"], + cand["object"]) + return 1 + + def _cache_edge_vector(self, eid: int, subject: str, relation: str, + obj: str) -> None: + """Embed 'subject | relation | object' and cache it for the semantic + probe. Batched lazily: failures flip _embed_ok off (lexical fallback + keeps the run alive); no failure ever blocks an ingest.""" + if not self._embed_ok: + return + text = f"{subject} | {relation} | {obj}" + try: + v = embed([text], model=self.cfg.embed_model, + url=self.cfg.embed_url)[0] + self.store.set_edge_vector(eid, self.cfg.embed_model, + hashlib.sha1(text.encode()).hexdigest(), v) + except EmbedderDown: + self._embed_ok = False + self._log("semantic probe disabled (embedder down at ingest)") + def _gate(self, chunk, keywords: list[str]) -> bool: """Lexical gate with stemming: chunk must mention a question stem.""" from .store import stem diff --git a/code/knowledge/extract.py b/code/knowledge/extract.py index 8d6843c..2dbd052 100644 --- a/code/knowledge/extract.py +++ b/code/knowledge/extract.py @@ -43,21 +43,18 @@ class TranslateSignature(dspy.Signature): class ExtractSignature(dspy.Signature): """You are the EXTRACT step of a knowledge machine. From the given text, - extract the facts that help answer the question. Each fact carries its - verbatim quote: the FULL sentence or table ROW that states the fact, - copied exactly (at least 10 characters). Only facts the text states; - no inference. - If the text is a fragment of a larger TABLE whose caption/headers show - its subject is wrong for the question, set stop_table=True with no facts. - Do NOT stop for text that is merely hard — only when the table's - subject is wrong.""" - question: str = dspy.InputField() + extract facts about the NAMED ENTITIES: biographical facts, positions + and offices held, events, relationships, quantities with their units. + Each fact carries its verbatim quote: the FULL sentence or table ROW + that states it, copied exactly (at least 10 characters). Only facts + the text states; no inference. Extract facts for ALL the named + entities that appear in the text; skip entities not mentioned.""" + entities: str = dspy.InputField( + desc="the named entities to extract facts about, comma separated") heading: str = dspy.InputField(desc="section path of this chunk; context only") text: str = dspy.InputField() facts: list[Fact] = dspy.OutputField( desc="the extracted facts; empty list if none") - stop_table: bool = dspy.OutputField( - desc="True when this table fragment's subject is wrong for the question") class AnswerFromKG(dspy.Signature): @@ -133,6 +130,35 @@ class SkimPromoteSignature(dspy.Signature): desc="one verdict per table in the list") +class TableRelevanceDecision(BaseModel): + """One table's extraction-worthiness verdict (skim-level stop).""" + table_index: int = dspy.OutputField(desc="the table's index from the list") + relevant: bool = dspy.OutputField( + desc="True when this table plausibly holds facts about the entities " + "or their context; False when its subject is clearly different " + "(wrong country, wrong topic, unrelated data)") + reason: str = dspy.OutputField( + desc="short reason, e.g. 'about world rivers, not Italy'") + + +class SkimTableSignature(dspy.Signature): + """You are the TABLE SKIM step of a knowledge machine. For each table + in an article, given its IDENTITY (caption, header columns, row count + — and the FIRST FEW ROWS only), decide whether the table plausibly + holds facts about the named entities or the question's subject. The + goal is to skip hopeless tables BEFORE paying extraction, and to + never skip a table that mentions the entities. Decide per table.""" + question: str = dspy.InputField( + desc="the current question (planning context; the extractor itself " + "never sees it)") + entities: str = dspy.InputField( + desc="the named entities the question is about, comma separated") + tables: str = dspy.InputField( + desc="one block per table: 'idx | caption | header: a, b, c | rows: N | first rows: <3-5 sample rows>'") + decisions: list[TableRelevanceDecision] = dspy.OutputField( + desc="one verdict per table in the list") + + def parse_facts(raw: str) -> list[dict]: """LEGACY pipe parser — kept ONLY for tests that script extractor responses as text. Production code consumes typed `Fact` objects from diff --git a/code/knowledge/store.py b/code/knowledge/store.py index c5c6b25..b689f59 100644 --- a/code/knowledge/store.py +++ b/code/knowledge/store.py @@ -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( diff --git a/code/knowledge/tests/semantic.py b/code/knowledge/tests/semantic.py new file mode 100644 index 0000000..75949d5 --- /dev/null +++ b/code/knowledge/tests/semantic.py @@ -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") \ No newline at end of file diff --git a/code/knowledge/tests/tablefrags.py b/code/knowledge/tests/tablefrags.py index f7112d6..1d91a19 100644 --- a/code/knowledge/tests/tablefrags.py +++ b/code/knowledge/tests/tablefrags.py @@ -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():