Skip to content

fix(preview): eliminate main-thread freeze when viewing large spreadsheets - #1946

Merged
wmfeht merged 1 commit into
lgse:mainfrom
JoeJoeflyn:fix/1939-xlsx-preview-freeze
Oct 30, 2026
Merged

wmfeht merged 1 commit into
lgse:mainfrom
JoeJoeflyn:fix/1939-xlsx-preview-freeze

Conversation

@JoeJoeflyn

@JoeJoeflyn JoeJoeflyn commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Resolves #1939.

Single-clicking a spreadsheet file with large numbers of rows (e.g. 15,000–25,000 rows, up to 100,000 cells) previously froze the GTK main loop for ~5 seconds before displaying the preview.

Root Cause

  1. TableState previously wrapped a gio::ListStore with a gtk::SortListModel and a gtk::CustomSorter. For 20,000 rows, sorting on the main loop performed ~300,000 comparisons across the C-FFI boundary, with two GObject dynamic type checks (g_type_check_instance_is_a) and two RefCell borrows per comparison.
  2. SortKey generation was executed eagerly across all columns during creation, allocating lowercase strings for text cells in every column even when never sorted.
  3. The row model was initially populated unsorted and then immediately re-sorted with a 25,000-item splice, forcing GTK to tear down and rebuild list structures twice.

Fix

  1. Replaced gtk::SortListModel with pure in-memory Rust slice sorting (indices.sort_by) on gio::ListStore. Sorting 25,000 rows dropped from ~4,500ms to <10ms.
  2. Made column sort-key extraction lazy per column (column_sort_keys: Vec<RefCell<Option<Vec<SortKey>>>>). Untouched columns never parse or allocate lowercase text.
  3. Populated the row store directly in initial sorted order on creation, avoiding the redundant secondary splice and re-layout pass.

Performance Verification

Tested in isolated Arch Linux KDE Plasma / Wayland VM:

  • freeze_5s.xlsx (18,000 rows × 4 cols = 72,000 cells):
    • Before: 4.5–5.2s main thread freeze, max D-Bus ping reply latency 714ms, 17 dropped intervals.
    • After: 0.00s freeze, max D-Bus ping reply latency 31.19ms, 40/40 pings on time.
  • cells_100k.xlsx (25,000 rows × 4 cols = 100,000 cells):
    • After: max D-Bus ping reply latency 190ms, 0 freeze. Sorting on column headers takes <10ms.

Visual Evidence

spreadsheet_preview_navigation.mp4
cells_100k_preview_verified.mp4
freeze_5s_preview.mp4

Follow-up: lazy table rows and CPU measurement

The follow-up uses a table-local lazy row model, reuses primary-key groups on sort-direction changes, and precomputes column populations. Row identities and the displayed/copy/selection order remain shared. Fresh CPU, elapsed-time and RAM measurements, including limitations and tradeoffs, are recorded in the follow-up comment rather than committed benchmark files.

Manual check: preview a CSV with repeated values, click another column header twice, switch the primary header, then scroll a large table. Equal keys should retain their secondary ordering, and newly visible rows should show the matching cells.

Per explicit owner direction, CI suites and pinned lint phases are left to GitHub, not run locally; local work was limited to performance builds/measurements, source formatting and a pinned isolated manual UI build/drive.

Verified signature history

With explicit owner approval, the five unsigned PR commits were consolidated into GitHub-verified commit d2b4ed0f and the same PR branch was updated with an exact-head --force-with-lease guard. Its complete Git tree is identical to 01dca680, so the code, prior benchmark findings and known header-sort regressions are unchanged. No signing keys or branch protections were changed.

This is a signature/history-only update. Per owner direction, CI runs on GitHub; no local builds, test suites or lint phases were run for it.

@github-actions github-actions Bot added the fix label Oct 30, 2026
@JoeJoeflyn

Copy link
Copy Markdown
Collaborator Author

Fixes and benchmark results

Fixed secondary-column tie breaking, bounded lazy caches for ragged tables, redundant sorting/model replacement on rebuilds, and the failing ragged-selection regression. Sorting and copying now share the Rust row permutation. The original PR's GTK-comparator removal is retained.

Benchmark source and benchmark documentation have been removed from the PR as requested; results belong here, not in the repository.

Measurements

AMD Ryzen 7 3750H, Rust 1.98.1, GTK 4.22.4, unoptimized test profile, private Xvfb/D-Bus. Dense fixtures used one warmup and five measured samples; numbers are medians. Widgets were unmapped: these measure model/widget work, not XLSX parsing, rendering, or Wayland responsiveness.

