Keep a durable Mail peer event log, projection and epoch continuity #159

Closed
opened 2026-11-03 07:27:15 +00:00 by svc-agent-writer · 2 comments

Outcome

The sync writer keeps a durable, immutable v1 event log and a reference projection, proves continuity across restarts and restores, and trims history to a bounded floor. No peer tool is added. Unit 1 of the epic #152.

Decision substrate

ADR 0012 (rules 2–8, 11, 12), ADR 0010, the contract kit contracts/mind-v1/ (README and recovery.md), and ADR 0008 for the envelope rules. The grill record is on #152.

Scope and acceptance criteria

  1. Schema v16: peer_events (seq INTEGER PRIMARY KEY AUTOINCREMENT; entity, kind, account, at, the authorised envelope for an add, previous revision and time) and peer_entities (entity, account, add sequence, current revision and time, envelope, deletion sequence).
  2. Store._emit(...) beside every existing changes insert, in the same transaction, at every mutation path: IMAP and stable-id adds, flags, deletes, stable-id moves, drop_mailbox, and the orphan and stable-id migrations. Inventory every writer and reader in the spec. A guard test fails on any statement that writes messages without _emit. changes and mail_changes stay byte-identical.
  3. Envelopes follow ADR 0008 lowercasing and filtering; an absent or invalid address is an empty list. Enforce the 32,768-byte field cap, 1,024 addresses per field and 320 characters per address; a record that cannot fit is recorded so unit 2 can return record_too_large, never truncated.
  4. The v16 migration builds peer_entities from current rows in one transaction at the first start of the new writer, records the base watermark, and keeps #151's source_id and epoch.
  5. The marker file <db>.peer-marker ({source_id, epoch, max_seq}), written atomically after every event-emitting transaction; a failed write fails closed. At startup: a non-empty log with no marker, or a database max_seq below the marker's, starts a new epoch.
  6. Epoch rotation in one transaction: delete every peer_events row, rebuild peer_entities at a new base watermark, write the new epoch and a new HMAC cursor key in meta, rewrite the marker. mailmind peer new-identity does the same with a new source_id. Document both in the restore and clone runbook.
  7. A [peer] config section: retention_seconds (default 604,800) and snapshot_lease_seconds (default 3,600); the config check refuses retention shorter than twice the lease. The writer records the floor in meta, then trims expired peer_events and tombstones in bounded batches after each sync pass. config.example.toml documents the section.
  8. Recovery evidence: P01 (writer terminated before and after a domain commit), P02 (add, then delete or move before the consumer reads; the add envelope stays replayable), P03 (API and writer restart keep identity, epoch and the marker), P04 (restore behind the marker and onto a fresh volume start a new epoch; event identities are never reused), and the writer half of P05 (trimming keeps a trustworthy floor). Each test drives the real Store.
  9. make check passes. First-start migration time measured on the 210k-row benchmark store and reported in the PR.

Non-goals

Any MCP tool (mail_peer_info, mail_peer_changes_v1, mail_peer_snapshot_v1), any ADR 0008 tool-list change, People consumer changes, release or deploy.

Blocked by

