store: auto-migrate old KGs (edges.origin_question); machine: abort honestly on dead LM
- KnowledgeStore._migrate(): idempotent additive migration on open — a pre-2026-10-19 KG no longer crashes the set gate with 'no such column' - _lm_dead(): transport/timeout deaths abort the run with notes (no answer beats a made-up one); code bugs still crash loudly - tests: migration from a hand-built old-schema store; LM-death abort (24/24)
This commit is contained in:
@@ -47,6 +47,23 @@ class RunReport:
|
|||||||
elapsed_s: float = 0.0
|
elapsed_s: float = 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def _lm_dead(e: BaseException) -> bool:
|
||||||
|
"""Is this exception the LM dying (transport/timeout), not a code bug?
|
||||||
|
Walks the cause chain: dspy wraps transport deaths in LM* classes
|
||||||
|
(LMTransportError) over raw TimeoutErrors. Code bugs must still crash
|
||||||
|
loudly in development."""
|
||||||
|
seen: list[BaseException] = []
|
||||||
|
cur: BaseException | None = e
|
||||||
|
while cur is not None and cur not in seen:
|
||||||
|
seen.append(cur)
|
||||||
|
if type(cur).__name__.startswith("LM"):
|
||||||
|
return True
|
||||||
|
if "timed out" in str(cur).lower():
|
||||||
|
return True
|
||||||
|
cur = cur.__cause__ or cur.__context__
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
class FloopRun:
|
class FloopRun:
|
||||||
"""One FLOOP execution over one question (top-level or recursive child)."""
|
"""One FLOOP execution over one question (top-level or recursive child)."""
|
||||||
|
|
||||||
@@ -95,6 +112,13 @@ class FloopRun:
|
|||||||
except BudgetExhausted:
|
except BudgetExhausted:
|
||||||
self.notes.append(f"budget exhausted at llm_calls={self.budget.llm_calls}")
|
self.notes.append(f"budget exhausted at llm_calls={self.budget.llm_calls}")
|
||||||
break
|
break
|
||||||
|
except Exception as e: # noqa: BLE001 — LM deaths abort honestly
|
||||||
|
if _lm_dead(e):
|
||||||
|
self.notes.append(
|
||||||
|
f"LM unreachable at llm_calls={self.budget.llm_calls} "
|
||||||
|
f"({type(e).__name__}); aborting — no answer beats a made-up one")
|
||||||
|
break
|
||||||
|
raise
|
||||||
return self._finish(t0)
|
return self._finish(t0)
|
||||||
|
|
||||||
# ---- steps -------------------------------------------------------------
|
# ---- steps -------------------------------------------------------------
|
||||||
@@ -267,6 +291,12 @@ class FloopRun:
|
|||||||
self.streams.final(answer)
|
self.streams.final(answer)
|
||||||
except BudgetExhausted:
|
except BudgetExhausted:
|
||||||
self.notes.append("budget died before the answer step")
|
self.notes.append("budget died before the answer step")
|
||||||
|
except Exception as e: # noqa: BLE001 — a dead LM answers nothing
|
||||||
|
if _lm_dead(e):
|
||||||
|
self.notes.append(f"LM unreachable before synthesis ({type(e).__name__}); "
|
||||||
|
"evidence is kept, the answer is not written")
|
||||||
|
else:
|
||||||
|
raise
|
||||||
return RunReport(
|
return RunReport(
|
||||||
goal=self.query, final_answer=answer, verified=verified,
|
goal=self.query, final_answer=answer, verified=verified,
|
||||||
llm_calls=self.budget.llm_calls, engine_calls=self.engine_calls,
|
llm_calls=self.budget.llm_calls, engine_calls=self.engine_calls,
|
||||||
|
|||||||
@@ -87,9 +87,20 @@ class KnowledgeStore:
|
|||||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
self.db = sqlite3.connect(self.path)
|
self.db = sqlite3.connect(self.path)
|
||||||
self.db.executescript(SCHEMA)
|
self.db.executescript(SCHEMA)
|
||||||
|
self._migrate()
|
||||||
self.db.commit()
|
self.db.commit()
|
||||||
self._mirror: Path | None = None
|
self._mirror: Path | None = None
|
||||||
|
|
||||||
|
def _migrate(self) -> None:
|
||||||
|
"""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)."""
|
||||||
|
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()
|
||||||
|
|
||||||
# ---- 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,
|
||||||
trusted: bool = True, source: str = "wikipedia") -> int:
|
trusted: bool = True, source: str = "wikipedia") -> int:
|
||||||
|
|||||||
@@ -85,6 +85,47 @@ def test_store_four_cases(tmp="/tmp/floop_kg_test.sqlite"):
|
|||||||
print("ok test_store_four_cases")
|
print("ok test_store_four_cases")
|
||||||
|
|
||||||
|
|
||||||
|
def test_migration_old_store():
|
||||||
|
"""A pre-2026-10-19 KG (no origin_question column) must migrate on open,
|
||||||
|
not crash the set gate (Emili's 2026-10-19 home run)."""
|
||||||
|
import sqlite3
|
||||||
|
p = Path("/tmp/floop_kg_old.sqlite")
|
||||||
|
if p.exists():
|
||||||
|
p.unlink()
|
||||||
|
# hand-build an OLD-schema store: edges WITHOUT origin_question
|
||||||
|
db = sqlite3.connect(p)
|
||||||
|
db.executescript("""
|
||||||
|
CREATE TABLE documents (
|
||||||
|
id INTEGER PRIMARY KEY, url TEXT UNIQUE, source TEXT, fetched_at TEXT,
|
||||||
|
sha256 TEXT, trusted INTEGER, title TEXT);
|
||||||
|
CREATE TABLE quotes (
|
||||||
|
id INTEGER PRIMARY KEY, doc_id INTEGER, verbatim TEXT, url TEXT, access_date TEXT);
|
||||||
|
CREATE TABLE nodes (id INTEGER PRIMARY KEY, norm_name TEXT, sort TEXT,
|
||||||
|
UNIQUE(norm_name, sort));
|
||||||
|
CREATE TABLE edges (id INTEGER PRIMARY KEY, src_node INTEGER, rel TEXT,
|
||||||
|
dst_value TEXT, dst_node INTEGER, quote_id INTEGER, extraction_confidence REAL,
|
||||||
|
ref_date TEXT, supersedes INTEGER, preferred INTEGER DEFAULT 0,
|
||||||
|
retracted INTEGER DEFAULT 0, retraction_reason TEXT, corroboration INTEGER DEFAULT 1);
|
||||||
|
""")
|
||||||
|
db.execute("INSERT INTO nodes(norm_name, sort) VALUES('germany','PLAC'),"
|
||||||
|
"('european union','CONCEPT')")
|
||||||
|
nid = db.execute("SELECT id FROM nodes WHERE norm_name='germany'").fetchone()[0]
|
||||||
|
db.execute("INSERT INTO edges(src_node, rel, dst_value, quote_id) "
|
||||||
|
"VALUES(?, 'member_of', 'european union', NULL)", (nid,))
|
||||||
|
db.commit()
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
ks = KnowledgeStore(p) # must migrate, not crash
|
||||||
|
origins = ks.set_origins() # the call that crashed on the old schema
|
||||||
|
# NULL-origin sets are NOT servable by the gate: without an origin question
|
||||||
|
# we cannot verify the set answers THIS question — safe re-gather instead.
|
||||||
|
# (The rows stay in the KG for non-enum probes; only the gate skips them.)
|
||||||
|
assert origins == [], f"NULL-origin sets must not be gate-servable: {origins}"
|
||||||
|
# and the store still answers normal probes after migration:
|
||||||
|
ks.close()
|
||||||
|
print("ok test_migration_old_store")
|
||||||
|
|
||||||
|
|
||||||
def test_table_parser_untruncated():
|
def test_table_parser_untruncated():
|
||||||
from knowledge.wiki import parse_tables
|
from knowledge.wiki import parse_tables
|
||||||
# vertical layout, 5 rows, header row -> total_rows MUST be 5, no truncation
|
# vertical layout, 5 rows, header row -> total_rows MUST be 5, no truncation
|
||||||
@@ -197,6 +238,7 @@ if __name__ == "__main__":
|
|||||||
test_chunker_sections()
|
test_chunker_sections()
|
||||||
test_containment()
|
test_containment()
|
||||||
test_store_four_cases()
|
test_store_four_cases()
|
||||||
|
test_migration_old_store()
|
||||||
test_list_ingest_aggregate()
|
test_list_ingest_aggregate()
|
||||||
test_table_parser_untruncated()
|
test_table_parser_untruncated()
|
||||||
print(f"\n{test_table_parser_untruncated.__name__} etc — 5 knowledge tests passed")
|
print(f"\n{test_table_parser_untruncated.__name__} etc — 6 knowledge tests passed")
|
||||||
@@ -104,6 +104,31 @@ def test_empty_decomposition_stops():
|
|||||||
assert len(rep.questions) == 1 # only the goal, no subs
|
assert len(rep.questions) == 1 # only the goal, no subs
|
||||||
|
|
||||||
|
|
||||||
|
def test_lm_death_aborts_cleanly():
|
||||||
|
"""A dead LM (timeout/transport) must abort with notes + evidence kept,
|
||||||
|
never crash the run with a traceback (Emili's 2026-10-19 home run)."""
|
||||||
|
class DeadLM(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
cause = TimeoutError("read timed out waiting for headers")
|
||||||
|
dead = DeadLM("wrapper")
|
||||||
|
dead.__cause__ = cause
|
||||||
|
|
||||||
|
class DeadModules(FakeModules):
|
||||||
|
def route_question(self, question, catalog, evidence):
|
||||||
|
raise dead
|
||||||
|
|
||||||
|
def synthesize(self, goal, evidence, unverified):
|
||||||
|
raise dead # the LM is dead everywhere, synthesis included
|
||||||
|
|
||||||
|
fm = DeadModules(init_subs=[{"text": "q?", "deps": [], "answer_type": "CONSTANT"}],
|
||||||
|
route_fn=lambda q: "numeric")
|
||||||
|
rep = FloopRun("goal?", budget(), modules=fm).run()
|
||||||
|
assert rep.final_answer == "" # no answer beats a fake
|
||||||
|
assert any("LM unreachable" in n for n in rep.notes)
|
||||||
|
assert rep.notes, "notes must explain the abort"
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
|
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
|
||||||
for fn in fns:
|
for fn in fns:
|
||||||
|
|||||||
Reference in New Issue
Block a user