research/semantic-kg: semantic probe + conflict taxonomy + temporal layer + derived-answer prover #24

Merged
onibot merged 14 commits from research/semantic-kg into main 2026-10-25 21:40:18 +01:00
3 changed files with 338 additions and 11 deletions
Showing only changes of commit f32a6db531 - Show all commits
+140 -6
View File
@@ -54,6 +54,39 @@ def norm_name(name: str) -> str:
return re.sub(r"\s+", " ", s).strip().casefold() 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: def stem(word: str) -> str:
"""Tiny suffix stemmer so question words match text words (draft): """Tiny suffix stemmer so question words match text words (draft):
'populated'/'population' -> 'populat', 'states' -> 'state'.""" 'populated'/'population' -> 'populat', 'states' -> 'state'."""
@@ -109,6 +142,25 @@ class KnowledgeStore:
if "list_ord" not in cols: if "list_ord" not in cols:
self.db.execute("ALTER TABLE edges ADD COLUMN list_ord INTEGER") self.db.execute("ALTER TABLE edges ADD COLUMN list_ord INTEGER")
self.db.commit() 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 ------------------------------------------------ # ---- documents & quotes ------------------------------------------------
def add_document(self, url: str, title: str, fetched_at: str, sha256: str, def add_document(self, url: str, title: str, fetched_at: str, sha256: str,
@@ -162,7 +214,7 @@ class KnowledgeStore:
return None return None
# contradiction classification: same src+rel, different value, not retracted # contradiction classification: same src+rel, different value, not retracted
others = self.db.execute( 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)", "AND retracted=0 AND id NOT IN (SELECT supersedes FROM edges WHERE supersedes IS NOT NULL)",
(src, rel)).fetchall() (src, rel)).fetchall()
cur = self.db.execute( cur = self.db.execute(
@@ -172,16 +224,32 @@ class KnowledgeStore:
(src, rel, dst_value, dst_node, quote_id, confidence, origin_question, (src, rel, dst_value, dst_node, quote_id, confidence, origin_question,
ref_date, list_ord)) ref_date, list_ord))
edge_id = cur.lastrowid 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, case = self._classify(new_val=dst_value, new_date=ref_date,
old_val=other_val, old_date=other_date) old_val=other_val, old_date=other_date,
if case == "duplicate": 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 continue
elif case == "supersedes": elif case == "supersedes":
self.db.execute("UPDATE edges SET supersedes=? WHERE id=?", (other_id, edge_id)) 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,)) self.db.execute("UPDATE edges SET preferred=1 WHERE id=?", (edge_id,))
elif case == "temporal": elif case == "temporal":
pass # both coexist; queries pick by date 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 else: # contradiction
self.db.execute( self.db.execute(
"INSERT INTO conflicts(node, rel, value_a, value_b, edge_a, edge_b) " "INSERT INTO conflicts(node, rel, value_a, value_b, edge_a, edge_b) "
@@ -190,18 +258,84 @@ class KnowledgeStore:
return edge_id return edge_id
@staticmethod @staticmethod
def _classify(new_val: str, new_date: str | None, old_val: str, old_date: str | None) -> str: def _classify(new_val: str, new_date: str | None, old_val: str, old_date: str | None,
"""Deterministic four-case classification (KNOWLEDGE.md §2).""" 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) nv, ov = norm_name(new_val), norm_name(old_val)
if nv == ov: if nv == ov:
return "duplicate" 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 # subsumption: the new value equals the old plus extra qualifiers
if ov and ov in nv and (new_date or old_date): if ov and ov in nv and (new_date or old_date):
return "supersedes" return "supersedes"
# both dated -> time series, not contradiction # both dated -> time series, not contradiction
if new_date and old_date and new_date != old_date: if new_date and old_date and new_date != old_date:
return "temporal" 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.
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 "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 -------------------------------------------------------------- # ---- queries --------------------------------------------------------------
def probe(self, seeds: list[str], depth: int = 1, limit: int = 20) -> list[EdgeView]: def probe(self, seeds: list[str], depth: int = 1, limit: int = 20) -> list[EdgeView]:
+9 -4
View File
@@ -73,11 +73,16 @@ def test_store_four_cases(tmp="/tmp/floop_kg_test.sqlite"):
assert a and b assert a and b
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0] conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert conflicts == 0, "dated different values are a time series, not a conflict" assert conflicts == 0, "dated different values are a time series, not a conflict"
# contradiction: same rel, undated different values -> exposed conflict # contradiction: same rel, undated different FUNCTIONAL values -> exposed conflict
c1 = ks.add_edge("Seine", "length_km", "777", q1) # (phase 1 taxonomy: entity-ish pairs are alternatives; numeric/date
c2 = ks.add_edge("Seine", "length_km", "776", q1) # values on a functional relation keep the contradiction. Different
# quotes — same-quote pairs are co-asserted conjunction, by law.)
qc1 = ks.add_quote(doc, "The Seine is 777 kilometres long.", "url", "d")
qc2 = ks.add_quote(doc, "One source lists the Seine at 776 kilometres.", "url", "d")
c1 = ks.add_edge("Seine", "length_km", "777", qc1)
c2 = ks.add_edge("Seine", "length_km", "776", qc2)
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0] conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert conflicts == 1, "undated different values must be exposed as conflict" assert conflicts == 1, "undated different functional values must be exposed as conflict"
# probe: seeds find edges with quotes # probe: seeds find edges with quotes
rows = ks.probe(["Loire", "loire"]) rows = ks.probe(["Loire", "loire"])
assert any(r.rel == "longest_river_of" and r.dst == "France" for r in rows) assert any(r.rel == "longest_river_of" and r.dst == "France" for r in rows)
+188
View File
@@ -0,0 +1,188 @@
"""Conflict taxonomy tests (phase 1, RESEARCH-derived-answers.md Part 1).
The four-case classifier conflated conjunction, paraphrase and polisèmia
into "contradiction" — 20 conflict pairs in the live KG after one Pedro
run, ZERO real contradictions. The taxonomy (deterministic, cost-ordered):
co-asserted same quote_id — one trusted sentence asserts both values
(conjunction, never a conflict)
paraphrase discriminant-free surface OR tails resolving to the same
node — the same fact said differently: MERGE (same_as,
append-only; corroboration up, no conflict row)
alternatives different discriminant entity, tails resolve to different
nodes, multi-valued relation — co-true readings (the
polisèmia: Spain / PSOE / SI). Recorded as alternatives,
not contradictions.
temporal both dated (time series) — unchanged law
contradiction what survives: functional relation, incompatible values
Laws under test (fixtures = the live 20-pair inventory):
1. The platform sentence split into 5 "called for" facts with the SAME
quote never yields conflicts (co-asserted).
2. "Prime Minister of Spain" vs "president of the Government (Spanish:
Presidente del Gobierno)" merges (paraphrase — tails resolve to the
same office; no conflict row).
3. The three presidencies (PM-of-Spain / SG-of-PSOE / president-of-SI)
land in the alternatives bucket, pairwise — never "contradiction".
4. Two different birth dates stay a real contradiction (functional rel).
5. Both-dated pairs stay temporal.
6. The alternatives bucket is queryable: the store exposes, per
(src, rel), the co-true value set with their tails — the ambiguity
substrate for the audit and the render.
Run: .venv/bin/python knowledge/tests/taxonomy.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.store import KnowledgeStore, norm_name
def make_store() -> tuple[KnowledgeStore, str]:
d = tempfile.mkdtemp()
return KnowledgeStore(f"{d}/kg.sqlite"), d
def add_doc(store: KnowledgeStore, text: str) -> int:
"""One document + one quote carrying the given verbatim text."""
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")
def test_coasserted_never_conflicts():
"""The platform sentence: 5 facts, one quote — conjunction, not conflict."""
store, _ = make_store()
q = add_doc(store, "Presenting a platform based on political regeneration, "
"Sánchez called for constitutional reforms establishing "
"federalism; a new progressive fiscal policy; extending "
"the welfare state to all citizens; increasing the "
"membership of labour unions; and regaining the "
"confidence of Socialist voters.")
for dst in ("constitutional reforms establishing federalism",
"a new progressive fiscal policy",
"extending the welfare state to all citizens",
"increasing the membership of labour unions",
"regaining the confidence of Socialist voters"):
store.add_edge("pedro sanchez", "called for", dst, quote_id=q)
n = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert n == 0, f"co-asserted facts must not conflict (got {n})"
print("ok: 5 same-quote facts -> 0 conflicts (co-asserted conjunction)")
def test_paraphrase_merges():
"""Same office, two surfaces, tails resolve to the same node -> merge."""
store, _ = make_store()
q1 = add_doc(store, "The prime minister of Spain, officially the president "
"of the Government, is the head of government of Spain.")
q2 = add_doc(store, "The head of government of Spain is the Prime Minister "
"of Spain, often called president of the Government.")
a = store.add_edge("pedro sanchez", "position held",
"prime minister of Spain",
dst_node_name="Prime Minister of Spain", quote_id=q1)
b = store.add_edge("pedro sanchez", "position held",
"president of the Government (Spanish: Presidente del Gobierno)",
dst_node_name="Prime Minister of Spain", quote_id=q2)
assert a and b, "both edges ingested"
n = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert n == 0, f"a paraphrase must merge, not conflict (got {n})"
# corroboration counted on the canonical edge, same_as alias recorded
canon = store.db.execute(
"SELECT corroboration FROM edges WHERE id=?", (min(a, b),)).fetchone()
assert canon and canon[0] >= 2, "paraphrase merge must corroborate the canonical edge"
aliases = store.db.execute(
"SELECT COUNT(*) FROM same_as WHERE edge_a IN (?,?) OR edge_b IN (?,?)",
(a, b, a, b)).fetchone()[0]
assert aliases >= 1, "the merge must record a same_as alias (append-only law)"
print("ok: paraphrase merges (canonical corroborated, same_as recorded)")
def test_three_presidencies_are_alternatives():
"""THE polisèmia: three offices, three institutions, co-true.
Live shape (run 090402 inventory): the three readings came from
DIFFERENT sentences — the intro sentence carries the party/SI offices,
the lead paragraph the premiership. Same-quote co-assertion would be
the conjunction case; the presidencies are separate assertions and
land in alternatives."""
store, _ = make_store()
q1 = add_doc(store, "He has been the prime minister of Spain since 2018.")
q2 = add_doc(store, "A member of the Spanish Socialist Workers' Party "
"(PSOE), he is also Secretary-General of the party "
"since 2017.")
q3 = add_doc(store, "He is the ninth president of Socialist "
"International since 2022.")
store.add_edge("pedro sanchez", "position held",
"prime minister of Spain since 2018",
dst_node_name="Spain", quote_id=q1)
store.add_edge("pedro sanchez", "position held",
"Secretary-General of the PSOE since 2017",
dst_node_name="PSOE", quote_id=q2)
store.add_edge("pedro sanchez", "position held",
"ninth president of Socialist International since 2022",
dst_node_name="Socialist International", quote_id=q3)
real = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
alts = store.db.execute("SELECT COUNT(*) FROM alternatives").fetchone()[0]
assert real == 0, f"co-true readings are not contradictions (got {real})"
assert alts == 3, f"three pairwise alternatives expected (got {alts})"
print("ok: three presidencies -> 3 alternatives, 0 contradictions")
def test_alternatives_queryable():
"""The ambiguity substrate: per (src, rel) the co-true value set."""
store, _ = make_store()
q1 = add_doc(store, "He has been the prime minister of Spain since 2018.")
q2 = add_doc(store, "He is also Secretary-General of the party since 2017.")
store.add_edge("pedro sanchez", "position held",
"prime minister of Spain since 2018", dst_node_name="Spain", quote_id=q1)
store.add_edge("pedro sanchez", "position held",
"Secretary-General of the PSOE since 2017",
dst_node_name="PSOE", quote_id=q2)
got = store.alternatives_of("pedro sanchez", "position held")
vals = {norm_name(v)[:30] for v, _t in got}
assert len(got) == 2 and len(vals) == 2, f"expected 2 alternative readings, got {got}"
print(f"ok: alternatives_of returns the co-true set: {[v[:40] for v, _ in got]}")
def test_functional_contradiction_survives():
"""Two different birth dates: a REAL contradiction, kept."""
store, _ = make_store()
q1 = add_doc(store, "Pedro Sánchez was born on 29 February 1972.")
q2 = add_doc(store, "Pedro Sánchez was born on 28 February 1972.")
store.add_edge("pedro sanchez", "date of birth", "29 February 1972", quote_id=q1)
store.add_edge("pedro sanchez", "date of birth", "28 February 1972", quote_id=q2)
real = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert real == 1, f"a functional contradiction must stay (got {real})"
print("ok: two birth dates -> 1 real contradiction (functional rel)")
def test_temporal_unchanged():
"""Both dated pairs: temporal, coexist — the old law, untouched."""
store, _ = make_store()
q1 = add_doc(store, "In 2014 he was elected Secretary-General.")
q2 = add_doc(store, "In 2017 he was re-elected Secretary-General.")
store.add_edge("pedro sanchez", "elected secretary-general",
"in 2014", ref_date="2014", quote_id=q1)
store.add_edge("pedro sanchez", "elected secretary-general",
"in 2017", ref_date="2017", quote_id=q2)
n = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert n == 0, f"dated pairs are temporal, not conflicts (got {n})"
print("ok: both-dated pair stays temporal, no conflict")
if __name__ == "__main__":
test_coasserted_never_conflicts()
test_paraphrase_merges()
test_three_presidencies_are_alternatives()
test_alternatives_queryable()
test_functional_contradiction_survives()
test_temporal_unchanged()
print("\ntaxonomy: 6/6 ok")