Skip to content

perf(mecatui): release settled answers' markdown from the render cache - #2641

Merged
peppescg merged 1 commit into
mainfrom
perf/2409-settled-markdown-cache
Nov 2, 2026
Merged

peppescg merged 1 commit into
mainfrom
perf/2409-settled-markdown-cache

Conversation

@peppescg

@peppescg peppescg commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

Summary

mecatui's memory grows with every turn and never comes back. Part of the growth is the assistant markdown cache: it kept glamour's output for every answer of the session (~35 KB of ANSI for a ~1 KB answer), next to the whole-block entry that already holds the rendered card.

  • The markdown cache now keeps at most one entry, for the most recently rendered assistant block. Only the final card can still change (AppendAssistant, ReviseAssistant, AppendReasoning and EndReasoningStream all target the last card), so that's the only entry worth keeping; a settled answer is served by its whole-block entry.
  • An answer without a reasoning summary renders the same at either expand state, so its whole-block entry now stays valid across a conversation-detail flip (F9). Without this, dropping the markdown would make F9 re-run glamour for every answer. renderPasses can't make that call up front the way it does for tool cards (whether an answer has reasoning isn't in the block metadata), so the entry declares it and renderedBlock masks the expand axis on the probe; admission is still one key comparison.

Output is byte-identical; no goldens change.

Issue relationship

Relates to #2409. This is point 1 of the proposal. Point 2, bounding the whole-block entries to the viewport, needs the virtualized transcript (#1273); so does the issue's "memory flat after warm-up" criterion.

Type of change

  • Other (describe): performance (memory)

Before | After

Real binary: mecatui connect against mecated serve --mock-script

400 scripted turns of a ~1 KB markdown answer (heading, list, Go fence, table) typed into a real mecatui in tmux at 120×40. Live heap comes from GODEBUG=gctrace=1 (heap after the last GC); RSS from ps. Same mecated binary for both; the reproduction script is at the end.

Turns Live heap, before Live heap, after RSS, before RSS, after
0 16 MB 15 MB 105 MB 103 MB
100 26 MB 21 MB 133 MB 126 MB
200 36 MB 28 MB 154 MB 141 MB
400 52 MB 37 MB 192 MB 161 MB

Growth over 400 turns: live heap +36 MB → +22 MB, RSS +87 MB → +58 MB. The final screens of the two runs are identical apart from the port in the header.

Benchmarks (new, markdown_cache_bench_test.go), benchstat, -count 10, Apple M3 Pro

                           │   before    │                after                 │
                           │   sec/op    │   sec/op     vs base                 │
LongSessionRetainedHeap-12   15.65m ± 1%   15.55m ± 1%         ~ (p=0.190 n=10)
ExpandToggle/plain-12        111.20m ± 2%   19.92m ± 2%   -82.09% (p=0.000 n=10)
ExpandToggle/reasoning-12     117.7m ± 0%   379.2m ± 0%  +222.06% (p=0.000 n=10)

                           │ retained-B/turn │ retained-B/turn  vs base       │
LongSessionRetainedHeap-12      91.25Ki ± 0%      51.32Ki ± 0%  -43.76% (p=0.000 n=10)

                           │    B/op     │     B/op      vs base               │
ExpandToggle/plain-12        148.737Mi ± 0%   4.923Mi ± 0%  -96.69% (p=0.000 n=10)
ExpandToggle/reasoning-12      166.0Mi ± 0%   302.9Mi ± 0%  +82.53% (p=0.000 n=10)

                           │ glamour/op │ glamour/op  vs base │
ExpandToggle/plain-12           0.000        0.000
ExpandToggle/reasoning-12         0.0        200.0

ExpandToggle flips F9 over a 200-turn session; glamour/op counts markdown renders per flip.

