Skip to content

rio-vt: compressed scrollback (byte planes + LZ4, decoded on read) - #2131

Open
raphamorim wants to merge 17 commits into
rio-vt-checkpointfrom
rio-vt-history-compression
Open

raphamorim wants to merge 17 commits into
rio-vt-checkpointfrom
rio-vt-history-compression

Conversation

@raphamorim

@raphamorim raphamorim commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #2130. Adds compressed scrollback to rio-vt: Crosswords::compress_history(max_blocks) packs history rows that aren't on screen, and an embedder calls it while output is quiet.

How it works

  • What gets compressed: blocks of 256 rows from the history above the viewport. It also covers the spare rows the ring keeps past the history for a later grow; after a long session those hold up to 1,000 evicted rows.
  • Encoding: a block's cells (one packed u64 each) are split into eight byte planes, so every cell's lowest byte comes first, then every cell's next byte, and so on. A plane that is one byte throughout is stored as that byte, which most are: the codepoint's high bytes in ASCII text, and the extras id where nothing is linked. Each remaining plane is LZ4-compressed on its own with lz4_flex, which is pure Rust and uses the safe encoder and decoder.
  • Why byte planes: they more than double the ratio over LZ4 on raw cells. On real logs, diffs and listings, LZ4 on raw cells gives about 10×, and LZ4 on planes gives 25–30×.
  • Why constant planes are special: LZ4 rebuilds a run of one byte a byte at a time. Skipping constant planes made reading a compressed history 3.4× faster.
  • What a compressed row keeps: its place in the ring and its flags. It gives back its cell buffer and points to its block through an Arc, so rotations, swaps and re-zeroing are unchanged.

Reads and writes

  • Reading (Index, so rendering, the cursor, vi motions, hints) decodes the row's whole block once into the block's cache and hands out that copy. Calling compress_history again drops those copies without re-encoding anything.

  • Bulk reads leave nothing decoded behind. These read inside transient_reads:

    • the formatter (snapshots, and the text with its scrollback);
    • bounds_to_string and selection_to_string, so copying a selection, block selections included;
    • a search over more than 512 lines (search_next, or regex_search over such a span).

    A block that isn't decoded yet is decoded once into a scratch owned by that read, and freed when the read returns. Blocks the viewport already decoded are read from their caches. Short searches, like the hints around the viewport on every frame, still use the caches, so frames don't decode the same block every time. A search counts as long when it runs more than 512 lines or wraps around the end, and both passes of a match share one scope. Code that isn't rio-vt's own never runs inside a scope. When a snapshot is streamed to the caller's io::Write, each write runs outside it, with reads going through the caches, so whatever the writer keeps stays valid. While a bulk read runs, its scratch holds every block it has touched; it doesn't drop them one at a time as it goes.

  • Writing (IndexMut) turns the row back into a plain row with its cells. The check is a test of one field on every write, with the work done out of line.

  • Overwritten rows: a row about to be blanked, such as one coming back to the bottom as a new line once the ring wraps, is reset without being decoded (index_mut_discard).

  • Column resizes decompress everything first, since they rewrite every row.

  • The style and extras sweeps read the ids each block's cells carry from a list kept beside the block, so nothing is decoded.

Numbers (benches/vt_snapshot.rs, 10k lines of styled 120-column history)

history rows 9.4 MB, stored in 179 KB (52×)
compress_history(None) ~5 ms
snapshot of compressed history, decoding every block 2.2 ms (1.1 ms uncompressed); about 4–12% more since bulk reads decode into their own scratch (2.6–2.7 → 2.8–3.0 ms on a busy machine)
byte planes + LZ4, real output (git log, git diff, ls -la) 27–30×

No path that doesn't compress got measurably slower. I ran vt_input and vt_snapshot on this branch and the base alternately. The differences stayed within this machine's run-to-run spread of ±5–10%, with no consistent direction.

Tests

  • Twin terminals: grid::compress::tests compares a terminal that compresses against a plain twin fed the same output, through random output, compression (all at once and in steps), resizes, scrolling back, and alt-screen switches. Snapshot (with palette) and text must stay identical.
  • Specific cases:
    • Sweeps keep ids used only by compressed rows.
    • Scrolling past a full history recycles compressed rows without decoding: a decode counter must not move.
    • Reads fill the decode cache, and compressing again empties it.
    • Writes make a row plain.
    • A column resize reflows the same as the twin.
    • Rows on screen while scrolled back stay plain.
    • The compression ratio holds.
  • Checking the tests: I broke the sweep's id marking and the discard path one at a time, and the matching test failed each time.
  • The formatter's random round trip now compresses every fourth terminal before taking its snapshot.
  • Small blocks in tests: test builds use 16-row blocks, so small terminals get many blocks and many block edges.

