szn

Bug 218 — Sixel registry eviction (step 4) can evict still-referenced images — dangling cell references

218. Sixel registry eviction (step 4) can evict still-referenced images — dangling cell references

File: src/screen.zig:250–258 Severity: CRITICAL Status: ✅ FIXED — step 4 now first tries to find an unreferenced slot; only falls back to minimum-ID eviction as absolute last resort.

// 4. If all slots are full and referenced, evict the oldest image (min id)
if (target_slot == null) {
    var min_id: u32 = std.math.maxInt(u32);
    var min_idx: usize = 0;
    for (self.sixel_images, 0..) |opt_img, idx| {
        if (opt_img) |img| {
            if (img.id < min_id) {
                min_id = img.id;
                min_idx = idx;
            }
        }
    }
    target_slot = min_idx;
}

Steps 1–3 guard against evicting a referenced image by checking isImageReferenced, but step 4 is the fallback and explicitly ignores references. It picks the slot with the minimum ID — which could be an old image still referenced by cells in the scrollback history. Evicting it frees the image data while grid cells still hold its ID in cell.char, producing a dangling reference that will either render garbage or crash when findSixelImage returns null but cell.attr.sixel is still true.

Fix: Track a per-image reference count (increment on sixel cell write, decrement on overwrite/erase) and only evict images with refcount == 0. Fall back to discarding the new image if all 64 slots have refcount > 0.