plan: Mail architecture v4 (simplified) #920

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

Replaces #915 (rev 3). After three review rounds that each found new P1s (77512, 77518, 77520), this is the simpler design our rule asks for, not a fourth patch. Needs kayg's review. Do not merge.

What changed. Most round-3 findings came from Mail building its own op queue, per-device counters, change cursors and epochs next to the ones the product already has. v4 removes all of them:

  1. No mail-owned sync machinery. Mail actions are ordinary executor actions. They reach devices, search and MCP through the save log and the one sync route (mail.acted / mail.applied / mail.refused / mail.synced / mail.reset / mail.send_state), with the same idempotency and restore behaviour as notes. Two gaps in the shared machinery are filed as shared issues: #918 (a restored index.db keeps its epoch, so a device can skip changes silently) and #919 (actions name their base token, so a late retry can never undo a newer change).
  2. Caches vs precious data. cache.db, bodies.db, images and search are rebuildable and never backed up. A rebuild is an ordinary mail.reset resync. Ids are derived, so there is no id_map to keep. state.db holds only credentials, settings and outgoing mail.
  3. Sending. No pipelining, RFC 5321 timeouts (10 min for the final reply), a transition table where every state has an exit, and data_started written after 354. Mail whose outcome is unknown is never resent automatically, and a restore releases nothing. Bytes left in the buffer at STARTTLS close the connection. The P1 spike checks mail-send 0.7 against these rules; if it fails any of them, we write a minimal in-house client.
  4. Identity. akey is fixed when the account is created and includes the host. msg id hashes the provider key together with the fingerprint.
  5. The Apple Mail proxy stub lists the v4 interfaces, including UNIQUE(account, message_id, rcpt_hash) and mail.raw.

Each of R-1…R-8, P1-6 and N-6 is mapped to the principle that resolves it in §20. All agreed decisions (ML/MR/LK/MA/MB, MA7b, Q16, Q20) and the gate sizes that fit the perf VMs are kept.

Size: mail-architecture.md 666 → 380 lines.

🤖 Generated with Claude Code