cargo test -p rio-vt passes (796), as does cargo test -p rioterm (310). Clippy is clean, and librio builds.

Also

  • Storage::swap is slice::swap now. The hand-rolled loop assumed Row was a fixed number of machine words. That was already wrong on 32-bit targets such as wasm, where Row was 6 words against the loop's 5, and the new fields would have made a partial swap there. vt_input is unchanged.

Memory the OS gets back: rows in slabs

Compressing freed each row's cell buffer, a small allocation. The allocator kept those: on macOS even a freed 16 MB malloc stays on the process's footprint, while an munmap is reflected at once. So the heap fell 50x but the footprint only about 2x. With 8 terminals of 10k lines at 120 columns: 82 MB filled, 40 MB compressed (25 MB later), and 44 MB after a column resize, for 10 MB of live heap.

Row::inner is now a Cells (grid/cells.rs): a Vec, or a slot of a Slab. A slab holds 256 rows' cells in one mapping from the OS (mmap; VirtualAlloc on Windows; the allocator on other targets), unmapped once all its rows let go of their slots.

  • How a slot behaves. It reads and writes as a Vec. Anything that would reallocate it moves the cells to a Vec first. Only cells without drop glue go in slabs.
  • Where rows get slots. The storage hands them out in order:
    • a growing history;
    • output recycling compressed rows (no allocation per row any more);
    • pooled rows taken back (a pooled row lets go of its slot);
    • unpacking for a column resize;
    • a reflow's rows, moved to slots of the new width before they grow and after they're cut.
  • Decoding and encoding.
    • A decoded block's rows are in a slab of their own, unmapped with the decoded copy.
    • Encode and decode work in buffers kept per thread.
    • A few unmapped slabs are kept for reuse, so a read doesn't fault in fresh pages each time. On macOS they are marked MADV_FREE_REUSABLE, which takes them off the footprint.
8 terminals × 10k lines, footprint buffer per row slabs
filled 82 MB 82 MB
compressed 40 MB 18 MB
output replaced the history, compressed again 25 MB 14 MB
read all of it back, compressed again not measured 19 MB
column resize, compressed again 44 MB 19 MB