## Outcome The sync writer keeps a durable, immutable v1 event log and a reference projection, proves continuity across restarts and restores, and trims history to a bounded floor. No peer tool is added. Unit 1 of the epic #152. ## Decision substrate ADR 0012 (rules 2–8, 11, 12), ADR 0010, the contract kit `contracts/mind-v1/` (README and `recovery.md`), and ADR 0008 for the envelope rules. The grill record is on #152. ## Scope and acceptance criteria 1. Schema v16: `peer_events` (`seq INTEGER PRIMARY KEY AUTOINCREMENT`; entity, kind, account, `at`, the authorised envelope for an `add`, previous revision and time) and `peer_entities` (entity, account, add sequence, current revision and time, envelope, deletion sequence). 2. `Store._emit(...)` beside every existing `changes` insert, in the same transaction, at every mutation path: IMAP and stable-id adds, flags, deletes, stable-id moves, `drop_mailbox`, and the orphan and stable-id migrations. Inventory every writer and reader in the spec. A guard test fails on any statement that writes `messages` without `_emit`. `changes` and `mail_changes` stay byte-identical. 3. Envelopes follow ADR 0008 lowercasing and filtering; an absent or invalid address is an empty list. Enforce the 32,768-byte field cap, 1,024 addresses per field and 320 characters per address; a record that cannot fit is recorded so unit 2 can return `record_too_large`, never truncated. 4. The v16 migration builds `peer_entities` from current rows in one transaction at the first start of the new writer, records the base watermark, and keeps #151's `source_id` and epoch. 5. The marker file `<db>.peer-marker` (`{source_id, epoch, max_seq}`), written atomically after every event-emitting transaction; a failed write fails closed. At startup: a non-empty log with no marker, or a database `max_seq` below the marker's, starts a new epoch. 6. Epoch rotation in one transaction: delete every `peer_events` row, rebuild `peer_entities` at a new base watermark, write the new epoch and a new HMAC cursor key in `meta`, rewrite the marker. `mailmind peer new-identity` does the same with a new `source_id`. Document both in the restore and clone runbook. 7. A `[peer]` config section: `retention_seconds` (default 604,800) and `snapshot_lease_seconds` (default 3,600); the config check refuses retention shorter than twice the lease. The writer records the floor in `meta`, then trims expired `peer_events` and tombstones in bounded batches after each sync pass. `config.example.toml` documents the section. 8. Recovery evidence: P01 (writer terminated before and after a domain commit), P02 (add, then delete or move before the consumer reads; the add envelope stays replayable), P03 (API and writer restart keep identity, epoch and the marker), P04 (restore behind the marker and onto a fresh volume start a new epoch; event identities are never reused), and the writer half of P05 (trimming keeps a trustworthy floor). Each test drives the real Store. 9. `make check` passes. First-start migration time measured on the 210k-row benchmark store and reported in the PR. ## Non-goals Any MCP tool (`mail_peer_info`, `mail_peer_changes_v1`, `mail_peer_snapshot_v1`), any ADR 0008 tool-list change, People consumer changes, release or deploy. ## Blocked by - dev/mail-mind-mcp#162 — ADR 0012; the substrate must be on `main` before Half-A.
Collaborator

⏸ SVD architect gate: dev/mail-mind-mcp#159 keep-a-durable-mail-peer-event-log-projection-and-epoch-cont

Status: CLEAN after 0 rework round(s) · 0 blocking defect(s) · 0 lens(es) INCONCLUSIVE (could not run) · 0 lens(es) DEGRADED (deterministic denial) · complexity substrate · dispatch effort high

Run: 20261103T080321Z-d724f809

Held because: CLEAN but 7 open risk(s) (2 verification · 5 decision) — HOLD-ALL parks everything. The risks, verbatim:

Open risks:

  1. Marker-missing rule. ADR 0012 rule 6 starts a new epoch only when the log is not empty and the marker is missing. The spec rotates whenever the marker is missing after v16 init, because init writes the first marker. Under the literal rule, a restored copy whose log is empty or fully trimmed would continue an epoch whose later seqs the live system already issued, which breaks P04. Question: accept the stricter rule (lean), or keep the literal ADR wording and amend the ADR? [decision]
  2. AC2's 'orphan migration' has no distinct code path: grep -n orphan src returns nothing. The spec maps it to drop_mailbox for a mailbox gone from the server (ingest.py:131-133), and the stable-id migration to retire_imap_rows (jmap.py:644). Question: did the #152 grill mean another path? [decision]
  3. rename_mailbox (store.py:1593-1607) rewrites mailbox/mailboxes of stable-id rows without a changes row, so under ADR 0012 rule 3 pairing it emits no peer event, and People sees no move for a renamed folder. Question: confirm no event (lean), or emit 'move' and let the changes/feed pairing diverge? [decision]
  4. Scope ceiling. The written set is exactly 16 files: 9 mechanical schema 15→16 test updates plus test_peer_evidence.py. New tests therefore go in tests/test_store.py rather than a new file, and SECURITY.md:11 ('Clone/restore identity safety is pending #152') stays stale. Any further breaking test cannot be absorbed without a re-slice. Question: accept, or land the schema-version test bumps as a preceding PR? [decision]
  5. The v16 first-start projection build over the 210k-row benchmark store may exceed the api's 60 s SCHEMA_WAIT_SECONDS. Check: the PR reports the measured seconds (bench_search build(), reset peer_base_seq and peer_entities, time Store(path)). If it is over 60 s, record whether the api container restarted once on the first deploy. [verification]
  6. mailmind peer new-identity takes no lock against a running sync writer, so their marker writes can race; the outcome is an extra epoch rotation at the next start, which is the safe direction. The runbook says to stop sync first. Question: is documentation enough (lean), or should the CLI refuse while a writer is active? [decision]
  7. Each event-emitting transaction adds one fsync of the marker. Check after deploy: compare 'backfill batch' and 'pass complete' durations in the sync logs for one day before and after the upgrade on the live pod. [verification]

