Skip to content

Commit ed6c206

Browse files
tiering: prune proves the full is this database's before it deletes; full is classified too
Council pass 8, reproduced by the coordinator against 46b5d09: - prune_hot attached whatever full it was given and deleted from hot on the strength of matching rows; it never read the mirror binding. The same learner on two machines exports the same transcripts, and a full the old copier wrote is nobody's bound archive. The modern path now requires the binding (instance equality) or, with no binding table, a copy of this very database (same context_access_state.instance -- a backup made from hot); anything else is unbound_full / instance_mismatch before verification. - the registry's fail-closed classification covered hot only; a table in the bound full that the registry cannot name now refuses (unclassified_table, 'in the full database') before the changed-session deletion can cascade through it. - an existing full path that is not a SQLite database failed at PRAGMA user_version with a bare DatabaseError; it is full_store_unavailable. - prune refuses an unclassified table by name, as the docs say, instead of verifying nothing and reporting every candidate skipped; the acceptance predicate itself stays a predicate. - cli/_focus.py catches LegacySyncRefused only; an unrelated RuntimeError stays observable. prune --help states the modern invariant. RED first for each (test_tiering_mirror.py pass-8 block, test_focus.py); 2538 passed under the coordinator's run.
1 parent 46b5d09 commit ed6c206

5 files changed

Lines changed: 198 additions & 10 deletions

File tree

