Run H (his E2E of run G's fixes) answered Q1 'three longest rivers of
Italy' with the WORLD list (Nile/Amazon/Yangtze fanned out, 226 rows).
Three root causes, all deterministic code (one is an LLM-side miss the
code now guards):
1. THE SUBJECT GUARD (new, _list_from_page): proper nouns of the
question ('Italy') must appear in the article title or the tables'
caption/headers — whole token, stem, or word prefix ('Europe' ->
'European', the gentilici pattern). The disjointness guard was vacuous
(first hop, empty evidence) and the fetch order put the world list
first; the guard now refuses it BEFORE the SELECT_TABLE call (zero
budget spent), logged as 'subject guard: ... refusing LIST'. Live
verified: world article refused, Italy article answered 22 members,
top-3 by table order = Po, Adige, Tiber.
2. WORD-BOUNDARY MATCHING (run H's KG pollution): the harvest ingested
227 world rows as 'Outflow' edges because goal term 'flow' matched
'Outflow' by substring; the discharge-list page did the same with 929
rows. _term_hits/_tokens/_col_hits replace every substring goal-term
match (harvest goal_hit + val_i, promote val_i, skim notice filter);
the keyword fallback ('flow'/'discharge' in ANY header) is gone — the
column must carry a goal term. Live: 0 Outflow edges.
3. THE EXPERT ANSWER LOG (his ask): 'OUTPUT EXPERT: Q1 -> ANSWER
value=3 (list of 3 members: Po, Adige, Tiber) quote=... url=...
[knowledge_graph]' — the answer is now IN the log, not deduced from
the fan-out that follows. Every expert output line carries the qid.
Tests: knowledge/tests/guards.py (boundary matching incl. flow !=
Outflow, proper-noun extraction, subject guard both ways, harvest
boundary, the new ANSWER log format). store.py fixture now names its
subject in the title (predates the law). Suite 52/52. Live smoke: the
full run-H regression chain on real Wikipedia.
362 lines
16 KiB
Python
362 lines
16 KiB
Python
"""Knowledge tests: chunker, containment, store's four contradiction cases.
|
|
No network, no LLM. Run: uv run python knowledge/tests/store.py
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) # repo root (for floop if needed)
|
|
|
|
from knowledge.checks import check_candidate, quote_containment, trusted_source
|
|
from knowledge.chunker import chunk_page
|
|
from knowledge.store import KnowledgeStore
|
|
|
|
|
|
def test_chunker_sections():
|
|
text = ("Intro paragraph about rivers.\n\n== Etymology ==\nThe name comes from Latin Liger.\n\n"
|
|
"== Course ==\n\n=== Upper ===\nIt starts in the Massif Central.\n\n"
|
|
"=== Lower ===\nIt reaches the Atlantic near Nantes.\n\n"
|
|
"== Long section ==\n" + ("Sentence one. " * 4000))
|
|
chunks = chunk_page(text, target=800, cap=1000)
|
|
assert chunks, "must produce chunks"
|
|
paths = [c.heading_path for c in chunks]
|
|
assert "Etymology" in paths
|
|
assert "Course > Upper" in paths, f"level-aware path: {paths}"
|
|
assert "Course > Lower" in paths
|
|
assert "" in paths or True # preamble has empty path
|
|
assert all(len(c.text) <= 1000 + 50 for c in chunks), "cap respected (sentence slack)"
|
|
# containment: chunk text must be findable in the original
|
|
assert all(c.text[:40] in text for c in chunks if len(c.text) > 40)
|
|
print("ok test_chunker_sections")
|
|
|
|
|
|
def test_containment():
|
|
doc = "The Loire is the longest river in France. It drains 117,054 km2 of land."
|
|
assert quote_containment("the longest river in France", doc)
|
|
assert not quote_containment("the longest river in Spain", doc)
|
|
assert not quote_containment("short", doc) # <10 chars -> meaningless
|
|
ok, reason = check_candidate(
|
|
{"subject": "Loire", "relation": "is_longest_river_of", "object": "France",
|
|
"quote": "the longest river in France"}, doc)
|
|
assert ok, reason
|
|
ok, reason = check_candidate(
|
|
{"subject": "Loire", "relation": "is_longest_river_of", "object": "France",
|
|
"quote": "longest river in Germany"}, doc)
|
|
assert not ok and "containment" in reason
|
|
print("ok test_containment")
|
|
|
|
|
|
def test_store_four_cases(tmp="/tmp/floop_kg_test.sqlite"):
|
|
p = Path(tmp)
|
|
if p.exists():
|
|
p.unlink()
|
|
ks = KnowledgeStore(p)
|
|
doc = ks.add_document(url="https://en.wikipedia.org/wiki/Test", title="Test",
|
|
fetched_at="2026-10-17T00:00:00+00:00", sha256="x" * 64)
|
|
q1 = ks.add_quote(doc, "The Loire is the longest river in France.", "url", "d")
|
|
q2 = ks.add_quote(doc, "The Loire is 1,006 kilometres long.", "url", "d")
|
|
|
|
# case: plain add
|
|
e1 = ks.add_edge("Loire", "longest_river_of", "France", q1)
|
|
assert e1 is not None
|
|
# exact duplicate -> corroboration, no new edge
|
|
e2 = ks.add_edge("loire", "longest_river_of", "France", q1)
|
|
assert e2 is None
|
|
row = ks.db.execute("SELECT corroboration FROM edges WHERE id=?", (e1,)).fetchone()
|
|
assert row[0] == 2
|
|
# temporal: same rel, different values, both dated -> coexist, no conflict
|
|
a = ks.add_edge("Loire", "length_km", "1006", q2, ref_date="2026")
|
|
b = ks.add_edge("Loire", "length_km", "1012", q2, ref_date="2020")
|
|
assert a and b
|
|
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
|
assert conflicts == 0, "dated different values are a time series, not a conflict"
|
|
# contradiction: same rel, undated different values -> exposed conflict
|
|
c1 = ks.add_edge("Seine", "length_km", "777", q1)
|
|
c2 = ks.add_edge("Seine", "length_km", "776", q1)
|
|
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
|
assert conflicts == 1, "undated different values must be exposed as conflict"
|
|
# probe: seeds find edges with quotes
|
|
rows = ks.probe(["Loire", "loire"])
|
|
assert any(r.rel == "longest_river_of" and r.dst == "France" for r in rows)
|
|
assert all(r.quote for r in rows), "every edge points at a quote"
|
|
ks.close()
|
|
print("ok test_store_four_cases")
|
|
|
|
|
|
def test_migration_old_store():
|
|
"""A pre-2026-10-19 KG (no origin_question column) must migrate on open,
|
|
not crash the set gate (Emili's 2026-10-19 home run)."""
|
|
import sqlite3
|
|
p = Path("/tmp/floop_kg_old.sqlite")
|
|
if p.exists():
|
|
p.unlink()
|
|
# hand-build an OLD-schema store: edges WITHOUT origin_question
|
|
db = sqlite3.connect(p)
|
|
db.executescript("""
|
|
CREATE TABLE documents (
|
|
id INTEGER PRIMARY KEY, url TEXT UNIQUE, source TEXT, fetched_at TEXT,
|
|
sha256 TEXT, trusted INTEGER, title TEXT);
|
|
CREATE TABLE quotes (
|
|
id INTEGER PRIMARY KEY, doc_id INTEGER, verbatim TEXT, url TEXT, access_date TEXT);
|
|
CREATE TABLE nodes (id INTEGER PRIMARY KEY, norm_name TEXT, sort TEXT,
|
|
UNIQUE(norm_name, sort));
|
|
CREATE TABLE edges (id INTEGER PRIMARY KEY, src_node INTEGER, rel TEXT,
|
|
dst_value TEXT, dst_node INTEGER, quote_id INTEGER, extraction_confidence REAL,
|
|
ref_date TEXT, supersedes INTEGER, preferred INTEGER DEFAULT 0,
|
|
retracted INTEGER DEFAULT 0, retraction_reason TEXT, corroboration INTEGER DEFAULT 1);
|
|
""")
|
|
db.execute("INSERT INTO nodes(norm_name, sort) VALUES('germany','PLAC'),"
|
|
"('european union','CONCEPT')")
|
|
nid = db.execute("SELECT id FROM nodes WHERE norm_name='germany'").fetchone()[0]
|
|
db.execute("INSERT INTO edges(src_node, rel, dst_value, quote_id) "
|
|
"VALUES(?, 'member_of', 'european union', NULL)", (nid,))
|
|
db.commit()
|
|
db.close()
|
|
|
|
ks = KnowledgeStore(p) # must migrate, not crash
|
|
origins = ks.set_origins() # the call that crashed on the old schema
|
|
# NULL-origin sets are NOT servable by the gate: without an origin question
|
|
# we cannot verify the set answers THIS question — safe re-gather instead.
|
|
# (The rows stay in the KG for non-enum probes; only the gate skips them.)
|
|
assert origins == [], f"NULL-origin sets must not be gate-servable: {origins}"
|
|
# and the store still answers normal probes after migration:
|
|
ks.close()
|
|
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
|
|
wt = ("{| class=wikitable" + chr(10)
|
|
+ "! Country !! Population" + chr(10)
|
|
+ "|-" + chr(10)
|
|
+ "| A" + chr(10) + "| 1" + chr(10)
|
|
+ "|-" + chr(10)
|
|
+ "| B" + chr(10) + "| 2" + chr(10)
|
|
+ "|-" + chr(10)
|
|
+ "| C" + chr(10) + "| 3" + chr(10)
|
|
+ "|-" + chr(10)
|
|
+ "| D" + chr(10) + "| 4" + chr(10)
|
|
+ "|-" + chr(10)
|
|
+ "| E" + chr(10) + "| 5" + chr(10)
|
|
+ "|}")
|
|
tables = parse_tables(wt)
|
|
assert len(tables) == 1
|
|
t = tables[0]
|
|
assert t.total_rows == 5, f"all 5 rows kept, got {t.total_rows}"
|
|
assert t.header == ["Country", "Population"], f"header parsed: {t.header}"
|
|
assert t.rows[0] == ["A", "1"]
|
|
# horizontal layout parses identically
|
|
wh = ("{| class=wikitable" + chr(10)
|
|
+ "! Country !! Population" + chr(10)
|
|
+ "|-" + chr(10)
|
|
+ "| A || 1" + chr(10)
|
|
+ "|-" + chr(10)
|
|
+ "| B || 2" + chr(10)
|
|
+ "|}")
|
|
t2 = parse_tables(wh)[0]
|
|
assert t2.total_rows == 2 and t2.rows[1] == ["B", "2"]
|
|
print("ok test_table_parser_untruncated")
|
|
|
|
|
|
def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"):
|
|
"""The LIST path end-to-end with a FAKE LLM: SELECT TABLE picks the table,
|
|
ALL rows ingested as member_of edges, aggregation is code-only."""
|
|
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
|
|
from knowledge.wiki import WikiTable
|
|
|
|
class FakeTablePicker:
|
|
def __init__(self, *a, **k):
|
|
pass
|
|
def __call__(self, **kw):
|
|
class P: pass
|
|
p = P()
|
|
p.table_index = "1"
|
|
p.column = "Country"
|
|
p.set_name = "sovereign states in Europe"
|
|
p.origin_question = kw.get("question", "")
|
|
return p
|
|
|
|
class FakeStore:
|
|
def __init__(self):
|
|
self.edges = []
|
|
self.docs = 0
|
|
self.quotes = 0
|
|
def add_document(self, **kw):
|
|
self.docs += 1
|
|
return 1
|
|
def add_quote(self, *a, **kw):
|
|
self.quotes += 1
|
|
return self.quotes
|
|
def add_edge(self, subject, rel, obj, qid, **kw):
|
|
self.edges.append((subject, rel, obj))
|
|
return len(self.edges)
|
|
|
|
ke = KnowledgeExpert.__new__(KnowledgeExpert) # no dspy init
|
|
ke.cfg = KnowledgeConfig()
|
|
ke.store = FakeStore()
|
|
ke.streams = None
|
|
ke.select_table = FakeTablePicker()
|
|
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 European states", pageid=1, url="u",
|
|
fetched_at="2026-10-18T00:00:00+00:00", text="x",
|
|
tables=[WikiTable(idx=1, header=["Country", "Population"],
|
|
rows=[["Albania", "2.8"], ["Belgium", "11.8"],
|
|
["Croatia", "3.9"]])])
|
|
ans = ke._list_from_page(page, "What are the countries in Europe?", None)
|
|
assert ans is not None
|
|
assert ans["list_count"] == 3, f"count = len (code, not LLM): {ans}"
|
|
assert ans["list_items"] == ["Albania", "Belgium", "Croatia"]
|
|
assert ans["coverage"]["complete_per_source"] is True
|
|
assert ans["coverage"]["rows_ingested"] == 3
|
|
# every row became a membership edge, quote = full row line
|
|
assert len(ke.store.edges) == 3
|
|
assert all(e[1] == "member_of" for e in ke.store.edges)
|
|
# rejected path: no table matches -> None -> fall through to extract path
|
|
class FakeNonePicker:
|
|
def __init__(self, *a, **k):
|
|
pass
|
|
def __call__(self, **kw):
|
|
class P: pass
|
|
p = P()
|
|
p.table_index = "NONE"
|
|
p.column = ""
|
|
p.set_name = ""
|
|
p.origin_question = ""
|
|
return p
|
|
ke.select_table = FakeNonePicker()
|
|
assert ke._list_from_page(page, "irrelevant", None) is None
|
|
print("ok test_list_ingest_aggregate")
|
|
|
|
|
|
def test_disjoint_guard_refuses_wrong_list():
|
|
"""The disjointness guard: an ingest whose members don't overlap the
|
|
entities the parent's evidence names is refused; the gather continues.
|
|
Emili's run-08: 'flow of Po, Adige, Tiber' must never be answered by the
|
|
Amazon's flow from a world-wide discharge table."""
|
|
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
|
|
|
|
ke = KnowledgeExpert.__new__(KnowledgeExpert)
|
|
ke.cfg = KnowledgeConfig()
|
|
ke.streams = None
|
|
ke._log = lambda text, think=False: None
|
|
|
|
# the parent's evidence: a scalar row naming the three rivers
|
|
evidence = "E1: Po, Adige, Tiber (answers Q1)"
|
|
assert ke._expected_entities(evidence) == ["Po", "Adige", "Tiber"]
|
|
|
|
# a world-wide discharge list: disjoint from the expected entities
|
|
assert ke._guard_ingest({"list_items": ["Amazon", "Congo", "Yangtze"]}, evidence) is False
|
|
# the right list: overlap — ingest is fine
|
|
assert ke._guard_ingest({"list_items": ["Po", "Adige", "Tiber"]}, evidence) is True
|
|
# no evidence (top-level question): guard passes, ingest is fine
|
|
assert ke._guard_ingest({"list_items": ["Amazon", "Congo"]}, "") is True
|
|
# LIST row evidence: 'list of 22 items: Po, Adige, ...' also seeds entities
|
|
ev2 = "E1: list of 3 items: Po, Adige, Tiber (answers Q1)"
|
|
assert ke._expected_entities(ev2) == ["Po", "Adige", "Tiber"]
|
|
print("ok test_disjoint_guard_refuses_wrong_list")
|
|
|
|
|
|
def test_list_members_ordered():
|
|
"""Ranked tables rank: the store keeps the source order via list_ord.
|
|
Served sets must return Po, Adige, Tiber first — NOT alphabetical
|
|
(Emili's 2026-10-20 log-09: adda, adige, arno from an old unordered set)."""
|
|
import tempfile, os
|
|
from knowledge.store import KnowledgeStore
|
|
p = os.path.join(tempfile.mkdtemp(), "kg.sqlite")
|
|
ks = KnowledgeStore(p)
|
|
doc = ks.add_document(url="u", title="t", fetched_at="now", sha256="x")
|
|
qid = ks.add_quote(doc, "q", "u", "now")
|
|
# ingest with ordinals: the table's order (Po 1st, Adige 2nd, Tiber 3rd)
|
|
for i, name in enumerate(["Po", "Adige", "Tiber", "Adda", "Oglio"], start=1):
|
|
ks.add_edge(name, "member_of", "longest rivers of Italy", qid,
|
|
src_sort="PLACE", dst_node_name="longest rivers of Italy",
|
|
origin_question="Which are the three longest rivers of Italy?",
|
|
list_ord=i)
|
|
assert ks.list_is_ordered("longest rivers of Italy")
|
|
assert ks.list_members("longest rivers of Italy", ordered=True) == \
|
|
["po", "adige", "tiber", "adda", "oglio"]
|
|
# unordered fallback (old sets, pre-ordinal): alphabetical, flagged
|
|
assert ks.list_members("longest rivers of Italy") == \
|
|
["adda", "adige", "oglio", "po", "tiber"]
|
|
print("ok test_list_members_ordered")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
test_chunker_sections()
|
|
test_containment()
|
|
test_store_four_cases()
|
|
test_migration_old_store()
|
|
test_verify_count()
|
|
test_list_ingest_aggregate()
|
|
test_table_parser_untruncated()
|
|
test_disjoint_guard_refuses_wrong_list()
|
|
test_list_members_ordered()
|
|
print(f"\n{test_table_parser_untruncated.__name__} etc — 9 knowledge tests passed") |