Operation Original PR (e527a970) Last measured follow-up candidate
Dense 25,000 rows / 100,000 cells: model creation 103.72 ms 141.75 ms
Cold column sort 38.90 ms 79.82 ms
Warm column sort 27.31 ms 52.44 ms
Identical sort 27.54 ms 0.094 ms
Non-default widget rebuild 53.21 ms 28.77 ms
Copy displayed TSV 36.65 ms 25.47 ms
Rows replaced during rebuild 24,999 0
Ragged 25,000 rows / 25,510 cells: visit all 256 columns 4,047.57 ms 2,931.19 ms
Approximate retained RSS growth during those column visits 155,528 KiB 784 KiB
Model items removed during those column visits 6,399,744 24,999

The measured candidate still regressed dense cold/warm sorting; a direct dense single-column fast path was added afterward. That final fast path has not been re-benchmarked, following the request to stop local runs. These measurements do not establish that final cold-sort latency improved. RSS is approximate and affected by allocator reuse; desktop load also affected timings.

Validation already completed

  • ./scripts/test-headless.py ui::table_view:: -- --nocapture — 11 passed on the final production code; the then-present manual benchmark was ignored.
  • ./scripts/test-headless.py ui::virtual_preview::tests::standalone_table_keeps_copy_model_alive_without_document_state -- --exact — 1 passed.
  • STRATA_CONTAINER_ENGINE=podman ./scripts/qa.sh table-preview-keeps-secondary-sorts sandboxed-office-shared-preview — 6 passed before the final dense fast-path refinement.
  • The new QA assertion was also deliberately given the old incorrect tie order; it failed at the intended header-sort check. The correct expectation was restored. The actual CI-failing selection-test fix was not reverted.

Per explicit owner direction, no further local tests, benchmarks, or lint checks are being run; GitHub CI will validate the pushed revision. Local pinned fmt/clippy phases and full suites were not run. No screenshots or benchmark logs are committed.

@JoeJoeflyn

JoeJoeflyn commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator Author

Dense-table CPU follow-up — 01dca680

Update: the fresh, like-for-like full-widget benchmark finds that cold/warm GTK header sorting remains slower than the original PR. The model-only measurements below must not be interpreted as full header-action or whole-application performance results.

Implemented the performance follow-up without committing benchmark sources or results:

  • A table-local gio::ListModel creates row GObjects only when GTK requests them, caches their identity by source row, and owns the single row permutation used by display, copy and selection. Sorting no longer clones/re-splices thousands of GObject references.
  • Changing only the primary sort direction reverses primary-key groups in linear time, preserving secondary ordering and stable equal keys.
  • Column populations are computed once from row widths instead of scanning all rows again for every cold column cache.

Fresh measurements, including CPU time

AMD Ryzen 7 3750H, Rust 1.98.1, GTK 4.22.4, private Xvfb/D-Bus. A throwaway harness compiles the exact production model methods and cell types from the original PR (e527a970), previous branch head (48083aa4), and this revision. It uses the real GIO/GObject implementations, not a replacement sorting algorithm.

These are model-only microbenchmarks: no XLSX parsing, widget construction, rendering, input dispatch, or end-to-end responsiveness measurement. CPU is process user+system time from getrusage; GTK-main-thread time was also recorded with CLOCK_THREAD_CPUTIME_ID and closely matched process CPU. This does not measure idle CPU, power, or whole-app RAM. Desktop load varied.

Optimized model code (rustc -C opt-level=3, reusing existing dependency builds; not a fully optimized release application). Dense fixture: 25,000 rows / 100,000 cells. Medians of 18 measured samples across two rounds with opposite revision order, each after one warmup.

Operation Original PR CPU Previous head CPU New CPU Previous → new elapsed
Model creation 45.22 ms 42.05 ms 3.66 ms 42.85 → 3.72 ms
Cold grouped-text sort 17.64 ms 15.66 ms 4.11 ms 16.00 → 4.19 ms
Warm sort-direction change 13.90 ms 12.01 ms 0.72 ms 12.27 → 0.72 ms
Copy displayed TSV 12.03 ms 5.54 ms 3.40 ms 5.74 → 3.46 ms
Cached-column switch after materializing every row object 12.18 ms 11.23 ms 2.11 ms 11.63 → 2.15 ms
Direction change after materializing every row object 13.21 ms 11.92 ms 0.70 ms 12.30 → 0.71 ms

The three requested operations use approximately 91%, 74%, and 94% less CPU than the previous head in this optimized-model comparison.

