iai-personal-memory-engine icon indicating copy to clipboard operation
iai-personal-memory-engine copied to clipboard

`migrate-to-lilli --swap`: finalize drops aged tombstones from the destination, then verify_store_equality demands COUNT(*) parity with the source, so the swap fails RED on any store older than the tombstone TTL

Open LC1207 opened this issue 2 months ago • 1 comments

Summary

iai-mcp migrate-to-lilli --src <store>/hippo/brain.sqlite3 --swap --apply --yes (3.1.0) contains two steps that contradict each other whenever the source holds tombstoned records older than tombstone_ttl_sec (default 7 days):

  1. migrate_sqlite_to_lilli copies every row verbatim, then calls _compact_aged_tombstones_at_finalize, which physically deletes from the freshly built destination every record with tombstoned_at < source_time_now - tombstone_ttl_sec.
  2. swap_to_lilli then calls verify_store_equality, whose dimension A (_verify_counts) compares raw SELECT COUNT(*) per table between the untouched source and that destination, and whose dimensions B/C/F co-scan every source row by id and report the first one "missing on dst".

The verifier has no knowledge of the finalize compaction (the string tombston does not occur in _to_lilli_verify.py), so any store that has run for more than a week without a tombstone purge fails verification by construction, the swap aborts before the rename, and the CLI prints a -N records delta with no hint that the tool itself removed them. The finalize step's own docstring names the safe alternative ("the aged bloat is then cleaned up by the first nightly sleep cycle instead"), which is exactly what happens when the compaction is disabled via the environment.

Environment

  • iai-personal-memory-engine v3.1.0 (b586c2a), source checkout, Python 3.12, macOS (Darwin 25.6), Apple Silicon.
  • Source store: legacy stdlib-sqlite format, brain.sqlite3 ≈ 99 MB, 8,554 records at the first attempt. Daemon stopped before the run; doctor check (gg) had recommended exactly this command.

Reproduction (measured)

First attempt, default TTL:

$ iai-mcp migrate-to-lilli --src ~/.iai-mcp/hippo/brain.sqlite3 --swap --apply --yes --verbose
iai-mcp migrate-to-lilli --swap [apply]
  detected format:   stdlib
  live store root:   /Users/<user>/.iai-mcp
  backup directory:  /Users/<user>/.iai-mcp/hippo.sqlite-backup-20260908
  staging root:      /Users/<user>/.iai-mcp/.migrate-staging-20260908T052039Z
  blockers (4):
    - A_counts: records: src=8554 dst=8028 (-526)
    - B_bytes: records id=00205b9e-aaa8-4858-90a8-5c4baaf977a8 missing on dst
    - C_decrypt: id=00205b9e-aaa8-4858-90a8-5c4baaf977a8 missing on dst during decrypt parity
    - F_codec: records id=00205b9e-aaa8-4858-90a8-5c4baaf977a8 missing on dst
  verify:            RED -- store equality NOT proven
  rows copied:       104710 (records=8554, edges=10361, events=85787, budget_ledger=0, ratelimit_ledger=0, _hippo_meta=8)
$ echo $?
1

Note the contradiction inside the tool's own output: rows copied: records=8554 and dst=8028 in the same run. copied counts source rows streamed (_to_lilli.py copy loop), not rows surviving finalize.

What the 526 rows are (source, read-only):

$ sqlite3 'file:~/.iai-mcp/hippo/brain.sqlite3?immutable=1' \
    "select substr(tombstoned_at,1,10) d, count(*) from records where tombstoned_at is not null group by d"
2026-08-30|526
2026-09-01|206
2026-09-02|524
2026-09-06|1066
$ sqlite3 'file:...?immutable=1' "select count(*) from records where tombstoned_at is not null \
    and tombstoned_at < datetime((select max(created_at) from records), '-7 days')"
526
$ sqlite3 'file:...?immutable=1' "select tier, tombstoned_at, pinned, never_decay from records \
    where id='00205b9e-aaa8-4858-90a8-5c4baaf977a8'"
episodic|2026-08-30 10:21:35.540757+00:00|0|0

MAX(created_at) was 2026-09-07, so the cutoff fell on 2026-08-31 and the 2026-08-30 cohort, and only that cohort, is older than the TTL. 526 aged tombstones in the source, 526 rows missing on the destination, and the named id belongs to the cohort.

Second attempt, compaction disabled through the documented knob, same source (grown by normal capture in the meantime):

$ IAI_MCP_ERASURE_TOMBSTONE_TTL_SEC=31536000 iai-mcp migrate-to-lilli --src ~/.iai-mcp/hippo/brain.sqlite3 --swap --apply --yes --verbose
iai-mcp migrate-to-lilli --swap [apply]
  detected format:   stdlib
  live store root:   /Users/<user>/.iai-mcp
  backup directory:  /Users/<user>/.iai-mcp/hippo.sqlite-backup-20260908
  staging root:      /Users/<user>/.iai-mcp/.migrate-staging-20260908T061043Z
  verify:            GREEN -- all dimensions match
  rows copied:       104968 (records=8572, edges=10526, events=85862, budget_ledger=0, ratelimit_ledger=0, _hippo_meta=8)
  swapped -- the live store now runs on the native engine; the previous store is kept at /Users/<user>/.iai-mcp/hippo.sqlite-backup-20260908
$ echo $?
0
$ sqlite3 'file:~/.iai-mcp/hippo.sqlite-backup-20260908/brain.sqlite3?immutable=1' "select count(*) from records"
8572

