Refactorin KnowledgeExpert.answer_question too long function

This commit is contained in:
2026-10-28 17:27:56 +01:00
parent 12fb3c78b2
commit 77fef0a499
3 changed files with 463 additions and 183 deletions
+16
View File
@@ -78,6 +78,22 @@ tests/state.py unit tests (no LLM)
tests/traces.py exporter tests (no network) tests/traces.py exporter tests (no network)
``` ```
### Knowledge pipeline structure
`KnowledgeExpert.answer_question` in `knowledge/expert.py` orchestrates proof,
stored answers, and article-by-article gathering with early exit. Focused methods
handle stored-answer gating, query composition/search, cached fetching, skimming,
and post-ingestion answer checks. Stateless module-level helpers build probe
seeds, rank article titles, and filter goal-relevant skim notices. Run-wide page
and link caches survive calls; extraction entities, skim notices, and pending
skim leads reset per call after the proof path falls through.
Offline orchestration regression tests (no Wikipedia, embedder, or LLM required):
```bash
.venv/bin/python knowledge/tests/answer_question.py
```
## Viewing a run as traces (Jaeger, 2026-10-27) ## Viewing a run as traces (Jaeger, 2026-10-27)
Every run records `events.jsonl`; `floop/traces.py` replays it as one Every run records `events.jsonl`; `floop/traces.py` replays it as one
+137 -146
View File
@@ -29,7 +29,7 @@ from floop.llm import predict
from .checks import check_candidate, quote_containment from .checks import check_candidate, quote_containment
from .chunker import chunk_page from .chunker import chunk_page
from .skim import find_quantities, skim_article from .skim import SkimSheet, find_quantities, skim_article
from .extract import (AnswerFromKG, ExtractClaims, ExtractSignature, Fact, from .extract import (AnswerFromKG, ExtractClaims, ExtractSignature, Fact,
SelectTableSignature, SkimPromoteSignature, SelectTableSignature, SkimPromoteSignature,
SkimTableSignature, TypeClaim, VerifyCountSignature) SkimTableSignature, TypeClaim, VerifyCountSignature)
@@ -144,6 +144,45 @@ def _proper_nouns(question: str) -> set[str]:
return proper_nouns(question) return proper_nouns(question)
def _probe_seeds(kws: list[str], evidence: str) -> list[str]:
"""Augment keywords with short values from the parent's evidence."""
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:
seeds.extend(val.split())
return seeds
def _rank_article_titles(per_query: list[list[str]],
terms: list[str]) -> list[str]:
"""Keep each query's winner first, then stably rank unique other titles."""
from .store import stem
title_terms = {t for w in terms 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(dict.fromkeys(t for found in per_query for t in found))
winners = list(dict.fromkeys(found[0] for found in per_query if found))
picked = set(winners)
return winners + sorted((t for t in candidates if t not in picked),
key=relevance, reverse=True)
def _goal_skim_notice(sheet: SkimSheet, goal_terms: list[str]) -> str:
"""Keep goal-relevant notices and quantity signals, not unrelated prose."""
notice = sheet.notice()
if notice and (not goal_terms
or any(_term_hits(gt, notice) for gt in goal_terms)
or any(find_quantities(notice))):
return notice
return ""
@dataclass @dataclass
class KnowledgeConfig: class KnowledgeConfig:
kb_path: str = "knowledge_store/kg.sqlite" kb_path: str = "knowledge_store/kg.sqlite"
@@ -455,60 +494,87 @@ class KnowledgeExpert:
`parent_question` + `evidence` are the machine's context: the original `parent_question` + `evidence` are the machine's context: the original
goal and the rows this question depends on (design §4: instantiated goal and the rows this question depends on (design §4: instantiated
question + parent + referenced rows in). References like 'that state' question + parent + referenced rows in). References like 'that state'
resolve against them.""" resolve against them. Orchestrates proof, cached answers, then
article-by-article gathering with early exit."""
t0 = time.time() t0 = time.time()
# 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) kws = self._keywords(question)
goal_terms = self._keywords(parent_question) if parent_question else [] goal_terms = self._keywords(parent_question) if parent_question else []
self._current_goal_terms = goal_terms # the harvest reads these self._current_goal_terms = goal_terms
self._current_goal_question = parent_question or question self._current_goal_question = parent_question or question
# ---- phase 3b: the derived-answer engine, BEFORE any judge ---- proven = self._try_prover_answer(question, charge_llm)
# If the question translates to the DSL and the store closes the
# path, the proof term IS the answer (re-execution = the check,
# verified=True) — the judge never runs on this question. No
# translation or no closed path -> the judge path, unchanged.
try:
proven = self._prover_answer(question, charge_llm)
except Exception as e: # noqa: BLE001 — the prover must never kill a run
self._log(f"prover path failed ({e!r}); judge path", think=True)
proven = None
if proven is not None: if proven is not None:
return proven return proven
# per-CALL skim state (PR-3): notices for the machine + ambiguous
# leads pending the bounded promotion decision self._prepare_gather_state()
self._skim_notices: list[str] = [] ev_entities = self._expected_entities(evidence or "")[:8]
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"):
self._seen_pages: dict[str, WikiPage] = {}
# LINK QUEUE (PR-2): goal-region links from skims, joining the fetch
# order as candidates (hops still live in the plan — the law stands)
if not hasattr(self, "_link_queue"):
self._link_queue: list[str] = []
# LIST activation (moved up: the set gate needs it before the probe)
list_mode = (str(answer_type or "").upper() == "LIST" list_mode = (str(answer_type or "").upper() == "LIST"
or self._is_enumeration(question)) or self._is_enumeration(question))
self._log(f"knowledge: question={question[:80]!r} keywords={kws}", think=True) self._log(f"knowledge: question={question[:80]!r} keywords={kws}", think=True)
probe_seeds = _probe_seeds(kws, evidence)
answer = self._try_stored_answer(question, probe_seeds, list_mode, charge_llm)
if answer is not None:
return answer
# 2. HYBRID KG probe: lexical seeds UNION semantic rank (embeddings) ordered = self._search_articles(question, kws, ev_entities, list_mode)
probe_seeds = list(kws) pages: list[WikiPage] = []
for line in (evidence or "").splitlines(): for title in ordered[: self.cfg.max_articles]:
if ":" in line: page = self._fetch_page(title)
val = line.split(":", 1)[1].split("(answers")[0].strip() if page is None:
if val and len(val.split()) <= 4: continue
probe_seeds.extend(val.split()) pages.append(page)
sheet = self._skim_page(page, kws, goal_terms, ev_entities)
self._harvest_side_tables(page, sheet, question, evidence)
self._promote_leads(evidence, charge_llm)
if list_mode and page.tables:
ans = self._list_from_page(page, question, charge_llm)
if ans is not None and self._guard_ingest(ans, evidence):
self._log(f"early exit after {page.title}: list "
f"({ans['list_count']} items)", think=True)
return {**ans, "source": "knowledge_graph",
"stats": {**self._skim_stats(pages),
"skim": self._skim_notices}}
self._process_page(page, question, kws, charge_llm,
goal_terms=goal_terms)
answer = self._try_gathered_answer(
question, probe_seeds, list_mode, page.title, charge_llm)
if answer is not None:
return {**answer, "source": "knowledge_graph",
"stats": {**self._skim_stats(pages),
"skim": self._skim_notices}}
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"
return {**self._audit_ambiguity(question, answer, rows, charge_llm), "source": src,
"stats": {**self._skim_stats(pages),
"checked": self._checked, "merged": self._merged,
"skim": self._skim_notices,
"elapsed_s": round(time.time() - t0, 1)}}
def _try_prover_answer(self, question: str, charge_llm=None) -> dict | None:
"""A closed proof bypasses the judge; a failed proof must not kill a run."""
try:
return self._prover_answer(question, charge_llm)
except Exception as e: # noqa: BLE001 — the prover must never kill a run
self._log(f"prover path failed ({e!r}); judge path", think=True)
return None
def _prepare_gather_state(self) -> None:
"""Reset per-call extraction/skim state, preserving the run's page cache."""
self._skim_notices = []
self._skim_leads = []
self._extract_entities = []
if not hasattr(self, "_seen_pages"):
self._seen_pages: dict[str, WikiPage] = {}
if not hasattr(self, "_link_queue"):
self._link_queue: list[str] = []
def _try_stored_answer(self, question: str, probe_seeds: list[str],
list_mode: bool, charge_llm=None) -> dict | None:
"""Probe held knowledge, enforcing the membership-set gate for lists."""
rows = self._probe(question, probe_seeds) rows = self._probe(question, probe_seeds)
self._log(f"kg probe ({probe_seeds}): {len(rows)} rows", think=True) 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
# answerability evidence; the gather must run.
if list_mode: if list_mode:
kg_set = self._set_gate_hit(probe_seeds, question) kg_set = self._set_gate_hit(probe_seeds, question)
if kg_set: if kg_set:
@@ -522,11 +588,11 @@ class KnowledgeExpert:
self._log(f"kg hit: {answer['value'][:60]}", think=True) self._log(f"kg hit: {answer['value'][:60]}", think=True)
return {**self._audit_ambiguity(question, answer, rows, charge_llm), return {**self._audit_ambiguity(question, answer, rows, charge_llm),
"source": "knowledge_graph", "kg_rows": len(rows)} "source": "knowledge_graph", "kg_rows": len(rows)}
return None
# 3-4. gap -> search + fetch. COMPOSE (deterministic, from main 23/10 — def _search_articles(self, question: str, kws: list[str],
# the model's own knowledge of the entities can no longer steer ev_entities: list[str], list_mode: bool) -> list[str]:
# retrieval) + the branch's extract-entities contract: the """Compose and search all queries before globally ranking candidates."""
# question-blind extractor transcribes facts about THESE.
queries, entity_terms = compose_queries( queries, entity_terms = compose_queries(
question, evidence_entities=ev_entities, list_mode=list_mode) question, evidence_entities=ev_entities, list_mode=list_mode)
self._rec("fn.done", fn="compose", self._rec("fn.done", fn="compose",
@@ -537,21 +603,6 @@ class KnowledgeExpert:
e for e in (entity_terms + sorted(_proper_nouns(question))) if e)) e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
self._log(f"compose -> queries {queries} entities {entity_terms}", self._log(f"compose -> queries {queries} entities {entity_terms}",
think=True) 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]] = [] per_query: list[list[str]] = []
for query in queries: for query in queries:
found = self.client.search(query, limit=self.cfg.max_search_results) found = self.client.search(query, limit=self.cfg.max_search_results)
@@ -560,48 +611,32 @@ class KnowledgeExpert:
in_={"query": query, "limit": self.cfg.max_search_results}, in_={"query": query, "limit": self.cfg.max_search_results},
out_={"titles": found}) out_={"titles": found})
self._log(f"wiki search ({query!r}): {found}", think=True) self._log(f"wiki search ({query!r}): {found}", think=True)
for title in found: ordered = _rank_article_titles(per_query, entity_terms + kws)
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) self._log(f"fetch order: {ordered[: self.cfg.max_articles]}", think=True)
return ordered
pages: list[WikiPage] = [] def _fetch_page(self, title: str) -> WikiPage | None:
for title in ordered[: self.cfg.max_articles]: """Reuse fetched articles; log network failures and let gathering continue."""
if title in self._seen_pages: if title in self._seen_pages:
page = self._seen_pages[title]
self._rec("fn.done", fn="fetch", in_={"title": title}, self._rec("fn.done", fn="fetch", in_={"title": title},
out_={"cached": True}) out_={"cached": True})
self._log(f"seen-index hit: {title} (already fetched this run)", self._log(f"seen-index hit: {title} (already fetched this run)",
think=True) think=True)
else: return self._seen_pages[title]
try: try:
page = 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 return None
self._seen_pages[title] = page self._seen_pages[title] = page
self._rec("fn.done", fn="fetch", in_={"title": title}, self._rec("fn.done", fn="fetch", in_={"title": title},
out_={"url": page.url, "chars": len(page.text), out_={"url": page.url, "chars": len(page.text),
"tables": len(page.tables)}) "tables": len(page.tables)})
pages.append(page) return page
# SKIM (PR-1): the structural read, in passing — question AND goal
# oriented; surfaces + signals, zero LLM. The sheet drives chunk def _skim_page(self, page: WikiPage, kws: list[str], goal_terms: list[str],
# ranking in _process_page; PR-2's harvest runs on its signals. ev_entities: list[str]) -> SkimSheet:
"""Record structural signals and retain notices/links for later questions."""
sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms, sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms,
evidence_entities=ev_entities) evidence_entities=ev_entities)
self._rec("fn.done", fn="skim", self._rec("fn.done", fn="skim",
@@ -614,77 +649,33 @@ class KnowledgeExpert:
self._log(f"skim {page.title}: {len(sheet.tables)} tables, " self._log(f"skim {page.title}: {len(sheet.tables)} tables, "
f"{len(sheet.infobox_quantities)} infobox quantities, " f"{len(sheet.infobox_quantities)} infobox quantities, "
f"{len(sheet.link_candidates)} link candidates", think=True) f"{len(sheet.link_candidates)} link candidates", think=True)
# PR-3 — the skim notice: goal-relevant surfaces seen in passing, notice = _goal_skim_notice(sheet, goal_terms)
# so later steps (router context, run notes) know what exists
# and where it lives. Filtered to goal signals: the notice is a
# pointer, not a dump.
notice = sheet.notice()
if notice: if notice:
goal_signal = (any(_term_hits(gt, notice) for gt in goal_terms)
or any(find_quantities(notice)))
if goal_signal or not goal_terms:
self._skim_notices.append(notice) self._skim_notices.append(notice)
if self.cfg.skim_link_queue: if self.cfg.skim_link_queue:
for link in sheet.link_candidates: for link in sheet.link_candidates:
if link not in self._link_queue: if link not in self._link_queue:
self._link_queue.append(link) self._link_queue.append(link)
# PR-2 — the opportunistic harvest: goal-relevant side-tables return sheet
# seen in passing become typed edges (zero LLM, containment law)
self._harvest_side_tables(page, sheet, question, evidence) def _try_gathered_answer(self, question: str, probe_seeds: list[str],
# PR-3 — bounded promotion of ambiguous leads (one LLM call, list_mode: bool, page_title: str,
# only when leads exist): promoted tables ingest through the charge_llm=None) -> dict | None:
# same containment-checked path as the deterministic harvest """Stop after an article closes the gap, using the list gate or judge."""
self._promote_leads(evidence, charge_llm)
# LIST path: one SELECT TABLE call per article; on hit, ingest ALL
# rows and answer by aggregation (no extract calls, no gate)
if list_mode and page.tables:
ans = self._list_from_page(page, question, charge_llm)
if ans is not None and self._guard_ingest(ans, evidence):
self._log(f"early exit after {page.title}: list "
f"({ans['list_count']} items)", think=True)
return {**ans, "source": "knowledge_graph",
"stats": {**self._skim_stats(pages),
"skim": self._skim_notices}}
# refused by the guard: wrong article's list — keep gathering
# 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). For enumerations the set gate applies
# here too: mention rows never answer a list question.
self._process_page(page, question, kws, charge_llm,
goal_terms=goal_terms)
if list_mode: if list_mode:
hit = self._set_gate_hit(probe_seeds, question) hit = self._set_gate_hit(probe_seeds, question)
if hit is not None: if hit is not None:
self._log(f"early exit after {page.title}: set {hit}", think=True) self._log(f"early exit after {page_title}: set {hit}", think=True)
return {**self._serve_set(hit, question), "source": "knowledge_graph", return self._serve_set(hit, question)
"stats": {**self._skim_stats(pages),
"skim": self._skim_notices}}
else: else:
answer = self._answer_from_rows( answer = self._answer_from_rows(
question, self._probe(question, probe_seeds), charge_llm) question, self._probe(question, probe_seeds), charge_llm)
if answer["value"] and answer["value"].upper() != "UNKNOWN": if answer["value"] and answer["value"].upper() != "UNKNOWN":
self._log(f"early exit after {page.title}: " self._log(f"early exit after {page_title}: "
f"{answer['value'][:60]}", think=True) f"{answer['value'][:60]}", think=True)
return {**self._audit_ambiguity(question, answer, return self._audit_ambiguity(
self._probe(question, probe_seeds), question, answer, self._probe(question, probe_seeds), charge_llm)
charge_llm), return None
"source": "knowledge_graph",
"stats": {**self._skim_stats(pages),
"skim": self._skim_notices}}
# 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, 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"
return {**self._audit_ambiguity(question, answer, rows, charge_llm), "source": src,
"stats": {**self._skim_stats(pages),
"checked": self._checked, "merged": self._merged,
"skim": self._skim_notices,
"elapsed_s": round(time.time() - t0, 1)}}
def _skim_stats(self, pages: list[WikiPage]) -> dict: def _skim_stats(self, pages: list[WikiPage]) -> dict:
"""stats shared by every return path: pages seen + link queue state.""" """stats shared by every return path: pages seen + link queue state."""
+273
View File
@@ -0,0 +1,273 @@
"""Offline regression tests for knowledge-answer orchestration.
Run: .venv/bin/python knowledge/tests/answer_question.py
"""
from __future__ import annotations
import sys
import unittest
from pathlib import Path
from unittest.mock import Mock, call, patch
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
from knowledge.expert import (KnowledgeConfig, KnowledgeExpert, _goal_skim_notice,
_probe_seeds, _rank_article_titles)
from knowledge.skim import SkimSheet
from knowledge.wiki import WikiPage, WikiTable
QUESTION = "What is the flow of Po?"
UNKNOWN = {"value": "UNKNOWN", "quote": "", "url": ""}
ANSWER = {"value": "1540", "quote": "Po flows", "url": "https://example.org/Po"}
SET_ANSWER = {**ANSWER, "list_items": ["Po"], "list_count": 1}
def page(title: str, tables: bool = False) -> WikiPage:
return WikiPage(
title=title, pageid=1, url=f"https://example.org/{title}",
text="Po flows", fetched_at="2026-10-28",
tables=[WikiTable(idx=1)] if tables else [])
class AnswerQuestionTests(unittest.TestCase):
def setUp(self):
self.expert = KnowledgeExpert.__new__(KnowledgeExpert)
e = self.expert
e.cfg = KnowledgeConfig()
e.client = Mock()
e.client.search.side_effect = [["Po"], ["Italy"]]
e.client.fetch_rich.side_effect = lambda title: page(title)
e._checked, e._merged = 5, 3
e._prover_answer = Mock(return_value=None)
e._probe = Mock(return_value=["row"])
e._answer_from_rows = Mock(return_value=UNKNOWN)
e._audit_ambiguity = Mock(side_effect=lambda _q, ans, _rows, _charge: ans)
e._set_gate_hit = Mock(return_value=None)
e._serve_set = Mock(return_value=SET_ANSWER)
e._list_from_page = Mock(return_value=None)
e._process_page = Mock()
e._harvest_side_tables = Mock()
e._promote_leads = Mock()
e._log = Mock()
e._rec = Mock()
self.compose = self.enterContext(patch(
"knowledge.expert.compose_queries",
return_value=(["query one", "query two"], ["Po"])))
self.skim = self.enterContext(patch(
"knowledge.expert.skim_article",
side_effect=lambda p, **_kw: SkimSheet(title=p.title, url=p.url)))
self.enterContext(patch("knowledge.expert.time.time", side_effect=[10, 12.34]))
def test_prover_returns_before_gather_state_is_reset(self):
e = self.expert
e._skim_notices = ["previous"]
e._prover_answer.return_value = {"value": "proven", "verified": True}
charge = Mock()
result = e.answer_question(QUESTION, parent_question="Italy", charge_llm=charge)
self.assertEqual(result, {"value": "proven", "verified": True})
self.assertEqual(e._skim_notices, ["previous"])
self.assertEqual(e._current_goal_question, "Italy")
e._prover_answer.assert_called_once_with(QUESTION, charge)
e._probe.assert_not_called()
e.client.search.assert_not_called()
def test_scalar_kg_hit_audits_without_search(self):
e = self.expert
e._answer_from_rows.return_value = ANSWER
result = e.answer_question(QUESTION, evidence="E1: Po (answers Q1)")
self.assertEqual(result, {**ANSWER, "source": "knowledge_graph", "kg_rows": 1})
self.assertEqual(e._probe.call_args.args[1][-1], "Po")
e._audit_ambiguity.assert_called_once_with(QUESTION, ANSWER, ["row"], None)
e.client.search.assert_not_called()
def test_list_kg_hit_uses_set_not_scalar_judge(self):
e = self.expert
e._set_gate_hit.return_value = "rivers"
result = e.answer_question(QUESTION, answer_type="list")
self.assertEqual(result, {**SET_ANSWER, "source": "knowledge_graph", "kg_rows": 1})
e._serve_set.assert_called_once_with("rivers", QUESTION)
e._answer_from_rows.assert_not_called()
e.client.search.assert_not_called()
def test_search_deduplicates_and_preserves_query_winners_then_relevance(self):
e = self.expert
e.cfg.max_articles = 5
e.client.search.side_effect = [
["First", "Other", "Po flow", "Po river"],
["Winner", "First", "Other"]]
result = e.answer_question(QUESTION)
self.assertEqual(result["stats"]["pages"],
["First", "Winner", "Po flow", "Other", "Po river"])
self.assertEqual(e.client.search.call_args_list, [
call("query one", limit=4), call("query two", limit=4)])
self.assertEqual(e._extract_entities, ["Po"])
self.assertEqual(e._rec.call_args_list[0], call(
"fn.done", fn="compose",
in_={"question": QUESTION, "evidence_entities": [], "list_mode": False},
out_={"queries": ["query one", "query two"], "entities": ["Po"]}))
def test_scalar_early_exit_skims_harvests_and_processes_before_answering(self):
e = self.expert
e._answer_from_rows.side_effect = [UNKNOWN, ANSWER]
order = Mock()
for name in ("_harvest_side_tables", "_promote_leads", "_process_page",
"_answer_from_rows"):
order.attach_mock(getattr(e, name), name)
charge = Mock()
result = e.answer_question(QUESTION, parent_question="Italy", charge_llm=charge)
self.assertEqual(result, {
**ANSWER, "source": "knowledge_graph",
"stats": {"pages": ["Po"], "link_queue": 0, "skim": []}})
self.assertEqual([c[0] for c in order.mock_calls], [
"_answer_from_rows", "_harvest_side_tables", "_promote_leads",
"_process_page", "_answer_from_rows"])
self.assertEqual(e._probe.call_count, 3)
e._audit_ambiguity.assert_called_once_with(QUESTION, ANSWER, ["row"], charge)
e.client.fetch_rich.assert_called_once_with("Po")
e._process_page.assert_called_once_with(
e._seen_pages["Po"], QUESTION, e._keywords(QUESTION), charge,
goal_terms=e._keywords("Italy"))
e._promote_leads.assert_called_once_with("", charge)
def test_table_list_early_exit_skips_extraction(self):
e = self.expert
e.client.fetch_rich.side_effect = lambda title: page(title, tables=True)
e._list_from_page.return_value = SET_ANSWER
result = e.answer_question(QUESTION, answer_type="LIST")
self.assertEqual(result["list_items"], ["Po"])
self.assertEqual(result["stats"]["pages"], ["Po"])
e._process_page.assert_not_called()
e._answer_from_rows.assert_not_called()
def test_disjoint_table_list_continues_to_next_article(self):
e = self.expert
e.client.fetch_rich.side_effect = lambda title: page(title, tables=True)
e._list_from_page.side_effect = [
{**SET_ANSWER, "list_items": ["Amazon"]}, SET_ANSWER]
result = e.answer_question(
QUESTION, answer_type="LIST", evidence="E1: Po (answers Q1)")
self.assertEqual(result["list_items"], ["Po"])
self.assertEqual(result["stats"]["pages"], ["Po", "Italy"])
self.assertEqual(e._process_page.call_count, 1)
def test_list_set_hit_after_processing(self):
e = self.expert
e._set_gate_hit.side_effect = [None, "rivers"]
result = e.answer_question("Which rivers flow through Italy?")
self.assertEqual(result["list_items"], ["Po"])
self.assertEqual(result["stats"]["pages"], ["Po"])
e._process_page.assert_called_once()
e._answer_from_rows.assert_not_called()
def test_final_reprobe_preserves_stats_and_unknown_source(self):
e = self.expert
result = e.answer_question(QUESTION)
self.assertEqual(result, {
**UNKNOWN, "source": "wikipedia_miss",
"stats": {"pages": ["Po", "Italy"], "link_queue": 0,
"checked": 5, "merged": 3, "skim": [], "elapsed_s": 2.3}})
self.assertEqual(e._probe.call_count, 4)
e._audit_ambiguity.assert_called_once_with(QUESTION, UNKNOWN, ["row"], None)
def test_final_reprobe_can_answer_after_all_articles(self):
e = self.expert
e._answer_from_rows.side_effect = [UNKNOWN, UNKNOWN, UNKNOWN, ANSWER]
result = e.answer_question(QUESTION)
self.assertEqual(result["value"], "1540")
self.assertEqual(result["source"], "knowledge_graph")
self.assertEqual(result["stats"]["merged"], 3)
def test_fetch_failure_is_logged_and_remaining_articles_are_processed(self):
e = self.expert
e.client.fetch_rich.side_effect = [RuntimeError("unavailable"), page("Italy")]
result = e.answer_question(QUESTION)
self.assertEqual(result["stats"]["pages"], ["Italy"])
e._log.assert_any_call("fetch failed: Po: unavailable")
def test_prover_failure_is_logged_and_gather_continues(self):
e = self.expert
e._prover_answer.side_effect = RuntimeError("translation failed")
result = e.answer_question(QUESTION)
self.assertEqual(result["source"], "wikipedia_miss")
e._log.assert_any_call(
"prover path failed (RuntimeError('translation failed')); judge path",
think=True)
def test_search_failure_propagates(self):
self.expert.client.search.side_effect = RuntimeError("search failed")
with self.assertRaisesRegex(RuntimeError, "search failed"):
self.expert.answer_question(QUESTION)
def test_cached_pages_and_link_queue_persist_but_not_notices(self):
e = self.expert
cached = page("Po")
e._seen_pages = {"Po": cached}
e._link_queue = ["Existing"]
e._skim_notices = ["stale"]
e._skim_leads = ["stale"]
self.skim.side_effect = lambda p, **_kw: SkimSheet(
title=p.title, url=p.url, link_candidates=["Existing", "New"])
result = e.answer_question(QUESTION)
self.assertEqual(result["stats"]["link_queue"], 2)
self.assertEqual(e._link_queue, ["Existing", "New"])
self.assertNotIn("stale", result["stats"]["skim"])
self.assertEqual(len(result["stats"]["skim"]), 2)
self.assertEqual(e._skim_leads, [])
e.client.fetch_rich.assert_called_once_with("Italy")
self.assertIs(e._process_page.call_args_list[0].args[0], cached)
e._rec.assert_any_call(
"fn.done", fn="fetch", in_={"title": "Po"}, out_={"cached": True})
def test_skim_notice_filters_goal_terms_but_keeps_quantities(self):
self.skim.side_effect = lambda p, **_kw: SkimSheet(
title=p.title, url=p.url,
infobox_quantities={"flow": "50 m3/s"} if p.title == "Italy" else {},
link_candidates=["Unrelated"])
result = self.expert.answer_question(QUESTION, parent_question="Italy")
self.assertEqual(len(result["stats"]["skim"]), 1)
self.assertTrue(result["stats"]["skim"][0].startswith("Italy:"))
def test_link_queue_can_be_disabled(self):
e = self.expert
e.cfg.skim_link_queue = False
self.skim.side_effect = lambda p, **_kw: SkimSheet(
title=p.title, url=p.url, link_candidates=["New"])
result = e.answer_question(QUESTION)
self.assertEqual(result["stats"]["link_queue"], 0)
class PipelineHelperTests(unittest.TestCase):
def test_probe_seeds_preserve_keywords_and_only_add_short_evidence_values(self):
kws = ["flow"]
evidence = (
"E1: Po (answers Q1)\n"
"E2: New York\n"
"E3: this value has too many words\n"
"E4: \n"
"no value delimiter")
self.assertEqual(_probe_seeds(kws, evidence), ["flow", "Po", "New", "York"])
self.assertEqual(kws, ["flow"])
self.assertEqual(_probe_seeds(kws, ""), kws)
def test_title_ranking_handles_empty_queries_and_duplicate_winners(self):
found = [[], ["Winner", "Other", "Flow rate"], ["Winner", "Flow volume"]]
self.assertEqual(_rank_article_titles(found, ["flow"]),
["Winner", "Flow rate", "Flow volume", "Other"])
self.assertEqual(_rank_article_titles([], ["flow"]), [])
def test_title_ranking_preserves_winners_even_without_relevant_terms(self):
self.assertEqual(_rank_article_titles(
[["Loire", "Other"], ["France", "Other"]], ["France"]),
["Loire", "France", "Other"])
def test_skim_notices_include_goal_matches_and_filter_unrelated_surfaces(self):
sheet = SkimSheet(title="Po", url="u", link_candidates=["River flow"])
self.assertEqual(_goal_skim_notice(sheet, ["flow"]), sheet.notice())
self.assertEqual(_goal_skim_notice(sheet, []), sheet.notice())
self.assertEqual(_goal_skim_notice(sheet, ["population"]), "")
self.assertEqual(_goal_skim_notice(SkimSheet(title="Po", url="u"), []), "")
if __name__ == "__main__":
unittest.main()