The run
Run the finished ledger on a sequence of calls, and check each return.
rollback(5) undoes every operation after time 5. Which one goes?
| Call | Returns |
|---|---|
deposit(1, "cy", 50) | 50 |
deposit(2, "ana", 80) | 80 |
deposit(3, "ben", 50) | 50 |
withdraw(4, "ana", 100) | None |
withdraw(5, "ana", 30) | 50 |
top(6, 3) | [('ana', 50), ('ben', 50), ('cy', 50)] |
deposit(7, "cy", 25) | 75 |
top(8, 2) | [('cy', 75), ('ana', 50)] |
balance_at("ana", 4) | 80 |
balance_at("ana", 5) | 50 |
balance_at("ben", 2) | None |
rollback(5) | |
top(10, 3) | [('ana', 50), ('ben', 50), ('cy', 50)] |
Here are the histories the run builds, one entry per change:
| Account | History, one entry per change | After rollback(5) |
|---|---|---|
| cy | (1, 50), (7, 75) | (1, 50): the deposit at 7 is undone |
| ana | (2, 80), (5, 50) | both kept |
| ben | (3, 50) | kept |
The failed withdrawal at 4 left no entry, so balance_at("ana", 4) still sees the 80 from time 2. The rollback to 5 keeps the withdrawal at exactly 5 and undoes the deposit at 7.
Break it three ways
Now break it, one bug at a time, and run the same calls and a short test per level:
| Bug | First level whose test fails | Where the run goes wrong |
|---|---|---|
top sorts by balance only | 2 | top(6, 3) returns [('cy', 50), ('ana', 50), ('ben', 50)], the ties in the order the accounts opened |
_balance walks forward and returns the first entry at or before t | 1 | balance_at("ana", 5) returns 80, and every top from 6 on shows ('ana', 80) |
rollback keeps only entries before t | 4 | top(10, 3) returns [('ana', 80), ('ben', 50), ('cy', 50)], because the withdrawal at exactly 5 was undone |
Every wrong answer is a plausible list or number, and none of them raises.
The second bug fails at level 1, two levels before the feature it belongs to. withdraw reads through _balance too. So as soon as an account has two entries, the next withdrawal sees the old balance. That's the one-path payoff: a bug in a shared path can't hide in a method nobody tests.
In the editor, write the ledger's ranking at a time: its top accounts by balance.
- 1
Write
top(history, t, n): each account's balance att, skip the accounts with none yet, rank by balance high to low with ties by name, and keep the firstn.
Run your code to check it. Output shows here.