fix(knowledge): cold-start gather — vertical tables, global rank, early exit

Emili's home run failed where the VPS seemed to work: warm-KG illusion; cold path never validated. Reproduced with a wiped KG. Fixes: (1) tables_as_text parses BOTH wikitext layouts (horizontal pipes and one-cell-per-line with row separators) + _clean_cell drops attrs/links/templates; (2) gather searches all queries, dedupes, ranks globally by title relevance, fetches ONE article at a time with EARLY EXIT when the KG answers; (3) hybrid order keeps each query's top-1 slot guaranteed (title relevance buries entity pages like 'Loire'). Also: NameError from refactor caught by baseline fallback; counters accumulate. Cold E2E verified: France (table quote) -> Loire (early exit, 1 article) in 2hops. RUNLOG Run D.
This commit is contained in:
2026-10-17 10:39:34 +02:00
parent 9094b2aec0
commit 6db05fef48
3 changed files with 162 additions and 53 deletions
+34
View File
@@ -246,3 +246,37 @@ state" resolved to France -> **KG hit: The Loire River (E2)** -> answer cites bo
- dspy 3.4 `dspy.LM(...)` returns a list of AttributeDicts on raw call (`text` key) — - dspy 3.4 `dspy.LM(...)` returns a list of AttributeDicts on raw call (`text` key) —
wrapped in `floop/llm.py:active_lm`. wrapped in `floop/llm.py:active_lm`.
- Tests at this point: 9 state + 5 machine + 3 knowledge = 17/17. - Tests at this point: 9 state + 5 machine + 3 knowledge = 17/17.
---
# Run D — cold-start fixed (2026-10-17)
**Trigger:** Emili's home run failed on the same question that worked on the VPS.
The log was conclusive — and honest: the VPS success had been a warm-KG illusion;
the cold-start path had never been validated end-to-end. Reproduced 1:1 on the VPS
with a wiped KG (same queries, same articles, same UNKNOWN).
Root causes (three, all in the gather):
1. **Vertical wikitext tables unparsed.** 'Demographics of the European Union' holds
the ranking table with ONE CELL PER LINE; the parser assumed horizontal pipes.
The article was fetched, chunked, extracted — and its table was garbage rows.
Fix: `tables_as_text` handles both layouts + cell attributes (`_clean_cell`).
Verified live: `France | 69,112,309 | 15.29% | 638,475 | 15.1% | 107`.
2. **Quota eaten by per-query fetch order.** 'List of EU member states by
population' appeared in search results but never got a slot (quota spent on the
first query's generic articles). Fix: search ALL queries, dedupe, rank globally,
fetch one at a time with **early exit** when the KG starts answering.
3. **Pure title-relevance rank buried entity pages.** 'Loire' shares no word with
'longest river in France' — lexical rank 0. Fix: hybrid order — each query's #1
keeps a guaranteed slot (the engine's own relevance), the rest ranked by title
relevance.
Cold-run result (KG empty at start): Q1 France (table row quote, source-verified)
-> Q2 The Loire (early exit after ONE article) -> final answer cites E1+E2.
Two bugs of my own found during the fix: a NameError from the refactor (caught by
the baseline fallback — the fallback layer earned its keep) and counter resets.
Note for benchmarks: early exit cut Q1 from ~22 to ~3 articles-extracted and Q2 to
1 article; the gather now stops when the graph answers.
+83 -26
View File
@@ -55,6 +55,8 @@ class KnowledgeExpert:
self.extract = dspy.Predict(ExtractSignature) self.extract = dspy.Predict(ExtractSignature)
self.answer = dspy.Predict(AnswerFromKG) self.answer = dspy.Predict(AnswerFromKG)
self.translate = dspy.Predict(TranslateSignature) self.translate = dspy.Predict(TranslateSignature)
self._checked = 0
self._merged = 0
# ---- helpers ----------------------------------------------------------- # ---- helpers -----------------------------------------------------------
def _log(self, text: str, think: bool = False) -> None: def _log(self, text: str, think: bool = False) -> None:
@@ -118,25 +120,89 @@ class KnowledgeExpert:
if q.strip()][:2] if q.strip()][:2]
if not queries: if not queries:
queries = [" ".join(kws[:3])] queries = [" ".join(kws[:3])]
self._log(f"translate -> queries {queries}", think=True) e_raw = (pred.entities or "").strip()
pages: list[WikiPage] = [] entity_terms = [t.strip() for t in
seen: set[str] = set() next((ln.split(":", 1)[1] for ln in e_raw.splitlines()
if ln.strip().upper().startswith("ENTITIES")), e_raw).split(",")
if t.strip()][:4]
self._log(f"translate -> 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
# (per-query quotas let generic articles eat the slots before the
# decisive article from a later query is even considered)
from .store import norm_name, stem
title_terms = {t for w in entity_terms + kws if len(w) > 2
for t in (norm_name(w), stem(w))}
def relevance(title: str) -> int:
tt = norm_name(title)
return sum(1 for t in title_terms if t and t in tt)
candidates: list[str] = []
seen_titles: set[str] = set()
per_query: list[list[str]] = []
for query in queries: for query in queries:
candidates = self.client.search(query, limit=self.cfg.max_search_results) found = self.client.search(query, limit=self.cfg.max_search_results)
self._log(f"wiki search ({query!r}): {candidates}", think=True) per_query.append(found)
for title in candidates: self._log(f"wiki search ({query!r}): {found}", think=True)
if len(pages) >= self.cfg.max_articles or title in seen: for title in found:
continue if title not in seen_titles:
seen.add(title) seen_titles.add(title)
candidates.append(title)
# hybrid order: each query's #1 is guaranteed a slot (the engine's own
# relevance catches entity pages whose title shares no words with the
# question — e.g. 'Loire' for 'longest river in France'); the rest are
# ranked by title relevance (which pulls list articles up when they
# are the right source)
ordered: list[str] = []
picked: set[str] = set()
for found in per_query:
if found and found[0] not in picked:
picked.add(found[0])
ordered.append(found[0])
for title in sorted((t for t in candidates if t not in picked),
key=relevance, reverse=True):
ordered.append(title)
self._log(f"fetch order: {ordered[: self.cfg.max_articles]}", think=True)
pages: list[WikiPage] = []
for title in ordered[: self.cfg.max_articles]:
try: try:
pages.append(self.client.fetch_rich(title)) page = self.client.fetch_rich(title)
except Exception as e: # noqa: BLE001 — network honesty: log and continue except Exception as e: # noqa: BLE001 — network honesty: log and continue
self._log(f"fetch failed: {title}: {e}") self._log(f"fetch failed: {title}: {e}")
continue
pages.append(page)
# EARLY EXIT: one article at a time; if the KG already answers,
# stop spending calls (the gather exists to fill the gap, not to
# hoover every candidate)
self._process_page(page, question, kws, charge_llm)
answer = self._answer_from_rows(
question, self.store.probe(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 {**answer, "source": "knowledge_graph",
"stats": {"pages": [p.title for p in pages]}}
# 5-7. chunk -> extract -> check -> merge (lexical gate on chunks) # 5-7. remaining pages already processed inline via _process_page
checked = 0 # (early exit); fall through to the final re-probe and answer.
merged = 0
for page in pages: # 8. re-probe (same seeds) and answer from the merged KG
rows = self.store.probe(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"
return {**answer, "source": src,
"stats": {"checked": self._checked, "merged": self._merged,
"pages": [p.title for p in pages],
"elapsed_s": round(time.time() - t0, 1)}}
def _process_page(self, page: WikiPage, question: str, kws: list[str],
charge_llm) -> int:
"""Chunk -> gate -> extract -> check -> merge for ONE page. Returns
number of candidates merged this page. Counters ACCUMULATE on self."""
chunks = chunk_page(page.text, target=self.cfg.chunk_chars_target, chunks = chunk_page(page.text, target=self.cfg.chunk_chars_target,
cap=self.cfg.chunk_chars_cap) cap=self.cfg.chunk_chars_cap)
gated = [c for c in chunks if self._gate(c, kws)][: self.cfg.max_chunks_extracted] gated = [c for c in chunks if self._gate(c, kws)][: self.cfg.max_chunks_extracted]
@@ -146,7 +212,7 @@ class KnowledgeExpert:
charge_llm() charge_llm()
raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text) raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text)
for cand in parse_facts(raw.facts): for cand in parse_facts(raw.facts):
checked += 1 self._checked += 1
ok, reason = check_candidate(cand, page.text) ok, reason = check_candidate(cand, page.text)
if not ok: if not ok:
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}") self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
@@ -156,17 +222,8 @@ class KnowledgeExpert:
sha256=hashlib.sha256(page.text.encode()).hexdigest()) sha256=hashlib.sha256(page.text.encode()).hexdigest())
qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at) 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.store.add_edge(cand["subject"], cand["relation"], cand["object"], qid)
merged += 1 self._merged += 1
return self._merged
# 8. re-probe (same seeds) and answer from the merged KG
rows = self.store.probe(probe_seeds)
self._log(f"merged {merged}/{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"
return {**answer, "source": src,
"stats": {"checked": checked, "merged": merged,
"pages": [p.title for p in pages],
"elapsed_s": round(time.time() - t0, 1)}}
def _gate(self, chunk, keywords: list[str]) -> bool: def _gate(self, chunk, keywords: list[str]) -> bool:
"""Lexical gate with stemming: chunk must mention a question stem.""" """Lexical gate with stemming: chunk must mention a question stem."""
+31 -13
View File
@@ -23,33 +23,51 @@ LANG = "en"
def tables_as_text(wikitext: str, max_tables: int = 3, max_rows: int = 40) -> str: def tables_as_text(wikitext: str, max_tables: int = 3, max_rows: int = 40) -> str:
"""Parse wikitext tables into plain text rows. Used by fetch_rich so """Parse wikitext tables into one text line per row ('cell | cell | cell').
ranking/list articles (whose data lives in tables, not prose) carry
their facts; containment is checked against the ENRICHED text.""" Handles BOTH layouts: horizontal rows ('| a || b || c') and vertical cells
(one cell per line, rows separated by '|-'). Cell attributes
('| style=... | value') are dropped; links/templates resolved. Containment
is checked against the ENRICHED page text."""
out: list[str] = [] out: list[str] = []
for m in re.finditer(r"\{\|(.*?)\|\}", wikitext, flags=re.S): for m in re.finditer(r"\{\|(.*?)\|\}", wikitext, flags=re.S):
if len(out) >= max_tables: if len(out) >= max_tables:
break break
rows: list[str] = [] rows: list[str] = []
cells: list[str] = []
for line in m.group(1).splitlines(): for line in m.group(1).splitlines():
line = line.strip() line = line.strip()
if re.fullmatch(r"\|-?", line): # wikitext row separator, not a cell if not line or line.startswith("|+"): # blank / caption
continue continue
if line.startswith("!") or line.startswith("|"): if line.startswith("|-") or line.startswith("!-"): # row separator
cells = [c.strip().lstrip("!|").strip() for c in line.split("||")] if cells:
cells = [re.sub(r"\[\[(?:[^|\]]*\|)?([^\]]+)\]\]", r"\1", c) for c in cells] rows.append(" | ".join(cells))
cells = [re.sub(r"\{\{[^}]*\|([^}]*)\}\}", r"\1", c) for c in cells] cells = []
cells = [re.sub(r"\{\{[^}]*\}\}", "", c) for c in cells] continue
cells = [re.sub(r"<[^>]+>", "", c).replace("!!", " ").strip() for c in cells if c] if line.startswith("|") or line.startswith("!"):
body = line.lstrip("|!")
for cell in re.split(r"\|\||!!", body):
cell = _clean_cell(cell)
if cell:
cells.append(cell)
if cells: if cells:
rows.append(" | ".join(cells)) rows.append(" | ".join(cells))
if len(rows) >= max_rows:
break
if rows: if rows:
out.append(chr(10).join(rows)) out.append(chr(10).join(rows[:max_rows]))
return (chr(10) * 2).join(out) return (chr(10) * 2).join(out)
def _clean_cell(cell: str) -> str:
"""Resolve links ([[a|b]]->b), templates ({{t|arg}}->arg), drop attrs and tags."""
cell = re.sub(r"\[\[(?:[^|\]]*\|)?([^\]]+)\]\]", r"\1", cell)
cell = re.sub(r"\{\{[^}]*\|([^}]*)\}\}", r"\1", cell)
cell = re.sub(r"\{\{[^}]*\}\}", "", cell)
if "|" in cell and "=" in cell.split("|")[0]: # '| attrs | value' -> value
cell = cell.split("|")[-1]
cell = re.sub(r"<[^>]+>", "", cell)
return cell.strip(" '\u201c\u201d")
class WikiError(RuntimeError): class WikiError(RuntimeError):
pass pass