Skip to content

Commit dcb62bb

Browse files
tiering: the mirror survives the export -> sync -> prune -> export cycle and never shrinks the archive
Council pass 8 (claude-opus-5.5 F1/F2/F3), each reproduced by the coordinator with the real Codex exporter: - F1: after prune evicted a session, the next incremental export re-imported it (the fingerprint lookup reads hot only) and re-captured the same evidence id -- a hash of the payload -- with a fresh first_captured_at; the mirror's all-columns collision check then refused every later sync and prune verified nothing. The registry now marks first_captured_at as capture metadata (compare_ignore); the collision check and prune's acceptance leave it out, and full keeps its first capture. - F2: a session re-imported with a shorter or re-indexed source replaced full's messages with hot's, deleting archived prose from the archive and its index. Children are now merged, never deleted: an upsert by id, and where hot's positional id carries prose full's row never had, full's row keeps its prose and native links and hot's prose is archived under the exporter's own revision id (<id>-rev-<sha24>, metadata.source_record_id) with its native links redirected. Such a session is not verifiable by prune and stays in hot; nothing captured is lost. R9 is repinned to the archive semantics (hot's rows present in full; a compacted-away message stays). - F3: find-duplicates --merge re-parents messages in hot; the id upsert now follows the move instead of colliding under the deleted duplicate. RED first (four new tests); 2543 passed under the coordinator's run.
1 parent 4fe94eb commit dcb62bb

3 files changed

Lines changed: 312 additions & 32 deletions

File tree

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

Lines changed: 126 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -938,8 +938,14 @@ def _missing_sql(
938938
)
939939

940940

941-
def _upsert_sql(table: str, cols: list[str], key: tuple[str, ...]) -> str:
942-
"""Insert new rows and update rows whose columns differ; never a delete."""
941+
def _upsert_sql(
942+
table: str, cols: list[str], key: tuple[str, ...], *, exclude: str | None = None
943+
) -> str:
944+
"""Insert new rows and update rows whose columns differ; never a delete.
945+
946+
``exclude`` names a temp table of ``id`` values to leave alone (the messages
947+
whose prose is kept under a revision id instead, pass 8 F2).
948+
"""
943949
non_key = [c for c in cols if c not in key]
944950
target = ", ".join(_q(c) for c in key)
945951
if non_key:
@@ -950,9 +956,11 @@ def _upsert_sql(table: str, cols: list[str], key: tuple[str, ...]) -> str:
950956
conflict = f"ON CONFLICT({target}) DO UPDATE SET {assignments} WHERE {differs}"
951957
else:
952958
conflict = f"ON CONFLICT({target}) DO NOTHING"
959+
excluded = f" AND h.id NOT IN (SELECT id FROM {exclude})" if exclude else ""
953960
return (
954961
f"INSERT INTO main.{_q(table)} ({', '.join(_q(c) for c in cols)}) "
955962
+ _missing_sql(table, cols, key, keys_only=False)
963+
+ excluded
956964
+ f" {conflict}"
957965
)
958966

@@ -1132,8 +1140,6 @@ def _copy_payload(conn: sqlite3.Connection, stats: SyncStats) -> bool:
11321140
from .tiering_registry import PAYLOAD, Role, columns
11331141

11341142
cols = {entry.name: columns(conn, entry.name, "main") for entry in PAYLOAD}
1135-
message_cols = ", ".join(_q(c) for c in cols["messages"])
1136-
reference_cols = ", ".join(_q(c) for c in cols["file_references"])
11371143