Change: 1. Schema v16 in store.py _TABLES. Add peer_events (seq AUTOINCREMENT, like wakes at store.py:192-203; an immutability trigger, like the actions triggers at store.py:181-188; a CHECK that only 'add' rows carry an envelope). Add peer_entities (WITHOUT ROWID, entity is the primary key under BINARY collation, a partial index on tombstones).
2. Store._emit(conn, kind, account, mailbox, uidvalidity, uid, source_id, at, headers), called right after each of the 8 INSERT INTO changes sites in the same _tx: upsert_messages:905, update_flags:984, delete_uids:1002, drop_mailbox:810, record_move:1500, update_source_flags:1567, delete_sources:1586, retire_imap_rows:1626. Only the SELECT/RETURNING lists that locate the row are widened (source_id, from_addr, to_addrs, cc_addrs). The changes SQL itself is never altered.
3. Entity is the same rule as ids.encode (ids.py:55-58), reached through a function-level import, because ids.py imports Store at module level.
4. The envelope comes from evidence.address and evidence.addresses filtered by the contract pattern ^[^\s@,]+@[^\s@,]+$. Records over the 320-char, 1,024-address or 32,768-byte caps are stored in full and flagged oversize=1, never truncated.
5. Marker hook inside _tx (store.py:731-742). The payload is read inside the transaction; after COMMIT it is written atomically (tmp file, fsync, os.replace, as in cli.py:264-269), and a write failure raises.
6. Startup goes between the identity transaction (store.py:638-641) and the schema_version publish (store.py:642-647). If peer_base_seq is missing, run _init_peer: one transaction that bumps sqlite_sequence to W = max_seq + 1 and builds the projection in fetchmany batches, keeping identity. Otherwise check continuity: rotate when the marker is missing or corrupt, its identity differs, or its max_seq is above the database's.
7. rotate_epoch and new_identity, plus a mailmind peer new-identity subparser following the keys block (cli.py:317-324).
8. trim_peer: record a monotonic floor, then delete in batches of 1,000 (shape of _fill_utc_keys at store.py:667-684). It runs after each pass in SyncWorker._loop (source.py:445) and in run_once.
9. PeerConfig after SyncConfig (config.py:131-162), with a model_validator requiring retention >= 2 x lease.
10. A README "Restore and clone" runbook section, and a [peer] section in config.example.toml.

Files: src/mail_mind_mcp/store.py · src/mail_mind_mcp/config.py · src/mail_mind_mcp/cli.py · src/mail_mind_mcp/source.py · config.example.toml · README.md · tests/test_store.py · tests/test_peer_evidence.py · tests/test_mailbox_search.py · tests/test_embed_scans.py · tests/test_copy_collapse.py · tests/test_recipients.py · tests/test_attachment_vectors.py · tests/test_attachments.py · tests/test_utc_dates.py · tests/test_evidence.py

Decision: accept the 7 open risk(s) above and dispatch this spec (svd:go), or park (svd:skip) / re-spec (svd:respec)?

Your call (when this issue is held at the gate via svd:hold):

  • add label svd:go — approve; Half-B dispatch accepts exactly this spec (open risks accepted)
  • add label svd:fire beside svd:go — approve AND authorise the Half-B fire from the phone; never on its own
  • add label svd:skip — park it; dispatch refuses it and the issue stays for a human
  • add label svd:respec — discard this spec; the next Half-A run re-produces it with this record as prior-attempt context

Spec: /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-03-keep-a-durable-mail-peer-event-log-projection-and-epoch-cont.md — next: codex-svd dispatch --args '<same-json>' --approved-spec-path /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-03-keep-a-durable-mail-peer-event-log-projection-and-epoch-cont.md