Identical command, identical store, one environment variable: RED becomes GREEN. Nothing else changed between the two runs except ~26 minutes of ordinary capture.

Where it is in the code (v3.1.0, b586c2a)

  • src/iai_mcp/migrate/_to_lilli.py
    • migrate_sqlite_to_lilli (def at line 432): streams every table with plain INSERT and records report.rows_copied[table] = copied (line 541) from the source cursor, so rows copied can never reflect a finalize-time delete.
    • line 570: _compact_aged_tombstones_at_finalize(dst, report) is called inside the same function, after the copy and the ANN rebuild.
    • _compact_aged_tombstones_at_finalize (def at line 275): computes drop_cutoff = _source_time_now(dst) - timedelta(seconds=cfg.tombstone_ttl_sec) and calls batched_tombstone_drop(tbl, "tombstoned_at IS NOT NULL AND tombstoned_at < '<cutoff>'") at line 328. It also untombstones pinned / never_decay rows first (tbl.update(where=…, values={"tombstoned_at": None, "live": 1})), which would diverge from the source under a byte-parity verifier too; not exercised here (pinned=0 everywhere in this store), noted for completeness.
    • _source_time_now (def at line 225): "now" is MAX(created_at) over the copied records, so the predicate ages against the store's own timeline, which is why a store that has simply been running for more than a week always has candidates.
    • The docstring of the finalize function states: "any failure is logged and recorded on the report; the migrated DATA and MigrateReport must survive regardless (the aged bloat is then cleaned up by the first nightly sleep cycle instead)". The nightly path is src/iai_mcp/lilli/cycle/sleep_pipeline/_optimize.py lines 92–100, same batched_tombstone_drop.
  • src/iai_mcp/maintenance.py line 439: batched_tombstone_drop — physical DELETE in batches of 100.
  • src/iai_mcp/daemon_config.py line 10: _ERASURE_DEFAULT_TOMBSTONE_TTL_SEC: int = 604800; line 78: read from IAI_MCP_ERASURE_TOMBSTONE_TTL_SEC in _load_erasure_config (any int > 0 accepted).
  • src/iai_mcp/migrate/_to_lilli_swap.py
    • line 330: report = migrate_sqlite_to_lilli(src_db, staging_root, batch=batch) (finalize compaction has already run when this returns).
    • line 336: verify_report = verify_store_equality(str(src_db), str(staging_root), key, src_root=live_root).
    • lines 340–346: on not verify_report.ok, blockers are copied from the failing dimensions and the function returns before any rename ("the staging tree is left in place for inspection").
  • src/iai_mcp/migrate/_to_lilli_verify.py
    • _ALL_TABLES (line 52): records, edges, events, budget_ledger, ratelimit_ledger, _hippo_meta.
    • _count (line 126): SELECT COUNT(*) AS n FROM {table} — no predicate.
    • _verify_counts (line 194): returns RED on the first table where src != dst, reason f"{table}: src={sn} dst={dn} ({delta:+d})".
    • _co_scan_bytes (line 225), used by _verify_bytes (278) and _verify_codec (685): streams every source row by id and returns "{table} id={rid} missing on dst" on the first miss; _verify_decrypt (310) does the same for the encrypted columns. All four therefore fail on the first aged tombstone.
    • verify_store_equality (line 707), docstring: "Return GREEN only when src (SQLite) and dst (lilli) are byte-equal."

Expected

Either the swap verifies GREEN with the compaction accounted for, or the compaction does not run before the equality gate. A store that has been running normally for eight days should not be un-migratable with the documented command, and the failure output should not present the tool's own deletion as a copy loss.

Suggested fixes (any one closes it)

  1. Move the finalize compaction after the verify gate in swap_to_lilli (or into the first daemon open of the new store). The docstring already treats the nightly sleep step as the equivalent path, so deferring it costs nothing. This is the smallest change.
  2. Make the verifier compaction-aware: pass report.tombstone_compact_dropped and the cutoff into verify_store_equality, and have _verify_counts / the co-scans exclude source rows matching the same tombstoned_at < cutoff predicate (asserting that the destination is missing exactly those, which is a stronger check than today's).
  3. At minimum, print report.tombstone_compact_dropped in the CLI summary and mention it in the A_counts blocker text, so a -526 reads as "526 aged tombstones compacted at finalize" instead of as lost data.

Workaround for users on 3.1.0

iai-mcp daemon stop
IAI_MCP_ERASURE_TOMBSTONE_TTL_SEC=31536000 iai-mcp migrate-to-lilli --src ~/.iai-mcp/hippo/brain.sqlite3 --swap          # preview
IAI_MCP_ERASURE_TOMBSTONE_TTL_SEC=31536000 iai-mcp migrate-to-lilli --src ~/.iai-mcp/hippo/brain.sqlite3 --swap --apply --yes
iai-mcp daemon start

The override applies only to that process; the daemon started afterwards uses the normal TTL and its sleep cycle compacts the aged tombstones on its own schedule. Verified on the store above: GREEN, 8,572 = 8,572, doctor (gg) now reports "native engine format".

LC1207 avatar Sep 08 '26 06:09 LC1207

Fixed in v3.2.0 (pip install -U iai-pme). migrate-to-lilli is now a faithful verbatim copy — aged-tombstone cleanup moved off the migration path to the nightly consolidation cycle, so store equality verifies by construction. The env-disable workaround is no longer needed. Thanks for the excellent report, @LC1207 — you named the exact contradiction.

CodeAbra avatar Sep 09 '26 00:09 CodeAbra