merge main (phase 0: K5 fix, --no-cache, import assert) into research/semantic-kg

Conflict resolutions, the honest way:
- extract/expert gap-step: main's deterministic COMPOSE wins over the
  branch's TRANSLATE LLM (main removed it 23/10 with measurement: the
  model was putting the ANSWER into retrieval queries). The branch's
  _extract_entities contract (question-blind extractor) is fed from
  compose's entities.
- tablefrags/semantic tests: restored the branch's adapted versions +
  fixed their single-insert sys.path bug (parent.parent resolved to
  knowledge/, not code/ — the tests were silently importing MAIN's
  expert.py through the venv pth; same class as the run-085457 trap).
This commit is contained in:
2026-10-25 20:04:47 +01:00
20 changed files with 1705 additions and 97 deletions
+63 -43
View File
@@ -1,7 +1,7 @@
"""The knowledge expert pipeline: KG-first, gather on gap, containment-checked.
Per question (one routed knowledge call):
1. TRANSLATE: question -> search queries + resolved entities [LLM, cheap]
1. COMPOSE: question + evidence -> queries/entities (deterministic) [engine]
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
@@ -31,14 +31,54 @@ from .chunker import chunk_page
from .skim import find_quantities, skim_article
from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature,
SkimPromoteSignature, SkimTableSignature,
TranslateSignature, VerifyCountSignature)
VerifyCountSignature)
from .embeddings import EmbedderDown, embed
from .queries import compose_queries, keywords, proper_nouns
from .store import KnowledgeStore, norm_name
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
tables_as_chunks, format_table_frag)
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
# (K5) bug (run 085457, 24-25/10): glm-5.3-flash glues row citations and
# glosses onto the value field (AnswerFromKG says "cite rows by id" but has
# no citation output field, so the model cites in the only field it has).
# Three live shapes, stripped at the judge's output boundary — BEFORE the
# evidence payload and the ablation audit see the value:
# "... (K5)" — row-id citation suffix
# "... (…; cited from rows K16 and K30)" — parenthetical gloss citing rows
# "15 (list of 15 members: …)" — the LIST path's own gloss of a count
# Trailing-only, marker-anchored: "(PSOE)" inside a name, "(since 2018)",
# "(Presidente del Gobierno)" are legitimate and MUST survive. Fixed code
# cleans the model's proposal (LLMs propose, code decides — the audit's
# _carries then finds the support rows and the ambiguity audit can run).
_ROW_CITATION_RE = re.compile(
r"\s*\(\s*(?:row\s+|rows\s+)?K\d+(?:\s*(?:,|and|;)\s*K?\d+)*\s*\)\s*$",
re.IGNORECASE)
_ROW_CITED_GLOSS_RE = re.compile(
r"\s*\([^()]*\bcited from (?:row|rows)\b[^()]*\)\s*$",
re.IGNORECASE)
_LIST_GLOSS_RE = re.compile(
r"\s*\(\s*list of\b[^()]*\)\s*$",
re.IGNORECASE)
def _clean_value(value: str) -> str:
"""Strip trailing citation/gloss parentheticals from a judge value.
The boundary law: only TRAILING shapes with a citation/list marker are
touched; mid-value text and legitimate parentheticals are the model's
own words and stay. Idempotent by construction (a cleaned value ends
clean). UNKNOWN and empty pass through untouched.
"""
v = (value or "").strip()
if not v or v.upper() == "UNKNOWN":
return v
for rx in (_ROW_CITATION_RE, _ROW_CITED_GLOSS_RE, _LIST_GLOSS_RE):
v = rx.sub("", v).rstrip()
return v.strip()
# header/caption terms that name the ENTITY column of a typical scalar table
_ENTITY_COL = ("river", "country", "name", "state", "city", "entity", "member")
@@ -96,16 +136,10 @@ def _prop_hit(prop: str, toks: set[str]) -> bool:
def _proper_nouns(question: str) -> set[str]:
"""Capitalized non-question words: 'Italy', 'Po' — the SUBJECT of the
question. The definitive guard for 'which are the three longest rivers
of Italy?' never accepting a world table (run H: Q1 answered Nile/
Amazon/Yangtze because the top search hit was the world list and the
disjointness guard was vacuous — no evidence, nothing to check)."""
words = re.findall(r"[A-Z][a-zÀ-ÿ]+(?:'[A-Za-z]+)?", question or "")
stops = {"What", "Which", "Who", "When", "Where", "Why", "How", "The",
"Is", "Are", "Was", "Were", "In", "On", "At", "For", "Of",
"Their", "Its", "Those", "These", "That", "This"}
return {w for w in words if w not in stops}
"""The subject guard's noun extractor — delegates to knowledge/queries.py
(single source: the query composer and the guards share the NE law).
Semantics unchanged: capitalized non-question words ('Italy', 'Po')."""
return proper_nouns(question)
@dataclass
@@ -142,7 +176,6 @@ class KnowledgeExpert:
self.streams = streams
self.extract = dspy.Predict(ExtractSignature)
self.answer = dspy.Predict(AnswerFromKG)
self.translate = dspy.Predict(TranslateSignature)
self.select_table = dspy.Predict(SelectTableSignature)
self.verify_count = dspy.Predict(VerifyCountSignature)
self.skim_promote = dspy.Predict(SkimPromoteSignature)
@@ -210,16 +243,10 @@ class KnowledgeExpert:
@staticmethod
def _keywords(question: str, k: int = 6) -> list[str]:
"""Deterministic lexical focus: content words of the question (draft)."""
stops = {"what", "which", "who", "when", "where", "is", "are", "was", "were",
"the", "of", "in", "on", "at", "a", "an", "and", "or", "to", "for",
"does", "do", "did", "by", "its", "it", "that", "this", "most", "second"}
words = [w.lower() for w in WORD_RE.findall(question)]
seen: list[str] = []
for w in words:
if w not in stops and len(w) > 2 and w not in seen:
seen.append(w)
return seen[:k]
"""Deterministic lexical focus — delegates to knowledge/queries.py
(single source: the probe seeds and the query composer share the
same keyword law)."""
return keywords(question, k)
def _set_gate_hit(self, probe_seeds: list[str], question: str) -> str | None:
"""The membership set (if any) this question may be served from.
@@ -271,9 +298,9 @@ class KnowledgeExpert:
question + parent + referenced rows in). References like 'that state'
resolve against them."""
t0 = time.time()
context = (f"Original question: {parent_question}" if parent_question else "")
if evidence:
context += (chr(10) * 2 if context else "") + f"Evidence:\n{evidence}"
# parent_question/evidence ARE the machine's context (design §4) —
# consumed directly by the probe seeds, the query composer and the
# guards; no prompt ever renders them into a TRANSLATE call anymore.
kws = self._keywords(question)
goal_terms = self._keywords(parent_question) if parent_question else []
self._current_goal_terms = goal_terms # the harvest reads these
@@ -325,23 +352,16 @@ class KnowledgeExpert:
return {**self._audit_ambiguity(question, answer, rows, charge_llm),
"source": "knowledge_graph", "kg_rows": len(rows)}
# 3-4. gap -> search + fetch. TRANSLATE (LLM) first: the question becomes
# entity-first Wikipedia queries — deterministic keywords alone surface
# list articles and miss demographics pages.
if charge_llm:
charge_llm()
pred = self.translate(question=question, context=context)
queries = [q.strip() for q in (pred.queries or []) if q.strip()][:2]
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
# 3-4. gap -> search + fetch. COMPOSE (deterministic, from main 23/10 —
# the model's own knowledge of the entities can no longer steer
# retrieval) + the branch's extract-entities contract: the
# question-blind extractor transcribes facts about THESE.
queries, entity_terms = compose_queries(
question, evidence_entities=ev_entities, list_mode=list_mode)
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)
e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
self._log(f"compose -> queries {queries} entities {entity_terms}",
think=True)
# search ALL queries first; merge + dedupe candidates; rank GLOBALLY
# by title relevance; then fetch one at a time with early exit
@@ -1145,7 +1165,7 @@ class KnowledgeExpert:
for i, r in enumerate(rows))
pred = self.answer(question=question, rows=rendered)
return {
"value": pred.value.strip(),
"value": _clean_value(pred.value),
"quote": pred.quote.strip(),
"url": next((r.url for r in rows if r.quote and pred.quote.strip()
and r.quote.strip() in pred.quote.strip()), rows[0].url),