Skip to content

perf(layout): open long documents on their first screens, lay out the rest in the background - #166

Merged
backnotprop merged 2 commits into
mainfrom
feat/fast-open
Nov 20, 2026
Merged

backnotprop merged 2 commits into
mainfrom
feat/fast-open

Conversation

@backnotprop

@backnotprop backnotprop commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Cause

On samples/big.md (2.5 MB, 14,100 blocks), Open::new called DocLayout::build, which rendered, aligned and wrapped every block before the first frame. Timing spans in the release binary (120x40, private tmux):

step ms
startup, theme, terminal setup ~1
read file + Document::of (parse/split) ~4 + ~8 read
DocLayout::build ~285
— tui-markdown render 14
— own + strip CJK marks + plain lines 5
— srcmap::align + decorate 200 (tables 145 over 276 tables, paragraphs 42, code 6)
— wrap (the reflow part) 60
Store::load (no saved annotations) <0.1
first terminal.draw 0.6

The first draw's width matched the build width (81 at 120 columns), so there was no extra reflow at 120 columns. In folder mode or with [ui] doc_width there was one: another 60 ms.

Fix

  • DocLayout::start lays out blocks from the top until 500 rows are ready (113 blocks, ~4 ms), then hands the remaining blocks to one background thread. That thread splits the work across cores with std::thread::scope (layout/background.rs).

  • Rows that are already laid out never move when the rest arrives: a block's rows depend only on that block, and first_row is assigned in order. A test checks that a lazy layout, reflowed before it finished, gives exactly the same rows (text and cell offsets) as a full build.

  • The layout waits for the background result only where something needs the whole document:

    • App::handle_event: any key or mouse event, so G, paging, clicks and selection see every block.
    • App::draw: only when the view reaches past the ready rows (finish_through).
    • annotate (keys, Pi notes, --annotate) and the headless helpers (--blocks, --snapshot).

    When the result is already in, merging it is just appending the blocks. A first key pressed within ~40 ms of opening waits for the rest of that time.

  • reflow (resize) runs across cores. On a layout that is not complete yet, it rewraps only the blocks that are ready, and the background blocks are rewrapped when they arrive. A first frame at a different width (folder tree, doc_width) therefore stays cheap.

  • DocLayout::build stays the eager path for bench and tests, now parallel too.

  • --bench also prints the first-screens time and the time until the background finishes.

Changed functions: DocLayout::{build, reflow}, new DocLayout::{start, finish, finish_through, poll, is_complete, place}, new RenderedBlock::{new, wrap} (the old per-block bodies of build and reflow), Open::new, App::{reload, annotate, describe_blocks, scroll_for_snapshot, select_quote_for_snapshot, scroll_by}, new App::{settle_layout_for_view, poll_layout, layout_pending}, one line at the top of App::handle_event, one line in App::draw, the footer's block count in App::draw_footer, cli::{bench, with_terminal, event_loop}. Document now derives Clone. No new dependencies.

Numbers

Real binary in a private tmux at 120x40, scratch HOME and PLANNOTATOR_DATA_DIR. Time from new-session until the first screen text shows, polled with capture-pane. Medians of 5 runs, in two interleaved rounds. The first run after each fresh build is slow on macOS, about 0.3 to 0.6 s for every binary, and is left out.

main this PR leaf
big.md first screen 0.333 / 0.325 s 0.048 / 0.053 s 0.087 / 0.085 s
plugins.md (16 KB) first screen 0.036 s 0.034 s
samples/ folder mode, big.md first 1.04 s 0.113 s

Interactions on big.md. Time from the tmux action until the screen equals a reference capture; medians of 4:

main this PR
G after 1 s 0.012 s 0.014 s
G right at the first screen (waits for the background) 0.008 s* 0.019 s
60 × PageDown in one burst 0.012 s 0.011 s
resize 120→90 columns 0.093 s 0.028 s
8 resizes in a row (mostly tmux client time) 0.319 s 0.275 s

* On main the first screen only appears after the full layout, so G is already free by then; the 0.3 s was paid before.

--bench samples/big.md: first screens 4 ms; rest in background 40–47 ms; full build 34–40 ms (was 285); reflow 11–18 ms per width (was 53–64). Rows (57,515) and mapped cells (2,380,068 of 2,586,780) are identical to main.