Unoptimized model code (opt-level=0, debug assertions; nine measured samples after warmup) also improves those operations:

Operation Original PR CPU Previous head CPU New CPU Previous → new elapsed
Model creation 115.96 ms 133.64 ms 43.50 ms 135.90 → 44.04 ms
Cold grouped-text sort 40.39 ms 46.72 ms 25.38 ms 52.11 → 26.64 ms
Warm sort-direction change 29.15 ms 35.26 ms 1.76 ms 38.24 → 1.78 ms

These are fresh model-only comparisons, not directly interchangeable with the earlier unmapped-widget benchmark table.

RAM and tradeoffs

  • On the ragged 25,000-row / 256-column fixture, retained RSS growth during column visits remains small: approximately 154 → 172 KiB between previous and new head, versus 150,132 KiB in the original PR. These are approximate medians across six fresh processes, affected by allocator reuse. Model items removed remain 24,999, versus 6,399,744 in the original PR.
  • Ragged optimized CPU is essentially unchanged versus the previous head: 151.20 → 151.64 ms; it is not a demonstrated further speedup there.
  • Lazy allocation shifts some cost to first item access: requesting the first 100 row objects takes 0.038 → 0.142 ms CPU. A separate fresh-model benchmark that creates and immediately materializes all rows takes 42.51 → 31.76 ms CPU optimized, and 125.66 → 118.80 ms unoptimized. The original PR's unoptimized full-materialization result was 112.48 ms, so that deliberately eager workload is still slightly slower than the original PR. This is not a claim that every operation became faster.

Verification and owner-directed scope

The pinned manual build completed. Through ./scripts/qa-drive.sh, repeated header reversals preserved secondary/casefold ties, and a real 100,000-cell CSV rendered, scrolled to newly materialized rows with matching source values, and reversed back correctly, with no GTK warnings/criticals. This was a manual observation, not a qa.sh scenario run. Initial manual probes targeting the header or offscreen buffer rows were corrected to body/visible targets.

Extended the existing sort/cache regressions and QA scenario, and added row-object identity/lifetime coverage, including headerless tables, clearing sorting, out-of-range model access, and model survival after TableState drops.

Per explicit owner direction, no local CI suites, Rust regression suite, qa.sh suite, or pinned fmt/clippy phases were run. Only benchmark builds/runs, native source formatting, and the pinned manual UI build/drive were performed locally. git diff --check passed. Benchmark sources and CSVs remain outside the repository.

The local measurement commands (all successful, non-empty selections) were:

python3 /tmp/strata-pr1946-cpu-XisW4M/build.py optimized
python3 /tmp/strata-pr1946-cpu-XisW4M/run.py optimized final original before candidate
BENCH_FIXTURES=25000,ragged,eager python3 /tmp/strata-pr1946-cpu-XisW4M/run.py optimized confirm candidate before original
python3 /tmp/strata-pr1946-cpu-XisW4M/build.py debug
python3 /tmp/strata-pr1946-cpu-XisW4M/run.py debug final original before candidate
BENCH_FIXTURES=eager python3 /tmp/strata-pr1946-cpu-XisW4M/run.py debug confirm candidate before original

Each profile was rebuilt before its runs. Dense runs selected nine measured iterations plus a warmup per fixture/revision; ragged runs selected three fresh processes per revision per round. The manual check used STRATA_CONTAINER_ENGINE=podman ./scripts/qa-drive.sh start with the five-row CSV fixture and isolated preferences, followed by individual send commands and stop. The first launch's unsupported array-shaped fixture was rejected; the supported fixture launched successfully, and the large CSV was generated inside its private fixture directory.

GitHub CI for 01dca680: all build/lint, four Rust shards, aggregate coverage, script and policy checks passed (run). The automated QA job was skipped by the workflow's default PR policy, not passed; only the pinned manual UI observations above cover that path locally.

@wmfeht

wmfeht commented Oct 30, 2026

Copy link
Copy Markdown
Collaborator

Review

No blocking bugs found. One minor behavior inconsistency and two small test notes below.

1. Rebuilt tables drop secondary sort columns from the header but keep them in the rows (low severity, document tables only)

apply_sort stores the full multi-column sort in self.sort, but on rebuild src/ui/table_view.rs:374 restores only the primary column via view.sort_by_column(...). In GTK that calls gtk_column_view_sorter_set_column, which clears every other sort column. The rebuilt view's sorter therefore holds only the primary, while the model still shows rows ordered with the secondary tie-breaker. The next header click reports only the rebuilt view's columns, so apply_sort does a full sort and the tie-breaker is silently dropped.

