The Review Log in go: Write Every Answer Down, Work the Card Out Later

How go schedules reviews with FSRS

By Daniel Chiwuzoh Β·

The Review Log in go: Write Every Answer Down, Work the Card Out Later

Picture an ajo collector in a Lagos market. Ajo is the informal savings scheme where a trusted woman goes round the shops with a small exercise book, and every trader who pays in gets a line: the name, the date, the amount. At the end of the month, if you ask her how much you've saved, she doesn't look at a number she's been rubbing out and rewriting all month. She opens the book, finds your lines, and adds them up.

Now imagine you come to her and say, "Madam, I paid you last Tuesday, but you weren't at the stall, so I gave it to your sister." She doesn't argue with the total. She finds last Tuesday in the book, writes the payment in, and adds up again. The new total is correct, because the total was never the thing she kept. The book was. πŸ“’

It's the whole idea behind how go (from θͺž, the suffix that means language) remembers what you know. Every answer you give is a line in a book. The thing the app shows you, "this word is due again on Thursday", is only the sum, and the app can always throw it away and add up again.

Let me build up to why that matters, one step at a time.

First, what spaced repetition is

If you learn a word today, you will forget it. Not straight away, but the memory fades on a curve: sharp at first, then slower. If someone tests you just before it fades too far, the memory comes back stronger, and the next fade is slower. Do that a few times and a word you learned in October is still there in March.

A review card asks what δΈŽε…š means, with four choices to pick from.

So the trick of a flashcard app isn't the flashcards, it's the timing. Show the card too soon and you waste the learner's time. Show it too late and they've forgotten it and have to learn it again. The job is to guess, for every single card, the day the learner is about to forget it.

go makes that guess with FSRS (the Free Spaced Repetition Scheduler), through a library called ts-fsrs. FSRS keeps two numbers on each card:

  • Stability: roughly, how many days this memory can go before it's likely to slip.

  • Difficulty: how hard this particular card is for this particular person.

Every time you answer, you give a rating from 1 to 4: Again, Hard, Good, Easy. In go you rarely press Again yourself. A wrong answer picks it for you, and on a right answer Good is the default, so the common case is a single Enter. FSRS takes the card as it stands, the rating, and the moment you answered, and gives back a new stability, a new difficulty and a due date.

So if you meet ι£ŸγΉγ‚‹ (taberu, to eat) and get it right, it might come back tomorrow. Get it right again and it comes back in a few days. Miss it and it comes back soon.

The catch: order matters

Here's the bit that makes everything else in this article necessary. Stay with me.

FSRS is a recurrence. Each answer is applied on top of the card that the previous answer left behind. So the state of a card isn't a total of its answers, the way the ajo savings are. It depends on the path.

Answer Good and then Again, and you end up with one card. Answer Again and then Good, same two answers, and you end up with a different card.

The same card for ι£ŸγΉγ‚‹ folded twice with the same two answers in swapped order, ending at a stability of 1.58 days one way and 4.71 days the other.

On a single phone, always online, that never bites: answers arrive in the order you gave them. But go works offline. You can study on the bus with no signal and the answers wait on the phone until it reconnects, or study on your laptop in the morning and your phone in the afternoon, and two piles of answers reach the server in whatever order the networks felt like.

If the server just took the newest message and overwrote the card (what people call "last write wins"), the card you ended up with would depend on which device happened to sync first. Same answers, different schedule. Nothing crashes, nothing logs an error. A word just comes back on the wrong day.

The book and the sum

So go keeps two tables, and the difference between them is the ajo collector's book and her total.

After a correct answer the learner rates the card Hard, Good or Easy.

srs_review_logs is the book. Every answer you ever give is a row, and rows are only ever added.

/**
 * Append-only. THE SOURCE OF TRUTH.
 *
 * `id` is minted BY THE CLIENT as a UUIDv7: it sorts by time, it can be
 * generated offline, and it makes the insert idempotent (`ON CONFLICT DO
 * NOTHING`), so a retried or duplicated flush costs nothing.
 */
export const srsReviewLogs = learnerSchema.table('srs_review_logs', {
  id: text('id').primaryKey(), // client-minted UUIDv7
  rating: smallint('rating').notNull(), // 1 Again | 2 Hard | 3 Good | 4 Easy
  reviewedAt: timestamp('reviewed_at', { withTimezone: true }).notNull(),
  receivedAt: timestamp('received_at', { withTimezone: true }).notNull().defaultNow(),
  // ...

srs_cards is the sum. One row per thing you're learning, holding the FSRS state: due date, stability, difficulty, reps, lapses. Its comment is just as blunt:

/**
 * A scheduled card: one per (user, facet).
 *
 * IMPORTANT: this table is a DERIVED CACHE, not the source of truth.
 * `srs_review_logs` is. Card state is a deterministic fold over that log.
 */

"Fold" is the programmer's word for what the ajo collector does at the end of the month: start from nothing, walk through the lines in order, and carry the running result along.

Three small choices that make the book trustworthy

The id is written by the phone, not the server. When you answer, the study page mints a UUIDv7 for that answer before anything touches the network. A UUIDv7 starts with a timestamp, so ids sort roughly by time, and the phone can make one with no signal at all. Then the server inserts it like this:

.insert(srsReviewLogs)
.values({ id: input.id, rating: input.rating, reviewedAt: answeredAt, /* ... */ })
.onConflictDoNothing({ target: srsReviewLogs.id })

If the phone sends the same answer twice (the first response got lost, the train went into a tunnel, you know how it is), the second insert simply does nothing. The answer is in the book once. A retried sync is free! πŸ™‚

There is always a single order. Two devices really can stamp the same millisecond. If the fold sorted only by time, two answers at the same instant could come out in either order, and the fold would no longer be deterministic. So we sort by time and then by id:

export function compareEvents(a: ReviewEvent, b: ReviewEvent): number {
  const at = a.reviewedAt.getTime()
  const bt = b.reviewedAt.getTime()
  if (at !== bt)
    return at - bt
  return a.id < b.id ? -1 : a.id > b.id ? 1 : 0
}

The fold doesn't look at the clock. It deliberately takes no "now". Its result depends only on the answers it's given, so the same history always folds to the same card. Even the randomness isn't random. FSRS adds a little "fuzz" to intervals so that fifty cards learned on the same day don't all fall due on the same day. In ts-fsrs that fuzz is seeded from the review time, the reps and the card's numbers, not from Math.random, so a replay lands on the same interval every time. And the FSRS numbers are stored as doublePrecision rather than real, so a replay reproduces bit-identical values.

Put those together and two phones that both went offline can sync in any order: the server ends up with the same lines in the book and therefore the same sum. No answer is ever thrown away, and nothing is decided by who arrived last.

The fast path and the slow path

Now, you might be thinking: if the card is a sum, do we really add up the whole book every time someone answers? That would be silly for the normal case, where the answer you just gave is obviously the newest one.

So there are two paths, and the choice is a one-line function:

export function canFastForward(cached: CardState, incoming: readonly ReviewEvent[], dedupeWindowMs: number = DEFAULTS.dedupeWindowMs): boolean {
  if (!cached.lastReview)
    return cached.reps === 0
  const last = cached.lastReview.getTime()
  return incoming.every(e => e.reviewedAt.getTime() - last >= dedupeWindowMs)
}

The fast path: the new answer is later than the card's last review. Apply it on top of the cached card, the same way you'd add one new payment to a total you already trust. One FSRS step.

The slow path: the new answer lands before the card's last review. The cached card is now wrong, because it was built without this answer in the middle. So the server locks the card row, reads the card's whole history, starts from an empty card, and folds every answer again. That's the ajo collector writing last Tuesday's payment in its place and adding up again.

Two timelines: an answer later than the last review takes one FSRS step on the cached card, while an answer from before it makes the server lock the card and fold every answer again.

Isn't that expensive? Not really. A card collects something like fifty reviews in its whole life, so refolding one is cheap. There's still a cap in for safety: past 5,000 answers on one card it folds only the last 500, and marks the card as truncated.

You may have noticed the dedupeWindowMs in there. That's for one more real situation.

The same answer, told twice

Say you have go open on your phone and your laptop, and both send an answer for the same card within a second or two of each other. Almost certainly that's one action reported twice, not two genuine reviews, and counting it twice would push the card further out than it should be. So inside the fold, if two answers for the same card come from different devices less than 2,000 milliseconds apart, the second one is marked superseded. It stays in the book (the schema says "kept for audit"), it just doesn't count in the sum.

But which one is the double depends on what else is in the book. There's a test for exactly this: answer A from a phone, B from a laptop 1.5 seconds later, then C from a tablet one second before either. After all three, the test expects C kept, A superseded, and B kept. So the fold rewrites every superseded flag on the card each time it runs, both ways, and an answer that falls inside the two second window always takes the slow path, because only a full replay can tell which one is the double.

Answers A, B and C from three devices on one timeline, showing B as the double before C arrives and A as the double after.

Where it actually breaks: the counters

Card replay is the easy part. Here's the part the project's rules call "where this actually breaks".

Around the card there's a lot of counting: XP, streaks, daily stats (how many reviews today, how many right, how long it took), achievements. Counting is naturally written as an increment: an answer came in, so add 2 XP, add 1 to today's reviews.

Increments and replay don't mix. If a sync is retried, or a card is replayed and its answers are walked again, every increment runs again and you've counted the same answer twice. Your XP drifts up and you'd never know. So every derived number in go is built in one of two ways, and nothing else is allowed.

Keyed by the log id

XP is a table of awards, one row per thing that earned XP, with a unique key:

export const xpEvents = learnerSchema.table('xp_events', {
  source: text('source').notNull(), // review | session-complete | streak | achievement | lesson
  refId: text('ref_id').notNull(),
  amount: integer('amount').notNull(),
  // ...
}, t => ({
  dedupe: uniqueIndex('xp_events_dedupe').on(t.userId, t.source, t.refId)
}))

For a review, refId is the review log's id. So the award for answer 0192... can exist once and only once. Emit it again during a replay and onConflictDoNothing turns it into nothing. Your XP total is then just the sum of those rows, recomputed rather than incremented. The same trick pays out quests, keyed by the quest and the day.

Rebuilt wholesale

Daily stats go the other way. Rather than adding to today's row, go throws the affected days away and works them out again from the log:

// Wholesale replacement of the touched days.
await tx
  .delete(srsDailyStats)
  .where(and(
    eq(srsDailyStats.userId, userId),
    eq(srsDailyStats.languageId, languageId),
    inArray(srsDailyStats.localDate, aggregate.affectedDates)
  ))

await tx.insert(srsDailyStats).values(aggregate.daily.map(/* ... */))

The function that produces aggregate can be described as "pure, order-independent, and total": no clock, no I/O, every value a sum or a count over the input, so shuffling the answers can't change the result.

On the fast path, the rebuild only covers recent history: from two days before the answer, snapped back to the start of that study day. That snap matters more than it looks. If the cutoff were a raw timestamp, it would skip that day's earlier reviews while still listing the day as affected, so the DELETE would remove a full row and the INSERT would put back a partial one. After a replay there's no cheap shortcut: an answer landing in the middle of history can change any later day, so the whole history is rebuilt.

How I found out it wasn't quite true yet

Everything above was in the design from the very first commit: the append-only log, the derived cards, the unique key on XP, the DELETE+INSERT. And the project's rule file has a line I wrote for myself:

Required test: for any permutation of a log set, final card state and all aggregates are byte-identical. If that test doesn't exist, assume this is broken.

For a while, that test didn't exist. Then in late October I was about to make the app faster, which meant replacing a lot of the queries behind Today and the review queue, and I wanted a safety net first.

The test takes one set of answers over four days and sends it to the server three ways:

  1. One at a time, as they happen, like a learner who's always online.

  2. All in one late batch, newest first.

  3. In small shuffled batches of seven, with the first batch sent twice.

Then it compares everything derived from the log for all three learners: cards, review logs, XP, daily stats, streaks and achievements. They must come out the same.

It held for one late batch. And it found three ways the code didn't keep the rule, which I pinned with it.fails (a test that's expected to fail, so fixing the bug flips it and you notice):

  1. An answer older than the card's last review was pulled forward to one millisecond after it, instead of being replayed into its place. So the card depended on arrival order, which is the exact thing the whole design was meant to prevent.

  2. A card's first-seen and last-correct dates, and an achievement's unlock time, were the moment the server received the answer, not when you gave it. An offline session synced the next day counted its new words on the day of the sync.

  3. Quest XP was only ever scored for the day of the rebuild, so an offline day that synced later never earned its quests.

The first one is my favourite, because it was a guard written to protect the fold. The old clock function had a guarantee in its comment: "A review is never at or before the previous review on the same card, so the per-card order is strictly total." It enforced that by nudging the time:

if (previousReviewedAt && ms <= previousReviewedAt.getTime()) {
  ms = previousReviewedAt.getTime() + 1
  adjusted = true
  reason = 'not-after-previous'
}

That made the order total, but by changing the history to fit the cache. It was the ajo collector being told about last Tuesday and writing the payment in at the bottom of the page with today's date. The (reviewed_at, id) order already made the fold total without moving anything.

Before and after: the old guard moved a late Oct 6 answer to one millisecond after the Oct 9 review, and the fix keeps it on Oct 6 and replays the card.

The fix landed about nine hours later, in "A review is dated when the learner answered, however late it reaches the server". The nudge is gone. The only things that can still move an answer's time are a clock that can't be right: more than five minutes in the future, or more than 30 days in the past, and either one sets clockAdjusted on the row so it stays visible. An older answer now takes the slow path and is replayed into its place. First-seen, last-correct, a ghost flag's date and a missed lesson question being cleared all follow the answer's own time. The same commit made an answer inside the two second window take the slow path, and set the superseded flags both ways. In its own words, "The shuffled-batch permutation test passes for real."

The third departure went the same afternoon: achievements are dated by the answer that crossed the threshold, and a sync batch notes the study day of every answer, so those days have their quests scored too. The last it.fails became an ordinary test.

I'll talk about the offline side of this (the queue on the phone, what is waiting, how late answers travel) in the next part. For this one, the rule was right from day one, and it took a test to show me the code wasn't quite keeping it.

One rebuild per sync, not one per answer

One last piece, because it's where correctness and speed met.

When I measured production before the speed work, /sync/mutations took 898ms. Part of the reason: offline sync rebuilt progress, XP, streak and achievements once per answer, and then once more over the whole history. A batch of 200 answers rebuilt the same days 200 times.

Because every rebuild is wholesale, it doesn't matter how often it runs, only from where. So now each answer in a batch just notes what it owes ("rebuild this language from this date", or "from the beginning" after a replay), the earliest request wins, and the batch runs each language's rebuild once at the end. A rebuild that fails is logged per language rather than failing a request whose answers are already safely in the book, and the next answer rebuilds it again.

That change was only safe because of everything before it. If XP were an increment, "run it once instead of 200 times" would change the answer. Because it's a sum keyed by log id, it only changes the cost.

So what is the card, really?

A convenience. A very useful one: the review queue asks "what is due?" on every page, and it would be daft to fold every card's history to answer that. So the cache is there, indexed, ready. But if it disappeared tomorrow, go could fold it back from the log and get exactly the same thing, down to the bit. The total can go. The book stays.

Then they that feared the LORD spake often one to another: and the LORD hearkened, and heard it, and a book of remembrance was written before him for them that feared the LORD, and that thought upon his name. - Malachi 3:16