Skip to content

mecatui: durable session store, streaming-render perf, turn observability, empty-turn fix (#79–#82) - #85

Merged
JAORMX merged 4 commits into
mainfrom
mecatui-debug-fixes-79-82
Jun 17, 2026
Merged

JAORMX merged 4 commits into
mainfrom
mecatui-debug-fixes-79-82

Conversation

@JAORMX

@JAORMX JAORMX commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

Four fixes from a live debugging session of mecatui (deepseek/deepseek-v4-flash over OpenRouter) that looked stuck but was a long, productive multi-agent run. Each issue went through the dev pipeline (architect → implement → adversarial review panel → iterate → one commit per issue). One commit per issue; all offline tests, -race, lint, and mecademo green.

What's in here

  • 6e91013 → Closes mecatui: persist session + event log by default (durable local store) #79 — durable session + event log by default. mecatui now persists the session conversation + the per-turn EventLog (.events.jsonl: EvResult{stop,usage} / EvNoProgress / EvCompaction) to $XDG_STATE_HOME/mecatui/sessions/<workspace-slug> instead of the in-memory memstore — a black box you can grep after a repro, and the precondition cloud-native Phase-1 rehydration needs. --store-dir override + --no-store opt-out; main-session retention GC (mecatui 720h/200; mecated default-off → byte-unchanged); 0700 + a plaintext-transcript privacy disclosure.

  • 1334ef8 → Closes mecatui: streaming render re-joins whole scrollback every token (O(scrollback) alloc churn, ~475 MB/s / 13 GC/s) #80 — incremental scrollback join. Streaming re-joined the whole scrollback + re-SetContent every token (O(scrollback × token-rate); measured ~475 MB/s, ~13 GC/s at depth). Now caches the settled-block prefix and only re-renders/appends the live suffix, handing the viewport a fresh []string via SetContentLines. Streaming-frame B/op −98.8% (33.4 MB → 383 KB), byte-identical output (goldens unchanged). Prefix invalidation is coupled to the shared renderBlock chokepoint so both render paths stay coherent (the panel caught a path-switch stale-prefix bug here — fixed + regression-tested).

  • 489b9e8 → Closes Observability: surface per-turn stop-reason / usage / stream lifecycle (loop is silent by design) #81 — turn-semantics observability. mecatl_turns_total{role} + mecatl_turn_empty_total{role} on the perf surface, and provider-tagged llmresilience diagnostics (DEBUG retry/per-attempt-timeout; INFO idle-stall / breaker transitions / exhaustion) — abnormal turns are now observable without touching the loop's three-line invariant (metrics + adapter seams are separate).

  • 22a4664 → Closes mecatui: turns end empty/truncated and require a manual re-kick (↑0 ↓0 · 30s → done) #82 — a pre-first-chunk timeout no longer becomes a phantom empty "done". Root cause (found in code): on a large context the model takes >30s to the first chunk; the openai adapter swallows the per-attempt-timeout cancel (yields nothing) and llmresilience.establish treated the empty stream as success — no error, no retry — so the loop nudged it and ended StopNoProgress, rendered as a benign done. Now a deadline-caused empty first-chunk surfaces as a retryable error → StopError with an operator-facing message, never a phantom done. Per-attempt-timeout default 30s→60s (mitigation). The zero-usage ctx-meter corruption is fixed display-only (estimate feeds the meter; the budget brakes stay on provider truth).

Notes for the reviewer

🤖 Generated with Claude Code

JAORMX and others added 4 commits June 17, 2026 16:35
…store)

mecatui now defaults the session/event store to a durable JSONL dir under
$XDG_STATE_HOME/mecatui/sessions/<workspace-slug> instead of the in-memory
memstore, so the conversation snapshot and the per-turn EventLog
(EvResult{stop,usage}/EvNoProgress/EvCompaction sidecar) survive the process —
a black box you can grep after a repro, and the precondition the cloud-native
Phase 1 rehydration path needs. New --store-dir override and --no-store opt-out
(precedence: --no-store -> ephemeral memstore; else explicit; else per-workspace
default), mirroring --memory-dir/--no-memory.

To bound a long-lived local store, add main-session retention by extending the
existing child-session GC: new app.Config.MainRetention + MainRetentionMaxTotal
(zero = disabled, so mecated is byte-unchanged — its new --main-retention /
--main-retention-max-total flags default off). mecatui defaults 720h / 200,
global (not per-family) count cap, oldest-first, live session always skipped on
BOTH the age and cap passes. jsonlstore.New now creates the dir 0700 (raw
transcripts are owner-only on both mains).

