knowledge: conflict taxonomy at merge (phase 1, RESEARCH-derived-answers Part 1)
The four-case classifier conflated conjunction, paraphrase and polisèmia
into "contradiction" — the live KG after one Pedro run held 20 conflict
pairs, ZERO real ones. The taxonomy (deterministic, cost-ordered):
co-asserted same quote_id — one trusted sentence asserts both values
(the platform sentence split into 5 "called for" facts)
paraphrase tails resolve to the same node — the same fact in two
surfaces: MERGE (same_as alias, append-only; the canonical
edge's corroboration goes up, no conflict row)
alternatives entity-ish values, different tails — co-true readings of a
multi-valued relation (THE three presidencies). New table
+ alternatives_of(src, rel): the ambiguity substrate,
detected at INGEST, deterministically — the audit no
longer needs to re-derive it at judge time
temporal both dated — unchanged
contradiction the residue: functional values (dates/quantities —
_looks_functional: numbers with at most unit/month words;
pure entity words are readings, not data)
Files: store.py (_classify 4->7 cases, migrations for alternatives +
same_as, alternatives_of), tests taxonomy.py (6/6: the 20-pair inventory
as fixtures), store.py test updated to the new law (different quotes for
the contradiction pair — same-quote is co-asserted by law).
Known scope notes: same_as is recorded but not yet consumed by the
probe/render (phase 4); the three-presidencies-in-one-sentence shape
stays conjunction (the live readings came from different quotes).
This commit is contained in:
+141
-7
@@ -54,6 +54,39 @@ def norm_name(name: str) -> str:
|
||||
return re.sub(r"\s+", " ", s).strip().casefold()
|
||||
|
||||
|
||||
# a value is FUNCTIONAL (only one can be true) when it is date-like or a
|
||||
# bare number/quantity: '29 February 1972', '2018', '15', '1,006 km',
|
||||
# '17 november 2023'. Two entity-ish values ('prime minister of Spain' vs
|
||||
# 'Secretary-General of the PSOE') are co-true readings of a multi-valued
|
||||
# relation instead. The signal: no entity WORDS survive after dropping
|
||||
# numbers, month names, and units.
|
||||
_MONTHS = {"january", "february", "march", "april", "may", "june", "july",
|
||||
"august", "september", "october", "november", "december",
|
||||
"gener", "febrer", "marc", "abril", "maig", "juny", "juliol",
|
||||
"agost", "setembre", "octubre", "novembre", "desembre",
|
||||
"de", "d", "of", "the", "in", "on", "at", "since", "until"}
|
||||
_UNITS = {"km", "km2", "mi", "m", "kg", "s", "cu", "ft", "ms", "mm", "cm",
|
||||
"people", "inhabitants", "days", "years", "months", "hours",
|
||||
"percent", "m3", "m3/s", "bps", "kb", "mb", "gb", "%", "eur",
|
||||
"usd", "millions", "billions"}
|
||||
|
||||
|
||||
def _looks_functional(value: str) -> bool:
|
||||
"""True when the value is date-like or a bare quantity (phase 1 signal:
|
||||
functional relations keep the contradiction case; entity-ish pairs go
|
||||
to alternatives). A value with two or more entity words is NOT
|
||||
functional ('prime minister of Spain'); a date or quantity is.
|
||||
A lone entity word ('Spain') is an entity reading, not a datum —
|
||||
functional needs NUMBERS with at most one unit/month word."""
|
||||
words = re.findall(r"[A-Za-zÀ-ÿ]{1,}", value or "")
|
||||
entity_words = [w for w in words
|
||||
if w.lower() not in _MONTHS and w.lower() not in _UNITS]
|
||||
has_number = bool(re.search(r"\d", value or ""))
|
||||
if not has_number:
|
||||
return False # pure words: an entity reading (Spain / PSOE)
|
||||
return len(entity_words) < 2
|
||||
|
||||
|
||||
def stem(word: str) -> str:
|
||||
"""Tiny suffix stemmer so question words match text words (draft):
|
||||
'populated'/'population' -> 'populat', 'states' -> 'state'."""
|
||||
@@ -109,6 +142,25 @@ class KnowledgeStore:
|
||||
if "list_ord" not in cols:
|
||||
self.db.execute("ALTER TABLE edges ADD COLUMN list_ord INTEGER")
|
||||
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
|
||||
# the world holds BOTH: it is the ambiguity substrate, never an
|
||||
# error state.
|
||||
self.db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS alternatives ("
|
||||
" id INTEGER PRIMARY KEY, node INTEGER, rel TEXT, "
|
||||
" value_a TEXT, value_b TEXT, edge_a INTEGER, edge_b INTEGER, "
|
||||
" UNIQUE(node, rel, edge_a, edge_b))")
|
||||
self.db.commit()
|
||||
# same_as: paraphrase merges. Append-only law — the merge never
|
||||
# deletes; the alias pair is recorded and the canonical edge's
|
||||
# corroboration goes up.
|
||||
self.db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS same_as ("
|
||||
" id INTEGER PRIMARY KEY, edge_a INTEGER, edge_b INTEGER, "
|
||||
" UNIQUE(edge_a, edge_b))")
|
||||
self.db.commit()
|
||||
|
||||
# ---- documents & quotes ------------------------------------------------
|
||||
def add_document(self, url: str, title: str, fetched_at: str, sha256: str,
|
||||
@@ -162,7 +214,7 @@ class KnowledgeStore:
|
||||
return None
|
||||
# contradiction classification: same src+rel, different value, not retracted
|
||||
others = self.db.execute(
|
||||
"SELECT id, dst_value, ref_date FROM edges WHERE src_node=? AND rel=? "
|
||||
"SELECT id, dst_value, ref_date, dst_node, quote_id 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(
|
||||
@@ -172,16 +224,32 @@ class KnowledgeStore:
|
||||
(src, rel, dst_value, dst_node, quote_id, confidence, origin_question,
|
||||
ref_date, list_ord))
|
||||
edge_id = cur.lastrowid
|
||||
for other_id, other_val, other_date in others:
|
||||
for other_id, other_val, other_date, other_dn, other_q in others:
|
||||
case = self._classify(new_val=dst_value, new_date=ref_date,
|
||||
old_val=other_val, old_date=other_date)
|
||||
if case == "duplicate":
|
||||
old_val=other_val, old_date=other_date,
|
||||
new_node=dst_node, old_node=other_dn,
|
||||
new_quote=quote_id, old_quote=other_q)
|
||||
if case in ("duplicate", "paraphrase"):
|
||||
if case == "paraphrase":
|
||||
self.db.execute(
|
||||
"INSERT OR IGNORE INTO same_as(edge_a, edge_b) VALUES(?,?)",
|
||||
(other_id, edge_id))
|
||||
self.db.execute(
|
||||
"UPDATE edges SET corroboration = corroboration + 1 WHERE id=?",
|
||||
(other_id,))
|
||||
continue
|
||||
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 == "alternatives":
|
||||
self.db.execute(
|
||||
"INSERT OR IGNORE INTO alternatives(node, rel, value_a, value_b, edge_a, edge_b) "
|
||||
"VALUES(?,?,?,?,?,?)",
|
||||
(src, rel, other_val, dst_value, other_id, edge_id))
|
||||
else: # contradiction
|
||||
self.db.execute(
|
||||
"INSERT INTO conflicts(node, rel, value_a, value_b, edge_a, edge_b) "
|
||||
@@ -190,18 +258,84 @@ class KnowledgeStore:
|
||||
return edge_id
|
||||
|
||||
@staticmethod
|
||||
def _classify(new_val: str, new_date: str | None, old_val: str, old_date: str | None) -> str:
|
||||
"""Deterministic four-case classification (KNOWLEDGE.md §2)."""
|
||||
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:
|
||||
"""Deterministic taxonomy (KNOWLEDGE.md §2 + RESEARCH-derived-answers
|
||||
Part 1). 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
|
||||
|
||||
Phase 2 (temporal windows) will feed real start/end into this; for
|
||||
now ref_date is the only date carrier, as before.
|
||||
"""
|
||||
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"
|
||||
return "contradiction"
|
||||
# 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.
|
||||
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"
|
||||
|
||||
# ---- phase 1: alternatives query (the ambiguity substrate) -------------
|
||||
def alternatives_of(self, src_name: str, rel: str) -> list[tuple[str, str]]:
|
||||
"""The co-true readings of one (src, rel): the alternatives bucket.
|
||||
|
||||
Returns [(value, tail_node_name), ...] — the set the audit and the
|
||||
render consume (the ambiguity was detected at INGEST, deterministi-
|
||||
cally; nobody needs to re-derive it at judge time). Values appear
|
||||
once, first-seen order; None tail when the edge carries no node.
|
||||
"""
|
||||
src = self.db.execute("SELECT id FROM nodes WHERE norm_name=?",
|
||||
(norm_name(src_name),)).fetchone()
|
||||
if not src:
|
||||
return []
|
||||
rows = self.db.execute(
|
||||
"SELECT a.value_a, a.value_b, na.norm_name, nb.norm_name "
|
||||
"FROM alternatives a "
|
||||
"LEFT JOIN edges ea ON ea.id = a.edge_a "
|
||||
"LEFT JOIN edges eb ON eb.id = a.edge_b "
|
||||
"LEFT JOIN nodes na ON na.id = ea.dst_node "
|
||||
"LEFT JOIN nodes nb ON nb.id = eb.dst_node "
|
||||
"WHERE a.node=? AND a.rel=? ORDER BY a.id",
|
||||
(src[0], rel)).fetchall()
|
||||
seen: list[tuple[str, str]] = []
|
||||
for va, vb, ta, tb in rows:
|
||||
for val, tail in ((va, ta), (vb, tb)):
|
||||
key = (val, tail or "")
|
||||
if key not in [(s, t or "") for s, t in seen]:
|
||||
seen.append((val, tail or ""))
|
||||
return [(v, t or None) for v, t in seen]
|
||||
|
||||
# ---- queries --------------------------------------------------------------
|
||||
def probe(self, seeds: list[str], depth: int = 1, limit: int = 20) -> list[EdgeView]:
|
||||
|
||||
Reference in New Issue
Block a user