Skip to content

perf(mecatui): memoize vp.View() to skip lipgloss re-pad on spinner-only frames (#139) - #143

Merged
JAORMX merged 3 commits into
mainfrom
worktree-issue-139
Jun 22, 2026
Merged

JAORMX merged 3 commits into
mainfrom
worktree-issue-139

Conversation

@JAORMX

@JAORMX JAORMX commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

What

Model.View() called m.vp.View() unconditionally on every Bubble Tea frame. The bubbles viewport re-runs a lipgloss Width().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):

1.31s 50.00%  Model.View
1.16s 44.27%    viewport.Model.View   (lipgloss.Render(Join(visibleLines)))
0.71s 27.10%      lipgloss.Wrap
0.60s 22.90%      ansi.stringWidth

How

A dirty-flag memo (renderer.vpViewCache / vpViewValid) behind the established m.rend *renderer pointer (so it survives View()'s value-receiver copy of Model, exactly like blockCache/joinCache). View() now calls m.rend.vpView(m.vp); invalidateVPView() is called at every site that changes viewport content, scroll offset, or geometry: refreshView, snapshotSelection, scrollLines (on observed YOffset movement), 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 frames
  • Steady-state bench (BenchmarkSpinnerTickVPView) — ~546 allocs/op, ~94 KB/op; existing streaming bench untouched
  • Byte-identical output — task test:golden green, zero golden diffs
  • Cache invalidation mutation-tested (positive+negative pairs for content/scroll/geometry, plus a per-handler invariant test proven to red on each deleted call)
  • No new exported engine/ surface — api-compat gate untouched

Regression prevention

  • Correctness (stale render): TestVPViewInvalidatedByEveryViewportHandler dispatches each viewport-mutating handler and asserts the cache invalidates — deleting any one invalidateVPView() call reds exactly that subtest.
  • Perf (memo silently stops hitting): BenchmarkSpinnerTickVPView is wired into task perf:scenarios (the bench regex previously matched only BenchmarkScrollbackView and never ran the new bench in CI) and routed to the advisory render-allocs suite in perfconvert — same posture as the tui_scrollback_view* siblings, which are too runtime.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

JAORMX and others added 2 commits June 22, 2026 12:08
…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]>
@JAORMX
JAORMX force-pushed the worktree-issue-139 branch from b57da55 to 46c9145 Compare June 22, 2026 09:19

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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. BenchmarkSpinnerTickVPView never calls View() in its measured loop (for b.Loop() → only m.Update(m.sp.Tick())), so the vpView cache is never read in the measured region. The ~546 allocs/94KB captures Update dispatch + chrome overhead, not the vp.View()-skip delta the issue targets. The trailing vpViewValid assertion passes vacuously. The bench comment ("vpViewCache is served verbatim") is false inside the loop. A bench that drives View() per tick (or a second bench isolating the View()-only cost) is what criterion #2 requires.
  • [Missing] Height-resize path untested. Spec enumerates SetHeight (update.go:877) as a geometry invalidation site. onResize only varies width; height flows through relayout's conditional refreshView (early-returns on height-equality). TestVPViewInvalidatedByEveryViewportHandler/onResize only 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/kpi stdlib-only, the advisory-vs-gated perf posture, and the Markdown workflow (llms.txt regenerated).
  • [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 to docs/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/refreshView ordering coupling is an untested invariant — render.go:318. The comment justifies not clearing vpViewValid by "every resetSession caller calls refreshView() afterwards." Verified true today (3 callers), but a 4th caller that forgets refreshView leaves vpViewValid=true against 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: clear vpViewValid in resetBlockCaches (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); a Cache[K,V] generic fits none without contorting the key contract. The new vpViewCache is 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; vpView inverts 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/renderInput in assembleLayout), so caching the viewport body never freezes the spinner. Selection-drag paths all route through snapshotSelection (invalidates). Resize ordering is safe: onResize invalidates after SetWidth; relayout's height-guard short-circuit still leaves the cache invalidated. Byte-identical output (golden-green) is consistent with the code: vpView returns vp.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, the renderTickMsg (~16ms) fires far more often than the ~100ms spinner tick and re-warms the cache via refreshView→invalidate. The bench doesn't capture that interleaving. Consider a one-line ADR note that the real streaming frame also pays the refreshView re-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 JAORMX left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

panel-review inline comments

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three inline review comments from the panel review — all low-severity / non-blocking:

  1. scrollback_bench_test.go:217 — the bench loop never calls View(), so it doesn't measure the vp.View()-skip allocs/op drop spec criterion #2 requires (it measures Update dispatch + chrome overhead instead).
  2. render.go:319 — the resetBlockCaches→refreshView ordering coupling is an untested invariant; clear vpViewValid in resetBlockCaches or add a resetSession guard test.
  3. render_cache_test.go:1377 — the onResize subtest 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())

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread cmd/mecatui/ui/render.go Outdated
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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 vpViewValid in resetBlockCaches (one bool write — cheaper than maintaining the cross-function coupling), or
  • Add a TestVPViewInvalidatedOnResetSession mirroring the per-handler guard (warm the cache, call resetSession, assert vpViewValid==false).

The first is the smaller, more robust change.

if newWidth < 10 {
newWidth = 40
}
mm, _ := m.Update(tea.WindowSizeMsg{Width: newWidth, Height: m.height})

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@JAORMX
JAORMX merged commit 09d37eb into main Jun 22, 2026
12 checks passed
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.

mecatui: memoize m.vp.View() — viewport re-pads (lipgloss grapheme-width measure) on every frame, incl. spinner-only frames during a think

1 participant