Privacy: the EventLog stores already-redacted events, but the SessionStore
persists the RAW conversation (tool args, file contents the agent read, command
output — which can include secrets) in plaintext JSONL; disclosed in --store-dir
help + docs/tui.md + docs/usage.md, with a single-mecatui-per-workspace
concurrency caveat (no cross-process lock; a second instance sharing the dir may
prune the other's idle sessions early).

Tests (offline): store-dir flag/default/precedence, embeddedConfig defaults,
jsonlstore 0700, GC main age-pass + global cap + live-skip on both passes
(mutation-verified) + age-then-cap interaction + disabled-by-default invariant,
and a two-Build e2e proving SessionStore.Load + EventLog.Read round-trip across
a process restart.

Deferred: an in-TUI welcome-splash disclosure line for the store needs new
server->client capability plumbing (the ui renders only from relayed
Capabilities); tracked as a follow-up. Privacy is already disclosed in help+docs.

Closes #79

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ck) per streamed token

The streaming render re-joined the ENTIRE conversation scrollback into a fresh
strings.Builder and re-split it via vp.SetContent on every streamed token: the
live tail block bumped blockRenders each frame, missing the whole-join fast
path, so the cost was O(scrollback-bytes x token-rate). Measured ~475 MB/s /
~13 GC/s during long-text streaming at depth vs ~0.3 MB/s idle (GC pressure, not
a leak), scaling with conversation length.

Cache the joined PREFIX of settled blocks as already-split lines
(joinPrefixLines/joinPrefixN) and only re-render + append the live SUFFIX each
frame, then hand the viewport a fresh []string via SetContentLines instead of
re-splitting a full joined string. Canonical per-block segment framing
(sep(0)="", sep(i>0)="\n", trailing "\n") keeps the output BYTE-IDENTICAL (goldens
regenerate with no diff). The line-slice fast path is gated on
!sel.active && !expandTools; selection/expand frames fall back to the existing
byte-identical SetContent(string) path.

Correctness: prefix invalidation is coupled to the SHARED renderBlock chokepoint
both render paths funnel through — any fresh render of a block covered by the
prefix (idx < joinPrefixN) drops the prefix, so a non-tail mutation during a
string-path frame can never leave a stale prefix for the next lines-path frame
(the path-switch stale-prefix bug the panel caught). Invariant: after any frame
on either path, joinPrefixLines covers exactly [0, joinPrefixN) and no block in
that range has re-rendered since the prefix was built.

Result: streaming-frame ~33.4 MB/op -> ~383 KB/op (-98.8%); the no-mutation
fast path is preserved. Steady (interaction-cadence — keystroke/scroll/overlay,
NOT idle/per-tick) frame B/op +~7% (one fresh line-slice per frame, the price of
a corruption-safe handoff), far below the streaming win.

Scoped out (separate follow-ups): the viewport maxLineWidth re-walk (upstream
bubbles; CPU, allocates nothing) and the ~29.5KB Model value-struct heap-escape
per Update (fights Bubble Tea's value-model contract — a risky refactor, not a
byte-identical perf change).

Tests (offline, byte-identical fresh-renderer oracle): prefix reuse, non-tail
mid-scrollback mutation, multi-block-in-one-frame (firstChanged=min),
width/expand drop, reset/index-aliasing, the path-switch stale-prefix regression
(fails pre-fix), the SetContentLines-vs-SetContent gate (selection + expand),
and alloc tripwires for both the O(suffix) streaming win and the steady-frame
ceiling. Mutation-verified.

Closes #80

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…(debuggable abnormal turns)

When a turn ends empty/truncated or stops early, the loop is silent by design
(the three-line invariant) and the rich signal (StopReason, EvNoProgress,
EvResult.Usage) is client-only/transient — so an abnormal turn left no durable
or live trace. Add turn-semantics observability WITHOUT touching the loop's
three-line budget, using the separate telemetry (EventSink) and adapter
(port.Diagnostics) seams.

Metrics (internal/adapter/telemetry, surfaced via the perf MCP):
- mecatl_turns_total{role} — every completed turn (the per-turn denominator),
  on EvTurnEnd. NOT stop-labelled: EvTurnEnd carries no stop and abnormal
  terminals already ride the existing runs_total{stop}, so a stop label would
  be dead/misleading.
- mecatl_turn_empty_total{role} — empty/no-progress turns, on EvNoProgress.
  Empty turns are a SUBSET of completed turns (a turn fires EvTurnEnd then
  EvNoProgress), so turn_empty_total/turns_total is the empty-turn SHARE; the
  counter tracks EvNoProgress emissions (advisory nudges + give-up, up to
  MaxNoProgressNudges+1 per stuck sequence). Both added to the mcpperf curated
  set + by_role breakdown. stop/role are closed enums — no cardinality leak.

