store/expert/machine: keep source order end-to-end; refuse fake top-N

log-09 bug: a KG-served set answered the fan-out top-3 with adda, adige,
arno — the alphabetical list_members order masquerading as a ranking.

- edges.list_ord (auto-migrated): each member_of edge records its row
  position in the source table; list_members(ordered=True) returns source
  order, list_is_ordered() tells whether the set has proven order
- ingest writes ordinals; fresh-serve and _serve_set keep table order and
  set coverage.ranked accordingly
- fan-out top-N: slices ONLY ranked lists; an unranked list refuses the
  slice, expands all entities, and says so in notes + thinking (never
  silently alphabetical)
- regression test: Po/Adige/Tiber first; unordered set -> all expanded
This commit is contained in:
2026-10-19 20:31:04 +02:00
parent 2489ce3898
commit 06124a0198
5 changed files with 132 additions and 26 deletions
+36 -12
View File
@@ -95,11 +95,16 @@ class KnowledgeStore:
"""Idempotent, additive migrations. CREATE TABLE IF NOT EXISTS never
upgrades an existing file, so stores predating a column change must
be migrated here or every query touching the column crashes
(2026-10-19: edges.origin_question, added with the set gate)."""
(2026-10-19: edges.origin_question, added with the set gate;
2026-10-20: edges.list_ord, the member's position in the source
table — a ranked table's order IS information and was being lost)."""
cols = {r[1] for r in self.db.execute("PRAGMA table_info(edges)")}
if "origin_question" not in cols:
self.db.execute("ALTER TABLE edges ADD COLUMN origin_question TEXT")
self.db.commit()
if "list_ord" not in cols:
self.db.execute("ALTER TABLE edges ADD COLUMN list_ord INTEGER")
self.db.commit()
# ---- documents & quotes ------------------------------------------------
def add_document(self, url: str, title: str, fetched_at: str, sha256: str,
@@ -133,7 +138,8 @@ class KnowledgeStore:
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:
origin_question: str | None = None,
list_ord: int | 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
@@ -157,8 +163,10 @@ class KnowledgeStore:
(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))
"extraction_confidence, origin_question, ref_date, preferred, list_ord) "
"VALUES(?,?,?,?,?,?,?,?,0,?)",
(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:
case = self._classify(new_val=dst_value, new_date=ref_date,
@@ -261,16 +269,32 @@ class KnowledgeStore:
).fetchall()
return [r[0] for r in rows]
def list_members(self, set_name: str) -> list[str]:
def list_members(self, set_name: str, ordered: bool = False) -> 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)
ingestion writes one edge per table row, untruncated).
`ordered=True` returns members in SOURCE TABLE order when the ingest
recorded ordinals (ranked tables rank); sets ingested before ordinals
existed return [] (the caller must NOT pretend they are ranked)."""
base = ("SELECT DISTINCT e.id, n.norm_name, e.list_ord 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(?)")
rows = self.db.execute(base, (set_name,)).fetchall()
if ordered:
if any(r[2] is None for r in rows):
return [] # ordinal-free set: order is unknown, never guessed
return [r[1] for r in sorted(rows, key=lambda r: r[2])]
return sorted(r[1] for r in rows)
def list_is_ordered(self, set_name: str) -> bool:
"""True when every member edge of this set carries a list ordinal."""
row = self.db.execute(
"SELECT COUNT(*), COUNT(list_ord) FROM edges "
"WHERE rel='member_of' AND retracted=0 AND lower(dst_value)=lower(?)",
(set_name,)).fetchone()
return bool(row) and row[0] > 0 and row[0] == row[1]
def set_origins(self) -> list[tuple[str, str]]:
"""(set_name, origin_question) for every membership set — the gate