Files
floop/code/knowledge/store.py
T
onibot e5482bd092 feat(logic): setop engine + set gate — the Europe count computed end-to-end
A) SET GATE: enumerations are answered only from membership sets, never from mention rows (the probe early-exit that served 'Armenia, Cyprus, Georgia, Turkey' to 'what countries are in Europe' is dead). Sets carry origin_question; the gate matches stem-Jaccard>=0.5 so a set is served to its own question only. B) SETOP ENGINE: logic's first real engine — a count over list rows is computed (difference/intersection/count over norm_name'd items, table markers 'Austria*' == 'Austria'), before ROUTE, zero LLM calls, verified=True because the computation IS the check. C) Catalog honesty: knowledge 'lists are ONE fetch', logic 'how-many over lists in evidence', floop 'NOT mere size'. Plus four substrate bugs the live runs exposed: LM-proxy prompt cache (instant answers are cache hits, never trust zero latency), _context rendering list rows as scalars ('E1: 50' routed 'those countries' to user), <br> concatenation in multi-value name cells, multi-line refs leaking into values ('franceincludes the 101 departments' -> France dropped from EU -> 24 not 23). Cold E2E: Q1 50 states ingested, Q2 27 EU members ingested, Q3 difference computed = 23, cited over E1/E2. 22/22 tests.
2026-10-18 19:49:24 +02:00

283 lines
12 KiB
Python

