knowledge: temporal restrictions layer (phase 2, RESEARCH-derived-answers Part 2)
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: <sibling index>}] — 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).
This commit is contained in:
+109
-36
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user