11381144
# Sessions whose children must be replaced, decided BEFORE the session
11391145
# upsert. ``content_hash`` alone is not enough: the exporters never write it
@@ -1177,36 +1183,40 @@ def record(table: str, written: int) -> None:
11771183
for entry in PAYLOAD:
11781184
table, key = entry.name, entry.key
11791185
if table == "messages":
1180-
# message_concepts references messages with NO ACTION: clear it for
1181-
# the replaced messages first (the mutable phase restores hot's rows).
1182-
# The DELETE then cascades file_references, scrub_log, native message
1183-
# sources and embeddings; each is restored below from hot.
1184-
conn.execute(
1185-
"DELETE FROM main.message_concepts WHERE message_id IN (SELECT id FROM "
1186-
"main.messages WHERE session_id IN (SELECT id FROM temp.tier_changed))"
1187-
)
1188-
conn.execute(
1189-
"DELETE FROM main.messages WHERE session_id IN (SELECT id FROM temp.tier_changed)"
1186+
# Full is the archive (pass 8, F2): native histories compact and
1187+
# expire, and a session re-imported after eviction may be shorter or
1188+
# re-indexed. So: never delete a full row; where hot's positional id
1189+
# now carries different prose, keep full's prose under the exporter's
1190+
# own revision id (exporters/base.py, _preserve_message_identity)
1191+
# and let the id follow hot, so prune can still verify the session.
1192+
displaced = _preserve_displaced_prose(conn, cols["messages"])
1193+
written = (
1194+
displaced
1195+
+ conn.execute(
1196+
_upsert_sql(
1197+
"messages",
1198+
cols["messages"],
1199+
("id",),
1200+
exclude="temp.tier_displaced",
1201+
)
1202+
).rowcount
11901203
)
1191-
written = conn.execute(
1192-
f"INSERT INTO main.messages ({message_cols}) SELECT {message_cols} "
1193-
"FROM hot.messages WHERE session_id IN (SELECT id FROM temp.tier_changed)"
1194-
).rowcount
11951204
stats.messages_synced = written
11961205
record(table, written)
11971206
elif table == "file_references":
1198-
conn.execute(
1199-
"DELETE FROM main.file_references WHERE session_id IN "
1200-
"(SELECT id FROM temp.tier_changed)"
1201-
)
12021207
written = conn.execute(
1203-
f"INSERT INTO main.file_references ({reference_cols}) SELECT {reference_cols} "
1204-
"FROM hot.file_references WHERE session_id IN (SELECT id FROM temp.tier_changed)"
1208+
_upsert_sql("file_references", cols["file_references"], ("id",))
12051209
).rowcount
12061210
stats.file_references_synced = written
12071211
record(table, written)
1212+
elif table == "context_native_message_sources":
1213+
# A displaced message's links (pass 8, F2) point at its revision id
1214+
# in full; everything else is the ordinary immutable insert.
1215+
_copy_native_links(conn, cols[table], record)
12081216
elif entry.role is Role.PAYLOAD_IMMUTABLE:
1209-
_refuse_immutable_collision(conn, table, cols[table], key)
1217+
_refuse_immutable_collision(
1218+
conn, table, cols[table], key, entry.compare_ignore
1219+
)
12101220
missing = _missing_sql(table, cols[table], key, keys_only=True)
12111221
col_list = ", ".join(_q(c) for c in cols[table])
12121222
record(
@@ -1218,6 +1228,7 @@ def record(table: str, written: int) -> None:
12181228
else:
12191229
record(table, conn.execute(_upsert_sql(table, cols[table], key)).rowcount)
12201230
conn.execute("DROP TABLE temp.tier_changed")
1231+
conn.execute("DROP TABLE IF EXISTS temp.tier_displaced")
12211232

12221233
# A row-maintenance trigger in full (``trg_*_updated_at_*``, ``*_sync_key``)
12231234
# can rewrite a just-copied mutable row. One more upsert pass converges it;
@@ -1238,12 +1249,90 @@ def record(table: str, written: int) -> None:
12381249
return clean
12391250

12401251

1252+
def _preserve_displaced_prose(conn: sqlite3.Connection, cols: list[str]) -> int:
1253+
"""Keep every captured message in full (pass 8, F2).
1254+
1255+
A session re-imported after eviction can be re-indexed: hot's positional id
1256+
now carries prose that full's row with that id never had, and hot has no
1257+
old row the exporter could re-key against (``exporters/base.py``,
1258+
``_preserve_message_identity``). Full's row keeps its prose and its native
1259+
links; hot's prose is archived under the exporter's own revision id
1260+
(``<id>-rev-<sha256(json([role, content]))[:24]>`` with
1261+
``metadata.source_record_id``). Those ids are left out of the upsert, and
1262+
their native links are redirected (``_copy_native_links``). Such a session
1263+
is not verifiable by prune (hot's row is not literally in full) and stays in
1264+
hot; nothing captured is lost. Returns the revision rows written.
1265+
"""
1266+
import hashlib
1267+
import json
1268+
1269+
conn.execute(
1270+
"CREATE TEMP TABLE IF NOT EXISTS tier_displaced (id TEXT PRIMARY KEY, rev TEXT)"
1271+
)
1272+
conn.execute("DELETE FROM temp.tier_displaced")
1273+
conflicts = conn.execute(
1274+
"SELECT h.id FROM hot.messages h JOIN main.messages f ON f.id = h.id "
1275+
"WHERE f.content IS NOT NULL AND trim(f.content) != '' "
1276+
"AND (f.role IS NOT h.role OR f.content IS NOT h.content)"
1277+
).fetchall()
1278+
written = 0
1279+
col_list = ", ".join(_q(c) for c in cols)
1280+
for (message_id,) in conflicts:
1281+
row = conn.execute(
1282+
f"SELECT {col_list} FROM hot.messages WHERE id=?", (message_id,)
1283+
).fetchone()
1284+
values = dict(zip(cols, row, strict=True))
1285+
digest = hashlib.sha256(
1286+
json.dumps([values["role"], values["content"]]).encode()
1287+
).hexdigest()[:24]
1288+
rev = f"{message_id}-rev-{digest}"
1289+
conn.execute("INSERT INTO temp.tier_displaced VALUES (?, ?)", (message_id, rev))
1290+
if conn.execute("SELECT 1 FROM main.messages WHERE id=?", (rev,)).fetchone():
1291+
continue
1292+
metadata = json.loads(values.get("metadata") or "{}")
1293+
metadata["source_record_id"] = message_id
1294+
values["id"], values["metadata"] = rev, json.dumps(metadata)
1295+
conn.execute(
1296+
f"INSERT INTO main.messages ({col_list}) VALUES "
1297+
f"({', '.join('?' for _ in cols)})",
1298+
[values[c] for c in cols],
1299+
)
1300+
written += 1
1301+
return written
1302+
1303+
1304+
def _copy_native_links(conn: sqlite3.Connection, cols: list[str], record) -> None:
1305+
"""Immutable insert of hot's native message links, displaced ids redirected."""
1306+
col_list = ", ".join(_q(c) for c in cols)
1307+
selected = ", ".join(
1308+
"COALESCE(d.rev, h.message_id)" if c == "message_id" else f"h.{_q(c)}"
1309+
for c in cols
1310+
)
1311+
written = conn.execute(
1312+
f"INSERT OR IGNORE INTO main.context_native_message_sources ({col_list}) "
1313+
f"SELECT {selected} FROM hot.context_native_message_sources h "
1314+
"LEFT JOIN temp.tier_displaced d ON d.id = h.message_id "
1315+
"WHERE NOT EXISTS (SELECT 1 FROM main.context_native_message_sources x "
1316+
"WHERE x.message_id = COALESCE(d.rev, h.message_id) "
1317+
"AND x.evidence_id = h.evidence_id)"
1318+
).rowcount
1319+
record("context_native_message_sources", written)
1320+
1321+
12411322
def _refuse_immutable_collision(
1242-
conn: sqlite3.Connection, table: str, cols: list[str], key: tuple[str, ...]
1323+
conn: sqlite3.Connection,
1324+
table: str,
1325+
cols: list[str],
1326+
key: tuple[str, ...],
1327+
ignore: tuple[str, ...] = (),
12431328
) -> None:
1244-
"""An overlapping immutable key must be column-equal (council pass 7, C1)."""
1329+
"""An overlapping immutable key must be column-equal (council pass 7, C1).
1330+
1331+
``ignore`` names capture metadata (``first_captured_at``) that a re-capture
1332+
after eviction legitimately changes; full's first value wins (pass 8, F1).
1333+
"""
12451334
on = " AND ".join(f"x.{_q(c)} = h.{_q(c)}" for c in key)
1246-
same = " AND ".join(f"x.{_q(c)} IS h.{_q(c)}" for c in cols)
1335+
same = " AND ".join(f"x.{_q(c)} IS h.{_q(c)}" for c in cols if c not in ignore)
12471336
row = conn.execute(
12481337
f"SELECT {', '.join(f'h.{_q(c)}' for c in key)} FROM hot.{_q(table)} h "
12491338
f"JOIN main.{_q(table)} x ON {on} WHERE NOT ({same}) LIMIT 1"
@@ -1627,8 +1716,16 @@ def _archive_context_complete(conn):
16271716
cols = columns(conn, entry.name, "main")
16281717
if cols != columns(conn, entry.name, "full"):
16291718
return False
1719+
# Capture metadata the copier does not compare (first_captured_at) is
1720+
# not required to match either: full keeps its first capture (pass 8).
1721+
compared = [c for c in cols if c not in entry.compare_ignore]
16301722
probe = _missing_sql(
1631-
entry.name, cols, entry.key, keys_only=False, source="main", archive="full"
1723+
entry.name,
1724+
compared,
1725+
entry.key,
1726+
keys_only=False,
1727+
source="main",
1728+
archive="full",
16321729
)
16331730
if conn.execute(probe + " LIMIT 1").fetchone():
16341731
return False

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,11 @@ class TableRole:
7373
#: Position in the copy order; parents come before children so every insert
7474
#: satisfies its foreign keys with ``PRAGMA foreign_keys=ON``. 0 = not copied.
7575
order: int = 0
76+
#: Columns that are capture metadata, not identity: an immutable row whose id
77+
#: is a hash of its payload may be re-captured (after eviction and a
78+
#: re-export) with a fresh value here. Full's first value wins; these
79+
#: columns are left out of the immutable-collision comparison (pass 8, F1).
80+
compare_ignore: tuple[str, ...] = ()
7681

7782

7883
class UnclassifiedTable(ValueError):
@@ -131,7 +136,9 @@ def _payload(order: int, name: str, role: Role, *key: str) -> TableRole:
131136
_payload(22, "context_board_columns", _M, "scope", "key"),
132137
# schema.py: context_evidence_immutable / assertions_immutable /
133138
# citations_immutable; relations are insert-only (store.py:475).
134-
_payload(23, "context_evidence", _I, "id"),
139+
TableRole(
140+
"context_evidence", _I, ("id",), 23, compare_ignore=("first_captured_at",)
141+
),
135142
# capture.py:78 INSERT OR IGNORE only; FK messages(id) ON DELETE CASCADE,
136143
# restored from hot after a message replacement.
137144
_payload(24, "context_native_message_sources", _I, "message_id", "evidence_id"),

0 commit comments

Comments
 (0)