When it happens: only tables embedded in document previews. Those widgets are rebuilt when the virtual list rebinds the row, for example when the table scrolls out of view and back (src/ui/virtual_preview.rs:646-652). Single-table spreadsheet previews create a fresh TableState and aren't affected.

Repro: in a document table, click "group", then "name". Scroll the table away and back, then click "name" again. Rows with equal names fall back to source order instead of staying grouped.

The old code also lost the secondary sort on rebuild (set_sorter switched to the new single-column sorter), but it did so at the moment of the rebuild. Now the display and the header disagree until the next click, which goes against this PR's goal of keeping secondary ordering. GTK has no public API to restore multiple sort columns, so the simplest consistent fix is probably to truncate self.sort to its first entry on rebuild and re-sort.

2. An existing test lost a check (src/ui/table_view/selection/tests.rs:247-253)

The sparse table now sorts at construction, so the empty row moves last. That part is expected. But the focus point was also moved to offset: 0 on the empty row, so the test no longer checks that copying a selection stops partway through the last cell of a ragged row (it previously ended at offset 4 in tail). Focusing row 1, column 1, offset 4 and expecting "a\nz\ttail" would keep that coverage.

3. Smaller notes

  • In src/ui/table_view/tests.rs, assert!(allocated <= 2 * actual_cells, …) is already covered by the following assert_eq!(allocated, body_cells, …).
  • tests/qa/scenarios/quick_preview/table-preview-keeps-secondary-sorts.jsonl has no quality rating (the qa-scenarios skill asks for one).
  • The PR description's Fix point 1 still says it sorts "on gio::ListStore"; the code now uses a custom RowModel.

Checked and correct

  • The row-width histogram in TableState::new, including removing the header row.
  • Absolute vs header-relative row indexes in the direction-reversal path.
  • RowModel::set_order releases its borrow before emitting items_changed.
  • Tie ordering matches GTK's GtkColumnViewSorter (secondary columns, then source order).
  • The QA scenario's expected orders, traced by hand.

This review is from reading the code. I didn't build the branch or run any tests.

@wmfeht

wmfeht commented Oct 30, 2026

Copy link
Copy Markdown
Collaborator

lgtm, just needs verified signatures on commits

@JoeJoeflyn

Copy link
Copy Markdown
Collaborator Author

Like-for-like widget benchmark: remaining sort regressions and RAM

Correction to the interpretation of my earlier model-only results: those results did not establish faster GTK header actions. The fresh full-widget benchmark below finds that cold and warm header sorting still regress against the original PR. Startup, redundant actions, rebuilds, copying and sparse-cache RAM improve, but this is not an across-the-board performance win.

Both the original PR (e527a970) and latest code (01dca680) were freshly compiled into the same temporary benchmark executable, using their actual table/widget/selection implementations. Original source needed namespace aliases because it lives in a nested temporary module; no sorting or widget behavior was substituted. The fixtures and operation sequence match the original posted benchmark. Only the benchmark ran, not the local CI suite.

Environment: AMD Ryzen 7 3750H, GTK 4.22.4 / GLib 2.88.3, native Cargo test profile unoptimized + debuginfo, private Xvfb/private D-Bus, accessibility bridge disabled. Checking the compiler inside the native runner's isolated environment reports Rust/Cargo 1.97.1, rather than the parent shell's 1.98.1. The two revisions use that same compiler. The previous standalone model-only measurements did use Rust 1.98.1. These are unmapped widgets, not XLSX parsing, drawing, or visible-window responsiveness measurements.

Dense measurements: one warmup plus five measured samples in each of three fresh processes per revision/fixture, with revision order alternated between rounds; medians of 15 samples. Ragged measurements: three fresh processes per revision. Historical measurements are not reused in the fresh comparison.

The complete original table, freshly remeasured

Operation Original PR, fresh Latest code, fresh
Dense 25,000 rows / 100,000 cells: model creation 121.58 ms 46.76 ms
Cold column sort through GTK 51.14 ms 56.97 ms — slower
Warm column sort through GTK 38.45 ms 77.13 ms — slower
Identical sort 36.68 ms 0.056 ms
Non-default widget rebuild 65.93 ms 22.51 ms
Copy displayed TSV 41.95 ms 18.80 ms
Rows replaced during rebuild 24,999 0
Ragged 25,000 rows / 25,510 cells: visit all 256 columns 4,479.84 ms 3,525.18 ms
Approximate retained RSS growth during those visits 152,348 KiB 700 KiB
Model items removed during those visits 6,399,744 24,999

