Save log: sync tokens check their entry; detect a log that went back in time (shared, from mail plan) #918

Open
opened 2026-11-04 09:02:23 +00:00 by kayg · 6 comments
Owner

Revision 3, after reviews 77539 and 77558 (and #920 N-1, N-4, N-5). Shared, not mail-specific. Compared with revision 2, this removes the durable commit flag and group commit, and rotation now happens only on proof of a rollback.

Problem

index.db can go back in time while devices hold newer tokens:

  • a backup restore;
  • a whole-host or VM snapshot rollback (the secrets root rolls back too);
  • a power loss under synchronous=NORMAL: the WAL tail is lost, and AUTOINCREMENT gives the lost seqs out again for different entries.

UserStore::position only refuses epoch ≠ or seq > head. Once the server writes past a device's seq, the device skips entries silently. The same goes for search's position and MCP Events.

Durability statement. Journal commits stay NORMAL. Notes durability comes from notes/history.db (its own FULL writer), not from index.db. This issue makes seq reuse detectable; it adds no fsync to ordinary commits. Notes commit latency is unchanged. Plugins whose intent would otherwise exist only in the journal keep it on the client until an outcome arrives (mail: the outbox clears on mail.applied/mail.refused; the provider is the durable store).

Fix

  1. Tokens prove where they came from and what they saw. Token = epoch-seq-c-m:
    • c = 32 bits of blake3(seq ‖ at_ms ‖ kind ‖ item ‖ request_id) of the entry at seq;
    • m = 32 bits of blake3_keyed(user key, epoch ‖ seq ‖ c). The user key is <secrets>/users/<u>/token.key, outside every backup.
  2. position(token):
    • bad m → invalid token (re-read). Never a rotation, so a garbled token from a client can't force refills for everyone;
    • other epoch → SyncTokenExpired, never a rotation;
    • valid m with seq > head, or the entry at seq missing, or c different → proof of a rollback: rotate, then SyncTokenExpired;
    • old tokens without c-m are accepted only while this boot's high-water check passed, then upgraded on the next reply.
    • Cost: one primary-key read.
  3. High-water file <secrets>/users/<u>/head = (epoch, seq, c). A timer writes it at most every 5 s and only when the head moved, off the writer thread: write the temp file, fsync it, then rename. A torn file therefore means a real rollback. At open:
    • unreadable or torn file = missing;
    • missing, and meta.highwater = 1 → restored;
    • missing, and no flag → create the file and set the flag. This is the first deploy, and it rotates nobody;
    • file epoch ≠ meta.epoch → restored (a backup from before an earlier rotation);
    • same epoch, and the file's seq > head or its c ≠ the entry → restored.
  4. Rotation = a new meta.epoch in a FULL commit, then the file is rewritten with fsync + rename, before the first new-epoch token goes out. It's rare and not on the notes path. Plugins get restored before their workers start.
    • Replay after rotation: clients don't drop their unconfirmed ops on 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. The server drops its own pending work, so a restore moves nothing server-side. (Mail: delete_forever is never replayed.)
  5. Plugin positions live only in index.db (e.g. upto: seq in their outcome entries), so they roll back with the log.
  6. Webhooks and MCP Events carry the full token. Receivers dedupe by token, not by seq (seqs can be reused after a rollback).

Tests

  • Restore a backup taken after the last start.
  • Restore a backup taken before an earlier rotation (plugins get restored).
  • Roll back a full-host snapshot.
  • Truncate the WAL, then write past a device's seq; with a mail archive pending it ends archived, no words.
  • A zero-length high-water file.
  • First deploy: nobody rotates.
  • A garbled or hand-edited token: invalid token, no rotation.
  • Rotation then power loss: no token for a forgotten epoch.
  • Perf: notes accept p50/p99 and typing flat vs dev (nothing on the notes path changes besides the one PK read in position).
**Revision 3, after reviews 77539 and 77558 (and #920 N-1, N-4, N-5).** Shared, not mail-specific. Compared with revision 2, this removes the durable commit flag and group commit, and rotation now happens only on proof of a rollback. ## Problem `index.db` can go back in time while devices hold newer tokens: - a backup restore; - a whole-host or VM snapshot rollback (the secrets root rolls back too); - a power loss under `synchronous=NORMAL`: the WAL tail is lost, and `AUTOINCREMENT` gives the lost seqs out again for *different* entries. `UserStore::position` only refuses `epoch ≠` or `seq > head`. Once the server writes past a device's seq, the device skips entries silently. The same goes for search's position and MCP Events. **Durability statement.** Journal commits stay NORMAL. Notes durability comes from `notes/history.db` (its own FULL writer), not from `index.db`. This issue makes seq reuse *detectable*; it adds **no fsync** to ordinary commits. **Notes commit latency is unchanged.** Plugins whose intent would otherwise exist only in the journal keep it on the client until an outcome arrives (mail: the outbox clears on `mail.applied`/`mail.refused`; the provider is the durable store). ## Fix 1. **Tokens prove where they came from and what they saw.** Token = `epoch-seq-c-m`: - `c` = 32 bits of `blake3(seq ‖ at_ms ‖ kind ‖ item ‖ request_id)` of the entry at `seq`; - `m` = 32 bits of `blake3_keyed(user key, epoch ‖ seq ‖ c)`. The user key is `<secrets>/users/<u>/token.key`, outside every backup. 2. **`position(token)`:** - bad `m` → `invalid token` (re-read). Never a rotation, so a garbled token from a client can't force refills for everyone; - other epoch → `SyncTokenExpired`, never a rotation; - valid `m` with `seq > head`, or the entry at `seq` missing, or `c` different → **proof of a rollback**: rotate, then `SyncTokenExpired`; - old tokens without `c-m` are accepted only while this boot's high-water check passed, then upgraded on the next reply. - Cost: one primary-key read. 3. **High-water file** `<secrets>/users/<u>/head` = `(epoch, seq, c)`. A timer writes it at most every 5 s and only when the head moved, off the writer thread: write the temp file, **fsync it**, then rename. A torn file therefore means a real rollback. At open: - unreadable or torn file = **missing**; - missing, and `meta.highwater = 1` → restored; - missing, and no flag → create the file and set the flag. This is the first deploy, and it rotates nobody; - file epoch ≠ `meta.epoch` → restored (a backup from before an earlier rotation); - same epoch, and the file's seq > head or its `c` ≠ the entry → restored. 4. **Rotation** = a new `meta.epoch` in a FULL commit, then the file is rewritten with fsync + rename, **before** the first new-epoch token goes out. It's rare and not on the notes path. Plugins get `restored` before their workers start. - **Replay after rotation:** clients don't drop their unconfirmed ops on `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. The server drops its own pending work, so a restore moves nothing server-side. (Mail: `delete_forever` is never replayed.) 5. **Plugin positions live only in `index.db`** (e.g. `upto: seq` in their outcome entries), so they roll back with the log. 6. **Webhooks and MCP Events** carry the full token. Receivers dedupe by token, not by seq (seqs can be reused after a rollback). ## Tests - Restore a backup taken **after** the last start. - Restore a backup taken **before** an earlier rotation (plugins get `restored`). - Roll back a full-host snapshot. - Truncate the WAL, then write past a device's seq; with a mail archive pending it ends archived, no words. - A zero-length high-water file. - First deploy: nobody rotates. - A garbled or hand-edited token: `invalid token`, no rotation. - Rotation then power loss: no token for a forgotten epoch. - Perf: notes accept p50/p99 and typing flat vs dev (nothing on the notes path changes besides the one PK read in `position`).
Author
Owner

Review note from the mail v4 review (full text on #920, finding P1-1). A mark written at each start misses the common case. Any backup taken after the last start has the same mark as the secrets file. Example: start Monday, back up Tuesday, restore Tuesday's backup Thursday. Nothing is detected, and devices skip entries silently. It also can't see a whole-host or VM snapshot rollback (the secrets root rolls back too), or a power loss under synchronous=NORMAL, where the WAL tail is lost and AUTOINCREMENT gives the same seqs out again.

Proposed instead:

  • Token entry check. Token = epoch-seq-check, where check = 32 bits of hash(seq, at_ms, request_id, kind) of the entry at that seq. position() does one PK lookup. A missing entry or a different check returns SyncTokenExpired and rotates the epoch.
  • High-water file. <secrets>/users/<u>/head, holding (epoch, head seq), written off the hot path every N s. At open, head < high-water or an epoch mismatch means restored, and plugins get their restored signal from that.
  • Plugin positions stay in index.db. Plugins keep their save-log positions inside index.db, for example as upto in their outcome entries, never in another database, so they roll back together with the log.

Test:

  • Restore a backup taken after the last start.
  • Roll back a full-host snapshot.
  • Simulate a power loss by truncating the WAL.

Each one must end with every device re-reading.

Review note from the mail v4 review (full text on #920, finding P1-1). A mark written **at each start** misses the common case. Any backup taken after the last start has the same mark as the secrets file. Example: start Monday, back up Tuesday, restore Tuesday's backup Thursday. Nothing is detected, and devices skip entries silently. It also can't see a whole-host or VM snapshot rollback (the secrets root rolls back too), or a power loss under `synchronous=NORMAL`, where the WAL tail is lost and `AUTOINCREMENT` gives the same seqs out again. **Proposed instead:** - **Token entry check.** Token = `epoch-seq-check`, where `check` = 32 bits of `hash(seq, at_ms, request_id, kind)` of the entry at that seq. `position()` does one PK lookup. A missing entry or a different check returns `SyncTokenExpired` and rotates the epoch. - **High-water file.** `<secrets>/users/<u>/head`, holding `(epoch, head seq)`, written off the hot path every N s. At open, `head < high-water` or an epoch mismatch means restored, and plugins get their `restored` signal from that. - **Plugin positions stay in `index.db`.** Plugins keep their save-log positions inside `index.db`, for example as `upto` in their outcome entries, never in another database, so they roll back together with the log. Test: - Restore a backup taken *after* the last start. - Roll back a full-host snapshot. - Simulate a power loss by truncating the WAL. Each one must end with every device re-reading.
kayg changed title from Save log: detect a restored index.db and rotate the epoch (shared, from mail plan R-1) to Save log: sync tokens check their entry; detect a log that went back in time (shared, from mail plan) 2026-11-04 09:15:02 +00:00
Author
Owner

Revised the issue body per 77539: token entry check + high-water file, plugin positions only in index.db, durable group-commit flag with notes cost and gate. The per-start mark is dropped.

Revised the issue body per 77539: token entry check + high-water file, plugin positions only in `index.db`, durable group-commit flag with notes cost and gate. The per-start mark is dropped.
Author
Owner

Second review (full text on #920, findings N-1, N-4, N-5). This issue needs changes:

  • Drop Commit { durable }. Notes accept p99 can't stay flat while notes commits wait behind FULL fsyncs on the shared writer. Batching commands into one transaction also lets one IdempotencyConflict drop the notes commits batched with it. Instead, the mail outbox clears on mail.applied/mail.refused, so the provider is the durable store. If accept-time durability is still needed: commit NORMAL, and let a separate barrier thread run one coalesced fdatasync on index.db-wal before answering, so the writer thread never waits.
  • Keyed check, narrow rotation. Check = blake3_keyed(user key in <secrets>, seq ‖ at_ms ‖ kind ‖ item ‖ request_id), 32 bits. Rotate only when a keyed check fails with seq ≤ head, or when the high-water file says so. Any other bad token just gets SyncTokenExpired, so one client can't force rotations and full reconciles for everyone. Accept unchecked old tokens only while high-water shows no rollback.
  • High-water rules: an epoch mismatch counts as restored, and plugins get restored. An unreadable or torn file counts as missing. The rotation is a FULL commit, and the file is rewritten (fsync + rename) before new-epoch tokens go out. meta.highwater = 1 stops the first deploy from rotating every user.
  • Tests: restore of a backup taken before an earlier rotation (Writer must not replay its pending entries); a zero-length high-water file; a garbled token from a client (no rotation).
Second review (full text on #920, findings N-1, N-4, N-5). This issue needs changes: - **Drop `Commit { durable }`.** Notes accept p99 can't stay flat while notes commits wait behind FULL fsyncs on the shared writer. Batching commands into one transaction also lets one `IdempotencyConflict` drop the notes commits batched with it. Instead, the mail outbox clears on `mail.applied`/`mail.refused`, so the provider is the durable store. If accept-time durability is still needed: commit NORMAL, and let a separate barrier thread run one coalesced `fdatasync` on `index.db-wal` before answering, so the writer thread never waits. - **Keyed check, narrow rotation.** Check = `blake3_keyed(user key in <secrets>, seq ‖ at_ms ‖ kind ‖ item ‖ request_id)`, 32 bits. Rotate only when a keyed check fails with `seq ≤ head`, or when the high-water file says so. Any other bad token just gets `SyncTokenExpired`, so one client can't force rotations and full reconciles for everyone. Accept unchecked old tokens only while high-water shows no rollback. - **High-water rules:** an epoch mismatch counts as restored, and plugins get `restored`. An unreadable or torn file counts as missing. The rotation is a FULL commit, and the file is rewritten (fsync + rename) before new-epoch tokens go out. `meta.highwater = 1` stops the first deploy from rotating every user. - Tests: restore of a backup taken before an earlier rotation (Writer must not replay its pending entries); a zero-length high-water file; a garbled token from a client (no rotation).
Author
Owner

Revision 3 per 77558: durable flag and group commit removed (notes commit latency unchanged); token = epoch-seq-c-m with a per-user keyed m, rotation only on proof; epoch mismatch = restored; a torn file = missing; rotation FULL + file fsync before new tokens; meta.highwater keeps the first deploy from rotating anyone; webhooks dedupe by token.

Revision 3 per 77558: durable flag and group commit removed (notes commit latency unchanged); token = `epoch-seq-c-m` with a per-user keyed `m`, rotation only on proof; epoch mismatch = restored; a torn file = missing; rotation FULL + file fsync before new tokens; `meta.highwater` keeps the first deploy from rotating anyone; webhooks dedupe by token.
Author
Owner

Per final review 77574 F-1: the high-water temp file is fsynced before its rename (at most every 5 s, only when the head moved, off the writer thread). Clients re-stamp their unconfirmed ops with the new token after a rotation and replay them; the server still drops its own pending work.

Per final review 77574 F-1: the high-water temp file is fsynced before its rename (at most every 5 s, only when the head moved, off the writer thread). Clients re-stamp their unconfirmed ops with the new token after a rotation and replay them; the server still drops its own pending work.
Author
Owner

Durability check of the claim in 77539/77558 (code on 41f2efa3 = prod BM13; throwaway probe on dev-01, nothing committed).

Verdict: the claim is true for index.db (the save log). It is not true for note text: an acknowledged "Saved" survives power loss. The hole is the one this issue already fixes (silent seq reuse). One extra gap is listed at the end.

Where each step of a note save lands

Step Store PRAGMAs / flush Survives process crash Survives power loss
Typing → room → history writer (group commit) notes/history.db WAL, synchronous=FULL (history.rs tune): WAL fsync per commit yes yes
"Saved" (101 reply to the 100 check) sent only once every change before the check is in history.db (room/acks.rs, ADR 0020) n/a n/a n/a
File write, 750 ms after the last change <note>.md tmp → sync_all → exchange/rename → sync_dir (fsio/swap.rs, fsio/lib.rs); pending row in history before, promote after yes yes
notes.saved/created/changed/deleted hints, action results + idempotency records index.db journal WAL, synchronous=NORMAL (store/schema.rs tune), default autocheckpoint (1000 pages). Only commit_once (write-executor publications) switches to FULL yes no: everything since the last checkpoint or FULL commit can roll back
Write-executor journal write-executor/* file sync_all + rename + sync_dir yes yes

The client also keeps its own copy: the editor's IndexedDB local copy holds unconfirmed changes (pendingSince, recovery intents), and a reconnect sends what the server is missing (sync step 2). So note text has two durable copies before "Saved" is even shown.

Probe (same pragmas and table shape as crates/store and crates/notes/history, SQLite 3.53.3)

  • strace -e fsync,fdatasync over 20 saves: history.db-wal 22 fsyncs, note.md.tmp 20 + dir 24, index.db-wal 0 per commit (its 3 came from setup and a forced checkpoint).
  • 50 saves acknowledged, then SIGKILL:
    • process crash (page cache kept): journal head 51, history 50 rows, note.md = v50, next seqs 52–54. Nothing lost.
    • power loss, every file rolled back to its last fsync (POSIX worst case): journal head 1, history 50 rows, note.md v50, next seqs 2, 3, 4. The seqs are handed out again.
  • Couldn't test real power-cut ordering. There's no root on the build VMs (no dm-flakey), and LazyFS isn't in nixpkgs; my source build was queued behind the bm14e train, so I stopped it. The "last fsync" rollback is the documented SQLite guarantee for WAL+NORMAL ("might roll back following a power loss"). In practice ext4 writeback usually narrows this to the last ~5–30 s of journal commits, and WAL checksums keep the result a consistent prefix.

What that means today

  • Note content: no loss after "Saved".
  • Save log: after a power cut, a device holding token …-N gets SyncTokenExpired (full reload) only if head is still below N when it reconnects. If startup recovery, scan hints or another device push head back past N first, the device silently skips the reused range. It then shows a stale list (a missing new note, a deleted one still shown, an old title) until the page reloads. Web tokens live only in memory (store.svelte.ts), so a reload fixes it. Search and tasks keep no journal cursor. #918's token entry check and high-water file are the right fix and add no fsync. Notes latency is unchanged.
  • Extra gap, not in this issue: engine idempotency records (execute.rs → store.commit with IdemWrite) are also NORMAL. After power loss, an action that already got its reply but is retried with the same key runs again. The notes actions are safe: notes.create derives the id from the key (watch::id_for_key), and append/patch/replace receipts live in history.db (FULL, history/receipts.rs). I haven't audited the other plugins (daily, contacts, attachments, auth). Each one should either keep its own durable receipt or tolerate a re-run. Suggest adding that as a checklist line here rather than putting an fsync on the shared writer, since 77558 already showed that FULL on the shared writer moves notes p99.

Decision: no separate "acknowledged saves" issue. It would duplicate this one, and acknowledged note saves are durable.

**Durability check of the claim in 77539/77558** (code on 41f2efa3 = prod BM13; throwaway probe on dev-01, nothing committed). **Verdict:** the claim is **true for `index.db` (the save log)**. It is **not** true for note text: an acknowledged "Saved" survives power loss. The hole is the one this issue already fixes (silent seq reuse). One extra gap is listed at the end. ### Where each step of a note save lands | Step | Store | PRAGMAs / flush | Survives process crash | Survives power loss | |---|---|---|---|---| | Typing → room → history writer (group commit) | `notes/history.db` | WAL, `synchronous=FULL` (`history.rs` `tune`): WAL fsync per commit | yes | **yes** | | **"Saved" (`101` reply to the `100` check)** | sent only once every change before the check is in history.db (`room/acks.rs`, ADR 0020) | n/a | n/a | n/a | | File write, 750 ms after the last change | `<note>.md` | tmp → `sync_all` → exchange/rename → `sync_dir` (`fsio/swap.rs`, `fsio/lib.rs`); pending row in history before, promote after | yes | **yes** | | `notes.saved`/`created`/`changed`/`deleted` hints, action results + idempotency records | `index.db` journal | WAL, `synchronous=NORMAL` (`store/schema.rs` `tune`), default autocheckpoint (1000 pages). Only `commit_once` (write-executor publications) switches to FULL | yes | **no**: everything since the last checkpoint or FULL commit can roll back | | Write-executor journal | `write-executor/*` | file `sync_all` + rename + `sync_dir` | yes | yes | The client also keeps its own copy: the editor's IndexedDB local copy holds unconfirmed changes (`pendingSince`, recovery intents), and a reconnect sends what the server is missing (sync step 2). So note text has two durable copies before "Saved" is even shown. ### Probe (same pragmas and table shape as `crates/store` and `crates/notes/history`, SQLite 3.53.3) - `strace -e fsync,fdatasync` over 20 saves: `history.db-wal` **22** fsyncs, `note.md.tmp` 20 + dir 24, `index.db-wal` **0 per commit** (its 3 came from setup and a forced checkpoint). - 50 saves acknowledged, then SIGKILL: - **process crash** (page cache kept): journal head 51, history 50 rows, `note.md` = v50, next seqs 52–54. Nothing lost. - **power loss**, every file rolled back to its last fsync (POSIX worst case): journal head **1**, history **50** rows, `note.md` **v50**, next seqs **2, 3, 4**. The seqs are handed out again. - **Couldn't test** real power-cut ordering. There's no root on the build VMs (no dm-flakey), and LazyFS isn't in nixpkgs; my source build was queued behind the `bm14e` train, so I stopped it. The "last fsync" rollback is the documented SQLite guarantee for WAL+NORMAL ("might roll back following a power loss"). In practice ext4 writeback usually narrows this to the last ~5–30 s of journal commits, and WAL checksums keep the result a consistent prefix. ### What that means today - **Note content:** no loss after "Saved". - **Save log:** after a power cut, a device holding token `…-N` gets `SyncTokenExpired` (full reload) only if head is still below N when it reconnects. If startup recovery, scan hints or another device push head back past N first, the device silently skips the reused range. It then shows a stale list (a missing new note, a deleted one still shown, an old title) until the page reloads. Web tokens live only in memory (`store.svelte.ts`), so a reload fixes it. Search and tasks keep no journal cursor. #918's token entry check and high-water file are the right fix and add no fsync. **Notes latency is unchanged.** - **Extra gap, not in this issue:** engine idempotency records (`execute.rs` → `store.commit` with `IdemWrite`) are also NORMAL. After power loss, an action that already got its reply but is retried with the same key **runs again**. The notes actions are safe: `notes.create` derives the id from the key (`watch::id_for_key`), and append/patch/replace receipts live in history.db (FULL, `history/receipts.rs`). I haven't audited the other plugins (daily, contacts, attachments, auth). Each one should either keep its own durable receipt or tolerate a re-run. Suggest adding that as a checklist line here rather than putting an fsync on the shared writer, since 77558 already showed that FULL on the shared writer moves notes p99. Decision: no separate "acknowledged saves" issue. It would duplicate this one, and acknowledged note saves are durable.
Sign in to join this conversation.
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#918
No description provided.