The trade-off. A flip over answers that carry a reasoning summary now re-runs glamour for each of them (200 renders above, ~1.3 ms each). That is roughly what a resize already costs, and with models that always emit reasoning it is the common case. The virtualized transcript (#1273) removes it by re-rendering only visible blocks. Answers without reasoning get a flip about 5× cheaper than before.

Test plan

Baseline checks

  • Linting (task lint): 0 issues in the root module and every other module except environment/microvm, where gosec flags launch_ownership_darwin.go:754 (darwin-only, untouched, also reported on origin/main)
  • Fast offline test suite (task test): not run separately; the race suite below is a superset
  • Pre-review race suite (task test:race): cmd/mecatui/ui passes. 28 tests fail locally in untouched packages (cmd/mecated, cmd/mecatui, internal/app, internal/adapter/{forker,server}, internal/executionexecutor, environment/microvm/gitexec, deploy/mecatl-execution-kind); every one of them fails the same way on a clean origin/main checkout. After the review fixes, task lint and go test -race ./cmd/mecatui/... were re-run on the final commits: same lint result, and every cmd/mecatui package passes except the same two root-package tests that fail on origin/main (TestConnectUsesSavedServerCAForLazyTLSRPC, TestStartupCompatibilityEmbeddedRejected)
  • Offline demo (go run ./cmd/mecademo): tool call, permission ask and approval, result

New tests in render_cache_test.go, each checked to fail when the change it guards is reverted:

  • TestSettledAssistantMarkdownIsReleased: after five answers the markdown cache holds one entry, for the tail block. Fails with clear removed (5 entries).
  • TestExpandToggleKeepsAnswersWithoutReasoning: a detail flip re-renders the two prompts and the settled answer with reasoning, not the plain answer; the first flip re-runs glamour exactly once (the released markdown); both directions equal a fresh render. Fails with the invariance disabled (4 re-renders instead of 3).

Changes

File Change
cmd/mecatui/ui/block_cache.go storeMarkdown keeps a single entry; expandInvariant on whole-block entries, masked in renderedBlock; type docs state the rule
cmd/mecatui/ui/render.go Assistant cards without reasoning are expand-invariant; comments updated
cmd/mecatui/ui/render_cache_test.go Two regression tests
cmd/mecatui/ui/markdown_cache_bench_test.go BenchmarkLongSessionRetainedHeap, BenchmarkExpandToggle

User-facing change

Lower memory growth in long sessions. F9 is faster when answers have no reasoning summary, and in long sessions where they do it costs about as much as a resize.

Special notes for reviewers

  • Reviewed with a panel (spec, standards, test adequacy, architecture, reuse, duplication, perf, security) before opening; findings addressed: type docs restated, the flip test now exercises the released-markdown path, benchmarks committed.
  • mecatui: render the streaming answer's markdown incrementally #2410 also edits the markdownAt doc comment, so whichever of the two lands second needs a one-comment rebase. Once both land, the single markdown entry could fold into streamMarkdown, which already tracks the live block (follow-up).
  • Not changed: the single entry stays a map (cleared on store) rather than a struct field, to avoid churn in six existing test assertions.
Reproduction script (real binary)

script.py writes the mock script; run.sh MECATED MECATUI LABEL TURNS OUTDIR drives one binary and appends label,turn,live_heap_MB,rss_MB to OUTDIR/results.csv.

import json, sys

def answer(i):
    items = "\n".join(f"- item {j}: the function now returns an error instead of panicking when the input is empty" for j in range(6))
    return (f"## Result for step {i}\n\nI looked at the **handler** and the `Store` interface. Here is what changed and why it "
            "matters for the rest of the package.\n\n" f"{items}\n\n"
            "```go\nfunc Handle(ctx context.Context, req *Request) (*Response, error) {\n\tif req == nil {\n\t\treturn nil, errEmpty\n\t}\n\treturn &Response{ID: req.ID}, nil\n}\n```\n\n"
            "| file | change | lines |\n|---|---|---|\n| a.go | refactor | 12 |\n| b.go | fix | 3 |\n\n"
            f"The change is small and self-contained. END-OF-ANSWER-{i}\n")

n = int(sys.argv[1])
print(json.dumps({"turns": [{"text": answer(i)} for i in range(1, n + 1)]}))
#!/bin/sh
set -eu
MECATED=$1 MECATUI=$2 LABEL=$3 TURNS=$4 OUT=$5
HERE=$(cd "$(dirname "$0")" && pwd)
WORK=$(mktemp -d "${TMPDIR:-/tmp}/proof2409.XXXXXX")
mkdir -p "$WORK/home" "$WORK/config" "$WORK/data" "$WORK/state" "$WORK/cache" "$WORK/ws" "$OUT"
export HOME="$WORK/home" XDG_CONFIG_HOME="$WORK/config" XDG_DATA_HOME="$WORK/data" \
	XDG_STATE_HOME="$WORK/state" XDG_CACHE_HOME="$WORK/cache"
python3 -I "$HERE/script.py" "$TURNS" >"$WORK/script.json"
PORT=$((18900 + $$ % 50))
SESSION="proof2409-$$"
"$MECATED" serve --mock-script "$WORK/script.json" --grpc-addr "127.0.0.1:$PORT" --http-addr "" \
	--metrics-addr "" --workspace "$WORK/ws" >"$WORK/mecated.log" 2>&1 &
DPID=$!
trap 'tmux kill-session -t "$SESSION" 2>/dev/null || true; kill $DPID 2>/dev/null || true' EXIT
until nc -z 127.0.0.1 "$PORT" 2>/dev/null; do sleep 0.05; done
tmux new-session -d -s "$SESSION" -x 120 -y 40 \
	"cd '$WORK/ws' && GODEBUG=gctrace=1 '$MECATUI' connect 127.0.0.1:$PORT --tls=false 2>'$WORK/gc.log'"
sleep 2
pane() { tmux capture-pane -p -t "$SESSION"; }
UIPID=$(pgrep -n -f "$MECATUI connect 127.0.0.1:$PORT")
record() {
	live=$(grep -E '^gc [0-9]+' "$WORK/gc.log" | tail -1 | sed -E 's/.* ([0-9]+)->([0-9]+)->([0-9]+) MB.*/\3/')
	rss=$(ps -o rss= -p "$UIPID" | tr -d ' ')
	echo "$LABEL,$1,$live,$((rss / 1024))" >>"$OUT/results.csv"
}
record 0
k=1
while [ $k -le "$TURNS" ]; do
	tmux send-keys -t "$SESSION" "question $k" Enter
	until pane | grep -qE "END-OF-ANSWER-$k([^0-9]|$)"; do sleep 0.05; done
	case $k in 25 | 50 | 100 | 150 | 200 | 300 | 400) sleep 1; record $k ;; esac
	k=$((k + 1))
