plan: Mail architecture v4 (simplified) #920
Closed
kayg
wants to merge 0 commits from
plan/mail-architecture-v4 into dev
pull from: plan/mail-architecture-v4
merge into: kayg:dev
kayg:main
kayg:port/tasks-float-2
kayg:fix/train-1116-2
kayg:fix/train-1116-3
kayg:fix/train-1116-1
kayg:fix/flake-1134
kayg:fix/server-1182
kayg:dev
kayg:port/notes-float-3c
kayg:docs/auto-update-ig
kayg:feat/dav-transport
kayg:port/tasks-float-1
kayg:wip/mail1011-sv-order-1116
kayg:fix/flake-1179
kayg:fix/flake-1178
kayg:fix/guards-1153-fsio-split
kayg:fix/guards-1153-notes-split-we
kayg:fix/guards-1153-notes-lib
kayg:fix/guards-1153-notes-home
kayg:fix/guards-1153-ui-primitives
kayg:fix/guards-1153-primitives-e2e
kayg:fix/guards-1153-visibility-doc
kayg:feat/paper-grey-1116
kayg:fix/flake-1165
kayg:fix/flake-1119
kayg:docs/imap-766-plan-v2
kayg:fix/e2e-unique-ports
kayg:t3/paged-search-reconcile-final
kayg:wip/mail1011-final-1115
kayg:docs/tasks-float-port
kayg:perf/editor-first-paint-1c
kayg:feat/imap-notes-fetch
kayg:feat/imap-notes-projection
kayg:feat/imap-notes-readonly
kayg:feat/imap-notes-auth
kayg:feat/imap-notes-server-foundation
kayg:wip/mail1011-txn-ownvocab-1115
kayg:wip/mail1011-txn-novocab-1115
kayg:perf/p1117-final-harness
kayg:perf/single-shot-repeats
kayg:port/tasks-matrix
kayg:wip/mail1011-txn-1115
kayg:fix/static-gates-1155
kayg:feat/files-s1-identity-r7
kayg:fix/files-r7-idle-loop
kayg:fix/daily-train-1152
kayg:port/notes-float
kayg:fix/editor-tables-test-types
kayg:port/notes-float-listscript
kayg:feat/tasks-actions
kayg:port/notes-float-phone-preload
kayg:perf/sound-comparator
kayg:port/notes-float-listscroll
kayg:port/notes-float-budgets
kayg:port/notes-float-suite-fix-b
kayg:port/notes-float-sidebar-fix
kayg:port/notes-float-trim
kayg:port/notes-float-3-lists
kayg:fix/attachments-meta-capability
kayg:docs/carddav-writes-v2-plan
kayg:feat/contacts-companion-pure
kayg:issue/carddav-read-perf-fix-r2
kayg:issue/carddav-read-r2
kayg:port/notes-float-devsync2
kayg:review/calendar-2
kayg:review/switcher-a-pills
kayg:port/notes-float-switcher-a
kayg:port/port-tables-2
kayg:review/switcher-ends
kayg:wip/whiteboard-s1-1114
kayg:port/port-tables
kayg:wip/mail1011-perfneutral
kayg:review/photo-tint
kayg:port/notes-float-shell
kayg:wip/local/collections-db
kayg:wip/local/mail-p1
kayg:wip/local/cold-growth-on-tiering
kayg:wip/local/tiering-v3-s1
kayg:wip/local/wal1051-cap
kayg:wip/local/tiering-v3-s1-resume
kayg:wip/local/index-position-startup-scan
kayg:port/notes-float-flat
kayg:port/notes-float-promote
kayg:wip/handover/mail1011-candidate
kayg:wip/handover/files-s1-candidate
kayg:port/notes-float-shell-only
kayg:port/notes-float-perf
kayg:feat/whiteboard-s1
kayg:feat/tiering-v5
kayg:fix/app-switch-hitch
kayg:wip/local/files-s1-dev-v4-final
kayg:feat/files-s1-dev-v4
kayg:fix/c2-glass-shared
kayg:feat/flat-lists
kayg:wip/handover/whiteboard-s1-resume
kayg:wip/att-lazy-861
kayg:feat/switcher-browse
kayg:wip/att-lazy-860
kayg:feat/tasks-float
kayg:recovered/flat-backup-candidate
kayg:perf/stalls-1054-kc
kayg:land/ai-toolbar
kayg:feat/collections-db
kayg:feat/collections-db-fixes
kayg:codex/mail-1011-redesign-20261111
kayg:fix/ai-toolbar
kayg:backup/macos-vm/st3-head
kayg:perf/trim-candidate-phonestack
kayg:feat/switcher-three
kayg:fix/1051-index-idle-checkpoint
kayg:perf/stalls-1054-kb
kayg:perf/stalls-1054-k
kayg:perf/stalls-1054-r3
kayg:fix/c2-contrast-tail
kayg:perf/stalls-1054-r3-preview
kayg:feat/collections-before
kayg:feat/tiering-v4
kayg:fix/timelog-caret
kayg:wip/local/tasks-actions
kayg:docs/tasks-writes-v2-plan
kayg:st3-r3
kayg:feat/pass8
kayg:review/calendar-2-before-1111
kayg:wip/tiering-v3-cold4
kayg:perf/stalls-1054-r2
kayg:fix/suite-A4
kayg:fix/suite-A5-probe
kayg:fix/suite-A6
kayg:fix/suite-A3
kayg:fix/suite-A2
kayg:fix/suite-A5
kayg:fix/suite-A1
kayg:wip/local/attachments-861-fix
kayg:feat/contrast
kayg:wip/local/ports-861
kayg:storage/wal-checkpoint-off-save-1051
kayg:wip/local/mail-1011-reconcile-20261110
kayg:feat/style-sheet-fixes
kayg:feat/money-round
kayg:perf/stalls-1054
kayg:wip/tiering-v3-cold5
kayg:t3/mail-1011-liveness
kayg:feat/iphone-fixes
kayg:feat/notes-approve
kayg:wip/local/shrow-work
kayg:feat/files-s1-identity
kayg:feat/quickfix
kayg:wip/tiering-v3-cold
kayg:wip/local/shared-row-swipes
kayg:backup/macos-vm/pfx-B
kayg:backup/macos-vm/pfx-C
kayg:backup/macos-vm/pfx-D
kayg:feat/contrast-r1
kayg:feat/tiering-v3-s2-tags
kayg:feat/folder-drop
kayg:t3/photos-s1
kayg:feat/tiering-v3-s1-namespace
kayg:wip/local/photos-s1
kayg:t3/photos-plan-slice-one
kayg:recovered/backup/p1b-61505
kayg:t3/paged-search-reconcile
kayg:t3/smooth-pane-transitions
kayg:t3/index-position-startup-scan
kayg:fix/private-staging-759b-r2
kayg:backup/macos-vm/hk/hk1009/pr877
kayg:backup/macos-vm/hk/hk1009/pr878
kayg:docs/undo-block-ids-plan
kayg:fix/undo-768
kayg:backup/macos-vm/hk/hk1009/pr875
kayg:backup/macos-vm/hk/hk1009/pr904
kayg:proto/block-identity-v7d
kayg:backup/macos-vm/hk/hk1009/pr846
kayg:backup/macos-vm/hk/hk1009/pr860
kayg:backup/macos-vm/hk/hk1009/pr861
kayg:backup/macos-vm/hk/hk1009/pr849
kayg:backup/macos-vm/hk/hk1009/pr848
kayg:backup/macos-vm/hk/hk1009/pr853
kayg:backup/macos-vm/hk/hk1009/pr957
kayg:backup/macos-vm/hk/hk1009/pr893
kayg:backup/macos-vm/hk/hk1009/pr889
kayg:backup/macos-vm/hk/hk1009/pr902
kayg:docs/imap-notes-plan
kayg:docs/quota-plan-2
kayg:fix/parallel-test-flakes
kayg:docs/calendar-backend-v2-plan
kayg:feat/calendar-ical-converter
kayg:backup/macos-vm/hk/hk1009/pr808
kayg:docs/contacts-import-v2-plan
kayg:issue/610-pm-midnight
kayg:feat/calendar-v2-s1-containment
kayg:backup/macos-vm/hk/hk1009/pr854
kayg:backup/macos-vm/hk/hk1009/pr845
kayg:backup/macos-vm/hk/hk1009/pr917
kayg:docs/dav-recorder-v2-plan
kayg:plan/previews-865
kayg:plan/save-log-durable-entry
kayg:backup/macos-vm/hk/hk1009/pr934
kayg:fix/e2e-data-on-ram
kayg:backup/macos-vm/hk/hk1009/pr888
kayg:feat/appwindow3
kayg:feat/appwindow2
kayg:feat/appwindow
kayg:feat/money-p1
kayg:feat/keys-sheet
kayg:review/calendar-2-themes
kayg:feat/smooth-cursor
kayg:fix/float-style
kayg:review/calendar-2-float
kayg:release/2026-11-06-hotfix
kayg:archive/port/rows-drop-code
kayg:archive/port/rows-actions
kayg:archive/port/rows
kayg:scratch/tasks-894-ui-gates
kayg:review/calendar-2-night-wip
kayg:recovered/flaky/toast-reduced
kayg:release/2026-11-05
kayg:archive/flaky/rows-drop-fixed
kayg:archive/flaky/rows-actions
kayg:archive/flaky/rows
kayg:sim/bm15-final
kayg:sim/bm15-bis-932
kayg:sim/bm15-bis-909
kayg:sim/bm15
kayg:sim/bm15-bis-887
kayg:perf/tiering-option-b
kayg:fix/sw-lazy-precache
kayg:archive/plan/save-log-durable-entry
kayg:mock/money-fix2
kayg:archive/fix/e2e-data-on-ram
kayg:mock/appearance-all
kayg:mock/pill-press
kayg:mock/pill-press-mac
kayg:backup/macos-vm/appearance-after
kayg:mock/auto-swipes
kayg:mock/mail-actions
kayg:backup/macos-vm/mock/mail-actions
kayg:mock/money-static
kayg:archive/review/standards-917
kayg:perf/tiering-761-fix
kayg:mock/type-audit
kayg:mock/third-pane
kayg:feat/contacts-import-v2-s1
kayg:perf/executor-hot-path
kayg:archive/port/hidden-blocks
kayg:archive/port/devices
kayg:scratch/executor-on-894
kayg:scratch/executor-spans2
kayg:scratch/executor-spans
kayg:archive/port/rows-drop
kayg:feat/tiering-761-d-scale
kayg:feat/tiering-761-c-index
kayg:feat/tiering-761-b-reader
kayg:archive/review/sharing-pr3-review-9fec3d1f
kayg:perf/ports-lazy-budgets
kayg:feat/tiering-761-a-migration
kayg:archive/review/sharing-pr3-review
kayg:archive/review/sharing-pr3-review-code
kayg:archive/plan/previews-865
kayg:archive/port/port-attachments-3
kayg:archive/port/contacts-merge
kayg:fix/motion-audit-859
kayg:fix/motion-audit-859-mac
kayg:archive/port/port-pickers
kayg:archive/port/port-tables-2
kayg:archive/port/port-tables
kayg:recovered/local/sharing-s1-pr2-room-snapshot-candidate
kayg:archive/fix/parallel-test-flakes-code-minipc01
kayg:docs/imap-766-readonly-slice
kayg:feat/dav-recorder-v3
kayg:research/788-diagnosis
kayg:archive/fix/parallel-test-flakes
kayg:archive/perf/pr792-cold-index-edit
kayg:docs/sharing-slice-1
kayg:recovered/feat/dav-recorder-v2
kayg:recovered/feat/dav-recorder-v2-edd7bbb
kayg:spike/imap-766-s0-cases
kayg:archive/fix/undo-768
kayg:recovered/feat/dav-recorder
kayg:recovered/feat/dav-recorder-901acd4
kayg:feat/contacts-import
kayg:perf/cold-growth-on-764
kayg:perf/cold-growth-on-tiering
kayg:recovered/feat/tasks-set-status
kayg:feat/tasks-move-reorder
kayg:feat/tasks-delete-promote-duplicate
kayg:feat/carddav-writes
kayg:perf/quota-on-tiering
kayg:perf/quota-simple
kayg:perf/cold-growth-on-quota-stack
kayg:recovered/perf/cold-growth-on-tiering
kayg:feat/calendar-identity
kayg:feat/calendar-event-parser
kayg:feat/calendar-props-maps
kayg:port/glass-when-ring
kayg:recovered/feat/tiering-761-s1-wip-8132a84
kayg:recovered/feat/tiering-761-s1-wip-9da4094
kayg:recovered/feat/tiering-761-s1-wip-724512c
kayg:recovered/feat/tiering-761-s1-wip-66e667e
kayg:recovered/feat/tiering-761-s1
kayg:wip/6by32-01-tier-761-s1-pause-20261030
kayg:spike/imap-766-s0
kayg:wip/6by32-02-calternal-pause-20261030
kayg:wip/8by64-01-review-688-pause-20261030
kayg:wip/6by32-01-verify-744-pause-20261030
kayg:wip/6by32-01-verify-742-pause-20261030
kayg:fix/private-staging-759b
kayg:wip/6by32-01-review-748-pause-20261030
kayg:wip/6by32-01-review-733c-pause-20261030
kayg:wip/6by32-01-review-733b-pause-20261030
kayg:review/calendar-month
kayg:wip/local/bm15-trash
kayg:plan/759b-staging
kayg:review/767b-tests
kayg:review/preview-2026-10-29
kayg:docs/tiering-731-plan
kayg:wip/c6b02-review-733d
kayg:wip/c6b02-bm1-full-a
kayg:docs/deploy-plan
kayg:fix/storage-owner-liveness-642
kayg:fix/storage-fix-7
kayg:feat/tiering-731
kayg:wip/tiering-731-first-attempt
kayg:perf/idle-honest-2
kayg:fix/storage-private-tmp-642-dev
kayg:fix/storage-exact-file-quarantine-642
kayg:perf/one-flush-save
kayg:review/calendar-static
kayg:review/indexing-ring
kayg:review/when-field-2
kayg:proto/block-identity-2-review
kayg:proto/block-identity-review
kayg:review/when-field
kayg:issue/tasks-create-ids
kayg:issue/tasks-create
kayg:review/combined
kayg:review/task-polish
kayg:review/top-buttons
kayg:review/q1-q5
kayg:archive/integ325-293
kayg:archive/integ325-ci
kayg:issue/calendar-adr
kayg:archive/old/train/2026-10-23bk2
kayg:archive/old/train/2026-10-23bk
kayg:issue/469-mockup-9a
kayg:issue/smart-tasks-mockup
kayg:issue/469-menus
kayg:issue/652-signout-flake
kayg:issue/652-history-fix7
kayg:issue/652-history-fix6
kayg:archive/old/issue/spring-check-perf
kayg:issue/spring-check-perf
kayg:issue/659-rename-fast
kayg:archive/old/train/2026-10-21ar
kayg:issue/search-hardening-3
kayg:issue/652-history-fix5
kayg:issue/660-port-sheets-glass
kayg:issue/652-history-fix4
kayg:issue/652-history-fix3
kayg:issue/652-history-fix2
kayg:issue/652-history-flake
kayg:train/2026-10-21an
kayg:issue/settings-admin-port
kayg:issue/search-port
kayg:train/2026-10-20am
kayg:issue/storage-split-fix2
kayg:issue/storage-split
kayg:archive/old/issue/folder-ids-fix
kayg:train/2026-10-20al
kayg:archive/old/issue/folder-ids
kayg:train/2026-10-20ak
kayg:issue/tables-mockup
kayg:train/2026-10-19aj
kayg:train/2026-10-19ai
kayg:issue/469-merge-fixes
kayg:issue/sidebar-band
kayg:archive/old/issue/608-settings-spec
kayg:train/2026-10-19ah
kayg:issue/swipe-offscreen
kayg:train/2026-10-19ag
kayg:archive/old/issue/590-nlp-adr
kayg:archive/old/issue/587-event-after-write-2
kayg:train/2026-10-19af
kayg:archive/old/issue/587-event-after-write
kayg:issue/469-pill-room-c
kayg:issue/469-pill-room
kayg:train/2026-10-19ae
kayg:issue/469-narrow-handle
kayg:issue/397-ios-swipe-2
kayg:issue/469-desk-fixes
kayg:archive/old/issue/auto-update-adr
kayg:issue/469-filter-gap
kayg:issue/469-port-1b
kayg:issue/442-opacity-flake
kayg:issue/327-web-fast-3
kayg:archive/old/issue/469-port-1
kayg:issue/469-port-1
kayg:issue/327-web-fast-2
kayg:archive/old/issue/327-web-fast
kayg:archive/old/issue/425-stt-bench-vq1
kayg:archive/old/issue/445-no-bleed
kayg:archive/old/issue/400-swipe-mockup-2
kayg:issue/426-client-review
kayg:issue/426-client-2
kayg:issue/426-client
kayg:archive/old/issue/476-safe-area-lab
kayg:archive/old/issue/445-top-light
kayg:issue/471-blocks-mockup
kayg:archive/old/issue/448-links-app-2
kayg:archive/old/issue/448-links-app
kayg:archive/old/issue/398-cold-links
kayg:issue/434-442-small-2
kayg:issue/434-442-small
kayg:archive/old/issue/398-unload
kayg:archive/old/issue/445-bottom-band
kayg:issue/445-bottom-band
kayg:issue/351-rem-3
kayg:issue/351-rem-2
kayg:issue/351-rem
kayg:archive/old/issue/327-first-note
kayg:issue/395-width-phone
kayg:archive/old/issue/327-typing
kayg:issue/396-ios-edges
kayg:issue/397-ios-swipe
kayg:archive/old/issue/327-notes-index
kayg:issue/345-347-contrast-empty-2
kayg:archive/old/issue/44-arenas
kayg:issue/44-arenas
kayg:archive/integ325
kayg:archive/old/issue/327-perf-harness
kayg:archive/old/issue/44-thp
kayg:issue/44-thp
kayg:archive/old/issue/285-sticky-pills
kayg:archive/old/issue/44-trim-3
kayg:issue/44-trim-3
kayg:archive/old/issue/165-cards
kayg:archive/old/issue/165-picker-2
kayg:archive/old/issue/212-multi-select
No reviewers
Labels
Milestone
Clear milestone
No items
No milestone
Projects
Clear projects
No items
No project
Assignees
Clear assignees
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
Loading…
Reference in a new issue
No description provided.
Delete branch "plan/mail-architecture-v4"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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:
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 restoredindex.dbkeeps 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).cache.db,bodies.db, images and search are rebuildable and never backed up. A rebuild is an ordinarymail.resetresync. Ids are derived, so there is noid_mapto keep.state.dbholds only credentials, settings and outgoing mail.data_startedwritten after354. 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 checksmail-send0.7 against these rules; if it fails any of them, we write a minimal in-house client.akeyis fixed when the account is created and includes the host.msg idhashes the provider key together with the fingerprint.UNIQUE(account, message_id, rcpt_hash)andmail.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.md666 → 380 lines.🤖 Generated with Claude Code
Review of v4 (head
4355db68): plan + #918 + #919I 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: i64on 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:
index.db, shared with notes. No group commit. Queue of 64.synchronous=NORMAL. Onlycommit_onceuses FULL.seqisAUTOINCREMENT, so a rolled-back tail gives the same seq numbers out again.position()only rejectsepoch ≠orseq > head.catch_upsends every entry in order, in pages of 1000, beforeready. 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:
storage.mdrecommends "a coordinated filesystem snapshot", and on Proxmox the secrets root rolls back with everything else.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):
epoch-seq-check, wherecheck= 32 bits ofhash(seq, at_ms, request_id, kind)of the entry atseq.position()does one PK lookup. If the entry is missing or the check differs, returnSyncTokenExpiredand rotate the epoch for everyone. The server has just learned it went back in time.<secrets>/users/<u>/head, holding epoch and head seq, written off the hot path every N seconds). At open,head < high-wateror an epoch mismatch means restored. That gives plugins theirrestoredsignal before work starts.P1-2 · Writer position is in a different database from the log it points into (§3 "Writer position", §5
writer_pos).writer_posis instate.db; the entries are inindex.db. Ifindex.dbloses its tail (power loss, P1-1b) whilestate.dbkeeps the position, the Writer's position is above the head. Newmail.actedentries 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_posfromstate.db. Each outcome entry already exists; give itupto: seq. At start the Writer reads its position from the lastmail.applied/mail.refusedfor 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).
stale. The person sees "Some changes you made offline weren't applied…" even though nothing conflicts.flags_seqcovers 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.cache.dbrebuild (§6) all set new seqs. After a rebuild, every queued offline action comes backstale.Narrowest correct rule:
seqper field:read,flagged, each label, placement. Bump it only when the value changes.baseand 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.(target, field)before sending, so "toggle N times offline" sends one final state per base. Thestale_basetest then needs no special case.baseoptional for online adapters (CLI, MCP, bulk jobs) and required only when the device outbox replays an action.base: i64and 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_upsends the backlog in order beforeready, 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:
catch_up, when more than Kmail.syncedentries for one account are pending, send one syntheticmail.refill {account}. The device pages the spine.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 belowB. Fix:mail.synced {…, oldest_ms, newest_ms}, and the device skips any batch withnewest_ms < B.P2-3 · Shared writer and checkpoints under backfill. About 340 KB/s of hint JSON into the shared
index.dbWAL 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:P2-4 · A crash between the
cache.dbcommit 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: addchanged_revper row and onehinted_revper account incache.db(columns, not a change table). At worker start, re-hint rows withchanged_rev > hinted_rev.P2-5 · An accepted action can be lost on power loss (§8 "Two acknowledgements"). The
mail.actedjournal 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 isNORMAL. For notes the content lives elsewhere; for mail nothing else holds it. Fix: a shared "durable" commit flag that usessynchronous=FULLwith 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).unknown/ "check Sent". It can't have gone out yet, because itsrelease_msis still in the future. Keep rows withrelease_ms > nowscheduled.state.db-only restore (P1-1), already-delivered rows come back aspendingand are retried automatically. Belt and braces: before the first DATA of any row created more than 10 min ago, runlookup_sent(Message-ID)wherecapsallow it.P2-7 · The id scheme flips when
pkeysupport changes (§4).msg iduses one formula with apkeyand 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 instate.db(account.id_scheme) and never switch it, as withakey.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 (hashof(id, sort_ms, flags)per month) and fetches only the months that differ. Add a gate: refill bytes aftercache_rebuild≤ 1% of the spine when nothing changed.P3
pkeyhosts. Withnas the rank by UID, moving one of two same-fpcopies (a list copy and a Cc copy) swaps their ids, because the moved copy gets a higher UID. Rank bycontent_hashfirst and by UID only among byte-identical copies.mail.refused {reason: restored}should show no words. Some of those actions did reach the provider before the restore.visible_entry/journal_forgive app-password callers onlynotes.*/sharing.*entries and requirenotes.read. Say the proxy follows the log as an in-process consumer, not through the app-password sync route, or theimap.mailscope needs those mail kinds.list_page_scaling.Answers to the four questions
P1: 3 · P2: 8 · P3: 5
v4.1 pushed (head
c68be1f9). Mapping of review 77534 (+ 77537 on #919, 77539 on #918). Section numbers refer todocs/plans/mail-architecture.md. kayg 14:40 IST: start minimal; Q7 and Q11 approved.epoch-seq-check(one PK lookup; mismatch →SyncTokenExpired+ epoch rotation), high-water file under--secretswritten every 5 s off the hot path, plugins getrestored. 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 devwriter_posremoved. The Writer position is the highestuptoamong its ownmail.applied/mail.refusedentries, so it rolls back with the logstaleonly if the field changed afterbaseand current ≠ requested; equal → no-op success; no Installation exemption (the outbox coalesces per target and field);basefrom an older epoch = changed; optional for online adapters. Notes behaviour does not changecatch_up, more than 200 pending mail hints collapse intomail.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 backlogoldest_ms/newest_ms; the device skips batches belowBchanged_revper row,hinted_revper account (columns, not a change table); re-hint at startmail.actedis a durable commit; the outbox clears only on thatlookup_sent(JMAP submissions or a Sent search by Message-ID); found → delivered; provider saves Sent and not found → send; else held asunknown. Future-scheduled rows stay scheduledaccount.id_schemefixed at creation; gaining or losing stable ids never switches itnswapcontent_hash, then UID among identical copies; fixture addedrefused {reason: restored}shows no wordsmailtopic in-process, not via the app-password routelist_page_scalingAccepted 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).
Second review of v4.1 (head
c68be1f9): plan + #918 + #919Checked against
origin/dev41f2efa3: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:index.db, FIFO queue of 64, one transaction per command.commit_innerreturnsErr(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.index.db.notes/history.dbhas its own FULL writer thread with its own group commit (ADR 0020). Soindex.dbcommits are cheap for notes because they are NORMAL.catch_up. The journal has no index onkindoritem.1. First-review findings
writer_pos)stale, and outbox coalescing is under-specified (N-3)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
IdempotencyConflictdrops 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.
mail.appliedormail.refused, not on accept. The UI stays optimistic, as it is now.appliedwith an option.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
fdatasynconindex.db-waland 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 afterdata_started).lookup_sentmisses (IMAP Sent search lag, a Sent copy in a localised folder, a mismatchedcaps.saves_sent). The mail is sent a second time.heldrow back with arelease_msin the past. Lookup finds nothing, because it was never sent, so it is sent although the person cancelled it.Fix:
delivered. Not found → held, with one line: "This mail was due at 10:42 and hasn't gone out. Send now?"unknownkeeps its own rule (never automatic).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.P2
N-3 · #919: a device's own unconfirmed action makes its next one
stale, and the outbox merge rules are missing.base69.read_seq≥ 69 and current (read) ≠ requested (unread), so the result isstale. 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.after: [op ids], the device's own unconfirmed ops on those targets. A change afterbasemade by one of those ops doesn't count. Keepfield_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.baseof its parts, and a merge that returns to the original value is dropped only if none of its parts was sent.mail.actedentries (with their seq), not justcache.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.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:
blake3_keyed(user key from <secrets>, seq ‖ at_ms ‖ kind ‖ item ‖ request_id), truncated to 32 bits.seq≤ head, or when the high-water file says so. A token from an older epoch is just expired, never a rotation.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
itemto the input.N-5 · #918 high-water edge cases that skip the
restoredsignal. The issue only handles "file epoch =meta.epochand file seq > head".restored. The mail Writer then applies days-old pendingmail.actedfrom the backup, and the Sender runs its normal path. Rule: any epoch mismatch counts as restored.meta.highwater = 1inindex.db. Rotate only if that flag is set and the file is gone; otherwise create the file.P3
topiccolumn and an index(topic, seq)onjournal. Then a notes-onlycatch_up, themail.refillcount and aLaggedre-scan skip mail rows instead of paging through them.uptoamong 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.3. Accepted risk (pending actions replayed after a late-noticed snapshot rollback)
Acceptable for actions:
Keep it, with one change: list
delete_foreveras the exception. Hold it until itsmail.applied, and refuse it with words ifrestoredarrives 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_upstill 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).
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 todocs/plans/mail-architecture.md.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 burstlookup_sent(→ delivered) or held with "This mail was due at 10:42 and hasn't gone out. Send now?".unknownstays held. After a detectedrestored, rows scheduled for later are held for review too. §1, §6, §9 and §15 now say the same thing: a restore sends nothingafter: [own unconfirmed op ids]plusfield_req, so a device's own in-flight change never makes its next onestale. "Current" and "changed" include pending actions. Rebuilt rows get the head. The outbox merges only unsent ops. Tests addedepoch-seq-c-mwith a per-user keyedm. A badm→invalid tokenwith no rotation; another epoch → expired. Only a validmagainst a missing or different entry, or the high-water file, rotates. Old tokens are accepted only while this boot's high-water check passedmeta.highwaterkeeps the first deploy from rotating anyonetopiccolumn +(topic, seq)index;catch_upskips other topics(kind, item, seq); cold-start gate: flat vs journal lengthAccepted 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_foreveris the exception: it shows as gone only aftermail.applied, andrestoredrefuses it. Sends are not in this risk; they are held.Size: 391 lines (unchanged; the cap was ≤ 391).
Third (final) review of v4.2 (head
bc1cd7bc): plan + #918 rev 3 + #919 rev 3I checked this against
origin/dev41f2efa3.journalalready hasat_ms, kind, item, installation, request_id, soccan be computed from existing columns.UserStore::positionchecks onlyepoch ≠andseq > head.Cmd::Onceis the only FULL commit on the shared writer.ensure_epochmints the epoch once. The new token and rotation rules fit that code. They add one PK read inpositionand nothing on the commit path.1. Round-2 and carried findings
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-1after+field_req, pending counted, rebuilt rows take the head, only unsent ops merge. One test is missing from §17 (P3-2)mgivesinvalid token, another epoch gives expired, and only a validmagainst a missing or different entry rotates. The plan §2 and #918 agree2. 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
…-70and a validm, andpositionproves a rollback and rotates. That's correct. The outbox then replays the archive with the same op id, but itsbaseis from the old epoch. #919 counts that as "changed", and current (Inbox) ≠ requested, so it returnsstale. 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 tomail.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", sorestoredfires. That drops pending actions and holds every scheduled send for review even when no entry was lost.Fix (no new machinery):
refused {restored}and astalethat 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_foreveris still refused with words and never replayed.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.restore_drillcase: 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).
restoredfires 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 ≤ nowgetslookup_sent: found →delivered, else held with "Send now?". There's no threshold. Rows scheduled for later stay scheduled unlessrestoredfired. Optional: aclean_stoprow 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 "answers250onceoutgoingis durable").The
outgoing+outgoing_rcptinsert is a NORMAL commit instate.db. Scenario: Apple Mail submits, the proxy answers250, 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 amail.send. If it clears only on a finalsend_stateinstead, 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 theoutgoinginsert a FULL commit instate.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 asend_state_machinecase: power cut right after accept, then the mail is delivered exactly once.3. P3 (one line each)
(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.stale(safe, but say so in §15). Field seqs stamped before a rotation (cache.dbsurvives a power-loss rotation) should count as "head at rotation". §17stale_baseis missing #919's "rebuild, then a late retry after a pre-rebuild change →stale".mail.dbrebuild (new epoch)". That's a rev-3 leftover; it should becache.dbrebuild /mail.reset.pkey-scheme account while the provider has no stable ids, so that its id doesn't change whenpkeycomes 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
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 todocs/plans/mail-architecture.md.refused {restored}or on astalecaused 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_foreveris 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 wordslookup_sentand is eitherdeliveredor held with "Send now?". Rows scheduled for later stay scheduled unlessrestoredfired. 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 timeoutgoing+outgoing_rcptinsert is a FULL commit instate.db(its own file, never on the notes writer). The device outbox and the proxy clear a send on accept and never replay it. Newsend_state_machinecase: power cut right after accept → delivered exactly once. The proxy stub says250comes after that commit(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 gatestale(safe). Seqs stamped before a rotation count as "head at rotation" (#919). Thestale_basetest "rebuild, then a late retry after a pre-rebuild change →stale" was addedcache.dbrebuild (mail.reset) or a save-log epoch rotation"pkey-scheme account during a stable-id outage getsblake3-128(akey ‖ fp ‖ n). It keeps that id whenpkeyreturns: it's found by placement/fp, and a rebuild reads it from the mirror file name with the same content hashSize: 391 lines (cap ≤ 391). Ready for kayg: the plan's approval plus the one F-2 residual.
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).
Closing: head
a8f2649cis already in dev (reached via6be86ba0); nothing left to merge. Branch kept.Pull request closed