Repository navigation
perf(mecatui): memoize vp.View() to skip lipgloss re-pad on spinner-only frames (#139) - #143
Conversation
…inner-only frames (#139) `View()` called `m.vp.View()` unconditionally on every Bubble Tea frame. The bubbles viewport re-runs a lipgloss Width().Height().Render(visibleLines) on each call, re-measuring every grapheme cluster's display width from scratch. During a reasoning turn the footer spinner fires at ~10fps and each tick forces a full viewport re-pad even though the body is byte-identical frame-to-frame: 1.31s 50.00% Model.View 1.16s 44.27% viewport.Model.View (lipgloss.Render(Join(visibleLines))) Fix: add a dirty-flag memo (`renderer.vpViewValid`/`vpViewCache`) behind the established `m.rend *renderer` pointer. `View()` now calls `m.rend.vpView(m.vp)` which serves from cache on unchanged frames. `invalidateVPView()` is called at every site that changes viewport content, scroll offset, or geometry: `refreshView`, `snapshotSelection`, `scrollLines` (when changed), `onMouseWheel`, `onScrollKey`, and `onResize`. Spinner-only frames (the motivating case) skip `vp.View()`'s lipgloss pad entirely. New bench: `BenchmarkSpinnerTickVPView` (steady-state, 400 blocks, spinner-only tick). Baseline: ~546 allocs/op, ~94 KB/op. Tests: three positive+negative mutation-test pairs covering content, scroll, and geometry invalidation axes, plus a `snapshotSelection` path test. Closes #139 Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
…ation guard (#139) Iteration 2 — panel-review follow-ups and a CI perf-gate wiring gap: - Drift-guard test (TestVPViewInvalidatedByEveryViewportHandler): dispatches each viewport-mutating handler (onResize, onMouseWheel, onScrollKey, scrollLines, snapshotSelection) and asserts vpViewValid==false after, turning the "every mutation site calls invalidateVPView" convention into an enforced invariant. Mutation-proven: deleting any one site's call reds exactly that subtest. - Wire BenchmarkSpinnerTickVPView into `task perf:scenarios` — the bench regex was `BenchmarkScrollbackView` (prefix), which never matched the new bench, so it was dead in CI. Widened to an alternation matching both. - Route tui_spinner_tick_vpview to the ADVISORY render-allocs suite in perfconvert (it carries the same runtime.ReadMemStats noise as its tui_scrollback_view* siblings; hard-gating it would false-positive unrelated PRs). Updated perfconvert's split test to assert the routing. - Field order vpViewCache/vpViewValid to match the joinCache/joinValid sibling convention; doc-note that scrollLines invalidates only on observed YOffset movement. Co-Authored-By: Claude Opus 4.8 <[email protected]>
b57da55 to
46c9145
Compare
JAORMX
left a comment
There was a problem hiding this comment.
Panel review — three-axis (Spec / Standards / Domain)
Ran a panel review across three orthogonal axes. Summary below; inline comments carry the specifics. No ship-blockers; the cache design is sound and the Rule-of-Three false-positive claim holds independently. The one concrete ask is a bench-completeness fix for spec criterion #2.
Spec axis — does this implement what was asked? (source: #139, 5 acceptance criteria)
- [Wrong] Criterion #2 not satisfied by the new bench.
BenchmarkSpinnerTickVPViewnever callsView()in its measured loop (for b.Loop()→ onlym.Update(m.sp.Tick())), so thevpViewcache is never read in the measured region. The ~546 allocs/94KB capturesUpdatedispatch + chrome overhead, not thevp.View()-skip delta the issue targets. The trailingvpViewValidassertion passes vacuously. The bench comment ("vpViewCache is served verbatim") is false inside the loop. A bench that drivesView()per tick (or a second bench isolating theView()-only cost) is what criterion #2 requires. - [Missing] Height-resize path untested. Spec enumerates
SetHeight(update.go:877) as a geometry invalidation site.onResizeonly varies width; height flows throughrelayout's conditionalrefreshView(early-returns on height-equality).TestVPViewInvalidatedByEveryViewportHandler/onResizeonly varies width, never height, so the height path is untested. Edge-correct today, but the coverage is incidental, not the per-site discipline criterion #4 implies.
Standards axis — does this follow project conventions? (sources: AGENTS.md, docs/adr/0019, docs/adr/0002)
- No hard violations. Consistent with the diagnostics rule, offline-tests rule,
perf/kpistdlib-only, the advisory-vs-gated perf posture, and the Markdown workflow (llms.txtregenerated). - [Judgement] In-place ADR edit (
docs/adr/0019:111-131): adds a dated note block to an Accepted ADR. ADR 0002 says frozen records are "superseded, never edited in place." This follows an already-established pattern in the same file (the 2026-06-15 / 06-17 blocks) and extends the mutable baseline/KPI inventory rather than the Decision — grey zone the file already occupies. Worth a maintainer sanity-check on whether the accumulating dated blocks should migrate todocs/design/IMPLEMENTATION-NOTES.md, but not a regression this PR introduces. - [Info] Phase 2 status prose stale (ADR 0019 ~line 229-237): still enumerates only the two
BenchmarkScrollbackView*benches; the third is in the dated note + baseline table. Minor doc-completeness gap.
Domain axis — what do the specialists say? (panel: software-architect, code-duplication-reviewer, ux-reviewer)
- [Low / mechanical]
resetBlockCaches/refreshViewordering coupling is an untested invariant —render.go:318. The comment justifies not clearingvpViewValidby "every resetSession caller calls refreshView() afterwards." Verified true today (3 callers), but a 4th caller that forgetsrefreshViewleavesvpViewValid=trueagainst an empty conversation → stale render. The per-handler guard covers the 6 handlers but not this path — the one invariant the comment makes load-bearing is the one not tested. Fix: clearvpViewValidinresetBlockCaches(one bool write) or add a caller-invariant test. - [Verified sound — no action] Rule-of-Three false positive confirmed. The three existing caches (
blockCache/joinCache/inputCache) are all key-based but each key is a bespoke correctness argument (map-keyed-with-aliasing / scalar-on-cross-cache-monotonic-counter / scalar-on-full-textarea-state); aCache[K,V]generic fits none without contorting the key contract. The newvpViewCacheis flag-based (no key; mutation-tested dirty bool) — a different correctness model.inputCache's own comment is literally the argument for why not a flag;vpViewinverts it because the viewport has 6 enumerable mutation sites and no comparable key. Extracting now would couple flag-invalidation to self-validating key-compares — Sandi Metz's "wrong abstraction." No change. - [Verified sound — no action] Invalidation surface complete for user-visible paths. Spinner glyph + cursor blink are outside the viewport (
renderFooter/renderInputinassembleLayout), so caching the viewport body never freezes the spinner. Selection-drag paths all route throughsnapshotSelection(invalidates). Resize ordering is safe:onResizeinvalidates afterSetWidth;relayout's height-guard short-circuit still leaves the cache invalidated. Byte-identical output (golden-green) is consistent with the code:vpViewreturnsvp.View()verbatim on miss. - [Low / judgement] Bench isolates the fix honestly but measures the lighter half of the real turn. The ~546 allocs/94KB is residual chrome (header/footer/input re-render via
assembleLayout), NOT the eliminated viewport pad. During a real GLM-5.2 think, therenderTickMsg(~16ms) fires far more often than the ~100ms spinner tick and re-warms the cache viarefreshView→invalidate. The bench doesn't capture that interleaving. Consider a one-line ADR note that the real streaming frame also pays therefreshViewre-pad (un-cached, by design), so the win is specifically the spinner-tick frames between content flushes — so a reader doesn't mistake 546 allocs/op for the in-turn cost.
Most important single issue: the bench doesn't call View() in its measured loop, so it doesn't demonstrate the vp.View()-skip allocs/op drop criterion #2 requires. The cache itself is sound and golden-green; the bench just isn't measuring the thing it claims to.
JAORMX
left a comment
There was a problem hiding this comment.
panel-review inline comments
JAORMX
left a comment
There was a problem hiding this comment.
Three inline review comments from the panel review — all low-severity / non-blocking:
scrollback_bench_test.go:217— the bench loop never callsView(), so it doesn't measure thevp.View()-skip allocs/op drop spec criterion #2 requires (it measuresUpdatedispatch + chrome overhead instead).render.go:319— theresetBlockCaches→refreshViewordering coupling is an untested invariant; clearvpViewValidinresetBlockCachesor add aresetSessionguard test.render_cache_test.go:1377— theonResizesubtest only varies width; the height-resize path (spec criterion #4) is untested.
The cache design is sound and the Rule-of-Three false-positive claim holds (independently confirmed by the duplication reviewer — the three existing caches are key-based with bespoke correctness arguments; the new one is flag-based, a different model). Golden-green / byte-identical output verified. No ship-blockers.
| // lipgloss grapheme-width pad. The spinner advances its tag on each update, | ||
| // so we call m.sp.Tick() from the UPDATED model each iteration to get a | ||
| // matching-id tick (avoids the stale-tick dedup that would drop the handler). | ||
| mm, _ := m.Update(m.sp.Tick()) |
There was a problem hiding this comment.
Spec criterion #2 not satisfied — the bench never calls View() in its measured loop. BenchmarkSpinnerTickVPView measures m.Update(m.sp.Tick()) only; the vpView cache is never read in the measured region, so the ~546 allocs/94KB captured here is Update dispatch + chrome overhead (header/footer/input re-render via assembleLayout), not the vp.View()-skip delta issue #139 targets. The trailing vpViewValid assertion passes vacuously because nothing in the loop invalidated it.
The bench comment at line 213 ("vpViewCache is served verbatim") is false inside the loop — the cache is neither served nor invalidated in the measured region; the cache write path (vpView re-render on miss) is also never exercised.
Criterion #2 reads: "Steady-state (spinner-only) bench shows allocs/op + B/op drop with a significant benchstat delta." A bench that drives View() per tick (the real per-frame cost the issue profiles — Model.View was 50% of CPU) is what the criterion requires. Suggested fix: add m = m.View() (or a m.rend.vpView(m.vp) call) inside for b.Loop(), or add a second BenchmarkSpinnerTickView bench isolating the View()-only cost so the vp.View()-skip is actually measured.
| r.joinPrefixN = 0 | ||
| r.joinPrefixKey = joinPrefixState{} | ||
| // vpViewValid is NOT cleared here — every resetSession caller calls refreshView() | ||
| // afterwards, which calls invalidateVPView(). Clearing it here would be redundant. |
There was a problem hiding this comment.
Untested invariant — the resetBlockCaches→refreshView ordering coupling the comment makes load-bearing is the one path the per-handler guard doesn't cover. The comment justifies not clearing vpViewValid here by "every resetSession caller calls refreshView() afterwards." Verified true today (the 3 resetSession callers — builtins.go:163, models.go:326, worktrees.go:193 — each follow with refreshView()), but a 4th caller that forgets refreshView leaves vpViewValid=true against a now-empty conversation → View() serves the stale pre-clear string.
TestVPViewInvalidatedByEveryViewportHandler covers the 6 handlers (onResize/onMouseWheel/onScrollKey/scrollLines/snapshotSelection/refreshView) but not the resetSession→resetBlockCaches path — so the one invariant this comment depends on is the one not mutation-tested.
Suggested fix (pick one):
- Clear
vpViewValidinresetBlockCaches(one bool write — cheaper than maintaining the cross-function coupling), or - Add a
TestVPViewInvalidatedOnResetSessionmirroring the per-handler guard (warm the cache, callresetSession, assertvpViewValid==false).
The first is the smaller, more robust change.
| if newWidth < 10 { | ||
| newWidth = 40 | ||
| } | ||
| mm, _ := m.Update(tea.WindowSizeMsg{Width: newWidth, Height: m.height}) |
There was a problem hiding this comment.
Height-resize path untested (spec criterion #4). Issue #139 enumerates "geometry — SetWidth (update.go:779), SetHeight (877)" as cache-key inputs, and criterion #4 requires mutation-testing the resize site. This subtest only varies width (newWidth := m.width / 2; WindowSizeMsg{Width: newWidth, Height: m.height} keeps height constant). Height flows through relayout's conditional refreshView (early-returns on height-equality), so the height path is covered only transitively — incidentally, not the per-site discipline criterion #4 implies.
Edge-correct today (no-op when unchanged), but a future change that makes a height-only resize mutate viewport layout without going through refreshView would serve stale content with no red test.
Suggested: add a height variant to this subtest — WindowSizeMsg{Width: m.width, Height: m.height/2} — asserting vpViewValid==false afterward, to pin the height path explicitly.
) Addresses PR #143 review (maintainer panel): - MUST-FIX: BenchmarkSpinnerTickVPView never called View() in its measured loop — it measured Update dispatch + chrome, not the vp.View()-skip, and the vpViewValid assertion passed vacuously. Now drives the real Update->View per-frame cycle (m.Update(tick) then m.View()), so the measured cost is the cached-View steady-state frame. Proven: ~1,088 allocs/op cached vs ~24,840 un-cached (~23×) — the win the old bench hid. - Clear vpViewValid in resetBlockCaches (defense-in-depth) so the "callers call refreshView() afterwards" ordering is no longer a load-bearing untested invariant; added TestResetBlockCachesInvalidatesVPView (mutation-verified). - Cover the SetHeight/relayout geometry path: new onResizeHeightOnly subtest varies height (the prior test varied width only). - ADR: corrected baseline number + memo-off comparison; added the third bench to the Phase-2 enumeration; noted the win is spinner-tick frames between content flushes (streaming frames still pay the refreshView re-pad by design). Co-Authored-By: Claude Opus 4.8 <[email protected]>
What
Model.View()calledm.vp.View()unconditionally on every Bubble Tea frame. The bubbles viewport re-runs a lipglossWidth().Height().Render(strings.Join(visibleLines, "\n"))per call, re-measuring every grapheme cluster's display width from scratch. During a reasoning turn the footer spinner ticks ~10×/s and each tick forced a full viewport re-pad even though the body was byte-identical frame-to-frame — visible render lag while the model thinks.Live pprof during GLM-5.2 streaming (from #139):
How
A dirty-flag memo (
renderer.vpViewCache/vpViewValid) behind the establishedm.rend *rendererpointer (so it survivesView()'s value-receiver copy ofModel, exactly likeblockCache/joinCache).View()now callsm.rend.vpView(m.vp);invalidateVPView()is called at every site that changes viewport content, scroll offset, or geometry:refreshView,snapshotSelection,scrollLines(on observedYOffsetmovement),onMouseWheel,onScrollKey,onResize. Spinner-only frames serve the cached string and skip the lipgloss pad entirely.Dirty-flag (not key-based) because
vp.View()exposes no cheap stable key; the mutation surface is small and bounded (six handlers), and a drift-guard test enforces that every one invalidates.Acceptance criteria (#139)
vp.View()served from cache on unchanged framesBenchmarkSpinnerTickVPView) — ~546 allocs/op, ~94 KB/op; existing streaming bench untouchedtask test:goldengreen, zero golden diffsengine/surface —api-compatgate untouchedRegression prevention
TestVPViewInvalidatedByEveryViewportHandlerdispatches each viewport-mutating handler and asserts the cache invalidates — deleting any oneinvalidateVPView()call reds exactly that subtest.BenchmarkSpinnerTickVPViewis wired intotask perf:scenarios(the bench regex previously matched onlyBenchmarkScrollbackViewand never ran the new bench in CI) and routed to the advisory render-allocs suite inperfconvert— same posture as thetui_scrollback_view*siblings, which are tooruntime.ReadMemStats-noisy to hard-gate. The trend dashboard surfaces an allocs jump.Review
Ran a three-axis panel (spec / standards / domain: software-architect, code-duplication, ux) — no ship-blockers; all findings (field order, scroll-gate doc note, the drift-guard test, the perf-gate wiring) addressed in iteration 2. The duplication reviewer confirmed the third dirty-flag cache is a Rule-of-Three false positive (the siblings are key-based, this one is flag-based — different correctness models, don't extract).
Closes #139
🤖 Generated with Claude Code