done
pane >"$OUT/final-$LABEL.txt"

Benchmarks: go test ./cmd/mecatui/ui/ -run '^$' -bench LongSessionRetainedHeap -benchtime 300x -benchmem -count 10 and -bench ExpandToggle -benchtime 20x, on this branch and on origin/main with markdown_cache_bench_test.go copied in.

🤖 Generated with Claude Code

The assistant markdown cache kept glamour's output for every answer of the
session next to the whole-block entry that already holds the rendered
card, so memory grew by roughly 35 KB per answer and never came back.

Keep a single markdown entry, for the most recently rendered block: only
the final card can still change, and a settled answer is served by its
whole-block entry. Mark answers without a reasoning summary as
expand-invariant so a conversation-detail flip reuses their entry instead
of re-running glamour for each of them.

Add BenchmarkLongSessionRetainedHeap (retained heap per turn) and
BenchmarkExpandToggle (detail-flip cost with and without reasoning) so the
trade-off can be reproduced.

Refs #2409

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@peppescg peppescg added the tui mecatui terminal UI (rendering, keybindings, footer, panes, scrollback) label Nov 1, 2026
@peppescg peppescg self-assigned this Nov 1, 2026
@peppescg
peppescg merged commit 3a67c2e into main Nov 2, 2026
44 checks passed
@peppescg
peppescg deleted the perf/2409-settled-markdown-cache branch November 2, 2026 08:54
@toolhive-release-app toolhive-release-app Bot mentioned this pull request Nov 18, 2026
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tui mecatui terminal UI (rendering, keybindings, footer, panes, scrollback)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants