23/41
Part 4 of 7 · VersionsLearn and do

A read at snapshot s takes the key's last change with a count of at most s

Each key keeps two lists: the counts its changes recorded, and the values. A second set at the same count replaces the value, since no snapshot saw the first one. Here are the key's lists after each call from the last step:

Callcountsvalues
set 30[0][30]
snapshot 0no changeno change
set 45[0, 1][30, 45]
set 60[0, 1][30, 60]
snapshot 1no changeno change
snapshot 2no changeno change
set 90[0, 1, 3][30, 60, 90]

set 60 has the same count as set 45, so it replaces 45.

To read the key at snapshot s, take its last change with a count of at most s: position bisect_right(counts, s) - 1. It's the same search as before, on a counter instead of a clock.

Snapshot 0 reads position bisect_right([0, 1, 3], 0) - 1 = 0, which is 30. Snapshots 1 and 2 both read position 1, which is 60. Nothing changed between them, and nothing had to be stored for snapshot 2. A snapshot costs O(1), and a read O(log c) for a key with c changes.

In the editor, write get(key, snap) for the SnapshotStore. It reads the table's three snapshots.