The latest code honors secondary-column tie-breaking that the original PR omitted. That correctness difference does not erase the measured latency regressions. I have not yet profiled their cause in the GTK header-action path.

Actual CPU time, not CPU percentage

Process user+system CPU time; main GTK-thread CPU was recorded independently and closely matched:

Operation Original CPU Latest CPU
Model creation 119.65 ms 46.15 ms
Cold header sort 50.12 ms 55.97 ms
Warm header sort 37.71 ms 75.75 ms
Non-default rebuild 64.73 ms 22.27 ms
Copy displayed TSV 41.30 ms 18.48 ms
Ragged all-column visits 4,397.38 ms 3,190.80 ms

So the full-widget cold/warm actions use approximately 12% and 101% more CPU than the original PR in this unoptimized experiment. The earlier 74%/94% CPU reductions applied only to isolated model operations against previous head 48083aa4, not these full GTK actions against the original PR.

RAM: growth is not total usage

The old “784 KiB” figure was additional RSS during column visits, not total application RAM. The fresh 700 KiB figure has that same meaning.

Approximate total RSS of the benchmark process, including GTK, code/resources, fixtures, widgets and allocator retention:

Snapshot Original Latest
Dense 100,000-cell case, after the measured operations 276.52 MiB 275.42 MiB
Ragged case, before column visits 377.71 MiB 375.48 MiB
Ragged case, after visiting every column 526.49 MiB 376.19 MiB

Dense retained process RSS is essentially unchanged in this experiment. The demonstrated large RAM improvement is in the ragged case: approximately 149 MiB of extra sort-cache growth avoided. RSS is approximate and allocator-dependent; these totals do not establish total RAM of a normal visible Strata session.

What the lazy-row tradeoff actually is

Row-object construction is deferred to first access rather than paid for every row up front. Objects are cached, not evicted as rows scroll away, so visiting every row can eventually materialize the whole table. The separate force-all-items, unoptimized model stress test was slightly slower than the original PR (118.80 versus 112.48 ms CPU), although faster than the previous branch head. This is distinct from the unresolved header-sort regressions above.

Local scope and repository state

./scripts/test-headless.py --config build.jobs=2 --no-run ui::table_view::widget_benchmark::compare_original_and_latest
./scripts/test-headless.py --config build.jobs=2 ui::table_view::widget_benchmark::compare_original_and_latest -- --ignored --exact --nocapture --test-threads=1

The temporary original-module build initially needed missing namespace aliases corrected; the corrected build completed. The exact benchmark selection passed: one outer benchmark, all 18 fixture/revision subprocess runs, with all expected nonzero sample counts. No Rust regression suite, QA scenario suite, or local CI/lint phases ran. The temporary module declaration was removed, git diff --check passed, and the working tree is clean. All harness source/logs remain outside the repository; no new production changes or commit were made for this measurement. GitHub CI remains green for unchanged 01dca680 (its automated QA job was skipped by the workflow policy).

…heets

Consolidate the unsigned PR history into a GitHub-verified commit.

Preserve the exact source tree of 01dca68, including sort ties, bounded sparse caches, lazy row objects and regression coverage.

Fixes lgse#1939.
@JoeJoeflyn
JoeJoeflyn force-pushed the fix/1939-xlsx-preview-freeze branch from 01dca68 to d2b4ed0 Compare October 30, 2026 17:41
@JoeJoeflyn

Copy link
Copy Markdown
Collaborator Author

Verified signatures: merge blocker cleared

With explicit owner consent, replaced the five unsigned PR commits with the single GitHub-signed Verified commit d2b4ed0f, updating this same PR branch using an exact-head --force-with-lease guard.

  • The complete source tree is unchanged from 01dca680: 2587ab97a411600150bc2d8f72922108585bd813. git diff --exit-code 01dca680 d2b4ed0f passed with no differences.
  • GitHub reports the new commit's verification as verified: true, reason: valid. No signing keys or repository protections were changed.
  • GitHub CI passed build/lint, all four Rust shards, aggregate coverage and script/policy checks. Automated QA was skipped under the existing PR workflow policy, not passed.
  • PR state is CLEAN / MERGEABLE / APPROVED. The PR has not been merged.

The owner explicitly authorized the history rewrite and directed CI to GitHub. No local builds, test suites or lint phases were run for this signature-only update. Previous benchmark findings, including the remaining GTK header-sort regressions, are unchanged. The temporary signing branch was deleted; the previous head remains preserved in local ref refs/backup/pr-1946-unsigned-01dca680.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] XLSX preview blocks the UI thread for ~5 seconds (window freezes)

2 participants