‎packages/agent-session-tools/src/agent_session_tools/maintenance.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1718,9 +1718,12 @@ def prune(
17181718
"""Prune old sessions from the hot DB — only those verified in the full DB.
17191719
17201720
Runs in dry-run mode by default; pass --no-dry-run to actually delete.
1721-
A session is only deleted when the full DB holds the same session with a
1722-
matching content hash and at least as many messages. Learning tables are
1723-
never touched.
1721+
The full DB must be the mirror bound to this database (run sync-full
1722+
first). A session is deleted only when the full DB holds the same session
1723+
row and exactly its messages, every mirrored memory and learner row of this
1724+
database is present there, the permanent controls agree, and the full DB
1725+
passes its foreign-key check; a session that owns learner records is never
1726+
a candidate.
17241727
"""
17251728
from agent_session_tools.tiering import TieringRefused, prune_hot
17261729

‎packages/agent-session-tools/src/agent_session_tools/tiering.py‎

Lines changed: 82 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -663,14 +663,35 @@ def _mirror_preflight(
663663
if not full.exists() or full.stat().st_size == 0:
664664
return plan
665665
plan.full_exists = True
666-
with closing(_open_ro(full)) as conn:
667-
version = conn.execute("PRAGMA user_version").fetchone()[0]
666+
try:
667+
full_conn = _open_ro(full)
668+
except sqlite3.Error as exc: # a directory, an unreadable volume, ...
669+
raise TieringRefused("full_store_unavailable", f"{full}: {exc}") from exc
670+
with closing(full_conn) as conn:
671+
try:
672+
version = conn.execute("PRAGMA user_version").fetchone()[0]
673+
except sqlite3.DatabaseError as exc: # exists but is not a SQLite database
674+
raise TieringRefused("full_store_unavailable", f"{full}: {exc}") from exc
668675
if version > CURRENT_VERSION:
669676
raise TieringRefused(
670677
"schema_mismatch",
671678
f"the full database is at schema {version}, newer than this build "
672679
f"({CURRENT_VERSION})",
673680
)
681+
# Pass 8 (sol S3): fail-closed classification covers the full tier too. A
682+
# table the registry cannot name in full -- FK-linked to payload or not --
683+
# must refuse before the changed-session deletion can cascade through it.
684+
# A full behind the current schema is classified after init_db migrates
685+
# it, in _mirror_copy's own check; here it is the file as found.
686+
if version == CURRENT_VERSION:
687+
try:
688+
classify_database(conn)
689+
except UnclassifiedTable as exc:
690+
raise TieringRefused(
691+
"unclassified_table",
692+
f"in the full database: {exc}",
693+
table=exc.table,
694+
) from exc
674695
_refuse_peer_ledger(conn, "main", "full")
675696
if _table_exists(conn, MIRROR_TABLE):
676697
row = conn.execute(
@@ -747,6 +768,46 @@ def _bind_full(full: Path, plan: _MirrorPlan) -> bool:
747768
conn.close()
748769

749770

771+
def _require_prune_binding(conn: sqlite3.Connection) -> None:
772+
"""Refuse to prune against a full that is not bound to the attached hot (``main``)."""
773+
from .tiering_registry import MIRROR_TABLE
774+
775+
instance = conn.execute(
776+
"SELECT instance FROM main.context_access_state WHERE id=1"
777+
).fetchone()[0]
778+
row = None
779+
if _table_exists(conn, MIRROR_TABLE, "full"):
780+
row = conn.execute(
781+
f"SELECT canonical_instance FROM full.{MIRROR_TABLE} WHERE id=1"
782+
).fetchone()
783+
if row is None:
784+
# No binding: the one other provable case is a copy of this very
785+
# database (a backup made from hot carries hot's own access-state
786+
# instance), which is this learner's data by construction. A full that
787+
# init_db seeded on its own -- the old copier's output, or anyone
788+
# else's -- has a different instance and is refused.
789+
own = None
790+
if _table_exists(conn, "context_access_state", "full"):
791+
got = conn.execute(
792+
"SELECT instance FROM full.context_access_state WHERE id=1"
793+
).fetchone()
794+
own = got[0] if got else None
795+
if own is not None and own == instance:
796+
return
797+
raise TieringRefused(
798+
"unbound_full",
799+
"the full database carries no mirror binding and is not a copy of this "
800+
"database; run sync-full first (a full written by the old copier is "
801+
"not this database's archive)",
802+
)
803+
if row[0] != instance:
804+
raise TieringRefused(
805+
"instance_mismatch",
806+
f"the full database is bound to instance {row[0]}; the hot database is "
807+
f"instance {instance}",
808+
)
809+
810+
750811
def _require_bound_to(canonical_instance: str | None, plan: _MirrorPlan) -> None:
751812
if canonical_instance != plan.instance:
752813
raise TieringRefused(
@@ -1381,6 +1442,23 @@ def prune_hot(
13811442
if modern:
13821443
# Hold verification and eviction in the same attached-DB transaction.
13831444
conn.execute("BEGIN IMMEDIATE")
1445+
# Pass 8 (luna B1): prune deletes from hot on the strength of rows it
1446+
# finds in full, so full must first be proven to be THIS database's
1447+
# mirror. Matching rows are not proof: the same learner on two
1448+
# machines exports the same transcripts, and a full written by the
1449+
# old copier is nobody's bound archive.
1450+
_require_prune_binding(conn)
1451+
# Pass 8 (sol S6): an unclassified table in hot is a named refusal
1452+
# here, as it is for sync-full and as the docs say -- not a silent
1453+
# "every candidate skipped".
1454+
from .tiering_registry import UnclassifiedTable, classify_database
1455+
1456+
try:
1457+
classify_database(conn, "main")
1458+
except UnclassifiedTable as exc:
1459+
raise TieringRefused(
1460+
"unclassified_table", str(exc), table=exc.table
1461+
) from exc
13841462

13851463
# A session's age is its newest known timestamp -- the rule delete and
13861464
# archive apply (F-AST-06, maintenance._SESSION_AGE_SQL). updated_at
@@ -1532,6 +1610,8 @@ def _archive_context_complete(conn):
15321610
try:
15331611
classify_database(conn, "main")
15341612
except UnclassifiedTable as exc:
1613+
# The predicate stays a predicate (false); prune_hot refuses by name
1614+
# before it gets here (pass 8, sol S6), so this is the probe-only path.
15351615
logger.warning("prune: %s -- nothing is evicted until this build knows it", exc)
15361616
return False
15371617
remote = set(_user_tables(conn, "full"))

‎packages/agent-session-tools/tests/test_tiering_mirror.py‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -837,3 +837,89 @@ def test_a_trigger_that_rolls_back_is_reported_as_a_refusal(mirror):
837837
assert (
838838
count(mirror["hot"], "SELECT count(*) FROM messages WHERE session_id=?", a) == 2
839839
)
840+
841+
842+
# --- council pass 8 (coordinator units) -------------------------------------
843+
844+
845+
def _unbind(full: Path) -> None:
846+
with closing(sqlite3.connect(full)) as conn:
847+
conn.execute("DELETE FROM tiering_mirror_state")
848+
conn.commit()
849+
850+
851+
def _rebind_to(full: Path, instance: str) -> None:
852+
with closing(sqlite3.connect(full)) as conn:
853+
conn.execute(
854+
"UPDATE tiering_mirror_state SET canonical_instance=?", (instance,)
855+
)
856+
conn.commit()
857+
858+
859+
def test_prune_refuses_a_full_that_is_not_bound_to_this_hot(mirror):
860+
"""Pass 8 (luna B1): ``prune_hot`` deletes from hot on the strength of rows it
861+
finds in ``full``; it must first prove that full is THIS hot's mirror. A
862+
full written by someone else, or bound to another instance, can hold the
863+
same rows (the same learner on two machines exports the same transcripts)
864+
and is still not this database's archive."""
865+
from agent_session_tools.tiering import prune_hot
866+
867+
export(mirror, "alpha", ["alpha decorators question", "alpha answer"], day=1)
868+
sync_to_full()
869+
_rebind_to(mirror["full"], "someone-else")
870+
with pytest.raises(TieringRefused) as info:
871+
prune_hot(days=0, dry_run=False)
872+
assert info.value.reason == "instance_mismatch"
873+
assert count(mirror["hot"], "SELECT COUNT(*) FROM sessions") == 1
874+
875+
_unbind(mirror["full"])
876+
with pytest.raises(TieringRefused) as info:
877+
prune_hot(days=0, dry_run=True)
878+
assert info.value.reason == "unbound_full"
879+
assert count(mirror["hot"], "SELECT COUNT(*) FROM sessions") == 1
880+
881+
882+
def test_prune_refuses_an_unclassified_table_by_name(mirror):
883+
"""Pass 8 (sol S6): the docs promise prune refuses like sync-full does; it
884+
used to log a warning, verify nothing and report every candidate skipped."""
885+
from agent_session_tools.tiering import prune_hot
886+
887+
export(mirror, "alpha", ["alpha decorators question", "alpha answer"], day=1)
888+
sync_to_full()
889+
for path in (mirror["hot"], mirror["full"]):
890+
with closing(sqlite3.connect(path)) as conn:
891+
conn.execute("CREATE TABLE context_future (id TEXT PRIMARY KEY)")
892+
conn.commit()
893+
with pytest.raises(TieringRefused) as info:
894+
prune_hot(days=0, dry_run=True)
895+
assert info.value.reason == "unclassified_table"
896+
assert info.value.table == "context_future"
897+
898+
899+
def test_sync_refuses_an_unclassified_table_that_only_full_has(mirror):
900+
"""Pass 8 (sol S3): fail-closed classification covered hot only; a table in
901+
the bound full that the registry cannot name (FK-linked to payload or not)
902+
must refuse before the changed-session deletion can cascade through it."""
903+
two_sessions(mirror)
904+
sync_to_full()
905+
with closing(sqlite3.connect(mirror["full"])) as conn:
906+
conn.execute("CREATE TABLE context_future (id TEXT PRIMARY KEY)")
907+
conn.commit()
908+
with pytest.raises(TieringRefused) as info:
909+
sync_to_full()
910+
assert info.value.reason == "unclassified_table"
911+
assert info.value.table == "context_future"
912+
913+
914+
def test_a_corrupt_full_file_is_a_refusal_not_a_traceback(mirror):
915+
"""Pass 8 (sol S2 / luna M1): an existing full path that is not a SQLite
916+
database failed at ``PRAGMA user_version`` with a bare ``DatabaseError``."""
917+
export(mirror, "alpha", ["alpha decorators question"], day=1)
918+
mirror["full"].write_text("this is not a database\n")
919+
with pytest.raises(TieringRefused) as info:
920+
sync_to_full()
921+
assert info.value.reason == "full_store_unavailable"
922+
assert (
923+
"not a database" in str(info.value).lower()
924+
or "file is not" in str(info.value).lower()
925+
)

‎packages/studyloop/src/studyloop/cli/_focus.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ def _apply_refocus(days: int, dry_run: bool = False) -> None:
115115
from studyloop.focus import get_focus
116116

117117
try:
118+
from agent_session_tools.replication.legacy import LegacySyncRefused
118119
from agent_session_tools.tiering import refocus
119120
except ImportError:
120121
console.print(
@@ -136,11 +137,11 @@ def _apply_refocus(days: int, dry_run: bool = False) -> None:
136137
except FileNotFoundError as exc:
137138
console.print(f"[yellow]Deferred: {exc}[/yellow]")
138139
return
139-
except RuntimeError as exc:
140-
# agent_session_tools.replication.legacy.LegacySyncRefused: refocus still
141-
# runs the legacy guard against the full database, which refuses as soon
142-
# as that database carries any context row -- after the first mirror
143-
# sync (plan 6). The focus is saved; only the data movement is refused.
140+
except LegacySyncRefused as exc:
141+
# refocus still runs the legacy guard against the full database, which
142+
# refuses as soon as that database carries any context row -- after the
143+
# first mirror sync (plan 6). The focus is saved; only the data movement
144+
# is refused. Any other RuntimeError is a defect and stays observable.
144145
console.print(
145146
f"[yellow]Refocus refused -- focus saved, data movement skipped: {exc}[/yellow]"
146147
)

‎packages/studyloop/tests/test_focus.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,3 +246,21 @@ def refuse(*_args, **_kwargs):
246246
assert "Traceback" not in flat
247247
assert "Legacy SQL sync cannot transfer" in flat
248248
assert "focus saved" in flat
249+
250+
def test_focus_apply_does_not_swallow_an_unrelated_runtime_error(
251+
self, isolated_config, monkeypatch
252+
):
253+
"""Pass 8 (sol S7): only the legacy refusal is an expected refusal; any
254+
other RuntimeError is a defect and must stay observable."""
255+
from agent_session_tools import tiering
256+
257+
def explode(*_args, **_kwargs):
258+
raise RuntimeError("lifecycle invariant broken")
259+
260+
monkeypatch.setattr(tiering, "refocus", explode)
261+
runner = CliRunner()
262+
runner.invoke(cli, ["focus", "set", "python", "--no-refocus"])
263+
264+
result = runner.invoke(cli, ["focus", "apply"])
265+
266+
assert isinstance(result.exception, RuntimeError), result.output

0 commit comments

Comments
 (0)