szn

Bug 444 — History ring defensive guards index empty list out of bounds and getHistoryLineMut is dead code with broken guard

444. Latent out-of-bounds access in bug #443’s defensive guards

Severity: LOW
Status: Fixed

Symptoms

None observed in production. Both defects are latent landmines that only fire if some other bug first corrupts the history ring bookkeeping (history_count > 0 or history_start > 0 while history.items.len == 0). If triggered, the server would crash (index-out-of-bounds panic in Debug/ Safe builds) or read out of bounds (ReleaseFast), taking down every attached session — the failure mode bug #380 explicitly tried to avoid.

Two reachable-by-corruption sites were found in code review of the bug #443 fix:

  1. getHistoryLine empty-history branch: returned &self.history.items[0] when history.items.len == 0 — an out-of-bounds read of an empty list.
  2. scrollUp reuse-path fallback: insert_idx = if (items.len > 0) ... else 0 still executed self.history.items[insert_idx] afterwards; with an empty list the else 0 fallback indexes slot 0 out of bounds. The same fallback pattern exists in clearHistory and setHistoryLimit eviction loops.
  3. getHistoryLineMut: zero callers in the tree, carried the identical broken empty-list guard, and cannot be hardened with a shared read-only sentinel (a mutating return must not alias a global other grids could observe or deinit).

Root Cause Analysis

Bug #443 standardized ring arithmetic on % history.items.len and added items.len > 0 guards to survive a corrupt ring, but the guard fallbacks chose index 0 — which is only safe if the list is non-empty, the exact condition being guarded against. A corrupted state therefore walked straight into the out-of-bounds access the guard was meant to prevent. getHistoryLine’s fallback had the same flaw behind a “callers always check idx < historyLen” assumption.


Solution

  1. Blank sentinel read path in src/grid.zig: added a container-level const EMPTY_HISTORY_LINE: GridLine = .{} and made getHistoryLine return &EMPTY_HISTORY_LINE for an empty ring. All callers already bounds-check (x < line.cells.items.len, .wrapped), so a blank line is invisible to rendering and selection. The sentinel is never allocated and never owned, so it cannot leak or be double-freed.
  2. Self-heal at every mutating entry point: added normalizeHistoryRing(), which resets history_count/history_start to 0 when history.items.len == 0, called at the top of scrollUp, clearHistory, and setHistoryLimit. After normalization, scrollUp provably takes the append path (correct for an empty ring), so the else 0 fallbacks are dead code; they are kept as belt-and-braces defense.
  3. Removed dead getHistoryLineMut (zero callers).
  4. Regression test "Grid recovers from corrupt empty history ring without OOB access (bug #444)" corrupts the ring state, exercises the read path, scrollDown, clearHistory, setHistoryLimit, and scrollUp, and asserts blank reads plus self-healed bookkeeping.