szn

Bug 494 — Grid.scrollUp ring corruption when physically full

494. Spare-slot index aliases a live line

Severity: MEDIUM (silent scrollback corruption; narrow trigger) Status: 🟢 FIXED Files: src/grid.zig:376-390

Problem

The spare-slot branch of scrollUp recycles a free history slot:

const insert_idx = if (self.history.items.len > 0)
    (self.history_start + self.history_count) % self.history.items.len
else
    0;

This index is only actually free when history_count < history.items.len. When history_count == history.items.len but still < history_limit (physically full ring, logically not at capacity), the branch is taken and line 389 overwrites the oldest live line: its cells buffer leaks, notifyEvict never fires (sixel refcounts for that line are never decremented — interacts with #491/#493), and history_start isn’t advanced → ring order is silently corrupted.

The trigger is narrow — e.g. OOM during setHistoryLimit compaction leaving history_start != 0 with len == count, or external mutation of the pub fields — but the corruption is silent and the pub fields make it reachable.

Proposed Fix

If history.items.len == history_count, take the eviction path instead (notify + recycle + advance history_start) rather than the spare-slot path. Consider making the ring fields private to close the external-mutation trigger.

Resolution

Restricted the spare-slot branch in Grid.scrollUp to only execute when history_count < history.items.len. When history_count == history.items.len and the ring cannot grow via append (i.e. history_start != 0), execution routes to the eviction path which properly calls notifyEvict, recycles the oldest line buffer, advances history_start, and maintains the ring order without memory leaks. Added regression test Grid.scrollUp takes eviction path when ring is physically full — bug #494.