Tests

  • layout::tests::a_long_document_lays_out_its_first_screens_first_and_the_rest_matches_a_full_build: the regression guard. Opening lays out under a tenth of the blocks, and after a reflow plus finish the rows equal a full build.
  • app::long_doc_tests::a_long_document_opens_lazily_and_g_and_saved_annotations_reach_its_end: 3,000 blocks with a saved annotation near the end. The reopened app has not laid out every block. G selects the last block, and the screen shows the last paragraph, block 3000/3000 and the restored annotation's bubble.

cargo fmt --check, cargo clippy --locked --workspace --all-targets -- -D warnings and cargo test --locked --workspace pass locally on macOS (rustc 1.96). Windows and musl are left to CI: the change uses only std::thread, Arc and available_parallelism.

Note: this app has no scrollbar or percentage today. The footer's block N/M comes from the parsed document, which is complete at open.

Review fixes (second commit)

  1. Reload + resize threw a deep view back near the top. A reload restarts the layout from the top. A width change before the rest arrived ran reflow, then scroll_by(0), which clamped the scroll to the ~500 ready rows.
    • scroll_by now waits for the real end before it clamps.
    • At the start of each frame, settle_layout_for_view waits for the rest when the view, the cursor, a pending selection or the selected block lies past the ready rows.
    • I checked the other readers of total_rows and the block list: input.rs (the cursor and click clamps) and page_by/select_block all run inside handle_event, which already waits for the whole layout.
    • A reload with the view near the top still does not wait. A reload deep in the document waits once, before its first frame.
    • Real binary, 15,000 paragraphs, G, then o with an EDITOR that appends and sleeps, and a resize to 100 columns during the edit. The old head shows "Paragraph 231…249"; main and this commit show "Paragraph 14981…14999", footer block 15000/15001. r with a resize at the same moment: 3/3 at the end.
    • Reload on big.md, from r until the "reloaded" status shows (median of 4): main 0.55 s at the top and 0.49 s at the end; this PR 0.05 s and 0.06 s.
  2. A panic on a layout thread left a broken terminal. Layout threads (the background one and the per-core workers) now keep the panic hook from running on their thread and only note their panic message (layout/worker_panic.rs; installed after ratatui::init). The waiting thread then panics with that message, so ratatui's hook runs once, on the main thread: the terminal is restored and the message is printed after it. The blocks are not laid out a second time. each_in_parallel joins its workers itself, so scope does not panic a second time. The event loop merges a finished background layout every iteration (25 ms poll while one is pending), so a panic ends the app even when no key is pressed.
    • Checked with a build that panics at block 5000, 3/3 runs: the alternate screen is gone, one message (layout thread panicked at …: injected layout panic), exit 101, terminal back in cooked mode.
  3. Empty file: main and this branch both showed block 1/0. It now says empty document.

New tests:

  • a_reload_deep_in_a_long_document_keeps_the_view_through_a_resize: after a reload, the first frame at the same and at a narrower width equals the frame of a fully laid-out reload. It fails without the fix.
  • a_panic_on_the_layout_thread_continues_on_the_waiting_thread
  • a_panicking_worker_ends_each_in_parallel_with_its_own_panic
  • an_empty_document_says_so_instead_of_counting_blocks

The app tests moved to app/doc_size_tests.rs. Rebased on main after #165 and #167. First screen on big.md after the rebase, on a loaded machine (load average ~40): 0.057–0.065 s against main's 0.33 s.

… rest in the background

A 2.5 MB file spent 285 ms laying out all 14,100 blocks before the first frame.
Open now lays out the first 500 rows (about 4 ms) and hands the remaining blocks
to a background thread that splits them across cores. Input, annotating, and any
view past the ready rows wait for it, so G, paging, block counts, the rail and
saved annotations see the whole document. Reflow on resize runs across cores too.

--bench reports the first-screens time and the background time.
…n a layout panic

A reload restarts the layout from the top. A resize before the rest arrived
clamped the scroll to the rows ready so far, throwing a view at the end of a
long document back near the top. Scroll clamping now waits for the real end,
and a frame whose view, cursor, selection or pending range lies past the ready
rows waits for the rest first.

A panic on a layout thread ran ratatui's panic hook there, restoring the
terminal while the main thread kept drawing, and the join then laid the same
blocks out again. Layout threads now only note their panic; the waiting
thread panics with that message, so the hook runs once, on the main thread.
The event loop merges a finished background layout as soon as it is ready.

An empty document's footer said "block 1/0"; it now says "empty document".
@backnotprop
backnotprop added this pull request to the merge queue Nov 20, 2026
Merged via the queue into main with commit fdddb8c Nov 20, 2026
3 checks passed
@backnotprop
backnotprop deleted the feat/fast-open branch November 20, 2026 01:32
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