diff --git a/RUNLOG.md b/RUNLOG.md index ce561c3..db64e2a 100644 --- a/RUNLOG.md +++ b/RUNLOG.md @@ -346,3 +346,34 @@ article, table fully parsed); Q2 -> 27 EU members ingested (Member state article); Q3 -> setop difference computed, verified=True, zero LLM calls. Answer: **23**, citing E3 over E1 and E2. The count is a computation over two typed lists — exactly what the INIT plan always asked for. + + +--- + +# Run F — count corroboration live (2026-10-19) + +**Goal:** verify the answer-level CHECK (DESIGN §12) end-to-end: LIST rows +must come back `verified` when the article prose corroborates the ingested +count, and the corroborating sentence must be cited in the payload. + +`How many European countries do not belong to European Union?` (cold KG) + +- Q1 → LIST path: table 1 (50 rows) of 'List of sovereign states... in Europe', + 50 members ingested, VERIFY found the prose count: + "There are 50 sovereign states with territory located within the common + definition of Europe and/or membership in international European + organisations..." → **E1 verified**, count_corroborated=true. +- Q2 → LIST path: table 1 (27 rows) of 'Member state of the European Union', + 27 members, VERIFY found: "The European Union (EU) is a supranational + union of 27 member states that are party to the EU's founding + treaties..." → **E2 verified**. (Emili predicted this exact sentence.) +- Q3 → setop difference, computed: 23, E3 verified. +- FINAL: 23, consistent with E1/E2. + +**Notes:** +- The run-level `[UNVERIFIED]` tag remains: it is the prover stub + (derivability check, v0.2); per-row verified is the honest state today. + E1+E2+E3 all verified, but 'answer follows from evidence' is still not + machine-checked — the synthesizer wrote it, no prover validated it. +- VERIFY adds exactly one LLM call per LIST ingest (budget 4→5, 8→9). + NOQUOTE → count_corroborated=false → row stays unverified: honest, no loop. diff --git a/code/floop/engine.py b/code/floop/engine.py index ed701be..5ac2e66 100644 --- a/code/floop/engine.py +++ b/code/floop/engine.py @@ -142,6 +142,15 @@ class KnowledgeEngine: prov = {"expert": "knowledge", "source": src, "note": ("source-verified: verbatim containment in trusted doc" if ans.get("quote") else "no quote — unverified")} + # LIST rows: the answer-level check corroborates the count outside the + # source table; combined with per-source completeness it makes the + # row verified (E3-style verified semantics, first non-stub use). + verified = False + cov = ans.get("coverage") or {} + if (isinstance(ans.get("list_items"), list) and ans["list_items"] + and cov.get("complete_per_source") and cov.get("count_corroborated")): + verified = True + prov["note"] = "count corroborated outside the source table" if parent_question: prov["parent_question"] = parent_question note = "" if value.upper() != "UNKNOWN" else "knowledge returned UNKNOWN" @@ -155,6 +164,7 @@ class KnowledgeEngine: engine="knowledge", trace=[f"kg pipeline: source={src} conf={ans.get('confidence', '?')}"], provenance=prov, - verified=False, # the prover is still a stub; the quote is source-verified + verified=verified, # True only when the count is corroborated + # outside the source table (LIST rows) note=note, ) \ No newline at end of file diff --git a/code/knowledge/DESIGN.md b/code/knowledge/DESIGN.md index be08f77..e9ce1fa 100644 --- a/code/knowledge/DESIGN.md +++ b/code/knowledge/DESIGN.md @@ -311,4 +311,63 @@ document artifact for audit. calls (2 + retries); ingestion and aggregation are free. A 500-row table costs the same LLM budget as a 5-row one — the cost of an enumeration is O(1) in the size of the list. - confirm or set preferred numbers. \ No newline at end of file + +## 12. Answer-level verification — the CHECK step for answers (2026-10-19) + +Emili's case: the EU member list is 27 rows ingested from a table, AND the +same article's prose says "a supranational union of 27 member states" — two +independent statements of the same count. When the corroborating sentence +exists, the count is not just complete-per-source; it is **corroborated**. +The LIST path now runs this check (one bounded LLM call, never a loop): + +``` +ingested N members from table T (coverage: complete_per_source) + │ + ▼ VERIFY COUNT (LLM): given set_name + N + the article PROSE (the extract + │ text — tables live in a separate structure, so the source table is + │ excluded BY CONSTRUCTION), find ONE verbatim sentence stating the + │ count of that set. NOQUOTE if none exists. + ▼ CHECK (code): containment of the sentence in the prose (same law as + every quote) AND the digits the sentence states == N. No LLM ever + compares numbers. + │ + ▼ verified row ⇔ complete_per_source AND count_corroborated +``` + +**Law split, again.** The LLM finds language (one sentence); fixed code +decides validity. `count_corroborated=False` is an HONEST state, not an +error: many lists have no prose count, and floop must never loop looking +for one. The row's payload carries the flag + the corroborating quote, so +the synthesizer can say "50, corroborated by the article's own prose" vs +"27, no independent count statement found". + +**What this is NOT (scope honesty).** Same-article prose and table often +derive from the same primary data — corroboration here is *structural +independence* (two statements in different forms), not *source +independence*. Cross-article corroboration (fetch a second article and +find the same count) is future work: it costs another gather round and +most questions will never have the redundancy for it. We do not pretend +to strictness we do not have. Not every question will have a Wikipedia +page, let alone redundant sources — the design target is honest answers +grounded in fetched sources, not strict verification everywhere. + +### Deferred (name it, don't hide it) + +- **Extension verification** (proving exactly WHICH members, not just how + many): needs per-member confirmation, expensive; only when a question + asks "which ones" and stakes justify it. +- **Definitional criteria** (the 46/48/50 Europe case): when an independent + counter disagrees with our count, the LLM extracts the *criterion* each + citation uses, code compares the numbers, and a criterion-mismatch is a + *definition-dependent count* answer ("50 per the EOC definition, 46 per + the Council of Europe") — NOT a conflict row. Same criterion + different + number → conflict row, surfaced. +- **Prose-list completeness** (lists with no dedicated page, assembled from + prose extraction): a corroborating count is the only signal that says + "you missed members"; a mismatch means `partial`, a legitimate honest + state. Negative knowledge ("this list is not exhaustive") is itself a + verbatim quotable claim. +- **Cross-article corroboration** as a second, stronger check level. + +Build order: count-corroboration now (cheap, saves the EU case), criteria +later (needs the extractor to output criterion labels), extension last. \ No newline at end of file diff --git a/code/knowledge/expert.py b/code/knowledge/expert.py index ffb6ba4..dfca9e4 100644 --- a/code/knowledge/expert.py +++ b/code/knowledge/expert.py @@ -21,10 +21,10 @@ from dataclasses import dataclass import dspy -from .checks import check_candidate +from .checks import check_candidate, quote_containment from .chunker import chunk_page from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature, - TranslateSignature, parse_facts) + TranslateSignature, VerifyCountSignature, parse_facts) from .store import KnowledgeStore, norm_name from .wiki import WikipediaClient, WikiPage @@ -56,6 +56,7 @@ class KnowledgeExpert: self.answer = dspy.Predict(AnswerFromKG) self.translate = dspy.Predict(TranslateSignature) self.select_table = dspy.Predict(SelectTableSignature) + self.verify_count = dspy.Predict(VerifyCountSignature) self._checked = 0 self._merged = 0 @@ -277,6 +278,38 @@ class KnowledgeExpert: 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. @@ -340,17 +373,27 @@ class KnowledgeExpert: items = sorted(set(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} + 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", - "coverage": {"source": page.title, "table": idx, - "rows_total": table.total_rows, - "rows_ingested": len(members), - "complete_per_source": len(members) == table.total_rows}, + "confidence": "high" if verify else "medium", + "coverage": coverage, } def _process_page(self, page: WikiPage, question: str, kws: list[str], diff --git a/code/knowledge/extract.py b/code/knowledge/extract.py index f539fd5..4a09e49 100644 --- a/code/knowledge/extract.py +++ b/code/knowledge/extract.py @@ -47,6 +47,25 @@ class AnswerFromKG(dspy.Signature): confidence: str = dspy.OutputField(desc="high medium low") +class VerifyCountSignature(dspy.Signature): + """You are the VERIFY step of a knowledge machine. A list answer has been + ingested from a table in one article (set_name, N elements). Find ONE + sentence in the article prose that states the expected count of that set + (independently of the table). Quote it VERBATIM. If no such sentence + exists, write NOQUOTE. + + Example: + set_name: European Union member states + count: 27 + GOOD quote: "The European Union (EU) is a supranational union of 27 + member states that are party to the EU's founding treaties" + BAD (not a count statement): a row of the table itself.""" + set_name: str = dspy.InputField() + count: str = dspy.InputField() + text: str = dspy.InputField(desc="the article prose WITHOUT the tables") + quote: str = dspy.OutputField(desc="verbatim sentence stating the count, or NOQUOTE") + + class SelectTableSignature(dspy.Signature): """You are the SELECT TABLE step of a knowledge machine. Given a question and the tables found in an article (index, caption, header columns, row diff --git a/code/knowledge/tests/store.py b/code/knowledge/tests/store.py index 2ddd6c3..f18420e 100644 --- a/code/knowledge/tests/store.py +++ b/code/knowledge/tests/store.py @@ -126,6 +126,58 @@ def test_migration_old_store(): print("ok test_migration_old_store") +def test_verify_count(): + """Answer-level CHECK: the LLM finds a corroborating sentence, code + compares the digits. Containment + equal digits -> corroborated.""" + from knowledge.expert import KnowledgeExpert, KnowledgeConfig + from knowledge.extract import VerifyCountSignature # noqa: F401 — wiring proof + + class FakeVerifier: + def __init__(self, *a, **k): + pass + def __call__(self, **kw): + class P: pass + p = P() + p.quote = ("The European Union (EU) is a supranational union of " + "27 member states that are party to the EU's founding treaties") + return p + + class FakeNoVerifier: + def __init__(self, *a, **k): + pass + def __call__(self, **kw): + class P: pass + p = P() + p.quote = "NOQUOTE" + return p + + ke = KnowledgeExpert.__new__(KnowledgeExpert) + ke.cfg = KnowledgeConfig() + ke.streams = None + ke.verify_count = FakeVerifier() + prose = ("The European Union (EU) is a supranational union of 27 member " + "states that are party to the EU's founding treaties, and thereby " + "subject to EU law.") + res = ke._verify_count("European Union member states", 27, prose, None) + assert res is not None and res["count_corroborated"] is True + + ke.verify_count = FakeNoVerifier() + assert ke._verify_count("European Union member states", 27, prose, None) is None + + # digits disagree -> not corroborated, honest + class FakeWrongVerifier: + def __init__(self, *a, **k): + pass + def __call__(self, **kw): + class P: pass + p = P() + p.quote = "The European Higher Education Area includes 48 countries" + return p + ke.verify_count = FakeWrongVerifier() + assert ke._verify_count("European Union member states", 27, prose, None) is None + print("ok test_verify_count") + + def test_table_parser_untruncated(): from knowledge.wiki import parse_tables # vertical layout, 5 rows, header row -> total_rows MUST be 5, no truncation @@ -202,6 +254,16 @@ def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"): ke._merged = 0 ke._log = lambda text, think=False: None # bound-style: no self + class FakeNoVerifier: # honest: no corroboration + def __init__(self, *a, **k): + pass + def __call__(self, **kw): + class P: pass + p = P() + p.quote = "NOQUOTE" + return p + ke.verify_count = FakeNoVerifier() + from knowledge.wiki import WikiPage page = WikiPage(title="List of states", pageid=1, url="u", fetched_at="2026-10-18T00:00:00+00:00", text="x", @@ -239,6 +301,7 @@ if __name__ == "__main__": test_containment() test_store_four_cases() test_migration_old_store() + test_verify_count() test_list_ingest_aggregate() test_table_parser_untruncated() - print(f"\n{test_table_parser_untruncated.__name__} etc — 6 knowledge tests passed") \ No newline at end of file + print(f"\n{test_table_parser_untruncated.__name__} etc — 7 knowledge tests passed") \ No newline at end of file