@@ -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+
12411322def _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
0 commit comments