### ⏸ SVD architect gate: dev/mail-mind-mcp#159 keep-a-durable-mail-peer-event-log-projection-and-epoch-cont **Status:** CLEAN after 0 rework round(s) · 0 blocking defect(s) · 0 lens(es) INCONCLUSIVE (could not run) · 0 lens(es) DEGRADED (deterministic denial) · complexity `substrate` · dispatch effort `high` **Run:** `20261103T080321Z-d724f809` **Held because:** CLEAN but 7 open risk(s) (2 verification · 5 decision) — HOLD-ALL parks everything. The risks, verbatim: **Open risks:** 1. Marker-missing rule. ADR 0012 rule 6 starts a new epoch only when the log is not empty and the marker is missing. The spec rotates whenever the marker is missing after v16 init, because init writes the first marker. Under the literal rule, a restored copy whose log is empty or fully trimmed would continue an epoch whose later seqs the live system already issued, which breaks P04. Question: accept the stricter rule (lean), or keep the literal ADR wording and amend the ADR? [decision] 2. AC2's 'orphan migration' has no distinct code path: `grep -n orphan src` returns nothing. The spec maps it to drop_mailbox for a mailbox gone from the server (ingest.py:131-133), and the stable-id migration to retire_imap_rows (jmap.py:644). Question: did the #152 grill mean another path? [decision] 3. rename_mailbox (store.py:1593-1607) rewrites mailbox/mailboxes of stable-id rows without a changes row, so under ADR 0012 rule 3 pairing it emits no peer event, and People sees no move for a renamed folder. Question: confirm no event (lean), or emit 'move' and let the changes/feed pairing diverge? [decision] 4. Scope ceiling. The written set is exactly 16 files: 9 mechanical schema 15→16 test updates plus test_peer_evidence.py. New tests therefore go in tests/test_store.py rather than a new file, and SECURITY.md:11 ('Clone/restore identity safety is pending #152') stays stale. Any further breaking test cannot be absorbed without a re-slice. Question: accept, or land the schema-version test bumps as a preceding PR? [decision] 5. The v16 first-start projection build over the 210k-row benchmark store may exceed the api's 60 s SCHEMA_WAIT_SECONDS. Check: the PR reports the measured seconds (bench_search build(), reset peer_base_seq and peer_entities, time Store(path)). If it is over 60 s, record whether the api container restarted once on the first deploy. [verification] 6. `mailmind peer new-identity` takes no lock against a running sync writer, so their marker writes can race; the outcome is an extra epoch rotation at the next start, which is the safe direction. The runbook says to stop sync first. Question: is documentation enough (lean), or should the CLI refuse while a writer is active? [decision] 7. Each event-emitting transaction adds one fsync of the marker. Check after deploy: compare 'backfill batch' and 'pass complete' durations in the sync logs for one day before and after the upgrade on the live pod. [verification] **Change:** 1. Schema v16 in store.py _TABLES. Add peer_events (seq AUTOINCREMENT, like wakes at store.py:192-203; an immutability trigger, like the actions triggers at store.py:181-188; a CHECK that only 'add' rows carry an envelope). Add peer_entities (WITHOUT ROWID, entity is the primary key under BINARY collation, a partial index on tombstones). 2. Store._emit(conn, kind, account, mailbox, uidvalidity, uid, source_id, at, headers), called right after each of the 8 INSERT INTO changes sites in the same _tx: upsert_messages:905, update_flags:984, delete_uids:1002, drop_mailbox:810, record_move:1500, update_source_flags:1567, delete_sources:1586, retire_imap_rows:1626. Only the SELECT/RETURNING lists that locate the row are widened (source_id, from_addr, to_addrs, cc_addrs). The changes SQL itself is never altered. 3. Entity is the same rule as ids.encode (ids.py:55-58), reached through a function-level import, because ids.py imports Store at module level. 4. The envelope comes from evidence.address and evidence.addresses filtered by the contract pattern ^[^\s@,]+@[^\s@,]+$. Records over the 320-char, 1,024-address or 32,768-byte caps are stored in full and flagged oversize=1, never truncated. 5. Marker hook inside _tx (store.py:731-742). The payload is read inside the transaction; after COMMIT it is written atomically (tmp file, fsync, os.replace, as in cli.py:264-269), and a write failure raises. 6. Startup goes between the identity transaction (store.py:638-641) and the schema_version publish (store.py:642-647). If peer_base_seq is missing, run _init_peer: one transaction that bumps sqlite_sequence to W = max_seq + 1 and builds the projection in fetchmany batches, keeping identity. Otherwise check continuity: rotate when the marker is missing or corrupt, its identity differs, or its max_seq is above the database's. 7. rotate_epoch and new_identity, plus a `mailmind peer new-identity` subparser following the keys block (cli.py:317-324). 8. trim_peer: record a monotonic floor, then delete in batches of 1,000 (shape of _fill_utc_keys at store.py:667-684). It runs after each pass in SyncWorker._loop (source.py:445) and in run_once. 9. PeerConfig after SyncConfig (config.py:131-162), with a model_validator requiring retention >= 2 x lease. 10. A README "Restore and clone" runbook section, and a [peer] section in config.example.toml. **Files:** `src/mail_mind_mcp/store.py` · `src/mail_mind_mcp/config.py` · `src/mail_mind_mcp/cli.py` · `src/mail_mind_mcp/source.py` · `config.example.toml` · `README.md` · `tests/test_store.py` · `tests/test_peer_evidence.py` · `tests/test_mailbox_search.py` · `tests/test_embed_scans.py` · `tests/test_copy_collapse.py` · `tests/test_recipients.py` · `tests/test_attachment_vectors.py` · `tests/test_attachments.py` · `tests/test_utc_dates.py` · `tests/test_evidence.py` **Decision:** accept the 7 open risk(s) above and dispatch this spec (`svd:go`), or park (`svd:skip`) / re-spec (`svd:respec`)? **Your call** (when this issue is held at the gate via `svd:hold`): - add label `svd:go` — approve; Half-B dispatch accepts exactly this spec (open risks accepted) - add label `svd:fire` **beside** `svd:go` — approve AND authorise the Half-B fire from the phone; never on its own - add label `svd:skip` — park it; dispatch refuses it and the issue stays for a human - add label `svd:respec` — discard this spec; the next Half-A run re-produces it with this record as prior-attempt context <sub>Spec: `/Users/piers/.local/state/exhaust/groupthink/specs/2026-11-03-keep-a-durable-mail-peer-event-log-projection-and-epoch-cont.md` — next: `codex-svd dispatch --args '<same-json>' --approved-spec-path /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-03-keep-a-durable-mail-peer-event-log-projection-and-epoch-cont.md`</sub>
Collaborator

