plan: Mail architecture (MA1–MA9) #915

Closed
kayg wants to merge 0 commits from plan/mail-architecture into dev
Owner

Needs kayg's review. Do not merge. Design only (no code, no measurements). Plan: docs/plans/mail-architecture.md.

Covers MA1-MA9: components and data flow, storage layout and schemas (state.db / mail.db / bodies.db + .eml mirror), stable message identity, sizes and big-O, sync/backfill/connection limits, device tiers (spine, headers, bodies), search changes, action pipeline and offline queue, send/undo/send-later, remote content and HTML cleaning, wrapped-key credential design with an explicit threat table, Apple Mail proxy on the shared IMAP front-end, deep links, failure table with user-facing words, perf budgets, the scaling and spam-scroll tests for the first PR, phased PR sequence with gates, and 20 numbered open questions (each with a recommendation).

Findings worth a look:

  • SearchProvider::list(user) returns every item at startup; it does not scale to millions of messages. Needs list_since in a separate search PR.
  • ADR 0046 says devices store Maildir; the plan changes that to a SQLite/IndexedDB cache plus on-demand Mail/ files.
  • Proxy UIDs need the ADR 0069 hazard handled (restored state could reuse a UID); plan generalises imap-uid and bumps UIDVALIDITY when unproven.
  • Search for existing work: no open PR or issue covers mail (#868 is the grill).

Refs #868.

Part of Calternal Mail planning. 🤖 Generated with Claude Code

**Needs kayg's review. Do not merge.** Design only (no code, no measurements). Plan: `docs/plans/mail-architecture.md`. Covers MA1-MA9: components and data flow, storage layout and schemas (`state.db` / `mail.db` / `bodies.db` + `.eml` mirror), stable message identity, sizes and big-O, sync/backfill/connection limits, device tiers (spine, headers, bodies), search changes, action pipeline and offline queue, send/undo/send-later, remote content and HTML cleaning, wrapped-key credential design with an explicit threat table, Apple Mail proxy on the shared IMAP front-end, deep links, failure table with user-facing words, perf budgets, the scaling and spam-scroll tests for the first PR, phased PR sequence with gates, and 20 numbered open questions (each with a recommendation). Findings worth a look: - `SearchProvider::list(user)` returns every item at startup; it does not scale to millions of messages. Needs `list_since` in a separate search PR. - ADR 0046 says devices store Maildir; the plan changes that to a SQLite/IndexedDB cache plus on-demand `Mail/` files. - Proxy UIDs need the ADR 0069 hazard handled (restored state could reuse a UID); plan generalises `imap-uid` and bumps UIDVALIDITY when unproven. - Search for existing work: no open PR or issue covers mail (#868 is the grill). Refs #868. Part of Calternal Mail planning. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
plan: Mail architecture (MA1–MA9)
Some checks failed
CI / server (pull_request) Has been cancelled
CI / rust (pull_request) Has been cancelled
CI / web (pull_request) Has been cancelled
Markdown extraction contract / markdown-native-contract (pull_request) Has been cancelled
Markdown extraction contract / markdown-editor-contract (pull_request) Has been cancelled
5c3d58af59
Design only: components, storage, sizes and big-O, action pipeline,
failure table, key wrapping, Apple Mail proxy, deep links, phased
delivery with gates, and open questions for review.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Author
Owner

Review: mail architecture plan (docs/plans/mail-architecture.md @ plan/mail-architecture)

I checked the plan against origin/dev: crates/core/src/search.rs, crates/search/src/indexer.rs, crates/store, crates/engine/src/execute.rs, crates/imap-uid, docs/storage.md and ADRs 0011, 0044, 0046, 0047, 0059, 0062, 0069.

Claims that check out: the search trait really does have list() at startup and per-entry touched(). There is no IMAP listener anywhere in crates/ (only imap-uid). Store is one FIFO writer thread per user. .eml is unclaimed text, so it goes on HDD under the 0062 tiering amendment. ADR 0046 really does say "Mail is stored as Maildir".

Sections that are fine as written: §2 (crate split, Caps-driven trait), §7 backfill passes and push, §14 deep links, §19 build-or-buy. The over-engineering risk is low. Mode P is deferred to P11, which is right.


P1: must fix before approval

P1-1. §3 Identity: the rules contradict each other, and a move can mint a new id.

  • Rule 1 says "fingerprint found → add the placement to that msg id". Rule 4 and the failure table say "same Message-ID twice → two msg ids, dup_of". With identical headers, the fingerprint is identical, so rule 1 always wins and rule 4 can't happen.
  • On non-Gmail IMAP a real COPY is a second message at the provider, but rule 1 folds it into one msg id. Then mail.trash on that id is ambiguous: which placement does it act on? And §15 "provider delete → remove placements; mirror file → Trash" moves the only mirror file to Trash while the other copy still exists.
  • Failure scenario: basic IMAP or CONDSTORE, a user moves a message Inbox → Project in another client. The Inbox delta (IDLE, seconds) sees the expunge before the Project timed delta (5 min) sees the add. The row is deleted and its fingerprint goes with it. Five minutes later the add mints a new msg id. Every note or task holding /mail/m/<old> (ML7) now breaks, which is exactly what §3 promises can't happen.
  • Fix:
    • (a) Use the provider's stable message id first: Gmail X-GM-MSGID, JMAP id, IMAP OBJECTID EMAILID (RFC 8474; the plan uses OBJECTID only for mailboxes). Fingerprint is the fallback only.
    • (b) Keep a tombstone (fingerprint → msg id, plus the mirror file in Trash) for the 30-day Trash window, so a late add re-attaches.
    • (c) A message row and its mirror file go only when the last placement goes.
    • (d) Define copy and duplicate semantics in one rule. Without a provider id, the same fingerprint inside one folder = duplicate; in another folder = an extra placement until a delete proves it was a move.
    • Add a fixture: "move seen as delete-then-add 5 min apart keeps the id".

P1-2. §10 Device outbox op id loses repeated intents.

  • "Installation + target + new state" drops the base that ADR 0047's recipe has (it uses Installation, file id, base hash and new hash).
  • Failure scenario: mark read → unread → read. The first and third requests get the same id. The executor (execute.rs: same key + same payload hash → replay the stored result) returns the first result, and the third action never runs. The thread stays unread, and the server-side op (INSERT OR IGNORE on the hash of the key) drops it too.
  • Fix: include the device's last-seen change_seq for the target (the base), or a per-Installation monotonic counter, in the id.
  • Test: toggling the same flag N times offline ends in the last state.

P1-3. §10 / §15 Send recovery still has a double-send path.

  • "Not found [in Sent] and no 2xx → retry" can't be decided after a crash, because the 2xx was only ever held in memory.
  • On plain IMAP providers our Sent copy is our own APPEND, which runs after SMTP. A crash after the final . but before the APPEND therefore always finds nothing in Sent, and the mail gets sent again. The §15 row "SMTP refused or timeout … 4xx retried 3 times" also lumps a timeout after the final . (unknown outcome) in with a real 4xx.
  • Fix:
    • Split submitting into connecting (safe to retry) and data_sent (from the moment the final . is written, never retry automatically). Persist the SMTP reply before the APPEND.
    • In data_sent with no recorded reply: look in Sent only where the provider saves Sent itself (Gmail, JMAP). Everywhere else go straight to unknown with the existing sentence.
    • Test: kill at each of these points: after RCPT, after the final ., after the reply, after the APPEND.

P1-4. §4 / §13 Bcc and envelope recipients have nowhere to live.

  • outgoing stores only mime. The proxy "picks the account by the From header and hands it to the same send pipeline".
  • Failure scenario: Apple Mail sends with a Bcc. Bcc recipients exist only in RCPT TO, so they are silently not delivered. Or, if a pipeline puts Bcc in the headers to keep it, the Bcc list leaks to every recipient.
  • Fix: add outgoing.rcpt (an envelope list) and mail_from. The composer strips Bcc from the MIME and keeps it in the envelope. The proxy uses its RCPT TO list verbatim.
  • Test: a Bcc via the composer and via the proxy reaches the Bcc mailbox, and the delivered bytes have no Bcc: header.

P1-5. §8 The spine can't render the lists Gate 2 is about.

  • A spine row is id, last date, sender, subject, unread, flags, category, count. There is no account, no folder or label set, and no per-folder sort key (thread_folder.last_ms differs from thread.last_ms, e.g. Sent versus Inbox).
  • Failure scenario: someone flings through Archive or the Unified Inbox past the 5,000-thread headers window. The device can't tell which spine rows belong to that list or in what order, so it shows blanks or asks the server. That breaks Gate 2 for every list except one.
  • Fix: the spine carries thread_folder membership in compact form (folder rid, role, category, last_ms, unread), about 16 B per membership. Re-state the size: Gmail threads average 2–3 labels.
  • The spam_scroll_content test must cover a non-Inbox folder and the Unified Inbox, not only the Inbox.

P1-6. §4 / §8 / §9 Rebuildable mail.db resets change.seq under every device and search cursor.

  • mail.db is "drop and rebuild" (§15), but change.seq lives in it. After a rebuild, seq restarts at 1. A device holding cursor 2,000,000 sees "nothing new" for days, and search's planned list_since(watermark) skips everything.
  • Fix: keep a mail_epoch (random, written at create) in state.db and in every cursor. An epoch mismatch → re-read the spine and do a full search reconcile.
  • Test: delete mail.db while a device and search are mid-stream; both converge.

P1-7. §13 Proxy without CONDSTORE makes Apple Mail's flag sync O(N) per folder per poll.

  • With no CONDSTORE/QRESYNC, Mail.app re-checks flags with UID FETCH 1:* (FLAGS). On a 100k-message unified Archive, that is 100k rows per folder per refresh, per Mac, forever. It is the exact per-device O(mailbox) cost the requirements forbid.
  • "Calls plugin actions" also needs care. An action returns one serde_json::Value (ActionResponse), so a 1:* answer would be a single huge Value, which breaks the 8 MB per-connection limit.
  • Fix:
    • Ship CONDSTORE (per-virtual-folder HIGHESTMODSEQ, derived from change.seq + epoch) in P9, not "later".
    • The front-end uses a paged read action (a keyset over proxy_uid ≤ 500 rows per call) and streams the replies.
    • Gate: Mail.app's steady-state refresh of an idle 100k-message folder costs O(changes) on the server.

P1-8. §12 Threat table: "a backup without the server's key file: Safe" is false with today's backup procedure.

  • docs/storage.md backs up the whole SSD system/ tree together with users/ ("copying both trees together"). system/invite.key is in that set, and system/mail.key "like invite.key" would be too.
  • Failure scenario: any copy of a coordinated backup holds both state.db and mail.key, so every app password in it can be read in Always-on mode.
  • Fix: put mail.key outside the coordinated backup set, with its own escrow step in storage.md (or systemd-creds/TPM from day one). Or correct the row to "Not safe" and say so in Settings.
  • Add a P3 test that a standard backup tarball contains no mail.key.

P1-9. §11 Network-safety list misses the ranges this deployment actually lives on.

  • Every incoming mail makes the server fetch sender-chosen URLs at ingest, with no user action. "Private, loopback, link-local and metadata" does not name 100.64.0.0/10 (CGNAT: the NetBird mesh where dev, prod and Forgejo hosts sit on *.vpn.kayg.org).
  • It also misses IPv4-mapped ::ffff:0:0/96, NAT64 64:ff9b::/96, 6to4 2002::/16, ULA fc00::/7, 0.0.0.0/8, and the server's own public addresses.
  • Fix: list the ranges explicitly in the plan, allow port 443 only, refuse IP-literal hosts, and use one deny-list function shared with backdrops (ADR 0039).
  • Test: a fixture mail with <img> pointing at each range and at a NetBird hostname; none is connected to.

P2: should fix in the plan

P2-1. §4 / §10 Overlay keyed by msg alone.

  • With overlay(msg PK, op_id, …), two pending ops on one message (archive, then flag) collide. Rolling back op A drops op B's change as well.
  • Also, step 4 clears the overlay (state.db) before or without atomically applying the result to mail.db. The thread flickers back, and a crash between the two leaves stale state until the next delta.
  • Fix: key the overlay as (msg, op_id), or derive it from the pending op rows. Apply to mail.db first, then clear the overlay (idempotent).

P2-2. §4 Journal hints plus a private change table supersede ADR 0044; this isn't a "clarification" (Q13).

  • 0044 says "No adapter keeps a separate event stream or sync rules", and MCP Events cursors map to journal positions. With this plan, MCP subscribers get only mail.changed hints.
  • Fix: write a 0044 amendment and say how MCP Events and the API read mail changes.
  • Also define change retention and compaction (one row per ref, latest kind). Otherwise a 2M-message backfill leaves 2M+ rows forever.

P2-3. §9 The search change is only half of it.

  • reconcile() also loads index.stamps(p.id()) into a HashMap of every held item: 2M entries per start, even with list_since.
  • Fix: the watermark is stored in the search index in the same transaction as the docs, the mail provider's reconcile skips the stamp map, and the full list runs only on an epoch change (P1-6) or a rebuild.

P2-4. §5 Startup sweep and orphan detection need a walk of Mail/.

  • "Orphan .tmp swept at start" and "finished file with no row (matched by id in its name)" can only be found by walking up to 2M files. §5 itself forbids that.
  • Fix: write temp files to Mail/<account>/.incoming/ (same filesystem) and sweep only that directory. Order the steps as: mail.db row with mirror_state = pending + target path → tmp → rename → ok. On restart, look only at pending rows.
  • Also list every Home walker (notes scan, Files watcher, quota accounting, File Provider enumeration, backups) and say how each skips or handles Mail/. Quota must come from counters, never from du.

P2-5. §15 "Rebuild from .eml names + provider" doesn't work as written.

  • Names carry the msg id, but re-linking to the provider needs the fingerprint (Message-ID, Date, From, Subject), and the name has only a 60-char subject. A rebuild therefore parses the headers of every file: about 2M random HDD reads, hours.
  • Fix: either a small msg id → fingerprint map in state.db (about 50 B × 2M ≈ 100 MB, so state it), or say the rebuild parses headers (the first 8 KB) in the background with a stated rate and budget. With P1-1(a), the provider id makes most of this unneeded.

P2-6. §3 / §13 Same fingerprint, different bytes.

  • Mailing-list copies of a message you were also Cc'd on share Message-ID, Date, From and Subject but differ in bytes (footers, List-*).
  • One msg id gets one mirror file, so the second copy's bytes are never kept, and proxy BODY[] for that placement serves the wrong bytes (RFC822.SIZE mismatch confuses Mail.app).
  • Fix: the mirror and BODY[] go per content hash; the msg id may point at several content hashes.

P2-7. §13 UIDVALIDITY bump must come from the authority, and category churn re-UIDs.

  • ADR 0069 keeps UIDVALIDITY and the floor in a host-owned authority outside backups and disables writes when the floor is unproved. The plan's bump is a deliberate deviation (fine, but it needs an ADR).
  • The new UIDVALIDITY value itself must come from that authority. If it came from the backed-up state.db, a restore could reuse an old UIDVALIDITY.
  • The §4 table lists "proxy UID counters" as backed-up state.db data. State that the counters there are only a cache.
  • Separately: the unified Inbox is "People only", so every category re-run or override moves messages out and back in. Each re-entry needs a new UID, and a background re-categorisation of 10k messages makes Mail.app re-download 10k. Give the background category lane a churn budget, or keep the unified Inbox membership stable once exposed.

P2-8. §13 Sent duplicates and identities.

  • Apple Mail APPENDs to Sent itself, often before our post-send copy exists, so the "drop if already in Sent" check misses it and both copies land.
  • Fix: for proxy submissions, skip our own Sent copy and let Mail's APPEND be the copy (dedupe by Message-ID in outgoing).
  • account.address is a single column, but Fastmail aliases and Gmail send-as are common. A legitimate From then gets 553. Add an identity table.

P2-9. §11 Fetching images at ingest for the whole history.

  • 2M messages × ~10–20 images each is tens of millions of outbound requests, many to dead hosts, into a 2 GB LRU that evicts them almost immediately.
  • Fix: fetch at ingest only inside the device headers window (90 days / 5k threads); older mail fetches at open (Q7's own fallback).
  • Also needed: a url_hash → content_hash, state table (cleaned HTML is written before images exist, so it must reference a URL id), and /mail/img/* scoped to the requesting user's cache.

P2-10. §8 The spine on web and phones.

  • The ceiling case is 140 MB (more with P1-5) in IndexedDB. Safari evicts script-writable storage under pressure, and after 7 days unused for non-installed sites; the full re-download then happens silently.
  • Fix: a per-device spine cap (e.g. the newest 200k threads per device, with the server answering beyond that), and Gate 2 stated within the cap. Also say what an eviction looks like to the person (nothing, just a refill).

P2-11. §16 / §17 / §18 Gates that can't run as written.

  • (a) The 1M and 2M fixtures with a raw mirror (60–120 GB) don't fit the perf VMs (7 GB RAM, shared disk, 15 GB free floor). Split the gates: DB, search and list gates at 1M–2M with synthetic rows and no raw; raw, mirror and open gates at 100k.
  • (b) spam_scroll_content and spam_scroll_frames are in P1, but the UI is P6. Move them to P6, or give P1 a minimal list view.
  • (c) The 10-26 process rule says "no dev landing without UI". P1–P5 are backend-only. Say how they land: a mail integration branch, or each PR with a thin UI.

P3: nice to fix

  1. §7 connections: "interactive 1 reserved" should mean never lent out, not held open. Gmail's 15-connection limit is shared with the person's phone and other clients, and idle reserved sockets get dropped. Steady state should be the watch connection only.
  2. §7 basic IMAP: expunges older than the 2,000-UID window linger up to a day (until the daily sweep). State it. Actions on those messages already roll back with "no longer exists", which is fine.
  3. §10 drafts: autosave on IMAP is APPEND new + expunge old. A crash in between leaves duplicates at the provider. Tag drafts with X-Calternal-Draft-Id and dedupe at start. State who wins when Apple Mail edits the same draft.
  4. §5 Trash: mail.delete_forever and mass provider-side deletes both put files in Calternal Trash for 30 days, against explicit intent, and the count goes against quota. Make delete_forever skip Trash.
  5. §4 file names: sanitise subjects (/, NUL, control characters, NFC, 255-byte limit, trailing dots). Subjects in file names show up on every synced device, so check that against the privacy line in §14 ("ids carry no subject").
  6. §16 accept p95 ≤ 50 ms: a durable state.db commit is one fsync. Perf-01/02 contended fsync is 60+ ms. Use group commit, or state the budget for quiet disks only.
  7. §13: "front-end never touches databases" conflicts with BODY[] reading file offsets. Say the action hands back a file handle or stream.
  8. §13: submission scope "imap.mail or smtp.mail": pick one (rec: imap.mail covers both, since it's one macOS account).
  9. ADR 0046: it also says "mail headers sync fully". The new ADR must change that line too, not only the Maildir sentence.
  10. Tiering: state that no format plugin may claim .eml. Under 0062, a claim would pull the whole mirror (120 GB worst case) onto SSD.
  11. Account removal: the confirm box must say queued and scheduled sends are cancelled (§15 "drop ops").
  12. §12 PRF: the PRF eval salt is per user and stored. Say where.
  13. §11 display: say sandbox without allow-same-origin. List the attributes the rewriter covers (srcset, <picture><source>, background=, SVG <image href>, poster, image-set(), @import, @font-face). The CSP is the backstop.

Counts: P1 9 · P2 11 · P3 13

## Review: mail architecture plan (docs/plans/mail-architecture.md @ plan/mail-architecture) I checked the plan against `origin/dev`: `crates/core/src/search.rs`, `crates/search/src/indexer.rs`, `crates/store`, `crates/engine/src/execute.rs`, `crates/imap-uid`, `docs/storage.md` and ADRs 0011, 0044, 0046, 0047, 0059, 0062, 0069. **Claims that check out:** the search trait really does have `list()` at startup and per-entry `touched()`. There is no IMAP listener anywhere in `crates/` (only `imap-uid`). Store is one FIFO writer thread per user. `.eml` is unclaimed text, so it goes on HDD under the 0062 tiering amendment. ADR 0046 really does say "Mail is stored as Maildir". **Sections that are fine as written:** §2 (crate split, `Caps`-driven trait), §7 backfill passes and push, §14 deep links, §19 build-or-buy. The over-engineering risk is low. Mode P is deferred to P11, which is right. --- ### P1: must fix before approval **P1-1. §3 Identity: the rules contradict each other, and a move can mint a new id.** - Rule 1 says "fingerprint found → add the placement to that msg id". Rule 4 and the failure table say "same Message-ID twice → two msg ids, `dup_of`". With identical headers, the fingerprint is identical, so rule 1 always wins and rule 4 can't happen. - On non-Gmail IMAP a real `COPY` is a second message at the provider, but rule 1 folds it into one msg id. Then `mail.trash` on that id is ambiguous: which placement does it act on? And §15 "provider delete → remove placements; mirror file → Trash" moves the *only* mirror file to Trash while the other copy still exists. - **Failure scenario:** basic IMAP or CONDSTORE, a user moves a message Inbox → Project in another client. The Inbox delta (IDLE, seconds) sees the expunge before the Project timed delta (5 min) sees the add. The row is deleted and its fingerprint goes with it. Five minutes later the add mints a **new** msg id. Every note or task holding `/mail/m/<old>` (ML7) now breaks, which is exactly what §3 promises can't happen. - **Fix:** - (a) Use the provider's stable message id first: Gmail `X-GM-MSGID`, JMAP `id`, IMAP `OBJECTID` `EMAILID` (RFC 8474; the plan uses OBJECTID only for mailboxes). Fingerprint is the fallback only. - (b) Keep a tombstone (fingerprint → msg id, plus the mirror file in Trash) for the 30-day Trash window, so a late add re-attaches. - (c) A message row and its mirror file go only when the **last** placement goes. - (d) Define copy and duplicate semantics in one rule. Without a provider id, the same fingerprint inside one folder = duplicate; in another folder = an extra placement until a delete proves it was a move. - Add a fixture: "move seen as delete-then-add 5 min apart keeps the id". **P1-2. §10 Device outbox op id loses repeated intents.** - "Installation + target + new state" drops the base that ADR 0047's recipe has (it uses Installation, file id, **base hash** and new hash). - **Failure scenario:** mark read → unread → read. The first and third requests get the same id. The executor (`execute.rs`: same key + same payload hash → replay the stored result) returns the first result, and the third action never runs. The thread stays unread, and the server-side `op` (`INSERT OR IGNORE` on the hash of the key) drops it too. - **Fix:** include the device's last-seen `change_seq` for the target (the base), or a per-Installation monotonic counter, in the id. - Test: toggling the same flag N times offline ends in the last state. **P1-3. §10 / §15 Send recovery still has a double-send path.** - "Not found [in Sent] and no 2xx → retry" can't be decided after a crash, because the 2xx was only ever held in memory. - On plain IMAP providers our Sent copy is our own `APPEND`, which runs *after* SMTP. A crash after the final `.` but before the `APPEND` therefore always finds nothing in Sent, and the mail gets sent again. The §15 row "SMTP refused or timeout … 4xx retried 3 times" also lumps a timeout after the final `.` (unknown outcome) in with a real 4xx. - **Fix:** - Split `submitting` into `connecting` (safe to retry) and `data_sent` (from the moment the final `.` is written, never retry automatically). Persist the SMTP reply before the `APPEND`. - In `data_sent` with no recorded reply: look in Sent only where the provider saves Sent itself (Gmail, JMAP). Everywhere else go straight to `unknown` with the existing sentence. - Test: kill at each of these points: after RCPT, after the final `.`, after the reply, after the APPEND. **P1-4. §4 / §13 Bcc and envelope recipients have nowhere to live.** - `outgoing` stores only `mime`. The proxy "picks the account by the From header and hands it to the same send pipeline". - **Failure scenario:** Apple Mail sends with a Bcc. Bcc recipients exist only in `RCPT TO`, so they are silently not delivered. Or, if a pipeline puts Bcc in the headers to keep it, the Bcc list leaks to every recipient. - **Fix:** add `outgoing.rcpt` (an envelope list) and `mail_from`. The composer strips Bcc from the MIME and keeps it in the envelope. The proxy uses its `RCPT TO` list verbatim. - Test: a Bcc via the composer and via the proxy reaches the Bcc mailbox, and the delivered bytes have no `Bcc:` header. **P1-5. §8 The spine can't render the lists Gate 2 is about.** - A spine row is `id, last date, sender, subject, unread, flags, category, count`. There is no account, no folder or label set, and no per-folder sort key (`thread_folder.last_ms` differs from `thread.last_ms`, e.g. Sent versus Inbox). - **Failure scenario:** someone flings through `Archive` or the Unified Inbox past the 5,000-thread headers window. The device can't tell which spine rows belong to that list or in what order, so it shows blanks or asks the server. That breaks Gate 2 for every list except one. - **Fix:** the spine carries `thread_folder` membership in compact form (folder rid, role, category, last_ms, unread), about 16 B per membership. Re-state the size: Gmail threads average 2–3 labels. - The `spam_scroll_content` test must cover a non-Inbox folder and the Unified Inbox, not only the Inbox. **P1-6. §4 / §8 / §9 Rebuildable `mail.db` resets `change.seq` under every device and search cursor.** - `mail.db` is "drop and rebuild" (§15), but `change.seq` lives in it. After a rebuild, seq restarts at 1. A device holding cursor 2,000,000 sees "nothing new" for days, and search's planned `list_since(watermark)` skips everything. - **Fix:** keep a `mail_epoch` (random, written at create) in `state.db` and in every cursor. An epoch mismatch → re-read the spine and do a full search reconcile. - Test: delete `mail.db` while a device and search are mid-stream; both converge. **P1-7. §13 Proxy without CONDSTORE makes Apple Mail's flag sync O(N) per folder per poll.** - With no CONDSTORE/QRESYNC, Mail.app re-checks flags with `UID FETCH 1:* (FLAGS)`. On a 100k-message unified Archive, that is 100k rows per folder per refresh, per Mac, forever. It is the exact per-device O(mailbox) cost the requirements forbid. - "Calls plugin actions" also needs care. An action returns one `serde_json::Value` (`ActionResponse`), so a `1:*` answer would be a single huge Value, which breaks the 8 MB per-connection limit. - **Fix:** - Ship CONDSTORE (per-virtual-folder `HIGHESTMODSEQ`, derived from `change.seq` + epoch) in P9, not "later". - The front-end uses a paged read action (a keyset over `proxy_uid` ≤ 500 rows per call) and streams the replies. - Gate: Mail.app's steady-state refresh of an idle 100k-message folder costs O(changes) on the server. **P1-8. §12 Threat table: "a backup without the server's key file: Safe" is false with today's backup procedure.** - `docs/storage.md` backs up the whole SSD `system/` tree together with `users/` ("copying both trees together"). `system/invite.key` is in that set, and `system/mail.key` "like invite.key" would be too. - **Failure scenario:** any copy of a coordinated backup holds both `state.db` and `mail.key`, so every app password in it can be read in Always-on mode. - **Fix:** put `mail.key` outside the coordinated backup set, with its own escrow step in `storage.md` (or systemd-creds/TPM from day one). Or correct the row to "Not safe" and say so in Settings. - Add a P3 test that a standard backup tarball contains no `mail.key`. **P1-9. §11 Network-safety list misses the ranges this deployment actually lives on.** - Every incoming mail makes the server fetch sender-chosen URLs at ingest, with no user action. "Private, loopback, link-local and metadata" does not name **100.64.0.0/10** (CGNAT: the NetBird mesh where dev, prod and Forgejo hosts sit on `*.vpn.kayg.org`). - It also misses IPv4-mapped `::ffff:0:0/96`, NAT64 `64:ff9b::/96`, 6to4 `2002::/16`, ULA `fc00::/7`, `0.0.0.0/8`, and the server's own public addresses. - **Fix:** list the ranges explicitly in the plan, allow port 443 only, refuse IP-literal hosts, and use one deny-list function shared with backdrops (ADR 0039). - Test: a fixture mail with `<img>` pointing at each range and at a NetBird hostname; none is connected to. --- ### P2: should fix in the plan **P2-1. §4 / §10 Overlay keyed by `msg` alone.** - With `overlay(msg PK, op_id, …)`, two pending ops on one message (archive, then flag) collide. Rolling back op A drops op B's change as well. - Also, step 4 clears the overlay (`state.db`) before or without atomically applying the result to `mail.db`. The thread flickers back, and a crash between the two leaves stale state until the next delta. - **Fix:** key the overlay as `(msg, op_id)`, or derive it from the pending `op` rows. Apply to `mail.db` first, then clear the overlay (idempotent). **P2-2. §4 Journal hints plus a private `change` table supersede ADR 0044; this isn't a "clarification" (Q13).** - 0044 says "No adapter keeps a separate event stream or sync rules", and MCP Events cursors map to journal positions. With this plan, MCP subscribers get only `mail.changed` hints. - **Fix:** write a 0044 amendment and say how MCP Events and the API read mail changes. - Also define `change` retention and compaction (one row per ref, latest kind). Otherwise a 2M-message backfill leaves 2M+ rows forever. **P2-3. §9 The search change is only half of it.** - `reconcile()` also loads `index.stamps(p.id())` into a `HashMap` of every held item: 2M entries per start, even with `list_since`. - **Fix:** the watermark is stored in the search index in the same transaction as the docs, the mail provider's reconcile skips the stamp map, and the full list runs only on an epoch change (P1-6) or a rebuild. **P2-4. §5 Startup sweep and orphan detection need a walk of `Mail/`.** - "Orphan `.tmp` swept at start" and "finished file with no row (matched by id in its name)" can only be found by walking up to 2M files. §5 itself forbids that. - **Fix:** write temp files to `Mail/<account>/.incoming/` (same filesystem) and sweep only that directory. Order the steps as: `mail.db` row with `mirror_state = pending` + target path → tmp → rename → `ok`. On restart, look only at `pending` rows. - Also list every Home walker (notes scan, Files watcher, quota accounting, File Provider enumeration, backups) and say how each skips or handles `Mail/`. Quota must come from counters, never from `du`. **P2-5. §15 "Rebuild from `.eml` names + provider" doesn't work as written.** - Names carry the msg id, but re-linking to the provider needs the fingerprint (Message-ID, Date, From, Subject), and the name has only a 60-char subject. A rebuild therefore parses the headers of every file: about 2M random HDD reads, hours. - **Fix:** either a small `msg id → fingerprint` map in `state.db` (about 50 B × 2M ≈ 100 MB, so state it), or say the rebuild parses headers (the first 8 KB) in the background with a stated rate and budget. With P1-1(a), the provider id makes most of this unneeded. **P2-6. §3 / §13 Same fingerprint, different bytes.** - Mailing-list copies of a message you were also Cc'd on share Message-ID, Date, From and Subject but differ in bytes (footers, `List-*`). - One msg id gets one mirror file, so the second copy's bytes are never kept, and proxy `BODY[]` for that placement serves the wrong bytes (`RFC822.SIZE` mismatch confuses Mail.app). - **Fix:** the mirror and `BODY[]` go per content hash; the msg id may point at several content hashes. **P2-7. §13 UIDVALIDITY bump must come from the authority, and category churn re-UIDs.** - ADR 0069 keeps UIDVALIDITY and the floor in a host-owned authority *outside* backups and disables writes when the floor is unproved. The plan's bump is a deliberate deviation (fine, but it needs an ADR). - The new UIDVALIDITY value itself must come from that authority. If it came from the backed-up `state.db`, a restore could reuse an old UIDVALIDITY. - The §4 table lists "proxy UID counters" as backed-up `state.db` data. State that the counters there are only a cache. - Separately: the unified `Inbox` is "People only", so every category re-run or override moves messages out and back in. Each re-entry needs a new UID, and a background re-categorisation of 10k messages makes Mail.app re-download 10k. Give the background category lane a churn budget, or keep the unified Inbox membership stable once exposed. **P2-8. §13 Sent duplicates and identities.** - Apple Mail `APPEND`s to Sent itself, often *before* our post-send copy exists, so the "drop if already in Sent" check misses it and both copies land. - **Fix:** for proxy submissions, skip our own Sent copy and let Mail's `APPEND` be the copy (dedupe by Message-ID in `outgoing`). - `account.address` is a single column, but Fastmail aliases and Gmail send-as are common. A legitimate From then gets 553. Add an `identity` table. **P2-9. §11 Fetching images at ingest for the whole history.** - 2M messages × ~10–20 images each is tens of millions of outbound requests, many to dead hosts, into a 2 GB LRU that evicts them almost immediately. - **Fix:** fetch at ingest only inside the device headers window (90 days / 5k threads); older mail fetches at open (Q7's own fallback). - Also needed: a `url_hash → content_hash, state` table (cleaned HTML is written before images exist, so it must reference a URL id), and `/mail/img/*` scoped to the requesting user's cache. **P2-10. §8 The spine on web and phones.** - The ceiling case is 140 MB (more with P1-5) in IndexedDB. Safari evicts script-writable storage under pressure, and after 7 days unused for non-installed sites; the full re-download then happens silently. - **Fix:** a per-device spine cap (e.g. the newest 200k threads per device, with the server answering beyond that), and Gate 2 stated within the cap. Also say what an eviction looks like to the person (nothing, just a refill). **P2-11. §16 / §17 / §18 Gates that can't run as written.** - (a) The 1M and 2M fixtures with a raw mirror (60–120 GB) don't fit the perf VMs (7 GB RAM, shared disk, 15 GB free floor). Split the gates: DB, search and list gates at 1M–2M with synthetic rows and no raw; raw, mirror and open gates at 100k. - (b) `spam_scroll_content` and `spam_scroll_frames` are in P1, but the UI is P6. Move them to P6, or give P1 a minimal list view. - (c) The 10-26 process rule says "no dev landing without UI". P1–P5 are backend-only. Say how they land: a `mail` integration branch, or each PR with a thin UI. --- ### P3: nice to fix 1. **§7 connections:** "interactive 1 reserved" should mean *never lent out*, not *held open*. Gmail's 15-connection limit is shared with the person's phone and other clients, and idle reserved sockets get dropped. Steady state should be the watch connection only. 2. **§7 basic IMAP:** expunges older than the 2,000-UID window linger up to a day (until the daily sweep). State it. Actions on those messages already roll back with "no longer exists", which is fine. 3. **§10 drafts:** autosave on IMAP is APPEND new + expunge old. A crash in between leaves duplicates at the provider. Tag drafts with `X-Calternal-Draft-Id` and dedupe at start. State who wins when Apple Mail edits the same draft. 4. **§5 Trash:** `mail.delete_forever` and mass provider-side deletes both put files in Calternal Trash for 30 days, against explicit intent, and the count goes against quota. Make delete_forever skip Trash. 5. **§4 file names:** sanitise subjects (`/`, NUL, control characters, NFC, 255-byte limit, trailing dots). Subjects in file names show up on every synced device, so check that against the privacy line in §14 ("ids carry no subject"). 6. **§16 accept p95 ≤ 50 ms:** a durable `state.db` commit is one fsync. Perf-01/02 contended fsync is 60+ ms. Use group commit, or state the budget for quiet disks only. 7. **§13:** "front-end never touches databases" conflicts with `BODY[]` reading file offsets. Say the action hands back a file handle or stream. 8. **§13:** submission scope "`imap.mail` or `smtp.mail`": pick one (rec: `imap.mail` covers both, since it's one macOS account). 9. **ADR 0046:** it also says "mail headers sync fully". The new ADR must change that line too, not only the Maildir sentence. 10. **Tiering:** state that no format plugin may claim `.eml`. Under 0062, a claim would pull the whole mirror (120 GB worst case) onto SSD. 11. **Account removal:** the confirm box must say queued and scheduled sends are cancelled (§15 "drop ops"). 12. **§12 PRF:** the PRF eval salt is per user and stored. Say where. 13. **§11 display:** say `sandbox` without `allow-same-origin`. List the attributes the rewriter covers (`srcset`, `<picture><source>`, `background=`, SVG `<image href>`, `poster`, `image-set()`, `@import`, `@font-face`). The CSP is the backstop. **Counts:** P1 9 · P2 11 · P3 13
Author
Owner

Revision 2 pushed (head 309c4c4a). Mapping of review comment 77512 to the plan (section numbers are in docs/plans/mail-architecture.md). Also folded in MB1–MB10 and MA7b (section 21); answered Q items removed; "journal" replaced by "save log" throughout.

P1

# Fix
P1-1 §3 rewritten: provider key first (X-GM-MSGID / JMAP id / EMAILID), one fingerprint rule as fallback only, duplicate vs placement rule, 30-day tombstone, row+file go only with the last placement, actions name a placement; fixture "move seen as delete-then-add 5 min apart" (§3, §15, §17 identity_moves)
P1-2 §10: op id = hash(Installation, target, base (epoch, seq), new state, per-Installation counter); op_ids test (§17)
P1-3 §10 send state machine held→connecting→data_sent→replied→copied→sent; data_sent fsynced before the final .; reply persisted before APPEND; timeout after . is unknown, not 4xx; JMAP/Gmail look-up, plain IMAP goes straight to unknown; four kill-point tests; §15 rows split
P1-4 §4 outgoing.mail_from, rcpt, MIME never holds Bcc; §10 Bcc rules; §13 proxy uses RCPT TO verbatim; test in §17 send_state_machine
P1-5 §8 spine carries folder/label memberships (folder, role, category, sort_ms, unread), size restated (~140 B/thread); Gate 2 now covers Inbox, Archive, Sent, label, category, Unified Inbox (§16, §17)
P1-6 §4 mail_epoch in state.db and in every cursor; retention/compaction of change; §9 search watermark; §15 rebuild row; change_feed_epoch test
P1-7 §13 CONDSTORE (and QRESYNC, Q20) in v1, proxy_change, mod-seqs in state.db/authority, paged mail.proxy_page ≤ 500, O(changes) gate; P10 gate
P1-8 §12 threat table corrected; §13a: secrets/mail.key in its own root outside every backup, docs/storage.md changes listed, escrow command, CI test that a backup tarball has no key
P1-9 §11: full deny-list table incl. 100.64/10, mapped/NAT64/6to4/ULA/link-local/metadata, own addresses; 443 only; IP literals refused; resolve once and connect to the checked IP; per hop; shared netguard crate; fixtures incl. NetBird host and rebinding

P2

# Fix
P2-1 §4 overlay keyed (msg, op_id); §10 step 4 apply to mail.db first, then clear overlay
P2-2 §9 + Q10: ADR 0044 amendment (hints name their cursor range; MCP/API read via mail.changes); change retention in §4
P2-3 §9 table: watermark stored in the search index in the same transaction; no stamp map for mail
P2-4 §5: pending row → .incoming/ → rename; recovery looks only at pending rows and .incoming/; table of every Home walker; quota from counters
P2-5 §4 id_map in state.db (~120 MB at 2M); §5 rebuild path and rate
P2-6 §3 rule 6 + §4 content table: one file per content hash; BODY[] per content version
P2-7 §13: UIDVALIDITY/floor/mod-seq come from the host-owned authority, state.db is a cache, ADR needed for the bump deviation; unified Inbox membership frozen at first exposure (no category churn)
P2-8 §13: proxy sends write no Sent copy, Mail's APPEND is the copy, dropped if caps.saves_sent; §4 identity table (MB9)
P2-9 §11: images fetched at ingest only inside the device window; img_ref table; /mail/img/* scoped to the user
P2-10 §8: per-device spine cap (200k web/phone, whole mailbox native), eviction behaviour, Q5
P2-11 §16 "Gate sizes that fit the perf VMs" (4c / 7.7 GiB / 23–45 GB free: 1M synthetic rows for DB and search, 100k real for raw, 2M by measured extrapolation, Q17); scroll tests moved to P6 (§17, §18); landing proposal Q16 (thin UI per PR from P2, P1 as the one approved backend-only exception)

P3 (all fixed in the text except two, §22): 1 §7 tokens not sockets · 2 §6 basic-IMAP expunge lag stated · 3 §10 drafts X-Calternal-Draft-Id and Apple-edit rule · 4 accepted: superseded by MB2 · 5 §4 file-name rule and privacy line · 6 accepted (group commit, quiet-disk budget, contended figure reported) · 7 §13 stream/handle · 8 §13 imap.mail covers submission · 9 §8 both ADR 0046 lines · 10 §4 no plugin may claim .eml · 11 §15 removal words · 12 §12 prf_salt in state.db · 13 §11 attribute list and sandbox without allow-same-origin.

Open for kayg: Q16 (how PRs land), Q17 (gate scale), Q18 (sign-in code in push payload), Q19, Q20, Q21 are new; the rest keep their numbers' recommendations (renumbered).

Revision 2 pushed (head 309c4c4a). Mapping of review comment 77512 to the plan (section numbers are in `docs/plans/mail-architecture.md`). Also folded in MB1–MB10 and MA7b (section 21); answered Q items removed; "journal" replaced by "save log" throughout. **P1** | # | Fix | |---|---| | P1-1 | §3 rewritten: provider key first (X-GM-MSGID / JMAP id / EMAILID), one fingerprint rule as fallback only, duplicate vs placement rule, 30-day tombstone, row+file go only with the last placement, actions name a placement; fixture "move seen as delete-then-add 5 min apart" (§3, §15, §17 `identity_moves`) | | P1-2 | §10: op id = hash(Installation, target, base `(epoch, seq)`, new state, per-Installation counter); `op_ids` test (§17) | | P1-3 | §10 send state machine `held→connecting→data_sent→replied→copied→sent`; `data_sent` fsynced before the final `.`; reply persisted before APPEND; timeout after `.` is unknown, not 4xx; JMAP/Gmail look-up, plain IMAP goes straight to `unknown`; four kill-point tests; §15 rows split | | P1-4 | §4 `outgoing.mail_from`, `rcpt`, MIME never holds Bcc; §10 Bcc rules; §13 proxy uses RCPT TO verbatim; test in §17 `send_state_machine` | | P1-5 | §8 spine carries folder/label memberships `(folder, role, category, sort_ms, unread)`, size restated (~140 B/thread); Gate 2 now covers Inbox, Archive, Sent, label, category, Unified Inbox (§16, §17) | | P1-6 | §4 `mail_epoch` in `state.db` and in every cursor; retention/compaction of `change`; §9 search watermark; §15 rebuild row; `change_feed_epoch` test | | P1-7 | §13 CONDSTORE (and QRESYNC, Q20) in v1, `proxy_change`, mod-seqs in `state.db`/authority, paged `mail.proxy_page` ≤ 500, O(changes) gate; P10 gate | | P1-8 | §12 threat table corrected; §13a: `secrets/mail.key` in its own root outside every backup, `docs/storage.md` changes listed, escrow command, CI test that a backup tarball has no key | | P1-9 | §11: full deny-list table incl. 100.64/10, mapped/NAT64/6to4/ULA/link-local/metadata, own addresses; 443 only; IP literals refused; resolve once and connect to the checked IP; per hop; shared `netguard` crate; fixtures incl. NetBird host and rebinding | **P2** | # | Fix | |---|---| | P2-1 | §4 overlay keyed `(msg, op_id)`; §10 step 4 apply to `mail.db` first, then clear overlay | | P2-2 | §9 + Q10: ADR 0044 amendment (hints name their cursor range; MCP/API read via `mail.changes`); `change` retention in §4 | | P2-3 | §9 table: watermark stored in the search index in the same transaction; no stamp map for mail | | P2-4 | §5: pending row → `.incoming/` → rename; recovery looks only at `pending` rows and `.incoming/`; table of every Home walker; quota from counters | | P2-5 | §4 `id_map` in `state.db` (~120 MB at 2M); §5 rebuild path and rate | | P2-6 | §3 rule 6 + §4 `content` table: one file per content hash; `BODY[]` per content version | | P2-7 | §13: UIDVALIDITY/floor/mod-seq come from the host-owned authority, `state.db` is a cache, ADR needed for the bump deviation; unified Inbox membership frozen at first exposure (no category churn) | | P2-8 | §13: proxy sends write no Sent copy, Mail's APPEND is the copy, dropped if `caps.saves_sent`; §4 `identity` table (MB9) | | P2-9 | §11: images fetched at ingest only inside the device window; `img_ref` table; `/mail/img/*` scoped to the user | | P2-10 | §8: per-device spine cap (200k web/phone, whole mailbox native), eviction behaviour, Q5 | | P2-11 | §16 "Gate sizes that fit the perf VMs" (4c / 7.7 GiB / 23–45 GB free: 1M synthetic rows for DB and search, 100k real for raw, 2M by measured extrapolation, Q17); scroll tests moved to P6 (§17, §18); landing proposal Q16 (thin UI per PR from P2, P1 as the one approved backend-only exception) | **P3** (all fixed in the text except two, §22): 1 §7 tokens not sockets · 2 §6 basic-IMAP expunge lag stated · 3 §10 drafts `X-Calternal-Draft-Id` and Apple-edit rule · 4 **accepted**: superseded by MB2 · 5 §4 file-name rule and privacy line · 6 **accepted** (group commit, quiet-disk budget, contended figure reported) · 7 §13 stream/handle · 8 §13 `imap.mail` covers submission · 9 §8 both ADR 0046 lines · 10 §4 no plugin may claim `.eml` · 11 §15 removal words · 12 §12 `prf_salt` in `state.db` · 13 §11 attribute list and sandbox without `allow-same-origin`. Open for kayg: Q16 (how PRs land), Q17 (gate scale), Q18 (sign-in code in push payload), Q19, Q20, Q21 are new; the rest keep their numbers' recommendations (renumbered).
Author
Owner

Re-review: mail architecture plan, revision 2 (head 309c4c4a)

Checked docs/plans/mail-architecture.md @ 309c4c4a against review 77512, mapping 77514 and origin/dev: crates/core/src/search.rs, crates/search/src/indexer.rs, crates/store/src/{lib,writer}.rs, crates/engine/src/execute.rs, crates/imap-uid, docs/storage.md, perf/README-perf-vms.md, ADR 0044/0046/0069.

Code facts used below:

  • store keeps idempotency receipts for 7 days (idempotency_retention), then prunes them.
  • store runs one transaction per commit with synchronous=NORMAL (FULL only for Once). There is no group commit today.
  • imap-uid is a model crate that nothing depends on (only its own Cargo.toml). No server flag or root configures an authority yet.
  • docs/storage.md has two roots (--data, --state), and system/ (with invite.key) is in the state backup.

The revision is a real improvement. Most P1s are properly closed. What's left is mostly new edge cases inside the new rules, plus four items that are only partly fixed.


1. First-review findings

# Verdict Notes
P1-1 identity fixed (new edge cases: N-4, N-5) Provider key first, one fallback rule, tombstone, last-placement rule, actions name a placement, fixtures. The core scenario (delete then add 5 min apart) is covered.
P1-2 op ids fixed (new: N-3) Base + per-Installation counter, op_ids test.
P1-3 send recovery fixed (new: N-1, N-6) State machine, data_sent fsynced before the final ., reply persisted before APPEND, plain IMAP goes straight to unknown, kill points.
P1-4 Bcc / envelope fixed mail_from, rcpt, MIME without Bcc, proxy uses RCPT TO verbatim, test.
P1-5 spine fixed (new: N-2) Memberships with sort_ms, size restated, Gate 2 covers six lists.
P1-6 epoch partly §4 prose and §15 say a rebuild writes a new epoch. The schema comment says mail_epoch … random at create, never reset. Built from the schema, this brings the original silent-skip bug back. "Starts with the same epoch only if the rebuild proves it can continue numbering" is undefined, and a rebuild after losing mail.db can never prove that. Fix: a rebuild always means a new epoch. Store the epoch with the change table (in mail.db, created with it) or rotate it in state.db inside the rebuild, and delete the "never reset" comment.
P1-7 proxy CONDSTORE fixed (new: N-7) CONDSTORE + QRESYNC in v1, proxy_change, mail.proxy_page, O(changes) gate.
P1-8 key in backups fixed §13a: --secrets root outside the coordinated backup, storage.md changes listed, escrow, CI tarball test. This matches the real two-root layout.
P1-9 deny-list fixed for images (new: N-8) Full table, 443 only, IP literals refused, resolve-once-connect-to-checked, every redirect hop, fixtures. Provider connections are not covered (N-8).
P2-1 overlay fixed (msg, op_id), apply to mail.db first, then clear.
P2-2 ADR 0044 fixed Amendment specified (hint names its range, MCP/API go through mail.changes), change compaction.
P2-3 search reconcile fixed Watermark in the index, same transaction, no stamp map. That matches indexer.rs:221-223.
P2-4 mirror walks fixed .incoming/, pending rows only, walker table, counters for quota.
P2-5 rebuild fixed (size: N-P3-2) id_map in state.db; header-parse fallback with a stated rate.
P2-6 content versions partly Rule 6 says the same fingerprint with different bytes = one msg id with several content versions. Rule 2 says the same fingerprint in the same folder = a new msg id with dup_of. The common case (a list copy and a direct Cc copy both in Inbox) matches both rules and gets different answers. Fix: rule 2 decides placement vs duplicate. Rule 6 applies only within one placement chain (cross-folder), and a dup_of row has its own single content version. Say so in one sentence and add the in-Inbox case to identity_moves.
P2-7 UIDVALIDITY authority partly The rule is right, but the authority it leans on doesn't exist. imap-uid is unused and has no configured root. §13a adds --secrets and doesn't mention the authority root at all. Fix: name the authority's location (rec: the same host-owned --secrets root, outside backups, so one root holds all non-restorable host state). Put it in §13a's storage.md change list, in P0's ADR, and in P10's scope. Also say the authority hands out mod-sequences in reservations like UIDs (4096), or every flag change becomes a host-file fsync.
P2-8 Sent dupes / identities fixed (new: N-6) No Calternal Sent copy for proxy sends, identity table.
P2-9 images at ingest fixed Device window only, img_ref, per-user scope.
P2-10 spine cap fixed (but see N-2) 200k web/phone, eviction behaviour stated, Q5.
P2-11 gates / landing partly (a) The split into 1M synthetic / 100k real / extrapolated 2M is right, but the 100k family has no disk margin (N-9). (b) The scroll tests moved to P6: fixed. (c) The landing rule has a second backend-only PR that isn't listed as an exception (N-10).
P3-1…3, 5, 7…13 fixed All present in the text.
P3-4, P3-6 accepted (§22) P3-4 superseded by MB2, fine. P3-6: see N-P3-5, because group commit is new code, not "the store's model".

Not fully fixed: 4 (P1-6, P2-6, P2-7, P2-11).


2. New findings

P1

N-1. §10 Partial RCPT TO acceptance re-sends to the recipients who already got it.

  • SMTP answers per recipient. To A and B gets 250, Bcc C gets 452 4.2.2 mailbox full (or a 450). DATA goes through, the final reply is 250, and A and B have the mail.
  • The state machine only knows "a 4xx reply is a real answer: retry (3 times)" and "SMTP refused → back to the composer as a draft". A retry of the message sends it to A and B a second time. Re-sending the draft by hand does the same.
  • This is exactly the "no blind second send" guarantee §10 makes.
  • Fix: persist the per-recipient RCPT replies in outgoing (e.g. rcpt_state BLOB, one code per recipient) before DATA. Automatic retries and Send again go only to recipients without a 2xx. Recipients with a 5xx produce one sentence ("Couldn't deliver to c@…: their mailbox is full"), and the rest counts as sent. Also, if every RCPT fails, don't send DATA.
  • Test: add "RCPT mixed 250/452/550" to send_state_machine: each recipient gets exactly one copy across all retries.

P2

N-2. §8 Lists show silent gaps below the spine's low-water mark.

  • The spine is "newest 200k threads by thread", and while filling it is "newest first". A list sorts by the membership's sort_ms, which can be much older than the thread's last_ms. Example: Sent rows for threads that got replies later, or Archive rows filed long ago in threads with fresh activity.
  • So below the boundary B (the oldest last_ms the device holds), the device has some rows for Sent or Archive but not all of them. Rows from threads outside the cap fall between them.
  • Failure: a phone with a 300k-thread mailbox, or any device mid-fill, scrolls Archive past B. It shows a list that looks complete but skips messages, with no prompt to ask the server. The person concludes the mail is gone. "The list ends at what we have and says so" doesn't trigger, because the list doesn't end; it has holes.
  • Fix: the device stores its spine low-water B per account. In every list, the device copy is authoritative only for rows with sort_ms ≥ B, and below that it switches to server pages (prefetched as for beyond-cap). Gate 2 and spam_scroll_content gain a case "folder whose old rows interleave with threads outside the cap" and a "mid-fill" case.

N-3. §10 A replay after 7 days re-runs an old action.

  • The executor's receipt is pruned after 7 days (store idempotency_retention). The server op row is the only other guard, and §10 never says how long applied ops are kept (the natural design deletes or clears them).
  • Failure: a phone sends "move to Project", the server applies it, and the reply is lost. The phone stays offline for 9 days and the person moves the thread to Archive on the web. The phone comes back and retries with the same id. The receipt is gone, the op row is gone, so the handler runs again and moves the thread back to Project.
  • Fix (O(1), no retention tuning): the server keeps a per-Installation high-water counter in state.db (the counter is already in the op id). An op whose counter ≤ the stored high-water for its Installation is answered as a replay, forever. The outbox sends in counter order. Add the case "retry after receipt pruning" to op_ids.

N-4. §3 Rule 2 races inside one delta: "move out and back" becomes a duplicate.

  • Basic IMAP, Inbox → Archive → Inbox in another client. One Inbox delta reports add uid 900 and expunge uid 5 for the same fingerprint.
  • If the add is processed first, rule 2 sees the fingerprint "in the same folder" (uid 5 still has a placement) and mints a new msg id with dup_of. The expunge then removes the last placement of the original id, which goes to the tombstone and Recently deleted.
  • Every /mail/m/<old> link now says "in Recently deleted" while the mail sits in Inbox under a new id.
  • Fix: apply removals before adds within one delta batch, and before declaring dup_of, check whether the matching placement still exists at the provider (one UID SEARCH UID <n> or the batch's expunge set). Add the fixture "move out and back within one delta window".

N-5. §3 / §5 Removing and re-adding an account changes every msg id.

  • Rule 1 mints msg id = blake3-128(account ‖ provider key), and account.id is a fresh BLOB on add. §5 says "Re-adding the same address finds the files by msg id and reuses them", and §15 drops indexes on removal.
  • After remove + re-add, every derived id is different, and for basic IMAP the random ids are gone with the dropped rows. So every ML7 link in notes and tasks breaks, and the kept .eml files are re-downloaded next to themselves.
  • Fix: derive the id input from a stable account key (provider + normalised address, kept in id_map / tombstones), not the row id. On removal, keep id_map rows for the 30-day window like other tombstones, so a re-add inside it re-attaches. Add the fixture "remove, re-add same address: links still open, no second file".

N-6. §13 Proxy submission: when Mail.app gets its reply, and what happens on a retry.

  • §13 hands the message to "the same send pipeline" and skips the hold, but doesn't say whether the listener answers 250 after outgoing is durable (then upstream failures must come back as a bounce or DSN, otherwise they are lost) or after the upstream reply (then a slow upstream exceeds Mail.app's timeout, Mail.app retries the submission, and the mail is sent twice).
  • "Duplicates are detected by Message-ID against outgoing" is written for the Sent APPEND, not for submission.
  • Fix: answer 250 once outgoing is durable. Dedupe submissions on (account, Message-ID, rcpt set) against outgoing (a repeat returns 250 and does nothing). An upstream refusal produces a local DSN into the account's Inbox in the proxy tree, plus the app's failure line. Add a test: submit twice with the same Message-ID, exactly one upstream send.

N-7. §13 After a mail.db rebuild or state.db restore, Mail.app keeps stale flags and stale UIDs.

  • proxy_uid stores only (vid, uid, msg), not the flags last exposed. After a mail.db rebuild, flags come fresh from the provider. Any change that happened while the old mail.db was broken or not yet synced never gets a proxy_change row, so CHANGEDSINCE reports nothing and Mail.app keeps the old flags forever.
  • Restore case: the restored state.db cache lacks UIDs that were handed out after the backup. The authority keeps the floor, so the messages get new UIDs above it. But nothing records that the old UIDs vanished, so QRESYNC's VANISHED (EARLIER) and CONDSTORE clients keep ghost copies.
  • Fix: (a) after a mail.db rebuild, give every exposed message one new mod-sequence (one O(N) pass, background lane), or store exposed flag bits in proxy_uid and diff them. (b) When the proxy_folder cache is behind the authority (next_uid lower), bump UIDVALIDITY for that folder, even though the floor is proved. That is the only state Mail.app recovers from cleanly. Add both to the P10 gate.
  • Related P3: proxy_change has no retention. Compact it to one row per (vid, uid) like change, and above a retention horizon answer QRESYNC with the client's known-UIDs path (RFC 7162 §3.2.5.2) instead of keeping history forever.

N-8. §11 / §2 netguard doesn't cover provider connections and autodetect.

  • netguard is shared with backdrops and the image proxy only. But accounts connects server-side to a person-chosen host and port ("any host"). Autodetect follows URLs and SRV records from the address's domain (autoconfig, .well-known/jmap). JMAP session objects hand back apiUrl / downloadUrl / eventSourceUrl that the server then calls.
  • On a multi-user server (invites, ADR 0059), that lets any account holder make the server connect to 100.64.0.0/10 mesh hosts or 127.0.0.1 on any port. The failure sentences ("couldn't verify mail.example.com's certificate", timeouts versus refusals) tell them what answered.
  • Fix: every mail-imap / mail-jmap / mail-smtp / autodetect / JMAP-session connection goes through netguard's resolve-once connector with the same deny-list (any port allowed only for the configured provider host). Add an admin allow-list for self-hosted mail on a private network (pairs with Q12). Fixtures: an IMAP host resolving to 100.64.x.x, and a JMAP session whose downloadUrl points at 127.0.0.1.

N-9. §16 The 100k raw-gate family has no disk margin on the perf VMs.

  • 23 GB free (the low end the plan quotes) minus the 15 GB floor leaves 8 GB, and the family is budgeted at "≤ 8 GB". That doesn't count the fake provider's own corpus: if the 100k × 60 KB messages are stored for it to serve, that's another ~6 GB, about 14 GB in total. The disk is also shared with perf-02 (both locks, but the other VM's leftovers still count).
  • Fix: the fake provider generates message bytes deterministically from (seed, index) and streams them (no source corpus on disk). The run aborts if df would cross 15 GB at any window, not only at start. If free space is under ~25 GB, the gate runs at 50k and says so in the report.

N-10. §18 "P1 is the one exception" isn't true: the search PR is a second backend-only landing.

  • P2 says the search PR (list_since, in-index watermark) "lands just before" P2. It has no UI and goes to dev on its own, which breaks the 10-26 rule the same way P1 does, but it isn't listed or asked about in Q16.
  • Fix: either fold the search change into P2 (it ships with the Mail tab list), or list it in Q16 as a second exception for kayg to approve. The same applies to P0 if ADR-only PRs count as landings (probably not, but say so).

N-11. §10 / §19 The send state machine needs a hook lettre doesn't have.

  • data_sent must be fsynced between writing the body and writing the final ., and the reply must be persisted before anything else. lettre's transport and its SmtpConnection::message() write the data and the terminating . in one call and return only the final response. Per-RCPT replies (N-1) aren't exposed either.
  • Fix: §19 and Q14 should say SMTP needs a small in-house client (EHLO, AUTH, MAIL, RCPT with per-recipient results, DATA/BDAT, a hook before the terminator), or a thin fork. Make it part of P1's spike, because the P9 gate depends on it.

P3

  1. §10 JMAP "not found → retry is safe" holds only while the server keeps EmailSubmission objects (RFC 8621 lets servers purge them). Check the $sent-style evidence or bound the window (do the lookup within minutes, else unknown).
  2. §4 id_map size. msg 16 + provider_key ≤ 20 + fp 32 + thread 16 + path_hash + row overhead, plus two secondary indexes (provider key, fp), comes to about 180–220 B per message, so ~400 MB at 2M, not ~120 MB. Restate it; it's backed up.
  3. §13 COPY → mail.move. There is no mail.copy action, and a cross-account MOVE (unified folder → another account's folder) is undefined. Add mail.copy and answer cross-account MOVE/COPY with NO and a plain text.
  4. §5 vs §3 rule 4. On basic IMAP a move is "one placement goes", so the file is never renamed and stays under Inbox/… while the mail lives in Archive. Rename to the surviving placement's folder when the file's path folder no longer has a placement.
  5. §4 group commit and fsync. The store has neither group commit nor FULL sync per commit (NORMAL in WAL). state.db needs its own writer with group commit, and data_sent / replied need FULL (or an explicit fsync). Call it new code in §4 instead of "follows the store crate's model", and put it in P1's gate.
  6. §16 "Cold start with 2M messages" is a budget, but §16 also says 2M is not run. Restate it at 1M with extrapolation. Also, "cold HDD" can't be measured on the perf VMs (one ext4 virtual disk, no HDD). Say how the page cache is dropped (needs root) or call it "cold page cache".
  7. §15 Quota reached. "Mirror growth stops" vs "new mail keeps flowing": say whether new mail is mirrored over quota (rec: yes for new mail, no for backfill), and whether bodies.db, images and the search share count (rec: no, they are caches).
  8. §12 Key rotation vs restore. Rotating mail.key makes older state.db backups need re-sign-in. Escrow should keep the previous key ids, or the docs should say a rotation invalidates older backups' S wraps.

Counts: new P1 1 · new P2 10 · new P3 8 (plus one related P3 under N-7). First-review findings not fully fixed: 4 (P1-6, P2-6, P2-7, P2-11).

## Re-review: mail architecture plan, revision 2 (head 309c4c4a) Checked `docs/plans/mail-architecture.md` @ 309c4c4a against review 77512, mapping 77514 and `origin/dev`: `crates/core/src/search.rs`, `crates/search/src/indexer.rs`, `crates/store/src/{lib,writer}.rs`, `crates/engine/src/execute.rs`, `crates/imap-uid`, `docs/storage.md`, `perf/README-perf-vms.md`, ADR 0044/0046/0069. Code facts used below: - `store` keeps idempotency receipts for **7 days** (`idempotency_retention`), then prunes them. - `store` runs one transaction per commit with `synchronous=NORMAL` (FULL only for `Once`). There is no group commit today. - `imap-uid` is a model crate that **nothing depends on** (only its own Cargo.toml). No server flag or root configures an authority yet. - `docs/storage.md` has two roots (`--data`, `--state`), and `system/` (with `invite.key`) is in the state backup. The revision is a real improvement. Most P1s are properly closed. What's left is mostly new edge cases inside the new rules, plus four items that are only partly fixed. --- ### 1. First-review findings | # | Verdict | Notes | |---|---|---| | P1-1 identity | **fixed** (new edge cases: N-4, N-5) | Provider key first, one fallback rule, tombstone, last-placement rule, actions name a placement, fixtures. The core scenario (delete then add 5 min apart) is covered. | | P1-2 op ids | **fixed** (new: N-3) | Base + per-Installation counter, `op_ids` test. | | P1-3 send recovery | **fixed** (new: N-1, N-6) | State machine, `data_sent` fsynced before the final `.`, reply persisted before APPEND, plain IMAP goes straight to `unknown`, kill points. | | P1-4 Bcc / envelope | **fixed** | `mail_from`, `rcpt`, MIME without Bcc, proxy uses RCPT TO verbatim, test. | | P1-5 spine | **fixed** (new: N-2) | Memberships with `sort_ms`, size restated, Gate 2 covers six lists. | | P1-6 epoch | **partly** | §4 prose and §15 say a rebuild writes a **new epoch**. The schema comment says `mail_epoch … random at create, never reset`. Built from the schema, this brings the original silent-skip bug back. "Starts with the same epoch only if the rebuild proves it can continue numbering" is undefined, and a rebuild after losing `mail.db` can never prove that. **Fix:** a rebuild always means a new epoch. Store the epoch with the `change` table (in `mail.db`, created with it) or rotate it in `state.db` inside the rebuild, and delete the "never reset" comment. | | P1-7 proxy CONDSTORE | **fixed** (new: N-7) | CONDSTORE + QRESYNC in v1, `proxy_change`, `mail.proxy_page`, O(changes) gate. | | P1-8 key in backups | **fixed** | §13a: `--secrets` root outside the coordinated backup, storage.md changes listed, escrow, CI tarball test. This matches the real two-root layout. | | P1-9 deny-list | **fixed for images** (new: N-8) | Full table, 443 only, IP literals refused, resolve-once-connect-to-checked, every redirect hop, fixtures. Provider connections are not covered (N-8). | | P2-1 overlay | **fixed** | `(msg, op_id)`, apply to `mail.db` first, then clear. | | P2-2 ADR 0044 | **fixed** | Amendment specified (hint names its range, MCP/API go through `mail.changes`), `change` compaction. | | P2-3 search reconcile | **fixed** | Watermark in the index, same transaction, no stamp map. That matches `indexer.rs:221-223`. | | P2-4 mirror walks | **fixed** | `.incoming/`, `pending` rows only, walker table, counters for quota. | | P2-5 rebuild | **fixed** (size: N-P3-2) | `id_map` in `state.db`; header-parse fallback with a stated rate. | | P2-6 content versions | **partly** | Rule 6 says the same fingerprint with different bytes = one `msg id` with several content versions. Rule 2 says the same fingerprint **in the same folder** = a new `msg id` with `dup_of`. The common case (a list copy and a direct Cc copy both in Inbox) matches both rules and gets different answers. **Fix:** rule 2 decides placement vs duplicate. Rule 6 applies only *within* one placement chain (cross-folder), and a `dup_of` row has its own single content version. Say so in one sentence and add the in-Inbox case to `identity_moves`. | | P2-7 UIDVALIDITY authority | **partly** | The rule is right, but the authority it leans on doesn't exist. `imap-uid` is unused and has no configured root. §13a adds `--secrets` and doesn't mention the authority root at all. **Fix:** name the authority's location (rec: the same host-owned `--secrets` root, outside backups, so one root holds all non-restorable host state). Put it in §13a's storage.md change list, in P0's ADR, and in P10's scope. Also say the authority hands out mod-sequences in reservations like UIDs (4096), or every flag change becomes a host-file fsync. | | P2-8 Sent dupes / identities | **fixed** (new: N-6) | No Calternal Sent copy for proxy sends, `identity` table. | | P2-9 images at ingest | **fixed** | Device window only, `img_ref`, per-user scope. | | P2-10 spine cap | **fixed** (but see N-2) | 200k web/phone, eviction behaviour stated, Q5. | | P2-11 gates / landing | **partly** | (a) The split into 1M synthetic / 100k real / extrapolated 2M is right, but the 100k family has no disk margin (N-9). (b) The scroll tests moved to P6: fixed. (c) The landing rule has a second backend-only PR that isn't listed as an exception (N-10). | | P3-1…3, 5, 7…13 | **fixed** | All present in the text. | | P3-4, P3-6 | accepted (§22) | P3-4 superseded by MB2, fine. P3-6: see N-P3-5, because group commit is new code, not "the store's model". | **Not fully fixed: 4** (P1-6, P2-6, P2-7, P2-11). --- ### 2. New findings #### P1 **N-1. §10 Partial `RCPT TO` acceptance re-sends to the recipients who already got it.** - SMTP answers per recipient. To A and B gets 250, Bcc C gets `452 4.2.2 mailbox full` (or a `450`). DATA goes through, the final reply is 250, and A and B have the mail. - The state machine only knows "a 4xx reply is a real answer: retry (3 times)" and "SMTP refused → back to the composer as a draft". A retry of the message sends it to A and B a second time. Re-sending the draft by hand does the same. - This is exactly the "no blind second send" guarantee §10 makes. - **Fix:** persist the per-recipient RCPT replies in `outgoing` (e.g. `rcpt_state BLOB`, one code per recipient) before DATA. Automatic retries and **Send again** go only to recipients without a 2xx. Recipients with a 5xx produce one sentence ("Couldn't deliver to c@…: their mailbox is full"), and the rest counts as sent. Also, if every RCPT fails, don't send DATA. - Test: add "RCPT mixed 250/452/550" to `send_state_machine`: each recipient gets exactly one copy across all retries. #### P2 **N-2. §8 Lists show silent gaps below the spine's low-water mark.** - The spine is "newest 200k threads by thread", and while filling it is "newest first". A list sorts by the *membership's* `sort_ms`, which can be much older than the thread's `last_ms`. Example: Sent rows for threads that got replies later, or Archive rows filed long ago in threads with fresh activity. - So below the boundary `B` (the oldest `last_ms` the device holds), the device has *some* rows for Sent or Archive but not all of them. Rows from threads outside the cap fall between them. - **Failure:** a phone with a 300k-thread mailbox, or any device mid-fill, scrolls Archive past `B`. It shows a list that looks complete but skips messages, with no prompt to ask the server. The person concludes the mail is gone. "The list ends at what we have and says so" doesn't trigger, because the list doesn't end; it has holes. - **Fix:** the device stores its spine low-water `B` per account. In every list, the device copy is authoritative only for rows with `sort_ms ≥ B`, and below that it switches to server pages (prefetched as for beyond-cap). Gate 2 and `spam_scroll_content` gain a case "folder whose old rows interleave with threads outside the cap" and a "mid-fill" case. **N-3. §10 A replay after 7 days re-runs an old action.** - The executor's receipt is pruned after 7 days (`store` `idempotency_retention`). The server `op` row is the only other guard, and §10 never says how long applied ops are kept (the natural design deletes or clears them). - **Failure:** a phone sends "move to Project", the server applies it, and the reply is lost. The phone stays offline for 9 days and the person moves the thread to Archive on the web. The phone comes back and retries with the same id. The receipt is gone, the op row is gone, so the handler runs again and moves the thread back to Project. - **Fix (O(1), no retention tuning):** the server keeps a per-Installation **high-water counter** in `state.db` (the counter is already in the op id). An op whose counter ≤ the stored high-water for its Installation is answered as a replay, forever. The outbox sends in counter order. Add the case "retry after receipt pruning" to `op_ids`. **N-4. §3 Rule 2 races inside one delta: "move out and back" becomes a duplicate.** - Basic IMAP, Inbox → Archive → Inbox in another client. One Inbox delta reports `add uid 900` and `expunge uid 5` for the same fingerprint. - If the add is processed first, rule 2 sees the fingerprint "in the same folder" (uid 5 still has a placement) and mints a new `msg id` with `dup_of`. The expunge then removes the last placement of the original id, which goes to the tombstone and Recently deleted. - Every `/mail/m/<old>` link now says "in Recently deleted" while the mail sits in Inbox under a new id. - **Fix:** apply removals before adds within one delta batch, and before declaring `dup_of`, check whether the matching placement still exists at the provider (one `UID SEARCH UID <n>` or the batch's expunge set). Add the fixture "move out and back within one delta window". **N-5. §3 / §5 Removing and re-adding an account changes every `msg id`.** - Rule 1 mints `msg id = blake3-128(account ‖ provider key)`, and `account.id` is a fresh BLOB on add. §5 says "Re-adding the same address finds the files by `msg id` and reuses them", and §15 drops indexes on removal. - After remove + re-add, every derived id is different, and for basic IMAP the random ids are gone with the dropped rows. So every ML7 link in notes and tasks breaks, and the kept `.eml` files are re-downloaded next to themselves. - **Fix:** derive the id input from a **stable account key** (`provider + normalised address`, kept in `id_map` / tombstones), not the row id. On removal, keep `id_map` rows for the 30-day window like other tombstones, so a re-add inside it re-attaches. Add the fixture "remove, re-add same address: links still open, no second file". **N-6. §13 Proxy submission: when Mail.app gets its reply, and what happens on a retry.** - §13 hands the message to "the same send pipeline" and skips the hold, but doesn't say whether the listener answers 250 **after `outgoing` is durable** (then upstream failures must come back as a bounce or DSN, otherwise they are lost) or **after the upstream reply** (then a slow upstream exceeds Mail.app's timeout, Mail.app retries the submission, and the mail is sent twice). - "Duplicates are detected by Message-ID against `outgoing`" is written for the Sent `APPEND`, not for submission. - **Fix:** answer 250 once `outgoing` is durable. Dedupe submissions on `(account, Message-ID, rcpt set)` against `outgoing` (a repeat returns 250 and does nothing). An upstream refusal produces a local DSN into the account's Inbox in the proxy tree, plus the app's failure line. Add a test: submit twice with the same Message-ID, exactly one upstream send. **N-7. §13 After a `mail.db` rebuild or `state.db` restore, Mail.app keeps stale flags and stale UIDs.** - `proxy_uid` stores only `(vid, uid, msg)`, not the flags last exposed. After a `mail.db` rebuild, flags come fresh from the provider. Any change that happened while the old `mail.db` was broken or not yet synced never gets a `proxy_change` row, so `CHANGEDSINCE` reports nothing and Mail.app keeps the old flags forever. - Restore case: the restored `state.db` cache lacks UIDs that were handed out after the backup. The authority keeps the floor, so the messages get new UIDs above it. But nothing records that the old UIDs vanished, so QRESYNC's `VANISHED (EARLIER)` and CONDSTORE clients keep ghost copies. - **Fix:** (a) after a `mail.db` rebuild, give every exposed message one new mod-sequence (one O(N) pass, background lane), or store exposed flag bits in `proxy_uid` and diff them. (b) When the `proxy_folder` cache is behind the authority (`next_uid` lower), **bump UIDVALIDITY** for that folder, even though the floor is proved. That is the only state Mail.app recovers from cleanly. Add both to the P10 gate. - Related P3: `proxy_change` has no retention. Compact it to one row per `(vid, uid)` like `change`, and above a retention horizon answer QRESYNC with the client's known-UIDs path (RFC 7162 §3.2.5.2) instead of keeping history forever. **N-8. §11 / §2 `netguard` doesn't cover provider connections and autodetect.** - `netguard` is shared with backdrops and the image proxy only. But `accounts` connects server-side to a **person-chosen host and port** ("any host"). Autodetect follows URLs and SRV records from the address's domain (autoconfig, `.well-known/jmap`). JMAP session objects hand back `apiUrl` / `downloadUrl` / `eventSourceUrl` that the server then calls. - On a multi-user server (invites, ADR 0059), that lets any account holder make the server connect to `100.64.0.0/10` mesh hosts or `127.0.0.1` on any port. The failure sentences ("couldn't verify mail.example.com's certificate", timeouts versus refusals) tell them what answered. - **Fix:** every `mail-imap` / `mail-jmap` / `mail-smtp` / autodetect / JMAP-session connection goes through `netguard`'s resolve-once connector with the same deny-list (any port allowed only for the configured provider host). Add an **admin** allow-list for self-hosted mail on a private network (pairs with Q12). Fixtures: an IMAP host resolving to `100.64.x.x`, and a JMAP session whose `downloadUrl` points at `127.0.0.1`. **N-9. §16 The 100k raw-gate family has no disk margin on the perf VMs.** - 23 GB free (the low end the plan quotes) minus the 15 GB floor leaves 8 GB, and the family is budgeted at "≤ 8 GB". That doesn't count the **fake provider's own corpus**: if the 100k × 60 KB messages are stored for it to serve, that's another ~6 GB, about 14 GB in total. The disk is also shared with perf-02 (both locks, but the other VM's leftovers still count). - **Fix:** the fake provider generates message bytes deterministically from `(seed, index)` and streams them (no source corpus on disk). The run aborts if `df` would cross 15 GB at any window, not only at start. If free space is under ~25 GB, the gate runs at 50k and says so in the report. **N-10. §18 "P1 is the one exception" isn't true: the search PR is a second backend-only landing.** - P2 says the search PR (`list_since`, in-index watermark) "lands just before" P2. It has no UI and goes to dev on its own, which breaks the 10-26 rule the same way P1 does, but it isn't listed or asked about in Q16. - **Fix:** either fold the search change into P2 (it ships with the Mail tab list), or list it in Q16 as a second exception for kayg to approve. The same applies to P0 if ADR-only PRs count as landings (probably not, but say so). **N-11. §10 / §19 The send state machine needs a hook `lettre` doesn't have.** - `data_sent` must be fsynced **between writing the body and writing the final `.`**, and the reply must be persisted before anything else. `lettre`'s transport and its `SmtpConnection::message()` write the data and the terminating `.` in one call and return only the final response. Per-RCPT replies (N-1) aren't exposed either. - **Fix:** §19 and Q14 should say SMTP needs a small in-house client (EHLO, AUTH, MAIL, RCPT with per-recipient results, DATA/BDAT, a hook before the terminator), or a thin fork. Make it part of P1's spike, because the P9 gate depends on it. #### P3 1. **§10 JMAP "not found → retry is safe"** holds only while the server keeps `EmailSubmission` objects (RFC 8621 lets servers purge them). Check the `$sent`-style evidence or bound the window (do the lookup within minutes, else `unknown`). 2. **§4 `id_map` size.** `msg` 16 + `provider_key` ≤ 20 + `fp` 32 + `thread` 16 + `path_hash` + row overhead, plus two secondary indexes (provider key, fp), comes to about 180–220 B per message, so ~400 MB at 2M, not ~120 MB. Restate it; it's backed up. 3. **§13 `COPY` → `mail.move`.** There is no `mail.copy` action, and a cross-account `MOVE` (unified folder → another account's folder) is undefined. Add `mail.copy` and answer cross-account MOVE/COPY with `NO` and a plain text. 4. **§5 vs §3 rule 4.** On basic IMAP a move *is* "one placement goes", so the file is never renamed and stays under `Inbox/…` while the mail lives in Archive. Rename to the surviving placement's folder when the file's path folder no longer has a placement. 5. **§4 group commit and fsync.** The store has neither group commit nor FULL sync per commit (NORMAL in WAL). `state.db` needs its own writer with group commit, and `data_sent` / `replied` need FULL (or an explicit `fsync`). Call it new code in §4 instead of "follows the store crate's model", and put it in P1's gate. 6. **§16 "Cold start with 2M messages"** is a budget, but §16 also says 2M is not run. Restate it at 1M with extrapolation. Also, "cold HDD" can't be measured on the perf VMs (one ext4 virtual disk, no HDD). Say how the page cache is dropped (needs root) or call it "cold page cache". 7. **§15 Quota reached.** "Mirror growth stops" vs "new mail keeps flowing": say whether new mail is mirrored over quota (rec: yes for new mail, no for backfill), and whether `bodies.db`, images and the search share count (rec: no, they are caches). 8. **§12 Key rotation vs restore.** Rotating `mail.key` makes older `state.db` backups need re-sign-in. Escrow should keep the previous key ids, or the docs should say a rotation invalidates older backups' S wraps. --- **Counts:** new P1 1 · new P2 10 · new P3 8 (plus one related P3 under N-7). First-review findings not fully fixed: **4** (P1-6, P2-6, P2-7, P2-11).
Author
Owner

Revision 3 pushed (head 34617a97) — the last patch round, with simplification. Mapping of re-review 77518. Section numbers refer to docs/plans/mail-architecture.md.

Simplification

  • The Apple Mail proxy (IMAP mail tree, submission port, CONDSTORE/QRESYNC, UID/mod-seq authority, proxy send path) moved to a stub, docs/plans/mail-apple-proxy.md: requirements, the findings that belong to it, and the interfaces the main plan owes it (§13). Still decided, scheduled as P10 (starts after P8; submission needs P9).
  • Send: one state machine, saved per recipient, with a small in-house SMTP client (§10).
  • Identity: one ordered rule set stated once (§3).

First-review findings still open

# Fix
P1-6 §4: the epoch lives in mail.db's meta table and is created with the database; a rebuilt or restored mail.db is a new file with a new random epoch. "Never reset / continue numbering" removed from schema and prose; §15 row and §5 say the same
P2-6 §3 rules 3: same-folder match = duplicate (own single version); other-folder match = extra placement, versions only across placements of one id. List copy + Cc copy in Inbox is an explicit fixture
P2-7 Moved to the proxy plan. Authority location rec: the same --secrets root (named in §13a and the proxy stub); mod-seq reservations and the ADR for the UIDVALIDITY bump listed there
P2-11 §18: P1 and the search list_since PR (now P1b) are named as the two approved backend-only exceptions (kayg Q16); P0 is docs, not a behaviour landing. Every other PR carries UI from the latest mockup

New findings

# Fix
N-1 (P1) §10: per-recipient states (outgoing_rcpt: pending/accepted/delivered/deferred/refused/unknown); RCPT replies persisted before DATA; no DATA if nobody accepted; data_sent FULL-fsynced before the terminator; retries and Send again only for recipients who did not get it; sentence names who did and didn't; test mixed 250/452/550
N-2 §8: per-account spine low-water B; lists authoritative only above B, server pages below; Gate 2 gains the interleaving and mid-fill cases (§16/§17/P6)
N-3 §10: per-Installation high-water counter in state.db, replays answered forever, outbox sends in counter order; test retry after receipt pruning
N-4 §3 rule 1: removals before additions in a delta batch, check the placement still exists before calling a duplicate; fixture move out and back
N-5 §3: ids derive from akey (provider + normalised address), id_map kept 30 days on removal; fixture remove then re-add (§5, §15)
N-6, N-7 Moved to the proxy plan (listed as findings there)
N-8 §11 item 5 and §2: netguard covers every outbound mail connection incl. provider hosts, autodetect, JMAP session URLs; admin allow-list for private networks (Q9); fixtures
N-9 §16: a run may use at most 70% of the space free above the 15 GB floor, checked per window; fake provider streams bytes from (seed, index); default 50k raw family (~4 GB), 100k only when ≥ 10 GB headroom
N-10 §18 as P2-11 above
N-11 §10/§2/§19: small in-house mail-smtp over rustls with a hook before the terminator and per-recipient results; lettre only for building MIME; spiked in P1 (Q11)

P3

# Fix
1 §10: JMAP lookup bounded to 10 minutes
2 §4/§6: id_map ~200 B/message, ~400 MB at 2M, restated
3 §10 mail.copy added, cross-account move/copy not offered in v1; the proxy side is in its stub
4 §3 rule 5: file renamed into a surviving placement's folder
5 §4: group commit and FULL-sync send states called new code, state_commit test in P1
6 §16: cold start restated at 1M with extrapolation; "cold page cache" (perf VMs have no HDD)
7 §5: new mail mirrored over quota, backfill pauses, caches don't count (Q16)
8 §12: rotation invalidates older backups' S wraps; escrow keeps previous key ids
proxy_change retention Proxy stub

Also recorded: Q16 approved, Q20 (CONDSTORE + QRESYNC both in v1; "extremely performant") — §21. Open questions renumbered Q1–Q16, each with a recommendation.

Revision 3 pushed (head 34617a97) — the last patch round, with simplification. Mapping of re-review 77518. Section numbers refer to `docs/plans/mail-architecture.md`. **Simplification** - The Apple Mail proxy (IMAP mail tree, submission port, CONDSTORE/QRESYNC, UID/mod-seq authority, proxy send path) moved to a stub, `docs/plans/mail-apple-proxy.md`: requirements, the findings that belong to it, and the interfaces the main plan owes it (§13). Still decided, scheduled as P10 (starts after P8; submission needs P9). - Send: one state machine, saved per recipient, with a small in-house SMTP client (§10). - Identity: one ordered rule set stated once (§3). **First-review findings still open** | # | Fix | |---|---| | P1-6 | §4: the epoch lives in `mail.db`'s `meta` table and is created with the database; a rebuilt or restored `mail.db` is a new file with a new random epoch. "Never reset / continue numbering" removed from schema and prose; §15 row and §5 say the same | | P2-6 | §3 rules 3: same-folder match = duplicate (own single version); other-folder match = extra placement, versions only across placements of one id. List copy + Cc copy in Inbox is an explicit fixture | | P2-7 | Moved to the proxy plan. Authority location rec: the same `--secrets` root (named in §13a and the proxy stub); mod-seq reservations and the ADR for the UIDVALIDITY bump listed there | | P2-11 | §18: P1 **and** the search `list_since` PR (now P1b) are named as the two approved backend-only exceptions (kayg Q16); P0 is docs, not a behaviour landing. Every other PR carries UI from the latest mockup | **New findings** | # | Fix | |---|---| | N-1 (P1) | §10: per-recipient states (`outgoing_rcpt`: pending/accepted/delivered/deferred/refused/unknown); RCPT replies persisted before DATA; no DATA if nobody accepted; `data_sent` FULL-fsynced before the terminator; retries and Send again only for recipients who did not get it; sentence names who did and didn't; test mixed 250/452/550 | | N-2 | §8: per-account spine low-water `B`; lists authoritative only above `B`, server pages below; Gate 2 gains the interleaving and mid-fill cases (§16/§17/P6) | | N-3 | §10: per-Installation high-water counter in `state.db`, replays answered forever, outbox sends in counter order; test retry after receipt pruning | | N-4 | §3 rule 1: removals before additions in a delta batch, check the placement still exists before calling a duplicate; fixture move out and back | | N-5 | §3: ids derive from `akey` (provider + normalised address), `id_map` kept 30 days on removal; fixture remove then re-add (§5, §15) | | N-6, N-7 | Moved to the proxy plan (listed as findings there) | | N-8 | §11 item 5 and §2: `netguard` covers every outbound mail connection incl. provider hosts, autodetect, JMAP session URLs; admin allow-list for private networks (Q9); fixtures | | N-9 | §16: a run may use at most 70% of the space free above the 15 GB floor, checked per window; fake provider streams bytes from `(seed, index)`; default 50k raw family (~4 GB), 100k only when ≥ 10 GB headroom | | N-10 | §18 as P2-11 above | | N-11 | §10/§2/§19: small in-house `mail-smtp` over rustls with a hook before the terminator and per-recipient results; `lettre` only for building MIME; spiked in P1 (Q11) | **P3** | # | Fix | |---|---| | 1 | §10: JMAP lookup bounded to 10 minutes | | 2 | §4/§6: `id_map` ~200 B/message, ~400 MB at 2M, restated | | 3 | §10 `mail.copy` added, cross-account move/copy not offered in v1; the proxy side is in its stub | | 4 | §3 rule 5: file renamed into a surviving placement's folder | | 5 | §4: group commit and FULL-sync send states called new code, `state_commit` test in P1 | | 6 | §16: cold start restated at 1M with extrapolation; "cold page cache" (perf VMs have no HDD) | | 7 | §5: new mail mirrored over quota, backfill pauses, caches don't count (Q16) | | 8 | §12: rotation invalidates older backups' S wraps; escrow keeps previous key ids | | `proxy_change` retention | Proxy stub | Also recorded: Q16 approved, Q20 (CONDSTORE + QRESYNC both in v1; "extremely performant") — §21. Open questions renumbered Q1–Q16, each with a recommendation.
Author
Owner

Review round 3: mail architecture plan, revision 3 (head 34617a97)

Checked docs/plans/mail-architecture.md and docs/plans/mail-apple-proxy.md @ 34617a97 against review 77518, mapping 77519, origin/dev docs/storage.md (a coordinated backup copies the whole users/ tree, so mail/mail.db and mail/state.db are in it) and ADR 0047 (the Installation is part of the op id; the plan doesn't say where the device stores the Installation id or its counter).

Summary. The simplification worked. Moving the proxy out, keeping one send state machine and one identity rule list makes the plan much easier to check, and most round-2 items are properly closed. But this is round 3 and it still finds new P1s. Both sit in the new mechanisms: restore and the epoch, and the per-Installation counter. Under our rule, fix them by simplifying, not by adding more rules. Each finding below suggests the smallest change I could find.


1. Round-2 findings

# Verdict Notes
P1-6 epoch partly Fixed for a rebuild: the epoch lives in mail.db meta and is created with the file, and §4, §5 and §15 agree. A file-level restore brings back the old meta row, so the claim "a rebuilt or restored mail.db is a new file with a new random epoch" (§4, §15) is false. See R-1
P2-6 content versions fixed Rule 3 now separates same-folder duplicates from other-folder placements, and the list+Cc fixture is in. Small schema gap in R-P3-2
P2-7 UIDVALIDITY authority fixed (moved) The --secrets root is named in §13a item 1 and in the stub, along with the reservations and the ADR
P2-11 gates / landing fixed P1 + P1b are the two named exceptions; P0 is docs; §9 and §21 agree
N-1 partial RCPT fixed Per-recipient table, replies stored before DATA, no DATA when nobody is accepted, test. Two leftovers: §15's "SMTP refused" row still says refused recipients "come back as a draft", while §10 says Send again (pick one), and some states have no exit (R-5)
N-2 low-water fixed B = the oldest thread last_ms the device holds. Every membership has sort_ms ≤ last_ms, so any row with sort_ms ≥ B belongs to a thread inside the spine. The argument holds
N-3 stale replay fixed as written It brings a new failure: R-2
N-4 move out and back fixed Rule 1
N-5 re-add fixed Uses akey. Edge cases in R-4
N-6 proxy submission partly Moved to the stub, but §13 and the stub say §10 provides "dedupe on (account, Message-ID, recipient set)". §10 and the schema have no such key. See R-6
N-7 fixed (moved) Listed in the stub
N-8 netguard fixed §11 item 5, §2 crate row, §15 row, fixtures, Q9
N-9 disk fixed The 70%-of-headroom rule is checked per window, the fake provider streams from (seed, index), and the run defaults to 50k. The arithmetic fits perf-02 (8 GB above the floor, 5.6 GB usable, 4 GB needed)
N-10 fixed
N-11 fixed mail-smtp is in-house, with Q11 and the P1 spike. New edges in R-3 and R-5

Not fully fixed: 2 (P1-6, N-6).


2. New findings

P1

R-1. Restoring a backup brings back an old epoch (changes silently skipped) and old queued intent (mail sent twice, later moves undone).

  • docs/storage.md copies system/ and all of users/ together, so a standard backup holds mail.db (with its meta.epoch) and state.db.
  • Restore on its own works: restore the backup taken at T, where mail.db is at (E, seq 800). Phones already hold (E, 1000). The server keeps working and writes seq 801…1000 for different changes. A phone asks for changes since 1000, gets nothing, and has silently missed 200 changes. Search's in-index watermark does the same thing. This is the original P1-6 bug, coming back through restore.
  • state.db at T has outgoing rows in held / pending / accepted and op rows that were applied after T. At start the timer heap releases the held mail, so the mail goes out a second time. The Actor replays the ops, so the provider moves threads back to where they were at T, undoing everything the person did after T.
  • Fix (one mechanism, simple):
    1. Leave mail.db and bodies.db out of the backup set. They are caches, so say so in the §13a storage.md change list. A restore then always rebuilds, and a rebuild already gets a new epoch.
    2. Keep a per-user state generation in the host-owned --secrets root (written with each state.db checkpoint, or simply the start time). If state.db's copy doesn't match it at open, the file was restored. In that case: rotate to a new epoch, put every non-final outgoing row into unknown (shown as "check Sent before sending again"), and put pending op rows on hold until a person confirms them, never replaying them automatically.
    3. Test: restore an older state.db + mail.db while a device holds a newer cursor and one send was held at backup time. The device re-reads, and nothing is sent or moved.

R-2. The per-Installation high-water drops real actions whenever counter order ≠ send order.

  • The rule is "counter ≤ high-water → answered as a replay, forever". It only works if one Installation can never send a lower counter after a higher one. The plan has at least three ways to break that:
    • Two tabs (web). If the Installation is the browser profile (one IndexedDB), tab A sends counter 11 while tab B's counter 10 is still in flight or queued. Counter 10 gets "replay", so the archive is reported accepted, never applied, and the overlay never existed. The thread quietly stays in Inbox.
    • Storage eviction. §8 itself expects Safari to evict script-written storage. If the Installation id survives (a cookie or the server session) but the counter is lost, every new op from counter 1 counts as a replay until the counter passes the old high-water.
    • Device restored from an iCloud/iTunes backup, or a VM snapshot. The counter goes back with the restore, so the same thing happens.
  • In each case the device is told "accepted", so its outbox clears. No error, no rollback: lost intent.
  • Fix (keeps the O(1) idea):
    1. The Installation id and its counter live in the same store, so losing one loses both and a fresh store means a new Installation. On native, keep that store out of device backups (iOS "this device only").
    2. One sender per Installation (web: a Web Lock held by one tab; other tabs hand ops to it).
    3. Remember the op id of the last counter per Installation. A request with counter ≤ high-water and an op id that matches a known one is a replay. Any other gets counter_conflict: the device renumbers above the high-water and resends.
    4. Add the cases "two tabs", "counter store lost" and "device snapshot restored" to op_ids.

P2

R-3. The SMTP final-reply timeout isn't specified, so the generic 10 s read timeout would turn large sends into unknown.

  • The only provider timeout in the plan is §15's "connect/read timeouts (10 s)", and §10 says the unknown window is "typically under two seconds".
  • RFC 5321 §4.5.3.2 tells clients to wait 10 minutes for the reply to the final ., and 5 minutes for MAIL/RCPT. Submission servers that scan a 20 MB attachment, or that are slow, routinely take more than 10 s.
  • With a 10 s timeout, every such send on a plain IMAP provider becomes unknown at once, with "Check Sent before sending again". The person presses Send again and the recipients get it twice. The server finished delivering after we stopped waiting.
  • Fix: mail-smtp uses the RFC 5321 timeouts, the final-reply timeout scales with message size (at least 10 min), and the reply stays readable while the connection is open. Only a dropped connection or a crash leads to unknown. Add "slow final reply (90 s)" as a fake-server case in send_state_machine, expecting delivered and no unknown.

R-4. akey = provider + address: address edits and host changes can attach a different mail to an old id.

  • Address edits: mail.account_update exists and the plan doesn't say whether akey changes with it. If it changes, every lookup (akey, provider key) misses, every message gets a new id, every ML7 link breaks, and the mirror is downloaded again. If it doesn't change, a later re-add under the new address doesn't match. Say: akey is fixed when the account is created, an update never rewrites it, and a re-add matches on it.
  • Host changes and provider moves (the bigger risk): for "any IMAP host" or a self-hosted JMAP server, the provider part of akey doesn't identify the server instance. Suppose the person moves me@kayg.org from one server to another under the same account, or removes it and re-adds it within 30 days on a new host. The new server's provider keys come from its own namespace. Stalwart's JMAP/IMAP ids, for example, are short counters, and JMAP ids are only unique per JMAP accountId. Rule 2 finds a tombstoned id_map row with an equal provider key and re-attaches an unrelated message to the old msg id. Old links in notes then open the wrong mail, and it joins the old thread.
  • Fix (one check, no new keys): a provider-key hit counts only if the stored fp also matches. If it doesn't, fall through to rule 3. Also include the JMAP accountId in the provider key. Fixture: re-add on a different host whose ids collide with the old ones; no old link opens the new mail.

R-5. The send state machine has states with no exit, so a crash in the RCPT phase leaves a mail stuck and unsent.

  • accepted is only left through delivered / deferred / refused (after the final reply) or unknown ("between step 3 and a persisted reply"). A crash or dropped connection after RCPT replies are stored but before data_sent leaves recipients accepted forever. Automatic retries pick up only deferred, and Send again only deferred / refused / unknown. Nothing sends it, and no sentence appears.
  • The plan's own kill point "after RCPT" has no expected outcome, so send_state_machine can't assert one.
  • These transitions are missing too:
    • MAIL FROM refused (e.g. 553 send-as not allowed, 552 SIZE): every recipient waits forever.
    • DATA answered 4xx/5xx before 354.
    • AUTH failure in the middle of a send.
  • Fix: add a short transition table to §10:
    • accepted with no data_sent → pending (nothing was delivered: step 3's own argument).
    • MAIL or DATA before 354, 4xx → all deferred; 5xx → all refused, with the server's text.
    • AUTH failure → the account goes to needs_sign_in, and the recipients stay pending.
    • Then the "after RCPT" kill point asserts "resent exactly once, to the same recipients".

R-6. The proxy's dedupe interface isn't in the main plan.

  • §13 and the stub both say §10 provides "dedupe on (account, Message-ID, recipient set)". §10 has no such rule, and outgoing has message_id but no unique key. The app path is covered by the executor's idempotency key. The proxy path has nothing, so the proxy plan would build against an interface that doesn't exist. That's the N-6 double send.
  • Fix: add rcpt_hash (sorted, normalised envelope recipients) and UNIQUE(account, message_id, rcpt_hash) to outgoing, and one sentence in §10: a repeat with the same key returns the existing row.
    • Let the proxy plan decide what a repeat after a refused / deferred result does. A deliberate resend from Mail.app must not be swallowed silently.
  • Also name the read that returns a content version's .eml stream. The interface table points at §10 for it, but §10's read list has only mail.page.

R-7. An optimistic change, or its rollback, never reaches other devices' caches.

  • The overlay lives in state.db, while the change feed (change, (epoch, seq)) lives in mail.db. Reads return effective = provider + overlay, so device B can cache a thread as archived from mail.page/mail.changes while A's archive is pending.
  • On rollback (§10 step 5) the overlay row is dropped, and mail.db never changed, so no change row is written. Device B keeps showing the thread archived until something else touches it, and its cursor says it's up to date.
  • The forward path is also invisible: B learns about A's archive only after the provider applies it, which can be hours when the provider is down.
  • Fix: every overlay insert and every overlay drop also touches the ref in change. It's a cross-database write, so do it after the state.db commit and redo it on start for ops newer than the last emitted one, like the hints in step 1. Test: two devices, provider refuses the move, and both end showing Inbox.

R-8. The in-house SMTP client doesn't say how it keeps replies matched to commands (TLS upgrade, pipelining).

  • Everything per recipient depends on matching each reply to the right RCPT. If they get out of step, a refused recipient is recorded as accepted ("a@ got it" when they didn't), or an accepted one as deferred, which leads to a second copy on retry.
  • Two cases to settle in §10:
    1. STARTTLS: anything the client has buffered when the TLS handshake starts must be discarded, or the connection fails if the buffer isn't empty, and then the client re-sends EHLO. Otherwise bytes injected before TLS are read as replies after it (the known STARTTLS response-injection class). Prefer implicit TLS on 465 when it is offered (RFC 8314).
    2. PIPELINING: v1 sends commands one at a time and doesn't use it. That's simpler, and RCPT round trips are not on a hot path. If it is ever used, replies must be matched strictly in order, including multi-line 250- replies.
  • Add fake-server cases: extra bytes before the TLS upgrade, multi-line replies, and a reply split across reads.

P3

  1. Stale cross-references after the renumbering:
    • §5 "section 3 rule 4" should be rule 5.
    • §14 rule 1 "section 3 rule 3" should be rule 4 (the tombstone).
    • §20 "Q18" should be Q13.
    • §15 "come back as a draft" contradicts §10's Send again (see N-1).
  2. id_map and duplicates. Rule 3 says a fingerprint-only mint goes under a unique (akey, fingerprint) key, but dup_of rows share that fingerprint, so the unique key either rejects them or they aren't in id_map. In the second case, a rebuild can't tell which of two same-folder copies was the original, and links to the duplicate can swap or break.
    • Fix: key it as (akey, fp, n), with n the order of arrival, and let the rebuild assign by UID order.
  3. Sent copy after partial retries. On plain IMAP, every SMTP transaction that reaches replied triggers an APPEND. A send that needed one retry for a deferred recipient leaves two copies in Sent.
    • Fix: append once, when the mail first has a delivered recipient, keyed by outgoing.id.

3. Rule check (3 rounds)

This round still found new P1/P2s: 2 P1 and 6 P2. Under the rule, the author should simplify, not patch where possible:

  • R-1: leave the caches out of backups, and add one restore marker.
  • R-2: keep the Installation id and its counter in the same store, and allow one sender per Installation.
  • R-5 and R-8: narrow mail-smtp (no pipelining, implicit TLS preferred, RFC timeouts, a transition table).

R-3, R-4, R-6 and R-7 are one sentence or one key each. I'd expect a revision 4 that does only this to be checked in one pass.

Counts: new P1 2 · new P2 6 · new P3 3. Round-2 findings not fully fixed: 2 (P1-6, N-6).

## Review round 3: mail architecture plan, revision 3 (head 34617a97) Checked `docs/plans/mail-architecture.md` and `docs/plans/mail-apple-proxy.md` @ 34617a97 against review 77518, mapping 77519, `origin/dev` `docs/storage.md` (a coordinated backup copies the whole `users/` tree, so `mail/mail.db` and `mail/state.db` are in it) and ADR 0047 (the Installation is part of the op id; the plan doesn't say where the device stores the Installation id or its counter). **Summary.** The simplification worked. Moving the proxy out, keeping one send state machine and one identity rule list makes the plan much easier to check, and most round-2 items are properly closed. But this is round 3 and it still finds new P1s. Both sit in the new mechanisms: restore and the epoch, and the per-Installation counter. Under our rule, fix them by **simplifying, not by adding more rules**. Each finding below suggests the smallest change I could find. --- ### 1. Round-2 findings | # | Verdict | Notes | |---|---|---| | P1-6 epoch | **partly** | Fixed for a rebuild: the epoch lives in `mail.db` `meta` and is created with the file, and §4, §5 and §15 agree. A **file-level restore** brings back the old `meta` row, so the claim "a rebuilt or restored `mail.db` is a new file with a new random epoch" (§4, §15) is false. See R-1 | | P2-6 content versions | fixed | Rule 3 now separates same-folder duplicates from other-folder placements, and the list+Cc fixture is in. Small schema gap in R-P3-2 | | P2-7 UIDVALIDITY authority | fixed (moved) | The `--secrets` root is named in §13a item 1 and in the stub, along with the reservations and the ADR | | P2-11 gates / landing | fixed | P1 + P1b are the two named exceptions; P0 is docs; §9 and §21 agree | | N-1 partial RCPT | fixed | Per-recipient table, replies stored before DATA, no DATA when nobody is accepted, test. Two leftovers: §15's "SMTP refused" row still says refused recipients "come back as a draft", while §10 says **Send again** (pick one), and some states have no exit (R-5) | | N-2 low-water | fixed | `B` = the oldest thread `last_ms` the device holds. Every membership has `sort_ms ≤ last_ms`, so any row with `sort_ms ≥ B` belongs to a thread inside the spine. The argument holds | | N-3 stale replay | fixed as written | It brings a new failure: R-2 | | N-4 move out and back | fixed | Rule 1 | | N-5 re-add | fixed | Uses `akey`. Edge cases in R-4 | | N-6 proxy submission | **partly** | Moved to the stub, but §13 and the stub say §10 provides "dedupe on `(account, Message-ID, recipient set)`". §10 and the schema have no such key. See R-6 | | N-7 | fixed (moved) | Listed in the stub | | N-8 netguard | fixed | §11 item 5, §2 crate row, §15 row, fixtures, Q9 | | N-9 disk | fixed | The 70%-of-headroom rule is checked per window, the fake provider streams from `(seed, index)`, and the run defaults to 50k. The arithmetic fits perf-02 (8 GB above the floor, 5.6 GB usable, 4 GB needed) | | N-10 | fixed | | | N-11 | fixed | `mail-smtp` is in-house, with Q11 and the P1 spike. New edges in R-3 and R-5 | **Not fully fixed: 2** (P1-6, N-6). --- ### 2. New findings #### P1 **R-1. Restoring a backup brings back an old epoch (changes silently skipped) and old queued intent (mail sent twice, later moves undone).** - `docs/storage.md` copies `system/` and all of `users/` together, so a standard backup holds `mail.db` (with its `meta.epoch`) and `state.db`. - Restore on its own works: restore the backup taken at T, where `mail.db` is at `(E, seq 800)`. Phones already hold `(E, 1000)`. The server keeps working and writes seq 801…1000 for *different* changes. A phone asks for changes since 1000, gets nothing, and has silently missed 200 changes. Search's in-index watermark does the same thing. This is the original P1-6 bug, coming back through restore. - `state.db` at T has `outgoing` rows in `held` / `pending` / `accepted` and `op` rows that were applied after T. At start the timer heap releases the held mail, so **the mail goes out a second time**. The Actor replays the ops, so the provider moves threads back to where they were at T, undoing everything the person did after T. - **Fix (one mechanism, simple):** 1. Leave `mail.db` and `bodies.db` out of the backup set. They are caches, so say so in the §13a `storage.md` change list. A restore then always rebuilds, and a rebuild already gets a new epoch. 2. Keep a per-user **state generation** in the host-owned `--secrets` root (written with each `state.db` checkpoint, or simply the start time). If `state.db`'s copy doesn't match it at open, the file was restored. In that case: rotate to a new epoch, put every non-final `outgoing` row into `unknown` (shown as "check Sent before sending again"), and put pending `op` rows on hold until a person confirms them, never replaying them automatically. 3. Test: restore an older `state.db` + `mail.db` while a device holds a newer cursor and one send was held at backup time. The device re-reads, and nothing is sent or moved. **R-2. The per-Installation high-water drops real actions whenever counter order ≠ send order.** - The rule is "counter ≤ high-water → answered as a replay, forever". It only works if one Installation can never send a lower counter after a higher one. The plan has at least three ways to break that: - **Two tabs (web).** If the Installation is the browser profile (one IndexedDB), tab A sends counter 11 while tab B's counter 10 is still in flight or queued. Counter 10 gets "replay", so the archive is reported accepted, never applied, and the overlay never existed. The thread quietly stays in Inbox. - **Storage eviction.** §8 itself expects Safari to evict script-written storage. If the Installation id survives (a cookie or the server session) but the counter is lost, every new op from counter 1 counts as a replay until the counter passes the old high-water. - **Device restored from an iCloud/iTunes backup, or a VM snapshot.** The counter goes back with the restore, so the same thing happens. - In each case the device is told "accepted", so its outbox clears. No error, no rollback: lost intent. - **Fix (keeps the O(1) idea):** 1. The Installation id and its counter live **in the same store**, so losing one loses both and a fresh store means a new Installation. On native, keep that store out of device backups (iOS "this device only"). 2. One sender per Installation (web: a Web Lock held by one tab; other tabs hand ops to it). 3. Remember the op id of the **last** counter per Installation. A request with counter ≤ high-water and an op id that matches a known one is a replay. Any other gets `counter_conflict`: the device renumbers above the high-water and resends. 4. Add the cases "two tabs", "counter store lost" and "device snapshot restored" to `op_ids`. #### P2 **R-3. The SMTP final-reply timeout isn't specified, so the generic 10 s read timeout would turn large sends into `unknown`.** - The only provider timeout in the plan is §15's "connect/read timeouts (10 s)", and §10 says the unknown window is "typically under two seconds". - RFC 5321 §4.5.3.2 tells clients to wait **10 minutes** for the reply to the final `.`, and 5 minutes for MAIL/RCPT. Submission servers that scan a 20 MB attachment, or that are slow, routinely take more than 10 s. - With a 10 s timeout, every such send on a plain IMAP provider becomes `unknown` at once, with "Check Sent before sending again". The person presses **Send again** and the recipients get it twice. The server finished delivering after we stopped waiting. - **Fix:** `mail-smtp` uses the RFC 5321 timeouts, the final-reply timeout scales with message size (at least 10 min), and the reply stays readable while the connection is open. Only a dropped connection or a crash leads to `unknown`. Add "slow final reply (90 s)" as a fake-server case in `send_state_machine`, expecting `delivered` and no `unknown`. **R-4. `akey = provider + address`: address edits and host changes can attach a different mail to an old id.** - Address edits: `mail.account_update` exists and the plan doesn't say whether `akey` changes with it. If it changes, every lookup `(akey, provider key)` misses, every message gets a new id, every ML7 link breaks, and the mirror is downloaded again. If it doesn't change, a later re-add under the new address doesn't match. **Say:** `akey` is fixed when the account is created, an update never rewrites it, and a re-add matches on it. - Host changes and provider moves (the bigger risk): for "any IMAP host" or a self-hosted JMAP server, the provider part of `akey` doesn't identify the server instance. Suppose the person moves `me@kayg.org` from one server to another under the same account, or removes it and re-adds it within 30 days on a new host. The new server's provider keys come from its own namespace. Stalwart's JMAP/IMAP ids, for example, are short counters, and JMAP ids are only unique per JMAP `accountId`. Rule 2 finds a tombstoned `id_map` row with an equal provider key and **re-attaches an unrelated message to the old `msg id`**. Old links in notes then open the wrong mail, and it joins the old thread. - **Fix (one check, no new keys):** a provider-key hit counts only if the stored `fp` also matches. If it doesn't, fall through to rule 3. Also include the JMAP `accountId` in the provider key. Fixture: re-add on a different host whose ids collide with the old ones; no old link opens the new mail. **R-5. The send state machine has states with no exit, so a crash in the RCPT phase leaves a mail stuck and unsent.** - `accepted` is only left through `delivered` / `deferred` / `refused` (after the final reply) or `unknown` ("between step 3 and a persisted reply"). A crash or dropped connection **after RCPT replies are stored but before `data_sent`** leaves recipients `accepted` forever. Automatic retries pick up only `deferred`, and Send again only `deferred` / `refused` / `unknown`. Nothing sends it, and no sentence appears. - The plan's own kill point "after RCPT" has no expected outcome, so `send_state_machine` can't assert one. - These transitions are missing too: - `MAIL FROM` refused (e.g. 553 send-as not allowed, 552 SIZE): every recipient waits forever. - `DATA` answered 4xx/5xx before `354`. - `AUTH` failure in the middle of a send. - **Fix:** add a short transition table to §10: - `accepted` with no `data_sent` → `pending` (nothing was delivered: step 3's own argument). - MAIL or `DATA` before 354, 4xx → all `deferred`; 5xx → all `refused`, with the server's text. - AUTH failure → the account goes to `needs_sign_in`, and the recipients stay `pending`. - Then the "after RCPT" kill point asserts "resent exactly once, to the same recipients". **R-6. The proxy's dedupe interface isn't in the main plan.** - §13 and the stub both say §10 provides "dedupe on `(account, Message-ID, recipient set)`". §10 has no such rule, and `outgoing` has `message_id` but no unique key. The app path is covered by the executor's idempotency key. The proxy path has nothing, so the proxy plan would build against an interface that doesn't exist. That's the N-6 double send. - **Fix:** add `rcpt_hash` (sorted, normalised envelope recipients) and `UNIQUE(account, message_id, rcpt_hash)` to `outgoing`, and one sentence in §10: a repeat with the same key returns the existing row. - Let the proxy plan decide what a repeat after a `refused` / `deferred` result does. A deliberate resend from Mail.app must not be swallowed silently. - Also name the read that returns a content version's `.eml` stream. The interface table points at §10 for it, but §10's read list has only `mail.page`. **R-7. An optimistic change, or its rollback, never reaches other devices' caches.** - The overlay lives in `state.db`, while the change feed (`change`, `(epoch, seq)`) lives in `mail.db`. Reads return `effective = provider + overlay`, so device B can cache a thread as archived from `mail.page`/`mail.changes` while A's archive is pending. - On rollback (§10 step 5) the overlay row is dropped, and `mail.db` never changed, so **no `change` row is written**. Device B keeps showing the thread archived until something else touches it, and its cursor says it's up to date. - The forward path is also invisible: B learns about A's archive only after the provider applies it, which can be hours when the provider is down. - **Fix:** every overlay insert and every overlay drop also touches the ref in `change`. It's a cross-database write, so do it after the `state.db` commit and redo it on start for ops newer than the last emitted one, like the hints in step 1. Test: two devices, provider refuses the move, and both end showing Inbox. **R-8. The in-house SMTP client doesn't say how it keeps replies matched to commands (TLS upgrade, pipelining).** - Everything per recipient depends on matching each reply to the right `RCPT`. If they get out of step, a refused recipient is recorded as `accepted` ("a@ got it" when they didn't), or an accepted one as `deferred`, which leads to a second copy on retry. - Two cases to settle in §10: 1. **STARTTLS:** anything the client has buffered when the TLS handshake starts must be discarded, or the connection fails if the buffer isn't empty, and then the client re-sends EHLO. Otherwise bytes injected before TLS are read as replies after it (the known STARTTLS response-injection class). Prefer implicit TLS on 465 when it is offered (RFC 8314). 2. **PIPELINING:** v1 sends commands one at a time and doesn't use it. That's simpler, and RCPT round trips are not on a hot path. If it is ever used, replies must be matched strictly in order, including multi-line `250-` replies. - Add fake-server cases: extra bytes before the TLS upgrade, multi-line replies, and a reply split across reads. #### P3 1. **Stale cross-references after the renumbering:** - §5 "section 3 rule 4" should be rule 5. - §14 rule 1 "section 3 rule 3" should be rule 4 (the tombstone). - §20 "Q18" should be Q13. - §15 "come back as a draft" contradicts §10's Send again (see N-1). 2. **`id_map` and duplicates.** Rule 3 says a fingerprint-only mint goes under a unique `(akey, fingerprint)` key, but `dup_of` rows share that fingerprint, so the unique key either rejects them or they aren't in `id_map`. In the second case, a rebuild can't tell which of two same-folder copies was the original, and links to the duplicate can swap or break. - Fix: key it as `(akey, fp, n)`, with `n` the order of arrival, and let the rebuild assign by UID order. 3. **Sent copy after partial retries.** On plain IMAP, every SMTP transaction that reaches `replied` triggers an `APPEND`. A send that needed one retry for a deferred recipient leaves two copies in Sent. - Fix: append once, when the mail first has a `delivered` recipient, keyed by `outgoing.id`. --- ### 3. Rule check (3 rounds) This round still found new P1/P2s: 2 P1 and 6 P2. Under the rule, the author should **simplify, not patch** where possible: - **R-1:** leave the caches out of backups, and add one restore marker. - **R-2:** keep the Installation id and its counter in the same store, and allow one sender per Installation. - **R-5 and R-8:** narrow `mail-smtp` (no pipelining, implicit TLS preferred, RFC timeouts, a transition table). R-3, R-4, R-6 and R-7 are one sentence or one key each. I'd expect a revision 4 that does only this to be checked in one pass. **Counts:** new P1 2 · new P2 6 · new P3 3. Round-2 findings not fully fixed: **2** (P1-6, N-6).
Author
Owner

Superseded by #920 (v4, simplified), following the 3-round rule: mail's own op queue, counters, cursors and epochs are gone, and the shared gaps are filed as #918 and #919. The R-1…R-8 mapping is in §20 of the new plan. Leaving this PR open for kayg to close.

Superseded by #920 (v4, simplified), following the 3-round rule: mail's own op queue, counters, cursors and epochs are gone, and the shared gaps are filed as #918 and #919. The R-1…R-8 mapping is in §20 of the new plan. Leaving this PR open for kayg to close.
Author
Owner

Superseded by #920 (merged).

Superseded by #920 (merged).
kayg closed this pull request 2026-11-04 09:43:57 +00:00
Some checks failed
CI / server (pull_request) Has been cancelled
CI / rust (pull_request) Has been cancelled
CI / web (pull_request) Has been cancelled
Markdown extraction contract / markdown-native-contract (pull_request) Has been cancelled
Markdown extraction contract / markdown-editor-contract (pull_request) Has been cancelled

Pull request closed

Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
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
kayg/calternal!915
No description provided.