Can You Rebuild a Learner From Their Review History? Event-Sourcing Order-Dependent State Offline
Classic SRS apps sync per-card (S, D) rows independently. The moment your scheduler maintains a cross-card recurrent state, naive row-level CRDTs silently corrupt memory. Here is how Kanso combines append-only logs, prefix-hashed checkpoints, atomic IndexedDB outboxes, and Postgres sync_xid watermarks.

Key Takeaway · Quick Answer
Order-dependent memory state—recurrent hidden channels, fatigue, log-RT baselines, and online Bayesian calibration—cannot be merged by overwriting per-card rows across devices. Kanso treats an immutable append-only ReviewEvent log in canonical (ts, id) order as the sole source of truth, pairing O(1) dual-hash prefix checkpoints with atomic IndexedDB outbox commits, BroadcastChannel tab fencing, and commit-safe Postgres sync_xid watermarks.
Why row-level card sync silently corrupts order-dependent ML state
In classic SM-2 or standalone FSRS tools, synchronization looks deceptively simple: each card owns an independent mutable row—stability, difficulty, due date, reps, lapses. If you review Deck A on your phone during a flight and Deck B on your laptop at home, a row-level last-write-wins merge works cleanly because Card X’s state never depends on Card Y.
The moment a scheduler tracks cross-card sequential state, that independence vanishes. Kanso’s RWKVHiddenState folds every review across every deck into a shared 16-channel WKV matrix, an exponentially decaying sessionFatigue scalar, a 24-card recency ring buffer, hierarchical per-CardKind Welford log-RT statistics, and an online diagonal Bayesian calibration head with sequential martingale sums. That fold is strictly non-commutative: reviewing X then Y yields different fatigue, recency overlap, prequential predictions, and—once the calibration gate opens—different stability updates than reviewing Y then X.
You cannot LWW-merge two opaque hidden-state JSON blobs from two offline devices without throwing away one device’s learning trajectory, nor can you average two recurrent matrices and expect anything coherent. The only mathematically sound primitive is event sourcing: make the immutable, append-only ReviewEvent log the single source of truth, and treat every FSRS row, recurrent state, calibration bucket, and even today’s session stats (deriveDailySessionFromEvents) as deterministic projections of that ordered log.
O(1) cold starts without silent drift: dual-hash extendable prefix checkpoints
Pure event sourcing carries an obvious operational cost: replaying 40,000 review events from index 0 on every browser tab open wastes CPU and battery. On the other hand, caching a mutable snapshot without cryptographic-style lineage binding creates silent state drift the first time an offline phone uploads a review timestamped two hours earlier than your laptop’s latest review.
Kanso resolves this tension with versioned checkpoints (CHECKPOINT_VERSION = 3) bound to an extendable dual 32-bit FNV-1a prefix hash (EventPrefixHashState). Every event hashes into a canonical token encoding every replay-sensitive field: id, cardId, ts, rating, responseMs, hintUsed, implicit, mode, desiredRetention, and schedulerMode. The accumulator maintains two independent rolling hashes—h1 over tokens and h2 over index-bound "${count}:${token}" pairs—plus count, lastTs, and lastId. Appending a chronological tail event extends the hash state in O(1), while finalization mixes in "len:${count}" so exact prefix length is always bound.
On startup or after a sync merge, rwkvReplay sorts events canonically by (ts ASC, id ASC)—matching Postgres ORDER BY ts ASC, id ASC and IndexedDB’s compound index by_ns_ts_id—and checks five conditions before trusting a stored checkpoint: version match, review count match, timestamp monotonicity, complete validated fsrs_states rows, and exact eventPrefixHash equality over [0, eventIndex). If a remote device simply appended newer reviews at the tail, Kanso skips full replay and runs rwkvFoldSuffix in O(ΔE). If an offline device inserted an older review mid-stream, an Undo tombstoned an earlier event, or a software update bumped CHECKPOINT_VERSION, the prefix hash mismatches automatically and Kanso replays cleanly from event 0.
This design turns two notoriously painful features—Undo and algorithm upgrades—into routine operations. Undoing a review writes an immutable event_tombstone (with tombstone-wins merge semantics so undone reviews can never resurrect from another device), while an account-wide monotonic resetAfterTs watermark permanently fences off pre-reset history. Upgrading the memory model simply increments CHECKPOINT_VERSION; every learner’s state rebuilds cleanly from raw review history on next load.
| Failure Mode / Operation | Row-Level (S, D) Sync | Kanso Event-Sourced Log + Checkpoints |
|---|---|---|
| Two offline devices review different decks | Works for FSRS, breaks cross-card recurrent state | Set-union on ReviewEvents + deterministic canonical (ts, id) fold |
| Out-of-order review arrives from flight | Overwrites card row; hidden state drifts silently | Prefix hash mismatches automatically; clean deterministic replay |
| LIFO Undo on phone while laptop is offline | Card row often resurrects on next sync | Tombstone-wins event_tombstones + derived daily counters |
| Upgrading scheduler / calibration math | Stuck with old mutated (S, D) snapshots | Bump CHECKPOINT_VERSION; rebuild exact state from raw events |
0ms offline writes: atomic IndexedDB outboxes and multi-tab fencing
A local-first browser app must feel instant offline without risking split-brain between local state and its cloud upload queue. Kanso stores learner data across seven IndexedDB object stores in kanso-srs-db: meta, events, event_tombstones, packs, pack_tombstones, fsrs_states, and sync_outbox.
When you rate a card, commitRatingToIdb executes a single readwrite IndexedDB transaction totaling roughly 2 KB: one events row, one fsrs_states row, one compact meta record (holding config, compact checkpoint, and monotonic storageRev), and—when cloud sync is active—the corresponding sync_outbox intent. Crucially, Kanso performs zero JavaScript await calls inside an open IDB transaction (preventing Safari’s aggressive auto-commit bug) and stages the outbox delta atomically inside that exact transaction. If the browser crashes or the tab closes mid-click, either both the review and its upload intent commit together, or neither does.
Multiple open tabs on the same browser introduce a subtle hazard: Tab A and Tab B both hold stale in-memory checkpoints, and a blind full-snapshot write from Tab B would wipe Tab A’s recent reviews. Kanso guards every commit with optimistic concurrency via storageRev on meta. Targeted O(1) commits detect rev bumps without dropping the new rating and flag conflictDetected so the stale tab reloads, while full-snapshot and delta-append commits strictly reject stale expectedStorageRev writes. Successful commits broadcast { type: "namespace_mutated", namespace, storageRev, tabId } over BroadcastChannel ("kanso-srs-sync-v1"), falling back to a tiny localStorage revision key ("kanso.idb.rev.v1") and focus-time storageRev checks when BroadcastChannel is unavailable.
- Atomic guest-to-account claim: Signing in moves guest events, packs, and tombstones into the authenticated user namespace and deletes guest records inside one IDB transaction, clearing syncCursor to null so the first cloud sync runs a full keyset bootstrap.
- Outbox fencing on erasure: A monotonic outboxFenceEpoch fences any in-flight async cloud pushes during GDPR wipe or account deletion so slow network callbacks can never re-enqueue stale items into a wiped database.
- Same-tab Undo consistency: Rapid rate-then-undo sequences coalesce in the outbox so event_tombstone strictly supersedes its review_event without resurrecting deleted rows across retries.
Why wall-clock cursors lose rows—and how Postgres sync_xid watermarks fix delta sync
The classic bug in incremental cloud sync is paginating by updated_at > lastSyncedAt. Under Postgres MVCC, wall-clock timestamps are not commit-ordered: Transaction A starts at 10:00:00.100, Transaction B starts and commits at 10:00:00.200, a client pulls up to 10:00:00.200 and advances its cursor, and then Transaction A finally commits at 10:00:00.400 carrying updated_at = 10:00:00.100. The next delta pull queries updated_at > 10:00:00.200 and skips Transaction A permanently.
Kanso eliminates MVCC visibility gaps using server-stamped 64-bit Postgres transaction IDs (sync_xid, compared in JavaScript as exact unsigned base-10 strings via compareSyncXid so 64-bit precision is never truncated by IEEE-754 floats). Strictly before running keyset-paginated pull queries ordered by (sync_xid ASC, id ASC), Kanso calls the kanso_sync_watermark() RPC to capture txid_snapshot_xmin. Every transaction with sync_xid < watermark is guaranteed already committed and visible in the pull; any uncommitted in-flight transaction—even one blocked on locks for minutes—has sync_xid >= watermark and will be fetched cleanly on the next delta pass using gte("sync_xid", sinceXid).
Finally, bidirectional sync enforces strict ordering between monotone and non-monotone mutations. Step 1 flushes only monotone CRDT outbox items—review_event and event_tombstone in batches of 250, pushing tombstones strictly after events—while deliberately deferring LWW items (profile, imported_pack, pack_tombstone) until after pull-and-merge so an offline device with stale settings never overwrites a newer remote revision. Packs sync manifest-first: Kanso pulls lightweight revision manifests and downloads bulky pack_data JSONB bodies only when a pack is missing locally or strictly newer than its cached revision token. Both nextSyncCursor and deferred outbox acknowledgments persist only after the merged snapshot commits durably to IndexedDB, with an automatic full keyset bootstrap refresh every 7 days as defense in depth.
Frequently Asked Questions
- How fast is deterministic replay if I accumulate tens of thousands of reviews?
- On normal reloads and tail delta syncs, Kanso does not replay from event 0 at all—it verifies the O(1) dual FNV-1a prefix hash on your stored checkpoint and folds only newly appended events via rwkvFoldSuffix. Even when a full rebuild is forced (for example after an out-of-order offline merge or a checkpoint schema upgrade), each step is pure O(1) fixed-size math, replaying tens of thousands of events in milliseconds.
- Why compare Postgres sync_xid as unsigned base-10 strings instead of JavaScript numbers?
- JavaScript’s IEEE-754 Number type loses integer precision above 2^53 − 1 (Number.MAX_SAFE_INTEGER), while Postgres 64-bit transaction IDs (xid8 / bigint) can exceed 53 bits. Comparing canonical base-10 strings by length-then-lexicographic order preserves exact 64-bit ordering without BigInt JSON serialization issues.
- What happens if I lose internet halfway through a study session or close the browser tab mid-sync?
- Every review commits atomically to IndexedDB alongside its sync_outbox entry in one local transaction, so the UI never blocks on the network and no rating can be stranded without an upload intent. When connectivity returns, flushSyncOutbox uploads queued reviews in 250-item chunks and removes only server-acknowledged opIds.
- Does event-sourcing mean my review history has to be uploaded to a cloud server?
- No. Kanso runs 100% locally in your browser’s IndexedDB by default with zero login required. The append-only event log, prefix-hashed checkpoints, and multi-tab reconciliation work identically offline; optional private cloud sync simply extends the same log across your own devices.
Put It Into Practice