"""KnowledgeStore: SQLite, append-only, per KNOWLEDGE.md §2 and DESIGN §2.
Laws implemented:
- append-only: no UPDATE/DELETE; corrections are retraction flags; conflicts are rows
- every edge points at a quote (the quote carries the truth, the edge is the index)
- contradiction is classified, never guessed: temporal (ref_date) / supersession /
real conflict (exposed) / retraction — the four cases of KNOWLEDGE.md §2
"""
from __future__ import annotations
import json
import re
import sqlite3
import unicodedata
from dataclasses import dataclass
from pathlib import Path
SCHEMA = """
CREATE TABLE IF NOT EXISTS documents (
id INTEGER PRIMARY KEY, url TEXT UNIQUE, source TEXT, fetched_at TEXT,
sha256 TEXT, trusted INTEGER, title TEXT
);
CREATE TABLE IF NOT EXISTS quotes (
id INTEGER PRIMARY KEY, doc_id INTEGER, verbatim TEXT, url TEXT, access_date TEXT
);
CREATE TABLE IF NOT EXISTS nodes (
id INTEGER PRIMARY KEY, norm_name TEXT, sort TEXT,
UNIQUE(norm_name, sort)
);
CREATE TABLE IF NOT EXISTS edges (
id INTEGER PRIMARY KEY, src_node INTEGER, rel TEXT, dst_value TEXT,
dst_node INTEGER, quote_id INTEGER, extraction_confidence REAL,
origin_question TEXT,
ref_date TEXT, supersedes INTEGER, preferred INTEGER DEFAULT 0,
retracted INTEGER DEFAULT 0, retraction_reason TEXT, corroboration INTEGER DEFAULT 1
);
CREATE TABLE IF NOT EXISTS conflicts (
id INTEGER PRIMARY KEY, node INTEGER, rel TEXT, value_a TEXT, value_b TEXT,
edge_a INTEGER, edge_b INTEGER, note TEXT
);
CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_node, rel);
CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(norm_name);
"""
def norm_name(name: str) -> str:
"""Conservative normalization: casefold + strip punctuation/diacritics, collapse ws."""
s = unicodedata.normalize("NFKD", name)
s = "".join(c for c in s if not unicodedata.combining(c))
s = re.sub(r"[^\w\s]", " ", s)
return re.sub(r"\s+", " ", s).strip().casefold()
def stem(word: str) -> str:
"""Tiny suffix stemmer so question words match text words (draft):
'populated'/'population' -> 'populat', 'states' -> 'state'."""
w = word.lower()
if len(w) > 3 and w.endswith("s"):
w = w[:-1]
if w.endswith("ed"):
w = w[:-2]
elif w.endswith("ing"):
w = w[:-3]
elif w.endswith("ion"):
w = w[:-3]
return w
@dataclass
class EdgeView:
src: str
rel: str
dst: str
quote: str
url: str
ref_date: str | None
corroboration: int
preferred: bool
conflict: bool
class KnowledgeStore:
"""All writes append; queries surface conflicts. File-backed (SQLite)."""
def __init__(self, path: str | Path):
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
self.db = sqlite3.connect(self.path)
self.db.executescript(SCHEMA)
self.db.commit()
self._mirror: Path | None = None
# ---- documents & quotes ------------------------------------------------
def add_document(self, url: str, title: str, fetched_at: str, sha256: str,
trusted: bool = True, source: str = "wikipedia") -> int:
cur = self.db.execute(
"INSERT OR IGNORE INTO documents(url, source, fetched_at, sha256, trusted, title) "
"VALUES(?,?,?,?,?,?)", (url, source, fetched_at, sha256, int(trusted), title))
self.db.commit()
row = self.db.execute("SELECT id FROM documents WHERE url=?", (url,)).fetchone()
return row[0]
def add_quote(self, doc_id: int, verbatim: str, url: str, access_date: str) -> int:
cur = self.db.execute(
"INSERT INTO quotes(doc_id, verbatim, url, access_date) VALUES(?,?,?,?)",
(doc_id, verbatim, url, access_date))
self.db.commit()
return cur.lastrowid
# ---- nodes & edges -------------------------------------------------------
def get_or_add_node(self, name: str, sort: str) -> int:
nn = norm_name(name)
row = self.db.execute("SELECT id FROM nodes WHERE norm_name=? AND sort=?",
(nn, sort)).fetchone()
if row:
return row[0]
cur = self.db.execute("INSERT INTO nodes(norm_name, sort) VALUES(?,?)", (nn, sort))
self.db.commit()
return cur.lastrowid
def add_edge(self, src_name: str, rel: str, dst_value: str, quote_id: int,
src_sort: str = "CONCEPT", dst_node_name: str | None = None,
dst_sort: str = "CONCEPT", confidence: float = 0.8,
ref_date: str | None = None,
origin_question: str | None = None) -> int | None:
"""Add an edge, applying the four contradiction cases (KNOWLEDGE.md §2).
Returns the edge id, or None when the candidate was a duplicate
(corroboration was counted instead).
"""
src = self.get_or_add_node(src_name, src_sort)
dst_node = self.get_or_add_node(dst_node_name, dst_sort) if dst_node_name else None
# exact duplicate -> corroboration
dup = self.db.execute(
"SELECT id FROM edges WHERE src_node=? AND rel=? AND dst_value=? AND retracted=0",
(src, rel, dst_value)).fetchone()
if dup:
self.db.execute("UPDATE edges SET corroboration = corroboration + 1 WHERE id=?",
(dup[0],))
self.db.commit()
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=? "
"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) VALUES(?,?,?,?,?,?,?,?,0)",
(src, rel, dst_value, dst_node, quote_id, confidence, origin_question, ref_date))
edge_id = cur.lastrowid
for other_id, other_val, other_date in others:
case = self._classify(new_val=dst_value, new_date=ref_date,
old_val=other_val, old_date=other_date)
if case == "duplicate":
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
else: # contradiction
self.db.execute(
"INSERT INTO conflicts(node, rel, value_a, value_b, edge_a, edge_b) "
"VALUES(?,?,?,?,?,?)", (src, rel, other_val, dst_value, other_id, edge_id))
self.db.commit()
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)."""
nv, ov = norm_name(new_val), norm_name(old_val)
if nv == ov:
return "duplicate"
# 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"
# ---- queries --------------------------------------------------------------
def probe(self, seeds: list[str], depth: int = 1, limit: int = 20) -> list[EdgeView]:
"""KG-first probe: stems match node names AND edge relations/values.
Entity questions hit via node names; ranking/property questions
(whose answer entity is unknown) hit via the relation. Corroboration-
weighted, conflicts surfaced, retracted skipped."""
views: list[EdgeView] = []
seen_nodes: set[int] = set()
seen_edges: set[int] = set()
stems = {stem(s) for s in seeds if len(s) > 2}
for st in sorted(stems):
# entity matches: node names containing the stem (or vice versa)
rows = self.db.execute(
"SELECT id, norm_name FROM nodes WHERE norm_name LIKE ? OR ? LIKE '%' || norm_name || '%'",
(f"%{st}%", st)).fetchall()
for nid, _nname in rows:
if nid in seen_nodes:
continue
seen_nodes.add(nid)
self._collect_edges(nid, views, seen_edges, limit)
# property matches: relation or value containing the stem
erows = self.db.execute(
"SELECT id FROM edges WHERE retracted=0 AND (rel LIKE ? OR dst_value LIKE ?) LIMIT ?",
(f"%{st}%", f"%{st}%", limit)).fetchall()
for (eid,) in erows:
if eid not in seen_edges:
self._collect_edge_by_id(eid, views, seen_edges)
views.sort(key=lambda v: -v.corroboration)
return views
def _collect_edges(self, nid: int, views: list, seen: set, limit: int) -> None:
for e in self.db.execute(
"SELECT e.id, e.rel, e.dst_value, e.dst_node, e.ref_date, e.corroboration, "
"e.preferred, e.retracted, q.verbatim, q.url, n.norm_name "
"FROM edges e JOIN quotes q ON q.id=e.quote_id "
"JOIN nodes n ON n.id=e.src_node "
"WHERE e.src_node=? AND e.retracted=0 ORDER BY e.corroboration DESC LIMIT ?",
(nid, limit)):
self._append_view(e, views, seen)
def _collect_edge_by_id(self, eid: int, views: list, seen: set) -> None:
e = self.db.execute(
"SELECT e.id, e.rel, e.dst_value, e.dst_node, e.ref_date, e.corroboration, "
"e.preferred, e.retracted, q.verbatim, q.url, n.norm_name "
"FROM edges e JOIN quotes q ON q.id=e.quote_id "
"JOIN nodes n ON n.id=e.src_node WHERE e.id=?", (eid,)).fetchone()
if e:
self._append_view(e, views, seen)
def _append_view(self, e, views: list, seen: set) -> None:
(eid, rel, dstv, dstn, rd, cor, pref, retr, quote, url, sname) = e
if eid in seen:
return
seen.add(eid)
conflict = self.db.execute(
"SELECT 1 FROM conflicts WHERE edge_a=? OR edge_b=?", (eid, eid)).fetchone()
views.append(EdgeView(
src=sname, rel=rel, dst=dstv, quote=quote, url=url,
ref_date=rd, corroboration=cor, preferred=bool(pref),
conflict=bool(conflict)))
# ---- membership queries (LIST path) --------------------------------------
def member_sets(self) -> list[str]:
"""Distinct set names that have membership edges (rel='member_of')."""
rows = self.db.execute(
"SELECT DISTINCT dst_value FROM edges WHERE rel='member_of' AND retracted=0"
).fetchall()
return [r[0] for r in rows]
def list_members(self, set_name: str) -> list[str]:
"""ALL elements of a set: every member_of edge pointing at set_name.
Deterministic and COMPLETE with respect to what was ingested (the
ingestion writes one edge per table row, untruncated)."""
rows = self.db.execute(
"SELECT DISTINCT n.norm_name FROM edges e "
"JOIN nodes n ON n.id=e.src_node "
"WHERE e.rel='member_of' AND e.retracted=0 AND lower(e.dst_value)=lower(?)",
(set_name,)).fetchall()
return sorted(r[0] for r in rows)
def set_origins(self) -> list[tuple[str, str]]:
"""(set_name, origin_question) for every membership set — the gate
matches a set to its own question, never to a different one."""
rows = self.db.execute(
"SELECT DISTINCT dst_value, origin_question FROM edges "
"WHERE rel='member_of' AND retracted=0 AND origin_question IS NOT NULL"
).fetchall()
return [(r[0], r[1]) for r in rows]
def set_provenance(self, set_name: str) -> tuple[str, str]:
"""(quote, url) of the first member edge of a set — provenance for
list answers served from the KG."""
row = self.db.execute(
"SELECT q.verbatim, q.url FROM edges e JOIN quotes q ON q.id=e.quote_id "
"WHERE e.rel='member_of' AND e.retracted=0 AND lower(e.dst_value)=lower(?) "
"LIMIT 1", (set_name,)).fetchone()
return (row[0], row[1]) if row else ("", "")
def close(self) -> None:
self.db.close()