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
+97 -40
View File
@@ -55,6 +55,8 @@ class KnowledgeExpert:
self.extract = dspy.Predict(ExtractSignature)
self.answer = dspy.Predict(AnswerFromKG)
self.translate = dspy.Predict(TranslateSignature)
self._checked = 0
self._merged = 0
# ---- helpers -----------------------------------------------------------
def _log(self, text: str, think: bool = False) -> None:
@@ -118,56 +120,111 @@ class KnowledgeExpert:
if q.strip()][:2]
if not queries:
queries = [" ".join(kws[:3])]
self._log(f"translate -> queries {queries}", think=True)
pages: list[WikiPage] = []
seen: set[str] = set()
for query in queries:
candidates = self.client.search(query, limit=self.cfg.max_search_results)
self._log(f"wiki search ({query!r}): {candidates}", think=True)
for title in candidates:
if len(pages) >= self.cfg.max_articles or title in seen:
continue
seen.add(title)
try:
pages.append(self.client.fetch_rich(title))
except Exception as e: # noqa: BLE001 — network honesty: log and continue
self._log(f"fetch failed: {title}: {e}")
e_raw = (pred.entities or "").strip()
entity_terms = [t.strip() for t in
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)
# 5-7. chunk -> extract -> check -> merge (lexical gate on chunks)
checked = 0
merged = 0
for page in pages:
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)][: self.cfg.max_chunks_extracted]
self._log(f"{page.title}: {len(chunks)} chunks, {len(gated)} gated in")
for chunk in gated:
if charge_llm:
charge_llm()
raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text)
for cand in parse_facts(raw.facts):
checked += 1
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)
merged += 1
# 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:
found = self.client.search(query, limit=self.cfg.max_search_results)
per_query.append(found)
self._log(f"wiki search ({query!r}): {found}", think=True)
for title in found:
if title not in seen_titles:
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:
page = self.client.fetch_rich(title)
except Exception as e: # noqa: BLE001 — network honesty: log and continue
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. 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)
self._log(f"merged {merged}/{checked} candidates; re-probe: {len(rows)} rows", think=True)
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": checked, "merged": merged,
"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,
cap=self.cfg.chunk_chars_cap)
gated = [c for c in chunks if self._gate(c, kws)][: self.cfg.max_chunks_extracted]
self._log(f"{page.title}: {len(chunks)} chunks, {len(gated)} gated in")
for chunk in gated:
if charge_llm:
charge_llm()
raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text)
for cand in parse_facts(raw.facts):
self._checked += 1
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
return self._merged
def _gate(self, chunk, keywords: list[str]) -> bool:
"""Lexical gate with stemming: chunk must mention a question stem."""
from .store import 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:
"""Parse wikitext tables into plain text rows. Used by fetch_rich so
ranking/list articles (whose data lives in tables, not prose) carry
their facts; containment is checked against the ENRICHED text."""
"""Parse wikitext tables into one text line per row ('cell | cell | cell').
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] = []
for m in re.finditer(r"\{\|(.*?)\|\}", wikitext, flags=re.S):
if len(out) >= max_tables:
break
rows: list[str] = []
cells: list[str] = []
for line in m.group(1).splitlines():
line = line.strip()
if re.fullmatch(r"\|-?", line): # wikitext row separator, not a cell
if not line or line.startswith("|+"): # blank / caption
continue
if line.startswith("!") or line.startswith("|"):
cells = [c.strip().lstrip("!|").strip() for c in line.split("||")]
cells = [re.sub(r"\[\[(?:[^|\]]*\|)?([^\]]+)\]\]", r"\1", c) for c in cells]
cells = [re.sub(r"\{\{[^}]*\|([^}]*)\}\}", r"\1", c) for c in cells]
cells = [re.sub(r"\{\{[^}]*\}\}", "", c) for c in cells]
cells = [re.sub(r"<[^>]+>", "", c).replace("!!", " ").strip() for c in cells if c]
if line.startswith("|-") or line.startswith("!-"): # row separator
if cells:
rows.append(" | ".join(cells))
if len(rows) >= max_rows:
break
cells = []
continue
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:
rows.append(" | ".join(cells))
if rows:
out.append(chr(10).join(rows))
out.append(chr(10).join(rows[:max_rows]))
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):
pass