Replaces #915 (rev 3). After three review rounds that each found new P1s (77512, 77518, 77520), this is the simpler design our rule asks for, not a fourth patch. **Needs kayg's review. Do not merge.** **What changed.** Most round-3 findings came from Mail building its own op queue, per-device counters, change cursors and epochs next to the ones the product already has. v4 removes all of them: 1. **No mail-owned sync machinery.** Mail actions are ordinary executor actions. They reach devices, search and MCP through the save log and the one sync route (`mail.acted` / `mail.applied` / `mail.refused` / `mail.synced` / `mail.reset` / `mail.send_state`), with the same idempotency and restore behaviour as notes. Two gaps in the shared machinery are filed as shared issues: **#918** (a restored `index.db` keeps its epoch, so a device can skip changes silently) and **#919** (actions name their base token, so a late retry can never undo a newer change). 2. **Caches vs precious data.** `cache.db`, `bodies.db`, images and search are rebuildable and never backed up. A rebuild is an ordinary `mail.reset` resync. Ids are *derived*, so there is no `id_map` to keep. `state.db` holds only credentials, settings and outgoing mail. 3. **Sending.** No pipelining, RFC 5321 timeouts (10 min for the final reply), a transition table where every state has an exit, and `data_started` written after `354`. Mail whose outcome is unknown is never resent automatically, and a restore releases nothing. Bytes left in the buffer at STARTTLS close the connection. The P1 spike checks `mail-send` 0.7 against these rules; if it fails any of them, we write a minimal in-house client. 4. **Identity.** `akey` is fixed when the account is created and includes the host. `msg id` hashes the provider key together with the fingerprint. 5. The Apple Mail proxy stub lists the v4 interfaces, including `UNIQUE(account, message_id, rcpt_hash)` and `mail.raw`. Each of R-1…R-8, P1-6 and N-6 is mapped to the principle that resolves it in §20. All agreed decisions (ML/MR/LK/MA/MB, MA7b, Q16, Q20) and the gate sizes that fit the perf VMs are kept. Size: `mail-architecture.md` 666 → 380 lines. 🤖 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>
Identity from provider ids with tombstones, epoch in every cursor,
send state machine with envelope/Bcc, spine memberships, CONDSTORE
proxy with paged replies, key file outside backups, full SSRF list,
gate sizes that fit the perf VMs, PR landing proposal, save-log wording.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Per-recipient send states, rebuild always writes a new epoch, one
identity rule set keyed on a stable account key, low-water mark for
lists, per-Installation replay counter, netguard on all outbound
connections, 70% disk-margin gates, P1 and search PR as approved
backend-only exceptions.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Replaces rev 3 (#915) after three review rounds with new P1s. Mail actions
are ordinary executor actions in the save log; caches are never backed up
and rebuild by ids that are derived; one send state machine with RFC 5321
timeouts and an exit for every state. Shared gaps filed as #918, #919.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
plan: Apple Mail proxy stub points at the v4 interfaces
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
4355db68f0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Author
Owner

Review of v4 (head 4355db68): plan + #918 + #919

I checked this against origin/dev: crates/store/src/{lib,schema,writer,read}.rs, crates/engine/src/lib.rs (journal, journal_for), crates/server/src/live.rs (run, catch_up, visible_entry), crates/notes/src/actions.rs (base: i64 on patch/replace), docs/storage.md, and ADRs 0011/0044/0047.

The simplification is right. Riding the executor and save log removes the round-3 bug class. What's left is mostly in the two shared fixes and in how mail's volume meets one shared journal. Facts from the code that the findings rely on:

  • One writer thread per user for index.db, shared with notes. No group commit. Queue of 64.
  • Journal commits use WAL + synchronous=NORMAL. Only commit_once uses FULL.
  • seq is AUTOINCREMENT, so a rolled-back tail gives the same seq numbers out again.
  • position() only rejects epoch ≠ or seq > head.
  • The journal is never pruned.
  • catch_up sends every entry in order, in pages of 1000, before ready. The route only filters for app passwords.

P1

P1-1 · #918 misses the common restore paths (§2, §6, §15 "Backup restored"). The mark is written at each server start, so any backup taken after the last start holds the same value as the secrets file. Example: start Monday, backup Tuesday, devices move ahead Wednesday, restore Tuesday's backup Thursday. The marks match, nothing rotates, and devices whose token is past the restored head skip entries silently once the server writes past them. That is the exact bug #918 is meant to fix. Two more paths it can't see:

  • (a) A whole-host or VM snapshot rollback. storage.md recommends "a coordinated filesystem snapshot", and on Proxmox the secrets root rolls back with everything else.
  • (b) A power loss under synchronous=NORMAL. The WAL tail is lost and its seqs are given out again for different entries.

Fix (covers all three, no hot-path cost):

  • Make the token check the entry, not just the seq. Token = epoch-seq-check, where check = 32 bits of hash(seq, at_ms, request_id, kind) of the entry at seq.
  • position() does one PK lookup. If the entry is missing or the check differs, return SyncTokenExpired and rotate the epoch for everyone. The server has just learned it went back in time.
  • Keep a small high-water file outside the backups (<secrets>/users/<u>/head, holding epoch and head seq, written off the hot path every N seconds). At open, head < high-water or an epoch mismatch means restored. That gives plugins their restored signal before work starts.
  • Drop the "random value per start" mark. It's the part that doesn't work.

P1-2 · Writer position is in a different database from the log it points into (§3 "Writer position", §5 writer_pos). writer_pos is in state.db; the entries are in index.db. If index.db loses its tail (power loss, P1-1b) while state.db keeps the position, the Writer's position is above the head. New mail.acted entries reuse those seqs, and the Writer skips them. Devices already applied them optimistically, so the actions show as done but never reach the provider and are never refused. The epoch check in §3 doesn't fire, because the epoch is unchanged.

Fix: remove writer_pos from state.db. Each outcome entry already exists; give it upto: seq. At start the Writer reads its position from the last mail.applied/mail.refused for that account, in the same database and the same rollback. That's one less table, and the "outcome first, then position" ordering goes away.

P1-3 · #919's rule as written refuses commuting actions and still lets a newer change be undone (§8 "Base", #919).

  • Whole-target granularity: device A flags a thread, device B (same base) marks it read, and B gets stale. The person sees "Some changes you made offline weren't applied…" even though nothing conflicts. flags_seq covers read, flag and labels together, so this happens on every race between two of them, including a provider push that only adds a Gmail label.
  • Any bump counts: the daily flag sweep, a delta that rewrites the same value, and a cache.db rebuild (§6) all set new seqs. After a rebuild, every queued offline action comes back stale.
  • Same-Installation exemption: web tabs share an Installation. Tab A archives, the reply is lost, and tab B un-archives. After the 7-day receipt prune, tab A's retry is exempt and archives again. That is the undo #919 exists to prevent, and it contradicts "two tabs need nothing special".

Narrowest correct rule:

  • Per field. Track seq per field: read, flagged, each label, placement. Bump it only when the value changes.
  • Stale only if both hold: the field changed after base and its current value ≠ the requested value. If current = requested, return success with no change. So two devices marking read both succeed, a flag racing a read commutes, and a provider push that already did the same thing is fine. The ABA late retry (archived → back to Inbox → old "archive" retry) is still refused.
  • No Installation exemption. Instead, the device outbox coalesces per (target, field) before sending, so "toggle N times offline" sends one final state per base. The stale_base test then needs no special case.
  • Base from an older epoch (after a restore): treat it as "changed since base".
  • base optional for online adapters (CLI, MCP, bulk jobs) and required only when the device outbox replays an action.
  • Opt-in per action. Notes keep their own per-note version base: i64 and merge (notes.patch/replace). Room/CRDT edits never go through this. #919 must not become an executor-wide check, or concurrent note edits that merge today would be refused. The #919 text says notes "already keep a base hash"; they keep a version that merges, so it isn't the same mechanism.

P2

P2-1 · Mail hints flood the one sync route (§7 "Save-log volume", ADR 0014). Every device session receives every mail.synced. That includes a Notes-only tab, CLI followers and MCP Events webhooks: 20 accounts backfilling means about 20 webhook deliveries a second. catch_up sends the backlog in order before ready, so a phone that was offline during a big backfill gets tens of MB of mail hints before the notes edits that sit after them. Notes sync latency on reconnect then depends on mail volume.

The size estimate is also low. 500 ids as hex JSON is about 17 KB per entry, so 4,000 entries is about 70 MB, not 40 MB. Fixes:

  • (a) The route accepts a kind-prefix filter. It's tiny, it's what ADR 0044 means by "filtered on the server", and it isn't a separate stream.
  • (b) In catch_up, when more than K mail.synced entries for one account are pending, send one synthetic mail.refill {account}. The device pages the spine.
  • (c) Ids as base64url (22 chars).

Add a gate: notes reconnect-to-ready p95 after a 100k backfill backlog, flat vs dev.

P2-2 · Hints for rows the device will throw away (§7 Devices). Phones keep the newest 200k, but backfill sends hints for the remaining 1.8M. Without dates in the hint, the device has to fetch mail.threads(ids) just to learn they're below B. Fix: mail.synced {…, oldest_ms, newest_ms}, and the device skips any batch with newest_ms < B.

P2-3 · Shared writer and checkpoints under backfill. About 340 KB/s of hint JSON into the shared index.db WAL means an autocheckpoint every ~12 s. On the perf VMs those fsyncs are 60–338 ms under contention, and the next notes commit waits behind them in the one writer thread. Fix:

  • Cap the hint rate per user, not per account: 1–2/s across all accounts, merged.
  • Add a gate for notes action accept p99 (not just typing), with 20 accounts backfilling on a contended disk.

P2-4 · A crash between the cache.db commit and the hint loses that hint (§7 Push: "Commit first, then write the hint"). Devices only refresh on hints, so those threads stay stale on devices until something else touches them. Fix: add changed_rev per row and one hinted_rev per account in cache.db (columns, not a change table). At worker start, re-hint rows with changed_rev > hinted_rev.

P2-5 · An accepted action can be lost on power loss (§8 "Two acknowledgements"). The mail.acted journal entry is the only record of the action, the device clears its outbox on accept (ADR 0047: "only after the server confirms durable storage"), and the commit is NORMAL. For notes the content lives elsewhere; for mail nothing else holds it. Fix: a shared "durable" commit flag that uses synchronous=FULL with group commit (drain the queue, one fsync), used by mail actions. Gate it against notes accept latency. Or state plainly that this is accepted risk.

P2-6 · The restore rule cancels legitimate scheduled mail, and misses state.db-only or snapshot rollbacks (§9 last row).

  • "Held and scheduled mail is not released" turns a send scheduled for next week into unknown / "check Sent". It can't have gone out yet, because its release_ms is still in the future. Keep rows with release_ms > now scheduled.
  • After a VM snapshot rollback or a state.db-only restore (P1-1), already-delivered rows come back as pending and are retried automatically. Belt and braces: before the first DATA of any row created more than 10 min ago, run lookup_sent(Message-ID) where caps allow it.

P2-7 · The id scheme flips when pkey support changes (§4). msg id uses one formula with a pkey and another without. A server that starts offering OBJECTID/EMAILID after an upgrade, or drops it, changes every id. Every link breaks, and the mirror names no longer match, so everything downloads again and the old files go to Recently deleted. Fix: fix the scheme per account at creation in state.db (account.id_scheme) and never switch it, as with akey.

P2-8 · A rebuild means a full download on native (§6, §7). mail.reset / an epoch change means "drop and refill": about 280 MB per native device for 2M threads, and 28 MB per phone, on every rebuild or detected restore. With P1-1's fix, a power-loss rollback triggers it too. Ids are derived, so the device's copy is still valid. Fix: the refill compares per-month spine digests (hash of (id, sort_ms, flags) per month) and fetches only the months that differ. Add a gate: refill bytes after cache_rebuild ≤ 1% of the spine when nothing changed.

P3

  • §4 rule 4, no-pkey hosts. With n as the rank by UID, moving one of two same-fp copies (a list copy and a Cc copy) swaps their ids, because the moved copy gets a higher UID. Rank by content_hash first and by UID only among byte-identical copies.
  • §3, words on refusal. mail.refused {reason: restored} should show no words. Some of those actions did reach the provider before the restore.
  • §13 / proxy stub. visible_entry/journal_for give app-password callers only notes.*/sharing.* entries and require notes.read. Say the proxy follows the log as an in-process consumer, not through the app-password sync route, or the imap.mail scope needs those mail kinds.
  • §3 "cache ⊕ pending". The keyset page overlay needs a rule for threads that pending moves take out of, or bring into, a page. Short pages are fine; skipped rows are not. Add it to list_page_scaling.
  • Journal retention. Mail adds entries to a journal that is never pruned. That's fine for now; put "journal size after a 1M backfill + 1 year of push" in the budgets.

Answers to the four questions

  1. Shared machinery: it holds, provided P2-1–P2-3 are in place (kind filter, refill collapse, per-user hint cap, a checkpoint-contention gate). "Rebuild = full resync" is cheap on phones (28 MB) but not on native (P2-8).
  2. #919: as written it refuses commuting actions and has the tab-undo hole. Use the per-field, "changed and ≠ requested" rule, opt-in per action, with notes untouched (P1-3).
  3. #918: not correct as specified. A per-start mark misses backups taken after the last start, snapshot rollbacks and power-loss rollbacks. Use the token entry check plus the high-water file (P1-1), and move the Writer position into the log (P1-2).
  4. Send, identity, cache and proxy findings: see the P2 and P3 sections above.

P1: 3 · P2: 8 · P3: 5

## Review of v4 (head 4355db68): plan + #918 + #919 I checked this against `origin/dev`: `crates/store/src/{lib,schema,writer,read}.rs`, `crates/engine/src/lib.rs` (`journal`, `journal_for`), `crates/server/src/live.rs` (`run`, `catch_up`, `visible_entry`), `crates/notes/src/actions.rs` (`base: i64` on patch/replace), `docs/storage.md`, and ADRs 0011/0044/0047. The simplification is right. Riding the executor and save log removes the round-3 bug class. What's left is mostly in the two shared fixes and in how mail's volume meets one shared journal. Facts from the code that the findings rely on: - One writer thread per user for `index.db`, shared with notes. No group commit. Queue of 64. - Journal commits use WAL + `synchronous=NORMAL`. Only `commit_once` uses FULL. - `seq` is `AUTOINCREMENT`, so a rolled-back tail gives the same seq numbers out again. - `position()` only rejects `epoch ≠` or `seq > head`. - The journal is never pruned. - `catch_up` sends every entry in order, in pages of 1000, before `ready`. The route only filters for app passwords. ### P1 **P1-1 · #918 misses the common restore paths (§2, §6, §15 "Backup restored").** The mark is written *at each server start*, so any backup taken after the last start holds the same value as the secrets file. Example: start Monday, backup Tuesday, devices move ahead Wednesday, restore Tuesday's backup Thursday. The marks match, nothing rotates, and devices whose token is past the restored head skip entries silently once the server writes past them. That is the exact bug #918 is meant to fix. Two more paths it can't see: - (a) A whole-host or VM snapshot rollback. `storage.md` recommends "a coordinated filesystem snapshot", and on Proxmox the secrets root rolls back with everything else. - (b) A power loss under `synchronous=NORMAL`. The WAL tail is lost and its seqs are given out again for different entries. **Fix (covers all three, no hot-path cost):** - Make the token check the entry, not just the seq. Token = `epoch-seq-check`, where `check` = 32 bits of `hash(seq, at_ms, request_id, kind)` of the entry at `seq`. - `position()` does one PK lookup. If the entry is missing or the check differs, return `SyncTokenExpired` *and* rotate the epoch for everyone. The server has just learned it went back in time. - Keep a small high-water file outside the backups (`<secrets>/users/<u>/head`, holding epoch and head seq, written off the hot path every N seconds). At open, `head < high-water` or an epoch mismatch means restored. That gives plugins their `restored` signal before work starts. - Drop the "random value per start" mark. It's the part that doesn't work. **P1-2 · Writer position is in a different database from the log it points into (§3 "Writer position", §5 `writer_pos`).** `writer_pos` is in `state.db`; the entries are in `index.db`. If `index.db` loses its tail (power loss, P1-1b) while `state.db` keeps the position, the Writer's position is above the head. New `mail.acted` entries reuse those seqs, and the Writer skips them. Devices already applied them optimistically, so the actions show as done but never reach the provider and are never refused. The epoch check in §3 doesn't fire, because the epoch is unchanged. **Fix:** remove `writer_pos` from `state.db`. Each outcome entry already exists; give it `upto: seq`. At start the Writer reads its position from the last `mail.applied`/`mail.refused` for that account, in the same database and the same rollback. That's one less table, and the "outcome first, then position" ordering goes away. **P1-3 · #919's rule as written refuses commuting actions and still lets a newer change be undone (§8 "Base", #919).** - *Whole-target granularity:* device A flags a thread, device B (same base) marks it read, and B gets `stale`. The person sees "Some changes you made offline weren't applied…" even though nothing conflicts. `flags_seq` covers read, flag and labels together, so this happens on every race between two of them, including a provider push that only adds a Gmail label. - *Any bump counts:* the daily flag sweep, a delta that rewrites the same value, and a `cache.db` rebuild (§6) all set new seqs. After a rebuild, every queued offline action comes back `stale`. - *Same-Installation exemption:* web tabs share an Installation. Tab A archives, the reply is lost, and tab B un-archives. After the 7-day receipt prune, tab A's retry is exempt and archives again. That is the undo #919 exists to prevent, and it contradicts "two tabs need nothing special". **Narrowest correct rule:** - **Per field.** Track `seq` per field: `read`, `flagged`, each label, placement. Bump it only when the *value* changes. - **Stale only if both hold:** the field changed after `base` *and* its current value ≠ the requested value. If current = requested, return success with no change. So two devices marking read both succeed, a flag racing a read commutes, and a provider push that already did the same thing is fine. The ABA late retry (archived → back to Inbox → old "archive" retry) is still refused. - **No Installation exemption.** Instead, the device outbox coalesces per `(target, field)` before sending, so "toggle N times offline" sends one final state per base. The `stale_base` test then needs no special case. - **Base from an older epoch** (after a restore): treat it as "changed since base". - **`base` optional for online adapters** (CLI, MCP, bulk jobs) and required only when the device outbox replays an action. - **Opt-in per action.** Notes keep their own per-note version `base: i64` and merge (`notes.patch`/`replace`). Room/CRDT edits never go through this. #919 must not become an executor-wide check, or concurrent note edits that merge today would be refused. The #919 text says notes "already keep a base hash"; they keep a version that *merges*, so it isn't the same mechanism. ### P2 **P2-1 · Mail hints flood the one sync route (§7 "Save-log volume", ADR 0014).** Every device session receives every `mail.synced`. That includes a Notes-only tab, CLI followers and MCP Events webhooks: 20 accounts backfilling means about 20 webhook deliveries a second. `catch_up` sends the backlog in order before `ready`, so a phone that was offline during a big backfill gets tens of MB of mail hints *before* the notes edits that sit after them. Notes sync latency on reconnect then depends on mail volume. The size estimate is also low. 500 ids as hex JSON is about 17 KB per entry, so 4,000 entries is about 70 MB, not 40 MB. Fixes: - (a) The route accepts a kind-prefix filter. It's tiny, it's what ADR 0044 means by "filtered on the server", and it isn't a separate stream. - (b) In `catch_up`, when more than K `mail.synced` entries for one account are pending, send one synthetic `mail.refill {account}`. The device pages the spine. - (c) Ids as base64url (22 chars). Add a gate: notes reconnect-to-ready p95 after a 100k backfill backlog, flat vs dev. **P2-2 · Hints for rows the device will throw away (§7 Devices).** Phones keep the newest 200k, but backfill sends hints for the remaining 1.8M. Without dates in the hint, the device has to fetch `mail.threads(ids)` just to learn they're below `B`. **Fix:** `mail.synced {…, oldest_ms, newest_ms}`, and the device skips any batch with `newest_ms < B`. **P2-3 · Shared writer and checkpoints under backfill.** About 340 KB/s of hint JSON into the shared `index.db` WAL means an autocheckpoint every ~12 s. On the perf VMs those fsyncs are 60–338 ms under contention, and the next notes commit waits behind them in the one writer thread. **Fix:** - Cap the hint rate per *user*, not per account: 1–2/s across all accounts, merged. - Add a gate for notes action accept p99 (not just typing), with 20 accounts backfilling on a contended disk. **P2-4 · A crash between the `cache.db` commit and the hint loses that hint (§7 Push: "Commit first, then write the hint").** Devices only refresh on hints, so those threads stay stale on devices until something else touches them. **Fix:** add `changed_rev` per row and one `hinted_rev` per account in `cache.db` (columns, not a change table). At worker start, re-hint rows with `changed_rev > hinted_rev`. **P2-5 · An accepted action can be lost on power loss (§8 "Two acknowledgements").** The `mail.acted` journal entry is the *only* record of the action, the device clears its outbox on accept (ADR 0047: "only after the server confirms durable storage"), and the commit is `NORMAL`. For notes the content lives elsewhere; for mail nothing else holds it. **Fix:** a shared "durable" commit flag that uses `synchronous=FULL` with group commit (drain the queue, one fsync), used by mail actions. Gate it against notes accept latency. Or state plainly that this is accepted risk. **P2-6 · The restore rule cancels legitimate scheduled mail, and misses `state.db`-only or snapshot rollbacks (§9 last row).** - "Held and scheduled mail is not released" turns a send scheduled for next week into `unknown` / "check Sent". It can't have gone out yet, because its `release_ms` is still in the future. Keep rows with `release_ms > now` scheduled. - After a VM snapshot rollback or a `state.db`-only restore (P1-1), already-delivered rows come back as `pending` and are retried automatically. Belt and braces: before the *first* DATA of any row created more than 10 min ago, run `lookup_sent(Message-ID)` where `caps` allow it. **P2-7 · The id scheme flips when `pkey` support changes (§4).** `msg id` uses one formula with a `pkey` and another without. A server that starts offering OBJECTID/EMAILID after an upgrade, or drops it, changes every id. Every link breaks, and the mirror names no longer match, so everything downloads again and the old files go to Recently deleted. **Fix:** fix the scheme per account at creation in `state.db` (`account.id_scheme`) and never switch it, as with `akey`. **P2-8 · A rebuild means a full download on native (§6, §7).** `mail.reset` / an epoch change means "drop and refill": about 280 MB per native device for 2M threads, and 28 MB per phone, on every rebuild or detected restore. With P1-1's fix, a power-loss rollback triggers it too. Ids are derived, so the device's copy is still valid. **Fix:** the refill compares per-month spine digests (`hash` of `(id, sort_ms, flags)` per month) and fetches only the months that differ. Add a gate: refill bytes after `cache_rebuild` ≤ 1% of the spine when nothing changed. ### P3 - **§4 rule 4, no-`pkey` hosts.** With `n` as the rank by UID, moving one of two same-`fp` copies (a list copy and a Cc copy) swaps their ids, because the moved copy gets a higher UID. Rank by `content_hash` first and by UID only among byte-identical copies. - **§3, words on refusal.** `mail.refused {reason: restored}` should show no words. Some of those actions did reach the provider before the restore. - **§13 / proxy stub.** `visible_entry`/`journal_for` give app-password callers only `notes.*`/`sharing.*` entries and require `notes.read`. Say the proxy follows the log as an in-process consumer, not through the app-password sync route, or the `imap.mail` scope needs those mail kinds. - **§3 "cache ⊕ pending".** The keyset page overlay needs a rule for threads that pending moves take out of, or bring into, a page. Short pages are fine; skipped rows are not. Add it to `list_page_scaling`. - **Journal retention.** Mail adds entries to a journal that is never pruned. That's fine for now; put "journal size after a 1M backfill + 1 year of push" in the budgets. ### Answers to the four questions 1. **Shared machinery:** it holds, provided P2-1–P2-3 are in place (kind filter, refill collapse, per-user hint cap, a checkpoint-contention gate). "Rebuild = full resync" is cheap on phones (28 MB) but not on native (P2-8). 2. **#919:** as written it refuses commuting actions and has the tab-undo hole. Use the per-field, "changed and ≠ requested" rule, opt-in per action, with notes untouched (P1-3). 3. **#918:** not correct as specified. A per-start mark misses backups taken after the last start, snapshot rollbacks and power-loss rollbacks. Use the token entry check plus the high-water file (P1-1), and move the Writer position into the log (P1-2). 4. Send, identity, cache and proxy findings: see the P2 and P3 sections above. P1: 3 · P2: 8 · P3: 5
Author
Owner

v4.1 pushed (head c68be1f9). Mapping of review 77534 (+ 77537 on #919, 77539 on #918). Section numbers refer to docs/plans/mail-architecture.md. kayg 14:40 IST: start minimal; Q7 and Q11 approved.

# Fix Where
P1-1 #918 rewritten: token = epoch-seq-check (one PK lookup; mismatch → SyncTokenExpired + epoch rotation), high-water file under --secrets written every 5 s off the hot path, plugins get restored. The per-start mark is dropped. Durability stated: NORMAL commits can lose the tail and reuse seqs. Instead of making notes pay for FULL, reuse becomes detectable; an opt-in durable commit (FULL + group commit) is for entries that are the only record of intent. Notes cost: at most one queued fsync behind a durable commit; gated flat vs dev #918, §2
P1-2 writer_pos removed. The Writer position is the highest upto among its own mail.applied/mail.refused entries, so it rolls back with the log §3, §5
P1-3 #919 rewritten: opt-in per action kind, per field; stale only if the field changed after base and current ≠ requested; equal → no-op success; no Installation exemption (the outbox coalesces per target and field); base from an older epoch = changed; optional for online adapters. Notes behaviour does not change #919, §2, §8
P2-1 Sync topics on the one route (kind prefixes; Notes-only tabs and existing webhooks never get mail); in catch_up, more than 200 pending mail hints collapse into mail.refill. Size corrected: backfill hints carry no ids (date range + count), ≈ 0.4 MB per 2M backfill; delta ids in base64url. Gate: notes reconnect-to-ready flat with a 100k mail backlog §2, §7, §16
P2-2 Hints carry oldest_ms/newest_ms; the device skips batches below B §7
P2-3 ≤ 1 mail hint/s per user, merged across accounts. Gate: notes accept p99 with 20 accounts backfilling + durable mail actions on a contended disk, flat vs dev §7, §16
P2-4 changed_rev per row, hinted_rev per account (columns, not a change table); re-hint at start §5, §7
P2-5 mail.acted is a durable commit; the outbox clears only on that §3, §8
P2-6 Restore row replaced by an overdue check at every start: rows due more than 10 min ago → lookup_sent (JMAP submissions or a Sent search by Message-ID); found → delivered; provider saves Sent and not found → send; else held as unknown. Future-scheduled rows stay scheduled §9
P2-7 account.id_scheme fixed at creation; gaining or losing stable ids never switches it §4, §5
P2-8 Refill keeps the device copy and compares per-month XOR digests; only differing months are re-paged. Gate ≤ 1% after an unchanged rebuild §6, §7, §16
P3 n swap Rank by content_hash, then UID among identical copies; fixture added §4
P3 words refused {reason: restored} shows no words §3
P3 proxy The proxy follows the mail topic in-process, not via the app-password route §13, proxy stub
P3 keyset overlay Rule for pending moves in/out of a page; cursor = last cache row; added to list_page_scaling §3, §17
P3 journal size Budget row: journal size after 1M backfill + 1 year of push (synthetic) §16

Accepted risk, stated in §3: a snapshot rollback that only devices detect later replays the mail actions that were pending at snapshot time (the person's last intent, the same as an outbox replay).

Size: 380 → 391 lines (rev 3 was 666).

v4.1 pushed (head c68be1f9). Mapping of review 77534 (+ 77537 on #919, 77539 on #918). Section numbers refer to `docs/plans/mail-architecture.md`. kayg 14:40 IST: start minimal; Q7 and Q11 approved. | # | Fix | Where | |---|---|---| | P1-1 | #918 rewritten: token = `epoch-seq-check` (one PK lookup; mismatch → `SyncTokenExpired` + epoch rotation), high-water file under `--secrets` written every 5 s off the hot path, plugins get `restored`. The per-start mark is dropped. **Durability stated:** NORMAL commits can lose the tail and reuse seqs. Instead of making notes pay for FULL, reuse becomes detectable; an opt-in **durable** commit (FULL + group commit) is for entries that are the only record of intent. Notes cost: at most one queued fsync behind a durable commit; gated flat vs dev | #918, §2 | | P1-2 | `writer_pos` removed. The Writer position is the highest `upto` among its own `mail.applied`/`mail.refused` entries, so it rolls back with the log | §3, §5 | | P1-3 | #919 rewritten: opt-in per action kind, per field; `stale` only if the field changed after `base` **and** current ≠ requested; equal → no-op success; no Installation exemption (the outbox coalesces per target and field); `base` from an older epoch = changed; optional for online adapters. **Notes behaviour does not change** | #919, §2, §8 | | P2-1 | Sync **topics** on the one route (kind prefixes; Notes-only tabs and existing webhooks never get mail); in `catch_up`, more than 200 pending mail hints collapse into `mail.refill`. Size corrected: backfill hints carry no ids (date range + count), ≈ 0.4 MB per 2M backfill; delta ids in base64url. Gate: notes reconnect-to-ready flat with a 100k mail backlog | §2, §7, §16 | | P2-2 | Hints carry `oldest_ms/newest_ms`; the device skips batches below `B` | §7 | | P2-3 | ≤ 1 mail hint/s per **user**, merged across accounts. Gate: notes accept p99 with 20 accounts backfilling + durable mail actions on a contended disk, flat vs dev | §7, §16 | | P2-4 | `changed_rev` per row, `hinted_rev` per account (columns, not a change table); re-hint at start | §5, §7 | | P2-5 | `mail.acted` is a durable commit; the outbox clears only on that | §3, §8 | | P2-6 | Restore row replaced by an **overdue check** at every start: rows due more than 10 min ago → `lookup_sent` (JMAP submissions or a Sent search by Message-ID); found → delivered; provider saves Sent and not found → send; else held as `unknown`. Future-scheduled rows stay scheduled | §9 | | P2-7 | `account.id_scheme` fixed at creation; gaining or losing stable ids never switches it | §4, §5 | | P2-8 | Refill keeps the device copy and compares per-month XOR digests; only differing months are re-paged. Gate ≤ 1% after an unchanged rebuild | §6, §7, §16 | | P3 `n` swap | Rank by `content_hash`, then UID among identical copies; fixture added | §4 | | P3 words | `refused {reason: restored}` shows no words | §3 | | P3 proxy | The proxy follows the `mail` topic in-process, not via the app-password route | §13, proxy stub | | P3 keyset overlay | Rule for pending moves in/out of a page; cursor = last cache row; added to `list_page_scaling` | §3, §17 | | P3 journal size | Budget row: journal size after 1M backfill + 1 year of push (synthetic) | §16 | Accepted risk, stated in §3: a snapshot rollback that only devices detect later replays the mail actions that were pending at snapshot time (the person's last intent, the same as an outbox replay). Size: 380 → 391 lines (rev 3 was 666).
Author
Owner

Second review of v4.1 (head c68be1f9): plan + #918 + #919

Checked against origin/dev 41f2efa3: crates/store/src/{writer,schema,lib}.rs, crates/server/src/live.rs (run, catch_up, visible_entry), crates/notes/src/history.rs, and ADRs 0011/0014/0021/0044/0047. Facts from the code that I rely on below:

  • One writer thread per user for index.db, FIFO queue of 64, one transaction per command. commit_inner returns Err (and drops the whole transaction) on an idempotency conflict.
  • Cmd::Once (publication receipts) already switches the shared writer to FULL for one commit, so notes can already wait behind an fsync there. That's rare today.
  • Notes durability doesn't come from index.db. notes/history.db has its own FULL writer thread with its own group commit (ADR 0020). So index.db commits are cheap for notes because they are NORMAL.
  • The live broadcast holds 1,024 entries of every kind. A lagging session falls back to catch_up. The journal has no index on kind or item.

1. First-review findings

# Status
P1-1 (#918 detection) Mostly fixed. Token check plus high-water is the right shape. Gaps are in N-4 and N-5 below
P1-2 (writer_pos) Fixed. Position is derived from its own outcome entries. Start-up cost is in P3
P1-3 (#919 rule) Mostly fixed. It's per field, opt-in, and notes are untouched. But a device's own in-flight action now makes its next action stale, and outbox coalescing is under-specified (N-3)
P2-1 topics / refill / size Fixed (SQL index in P3)
P2-2, P2-3, P2-4, P2-7, P2-8 Fixed
P2-5 accepted action lost on power loss Replaced by a fix that breaks the notes no-regression rule (N-1)
P2-6 restore and sends Regressed. The overdue check re-sends mail (N-2)
P3s Fixed

Two sections now contradict each other. §1 principle 3 ("never sent again automatically… a restore never releases held mail") and §6 ("A restore by itself sends nothing") don't match the §9 overdue row ("not found → send as normal").

P1

N-1 · The durable group commit makes note saves wait behind mail fsyncs (#918 §4, plan §3/§8). The issue states the cost itself: a notes commit queued behind a durable one waits for one fsync, 6.5 ms quiet and 60–338 ms contended. At 1 durable commit/s on a contended disk, about 6–30% of notes commits land inside that window. Notes accept p99 moves by the full fsync time. A select-all archive or a Cal bulk job sends a burst of durable commits in a row. The gate can't pass, and the fallback ("own fsync window between notes commits") still blocks the one writer thread for the fsync. There's also a correctness problem: draining queued commands into one transaction means one command's IdempotencyConflict drops every notes commit batched with it, unless each command gets its own SAVEPOINT.

Fix (recommended; simpler, no fsync, no new machinery): treat the provider as the durable store.

  • The device outbox clears an op when it sees that op's mail.applied or mail.refused, not on accept. The UI stays optimistic, as it is now.
  • A power loss can lose accepted-but-not-applied entries from the last few seconds. The outbox replays them with the same op id. The executor's idempotency record went with the same power loss, so it runs again, which is harmless because actions set state.
  • Online adapters (CLI, MCP) take that same short window as a stated risk, or wait for applied with an option.
  • ADR 0047's "only after the server confirms durable storage" is met by the provider's OK.
  • Delete Commit { durable } from #918.

Only if accept-time durability is really needed: keep every commit NORMAL on the writer thread. A separate barrier thread does one coalesced fdatasync on index.db-wal and only then answers the mail caller. The writer thread never waits, so notes never queue behind it. A checkpoint under NORMAL syncs the WAL before resetting it, so frames committed earlier are covered. Gate: notes accept p99 flat with a 10k-archive burst on a contended disk.

I don't recommend a separate mail-intent DB with FULL. It brings back the two-databases ordering problem that P1-2 removed.

N-2 · The overdue check re-sends mail whose outcome is unknown, and a restore brings back sends the person cancelled (§9 overdue row, §1, §6). The row covers "recipients not yet final", which includes unknown (crash after data_started).

  • Case 1: final reply lost and the server restarts. More than 10 min later, lookup_sent misses (IMAP Sent search lag, a Sent copy in a localised folder, a mismatched caps.saves_sent). The mail is sent a second time.
  • Case 2: send, Undo (or unschedule), then a backup restore or snapshot rollback brings the held row back with a release_ms in the past. Lookup finds nothing, because it was never sent, so it is sent although the person cancelled it.

Fix:

  • The overdue check never sends on its own. Found → delivered. Not found → held, with one line: "This mail was due at 10:42 and hasn't gone out. Send now?"
  • unknown keeps its own rule (never automatic).
  • After a detected restored, scheduled rows also go to held-for-review with one line. This updates my earlier P2-6: keeping them scheduled was right about time, but a cancel made in the lost future is gone too.
  • Still accepted after this: an undetected snapshot rollback can send a scheduled mail that was cancelled in the lost future. State it next to the action risk.

P2

N-3 · #919: a device's own unconfirmed action makes its next one stale, and the outbox merge rules are missing.

  • Flaky network: mark read (accepted at seq 70, reply lost), then mark unread with base 69. read_seq ≥ 69 and current (read) ≠ requested (unread), so the result is stale. The person sees "changed somewhere else" about their own change. The Installation exemption covered this; dropping it was right, but the case needs a narrower answer.
  • Fix: an action carries after: [op ids], the device's own unconfirmed ops on those targets. A change after base made by one of those ops doesn't count. Keep field_req (the request id of the last change) next to each field seq. Tab B's un-archive is never in tab A's list, so the undo stays blocked.
  • Coalescing applies only to the not-yet-sent tail. An op already sent keeps its payload and key. The merged op takes the oldest base of its parts, and a merge that returns to the original value is dropped only if none of its parts was sent.
  • "Current" and "changed" must include pending mail.acted entries (with their seq), not just cache.db. Today cache values change only on the next delta. Without that, a racing action from a stale base slips through as last-writer-wins until the delta arrives.
  • Rebuilt rows get field_seq = head at rebuild. The value 0 would re-open the undo for any change made before the rebuild.

N-4 · #918: any client can force an epoch rotation for the whole user. "Missing entry or a different check → rotate for everyone" fires on any token whose check doesn't match. That includes a malformed or hand-edited token from a buggy client, CLI script or low-scope MCP key. Each rotation sends every device into refill and search into a full reconcile (2M mail docs). The new epoch is visible to the client, so it can happen again and again.
Fix:

  • Make the check keyed: blake3_keyed(user key from <secrets>, seq ‖ at_ms ‖ kind ‖ item ‖ request_id), truncated to 32 bits.
  • Rotate only when a keyed check fails and seq ≤ head, or when the high-water file says so. A token from an older epoch is just expired, never a rotation.
  • Old tokens without a check: accept them only while the high-water file shows no rollback, not "once" blindly.

On collision odds: a 32-bit check misses one affected token in 2³² per rollback. That gives today's silent skip, nothing worse, so it's fine. Add item to the input.

N-5 · #918 high-water edge cases that skip the restored signal. The issue only handles "file epoch = meta.epoch and file seq > head".

  • (a) Epoch differs. A backup taken before an earlier rotation is restored. Devices are fine (epoch expired), but plugins get no restored. The mail Writer then applies days-old pending mail.acted from the backup, and the Sender runs its normal path. Rule: any epoch mismatch counts as restored.
  • (b) A rename without fsync can leave a zero-length or torn file after power loss. Rule: unreadable counts as missing.
  • (c) The rotation itself must be a FULL commit, and the file rewritten (fsync + rename) before the first new-epoch token goes out. Otherwise a power loss right after rotating hands out tokens for an epoch the DB forgot. That's rare, and it's not on the notes path.
  • (d) "Missing file → rotate once" makes the #918 deploy rotate every user at once (full search reconcile everywhere). Record meta.highwater = 1 in index.db. Rotate only if that flag is set and the file is gone; otherwise create the file.

P3

  • Topics in SQL: add a topic column and an index (topic, seq) on journal. Then a notes-only catch_up, the mail.refill count and a Lagged re-scan skip mail rows instead of paging through them.
  • Writer start: "highest upto among its outcome entries" and "pending after it" are backward scans of a journal that is never pruned, with no index on kind or item. An idle account scans the whole log. Use an index (kind, item, seq) or the topic index above, and put it in the cold-start gate.
  • Writer coalescing: "read+unread cancel out" should be "send the final state per field". Cancelling leaves the provider wrong if another client changed it in between.
  • Webhooks / MCP Events: the payload should carry the checked token, and receivers should dedupe by token, not seq. Seqs are reused after a rollback.

3. Accepted risk (pending actions replayed after a late-noticed snapshot rollback)

Acceptable for actions:

  • The window is the Writer's lag at snapshot time, which is seconds while the provider is reachable.
  • The effect is a reversible folder or flag state: nothing is deleted and nothing is sent.
  • No cheap fix exists without a witness outside the snapshot. Value checks fail on A→B→A, and the high-water file rolls back too.

Keep it, with one change: list delete_forever as the exception. Hold it until its mail.applied, and refuse it with words if restored arrives first. Not acceptable for sends: that's N-2. With N-2 fixed, what's left is the single undetected-rollback scheduled-send case.

On (c): can notes still queue behind mail?

On the writer: only through the durable commits (N-1). With N-1 fixed, mail adds at most ~1 NORMAL commit/s plus action entries, each well under a millisecond. On the route: topics stop delivery, but without the P3 index catch_up still pages through mail rows. On the broadcast: mail bursts can push a slow notes session past the 1,024-entry buffer into a re-scan. That's covered by the P3 index and the reconnect gate.

P1: 2 · P2: 3 · P3: 4. Not fully fixed from round 1: P1-1 (N-4, N-5), P1-3 (N-3), P2-5 (N-1), P2-6 (N-2).

## Second review of v4.1 (head c68be1f9): plan + #918 + #919 Checked against `origin/dev` 41f2efa3: `crates/store/src/{writer,schema,lib}.rs`, `crates/server/src/live.rs` (`run`, `catch_up`, `visible_entry`), `crates/notes/src/history.rs`, and ADRs 0011/0014/0021/0044/0047. Facts from the code that I rely on below: - One writer thread per user for `index.db`, FIFO queue of 64, one transaction per command. `commit_inner` returns `Err` (and drops the whole transaction) on an idempotency conflict. - `Cmd::Once` (publication receipts) already switches the shared writer to FULL for one commit, so notes can already wait behind an fsync there. That's rare today. - Notes durability doesn't come from `index.db`. `notes/history.db` has its own FULL writer thread with its own group commit (ADR 0020). So `index.db` commits are cheap for notes *because* they are NORMAL. - The live broadcast holds 1,024 entries of every kind. A lagging session falls back to `catch_up`. The journal has no index on `kind` or `item`. ### 1. First-review findings | # | Status | |---|---| | P1-1 (#918 detection) | **Mostly fixed.** Token check plus high-water is the right shape. Gaps are in N-4 and N-5 below | | P1-2 (`writer_pos`) | **Fixed.** Position is derived from its own outcome entries. Start-up cost is in P3 | | P1-3 (#919 rule) | **Mostly fixed.** It's per field, opt-in, and notes are untouched. But a device's own in-flight action now makes its next action `stale`, and outbox coalescing is under-specified (N-3) | | P2-1 topics / refill / size | Fixed (SQL index in P3) | | P2-2, P2-3, P2-4, P2-7, P2-8 | Fixed | | P2-5 accepted action lost on power loss | **Replaced by a fix that breaks the notes no-regression rule** (N-1) | | P2-6 restore and sends | **Regressed.** The overdue check re-sends mail (N-2) | | P3s | Fixed | Two sections now contradict each other. §1 principle 3 ("never sent again automatically… a restore never releases held mail") and §6 ("A restore by itself sends nothing") don't match the §9 overdue row ("not found → send as normal"). ### P1 **N-1 · The durable group commit makes note saves wait behind mail fsyncs (#918 §4, plan §3/§8).** The issue states the cost itself: a notes commit queued behind a durable one waits for one fsync, 6.5 ms quiet and 60–338 ms contended. At 1 durable commit/s on a contended disk, about 6–30% of notes commits land inside that window. Notes accept p99 moves by the full fsync time. A select-all archive or a Cal bulk job sends a burst of durable commits in a row. The gate can't pass, and the fallback ("own fsync window between notes commits") still blocks the one writer thread for the fsync. There's also a correctness problem: draining queued commands into one transaction means one command's `IdempotencyConflict` drops every notes commit batched with it, unless each command gets its own SAVEPOINT. **Fix (recommended; simpler, no fsync, no new machinery): treat the provider as the durable store.** - The device outbox clears an op when it sees that op's `mail.applied` or `mail.refused`, not on accept. The UI stays optimistic, as it is now. - A power loss can lose accepted-but-not-applied entries from the last few seconds. The outbox replays them with the same op id. The executor's idempotency record went with the same power loss, so it runs again, which is harmless because actions set state. - Online adapters (CLI, MCP) take that same short window as a stated risk, or wait for `applied` with an option. - ADR 0047's "only after the server confirms durable storage" is met by the provider's OK. - Delete `Commit { durable }` from #918. **Only if accept-time durability is really needed:** keep every commit NORMAL on the writer thread. A separate barrier thread does one coalesced `fdatasync` on `index.db-wal` and only then answers the mail caller. The writer thread never waits, so notes never queue behind it. A checkpoint under NORMAL syncs the WAL before resetting it, so frames committed earlier are covered. Gate: notes accept p99 flat with a 10k-archive burst on a contended disk. I don't recommend a separate mail-intent DB with FULL. It brings back the two-databases ordering problem that P1-2 removed. **N-2 · The overdue check re-sends mail whose outcome is unknown, and a restore brings back sends the person cancelled (§9 overdue row, §1, §6).** The row covers "recipients not yet final", which includes `unknown` (crash after `data_started`). - Case 1: final reply lost and the server restarts. More than 10 min later, `lookup_sent` misses (IMAP Sent search lag, a Sent copy in a localised folder, a mismatched `caps.saves_sent`). The mail is **sent a second time**. - Case 2: send, Undo (or unschedule), then a backup restore or snapshot rollback brings the `held` row back with a `release_ms` in the past. Lookup finds nothing, because it was never sent, so it is **sent although the person cancelled it**. **Fix:** - The overdue check never sends on its own. Found → `delivered`. Not found → held, with one line: "This mail was due at 10:42 and hasn't gone out. Send now?" - `unknown` keeps its own rule (never automatic). - After a detected `restored`, scheduled rows also go to held-for-review with one line. This updates my earlier P2-6: keeping them scheduled was right about time, but a cancel made in the lost future is gone too. - Still accepted after this: an *undetected* snapshot rollback can send a scheduled mail that was cancelled in the lost future. State it next to the action risk. ### P2 **N-3 · #919: a device's own unconfirmed action makes its next one `stale`, and the outbox merge rules are missing.** - Flaky network: mark read (accepted at seq 70, reply lost), then mark unread with `base` 69. `read_seq` ≥ 69 and current (read) ≠ requested (unread), so the result is `stale`. The person sees "changed somewhere else" about their own change. The Installation exemption covered this; dropping it was right, but the case needs a narrower answer. - **Fix:** an action carries `after: [op ids]`, the device's own unconfirmed ops on those targets. A change after `base` made by one of those ops doesn't count. Keep `field_req` (the request id of the last change) next to each field seq. Tab B's un-archive is never in tab A's list, so the undo stays blocked. - **Coalescing** applies only to the not-yet-sent tail. An op already sent keeps its payload and key. The merged op takes the *oldest* `base` of its parts, and a merge that returns to the original value is dropped only if none of its parts was sent. - **"Current" and "changed"** must include pending `mail.acted` entries (with their seq), not just `cache.db`. Today cache values change only on the next delta. Without that, a racing action from a stale base slips through as last-writer-wins until the delta arrives. - **Rebuilt rows** get `field_seq` = head at rebuild. The value 0 would re-open the undo for any change made before the rebuild. **N-4 · #918: any client can force an epoch rotation for the whole user.** "Missing entry or a different check → rotate for everyone" fires on any token whose check doesn't match. That includes a malformed or hand-edited token from a buggy client, CLI script or low-scope MCP key. Each rotation sends every device into refill and search into a full reconcile (2M mail docs). The new epoch is visible to the client, so it can happen again and again. **Fix:** - Make the check keyed: `blake3_keyed(user key from <secrets>, seq ‖ at_ms ‖ kind ‖ item ‖ request_id)`, truncated to 32 bits. - Rotate only when a keyed check fails *and* `seq` ≤ head, or when the high-water file says so. A token from an older epoch is just expired, never a rotation. - Old tokens without a check: accept them only while the high-water file shows no rollback, not "once" blindly. On collision odds: a 32-bit check misses one affected token in 2³² per rollback. That gives today's silent skip, nothing worse, so it's fine. Add `item` to the input. **N-5 · #918 high-water edge cases that skip the `restored` signal.** The issue only handles "file epoch = `meta.epoch` and file seq > head". - (a) Epoch differs. A backup taken before an earlier rotation is restored. Devices are fine (epoch expired), but plugins get no `restored`. The mail Writer then applies days-old pending `mail.acted` from the backup, and the Sender runs its normal path. **Rule:** any epoch mismatch counts as restored. - (b) A rename without fsync can leave a zero-length or torn file after power loss. **Rule:** unreadable counts as missing. - (c) The rotation itself must be a FULL commit, and the file rewritten (fsync + rename) before the first new-epoch token goes out. Otherwise a power loss right after rotating hands out tokens for an epoch the DB forgot. That's rare, and it's not on the notes path. - (d) "Missing file → rotate once" makes the #918 deploy rotate every user at once (full search reconcile everywhere). Record `meta.highwater = 1` in `index.db`. Rotate only if that flag is set and the file is gone; otherwise create the file. ### P3 - **Topics in SQL:** add a `topic` column and an index `(topic, seq)` on `journal`. Then a notes-only `catch_up`, the `mail.refill` count and a `Lagged` re-scan skip mail rows instead of paging through them. - **Writer start:** "highest `upto` among its outcome entries" and "pending after it" are backward scans of a journal that is never pruned, with no index on kind or item. An idle account scans the whole log. Use an index `(kind, item, seq)` or the topic index above, and put it in the cold-start gate. - **Writer coalescing:** "read+unread cancel out" should be "send the final state per field". Cancelling leaves the provider wrong if another client changed it in between. - **Webhooks / MCP Events:** the payload should carry the checked token, and receivers should dedupe by token, not seq. Seqs are reused after a rollback. ### 3. Accepted risk (pending actions replayed after a late-noticed snapshot rollback) **Acceptable for actions:** - The window is the Writer's lag at snapshot time, which is seconds while the provider is reachable. - The effect is a reversible folder or flag state: nothing is deleted and nothing is sent. - No cheap fix exists without a witness outside the snapshot. Value checks fail on A→B→A, and the high-water file rolls back too. Keep it, with one change: list `delete_forever` as the exception. Hold it until its `mail.applied`, and refuse it with words if `restored` arrives first. **Not acceptable for sends**: that's N-2. With N-2 fixed, what's left is the single undetected-rollback scheduled-send case. ### On (c): can notes still queue behind mail? On the writer: only through the durable commits (N-1). With N-1 fixed, mail adds at most ~1 NORMAL commit/s plus action entries, each well under a millisecond. On the route: topics stop delivery, but without the P3 index `catch_up` still pages through mail rows. On the broadcast: mail bursts can push a slow notes session past the 1,024-entry buffer into a re-scan. That's covered by the P3 index and the reconnect gate. P1: 2 · P2: 3 · P3: 4. Not fully fixed from round 1: P1-1 (N-4, N-5), P1-3 (N-3), P2-5 (N-1), P2-6 (N-2).
Author
Owner

v4.2 pushed (head bc1cd7bc). This is the mapping of second review 77555, plus 77558 on #918 and 77560 on #919. Every fix either removes machinery or narrows a rule. Decisions are kayg's ("start minimal"). Section numbers refer to docs/plans/mail-architecture.md.

# Fix Where
N-1 The durable commit flag and group commit are deleted from #918 and the plan. The provider is the durable store: the device outbox clears an op only on mail.applied/mail.refused. An accepted entry lost to a power loss is replayed with the same op id, and that's harmless because the action only sets state. Notes commit latency is unchanged, since no mail fsync exists. The gate now uses a 10k-archive burst #918, §3, §8, §16
N-2 Nothing sends on its own after uncertainty. An overdue row is either found by lookup_sent (→ delivered) or held with "This mail was due at 10:42 and hasn't gone out. Send now?". unknown stays held. After a detected restored, rows scheduled for later are held for review too. §1, §6, §9 and §15 now say the same thing: a restore sends nothing §1, §6, §9, §15, §17
N-3 #919: after: [own unconfirmed op ids] plus field_req, so a device's own in-flight change never makes its next one stale. "Current" and "changed" include pending actions. Rebuilt rows get the head. The outbox merges only unsent ops. Tests added #919, §2, §5, §8, §17
N-4 #918: token = epoch-seq-c-m with a per-user keyed m. A bad m → invalid token with no rotation; another epoch → expired. Only a valid m against a missing or different entry, or the high-water file, rotates. Old tokens are accepted only while this boot's high-water check passed #918, §2
N-5 #918: an epoch mismatch counts as restored; an unreadable or torn file counts as missing. Rotation is a FULL commit plus a file fsync before any new-epoch token. meta.highwater keeps the first deploy from rotating anyone #918
P3 topic index topic column + (topic, seq) index; catch_up skips other topics §2
P3 Writer start One lookup on (kind, item, seq); cold-start gate: flat vs journal length §3, §16
P3 coalescing "Send the final state per field" replaces "read+unread cancel out" §8
P3 webhooks Payloads carry the full token; receivers dedupe by token §2, #918

Accepted risk (§3): after a snapshot rollback that only devices notice later, the folder/flag actions that were pending at snapshot time are replayed. That's seconds of Writer lag, and the effect can be undone. delete_forever is the exception: it shows as gone only after mail.applied, and restored refuses it. Sends are not in this risk; they are held.

Size: 391 lines (unchanged; the cap was ≤ 391).

v4.2 pushed (head bc1cd7bc). This is the mapping of second review 77555, plus 77558 on #918 and 77560 on #919. Every fix either removes machinery or narrows a rule. Decisions are kayg's ("start minimal"). Section numbers refer to `docs/plans/mail-architecture.md`. | # | Fix | Where | |---|---|---| | N-1 | The durable commit flag and group commit are **deleted** from #918 and the plan. The provider is the durable store: the device outbox clears an op only on `mail.applied`/`mail.refused`. An accepted entry lost to a power loss is replayed with the same op id, and that's harmless because the action only sets state. **Notes commit latency is unchanged**, since no mail fsync exists. The gate now uses a 10k-archive burst | #918, §3, §8, §16 | | N-2 | **Nothing sends on its own after uncertainty.** An overdue row is either found by `lookup_sent` (→ delivered) or held with "This mail was due at 10:42 and hasn't gone out. Send now?". `unknown` stays held. After a detected `restored`, rows scheduled for later are held for review too. §1, §6, §9 and §15 now say the same thing: a restore sends nothing | §1, §6, §9, §15, §17 | | N-3 | #919: `after: [own unconfirmed op ids]` plus `field_req`, so a device's own in-flight change never makes its next one `stale`. "Current" and "changed" include pending actions. Rebuilt rows get the head. The outbox merges only unsent ops. Tests added | #919, §2, §5, §8, §17 | | N-4 | #918: token = `epoch-seq-c-m` with a per-user keyed `m`. A bad `m` → `invalid token` with no rotation; another epoch → expired. Only a valid `m` against a missing or different entry, or the high-water file, rotates. Old tokens are accepted only while this boot's high-water check passed | #918, §2 | | N-5 | #918: an epoch mismatch counts as restored; an unreadable or torn file counts as missing. Rotation is a FULL commit plus a file fsync before any new-epoch token. `meta.highwater` keeps the first deploy from rotating anyone | #918 | | P3 topic index | `topic` column + `(topic, seq)` index; `catch_up` skips other topics | §2 | | P3 Writer start | One lookup on `(kind, item, seq)`; cold-start gate: flat vs journal length | §3, §16 | | P3 coalescing | "Send the final state per field" replaces "read+unread cancel out" | §8 | | P3 webhooks | Payloads carry the full token; receivers dedupe by token | §2, #918 | **Accepted risk (§3):** after a snapshot rollback that only devices notice later, the folder/flag actions that were pending at snapshot time are replayed. That's seconds of Writer lag, and the effect can be undone. `delete_forever` is the exception: it shows as gone only after `mail.applied`, and `restored` refuses it. Sends are not in this risk; they are held. Size: 391 lines (unchanged; the cap was ≤ 391).
Author
Owner

Third (final) review of v4.2 (head bc1cd7bc): plan + #918 rev 3 + #919 rev 3

I checked this against origin/dev 41f2efa3. journal already has at_ms, kind, item, installation, request_id, so c can be computed from existing columns. UserStore::position checks only epoch ≠ and seq > head. Cmd::Once is the only FULL commit on the shared writer. ensure_epoch mints the epoch once. The new token and rotation rules fit that code. They add one PK read in position and nothing on the commit path.

1. Round-2 and carried findings

# Status
N-1 durable group commit Fixed. Commit { durable } is gone from #918, §3, §8 and §16. Nothing new sits on the notes writer. The replay path it relies on has a gap, see F-1
N-2 sends after uncertainty Mostly fixed. §1, §6, §15 and the §17 drill say "a restore sends nothing". The §9 overdue row is still narrower (10-minute window), see F-2
N-3 own in-flight ops / merging Fixed in #919 and §8. after + field_req, pending counted, rebuilt rows take the head, only unsent ops merge. One test is missing from §17 (P3-2)
N-4 keyed token, narrow rotation Fixed. A bad m gives invalid token, another epoch gives expired, and only a valid m against a missing or different entry rotates. The plan §2 and #918 agree
N-5 high-water edges Fixed in #918 (a), (b), (c), (d). (b) leaves one gap: the periodic write has no fsync, see F-1
P1-1, P1-3, P2-5, P2-6 (round 1) Closed through N-4/N-5, N-3, N-1 and N-2 above. The F-1 and F-2 notes apply
Round-2 P3s (topic index, Writer start, final-state coalescing, webhook dedupe by token) Fixed. Cost of the indexes: P3-1

2. New findings

No P1. The structure holds: one executor, one log, one route, derived ids, rebuildable caches. Each item below is a rule change of a line or two. None needs new machinery.

F-1 (P2) · After a power loss, the N-1 replay never applies, so the person's last actions are dropped (#918 §2–3, #919 "older epoch", plan §3).
Scenario: archive at seq 70 is accepted. The power fails before the Writer applies it. The WAL tail is lost, so head is 65. The phone reconnects with token …-70 and a valid m, and position proves a rollback and rotates. That's correct. The outbox then replays the archive with the same op id, but its base is from the old epoch. #919 counts that as "changed", and current (Inbox) ≠ requested, so it returns stale. The person sees "…changed somewhere else" about their own archive, and the archive is gone. Entries that survived the tail loss but were still pending go to mail.refused {restored} without words, the device clears them, and the thread drops back into Inbox silently. A second trigger: the 5-second high-water write is write + rename with no fsync. On XFS/btrfs a power loss can leave it zero-length, which reads as "missing + flag", so restored fires. That drops pending actions and holds every scheduled send for review even when no entry was lost.
Fix (no new machinery):

  • (a) refused {restored} and a stale that comes only from an older-epoch base don't clear the outbox. After re-reading, the device re-stamps those unconfirmed ops with the new token and replays them. These are the person's own unconfirmed intents (folder/flag), which is the shape of the accepted risk. Server-side pending is still dropped, so "a restore moves nothing" holds for the server. delete_forever is still refused with words and never replayed.
  • (b) The high-water write does fsync(file) before the rename, at most once per 5 s and only when head moved. That's off the writer thread and away from notes. A torn file then means a real rollback.
  • Add a restore_drill case: WAL truncated with an archive pending. It must end archived, with no words.

F-2 (P2) · The 10-minute overdue threshold lets a restore or snapshot rollback send a mail twice (§9 overdue row vs §6/§15).

  • Detected restore: §9 holds only rows due more than 10 min ago and "rows scheduled for later". A row released at 10:00:05, delivered, then restored at 10:05 from a 09:59:55 backup is neither. It goes down the normal path and is sent again. That contradicts §6 ("every unsent row… is held").
  • Undetected snapshot rollback: the high-water file rolls back too, so no restored fires at open. The same 10-minute window sends a second copy before any device notices. Mapping 77568 says "sends are not in this risk; they are held", and for this window that's not true.
    Fix: at every start, any non-final row with release_ms ≤ now gets lookup_sent: found → delivered, else held with "Send now?". There's no threshold. Rows scheduled for later stay scheduled unless restored fired. Optional: a clean_stop row written at graceful shutdown and deleted at start, so a normal deploy doesn't hold a mail whose Undo window just passed. A live snapshot or a power loss never carries that row. Ask kayg to accept the residual explicitly: after an undetected rollback, a scheduled mail cancelled in the lost future still goes out at its time. There's no witness outside the snapshot, and this is a send, so it falls outside the stated accepted risk.

F-3 (P2) · Send accept isn't durable, but both docs act as if it were (§5 "one FULL-sync write is data_started", §9 Accept, proxy N-6 "answers 250 once outgoing is durable").
The outgoing + outgoing_rcpt insert is a NORMAL commit in state.db. Scenario: Apple Mail submits, the proxy answers 250, Apple Mail deletes its Outbox copy, and the power fails 1 s later. The row is gone and the mail is lost, with no failure line anywhere. The same thing happens for a device send if the outbox clears on accept. The plan doesn't say when a device clears a mail.send. If it clears only on a final send_state instead, a restore plus the outbox replay creates a new row (the dedupe row is gone) and sends a mail that may already have been delivered. Fix: make the outgoing insert a FULL commit in state.db. That's one fsync per send, on its own file, and never on the notes writer. Then state: "the device outbox and the proxy clear a send on accept, and a send is never replayed". Add a send_state_machine case: power cut right after accept, then the mail is delivered exactly once.

3. P3 (one line each)

  1. The (topic, seq) and (kind, item, seq) indexes add two B-tree inserts to every notes journal commit and need a migration over a journal that is never pruned. Make the second one partial (WHERE topic = 'mail'), and put notes commit p99 and migration time at 1M entries in the P0b gate.
  2. #919: after a cache rebuild, every value-changing queued offline action returns stale (safe, but say so in §15). Field seqs stamped before a rotation (cache.db survives a power-loss rotation) should count as "head at rotation". §17 stale_base is missing #919's "rebuild, then a late retry after a pre-rebuild change → stale".
  3. The plan's status line still says "v4.1 (v4 review 77534 folded in)".
  4. Proxy stub, row N-7, still says "after a mail.db rebuild (new epoch)". That's a rev-3 leftover; it should be cache.db rebuild / mail.reset.
  5. §4 rule 2: say how an id is computed for a new message that arrives on a pkey-scheme account while the provider has no stable ids, so that its id doesn't change when pkey comes back.

4. Verdict: ready for owner approval (with F-1…F-3 folded in as text)

This round found no P1. The three P2s are edge rules in paths that already exist: a replay rule after rotation, the overdue threshold, and one FULL commit on state.db. Each is a line or two in §3/§9/#918, adds no tables, queues or epochs, and puts nothing on the notes writer. The main decisions are sound: mail rides the executor and the one save log, ids are derived, caches are never backed up, the Writer position lives in the log, and tokens prove their entry. They removed the bug class that rounds 1–3 kept hitting, and v4.2 now matches the owner's stance everywhere except F-2. Notes perf is protected: there's no new fsync on the shared writer, mail is on its own topic, hints are capped per user, and the gates are "flat vs dev". The only thing needing kayg's decision is the F-2 residual (an undetected rollback plus a cancelled scheduled send). Everything else is author follow-up, not a reason to rethink.

P1: 0 · P2: 3 · P3: 5

## Third (final) review of v4.2 (head bc1cd7bc): plan + #918 rev 3 + #919 rev 3 I checked this against `origin/dev` 41f2efa3. `journal` already has `at_ms, kind, item, installation, request_id`, so `c` can be computed from existing columns. `UserStore::position` checks only `epoch ≠` and `seq > head`. `Cmd::Once` is the only FULL commit on the shared writer. `ensure_epoch` mints the epoch once. The new token and rotation rules fit that code. They add one PK read in `position` and nothing on the commit path. ### 1. Round-2 and carried findings | # | Status | |---|---| | N-1 durable group commit | **Fixed.** `Commit { durable }` is gone from #918, §3, §8 and §16. Nothing new sits on the notes writer. The replay path it relies on has a gap, see F-1 | | N-2 sends after uncertainty | **Mostly fixed.** §1, §6, §15 and the §17 drill say "a restore sends nothing". The §9 overdue row is still narrower (10-minute window), see F-2 | | N-3 own in-flight ops / merging | **Fixed** in #919 and §8. `after` + `field_req`, pending counted, rebuilt rows take the head, only unsent ops merge. One test is missing from §17 (P3-2) | | N-4 keyed token, narrow rotation | **Fixed.** A bad `m` gives `invalid token`, another epoch gives expired, and only a valid `m` against a missing or different entry rotates. The plan §2 and #918 agree | | N-5 high-water edges | **Fixed** in #918 (a), (b), (c), (d). (b) leaves one gap: the periodic write has no fsync, see F-1 | | P1-1, P1-3, P2-5, P2-6 (round 1) | Closed through N-4/N-5, N-3, N-1 and N-2 above. The F-1 and F-2 notes apply | | Round-2 P3s (topic index, Writer start, final-state coalescing, webhook dedupe by token) | Fixed. Cost of the indexes: P3-1 | ### 2. New findings No P1. The structure holds: one executor, one log, one route, derived ids, rebuildable caches. Each item below is a rule change of a line or two. None needs new machinery. **F-1 (P2) · After a power loss, the N-1 replay never applies, so the person's last actions are dropped (#918 §2–3, #919 "older epoch", plan §3).** Scenario: archive at seq 70 is accepted. The power fails before the Writer applies it. The WAL tail is lost, so head is 65. The phone reconnects with token `…-70` and a valid `m`, and `position` proves a rollback and rotates. That's correct. The outbox then replays the archive with the same op id, but its `base` is from the old epoch. #919 counts that as "changed", and current (Inbox) ≠ requested, so it returns `stale`. The person sees "…changed somewhere else" about their own archive, and the archive is gone. Entries that survived the tail loss but were still pending go to `mail.refused {restored}` *without words*, the device clears them, and the thread drops back into Inbox silently. A second trigger: the 5-second high-water write is write + rename with no fsync. On XFS/btrfs a power loss can leave it zero-length, which reads as "missing + flag", so `restored` fires. That drops pending actions and holds every scheduled send for review even when no entry was lost. **Fix (no new machinery):** - (a) `refused {restored}` and a `stale` that comes *only* from an older-epoch base don't clear the outbox. After re-reading, the device re-stamps those unconfirmed ops with the new token and replays them. These are the person's own unconfirmed intents (folder/flag), which is the shape of the accepted risk. Server-side pending is still dropped, so "a restore moves nothing" holds for the server. `delete_forever` is still refused with words and never replayed. - (b) The high-water write does `fsync(file)` before the rename, at most once per 5 s and only when head moved. That's off the writer thread and away from notes. A torn file then means a real rollback. - Add a `restore_drill` case: WAL truncated with an archive pending. It must end archived, with no words. **F-2 (P2) · The 10-minute overdue threshold lets a restore or snapshot rollback send a mail twice (§9 overdue row vs §6/§15).** - *Detected restore:* §9 holds only rows due more than 10 min ago and "rows scheduled for later". A row released at 10:00:05, delivered, then restored at 10:05 from a 09:59:55 backup is neither. It goes down the normal path and is **sent again**. That contradicts §6 ("every unsent row… is held"). - *Undetected snapshot rollback:* the high-water file rolls back too, so no `restored` fires at open. The same 10-minute window sends a second copy before any device notices. Mapping 77568 says "sends are not in this risk; they are held", and for this window that's not true. **Fix:** at every start, any non-final row with `release_ms ≤ now` gets `lookup_sent`: found → `delivered`, else held with "Send now?". There's no threshold. Rows scheduled for later stay scheduled unless `restored` fired. Optional: a `clean_stop` row written at graceful shutdown and deleted at start, so a normal deploy doesn't hold a mail whose Undo window just passed. A live snapshot or a power loss never carries that row. **Ask kayg to accept the residual explicitly:** after an *undetected* rollback, a scheduled mail cancelled in the lost future still goes out at its time. There's no witness outside the snapshot, and this is a send, so it falls outside the stated accepted risk. **F-3 (P2) · Send accept isn't durable, but both docs act as if it were (§5 "one FULL-sync write is `data_started`", §9 Accept, proxy N-6 "answers `250` once `outgoing` is durable").** The `outgoing` + `outgoing_rcpt` insert is a NORMAL commit in `state.db`. Scenario: Apple Mail submits, the proxy answers `250`, Apple Mail deletes its Outbox copy, and the power fails 1 s later. The row is gone and **the mail is lost**, with no failure line anywhere. The same thing happens for a device send if the outbox clears on accept. The plan doesn't say when a device clears a `mail.send`. If it clears only on a final `send_state` instead, a restore plus the outbox replay creates a new row (the dedupe row is gone) and sends a mail that may already have been delivered. **Fix:** make the `outgoing` insert a FULL commit in `state.db`. That's one fsync per send, on its own file, and never on the notes writer. Then state: "the device outbox and the proxy clear a send on accept, and a send is never replayed". Add a `send_state_machine` case: power cut right after accept, then the mail is delivered exactly once. ### 3. P3 (one line each) 1. The `(topic, seq)` and `(kind, item, seq)` indexes add two B-tree inserts to every **notes** journal commit and need a migration over a journal that is never pruned. Make the second one partial (`WHERE topic = 'mail'`), and put notes commit p99 and migration time at 1M entries in the P0b gate. 2. #919: after a cache rebuild, every *value-changing* queued offline action returns `stale` (safe, but say so in §15). Field seqs stamped before a rotation (`cache.db` survives a power-loss rotation) should count as "head at rotation". §17 `stale_base` is missing #919's "rebuild, then a late retry after a pre-rebuild change → `stale`". 3. The plan's status line still says "v4.1 (v4 review 77534 folded in)". 4. Proxy stub, row N-7, still says "after a `mail.db` rebuild (new epoch)". That's a rev-3 leftover; it should be `cache.db` rebuild / `mail.reset`. 5. §4 rule 2: say how an id is computed for a *new* message that arrives on a `pkey`-scheme account while the provider has no stable ids, so that its id doesn't change when `pkey` comes back. ### 4. Verdict: **ready for owner approval** (with F-1…F-3 folded in as text) This round found no P1. The three P2s are edge rules in paths that already exist: a replay rule after rotation, the overdue threshold, and one FULL commit on `state.db`. Each is a line or two in §3/§9/#918, adds no tables, queues or epochs, and puts nothing on the notes writer. The main decisions are sound: mail rides the executor and the one save log, ids are derived, caches are never backed up, the Writer position lives in the log, and tokens prove their entry. They removed the bug class that rounds 1–3 kept hitting, and v4.2 now matches the owner's stance everywhere except F-2. Notes perf is protected: there's no new fsync on the shared writer, mail is on its own topic, hints are capped per user, and the gates are "flat vs dev". The only thing needing kayg's decision is the F-2 residual (an undetected rollback plus a cancelled scheduled send). Everything else is author follow-up, not a reason to rethink. P1: 0 · P2: 3 · P3: 5
Author
Owner

v4.3 pushed (head a8f2649c). Mapping of final review 77574. Nothing new: no tables, queues or epochs were added, and the notes writer is untouched. Section numbers refer to docs/plans/mail-architecture.md.

# Fix Where
F-1 Devices don't clear unconfirmed ops on refused {restored} or on a stale caused only by an older-epoch base. After re-reading, they re-stamp those ops with the new token and replay them, so a power loss never drops the person's last archive. The server still drops its own pending work. delete_forever is refused with words and never replayed. The high-water temp file is fsynced before its rename (at most every 5 s, only when the head moved, off the writer thread). New drill case: WAL truncated with an archive pending ends archived, with no words §2, §3, §17, #918, #919
F-2 No threshold: at every start, any due, unfinished row gets lookup_sent and is either delivered or held with "Send now?". Rows scheduled for later stay scheduled unless restored fired. Needs kayg's acceptance (now a row in the §9 table): after an undetected rollback, a scheduled mail cancelled in the lost window still goes out at its time §9
F-3 The outgoing + outgoing_rcpt insert is a FULL commit in state.db (its own file, never on the notes writer). The device outbox and the proxy clear a send on accept and never replay it. New send_state_machine case: power cut right after accept → delivered exactly once. The proxy stub says 250 comes after that commit §5, §9, §17, proxy stub
P3-1 The Writer's (kind, item, seq) index is partial (WHERE topic = 'mail'). Notes commit p99 with the indexes, and migration time at 1M journal entries, are in the P0b gate §2, §16
P3-2 §15 says a cache rebuild makes value-changing queued actions stale (safe). Seqs stamped before a rotation count as "head at rotation" (#919). The stale_base test "rebuild, then a late retry after a pre-rebuild change → stale" was added §15, §17, #919
P3-3 Status line updated (v4.3) top
P3-4 Proxy stub N-7: "cache.db rebuild (mail.reset) or a save-log epoch rotation" proxy stub
P3-5 §4 rule 2: a new message on a pkey-scheme account during a stable-id outage gets blake3-128(akey ‖ fp ‖ n). It keeps that id when pkey returns: it's found by placement/fp, and a rebuild reads it from the mirror file name with the same content hash §4

Size: 391 lines (cap ≤ 391). Ready for kayg: the plan's approval plus the one F-2 residual.

v4.3 pushed (head a8f2649c). Mapping of final review 77574. Nothing new: no tables, queues or epochs were added, and the notes writer is untouched. Section numbers refer to `docs/plans/mail-architecture.md`. | # | Fix | Where | |---|---|---| | F-1 | Devices don't clear unconfirmed ops on `refused {restored}` or on a `stale` caused only by an older-epoch base. After re-reading, they re-stamp those ops with the new token and replay them, so a power loss never drops the person's last archive. The server still drops its own pending work. `delete_forever` is refused with words and never replayed. The high-water temp file is fsynced before its rename (at most every 5 s, only when the head moved, off the writer thread). New drill case: WAL truncated with an archive pending ends archived, with no words | §2, §3, §17, #918, #919 | | F-2 | No threshold: at every start, any due, unfinished row gets `lookup_sent` and is either `delivered` or held with "Send now?". Rows scheduled for later stay scheduled unless `restored` fired. **Needs kayg's acceptance** (now a row in the §9 table): after an *undetected* rollback, a scheduled mail cancelled in the lost window still goes out at its time | §9 | | F-3 | The `outgoing` + `outgoing_rcpt` insert is a **FULL commit in `state.db`** (its own file, never on the notes writer). The device outbox and the proxy clear a send on accept and never replay it. New `send_state_machine` case: power cut right after accept → delivered exactly once. The proxy stub says `250` comes after that commit | §5, §9, §17, proxy stub | | P3-1 | The Writer's `(kind, item, seq)` index is partial (`WHERE topic = 'mail'`). Notes commit p99 with the indexes, and migration time at 1M journal entries, are in the P0b gate | §2, §16 | | P3-2 | §15 says a cache rebuild makes value-changing queued actions `stale` (safe). Seqs stamped before a rotation count as "head at rotation" (#919). The `stale_base` test "rebuild, then a late retry after a pre-rebuild change → `stale`" was added | §15, §17, #919 | | P3-3 | Status line updated (v4.3) | top | | P3-4 | Proxy stub N-7: "`cache.db` rebuild (`mail.reset`) or a save-log epoch rotation" | proxy stub | | P3-5 | §4 rule 2: a new message on a `pkey`-scheme account during a stable-id outage gets `blake3-128(akey ‖ fp ‖ n)`. It keeps that id when `pkey` returns: it's found by placement/`fp`, and a rebuild reads it from the mirror file name with the same content hash | §4 | Size: 391 lines (cap ≤ 391). Ready for kayg: the plan's approval plus the one F-2 residual.
Author
Owner

kayg approved this plan on 2026-11-04 ("as long as it meets the foolproof, resilient, reliable and extremely performant milestone, approved"), and accepted the §9 leftover case (a scheduled mail cancelled in the window lost to an undetected rollback still goes out).

kayg approved this plan on 2026-11-04 ("as long as it meets the foolproof, resilient, reliable and extremely performant milestone, approved"), and accepted the §9 leftover case (a scheduled mail cancelled in the window lost to an undetected rollback still goes out).
Author
Owner

Closing: head a8f2649c is already in dev (reached via 6be86ba0); nothing left to merge. Branch kept.

Closing: head a8f2649c is already in dev (reached via 6be86ba0); nothing left to merge. Branch kept.
kayg closed this pull request 2026-11-04 13:05:04 +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!920
No description provided.