"""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] Laws: no quote, no edge; no edge, no answer. Every step logged via RunStreams. """ from __future__ import annotations import hashlib import re import time from dataclasses import dataclass import dspy from .checks import check_candidate, quote_containment from .chunker import chunk_page from .skim import find_quantities, skim_article from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature, SkimPromoteSignature, TranslateSignature, VerifyCountSignature, parse_facts) from .store import KnowledgeStore, norm_name from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert, tables_as_chunks, format_table_frag, parse_stop_table) WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+") @dataclass class KnowledgeConfig: kb_path: str = "knowledge_store/kg.sqlite" max_articles: int = 3 # per knowledge call max_search_results: int = 4 # candidates considered max_chunks_extracted: int = 6 # per call (lexical gate decides which) max_extract_retries: int = 2 chunk_chars_target: int = 32000 chunk_chars_cap: int = 48000 # skim harvest (PR-2): goal-relevant side-tables are ingested in passing 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 class KnowledgeExpert: """The machine's knowledge attendant — replaces stub:knowledge when wired.""" def __init__(self, config: KnowledgeConfig | None = None, store: KnowledgeStore | None = None, client: WikipediaClient | None = None, streams=None): self.cfg = config or KnowledgeConfig() self.store = store or KnowledgeStore(self.cfg.kb_path) self.client = client or WikipediaClient() 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) self._checked = 0 self._merged = 0 # skim notices accumulated this CALL (PR-3): what the fetched # articles contained beyond the current question's answer self._skim_notices: list[str] = [] # ambiguous leads (quantity tables with no goal-vocabulary match) # pending the bounded promotion decision self._skim_leads: list[tuple[WikiPage, WikiTable]] = [] # ---- helpers ----------------------------------------------------------- def _log(self, text: str, think: bool = False) -> None: if self.streams: self.streams.state(text, think=think) @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] def _set_gate_hit(self, probe_seeds: list[str], question: str) -> str | None: """The membership set (if any) this question may be served from. Mention rows never answer enumerations — only a set does. And a set belongs to ITS question: serving Q1's 'countries in Europe' set to 'which are EU members?' would be a confident wrong answer. The match is stem-Jaccard >= 0.5 between the incoming question and the set's ORIGIN question — near-repeats are served, different questions gather.""" from .store import stem q_stems = {stem(w) for w in WORD_RE.findall(question.casefold()) if len(w) > 2} for set_name, origin in self.store.set_origins(): o_stems = {stem(w) for w in WORD_RE.findall(origin.casefold()) if len(w) > 2} if not q_stems or not o_stems: continue jac = len(q_stems & o_stems) / len(q_stems | o_stems) if jac >= 0.5 and self.store.list_members(set_name): return set_name return None def _serve_set(self, set_name: str, question: str) -> dict: """Answer an enumeration from a held membership set: the full member list with provenance, coverage complete per source. Table order is preserved when the ingest recorded ordinals (ranked tables rank).""" ordered = self.store.list_is_ordered(set_name) members = self.store.list_members(set_name, ordered=ordered) quote, url = self.store.set_provenance(set_name) self._log(f"kg set hit: {set_name} ({len(members)} members" f"{', ranked' if ordered else ', unordered'})", think=True) return {"value": str(len(members)), "list_items": members, "list_count": len(members), "quote": quote, "url": url, "confidence": "high", "coverage": {"source": "knowledge_graph", "set": set_name, "rows_ingested": len(members), "rows_total": len(members), "complete_per_source": True, "ranked": ordered}} # ---- the pipeline -------------------------------------------------------- def answer_question(self, question: str, parent_question: str = "", evidence: str = "", charge_llm=None, answer_type: str = "") -> dict: """Returns the answer dict {value, quote, url, source, confidence}. `parent_question` + `evidence` are the machine's context: the original goal and the rows this question depends on (design §4: instantiated 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}" kws = self._keywords(question) goal_terms = self._keywords(parent_question) if parent_question else [] self._current_goal_terms = goal_terms # the harvest reads these self._current_goal_question = parent_question or question # per-CALL skim state (PR-3): notices for the machine + ambiguous # leads pending the bounded promotion decision self._skim_notices: list[str] = [] self._skim_leads: list[tuple[WikiPage, object]] = [] ev_entities = [e for e in self._expected_entities(evidence or "")][:8] # 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" 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' 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) 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: kg_set = self._set_gate_hit(probe_seeds, question) if kg_set: return {**self._serve_set(kg_set, question), "source": "knowledge_graph", "kg_rows": len(rows)} self._log(f"set gate: {len(rows)} mention rows are not answerability " f"for an enumeration; gather runs", think=True) else: answer = self._answer_from_rows(question, rows, charge_llm) if answer["value"] and answer["value"].upper() != "UNKNOWN": self._log(f"kg hit: {answer['value'][:60]}", think=True) return {**answer, "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) q_raw = (pred.queries or "").strip() queries = [q.strip() for q in next((ln.split(":", 1)[1] for ln in q_raw.splitlines() if ln.strip().upper().startswith("QUERIES")), q_raw).split(",") if q.strip()][:2] if not queries: queries = [" ".join(kws[:3])] 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) # 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]: if title in self._seen_pages: page = self._seen_pages[title] self._log(f"seen-index hit: {title} (already fetched this run)", think=True) else: 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 self._seen_pages[title] = page pages.append(page) # SKIM (PR-1): the structural read, in passing — question AND goal # oriented; surfaces + signals, zero LLM. The sheet drives chunk # ranking in _process_page; PR-2's harvest runs on its signals. sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms, evidence_entities=ev_entities) self._log(f"skim {page.title}: {len(sheet.tables)} tables, " f"{len(sheet.infobox_quantities)} infobox quantities, " f"{len(sheet.link_candidates)} link candidates", think=True) # PR-3 — the skim notice: goal-relevant surfaces seen in passing, # 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: goal_signal = (any(gt in notice.casefold() for gt in goal_terms) or any(find_quantities(notice))) if goal_signal or not goal_terms: self._skim_notices.append(notice) if self.cfg.skim_link_queue: for link in sheet.link_candidates: if link not in self._link_queue: self._link_queue.append(link) # PR-2 — the opportunistic harvest: goal-relevant side-tables # seen in passing become typed edges (zero LLM, containment law) self._harvest_side_tables(page, sheet, question, evidence) # PR-3 — bounded promotion of ambiguous leads (one LLM call, # only when leads exist): promoted tables ingest through the # same containment-checked path as the deterministic harvest 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: hit = self._set_gate_hit(probe_seeds, question) if hit is not None: self._log(f"early exit after {page.title}: set {hit}", think=True) return {**self._serve_set(hit, question), "source": "knowledge_graph", "stats": {**self._skim_stats(pages), "skim": self._skim_notices}} else: 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": {**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) 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": {**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: """stats shared by every return path: pages seen + link queue state.""" return {"pages": [p.title for p in pages], "link_queue": len(self._link_queue)} def _expected_entities(self, evidence: str) -> list[str]: """Entities the parent's evidence already names — 'the three longest rivers' means the answer's members must be among them. Extracted deterministically from the rendered evidence lines (E1: value (answers Qx)), from LIST rows' list_items and scalar rows' values. No LLM.""" out: list[str] = [] for line in (evidence or "").splitlines(): if "(answers" not in line: continue val = line.split(":", 1)[1].split("(answers")[0].strip() if not val: continue # LIST rows render 'list of N items: a, b, c...' — members are known m = re.match(r"list of \d+ items: (.+)$", val) if m: out.extend(t.strip() for t in m.group(1).rstrip(".").split(",")) continue # scalar: a single named entity (Po) or a short comma list (Po, Adige, Tiber) if len(val.split()) <= 6 and not val.isdigit(): out.extend(t.strip() for t in val.split(",") if t.strip()) return [e for e in out if e] def _disjoint(self, members: list[str], expected: list[str]) -> bool: """Deterministic overlap check, case-insensitive by prefix-normalized tokens. Disjoint (or near-disjoint) ingest is WRONG for a question about known entities — keep gathering, don't answer from it.""" if not expected or not members: return False en = {norm_name(e) for e in expected} mn = {norm_name(m) for m in members} inter = en & mn # no expected entity appears, or < 1/3 do: wrong article's list return len(inter) * 3 < len(mn) or not inter def _guard_ingest(self, ans: dict, evidence: str) -> bool: """The disjointness guard: refuse a LIST ingest whose members don't overlap the entities the parent's evidence already names. 'Cabal de Po, Adige, Tiber' must never be answered by the Amazon's flow.""" if not (evidence and ans.get("list_items")): return True # nothing to check against — ingest is fine expected = self._expected_entities(evidence) if not expected: return True if self._disjoint(ans["list_items"], expected): self._log( f"guard: ingest of {len(ans['list_items'])} members disjoint from " f"{len(expected)} expected entities — refusing, gather continues", think=True) return False return True def _is_enumeration(self, question: str) -> bool: """Deterministic LIST detection: plural nouns + enumeration ask words. Cheap, logged, and overridable by the planner's explicit answer_type.""" q = question.casefold() words = set(WORD_RE.findall(q)) ask = {"which", "what", "list", "name", "enumerate", "identify"} plurals = [w for w in words if w.endswith("s") and len(w) > 4 and w not in ("states?", "does", "was", "has")] return bool(words & ask) and len(plurals) >= 1 def _verify_count(self, set_name: str, count: int, prose: str, charge_llm) -> dict | None: """Answer-level CHECK: corroborate the list COUNT from article prose that is NOT the source table. Law split: the LLM finds language (one verbatim sentence stating the count); fixed code decides validity — the sentence must be contained in the prose AND state the same count as `count` digits. No LLM ever compares numbers. Returns a verification record or None (no corroborating sentence found — honest, not an error).""" if not prose or count <= 0: return None if charge_llm: charge_llm() pred = self.verify_count(set_name=set_name, count=str(count), text=prose[: self.cfg.chunk_chars_cap]) q = (pred.quote or "").strip() if not q or q.upper() in ("NOQUOTE", "NONE", "N/A"): return None if not quote_containment(q, prose): self._log(f"verify: quote not contained in prose — rejected") return None # deterministic number comparison: the digits the sentence states # must equal the count we computed from the rows nums = {int(n.replace(",", "")) for n in re.findall(r"[\d,]{1,7}", q) if n.replace(",", "").isdigit()} if count in nums: return {"count_corroborated": True, "quote": q} self._log(f"verify: corroborating sentence states {nums}, not {count} " f"— numbers disagree") return None def _list_from_page(self, page: WikiPage, question: str, charge_llm) -> dict | None: """The LIST path: SELECT TABLE (LLM picks table+column from metadata, never the rows) -> ingest ALL rows as membership edges -> aggregate. Returns the list answer dict, or None when no table in this page enumerates the answer (fall through to the extract path).""" rendered = chr(10).join( f"{t.idx} | {t.caption or '(no caption)'} | " f"header: {', '.join(t.header[:6]) or '(none)'} | rows: {t.total_rows}" for t in page.tables) if charge_llm: charge_llm() pred = self.select_table(question=question, tables=rendered) idx_raw = (pred.table_index or "").strip() if not idx_raw or idx_raw.upper() in ("NONE", "N/A", "0"): return None try: idx = int(re.findall(r"\d+", idx_raw)[0]) except (ValueError, IndexError): return None table = next((t for t in page.tables if t.idx == idx), None) if table is None: return None page._list_table_idx = idx # the harvest skips the LIST answer's table column = (pred.column or "").strip() col_i = next((i for i, h in enumerate(table.header) if column.casefold() in h.casefold()), 0) set_name = (pred.set_name or "").strip() or question[:60] origin_question = (pred.origin_question or "").strip() or question # INGEST ALL ROWS: one membership edge per row, quote = the full # stored row line, containment against the stored table text doc_id = self.store.add_document( url=page.url, title=page.title, fetched_at=page.fetched_at, sha256=hashlib.sha256(page.text.encode()).hexdigest()) table_text = chr(10).join(table.text_lines()) members: list[str] = [] ord_counter = 0 for row in table.rows: element = (row[col_i] if col_i < len(row) else (row[0] if row else "")).strip() if not element: continue if " / " in element: element = element.split(" / ")[0].strip() # first of multi-value cell if element.casefold() in ("total", "totals", "sum", "average", "mean"): continue # aggregate footer rows are not members if element.isdigit(): continue # a bare number in the element column is not a member ord_counter += 1 row_line = " | ".join(row) ok, reason = check_candidate( {"subject": element, "relation": "member_of", "object": set_name, "quote": row_line}, table_text) if not ok: self._log(f"list row rejected ({reason}): {element[:40]}") continue qid = self.store.add_quote(doc_id, row_line, page.url, page.fetched_at) self.store.add_edge(element, "member_of", set_name, qid, src_sort="PLACE", dst_node_name=set_name, origin_question=origin_question, list_ord=ord_counter) members.append(element) self._merged += 1 if not members: return None # ORDER-PRESERVING dedup: the table's order IS information (a ranked # table ranks — top-N slices read it). Sorting alphabetically imposed # an order the source never had. items = list(dict.fromkeys(members)) self._log(f"LIST ingest: {len(items)} members of '{set_name}' from " f"table {idx} ({table.total_rows} rows)", think=True) # ANSWER-LEVEL CHECK: corroborate the count from prose OUTSIDE the # table (the extract text is the article prose; tables are separate). # One bounded call; failure = honest 'no corroboration', never a loop. verify = self._verify_count(set_name, len(items), page.text, charge_llm) coverage = {"source": page.title, "table": idx, "rows_total": table.total_rows, "rows_ingested": len(members), "complete_per_source": len(members) == table.total_rows, "ranked": True} # row order = source order; top-N reads it if verify: coverage["count_corroborated"] = True coverage["corroboration_quote"] = verify["quote"] else: coverage["count_corroborated"] = False return { "value": str(len(items)), "list_items": items, "list_count": len(items), "quote": table.rows[0] and " | ".join(table.rows[0]), "url": page.url, "confidence": "high" if verify else "medium", "coverage": coverage, } def _ingest_scalar_table(self, page: WikiPage, t, ent_i: int, val_i: int) -> int: """Shared row ingestion for the skim paths (harvest + promote): every row becomes a scalar edge — subject = entity cell, relation = value-column header, object = value + UNIT (the unit lives in the caption), quote = the verbatim stored row line, containment against the stored table text. Zero LLM; the verbatim law is kept.""" cap_q = find_quantities(resolve_convert(t.caption or "")) unit = cap_q[0].split(" ", 1)[1] if cap_q else "" doc_id = self.store.add_document( url=page.url, title=page.title, fetched_at=page.fetched_at, sha256=hashlib.sha256(page.text.encode()).hexdigest()) table_text = chr(10).join(t.text_lines()) rel = t.header[val_i] if val_i < len(t.header) else "value" merged = 0 for row in t.rows: subj = (row[ent_i] if ent_i < len(row) else "").strip() obj = (row[val_i] if val_i < len(row) else "").strip() if not subj or not obj or subj.casefold() in ( "total", "totals", "sum", "average", "mean") or subj.isdigit(): continue if " / " in subj: subj = subj.split(" / ")[0].strip() if unit and re.fullmatch(r"[\d,.]+", obj): obj = f"{obj} {unit}" # quantities carry values AND units row_line = " | ".join(row) ok, reason = check_candidate( {"subject": subj, "relation": rel, "object": obj, "quote": row_line}, table_text) if not ok: self._log(f"harvest row rejected ({reason}): {subj[:40]}") continue qid = self.store.add_quote(doc_id, row_line, page.url, page.fetched_at) self.store.add_edge(subj, rel, obj, qid) self._merged += 1 merged += 1 if merged: self._log(f"skim ingest: {merged} rows of table {t.idx} " f"({page.title}) as '{rel}' edges", think=True) return merged def _entity_overlap_count(self, t, ent_i: int, expected: list[str]) -> \ tuple[int, int]: """(overlap, members) — how many of the table's entity-column members the parent's evidence names, and how many members there are.""" members = [(r[ent_i] if ent_i < len(r) else "").strip() for r in t.rows] members = [m.split(" / ")[0].strip() for m in members if m] if not expected: return 0, len(members) en = {norm_name(e) for e in expected} return sum(1 for m in members if norm_name(m) in en), len(members) def _harvest_side_tables(self, page: WikiPage, sheet, question: str, evidence: str) -> int: """PR-2 — the opportunistic harvest: goal-relevant tables seen in passing are ingested as typed rows, zero LLM (KNOWLEDGE.md §7). A table is harvested when its caption/header carries a GOAL term AND its entity column overlaps the entities the parent's evidence names (the disjointness guard inverted: overlap = about our entities) — the Italy case: table 2 'Flow at the mouth' while the question asked for lengths. Rows become scalar edges via _ingest_scalar_table (verbatim quote, containment, unit from the caption). Deterministic detection; quantity tables with no goal-vocabulary match are queued as leads for PR-3's bounded promotion, never guessed here.""" if not self.cfg.skim_harvest: return 0 expected = self._expected_entities(evidence or "") goal_terms = self._current_goal_terms or [] harvested = 0 for t in page.tables: if harvested >= self.cfg.skim_harvest_max_tables: break if t.idx == getattr(page, "_list_table_idx", -1): continue # the table that answered the LIST question goal_hit = any(gt and (gt in (t.caption or "").casefold() or gt in " ".join(t.header).casefold()) for gt in goal_terms) qty_signal = bool(find_quantities( resolve_convert(t.caption or "") + " " + " ".join(t.header[:1]))) if not goal_hit: if qty_signal: # a quantity table we cannot tie to the goal vocabulary: # RECORDED as a lead for the bounded promotion (PR-3), # never ingested on the unit pattern alone — and the # seen-index lets a later question come back for it self._skim_leads.append((page, t)) self._log(f"skim harvest: table {t.idx} of {page.title}: " f"quantity signal without a goal term — queued " f"as lead", think=True) continue # entity column: first column whose header is a name-like column # (River, Country, Name, ...) or column 0; value column: the # header carrying a GOAL term (goal-directed harvest — the # header names the attribute the goal asks for), keyword # fallbacks (flow/discharge/quantity headers) after ent_i = next((i for i, h in enumerate(t.header) if h.casefold() in ("river", "country", "name", "state", "city", "entity", "member")), 0) val_i = next((i for i, h in enumerate(t.header) if i != ent_i and h and any( gt in h.casefold() for gt in goal_terms)), None) if val_i is None: val_i = next((i for i, h in enumerate(t.header) if i != ent_i and (find_quantities(h) or "flow" in h.casefold() or "discharge" in h.casefold())), None) if val_i is None: self._log(f"skim harvest: table {t.idx} of {page.title}: no " f"value column — recorded, not ingested", think=True) continue overlap, nm = self._entity_overlap_count(t, ent_i, expected) if expected and overlap == 0 and nm >= 2: # not about our entities — a world table is not our answer self._log(f"skim harvest: table {t.idx} of {page.title}: " f"{overlap}/{nm} entity overlap — skipped", think=True) continue merged = self._ingest_scalar_table(page, t, ent_i, val_i) if merged: harvested += 1 return harvested def _promote_leads(self, evidence: str, charge_llm) -> int: """PR-3 — the bounded promotion of ambiguous leads: quantity tables with no goal-vocabulary match, decided by ONE LLM call per fetched page that has leads (≤ max_articles per knowledge call, only when leads exist — most pages have none). The call sees the tables' IDENTITY (caption/headers/row count/quantity signals — never the rows). The law split stands: the LLM proposes (which table is about the goal), fixed code disposes — a promoted table still passes the entity-overlap check and ingests through the same containment-checked path as the deterministic harvest. Runs inside the fetch loop, BEFORE the early-exit checks: leads die with the call otherwise (a later question only re-harvests pages its own search surfaces again).""" if not self._skim_leads: return 0 if not self.cfg.skim_harvest: self._skim_leads = [] return 0 expected = self._expected_entities(evidence or "") # group by page; each lead gets a GLOBAL line id (two pages can both # have a 'table 1' — the idx alone would collide in the lookup) leads: list[tuple[WikiPage, object]] = self._skim_leads rendered = [] lookup: dict[int, tuple[WikiPage, object]] = {} for lid, (page, t) in enumerate(leads, start=1): cap = resolve_convert(t.caption or "") or "(no caption)" qtys = find_quantities("\n".join(t.text_lines()))[:3] rendered.append( f"{lid} | {cap} | header: {', '.join(t.header[:6])} | " f"rows: {t.total_rows} | quantities: {', '.join(qtys) or 'none'}") lookup[lid] = (page, t) if not rendered: return 0 if charge_llm: charge_llm() pred = self.skim_promote( goal=self._current_goal_question, entities=", ".join(expected[:8]), tables="\n".join(rendered)) promoted = 0 for line in (pred.decision or "").strip().splitlines(): m = re.match(r"\s*(\d+)\s*:\s*(YES|NO)\s*(.*)$", line.strip(), flags=re.I) if not m: continue idx, verdict, col = int(m.group(1)), m.group(2).upper(), m.group(3).strip() got = lookup.get(idx) if verdict != "YES" or got is None: continue page, t = got ent_i = next((i for i, h in enumerate(t.header) if h.casefold() in ("river", "country", "name", "state", "city", "entity", "member")), 0) val_i = next((i for i, h in enumerate(t.header) if col and col.casefold() in h.casefold()), None) if val_i is None: val_i = next((i for i, h in enumerate(t.header) if i != ent_i and (find_quantities(h) or "flow" in h.casefold() or "discharge" in h.casefold())), None) if val_i is None: continue overlap, nm = self._entity_overlap_count(t, ent_i, expected) if expected and overlap == 0 and nm >= 2: self._log(f"skim promote: table {idx} ({page.title}): LLM said " f"YES but {overlap}/{nm} entity overlap — refused", think=True) continue merged = self._ingest_scalar_table(page, t, ent_i, val_i) if merged: self._log(f"skim promote: {merged} rows of table {idx} " f"({page.title}) ingested (LLM-proposed)", think=True) promoted += 1 self._skim_leads = [] # consumed: bounded, never re-asked return promoted def _process_page(self, page: WikiPage, question: str, kws: list[str], charge_llm, goal_terms: list[str] | None = None) -> int: """Chunk -> gate -> RANK (skim) -> extract -> check -> merge for ONE 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.""" 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)] if goal_terms: from .store import stem def rank(c) -> tuple[int, int]: low = c.text.casefold() sig = sum(1 for t in set(kws + goal_terms) if t and (t in low or stem(t) in low)) return (sig + 2 * len(find_quantities(c.text)), -c.idx) 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() 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] frag_slots = max(0, self.cfg.max_chunks_extracted - len(capped)) frag_budget = min(frag_slots, len(table_frags)) self._log(f"{page.title}: {len(chunks)} chunks, {len(gated)} gated, " f"{len(capped)} extracted (skim-ranked); " f"{len(table_frags)} table frags, {frag_budget} considered", think=True) extracted = 0 for chunk in capped: 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 extracted += 1 # ---- table fragments (extract path) ----------------------------- from .store import stem as _stem # containment target: prose + ALL table rows (the fragment's rows # live in page.tables, not in page.text, since the enrichment left) tables_text = "\n".join("\n".join(t.text_lines()) for t in page.tables) containment = page.text + "\n" + tables_text if tables_text else page.text frag_considered = 0 for frag in table_frags[:frag_budget]: if frag["table_idx"] in stopped: continue text = format_table_frag(frag) low = text.casefold() sig = sum(1 for t in set(kws + goal_terms) if t and (t in low or _stem(t) in low)) qty = len(find_quantities(low)) if sig == 0 and qty == 0: self._log(f"table frag skipped (no signal): " f"table {frag['table_idx']} part {frag['part']}/{frag['of']}") continue frag_considered += 1 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 parse_stop_table(raw.facts): 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 parse_facts(raw.facts): self._checked += 1 # containment against prose + FULL table text: the fragment is # rendered from the same rows, so quotes verify honestly 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 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 if not keywords: return True low = chunk.text.casefold() return any(stem(k) in low or k in low for k in keywords) def _answer_from_rows(self, question: str, rows, charge_llm=None) -> dict: if not rows: return {"value": "UNKNOWN", "quote": "", "url": "", "confidence": "low"} if charge_llm: charge_llm() rendered = "\n".join( f"K{i}: {r.src} | {r.rel} | {r.dst} | quote: {r.quote} | {r.url}" f"{' | CONFLICT' if r.conflict else ''}" for i, r in enumerate(rows)) pred = self.answer(question=question, rows=rendered) return { "value": pred.value.strip(), "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), "confidence": pred.confidence.strip().lower(), }