Benches against the previous commit (minimum of two interleaved runs):

  • input and frame benches: within ±2%, emoji +3.3%;
  • compress_10k: 6% faster;
  • a snapshot of compressed history: 2.45 ms per 10k rows instead of 2.22 (+10%; the decoded blocks' pages).

In rio itself (#2134 turns compression on), cat of a 272 MB log into a 100k-line history leaves the process at 109–112 MB of footprint, against 230–233 MB on main, with the same throughput. The full numbers are in #2134.

Windows' VirtualAlloc path couldn't be built here (no cross toolchain for this repo's pinned Rust); CI's Windows job covers it.

Possible follow-ups

  • Deflate for cold blocks: deflate on the planes gets 45–50× but decodes several times slower. It could serve as a second tier for blocks nobody has touched in a long time.
  • Smaller blocks: a read of a few rows would decode fewer of them, at some cost in ratio.

Crosswords::compress_history(max_blocks) packs cold history (rows above
the viewport, and the rows the ring keeps for a later grow) in blocks of
256 rows. Cells are split into byte planes; a plane that's one byte
throughout is kept as that byte, the others LZ4-compressed (lz4_flex,
pure Rust, safe). A compressed row keeps its place in the ring and its
flags, and points at its block.

- Reading (Index) decodes the row's block once into the block's cache;
  writing (IndexMut) makes the row plain again. Compressing again drops
  the caches without re-encoding.
- Rows about to be overwritten (scrolled into place, erased) are blanked
  without decoding (index_mut_discard).
- A column resize decompresses first.
- The style and extras sweeps read a block's ids instead of its cells.
- history_memory() reports compressed/plain rows and bytes.

10k styled lines: 9.4 MB of rows in 179 KB, compressed in ~5 ms; a
snapshot reading all of it back takes 2.2 ms instead of 1.1. Tests
compare a compressing terminal with a plain twin through random output,
compression, resizes, scrolling and screen switches; the formatter's
random round trip compresses every fourth terminal.
The hand-rolled word loop assumed Row's size in words: 5 before this
branch (already wrong on 32-bit targets, where Row is 6 words), 6 with
the compressed-row fields on 64-bit but 7 on 32-bit (wasm), so it would
swap only part of each row there. slice::swap makes the same copies on
every target; vt_input is unchanged.
…per-row scans

- snapshot_visible read and cleared row dirty bits through the grid: a
  compressed row read as its decoded copy (always dirty), and clearing
  the bit decompressed it, so scrolling back unpacked the history.
  Storage::is_dirty/set_dirty touch the stored row's own bit.
- compress_from builds no index of the whole ring and finds a row's
  block from the last one looked up; memory_from likewise, and counts an
  encoding two blocks share once.
… reads rows decompresses them

- A block whose rows were mostly written (made plain) is unpacked
  whole on the next compression and compressed again with them: one
  row left in it no longer keeps all of it.
- damage_range_rows (selections, highlights) and Grid::scroll_down
  mark the stored rows dirty; scroll_to_prompt reads the stored rows'
  marks; writing over a wide character at the top left checks the row
  above before taking it to change.
- Tests: accounting, idempotent and stepwise compression, editing,
  clearing and reset, row grows over compressed history, resizes while
  scrolled back, a pinned viewport, the alt screen, ids reused after
  sweeps, search, selections, vi motions and prompt jumps over blocks.
…uts isn't taken for a sparse one

The live-row counts and the decoded-copy replacements were found by a
linear scan per new block, quadratic in the blocks per call; both are
hash maps now, so a call is linear in the ring. Live rows are counted
over the whole ring, the viewport's too, so a block cut by its edge
isn't unpacked and split as one mostly written. Storage::rows (rows
as stored, a compressed one empty) is crate-internal.
…imited call shares its limit across the screens

A call limited to a few blocks walked the whole ring again from the
oldest row, and counted the live rows of every block first: a pass in
one-block steps cost the ring once per block. The grid keeps where it
stopped, and a call on the same ring (nothing scrolled, resized or
scrolled back meanwhile) goes on from there without the first walk.
The inactive screen's history is compressed once the active one's is
done, so a limited call does about its limit, not twice it.
…nce compressed

A row's cells were a Vec of their own: a small allocation that, freed
when the row was compressed, stayed with the allocator (on macOS even a
freed 16 MB malloc stays on the footprint; an munmap goes at once). 8
terminals of 10k lines took 40 MB of footprint compressed (25 MB later)
and 44 MB after a column resize, for 10 MB of live heap.

- Row::inner is a Cells: a Vec, or a slot of a Slab, 256 rows' cells in
  one mmap (VirtualAlloc on Windows, the allocator elsewhere) unmapped
  once all its rows let go of their slots. A slot reads and writes as a
  Vec; whatever would reallocate it moves the cells to a Vec first.
  Only cells without drop glue go in slabs.
- The storage hands its rows slots in order: a growing history, output
  recycling compressed rows (no allocation per row any more), pooled
  rows taken back, unpacking for a column resize, and a reflow's rows,
  moved to slots of the new width before they grow and after they're
  cut.
- A decoded block's rows are in a slab of their own, unmapped with the
  decoded copy; encode and decode work in buffers kept per thread. A
  few unmapped slabs are kept for reuse (on macOS marked reusable, off
  the footprint), so a read of the history doesn't fault in fresh
  pages each time.

Now 14-20 MB, also after reading it all back and after a resize. The
input and frame benches are unchanged (within 2%), compressing is 6%
faster, and a snapshot of compressed history takes 2.45 ms per 10k
rows instead of 2.22.
…rows were made plain

The resume cursor was kept by the ring's shape alone, so a write into
compressed history or a column grow that kept the shape (nothing soft
wrapped) left the rows before the cursor plain until the next full
pass. It now lives with the storage and anything that makes compressed
rows plain forgets it; a sparse block's rows are unpacked into slab
slots.
… viewport

What's drawn reads a little past the viewport's top (a search's matches
running into it). A pass in steps dropped that block's decoded copy,
and the next frame decoded it again, pass after pass. A whole pass
(`compress_history(None)`) still drops it.
…es nothing decoded behind

Bulk reads decoded every block they touched into the block's cache,
kept until a compression pass dropped it. Now the formatter (snapshots,
the text with the scrollback), bounds_to_string (copying a selection)
and a search over more than 512 lines (search_next, or regex_search
over such a span) read inside `transient_reads`: a block no one decoded
yet is decoded once into a scratch of the read's own, freed when it
returns. Blocks the viewport decoded are read from their caches. Short
searches (the hints around the viewport, every frame) still read the
caches, so a frame doesn't decode the same block again.
…s scope; block selections and both passes of a match in one

- format_to/snapshot_to ran the caller's io::Write inside the scope, so
  a writer holding the terminal could read a row there, keep it, and
  use it after the scratch was freed. Out now writes to the sink
  through outside_transient_reads (the scope's scratch set aside, reads
  going through the caches), and plain text is built in its scope and
  written after.
- selection_to_string is one scope (a block selection copied a line at
  a time, each decoding into the caches).
- regex_search_left/right open one scope for both of a match's passes,
  and tell a search round the end from a short one by position, not by
  rows alone.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant