1442 lines
72 KiB
Python
1442 lines
72 KiB
Python
"""The knowledge expert pipeline: KG-first, gather on gap, containment-checked.
|
|
|
|
Per question (one routed knowledge call):
|
|
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
|
|
tables deserve extraction (identity + first rows, BEFORE spend)[LLM, 1/page]
|
|
5. EXTRACT per chunk (map), QUESTION-BLIND (entities only) [LLM]
|
|
6. CHECK: containment in FULL text + well-formedness [engine]
|
|
7. MERGE into the store: corroboration / conflicts / supersession
|
|
+ vector cache for the semantic probe [engine]
|
|
8. ANSWER from KG rows (select + one LLM answer call) [LLM]
|
|
|
|
Laws: no quote, no edge; no edge, no answer. The extractor never sees the
|
|
question (research/semantic-kg): it transcribes facts about ENTITIES — the
|
|
question lives in retrieval (skim/ranking/probe) and the judge only.
|
|
Every step logged via RunStreams.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import re
|
|
import time
|
|
from dataclasses import dataclass
|
|
|
|
import dspy
|
|
from floop.llm import predict
|
|
|
|
from .checks import check_candidate, quote_containment
|
|
from .chunker import chunk_page
|
|
from .skim import SkimSheet, find_quantities, skim_article
|
|
from .extract import (AnswerFromKG, ExtractClaims, ExtractSignature, Fact,
|
|
SelectTableSignature, SkimPromoteSignature,
|
|
SkimTableSignature, TypeClaim, VerifyCountSignature)
|
|
from .embeddings import EmbedderDown, embed
|
|
from .queries import compose_queries, keywords, proper_nouns
|
|
from .store import KnowledgeStore, norm_name
|
|
from .two_pass import claims_from, fact_from_claim
|
|
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")
|
|
|
|
|
|
def _tokens(text: str) -> set[str]:
|
|
"""Casefolded word tokens — the boundary-correct matching base. 'flow'
|
|
must not match 'Outflow' (run H: 227 world rows ingested as 'Outflow'
|
|
edges because a goal term hit a substring)."""
|
|
return {w.casefold() for w in WORD_RE.findall(text or "")}
|
|
|
|
|
|
def _term_hits(term: str, text: str) -> bool:
|
|
"""Goal-term match with word boundaries: the term must appear as a
|
|
WHOLE token (stem tolerated) in the text's tokens."""
|
|
if not term:
|
|
return False
|
|
toks = _tokens(text)
|
|
if term.casefold() in toks:
|
|
return True
|
|
from .store import stem
|
|
return stem(term) in {stem(t) for t in toks if t}
|
|
|
|
|
|
def _col_hits(col: str, header: str) -> bool:
|
|
"""The LLM names a column (possibly multi-word: 'Mean discharge').
|
|
It matches a header when any of its content tokens appears as a whole
|
|
token in the header ('discharge' in 'Average discharge' -> True;
|
|
'Flow at the mouth' vs 'Length (km)' -> False)."""
|
|
if not col:
|
|
return False
|
|
stops = {"the", "at", "of", "in", "a", "an", "and"}
|
|
from .store import stem
|
|
ctoks = {t for t in _tokens(col) if t not in stops and len(t) > 2}
|
|
if not ctoks:
|
|
return False
|
|
htoks = _tokens(header)
|
|
hstems = {stem(t) for t in htoks if t}
|
|
return any(c in htoks or stem(c) in hstems for c in ctoks)
|
|
|
|
|
|
def _prop_hit(prop: str, toks: set[str]) -> bool:
|
|
"""Proper-noun subject match: whole token, stem, or WORD PREFIX —
|
|
'Europe' matches 'European' (the gentilici pattern is everywhere on
|
|
Wikipedia: 'List of European states' answers 'countries in Europe?').
|
|
Prefix >= 4 chars keeps it from matching junk."""
|
|
pl = prop.casefold()
|
|
from .store import stem
|
|
ps = stem(pl)
|
|
for t in toks:
|
|
if t == pl or stem(t) == ps:
|
|
return True
|
|
if len(pl) >= 4 and (t.startswith(pl) or pl.startswith(t) and len(t) >= 4):
|
|
return True
|
|
return False
|
|
|
|
|
|
def _proper_nouns(question: str) -> set[str]:
|
|
"""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)
|
|
|
|
|
|
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
|
|
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
|
|
ambiguity_rounds: int = 3 # ablation rounds per scalar answer (run J)
|
|
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
|
|
# semantic retrieval (research/semantic-kg)
|
|
embed_url: str = "http://127.0.0.1:11435/api/embed"
|
|
embed_model: str = "nomic-embed-text:latest"
|
|
semantic_tau: float = 0.45 # calibration: rivers 0.49-0.52 in, Pedro
|
|
# cross-question 0.35-0.38 out, spouse-noise ~0.67
|
|
max_facts_per_chunk: int = 12 # question-blind extraction needs a cap
|
|
max_claims_per_chunk: int = 6 # DEPRECATED (owner ruling 26/10:
|
|
# completeness beats budget) — no longer
|
|
# read by the two-pass loop; kept only for
|
|
# the table-frags legacy path
|
|
extract_mode: str = "two_pass" # "two_pass" (claims -> typed Facts, short
|
|
# outputs) | "single" (legacy one-call typed
|
|
# array — table frags keep using it)
|
|
|
|
|
|
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 = predict(ExtractSignature)
|
|
self.claims = predict(ExtractClaims)
|
|
self.typeclaim = predict(TypeClaim)
|
|
self.answer = predict(AnswerFromKG)
|
|
self.select_table = predict(SelectTableSignature)
|
|
self.verify_count = predict(VerifyCountSignature)
|
|
self.skim_promote = predict(SkimPromoteSignature)
|
|
self.skim_tables = predict(SkimTableSignature)
|
|
self._checked = 0
|
|
self._merged = 0
|
|
# semantic probe: cached question vector for this call (the probe
|
|
# runs after every ingest; embedding the question twice is waste)
|
|
self._qvec_cache: dict[str, list[float]] = {}
|
|
self._embed_ok = True # flips False on first EmbedderDown; honest
|
|
# 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)
|
|
|
|
def _rec(self, event: str, **fields) -> None:
|
|
"""Flight-recorder event (post-mortem debugging, owner 26/10):
|
|
every component, LLM or not, leaves one JSON line. No streams ->
|
|
silent no-op (the recorder law: observability never breaks a run;
|
|
__new__-built test fakes never define it either)."""
|
|
if getattr(self, "streams", None) is not None:
|
|
try:
|
|
self.streams.recorder.emit(event, **fields)
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
|
|
def _qvec(self, question: str) -> list[float] | None:
|
|
"""Question vector, cached per question text. None = embedder down
|
|
(the probe degrades to lexical — offline fallback law, never dead)."""
|
|
if not self._embed_ok:
|
|
return None
|
|
if question in self._qvec_cache:
|
|
return self._qvec_cache[question]
|
|
try:
|
|
v = embed([question], model=self.cfg.embed_model,
|
|
url=self.cfg.embed_url)[0]
|
|
self._qvec_cache[question] = v
|
|
return v
|
|
except EmbedderDown as e:
|
|
self._embed_ok = False
|
|
self._log(f"semantic probe disabled (embedder down): {e}")
|
|
return None
|
|
|
|
def _probe(self, question: str, seeds: list[str]) -> list:
|
|
"""HYBRID probe (research/semantic-kg): lexical seeds UNION semantic
|
|
rank. The lexical probe keeps exact-vocabulary recall (Po/flow);
|
|
the semantic layer surfaces vocabulary the lexical one cannot see
|
|
('President' vs 'Prime Minister', calibration 0.71). Dedup by edge
|
|
id; semantic order fills the tail after lexical hits."""
|
|
rows = self.store.probe(seeds)
|
|
qv = self._qvec(question)
|
|
if qv is None:
|
|
self._rec("probe.done", q=question[:80], seeds=list(seeds),
|
|
rows=len(rows), semantic=0)
|
|
return rows
|
|
sem = self.store.semantic_probe(qv, tau=self.cfg.semantic_tau)
|
|
if not sem:
|
|
self._rec("probe.done", q=question[:80], seeds=list(seeds),
|
|
rows=len(rows), semantic=0)
|
|
return rows
|
|
seen = {r.eid for r in rows}
|
|
added = 0
|
|
for r in sem:
|
|
if r.eid in seen:
|
|
continue
|
|
seen.add(r.eid)
|
|
rows.append(r)
|
|
added += 1
|
|
if added:
|
|
self._log(f"semantic probe: +{added} edges the lexical probe missed "
|
|
f"(tau={self.cfg.semantic_tau})", think=True)
|
|
self._rec("probe.done", q=question[:80], seeds=list(seeds),
|
|
rows=len(rows), semantic=added,
|
|
tau=self.cfg.semantic_tau)
|
|
return rows
|
|
|
|
@staticmethod
|
|
def _keywords(question: str, k: int = 6) -> list[str]:
|
|
"""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.
|
|
|
|
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._rec("fn.done", fn="serve_set",
|
|
in_={"set": set_name, "question": question},
|
|
out_={"members": members[:50], "count": len(members),
|
|
"ranked": ordered})
|
|
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 _prover_answer(self, question: str, charge_llm=None) -> dict | None:
|
|
"""The derived-answer path (phase 3b): translate -> validate ->
|
|
evaluate -> re-execute. Returns the answer dict with the proof
|
|
term, or None to fall back to the judge.
|
|
|
|
The laws, end to end: the LLM only TRANSLATES (one structured
|
|
call, the store's relation vocabulary in); the term is validated
|
|
BEFORE evaluation (a mistranslation is an invalid term, never a
|
|
wrong answer); the proof's steps name every edge; re-execution
|
|
IS the check (verified=True with a real prover, not a flag);
|
|
multi-binding returns the SET with ambiguous=True — the three
|
|
readings surface as what they are, deterministically.
|
|
"""
|
|
from .prover import evaluate, re_execute, validate_query
|
|
from .translate_dsl import TranslateToDSL
|
|
if not hasattr(self, "translate_dsl"):
|
|
self.translate_dsl = predict(TranslateToDSL)
|
|
rels = [r[0] for r in self.store.db.execute(
|
|
"SELECT DISTINCT rel FROM edges WHERE retracted=0 "
|
|
"ORDER BY rel LIMIT 200").fetchall()]
|
|
if not rels:
|
|
return None
|
|
if charge_llm:
|
|
charge_llm()
|
|
try:
|
|
pred = self.translate_dsl(question=question,
|
|
relations=", ".join(rels))
|
|
except Exception as e: # noqa: BLE001 — translation failure = fallback
|
|
self._log(f"translate-to-DSL failed ({e!r}); judge path", think=True)
|
|
return None
|
|
q = getattr(pred, "query", None)
|
|
if not q:
|
|
return None # the model honestly declined
|
|
ok, reason = validate_query(q)
|
|
if not ok:
|
|
self._log(f"prover: invalid DSL term ({reason}); judge path", think=True)
|
|
self._rec("prover.done", q=question[:80], verdict="invalid_dsl",
|
|
reason=reason, dsl=q)
|
|
return None
|
|
proof = evaluate(self.store, q)
|
|
if not proof.bindings:
|
|
self._log(f"prover: no closed path; judge path", think=True)
|
|
self._rec("prover.done", q=question[:80], verdict="no_closed_path",
|
|
dsl=q)
|
|
return None
|
|
if not re_execute(self.store, q, proof):
|
|
self._log("prover: re-execution mismatch (store changed?); judge path",
|
|
think=True)
|
|
self._rec("prover.done", q=question[:80],
|
|
verdict="reexecution_mismatch", dsl=q)
|
|
return None
|
|
vals = []
|
|
quote = ""
|
|
url = ""
|
|
for b in proof.bindings:
|
|
v = next((bv["value"] for k, bv in b.items()
|
|
if isinstance(bv, dict) and bv.get("value")), None)
|
|
if v:
|
|
vals.append(v)
|
|
if not quote:
|
|
eid = next((bv["eid"] for k, bv in b.items()
|
|
if isinstance(bv, dict) and bv.get("eid")), None)
|
|
if eid:
|
|
row = self.store.db.execute(
|
|
"SELECT q.verbatim, q.url FROM quotes q "
|
|
"JOIN edges e ON e.quote_id=q.id WHERE e.id=?",
|
|
(eid,)).fetchone()
|
|
if row:
|
|
quote, url = row
|
|
n = len(vals)
|
|
if n == 1:
|
|
answer = {"value": vals[0], "quote": quote, "url": url,
|
|
"source": "derived_proof", "confidence": "high",
|
|
"verified": True, "proof": proof}
|
|
else:
|
|
answer = {"value": "; ".join(vals), "quote": quote, "url": url,
|
|
"source": "derived_proof", "confidence": "high",
|
|
"verified": True, "proof": proof,
|
|
"ambiguous": True,
|
|
"axis": f"which reading of '{question[:60]}'?",
|
|
"alternatives": [{"value": v, "quote": quote, "url": url}
|
|
for v in vals]}
|
|
self._log(f"prover: closed path ({n} binding(s): "
|
|
f"{'; '.join(v[:40] for v in vals[:3])}) — no judge call",
|
|
think=True)
|
|
self._rec("prover.done", q=question[:80],
|
|
verdict="closed" if n == 1 else "ambiguous",
|
|
dsl=q, n_bindings=n, bindings=[v[:80] for v in vals])
|
|
return answer
|
|
|
|
def kg_snapshot(self) -> dict:
|
|
"""The KG as a JSON-safe object for the flight recorder: every
|
|
live edge with its temporal window and its LAST-TOUCH event (owner
|
|
26/10: 'cada fila del kg podria tenir anotat quan s'afegeix o
|
|
edita'). The last-touch map comes from this run's merge events
|
|
(in the recorder's memory); rows the run never touched carry the
|
|
empty marker. One snapshot per run — emitted once at the end."""
|
|
try:
|
|
last_touch: dict[int, dict] = {}
|
|
rec = (self.streams.recorder if self.streams else None)
|
|
if rec is not None:
|
|
for e in rec.events_of("fact.merged"):
|
|
if e.get("eid") is not None:
|
|
last_touch[e["eid"]] = {"seq": e.get("seq"),
|
|
"ts": e.get("ts"),
|
|
"page": e.get("page")}
|
|
edges = []
|
|
for (eid, subj, rel, dstv, s, en, red) in self.store.db.execute(
|
|
"SELECT e.id, n.norm_name, e.rel, e.dst_value, "
|
|
"e.t_start, e.t_end, e.retracted "
|
|
"FROM edges e JOIN nodes n ON n.id=e.src_node "
|
|
"ORDER BY e.id").fetchall():
|
|
edges.append({
|
|
"eid": eid, "subject": subj, "rel": rel,
|
|
"object": dstv, "t_start": s, "t_end": en,
|
|
"retracted": bool(red),
|
|
"last_touch": last_touch.get(eid),
|
|
})
|
|
conflicts = self.store.db.execute(
|
|
"SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
|
return {"n_edges": len(edges),
|
|
"n_live": sum(1 for e in edges if not e["retracted"]),
|
|
"n_conflicts": conflicts, "edges": edges}
|
|
except Exception: # noqa: BLE001 — a snapshot must never kill a run
|
|
return {"n_edges": 0, "n_live": 0, "n_conflicts": 0, "edges": []}
|
|
|
|
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. Orchestrates proof, cached answers, then
|
|
article-by-article gathering with early exit."""
|
|
t0 = time.time()
|
|
kws = self._keywords(question)
|
|
goal_terms = self._keywords(parent_question) if parent_question else []
|
|
self._current_goal_terms = goal_terms
|
|
self._current_goal_question = parent_question or question
|
|
proven = self._try_prover_answer(question, charge_llm)
|
|
if proven is not None:
|
|
return proven
|
|
|
|
self._prepare_gather_state()
|
|
ev_entities = self._expected_entities(evidence or "")[:8]
|
|
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)
|
|
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
|
|
|
|
ordered = self._search_articles(question, kws, ev_entities, list_mode)
|
|
pages: list[WikiPage] = []
|
|
for title in ordered[: self.cfg.max_articles]:
|
|
page = self._fetch_page(title)
|
|
if page is None:
|
|
continue
|
|
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)
|
|
self._log(f"kg probe ({probe_seeds}): {len(rows)} rows", think=True)
|
|
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 {**self._audit_ambiguity(question, answer, rows, charge_llm),
|
|
"source": "knowledge_graph", "kg_rows": len(rows)}
|
|
return None
|
|
|
|
def _search_articles(self, question: str, kws: list[str],
|
|
ev_entities: list[str], list_mode: bool) -> list[str]:
|
|
"""Compose and search all queries before globally ranking candidates."""
|
|
queries, entity_terms = compose_queries(
|
|
question, evidence_entities=ev_entities, list_mode=list_mode)
|
|
self._rec("fn.done", fn="compose",
|
|
in_={"question": question, "evidence_entities": ev_entities,
|
|
"list_mode": list_mode},
|
|
out_={"queries": queries, "entities": entity_terms})
|
|
self._extract_entities = list(dict.fromkeys(
|
|
e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
|
|
self._log(f"compose -> queries {queries} entities {entity_terms}",
|
|
think=True)
|
|
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._rec("fn.done", fn="search",
|
|
in_={"query": query, "limit": self.cfg.max_search_results},
|
|
out_={"titles": found})
|
|
self._log(f"wiki search ({query!r}): {found}", think=True)
|
|
ordered = _rank_article_titles(per_query, entity_terms + kws)
|
|
self._log(f"fetch order: {ordered[: self.cfg.max_articles]}", think=True)
|
|
return ordered
|
|
|
|
def _fetch_page(self, title: str) -> WikiPage | None:
|
|
"""Reuse fetched articles; log network failures and let gathering continue."""
|
|
if title in self._seen_pages:
|
|
self._rec("fn.done", fn="fetch", in_={"title": title},
|
|
out_={"cached": True})
|
|
self._log(f"seen-index hit: {title} (already fetched this run)",
|
|
think=True)
|
|
return self._seen_pages[title]
|
|
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}")
|
|
return None
|
|
self._seen_pages[title] = page
|
|
self._rec("fn.done", fn="fetch", in_={"title": title},
|
|
out_={"url": page.url, "chars": len(page.text),
|
|
"tables": len(page.tables)})
|
|
return page
|
|
|
|
def _skim_page(self, page: WikiPage, kws: list[str], goal_terms: list[str],
|
|
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,
|
|
evidence_entities=ev_entities)
|
|
self._rec("fn.done", fn="skim",
|
|
in_={"title": page.title, "question_terms": kws,
|
|
"goal_terms": goal_terms},
|
|
out_={"tables": len(sheet.tables),
|
|
"infobox_quantities": len(sheet.infobox_quantities),
|
|
"link_candidates": len(sheet.link_candidates),
|
|
"notice": sheet.notice()[:200]})
|
|
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)
|
|
notice = _goal_skim_notice(sheet, goal_terms)
|
|
if notice:
|
|
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)
|
|
return sheet
|
|
|
|
def _try_gathered_answer(self, question: str, probe_seeds: list[str],
|
|
list_mode: bool, page_title: str,
|
|
charge_llm=None) -> dict | None:
|
|
"""Stop after an article closes the gap, using the list gate or judge."""
|
|
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)
|
|
else:
|
|
answer = self._answer_from_rows(
|
|
question, self._probe(question, 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 self._audit_ambiguity(
|
|
question, answer, self._probe(question, probe_seeds), charge_llm)
|
|
return None
|
|
|
|
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 _audit_ambiguity(self, question: str, answer: dict, rows,
|
|
charge_llm=None) -> dict:
|
|
"""Ablation ambiguity detector (KNOWLEDGE.md §8, run J).
|
|
|
|
The KG just answered with value V from some support row(s). Ask the
|
|
SAME judge (AnswerFromKG) whether the question ALSO answers without
|
|
that support: mask the rows whose object/relation produced V, re-ask.
|
|
A DIFFERENT surviving value = a second defensible reading -> flag.
|
|
Repeat (bounded) until the rows run out of answers. Same-value
|
|
survivors are corroboration, not ambiguity — silent.
|
|
|
|
Zero new prompts: same AnswerFromKG signature, one call per round.
|
|
The store is NEVER mutated — the mask is a view, deletion happens
|
|
nowhere. Ordinary questions end at round 1 with UNKNOWN (silent).
|
|
"""
|
|
value = str(answer.get("value", "")).strip()
|
|
if (not value or value.upper() == "UNKNOWN" or not rows):
|
|
return answer
|
|
|
|
# The supporting rows for the PICKED value. DST-FIRST LAW (run L):
|
|
# when a row has a meaningful dst it is the VALUE BEARER — quotes
|
|
# interleave readings in one paragraph ('... Secretary-General ...
|
|
# president of Socialist International ...' is ONE quote), so
|
|
# quote-matching over-masks and the audit dies silent at round 1.
|
|
# The quote is a fallback ONLY for rows whose dst is empty/numeric.
|
|
_NUMERIC_RE = re.compile(r"^[\d\s.,:+\-/–—%]+$")
|
|
|
|
def _dst(r) -> str:
|
|
return (getattr(r, "dst", "") or "").strip()
|
|
|
|
def _dst_meaningful(r) -> bool:
|
|
d = _dst(r)
|
|
return bool(d) and not _NUMERIC_RE.match(d)
|
|
|
|
def _carries(r) -> bool:
|
|
v = value.casefold()
|
|
if _dst_meaningful(r):
|
|
return v in _dst(r).casefold()
|
|
quote = (getattr(r, "quote", "") or "").strip().casefold()
|
|
return v in quote
|
|
|
|
def _carries_target(r, val: str) -> bool:
|
|
"""DST-FIRST law, parameterized for a round's surviving value.
|
|
|
|
The judge's value may be an OFFICE DESCRIPTION, not the dst
|
|
entity itself ('prime minister of Spain' vs dst='Spain') —
|
|
resolve the row by reciprocal token containment: the dst
|
|
names the entity, the value describes the reading; overlap
|
|
means this row carried it."""
|
|
v = val.casefold()
|
|
if _dst_meaningful(r):
|
|
d = _dst(r).casefold()
|
|
if v == d or v in d or d in v:
|
|
return True
|
|
vt = set(WORD_RE.findall(v))
|
|
dt = set(WORD_RE.findall(d))
|
|
return bool(vt & dt) if vt and dt else False
|
|
quote = (getattr(r, "quote", "") or "").strip().casefold()
|
|
return v in quote
|
|
|
|
support = [r for r in rows if _carries(r)]
|
|
if not support:
|
|
return answer # the judge invented it: nothing to ablate
|
|
|
|
alternatives: list[dict] = []
|
|
seen = {norm_name(value)}
|
|
masked = set(id(r) for r in support)
|
|
|
|
for _ in range(self.cfg.ambiguity_rounds):
|
|
view = [r for r in rows if id(r) not in masked]
|
|
if not view:
|
|
break
|
|
re_ans = self._answer_from_rows(question, view, charge_llm)
|
|
re_val = str(re_ans.get("value", "")).strip()
|
|
if not re_val or re_val.upper() == "UNKNOWN":
|
|
break # the KG has no other reading: clean
|
|
key = norm_name(re_val)
|
|
if key in seen:
|
|
break # same value again: corroboration, not ambiguity
|
|
seen.add(key)
|
|
# which surviving row produced this reading? DST-FIRST here too
|
|
# — same law as the pick's mask, for the report and the next mask
|
|
src_row = next((r for r in view if _carries_target(r, re_val)), None)
|
|
alternatives.append({
|
|
"value": re_val,
|
|
"quote": re_ans.get("quote", ""),
|
|
"url": (src_row.url if src_row is not None
|
|
else re_ans.get("url", "")),
|
|
})
|
|
# mask this reading's own support too — next round hunts a third
|
|
new_support = [r for r in view if _carries_target(r, re_val)]
|
|
if not new_support:
|
|
break
|
|
masked |= set(id(r) for r in new_support)
|
|
|
|
if not alternatives:
|
|
return answer # ordinary question: byte-identical
|
|
self._log(f"ambiguity audit: {len(alternatives)} other reading(s) "
|
|
f"({'; '.join(a['value'][:40] for a in alternatives[:3])}) "
|
|
f"— flagging, not choosing", think=True)
|
|
return {**answer, "ambiguous": True,
|
|
"axis": f"which {question.strip().rstrip('?')}?",
|
|
"alternatives": alternatives}
|
|
|
|
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)."""
|
|
# SUBJECT GUARD (run H): proper nouns of the question ('Italy') must
|
|
# appear in the article title OR the tables' captions/headers — a
|
|
# world list must never answer a question about one country. With no
|
|
# evidence yet (first hop), the disjointness guard is vacuous; THIS
|
|
# is the guard that fired instead of it.
|
|
props = _proper_nouns(question)
|
|
if props:
|
|
surface = " ".join([page.title]
|
|
+ [t.caption or "" for t in page.tables]
|
|
+ [" ".join(t.header) for t in page.tables])
|
|
toks = _tokens(surface)
|
|
if not any(_prop_hit(p, toks) for p in props):
|
|
self._log(f"subject guard: {page.title} names none of "
|
|
f"{sorted(props)} — refusing LIST from this article",
|
|
think=True)
|
|
return None
|
|
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)
|
|
chosen = pred.chosen
|
|
if chosen is None:
|
|
return None
|
|
idx = chosen.table_index
|
|
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 = chosen.column.strip()
|
|
col_i = next((i for i, h in enumerate(table.header)
|
|
if column.casefold() in h.casefold()), 0)
|
|
set_name = chosen.set_name.strip() or question[:60]
|
|
origin_question = 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)
|
|
self._rec("fn.done", fn="list_ingest",
|
|
in_={"title": page.title, "table": idx, "set": set_name,
|
|
"rows": table.total_rows},
|
|
out_={"members": items[:50], "count": len(items),
|
|
"verified": bool(verify)})
|
|
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
|
|
# WORD BOUNDARIES (run H: 'flow' matched 'Outflow' by substring
|
|
# and 227 world rows entered the KG as 'Outflow' edges)
|
|
goal_hit = any(
|
|
_term_hits(gt, (t.caption or "") + " " + " ".join(t.header))
|
|
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 _ENTITY_COL), 0)
|
|
val_i = next((i for i, h in enumerate(t.header)
|
|
if i != ent_i and h and any(
|
|
_term_hits(gt, h) for gt in goal_terms)), 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
|
|
self._rec("fn.done", fn="harvest",
|
|
in_={"title": page.title, "table": t.idx,
|
|
"column": t.header[val_i] if val_i < len(t.header) else "value"},
|
|
out_={"merged": merged})
|
|
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 d in (pred.decisions or []):
|
|
got = lookup.get(d.table_index)
|
|
if not d.promote or got is None:
|
|
continue
|
|
page, t = got
|
|
col = (d.column or "").strip()
|
|
ent_i = next((i for i, h in enumerate(t.header)
|
|
if h.casefold() in _ENTITY_COL), 0)
|
|
val_i = next((i for i, h in enumerate(t.header)
|
|
if col and _col_hits(col, h)), 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 {d.table_index} ({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._rec("fn.done", fn="promote",
|
|
in_={"title": page.title, "table": d.table_index,
|
|
"column": col},
|
|
out_={"merged": merged, "refused": False})
|
|
self._log(f"skim promote: {merged} rows of table {d.table_index} "
|
|
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.
|
|
|
|
research/semantic-kg: the extractor is QUESTION-BLIND — it receives
|
|
the ENTITIES (from TRANSLATE + evidence + proper nouns) and
|
|
transcribes their facts; ranking/gating still uses the question
|
|
(the machine's slots are limited — the best-guess chunks get them).
|
|
Tables: SkimTableSignature decides BEFORE extraction which tables
|
|
deserve fragments (identity + first rows, one call per page);
|
|
fragments of rejected tables are skipped with zero extract spend."""
|
|
entities = self._extract_entities or sorted(_proper_nouns(question))
|
|
ent_str = ", ".join(entities[:8]) or "(none named)"
|
|
chunks = chunk_page(page.text, target=self.cfg.chunk_chars_target,
|
|
cap=self.cfg.chunk_chars_cap)
|
|
# the gate keeps question terms OR entity mentions — a chunk about
|
|
# the entity (but in other vocabulary) is exactly what the semantic
|
|
# layer exists for; a chunk about neither is noise for both
|
|
gated = [c for c in chunks if self._gate(c, kws)
|
|
or any(_term_hits(e, c.text) for e in entities)]
|
|
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]
|
|
self._rec("fn.done", fn="chunk_gate",
|
|
in_={"title": page.title, "chunks": len(chunks),
|
|
"question_terms": kws, "entities": entities},
|
|
out_={"gated": len(gated), "extracted": len(capped)})
|
|
|
|
# ---- TABLE SKIM (research/semantic-kg): decide table relevance
|
|
# BEFORE paying extraction — identity + first rows, one call per
|
|
# page. The LIST answer's own table never enters; tables that name
|
|
# an entity are ALWAYS relevant (never skipped by the LLM's word).
|
|
list_idx = getattr(page, "_list_table_idx", -1)
|
|
table_frags_all = [f for f in tables_as_chunks(page.wikitext)
|
|
if f["table_idx"] != list_idx]
|
|
stopped: set[int] = set()
|
|
if table_frags_all and page.tables:
|
|
# deterministic safety net: a table whose caption/headers/first
|
|
# rows NAME an entity is relevant, no LLM call needed
|
|
def _names_entity(t) -> bool:
|
|
surface = " ".join([t.caption or ""] + list(t.header[:6])
|
|
+ [r and " ".join(r[:2]) or ""
|
|
for r in t.rows[:3]])
|
|
toks = _tokens(surface)
|
|
return any(_prop_hit(e, toks) for e in entities)
|
|
|
|
undecided = [t for t in page.tables
|
|
if t.idx != list_idx and not _names_entity(t)]
|
|
if undecided:
|
|
rendered = chr(10).join(
|
|
f"{t.idx} | {t.caption or '(no caption)'} | "
|
|
f"header: {', '.join(t.header[:6]) or '(none)'} | "
|
|
f"rows: {t.total_rows} | first rows: "
|
|
+ " ;; ".join(" | ".join(r) for r in t.rows[:3] if r)
|
|
for t in undecided)
|
|
if charge_llm:
|
|
charge_llm()
|
|
pred = self.skim_tables(question=question,
|
|
entities=ent_str, tables=rendered)
|
|
for d in (pred.decisions or []):
|
|
if not d.relevant:
|
|
stopped.add(d.table_index)
|
|
self._log(f"table skim: table {d.table_index} "
|
|
f"({(d.reason or '')[:50]}) — skipped before "
|
|
f"extraction", think=True)
|
|
table_frags = [f for f in table_frags_all
|
|
if f["table_idx"] not in stopped]
|
|
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 self.cfg.extract_mode == "two_pass":
|
|
# two-pass (26/10): Pass 1 claims (short strings, coref
|
|
# resolved), Pass 2 one typed Fact per claim — every
|
|
# output short; the giant typed array is gone from prose.
|
|
claims = claims_from(self, entities=ent_str,
|
|
heading=chunk.heading_path,
|
|
text=chunk.text, charge_llm=charge_llm)
|
|
self._rec("claims.done", page=page.title,
|
|
heading=chunk.heading_path,
|
|
out_={"n_claims": len(claims),
|
|
"claims": list(claims)})
|
|
# owner ruling 26/10: completeness beats budget — every
|
|
# unique claim gets its TYPE call (no cap, dedup only)
|
|
for claim in claims:
|
|
fact = fact_from_claim(self, claim, text=chunk.text,
|
|
charge_llm=charge_llm)
|
|
self._rec("type.done", page=page.title, claim=claim[:200],
|
|
out_={"fact": getattr(fact, "__dict__", None)}
|
|
if fact is not None else {"fact": None})
|
|
if fact is None:
|
|
continue # honestly declined: no invention
|
|
merged, _eid = self._ingest_candidate(
|
|
fact, page, containment=page.text)
|
|
extracted += merged
|
|
continue
|
|
if charge_llm:
|
|
charge_llm()
|
|
raw = self.extract(entities=ent_str, heading=chunk.heading_path,
|
|
text=chunk.text)
|
|
# phase 2: ingest with order assertions — fact_ids collects the
|
|
# edge id per 0-based position in THIS extraction's facts list,
|
|
# so 'orders' sibling references resolve to real edges
|
|
fact_ids: list[int | None] = []
|
|
for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]:
|
|
merged, eid = self._ingest_candidate(cand, page, containment=page.text)
|
|
extracted += merged
|
|
fact_ids.append(eid)
|
|
# second pass: the order assertions of all facts of this chunk
|
|
for cand, fid in zip((raw.facts or [])[: self.cfg.max_facts_per_chunk], fact_ids):
|
|
if fid is None:
|
|
continue
|
|
for o in (getattr(cand, "orders", None) or []):
|
|
other = o.get("other")
|
|
rel = o.get("rel")
|
|
if (other is None or rel not in ("before", "after", "concurrent")
|
|
or not 0 <= other < len(fact_ids)
|
|
or fact_ids[other] is None):
|
|
continue # malformed reference: skip honestly
|
|
self.store.add_fact_order(fid, fact_ids[other], rel)
|
|
# ---- 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(entities=ent_str, heading=heading, text=text)
|
|
for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]:
|
|
merged, _eid = self._ingest_candidate(cand, page, containment=containment)
|
|
extracted += merged
|
|
return self._merged
|
|
|
|
def _ingest_candidate(self, cand, page: WikiPage, containment: str) -> tuple[int, int | None]:
|
|
"""Containment-check one typed Fact, merge it, cache its vector.
|
|
|
|
Returns (merged, eid): merged=1 when the candidate was accepted
|
|
(a duplicate counts — corroboration was recorded), eid=None when
|
|
no NEW edge was created (duplicate or reject). Phase 2: the CALLER
|
|
wires order assertions through the returned eid."""
|
|
self._checked += 1
|
|
cand = {"subject": cand.subject, "relation": cand.relation,
|
|
"object": cand.object, "quote": cand.quote,
|
|
"start": getattr(cand, "start", None),
|
|
"end": getattr(cand, "end", None),
|
|
"point": getattr(cand, "point", None)}
|
|
ok, reason = check_candidate(cand, containment)
|
|
if not ok:
|
|
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
|
|
self._rec("fact.rejected", reason=reason, fact=dict(cand),
|
|
page=page.title)
|
|
self._rec("fn.done", fn="check",
|
|
in_={"subject": cand.get("subject", ""),
|
|
"relation": cand.get("relation", ""),
|
|
"object": cand.get("object", "")},
|
|
out_={"ok": False, "reason": reason})
|
|
return 0, None
|
|
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)
|
|
eid = self.store.add_edge(cand["subject"], cand["relation"],
|
|
cand["object"], qid,
|
|
t_start=cand["start"] or None,
|
|
t_end=cand["end"] or None)
|
|
self._merged += 1
|
|
self._rec("fact.merged", eid=eid, fact=dict(cand), page=page.title)
|
|
self._rec("fn.done", fn="check",
|
|
in_={"subject": cand["subject"], "relation": cand["relation"],
|
|
"object": cand["object"]},
|
|
out_={"ok": True, "merged": True, "eid": eid})
|
|
if eid is not None:
|
|
self._cache_edge_vector(eid, cand["subject"], cand["relation"],
|
|
cand["object"])
|
|
return 1, eid
|
|
|
|
def _cache_edge_vector(self, eid: int, subject: str, relation: str,
|
|
obj: str) -> None:
|
|
"""Embed 'subject | relation | object' and cache it for the semantic
|
|
probe. Batched lazily: failures flip _embed_ok off (lexical fallback
|
|
keeps the run alive); no failure ever blocks an ingest."""
|
|
if not self._embed_ok:
|
|
return
|
|
text = f"{subject} | {relation} | {obj}"
|
|
try:
|
|
v = embed([text], model=self.cfg.embed_model,
|
|
url=self.cfg.embed_url)[0]
|
|
self.store.set_edge_vector(eid, self.cfg.embed_model,
|
|
hashlib.sha1(text.encode()).hexdigest(), v)
|
|
except EmbedderDown:
|
|
self._embed_ok = False
|
|
self._log("semantic probe disabled (embedder down at ingest)")
|
|
|
|
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)
|
|
answer = {
|
|
"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),
|
|
"confidence": str(pred.confidence.value),
|
|
}
|
|
self._rec("fn.done", fn="judge",
|
|
in_={"question": question,
|
|
"rows": [f"K{i}: {r.src} | {r.rel} | {r.dst}"
|
|
for i, r in enumerate(rows)][:12]},
|
|
out_={"value": answer["value"], "confidence": answer["confidence"],
|
|
"quote": answer["quote"][:120]})
|
|
return answer |