szn

Bug 564 — Tier B reflow silently drops trailing content after interior erased cells on shrink

564. Tier B row transfer truncates cell storage to display width nw, losing trailing content when trimmed_len > nw

Severity: HIGH (silent data loss on ordinary resize)
Status: ✅ RESOLVED (rev 849:33bd56b0a6aa)
Files:

Related: Algorithm Optimization Plan, Text Reflow, Bug Index

Symptom

When shrinking a pane whose unwrapped row contains interior erased cells (char == 0, produced by CSI K, eraseChars, or sixel clearing) followed by visible characters, the trailing visible characters silently disappear and cannot be recovered by widening the pane back to its original width1.

Minimal Plain-ASCII Repro

Step State of Row 0 Expected Actual (Before Fix)
Initial (width = 80) 40 × 'A', 20 × char(0), 20 × 'B' (wrapped = false) Display width = 60, trimmed_len = 80 Display width = 60, trimmed_len = 80
grid.reflow(60) fitsSingleLine returns true (60 <= 60), Tier B triggers All 80 cells retained ('A', erased gap, 'B') gl.cells.items.len set to 60 — all 20 'B's truncated
grid.reflow(80) Widen back to 80 columns Columns 60..80 still contain 'B' Columns 60..80 are empty (char == 0)

Cause

Phase 1 of the algorithmic optimization plan (rev 844:6623e2375eff) added a Tier B fast path in Grid.reflowCursorInternal to move standalone unwrapped rows directly into the resized grid without flattening or reallocating1:

// src/grid.zig:1231-1233 — eligibility check
if (!first_line.wrapped and first_line.cells.capacity <= max_retained_cap) {
    const trimmed_len = trimmedCellLen(first_line.cells.items);
    if (fitsSingleLine(first_line.cells.items[0..trimmed_len], new_width)) {

In Phase 2 (materialize.take), the .transfer branch unconditionally set the cell slice length to the new display width nw:

// Before (src/grid.zig:1368)
gl.cells.items.len = nw;
if (tr.trimmed_len < nw) {
    @memset(gl.cells.items[tr.trimmed_len..nw], Cell.empty());
}

The bug is a unit mismatch between display width and cell count:

Fix

Preserved all cells up to @max(tr.trimmed_len, nw) in materialize.take (rev 849:33bd56b0a6aa), matching the invariant already upheld by rewrapWithBreaks1:

// src/grid.zig:1368-1374
// Preserve all cells up to trimmed_len when interior
// zero-width cells (e.g. char==0 from eraseChars) make
// cell count exceed display width `nw`.
gl.cells.items.len = @max(tr.trimmed_len, nw);
if (tr.trimmed_len < nw) {
    @memset(gl.cells.items[tr.trimmed_len..nw], Cell.empty());
}

Because first_line.cells.capacity is already >= tr.trimmed_len (coming from the original row) and ensureTotalCapacityPrecise(allocator, new_width) ensures capacity >= nw, setting items.len = @max(tr.trimmed_len, nw) never exceeds capacity and remains 100% infallible during Phase 2 commit.

Verification

  1. Source: src/grid.zig (Grid.trimmedCellLen, Grid.reflowCursorInternal, materialize.take, and regression test at lines 634, 1227–1250, 1364–1378, and 3032–3057). ↩ ↩2 ↩3