Find the bug · #6 · Off by one Hard JavaScript
The crash log has gaps
A service keeps its last few log lines in a ring buffer, and the crash reports come back with gaps.
On this page
The report
A service keeps its last few log lines in a ring buffer and attaches them to every crash report. The reports show gaps (null) and the oldest line is missing, even before the buffer has filled up.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Keeps the last `capacity` log lines; older lines are overwritten.
class RingBuffer {
constructor(capacity) {
this.capacity = capacity;
this.items = new Array(capacity);
this.next = 0;
this.count = 0;
}
push(item) {
this.items[this.next] = item;
this.next = (this.next + 1) % (this.capacity - 1);
this.count = Math.min(this.count + 1, this.capacity);
}
toArray() {
const start = (this.next - this.count + this.capacity) % this.capacity;
const out = [];
for (let i = 0; i < this.count; i++) out.push(this.items[(start + i) % this.capacity]);
return out;
}
}Read it, then pick a line.
Write down next after each push. Does it ever reach the last slot?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
const log = new RingBuffer(3);
['a', 'b', 'c'].forEach((line) => log.push(line));
console.log(JSON.stringify(log.toArray()));
log.push('d');
console.log(JSON.stringify(log.toArray()));It prints
["b",null,"c"] ["c","d",null]
It should print
["a","b","c"] ["b","c","d"]
Show the answer: the bug, the fix, and how you’d find it
The bug (line 11)
Line 11 wraps next with % (this.capacity - 1). With a capacity of 3 it only ever cycles through slots 0 and 1: slot 2 is never written, and slot 0 is overwritten one push too early. Wrapping a 0-based index over capacity slots is % this.capacity.
The fix
8 }9 push(item) {10 this.items[this.next] = item;11 this.next = (this.next + 1) % (this.capacity - 1);11 this.next = (this.next + 1) % this.capacity;12 this.count = Math.min(this.count + 1, this.capacity);13 }14 toArray() {How you’d find it
- Reproduce with a capacity of 3 and three pushes. The buffer should be exactly full with a, b and c. You get b, a gap, then c.
- A gap is a slot that was never written. Write down
nextafter each push: 1, then 0, then 1. It never reaches 2. - Only the wrap resets
next, so the modulus is the suspect:% 2where it should be% 3.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
const r = new RingBuffer(3);
for (const x of [1, 2, 3, 4, 5]) r.push(x);
assert.deepEqual(r.toArray(), [3, 4, 5]);
const one = new RingBuffer(1);
one.push('x');
one.push('y');
assert.deepEqual(one.toArray(), ['y']);Where else this bites
- Circular queues in DSA, and round-robin load balancing (
% servers.length). - Any wrap-around index: the modulus is the number of slots, not the last index.