Resilience diagnostics (internal/adapter/llmresilience) via a new optional
Config.Diagnostics port.Diagnostics (nil -> Nop; an ADAPTER seam, outside the
loop's three-line budget; logs via the injected sink, never slog): DEBUG on
retry + per-attempt-timeout; INFO on idle-stall ("stream stalled (idle
timeout)" — the decisive model-silent-vs-upstream-stall signal for #82),
circuit-breaker open/half-open/closed transitions, and establish exhaustion.
Each line is provider-tagged (cfg.diag().With("provider", id) at both Wrap
sites). A failed half-open trial that re-opens the breaker now emits (was
silently swallowed). clampErr trims on a rune boundary.

TUI: footer already surfaces the stop reason; added a structured_output case
("stopped · schema unmet") so no raw underscore'd token leaks, plus an
end-to-end ResultMsg->footer regression test.

Tests (offline): turn/empty counters with asserted labels incl. the realistic
EvTurnEnd+EvNoProgress pair (the subset relationship) and role-scoping; the
resilience retry/per-attempt-timeout/idle-stall/breaker-open/re-open/closed/
exhaustion lines with asserted level+fields+provider tag, the nil-Diagnostics
safe path, and the backoff arg; breaker exactly-once is mutation-killing.

Deferred (follow-ups): stream-lifecycle DEBUG in the openai/anthropic Provider
(no Diagnostics seam there yet — larger change) and a --debug-events live tail
(overlaps the existing port.EventLog seam).

Closes #81

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…mpty "done"

Root cause of the "turns end empty (↑0 ↓0 · 30s → done), I have to re-kick"
report: on a large context the HTTP request connects fast but the model takes
longer than the 30s per-attempt timeout to emit the first chunk. The openai
adapter swallows the resulting ctx-cancel (yields nothing), and
llmresilience.establish treated that empty stream as a SUCCESS — no error, no
retry, breaker untouched — so the loop saw an empty turn, nudged it, and ended
cleanly with StopNoProgress, rendered as a benign "done". The 30s == the
per-attempt timeout; the ↑0 ↓0 == no usage. The timeout was being laundered
into a fake empty completion.

Fix C (root): in establish's empty-stream branch, if the first-chunk pull ended
because the per-attempt context hit DeadlineExceeded (captured pre-cancel) AND
the caller ctx is not done, return a retryable establishment failure instead of
a phantom empty success. It then routes through the existing retry/classifier/
breaker path and, after MaxAttempts, surfaces as ExhaustedError -> StopError —
an honest, diagnosable error, never a phantom "done". A genuinely empty stream
(no deadline) keeps the unchanged empty-success path. Still pre-first-chunk, so
no-replay holds. The error string is now operator-facing ("the model did not
start responding within the per-attempt timeout (Ns), across N attempts. Try
resending, switching to a faster model, or raising --llm-per-attempt-timeout.")
— no package-name/jargon leak.

Fix B (mitigation, not the fix): raise the per-attempt-timeout default 30s -> 60s
(it covers establishment + the first chunk; large-context reasoning models can
exceed 30s to first token). With Fix C even a too-low value now fails honestly.

Fix A (the ctx-meter sub-bug): when a turn reports zero InputTokens but the
conversation is non-empty, the footer context meter read 0%/0-of-window. The
engine now fills a DISPLAY-ONLY estimate (TokenCounter.CountMessages) into the
EvTurnEnd payload (flagged TurnEnd.Estimated), while RecordUsage / the cumulative
sess.Usage / EvResult / the MaxRunTokens+MaxTeamTokens budget brakes stay on the
provider's ACTUAL usage — the estimate is a heuristic, wrong as a spend-budget
unit. Plus a UI belt-and-braces: the meter only overwrites on a non-zero turn
(sticky otherwise). The estimated meter figure is documented in docs/tui.md.

Tests (offline): Fix C retry/exhaust/breaker + operator-message assertions + the
genuinely-empty negative guard; a loop-level e2e (a swallow-on-cancel provider
wrapped by llmresilience.Wrap drives Engine.Run to StopError, NOT the phantom
StopNoProgress — the #82 regression guard, fails if Fix C is reverted); the
display-only split (EvTurnEnd estimate vs provider-truth budget) + the
empty-conversation boundary guard. The restored TestTeamTokenBudgetZeroUsageNeverTrips
proves the budget brake still ignores usage-less turns.

Live verification (deferred to a real run, per the issue): on deepseek-v4-flash
over OpenRouter with a large context, a dead turn now shows the per-attempt-
timeout/exhausted resilience INFO lines (#81) + StopError, and turn_empty_total
(#81) / the .events.jsonl black box (#79) confirm the path.

Closes #82

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@JAORMX
JAORMX merged commit 718b7b8 into main Jun 17, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment