From 99f8b6e9db6cb825b8020cc485173594d7766c27 Mon Sep 17 00:00:00 2001 From: Onibot Date: Sun, 25 Oct 2026 21:07:34 +0100 Subject: [PATCH] knowledge: temporal restrictions layer (phase 2, RESEARCH-derived-answers Part 2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The extractor's temporal vocabulary is RESTRICTIONS, never Allen labels: typed Fact gains start/end/point (optional, ISO-ish) + granularity + orders [{rel: before|after|concurrent, other: }] — the text's connectives transcribed, not classified. The Allen algebra stays a COMPUTED VIEW over endpoints. - checks.py: every stated date must be CONTAINED IN THE QUOTE — an invented date rejects the whole candidate (LLM proposes, code verifies against the source surface). - store.py: edges gain t_start/t_end (valid-time window, None end = OPEN, honest to 'since 2018'); fact_order table (order assertions between addressable facts — reification is free); _classify consumes interval arithmetic: overlapping open windows -> alternatives (coexistence provable, no statistics), disjoint windows -> succession (never a conflict). Boundary law at year granularity: [2014,2018) vs [2018,None) = succession — the mandate changed hands in 2018. add_fact_order validates rel in {before, after, concurrent}. - expert.py: _ingest_candidate returns (merged, eid) and passes the windows; the prose path collects positional fact_ids and wires the orders' sibling references to real edge ids (malformed refs skip honestly). Tests: temporal.py 6/6 (typed fields, containment rejection, open- window overlap -> alternatives, touch-at-year -> succession, empty stays empty, fact_order ingest) + 7/7 interval cases incl. the open-past degenerate. Suite: all green. LIVE (run 20261025-205018, cold KG, glm-5.3-flash): 29 edges carry windows (Spain 2018 / PSOE 2017 / SI 2022 all open-ended), 25 fact_order rows (Madrid before Congress of Deputies...), 8 invented end-dates REJECTED by the containment check (the footballer Pedro articles — the check catching exactly what it should), 0 conflicts. The run itself answered UNKNOWN on its Q1 ("what DATE did he take office") — honest: the blind extractor did not transcribe the exact date this run and the noisy re-probe view (four Pedros) is the known branch weakness, not a phase-2 regression. Design note for phase 4: the three presidencies live under DIFFERENT rels, so the alternatives substrate must be queried trans-rel by the consumer (alternatives_of is per-rel by construction). --- code/knowledge/checks.py | 7 ++ code/knowledge/expert.py | 45 +++++++-- code/knowledge/extract.py | 30 +++++- code/knowledge/store.py | 145 +++++++++++++++++++++------- code/knowledge/tests/temporal.py | 161 +++++++++++++++++++++++++++++++ 5 files changed, 342 insertions(+), 46 deletions(-) create mode 100644 code/knowledge/tests/temporal.py diff --git a/code/knowledge/checks.py b/code/knowledge/checks.py index 75d3914..09e8847 100644 --- a/code/knowledge/checks.py +++ b/code/knowledge/checks.py @@ -42,4 +42,11 @@ def check_candidate(cand: dict, full_text: str) -> tuple[bool, str]: subj, rel, obj = cand.get("subject", ""), cand.get("relation", ""), cand.get("object", "") if not (subj and rel and obj): return False, "incomplete triple" + # phase 2: temporal restrictions are quotable — every stated date must + # be CONTAINED IN THE QUOTE (an invented date rejects the candidate; + # the model proposes, code verifies against the source surface) + for field in ("start", "end", "point"): + val = (cand.get(field) or "").strip() + if val and val not in quote: + return False, f"temporal {field} not in quote" return True, "ok" \ No newline at end of file diff --git a/code/knowledge/expert.py b/code/knowledge/expert.py index cc429d2..4b0a3ed 100644 --- a/code/knowledge/expert.py +++ b/code/knowledge/expert.py @@ -1076,8 +1076,26 @@ class KnowledgeExpert: 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]: - extracted += self._ingest_candidate(cand, page, containment=page.text) + 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 @@ -1103,31 +1121,40 @@ class KnowledgeExpert: 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]: - extracted += self._ingest_candidate(cand, page, containment=containment) + merged, _eid = self._ingest_candidate(cand, page, containment=containment) + extracted += merged return self._merged - def _ingest_candidate(self, cand, page: WikiPage, containment: str) -> int: + def _ingest_candidate(self, cand, page: WikiPage, containment: str) -> tuple[int, int | None]: """Containment-check one typed Fact, merge it, cache its vector. - Returns 1 when merged, 0 otherwise. Shared by the prose and table- - fragment extract paths (research/semantic-kg).""" + + 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} + "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]}") - return 0 + 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) + cand["object"], qid, + t_start=cand["start"] or None, + t_end=cand["end"] or None) self._merged += 1 if eid is not None: self._cache_edge_vector(eid, cand["subject"], cand["relation"], cand["object"]) - return 1 + return 1, eid def _cache_edge_vector(self, eid: int, subject: str, relation: str, obj: str) -> None: diff --git a/code/knowledge/extract.py b/code/knowledge/extract.py index df76e10..1f69025 100644 --- a/code/knowledge/extract.py +++ b/code/knowledge/extract.py @@ -20,12 +20,40 @@ class Confidence(str, Enum): class Fact(BaseModel): - """One fact extracted from a text, with its verbatim supporting quote.""" + """One fact extracted from a text, with its verbatim supporting quote + and its TEMPORAL RESTRICTIONS (phase 2 — restrictions, never Allen + labels; the algebra is a computed view over these endpoints). + + All temporal fields are optional and must be CONTAINED IN THE QUOTE + (an invented date fails the containment check and the whole fact is + rejected — the honest law). 'since YYYY' means start=YYYY, end OPEN. + Granularity is honest precision: 'year' | 'month' | 'day'. + orders: temporal-order assertions BETWEEN SIBLING FACTS of the same + extraction, by their 0-based position in the same facts list — + {rel: before|after|concurrent, other: }.""" subject: str = dspy.OutputField(desc="the fact's subject entity") relation: str = dspy.OutputField(desc="the relation between subject and object") object: str = dspy.OutputField(desc="the fact's object / value") quote: str = dspy.OutputField( desc="VERBATIM quote from the text that states the fact: the FULL sentence or table row, copied exactly (at least 10 characters)") + start: str | None = dspy.OutputField( + default=None, + desc="when the fact begins, as stated in the text (a year like 2018, or a full date); empty when the text states no start") + end: str | None = dspy.OutputField( + default=None, + desc="when the fact ends, as stated in the text; empty when ongoing/unknown") + point: str | None = dspy.OutputField( + default=None, + desc="for point-in-time facts (events): the stated date; empty otherwise") + granularity: str | None = dspy.OutputField( + default=None, + desc="precision of the stated dates: year, month, or day; empty when no dates") + orders: list[dict] = dspy.OutputField( + default_factory=list, + desc="temporal order between THIS fact and SIBLING facts of the same list, " + "ONLY when the text asserts it with a connective (before/after/at the same " + "time as); each entry {rel: before|after|concurrent, other: <0-based index " + "of the sibling fact>}; empty when the text asserts no order") class ExtractSignature(dspy.Signature): diff --git a/code/knowledge/store.py b/code/knowledge/store.py index e0216c1..924e12e 100644 --- a/code/knowledge/store.py +++ b/code/knowledge/store.py @@ -87,6 +87,39 @@ def _looks_functional(value: str) -> bool: return len(entity_words) < 2 +# ---- phase 2: valid-time windows (RESEARCH-derived-answers Part 2) ----------- +# A window is (start, end) with None = OPEN. Granularity is compared as +# text (ISO-like, left-padded by the extractor: '2018' < '2018-06' < +# '2018-06-02' all compare correctly as strings when normalized to the +# finest stated granularity — a year window is the interval +# [2018, 2019), honest to its precision). + +def _window(start: str | None, end: str | None) -> tuple[str | None, str | None] | None: + """The window, or None when the fact states NO time at all (empty + windows stay empty — no invention, no pretending).""" + if not start and not end: + return None + return (start or None, end or None) + + +def _overlaps(a: tuple[str | None, str | None], + b: tuple[str | None, str | None]) -> bool: + """Two valid-time windows overlap? None endpoints are OPEN (±inf). + + The boundary law (year granularity, honest to its precision): an end + year CLOSES the window and the next start year OPENS there — + [2014,2018) vs [2018,None) is SUCCESSION (the mandate changed hands + in 2018), not coexistence. Overlap is max(starts) < min(ends); the + open sides degenerate correctly: both starts None (share the + indefinite past) or both ends None (both ongoing) always overlap. + """ + lo = max(a[0] or "-inf", b[0] or "-inf") + hi = min(a[1] or "9999", b[1] or "9999") + if lo == "-inf" or hi == "9999": + return True + return lo < hi # strict: touching at one year = succession + + def stem(word: str) -> str: """Tiny suffix stemmer so question words match text words (draft): 'populated'/'population' -> 'populat', 'states' -> 'state'.""" @@ -142,6 +175,19 @@ class KnowledgeStore: if "list_ord" not in cols: self.db.execute("ALTER TABLE edges ADD COLUMN list_ord INTEGER") self.db.commit() + # ---- phase 2: temporal windows (RESEARCH-derived-answers Part 2) ---- + for col in ("t_start", "t_end"): + if col not in cols: + self.db.execute(f"ALTER TABLE edges ADD COLUMN {col} TEXT") + self.db.commit() + # fact_order: order assertions BETWEEN facts (edges are addressable; + # reification is free). rel in {before, after, concurrent}. + self.db.execute( + "CREATE TABLE IF NOT EXISTS fact_order (" + " id INTEGER PRIMARY KEY, edge_a INTEGER, edge_b INTEGER, " + " rel TEXT, quote_id INTEGER, " + " UNIQUE(edge_a, edge_b, rel))") + self.db.commit() # ---- phase 1: the conflict taxonomy (RESEARCH-derived-answers.md) ---- # alternatives: co-true readings of one (src, rel) — the polisèmia # (the three presidencies). Same shape as conflicts (pairwise), but @@ -195,8 +241,14 @@ class KnowledgeStore: dst_sort: str = "CONCEPT", confidence: float = 0.8, ref_date: str | None = None, origin_question: str | None = None, - list_ord: int | None = None) -> int | None: - """Add an edge, applying the four contradiction cases (KNOWLEDGE.md §2). + list_ord: int | None = None, + t_start: str | None = None, t_end: str | None = None) -> int | None: + """Add an edge, applying the taxonomy (KNOWLEDGE.md §2 + the + RESEARCH-derived-answers parts 1-2). + + t_start/t_end: the fact's VALID-TIME window as stated in the source + ('since 2018' -> t_start='2018', t_end=None = OPEN). None/None when + the text states no time — empty windows stay empty, no invention. Returns the edge id, or None when the candidate was a duplicate (corroboration was counted instead). @@ -214,21 +266,24 @@ class KnowledgeStore: return None # contradiction classification: same src+rel, different value, not retracted others = self.db.execute( - "SELECT id, dst_value, ref_date, dst_node, quote_id FROM edges WHERE src_node=? AND rel=? " + "SELECT id, dst_value, ref_date, dst_node, quote_id, t_start, t_end " + "FROM edges WHERE src_node=? AND rel=? " "AND retracted=0 AND id NOT IN (SELECT supersedes FROM edges WHERE supersedes IS NOT NULL)", (src, rel)).fetchall() cur = self.db.execute( "INSERT INTO edges(src_node, rel, dst_value, dst_node, quote_id, " - "extraction_confidence, origin_question, ref_date, preferred, list_ord) " - "VALUES(?,?,?,?,?,?,?,?,0,?)", + "extraction_confidence, origin_question, ref_date, preferred, list_ord, t_start, t_end) " + "VALUES(?,?,?,?,?,?,?,?,0,?,?,?)", (src, rel, dst_value, dst_node, quote_id, confidence, origin_question, - ref_date, list_ord)) + ref_date, list_ord, t_start, t_end)) edge_id = cur.lastrowid - for other_id, other_val, other_date, other_dn, other_q in others: + for other_id, other_val, other_date, other_dn, other_q, o_ts, o_te in others: case = self._classify(new_val=dst_value, new_date=ref_date, old_val=other_val, old_date=other_date, new_node=dst_node, old_node=other_dn, - new_quote=quote_id, old_quote=other_q) + new_quote=quote_id, old_quote=other_q, + new_start=t_start, new_end=t_end, + old_start=o_ts, old_end=o_te) if case in ("duplicate", "paraphrase"): if case == "paraphrase": self.db.execute( @@ -241,10 +296,10 @@ class KnowledgeStore: elif case == "supersedes": self.db.execute("UPDATE edges SET supersedes=? WHERE id=?", (other_id, edge_id)) self.db.execute("UPDATE edges SET preferred=1 WHERE id=?", (edge_id,)) - elif case == "temporal": - pass # both coexist; queries pick by date - elif case == "coasserted": - pass # one trusted sentence asserts both: conjunction, never a conflict + elif case in ("temporal", "coasserted", "succession"): + # both dated (series) / one sentence asserts both / disjoint + # windows: the world holds or moves on — never a conflict + pass elif case == "alternatives": self.db.execute( "INSERT OR IGNORE INTO alternatives(node, rel, value_a, value_b, edge_a, edge_b) " @@ -257,52 +312,70 @@ class KnowledgeStore: self.db.commit() return edge_id + def add_fact_order(self, edge_a: int, edge_b: int, rel: str, + quote_id: int | None = None) -> None: + """Record a temporal-order assertion BETWEEN two facts (phase 2). + + The text asserts the order with a connective ('before becoming', + 'at the same time as'); the extractor transcribes it as an order + restriction, code verifies the connective's quote and stores it + here. Edges are addressable — reification is free. rel is one of + {before, after, concurrent} (the extractor's vocabulary; Allen's + finer relations are computed views over the windows, never labels). + """ + if rel not in ("before", "after", "concurrent"): + raise ValueError(f"unknown order relation {rel!r}") + self.db.execute( + "INSERT OR IGNORE INTO fact_order(edge_a, edge_b, rel, quote_id) " + "VALUES(?,?,?,?)", (edge_a, edge_b, rel, quote_id)) + self.db.commit() + @staticmethod def _classify(new_val: str, new_date: str | None, old_val: str, old_date: str | None, new_node: int | None = None, old_node: int | None = None, - new_quote: int | None = None, old_quote: int | None = None) -> str: + new_quote: int | None = None, old_quote: int | None = None, + new_start: str | None = None, new_end: str | None = None, + old_start: str | None = None, old_end: str | None = None) -> str: """Deterministic taxonomy (KNOWLEDGE.md §2 + RESEARCH-derived-answers - Part 1). Cost-ordered: the cheapest signal decides. + parts 1-2). Cost-ordered: the cheapest signal decides. duplicate same normalized value coasserted same quote — one trusted sentence asserts both (conjunction: the platform sentence split into facts) supersedes subsumption with dates - temporal both dated, different dates — time series - paraphrase tails resolve to the SAME node (same institution / - office behind two surfaces) — the same fact - alternatives different tails or discriminant entity, multi-valued - reading — co-true (the polisèmia) - contradiction the residue: functional relation, incompatible values + temporal both dated (ref_date), different dates — time series + paraphrase tails resolve to the SAME node — the same fact + alternatives co-true readings: overlapping VALID-TIME windows + (two open ends overlap), or entity-ish values with + different tails + contradiction the residue: functional values, disjoint windows on + a functional relation - Phase 2 (temporal windows) will feed real start/end into this; for - now ref_date is the only date carrier, as before. + Interval arithmetic (phase 2): windows come from the text via the + extractor (t_start/t_end, end=None = OPEN). Two windows OVERLAP -> + coexistence -> alternatives. DISJOINT -> succession (never a + conflict; the world just moved on). The comparison is honest: a + window with no endpoints does not pretend to overlap. """ nv, ov = norm_name(new_val), norm_name(old_val) if nv == ov: return "duplicate" - # CO-ASSERTED: same quote — a trusted source asserting A and B in one - # sentence means the world holds both. Provenance is the cheapest - # possible signal and it is already on the row. if new_quote is not None and new_quote == old_quote: return "coasserted" - # subsumption: the new value equals the old plus extra qualifiers if ov and ov in nv and (new_date or old_date): return "supersedes" - # both dated -> time series, not contradiction if new_date and old_date and new_date != old_date: return "temporal" - # PARAPHRASE: both tails carry a resolved node and it is the SAME - # node — two surfaces of the same institution/office. The merge is - # an alias (same_as), never a conflict. + # ---- phase 2: interval arithmetic over valid-time windows ------- + new_w = _window(new_start, new_end) + old_w = _window(old_start, old_end) + if new_w and old_w: + if _overlaps(new_w, old_w): + return "alternatives" # coexistence is provable + # disjoint: succession — not a conflict, not co-true either + return "succession" if new_node and old_node and new_node == old_node: return "paraphrase" - # ALTERNATIVES vs CONTRADICTION: value type decides functionality. - # A date-like or bare-numeric value on a date-like relation is - # functional (only one can be true); two entity-ish values are - # co-true readings of a multi-valued relation (a person holds many - # offices). Temporal windows (phase 2) will tighten this with - # interval overlap; today tails-differ + entity-ish is the signal. if _looks_functional(new_val) or _looks_functional(old_val): return "contradiction" return "alternatives" diff --git a/code/knowledge/tests/temporal.py b/code/knowledge/tests/temporal.py new file mode 100644 index 0000000..b9ae55e --- /dev/null +++ b/code/knowledge/tests/temporal.py @@ -0,0 +1,161 @@ +"""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") \ No newline at end of file