spec-verify-dispatch Half B for dev/mail-mind-mcp#159 keep-a-durable-mail-peer-event-log-projection-and-epoch-cont completed integration verify.

  • PR: #163
  • Branch: feat/svd-dev-mail-mind-mcp-159-keep-a-durable-mail-peer-event-b585edf8
  • Commit: 73b8414ec3
  • Build: none
  • Test: green
  • Reader audit clean: True
  • Spec fidelity: True
  • Ready for merge: True
  • Check ci/woodpecker/pr/validation: green https://ci.groupthink.asia/repos/72/pipeline/20/1
  • Checks: required ci/woodpecker/pr/validation resolved pass by CI-wait poll
  • Warning: The spec's Acceptance Criteria require the PR body to report the v16 first-start time on the 210k-row benchmark store. I did not check the PR body for it.
  • Warning: Spec Open Risks 5 and 7 (migration time against the 60 s SCHEMA_WAIT_SECONDS, and marker fsync cost) are post-deploy verification items.
  • CI wait: ci/woodpecker/pr/validation -> pass
  • Decision: review the PR and merge? (codex-svd ship --run-id 20261103T083717Z-b585edf8 --confirm-merge)
spec-verify-dispatch Half B for dev/mail-mind-mcp#159 keep-a-durable-mail-peer-event-log-projection-and-epoch-cont completed integration verify. - PR: https://git.groupthink.asia/dev/mail-mind-mcp/pulls/163 - Branch: feat/svd-dev-mail-mind-mcp-159-keep-a-durable-mail-peer-event-b585edf8 - Commit: 73b8414ec35c5f4321c0b2b9067418dd60ae554e - Build: none - Test: green - Reader audit clean: True - Spec fidelity: True - Ready for merge: True - Check ci/woodpecker/pr/validation: green https://ci.groupthink.asia/repos/72/pipeline/20/1 - Checks: required ci/woodpecker/pr/validation resolved pass by CI-wait poll - Warning: The spec's Acceptance Criteria require the PR body to report the v16 first-start time on the 210k-row benchmark store. I did not check the PR body for it. - Warning: Spec Open Risks 5 and 7 (migration time against the 60 s SCHEMA_WAIT_SECONDS, and marker fsync cost) are post-deploy verification items. - CI wait: ci/woodpecker/pr/validation -> pass - Decision: review the PR and merge? (`codex-svd ship --run-id 20261103T083717Z-b585edf8 --confirm-merge`)
Sign in to join this conversation.
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
dev/mail-mind-mcp#159
No description provided.