ADR 0003: Two-tier lazy packed viewport rows and RLE FrozenRow scrollback¶
Status¶
Accepted. 2026-11-21.
Context¶
Grid and scrollback storage in pure Python faces three simultaneous traps:
Object-per-cell heap blowup: Representing a
10,000 x 80scrollback buffer aslist[list[Cell]](800,000 frozen slotted dataclasses) consumes56.46 MiBof traced CPython 3.15 heap (>130 MiBwithout__slots__) and amplifies garbage-collection pause times.Pooled
StyleIdRGB leaks andu16overflows: Designs that internStyleobjects into aStylePoolindexed byarray("I")(u32) orarray("H")(u16) break on 24-bit RGB (SGR 38;2;r;g;b) streams (btop,chafa,timg, smooth fades, or hostile PTYs). Without eviction, 16.7 million RGB combinations leak gigabytes ofStyleobjects acrossRIS; witharray("H")(u16), style#65,536(reached in<50 msof240x80truecolor frames) raisesOverflowErroror requires expensive stop-the-world reference counting across active and historical cells.Unwritten-blank vs space vs wide-spacer ambiguity: Using
""for unwritten blank cells causes cursor jumps (CSI 1;10 H+"OK") to collapse interior columns when joining cell text ("OK"instead of" OK") and collides with""on wide-characterSPACER_TAILcells. Conversely, scanning backward across" "cells duringEL 0(CSI K) must never erase explicit" "characters printed to the left of the erase start column.
Decision¶
Adopt a two-tier memory architecture that uses inline 64-bit bit-packed
attribute words (zero StylePool) across both hot mutable viewport rows and
cold run-length-encoded (RLE) scrollback lines:
Hot viewport
_Row(libvt._grid):chars: list[str]of lengthcols:" "for narrow blank or erased cells, single-codepoint or multi-codepoint grapheme strings for printed cells, and""reserved strictly forWidthRole.SPACER_TAILandWidthRole.SPACER_HEAD.used: int: High-water column index (0..cols) of explicitly written or non-defaultBCE-erased content.clear_range(lo, cols, bce_word=0)clampsused = min(used, lo)without scanning left pastlo, preserving explicit spaces printed left oflo.Lazy 64-bit
attrs: Starts asattrs: array.array[int] | None = Nonewith scalaruniform_attr: int = 0andhas_wide: bool = False. Plain default-styled ASCII writes slice-assignchars[col:end] = list(seg)with zeroarray("Q")allocation. On the first non-uniform style, wide glyph, protected attribute, orHAS_EXTcell,_Rowpromotesattrs = array.array("Q", [uniform_attr]) * cols.64-bit inline bit layout (
0== blank default narrow unprotected cell):bits
0..24(25b): foreground color (0= default,1..16=AnsiColor,256..511=IndexedColor(0..255)keeping0..15distinct fromAnsiColor,(1 << 24) | 0xRRGGBB=RgbColor).bits
25..49(25b): background color (same encoding).bits
50..56(7b):bold,dim,italic,blink,reverse,hidden,strikethrough.bits
57..59(3b):UnderlineStyle(0..5).bits
60..61(2b):WidthRole(NARROW=0,WIDE=1,SPACER_TAIL=2,SPACER_HEAD=3).bit
62(1b):overline.bit
63(1b):HAS_EXT, gating lazyext: dict[int, _CellExt] | Noneholdingunderline_color: Color,hyperlink: Hyperlink | None, andprotected: bool(DECSCA).
Cold scrollback
FrozenRow(libvt._grid) and_Rowrecycling:When
Screen.scroll_upevicts a full-width top row intohistory, it seals the row into an immutableFrozenRow(text: str, cols: int, runs: tuple[tuple[int, int], ...], exts: tuple[tuple[int, _CellExt], ...], wrapped: bool)whererunsstores(end_col, attr_u64)RLE spans (sharing a singleton()tuple when completely default-styled) and recycles the cleared_Rowinstance to the bottom of the viewport.Measured on CPython 3.15.1 (
10,000 x 80styled CLI log rows),FrozenRowRLE scrollback consumes~2.66 MiBvs22.59 MiBfor cloned mutable_Rows (8.5xreduction) and56.46 MiBforCellgrids (21.2xreduction) — with zerozstddependency and zeroStylePoolleak.
Unified public
RowView,RowRun, andCellviews (libvt.screen):RowViewwraps either a live_Rowor aFrozenRow, exposing.text,.wrapped,row[col] -> Cell(returningBLANK_CELLwhen default), and.runs -> tuple[RowRun, ...]forO(runs)styled span rendering.Primary scrollback stores
FrozenRowrecords in256-row copy-on-write tuple blocks (_FrozenHistory/_HistoryView), soScreen.history,Terminal.history, andSnapshot.historysatisfycollections.abc.Sequence[RowView]withO(1)snapshot capture andO(1)random row indexing without leaking mutable storage.
Alternatives considered¶
Storage model |
|
24-bit RGB safety |
Multi-codepoint graphemes |
Verdict |
|---|---|---|---|---|
Lazy 64-bit |
|
inline 64b (leak-free) |
native |
Adopted |
Uncompressed cloned |
|
inline 64b (leak-free) |
native |
|
|
|
leaks unbounded RGB styles |
side-dict per cluster |
OOM on RGB streams |
|
|
|
native |
Crashes/corrupts on truecolor |
|
|
per-cell objects |
native |
High RAM and GC pressure |
Consequences¶
Positive¶
Truecolor animations (
16.7Mcolors) allocate zero persistent style-table entries and never overflow 16-bit IDs.Unstyled ASCII logs skip
array("Q")allocation on active rows and compress to onestr+ shared empty tuple in scrollback, recycling_Rowbuffers on every scroll.IndexedColor(0..15)(SGR 38;5;0..15) round-trips distinctly fromAnsiColor(0..15)(SGR 30..37,90..97).
Tradeoffs¶
Random cell indexing into
FrozenRow(history[i][col]) performs a short tuple scan (bisect/ linear over typically 1-6 RLE spans) rather thanO(1)array indexing.
Risks¶
Wide-character
WIDE/SPACER_TAILpairing corruption duringICH(CSI @) orDCH(CSI P). Mitigation: heal split wide pairs after or at the exact cut boundaries (colwhencolisSPACER_TAIL, andrightwhen a shiftedWIDEhead loses its tail at the right margin), verified by 400+ randomized fuzz trials.