"""Temporal restriction tests (phase 2, RESEARCH-derived-answers Part 2). The extractor's temporal vocabulary is RESTRICTIONS, never Allen labels: start/end/point (dates, optional, containment-checked against the quote), granularity, and fact-order assertions {before, after, concurrent} that reference sibling facts by local index. The Allen algebra stays a COMPUTED VIEW over endpoints (the store's job); asking the model to choose labels would replace transcription with classification and produce uncheckable, granularity-blind, silently-disagreeing labels. Laws under test: 1. A date field not contained in the quote is REJECTED (the honest law: the model proposes, code verifies against the source surface). 2. Windows feed the taxonomy: overlapping open windows on one (src,rel) are alternatives (coexistence is interval arithmetic, not statistics); disjoint windows are succession — never a conflict. 3. 'since 2018' means END OPEN; two open ends overlap. 4. Order assertions between sibling facts survive ingest as fact_order rows (edges are addressable; reification is free). 5. Empty temporal fields stay empty — no invented dates. The extractor call itself is scripted (structured-output Fact objects, like the live dspy adapter returns); no network. Run: .venv/bin/python knowledge/tests/temporal.py """ from __future__ import annotations import sys import tempfile from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) from knowledge.extract import Fact from knowledge.store import KnowledgeStore def make_store() -> KnowledgeStore: return KnowledgeStore(f"{tempfile.mkdtemp()}/kg.sqlite") def add_doc(store: KnowledgeStore, text: str) -> int: url = f"u{abs(hash(text)) % 10**8}" doc_id = store.add_document(url=url, title="t", fetched_at="2026-10-25", sha256=f"{abs(hash(text)) % 10**16:016x}") return store.add_quote(doc_id=doc_id, verbatim=text, url=url, access_date="2026-10-25") # --- the Fact contract --------------------------------------------------------- def test_fact_temporal_fields(): """Fact carries optional start/end/point/granularity + orders.""" f = Fact(subject="X", relation="position held", object="President of A", quote="X was president of A and B at the same time for one month.", start="2020", end=None, point=None, granularity="year", orders=[]) assert f.start == "2020" and f.granularity == "year" f2 = Fact(subject="X", relation="position held", object="President of B", quote="X was also president of B.", start=None, end=None, point=None, granularity=None, orders=[{"rel": "concurrent", "other": 0}]) assert f2.orders[0]["rel"] == "concurrent" print("ok: Fact typed temporal fields + order assertions") def test_date_not_in_quote_rejected(): """The honest law: a temporal field must be contained in the quote.""" from knowledge.checks import check_candidate good = {"subject": "X", "relation": "term start", "object": "2018", "quote": "X took office in 2018.", "start": "2018"} bad = {"subject": "X", "relation": "term start", "object": "2018", "quote": "X took office some years ago.", "start": "2018"} ok, reason = check_candidate(good, "X took office in 2018.") assert ok, f"contained date must pass: {reason}" ok, reason = check_candidate(bad, "X took office some years ago.") assert not ok, f"invented date must be rejected, got pass ({reason})" print("ok: temporal containment check (invented dates rejected)") # --- windows feed the taxonomy --------------------------------------------------- def test_overlapping_open_windows_are_alternatives(): """'since 2018' and 'since 2022' on one (src, rel): two open intervals overlap -> coexistence -> alternatives, not contradiction.""" store = make_store() q1 = add_doc(store, "He has been the prime minister of Spain since 2018.") q2 = add_doc(store, "He is the ninth president of Socialist International since 2022.") store.add_edge("pedro sanchez", "position held", "prime minister of Spain", quote_id=q1, t_start="2018") store.add_edge("pedro sanchez", "position held", "ninth president of Socialist International", quote_id=q2, t_start="2022") conf = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0] alts = store.db.execute("SELECT COUNT(*) FROM alternatives").fetchone()[0] assert conf == 0, f"overlapping open windows must not conflict (got {conf})" assert alts >= 1, "overlapping open windows are co-true alternatives" print("ok: overlapping open windows -> alternatives (interval arithmetic)") def test_disjoint_windows_are_succession_not_conflict(): """Leader of the Opposition (2014-2018) vs prime minister (2018-): the 'became' pair — disjoint windows mean succession, never a conflict.""" store = make_store() q1 = add_doc(store, "In 2014, he was elected, becoming Leader of the Opposition.") q2 = add_doc(store, "In 2018 he became prime minister.") store.add_edge("pedro sanchez", "became", "Leader of the Opposition", quote_id=q1, t_start="2014", t_end="2018") store.add_edge("pedro sanchez", "became", "prime minister", quote_id=q2, t_start="2018") conf = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0] alts = store.db.execute("SELECT COUNT(*) FROM alternatives").fetchone()[0] assert conf == 0, f"succession is not a conflict (got {conf})" assert alts == 0, f"disjoint windows are not co-true (got {alts} alts)" print("ok: disjoint windows -> succession, no conflict, no alternatives") def test_empty_windows_stay_empty(): """No dates in the text -> no dates in the edge. No invention.""" store = make_store() q1 = add_doc(store, "He was a city councillor in Madrid.") q2 = add_doc(store, "He later was a member of parliament.") e1 = store.add_edge("pedro sanchez", "became", "city councillor", quote_id=q1) e2 = store.add_edge("pedro sanchez", "became", "member of parliament", quote_id=q2) row = store.db.execute("SELECT t_start, t_end FROM edges WHERE id=?", (e1,)).fetchone() assert row == (None, None), f"undated facts keep empty windows ({row})" print("ok: no dates in text -> empty windows stay empty") # --- fact_order ------------------------------------------------------------------- def test_order_assertions_ingest(): """'X was leader of the opposition BEFORE being president' -> two facts, one fact_order row (before), reification-free (edges carry ids).""" store = make_store() q = add_doc(store, "X was leader of the opposition before becoming president.") a = store.add_edge("X", "position held", "leader of the opposition", quote_id=q) b = store.add_edge("X", "position held", "president", quote_id=q) store.add_fact_order(a, b, "before", quote_id=q) rows = store.db.execute( "SELECT rel FROM fact_order WHERE edge_a=? AND edge_b=?", (a, b)).fetchall() assert rows and rows[0][0] == "before", f"fact_order row missing: {rows}" # concurrent order also representable c = store.add_edge("X", "position held", "president of B", quote_id=q) store.add_fact_order(b, c, "concurrent", quote_id=q) n = store.db.execute("SELECT COUNT(*) FROM fact_order").fetchone()[0] assert n == 2, f"expected 2 fact_order rows, got {n}" print("ok: fact_order rows ingest (before/concurrent between addressable edges)") if __name__ == "__main__": test_fact_temporal_fields() test_date_not_in_quote_rejected() test_overlapping_open_windows_are_alternatives() test_disjoint_windows_are_succession_not_conflict() test_empty_windows_stay_empty() test_order_assertions_ingest() print("\ntemporal: 6/6 ok")