Skip to content

Free terminal GPU memory on Mac when the glyph cache grows large - #43465

Merged
brennanb2025 merged 40 commits into
stablyai:mainfrom
atharv2309-commits:fix/webgl-atlas-memory-rebuild
Nov 23, 2026
Merged

brennanb2025 merged 40 commits into
stablyai:mainfrom
atharv2309-commits:fix/webgl-atlas-memory-rebuild

Conversation

@atharv2309-commits

@atharv2309-commits atharv2309-commits commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Before: on a Mac, the app's GPU memory kept growing during long or very colorful terminal sessions, sometimes past 6 GB. It only came back down if you turned GPU acceleration off and on again.

Now: when one of the terminal's glyph sheets gets very large, the app waits for a quiet moment (the output pauses and you stop typing or clicking) and then quietly recreates the terminals' GPU drawing surfaces for that sheet, one per screen refresh. That gives the memory back, and the terminals look the same.

What Changed

What users see. On desktop macOS, GPU memory comes back down after heavy terminal output instead of piling up. Normal output never triggers it. After very heavy, constantly changing colored output (for example, a flood of random CJK and emoji in 256 colors), the affected terminals are recreated at most once a minute, and only once that output has paused for 2 s and the user has stopped typing, clicking, scrolling or dragging for 2 s. Output that never pauses keeps its memory until it does, as before this change. Windows, Linux and touch devices are unchanged.

How it works.

  • Trigger. The WebGL addon reports when its shared glyph atlas adds a page. A 4096² page means the atlas has reached about 64 MiB. When that happens and real terminal output has been parsed into that atlas, the renderers that share it are scheduled for a rebuild. Only atlases with fresh output qualify, so repaints, idle warm-up, reveals and empty parse barriers never trigger one.
  • Rebuild. The grown atlas is emptied in place, then every renderer that shares it is recreated through one queue, one context per frame (dispose and attach in the same task, then an immediate paint), so no frame pays for more than one context and a shown pane never drops to the slower renderer. Destroying each old context frees what it retained. Hidden tabs, collapsed splits and chat-covered panes just drop their context and get a new one when shown; a chat cover reattaches its pane when it closes.
  • Timing.
    • Attempts are at least 60 seconds apart.
    • An atlas waits until output into it has paused for 2 s and user input (keys, clicks, wheel, held-pointer drags, focus changes, clicks in an embedded browser page) has stopped for 2 s. Input during a rebuild holds its remaining steps.
    • Nothing runs while the window is hidden, another app has focus, or focus is inside an embedded browser page; it resumes when the window is back, with no polling.
    • A visible pane in the middle of a synchronized-output frame delays its atlas's rebuild (eight 250 ms retries, then it waits for new output), and in the queue it moves behind ready panes for up to 10 s.
    • Replacement canvases are painted immediately, so nothing goes blank.
  • Bookkeeping. Atlas owners are indexed, and each attempt checks only the affected panes. The work per output chunk is constant.
  • Scope. macOS only, because it is the only platform where the retained memory was measured. Elsewhere, recreating many contexts at once can exhaust the driver's context budget.

Why

On Apple GPUs, each terminal's WebGL context keeps the memory from its glyph-atlas uploads until the context is destroyed. Shrinking or clearing the atlas frees none of it:

  • In one measurement, shrinking the atlas from 388 MB to 8 MB released 0 MB of GPU memory.
  • Recreating the contexts released about 10 GB.

So recreating the contexts is the only lever available at this layer. A glyph atlas that doesn't depend on color would avoid the growth altogether, but that would mean rewriting the WebGL renderer.

The original version rebuilt every renderer on every 4096² page. Under sustained heavy output that meant a rebuild every 4–5 s, and paths other than output could re-trigger it. The follow-up commits:

  • arm rebuilds only from parsed output, wait for output and input to pause, and space attempts at least 60 seconds apart (a 10 s cadence stalled typing and frames under sustained output on the M4 MacBook Air);
  • clear the atlas in place and recreate one context per frame instead of all at once (one 300-370 ms frame before);
  • park while the window is hidden or unfocused;
  • limit each rebuild to the panes that share the grown atlas;
  • keep off-screen panes detached;
  • limit the trigger to macOS.

Linked Issue

Fixes #43464

Visual Proof

No visual change is intended: terminals should look the same before and after a rebuild. Glyph checks after rebuilds (long output and scrollback, emoji, CJK, ligatures, bold and italic, font size, theme, resize, pixel-ratio change, 12 terminals, hidden tabs, selection) and their before/after screenshots are in the latest status comment; every before/after diff of the reference block was 0.000%.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below
  • Every added test fails without this change and avoids the test anti-patterns

Platforms tested:

  • macOS: M4 MacBook Air and an Apple Silicon MacBook Pro, each running an isolated production build.
  • Windows and Linux: not run; the trigger is off there. Lint, typecheck and unit tests pass on Linux.
  • Remote and SSH output: goes through the same client-side renderer path.

GPU memory on the M4 MacBook Air, head f3bbeb2, 2 visible panes (production build):

Run Rebuilds GPU process
Heavy colored bursts (8 s on, 3 s off) at 300 lines/s per pane, 150 s 3, each in a pause, 66 s apart 3.4–3.7 GB before each rebuild, 1.2–1.4 GB after, about 540 MB once idle
60 s of non-stop heavy output 0 while it ran, 1 at 1.9 s after it stopped 3,841 MB → 541 MB
Bursts faster than the terminal can draw (about 1.3k lines/s per pane) 1, after the stream ended (the renderer never saw a pause) 4,474 MB peak → 547 MB
60 s of realistic output (colored diffs, test logs) 0, 0 long tasks 708 MB peak
  • Typing: keystroke echo p50/p95 was 10.2/19.6 ms when quiet and 10.5/17.4 ms with a rebuild due. Rebuilds ran 2.0 s after the last keystroke and 1.9 s after a drag ended, never during either.

  • Frames: the longest frame within 1 s of a rebuild was 167–243 ms, below the 472–533 ms frames the flood itself causes.

  • Larger scale (earlier runs): main reached 7,055–11,264 MB with 6 workspaces × 2 panes. The Apple Silicon MacBook Pro run on 782115b went from 7,757 MB to 251–495 MB.

  • Automated: the perf contracts terminal-webgl-atlas-memory-rebuild.performance.test.ts and pane-webgl-reattach.performance.test.ts cover:

    • output gating, the output and input quiet windows, and the 60 s spacing;
    • parking while hidden, unfocused or in an embedded page;
    • scoping to the grown atlas, including after a font or zoom atlas swap;
    • the synchronized-output retry budget;
    • on-screen and chat-cover rules;
    • visits only the due atlas's owners;
    • one context per frame, with each queued pane checked at most once per frame at 300 and 3,000 entries;
    • a synchronized frame that never closes stops retrying;
    • the platform gate.

    check:changed passes, and CI is green.

  • Earlier measurements by the original author, on v1.4.261 vs. the first version of this branch: 2,101 MB vs. 419 MB after 60 s of heavy output in 2 panes. The author's daily app reached 6,333 MB after about 17 h, and fell to 377 MB after turning GPU acceleration off and on.

Performance

Adds constant work per parsed output chunk (one atlas lookup and a timestamp) and per input event (a timestamp), plus one shared timer while an atlas is due; nothing scans all terminals. A rebuild runs at most once a minute, only after output and input pause, and recreates one WebGL context per frame. The trade-off: under output that never pauses the memory stays until it does, so a rebuild never competes with typing or a busy terminal. Measured on the M4 MacBook Air (numbers below and in the status comments); the work counts are pinned by the two perf contracts.

Risk

Level: Medium

  • Riskiest part: recreating WebGL renderers automatically while output is flowing.
    • If it went wrong, users would see a pane repaint, briefly fall back to the slower non-GPU renderer, or stall.
    • It is bounded: at most once a minute, only for atlases that reached a 4096² page and received new output, only once output and input have paused, one context per frame, and only on desktop macOS.
  • Hidden and chat-covered panes: they stay on the non-GPU renderer until shown. Reveal, fit and cover-close paths reattach them.
  • Limitation: output that never pauses for 2 s (a continuous flood) keeps its GPU memory until it pauses, as without this change. That is deliberate: rebuilding during sustained output stalled typing and frames.
  • Not affected: no settings, saved data, PTY lifecycle or remote protocol changes.
  • Back out: a plain revert.

AI Disclosure

Investigation, repro harness, and patch by Claude (Opus 5.5) in Claude Code, reviewed by me before submission. Maintainer follow-up commits were made with AI assistance and reviewed through the maintainers' review loop.

Review

Maintainer review status, perf scan and regression audit are in the PR comments.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

… 4096² page

The shared atlas can grow to 16 pages of 4096² and each pane's WebGL context
keeps GPU memory from uploading it until the context is destroyed, so long
sessions pinned GBs in the GPU process. Recreate renderers when a 4096² page
is merged, reusing rebuildAllTerminalWebglRenderers.
@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The change adds macOS desktop WebGL atlas-memory tracking. It tracks attached panes by shared glyph atlas and schedules a rebuild when an atlas reports a 4096-pixel-wide page and receives PTY output. Rebuild attempts are at least 10 seconds apart. Synchronized output can defer an atlas for up to six retries. The renderer coordinates detachment, selective reattachment, and immediate replacement-canvas painting. Visibility tracking and tests cover pane selection, timing, retries, and platform exclusions.

Severity of issue fixed: Medium

Merge Risk: Low · up to 78211

This change rebuilds terminal WebGL renderers when the glyph atlas grows large, to curb GPU memory growth on macOS. Two minor edge cases remain: in some situations the memory-recovery rebuild may not re-trigger until the pane receives more output. The risk is low and bounded.

Pre-merge checks: Passed 4

Check name Status Explanation
Linked Issues check Passed [#43464] The issue requires that per-context WebGL memory from glyph-atlas uploads be released on macOS Apple Silicon, so the GPU process stops growing to several GB. At head 782115b, handleTerminalWe…
Out of Scope Changes check Passed All changed files serve the atlas-memory rebuild trigger for #43464. terminal-webgl-atlas-memory-rebuild.ts implements the trigger, gating, spacing, output re-arm, synchronized-output retry, and owner…
Title check Passed The title names the main change: freeing terminal GPU memory on Mac when the glyph cache (glyph atlas) grows large. The changeset adds a macOS-only atlas-page trigger that recreates WebGL renderers to…
Description check Passed The description is detailed and covers the problem, mechanism, rationale, linked issue, testing, performance, and risk. It has a clear ELI5 and a Risk section with level and backout. Several template …
Full details: Linked Issues check

Explanation

[#43464] The issue requires that per-context WebGL memory from glyph-atlas uploads be released on macOS Apple Silicon, so the GPU process stops growing to several GB. At head 782115b, handleTerminalWebglAtlasPage in terminal-webgl-atlas-memory-rebuild.ts marks an atlas due only when a merged page has width exactly 4096 and PTY output has reached that atlas. rebuildDueAtlases then calls rebuildPanes with every attached owner of the due atlas. Owners detach before any reattach. Shown panes reattach now. Hidden panes reattach on visibility. Chat-covered panes stay detached until the cover releases them. This is the existing context-recreate path that releases the memory. The platform gate (navigator.userAgent includes 'Macintosh' and maxTouchPoints not positive) covers the reported platform. The 10 s spacing, the output-based re-arm, and the synchronized-output retry limit when the release runs. They do not prevent it for the reported workload. No non-coding requirements exist in the issue. Limits: the performance test file and the pane-webgl-renderer and reattach hunks were not read. The footprint figures are author-reported and were not re-run.

Full details: Out of Scope Changes check

Explanation

All changed files serve the atlas-memory rebuild trigger for #43464. terminal-webgl-atlas-memory-rebuild.ts implements the trigger, gating, spacing, output re-arm, synchronized-output retry, and owner indexing. pane-webgl-renderer.ts wires the atlas page handler, output tracking, and cleanup on dispose and attach failure. pane-manager-registry.ts and pane-manager.ts track visible managers, which the rebuild uses to select shown panes. pane-webgl-reattach.ts adds the shouldReattach option, the rebuilder registration, and the replacement paint. terminal-render-pause-release.ts adds paintReplacementCanvasNow for that repaint. pane-terminal-output-scheduler.ts records PTY output for re-arming. NativeChatPaneCover.tsx and restoreWebglAfterChatCover handle panes the rebuild leaves detached under a chat cover, which is a direct side effect of the rebuild. The performance test file covers these rules. The PR reports no vendored-patch, lockfile, or private-field changes. Limits: the test file and some changed hunks were not read directly, so this relies on the summary and the trigger file.

Full details: Title check

Explanation

The title names the main change: freeing terminal GPU memory on Mac when the glyph cache (glyph atlas) grows large. The changeset adds a macOS-only atlas-page trigger that recreates WebGL renderers to release that memory, so the title is directly related to the primary change.

Full details: Description check

Explanation

The description is detailed and covers the problem, mechanism, rationale, linked issue, testing, performance, and risk. It has a clear ELI5 and a Risk section with level and backout. Several template items are weak or missing. The Visual Proof section gives no attached before/after media in the description and points to a status comment instead. The AI Disclosure section is filled in. The Review and Notes sections are generic. The Performance section is present and substantive. The Testing checklist is checked, and platform coverage is stated. Overall the description is mostly complete, so the check passes.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 53df5dde-af6d-44d8-a549-307694986ab1
Commits

Reviewing files that changed from the base of the PR and between 7d58f76 and 782115b.

Files selected for processing: 6

  • src/renderer/src/components/terminal-pane/chat/NativeChatPaneCover.tsx
  • src/renderer/src/lib/pane-manager/pane-manager-registry.ts
  • src/renderer/src/lib/pane-manager/pane-manager.ts
  • src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-reattach.ts
  • src/renderer/src/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-memory-rebuild.performance.test.ts
  • src/renderer/src/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-memory-rebuild.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 623b7369-77e1-49b8-8b07-a2ae11111934
Commits

Reviewing files that changed from the base of the PR and between 65c84d4 and 19b3678.

Files selected for processing: 1

  • src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-renderer.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

A dense static screen could refill the fresh atlas past a 4096² page on
repaint alone and re-trigger the rebuild every frame. Ignore atlas-page
events until two frames after the rebuild, so only later output re-arms it.
@atharv2309-commits

Copy link
Copy Markdown
Contributor Author

@nwparker This follows up your #39715. On v1.4.261, the GPU process still reaches about 6 GB on Apple Silicon (details in #43464). CI did not start because I am a first-time contributor. Could you approve the workflow run? Thanks!

Rebuild at most once per 10 s and only after new terminal output, so repaints,
idle warm-up and reveals cannot re-trigger it. Limit it to macOS, where the
retained per-context memory was measured.
Release a pane's watcher when its WebGL renderer is disposed, and trigger only on
4096 merged pages, not the oversized-glyph page a rebuild cannot free.
Count output parsed before the large atlas page appears, so a finished burst still
re-arms the rebuild, and keep the gate to desktop macOS.
@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks for this. I pushed a few commits on top and merged main:

  • Rebuilds are at least 10 s apart, and after a rebuild they re-arm only once a terminal has parsed new output. Repaints, idle glyph warm-up and revealing a hidden pane can no longer trigger another one.
  • The trigger is limited to desktop macOS, the only platform where the retained memory was measured.
  • Only 4096² merged pages count. The oversized-glyph page is excluded because a rebuild can't free it.
  • Each renderer's output watcher is released when its WebGL renderer is disposed.
  • Added a perf contract for the spacing and the re-arm rule.

Rebuild only the panes whose renderer uses the atlas that grew, count output by
cursor movement so empty parse barriers can't re-arm it, and wait for a
synchronized-output frame to finish before repainting.
Count real PTY output per atlas from the output scheduler instead of cursor
movement, so steady scrolling output keeps re-arming and one atlas's output
never rebuilds another. Cap the synchronized-frame wait at 1 s.
Hidden panes sharing the grown atlas still detach, so the atlas retires, but
reattach on reveal through the existing fit path instead of immediately. A visible
synchronized-output frame defers only its own atlas until that atlas's next
output, with no retry timer.
…uild attempts

Reattach only panes that are actually rendered (expanded-split siblings heal on their
next fit). Space every rebuild attempt, deferred or not, at least 10 s apart, and
let a deferred atlas retry on its own a bounded number of times.
Detach the grown atlas's owners directly instead of walking every manager, and
reattach (or let a synchronized frame defer) only panes that are actually on
screen: window shown, tab shown, pane laid out. Count deferred retries per atlas.
@atharv2309-commits

Copy link
Copy Markdown
Contributor Author

@brennanb2025 Thanks for taking this further. Re-arming on output and the 10 s spacing are a cleaner guard than my two-frame window. Limiting it to macOS and to exact 4096² pages also makes sense. I appreciate the help!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: fe7ad17d-8f3e-4e47-ba44-4db3494e6d54
Commits

Reviewing files that changed from the base of the PR and between 85552a5 and 7d58f76.

Files selected for processing: 8

  • src/renderer/src/lib/pane-manager/pane-manager-registry.ts
  • src/renderer/src/lib/pane-manager/pane-manager.ts
  • src/renderer/src/lib/pane-manager/terminal-output/pane-terminal-output-scheduler.ts
  • src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-reattach.ts
  • src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-renderer.ts
  • src/renderer/src/lib/pane-manager/terminal-rendering/terminal-render-pause-release.ts
  • src/renderer/src/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-memory-rebuild.performance.test.ts
  • src/renderer/src/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-memory-rebuild.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@brennanb2025

Copy link
Copy Markdown
Contributor

Perf scan (fresh reviewer, full perf-scan on head 782115b merged onto main bc9f02f)

Reviewed audit merge 6dc6e7c against main bc9f02fd, incorporating PR head 782115b2, plus the supplied xterm dependency sources. Verdict: clean on source-proven work counts. No edits, builds, installs, tests or posts performed; GPU latency and memory savings remain unmeasured.

All added runtime work runs on the renderer thread. Let H be attached owners of due atlases, V visible managers and S on-screen, uncovered owners eligible for reattachment.

Added work Trigger, population and bound
Per-write output hook Every nonempty scheduler write, including PTY output and notices. One terminal lookup, atlas-identity check and bounded map/set operations; no terminal inventory or payload scan. At 300 terminals × 10 writes/s: 3,000 hooks/s; at 10× population: 30,000. Each hook remains O(1); detached/non-Mac terminals return after lookup.
Owner bookkeeping WebGL attach/detach updates one pane’s ownership; atlas changes enqueue one microtask per event. Page-add events fan out to that atlas’s owners, each doing O(1) indexing. Only exact 4096-wide pages on desktop Mac qualify.
Scheduling and deferred retries One shared timer; attempts ≥10 seconds apart. A synchronized-output frame permits six autonomous retries after the initial attempt, then waits for output into that atlas. Other atlases cannot re-arm it. Each attempt visits only due owners.
On-screen scan Each attempt copies/checks H owners. Synchronized-output admission and reattachment selection each perform at most H visibility checks, each scanning ≤V manager roots: O(HV), with ≤2H rectangle reads and cover queries. Hidden managers are excluded; a hidden window skips DOM visibility checks. Reads precede detach mutations.
Rebuild One qualifying batch disposes H addons/contexts, including hidden owners needed to retire the shared atlas. xterm installs H fallback DOM renderers. Only S eligible owners construct replacement WebGL renderers and synchronously repaint their viewports; hidden owners remain detached. Cost includes DOM rows, shader/buffer/texture setup and visible-cell rasterization/upload. At most one batch per ten seconds; recurrence requires new atlas growth and output.
Cover restoration and cleanup Cover cleanup consumes one weak-map entry and can reattach one shown, connected pane. Close, suspension and attach failure untrack ownership; ownerless atlases leave the due set. One diagnostic is emitted per nonempty rebuild batch.

The dependency’s array-based atlas-owner cache adds quadratic lookup/compaction during cohort disposal. This predates the span but gains a new caller. At the configured 128 live-context ceiling, a conservative bound is approximately 16,384 owner-element visits/moves per batch, unchanged with 300 versus 3,000 live terminals; 128 fallback renderers remain a separate cost. This is not a confirmed scaling defect. Context-loss transients and actual rebuild duration were not measured.

Steady-idle wakeups attributable to this change are 0/s before and after once pending recovery settles. A deferred recovery episode adds at most seven attempts without further output.

Six-question disposition:

  1. Admission: checked; no per-write construction or global scan.
  2. Ownership: checked; per-atlas indexing and one timer prevent duplicate coordinator work.
  3. Thread/storage: checked; synchronous renderer/GPU work, no new main-process, storage, subprocess or network work.
  4. Growth/progress: checked; retries terminate, and fresh output can resume recovery.
  5. Hosts: Mac-only rebuild gate inspected; remote PTY sources use the same local renderer route. Windows/Linux/touch Apple devices skip recovery.
  6. Obsolescence: checked; teardown removes strong ownership, hidden panes avoid replacement contexts, weak bookkeeping permits collection.

Touched regression classes—hot-path rescans, polling/idle wakeups, hidden-owner work, lifecycle retention, fanout and newly reachable expensive work—were inspected with the bounds above; none established a blocker. The performance test was read, not executed; its mocked rebuilder does not validate real teardown, repaint cost or GPU release. Ancillary terminal-reliability skill was unavailable at the referenced path.

@brennanb2025

Copy link
Copy Markdown
Contributor

Status: ready for review at 782115b

Problem: on macOS, every terminal's WebGL context keeps the GPU memory from glyph-atlas uploads until the context is destroyed. Clearing the atlas frees none of it. Heavy colored output took the GPU process to 7–11 GB.

What changes for users (desktop macOS only; Windows, Linux and touch devices are unchanged):

  • When a shared glyph atlas reaches a 4096² page and PTY output has reached that atlas, the renderers that share it are recreated, which frees the memory.
  • Rebuilds are at least 10 s apart.
  • On-screen panes repaint on a fresh canvas straight away. Hidden, collapsed and chat-covered panes get WebGL back when shown.
  • A visible pane in the middle of a synchronized-output frame delays the rebuild.

Added on top of the original change:

  • Output-based re-arm: only real PTY output into the grown atlas re-arms it.
  • Atlas owner index, so rebuilds touch only that atlas's panes.
  • Visibility handling: on-screen checks per pane (stale-visibility aware), and the chat-cover restore.
  • Immediate replacement paint that keeps the selection redraw.
  • Bounded synchronized-output retries.
  • A perf contract (terminal-webgl-atlas-memory-rebuild.performance.test.ts, 14 cases).

Deferred (P2, none blocking):

  • Check the sync-mode flag before the visibility check.
  • Closing a tab right after a rebuild can create one throwaway context.
  • A chat-covered pane draws its output on the DOM renderer until its cover closes.
  • No test for the cover-unmount restore.
  • If a rebuild runs while the window is hidden and a frame is still open on reveal, the pane can show it half drawn.

Verified on 782115b25d0f37fbfbad4a37d154645c5310927f:

  • Typecheck, check:changed and perf contract (14/14) pass.
  • CI is green.
  • Fresh blinded regression audit: SAFE.
  • Fresh review: CLEAN.
  • Perf scan: clean (comment above).

macOS run (one isolated production build of this head, 6 worktrees × 2 panes):

Step GPU process IOAccelerator WebGL contexts
Heavy colored output written straight into xterm, which bypasses the PTY path, so nothing rebuilds (as before this change) 7,757 MB 7,048 MB 6
Then 25 s of heavy output through real PTYs 495 MB 63 MB 2
60 s of heavy PTY output in the 2 visible panes 251 MB after, 2,275 MB sampled peak 37 MB after 2
60 s of realistic PTY output (colored diffs) 291 MB 37 MB 2
  • Heavy output: 6 rebuilds in 60 s, one per 10 s. The longest renderer task was 428 ms; that output keeps the renderer saturated on its own.
  • Realistic output: 0 rebuilds and 0 long tasks.
  • Main, for reference (earlier M4Air run): 7,055–8,748 MB.

Benchmark: head=782115b25d0f37fbfbad4a37d154645c5310927f gate=PASS machine=macOS-arm64 listeners=terminal-output-scheduler,webgl-atlas-page,webgl-atlas-change heavy-pty-60s: rebuilds=6 (≤1/10s) gpu-after=251MB peak-accel=2275MB; realistic-pty-60s: rebuilds=0 longtasks=0 gpu=291MB; no-rebuild path: 7757MB

After heavy output and rebuilds, both panes render correctly:

after heavy output

After realistic output:

after realistic output

@brennanb2025 brennanb2025 changed the title fix(terminal): rebuild WebGL renderers once the glyph atlas reaches a 4096² page Free terminal GPU memory on Mac when the glyph cache grows large Nov 20, 2026
…d typing stops, at most once a minute

The paired M4Air benchmark showed the 10 s rebuild cadence stalling input and frames under
sustained new-glyph output. A due atlas now waits for 2 s without output into it and 2 s
without user input, stays 60 s from the last attempt, and rebuilds output that never pauses
once it has waited 60 s (still never while typing), which bounds the retained GPU memory.
…ing, and count captured shortcuts and chunked pastes as typing

Typing that resumed after a rebuild started still let the per-frame chain recreate contexts
between keystrokes, and shortcuts the keyboard handler sends itself (Cmd+Left, Cmd+Backspace,
Shift+Enter) and chunked pastes never reached the typing hold.
…put, and let an overdue atlas past synchronized frames

Holding later reattaches while typing kept panes on the DOM renderer long enough for the grid
drift probe to refit them, resizing the PTY mid-typing; the chain itself is short (0.3-0.4 s for
six panes on the M4 Air). Typing is now also recorded for quick commands, drops, pastes and
native-chat runtime input, and a TUI that keeps reopening synchronized frames can no longer hold
an overdue atlas: it rebuilds, and a pane mid-frame reattaches when its frame closes.
…eep detached panes out of grid fits, count standalone typing

An overdue rebuild that went ahead while an on-screen TUI held a synchronized-output frame left
that pane blank (xterm holds the DOM paint until the frame closes); an overdue atlas blocked by a
frame now looks again every 250 ms and rebuilds in the gap between frames. Panes a rebuild left on
the DOM renderer skip the grid drift fit until WebGL is back, so their PTY is not resized twice.
Typing in standalone terminals now holds rebuilds too.
…ng one context per frame; free it only once output pauses

The quiet-screen rebuild detached every pane at once, painting the waiting ones on the DOM renderer
in one task (one 300-370 ms frame on the M4 Air). It now clears the shared atlas in place and
recreates one context per frame (dispose and attach in the same task), so no frame pays for more
than one pane and no shown pane ever drops to the DOM renderer; destroying each old context still
frees what it retained. Any click, wheel or key pauses the remaining steps, which keep their old
context meanwhile. The 60 s cap for output that never pauses is gone: memory then stays as it does
without this change and is freed when output pauses. The grid-fit guard is no longer needed.
… due atlas, never paint mid synchronized frame, skip while the window is hidden

A pane revealed or uncovered mid-chain was still dropped to the DOM renderer because the
recreate-or-drop choice was fixed at the start; each step now asks on its frame. Every due atlas is
emptied in place (not only the first pane's), so no recreated context uploads a large page. A pane
whose synchronized frame stays open keeps its old context and keeps checking instead of being
painted mid-frame. Nothing rebuilds while the window is hidden.
…it for the window to show instead of polling

Overlapping batches each ran their own per-frame chain, so two could recreate a context in the same
frame, and a held chain kept closed terminals (and their scrollback) alive in its closures. One queue
of weak references now serves every batch. A hidden window no longer re-checks every minute; it
resumes on the window's visibility signal.
… its own frame, keep a hidden window parked, count browser-page clicks

A pane held mid synchronized frame blocked every pane queued behind it; waiting panes now rotate to
the back, and one still waiting after 10 s keeps its old context and leaves the queue. The queue's
first step no longer shares a frame with the second. Output into a hidden window no longer restarts
the parked scheduler. Clicks into an embedded browser page hold rebuilds like other input.
…cused, and count embedded-browser input as interaction
…ser page, count window focus and reveal as interaction, never strand an atlas that comes due while the queue is parked
…closes until new output re-arms it

A frame held open past xterm's watchdog left the atlas due, so every 60 s it ran another eight
250 ms retries for as long as the frame stayed open, waking an idle renderer forever. The atlas
now drops out of the due set after its retries; output into it (the frame closing included)
re-arms it with a fresh budget.
…eep a held pointer counting as interaction

Closed entries ahead of a pane mid synchronized-output frame did not use up the frame's look
budget, so that pane was checked once per closed entry (300 checks at 300 entries). Every entry,
dropped or rotated, now uses one look. A pointer held down while it moves (text selection, a
divider drag) now also holds atlas rebuilds.
@brennanb2025

brennanb2025 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Perf scan (fresh Codex reviewer, full perf-scan on head f3bbeb2; the two earlier scans' findings, an idle retry loop and a per-frame look budget, were fixed in d1f302e and f3bbeb2)

Scope and verdict

Reviewed PR #43465’s complete diff, 075b631fd9d80df5c289118c3c18acc4f3247524..f3bbeb2ca6980c848955d7b8df4160cf313cfaa5, including all commits after 782115b, both earlier perf-scan reports, production callers, teardown paths, and installed xterm implementations.

No additional source-proven P0/P1 finding. This is a source audit, not a measured frame-time or GPU-memory pass. Context creation, synchronous painting, and driver reclamation remain unmeasured. No files edited or comments posted.

Earlier findings: fix confirmation

Earlier finding Evidence at this head Disposition
Indefinite idle retry cycle terminal-webgl-atlas-memory-rebuild.ts:181–191: after eight retries, forgetDue() removes the atlas and its retry state; the output mark is deleted. Later parsed output restores the output mark and can re-admit the still-large atlas. Fixed by d1f302e. The former nine-check cycle every approximately 62 seconds cannot restart without another admission event.
Same waiting pane probed repeatedly after stale entries are removed pane-webgl-reattach.ts:102–141: liveQueueHead() removes at most one stale entry; every outer iteration consumes one look, including stale removals. Fixed by f3bbeb2. For 299/2,999 stale entries followed by one waiting survivor, the first callback makes one survivor verdict call, previously 300/3,000.

The retry fix’s test now asserts no scheduled timer after ten idle minutes, followed by successful output-driven recovery. The queue fix adds the exact stale-prefix/waiting-survivor case at N=300 and N=3,000. These assertions were inspected, not executed.

One finite scheduling detail remains: on retry exhaustion, retry remains true, so scheduleRebuild() can receive an empty due set and schedule one timeout with a nonfinite delay. Its callback returns immediately at the empty-set guard and does not reschedule. This does not restore the recurring idle loop.

Added-work inventory

All application work below runs on the renderer thread unless specified otherwise.

Population: T live terminals; G attached tracked WebGL owners; A due atlases; K owners admitted in a batch; V visible managers; Q queued entries; P nonempty parsed-write completions/s. Fleet envelopes are T=300/3,000, independently of 750/7,500 worktrees and 100/1,000 agents. Actual recovery work follows G/A/K/Q, not every mounted terminal. Existing hidden retention permits six hidden contexts; visible contexts are additional.

Added work Trigger and population Work and bound
Interaction-module initialization Once per eligible Mac renderer document Five window listeners, one browser-pointer subscription, one permanent park-visibility subscription. No startup inventory, filesystem access, subprocess, or periodic timer.
Atlas-owner index Attach, detach, failure, atlas replacement; one owner Expected constant map/set operations. Strong attached registry ≤G; explicit teardown removes owners. The final owner leaving removes its atlas from the due set.
Atlas-page handler Every page-add event, forwarded to each sharing owner Gₐ callbacks for an atlas with Gₐ owners. Each indexes its own pane. Only width 4096, tracked attachment, eligible platform, and output evidence admit recovery.
Atlas-change continuation Each forwarded atlas-identity change One microtask per affected addon, followed by an attachment check and owner-local reindex. No terminal inventory.
Output-pipeline hooks Each nonempty completed write through five composition sites Direct foreground write; queued foreground/background drain; explicit foreground/background flush. One owner lookup and constant atlas/timestamp bookkeeping per completion. No text scan or per-chunk fleet scan.
Completion payload reference Each composed callback Captures parsedData without copying or serializing it. Normally shares the submitted string; a transformed foreground write can additionally retain its original input until callback-buffer cleanup. No independent history accumulator.
Due-atlas scheduling Large atlas plus parsed output One shared scheduler timeout. Scheduling/rechecking visits A deadlines. Existing timer or park watcher prevents scanning A on every output chunk.
Quiet/cooldown checks Due atlas receives output or interaction Requires two seconds of output and interaction quiet. Successful/give-up attempts update a shared 60-second cooldown. Intermediate synchronized-frame retries are separate.
Synchronized-frame preflight Ready atlas with an on-screen uncovered owner in mode 2026 Copies/validates only that atlas’s owners; up to nine inspections per continuously held episode, separated by eight 250 ms retries. Exhaustion removes admission until fresh output.
Atlas clearing Ready atlas passes preflight One synchronous clearTexture() per admitted atlas: page eviction, glyph-cache reset, small-page creation, and existing owner event fanout. All ready atlases clear in one task; this portion is not frame-sliced.
Visibility index Manager registration, visibility change, destruction Constant set maintenance. Recovery membership queries visit up to V manager roots; hidden managers and their panes are not enumerated. Preflight/classification can make approximately 2K membership queries.
Queue admission Nonempty recovery batch Filters K owners, sorts shown owners first using set membership, and deduplicates by pane. O(K log K) sorting. One shared weak queue across overlapping batches; no fixed numeric queue cap.
Per-frame processing Recovery rAF, after parking and interaction gates At most one context recreation or hidden-context disposal per callback. Up to Q original entries may be inspected, each at most once in that callback. Closed/disconnected/rendererless entries are retired.
Queue synchronization waits Pane enters mode 2026 after admission Waiting panes rotate behind other work. An all-waiting queue uses one 250 ms timeout followed by rAF. A pane expires on a check ≥10 seconds after its first wait, keeping its old context. Parking/interaction may extend elapsed wall time.
Interaction hold Input arrives during queue processing One timeout until the remaining quiet deadline, then rAF. Further input extends the hold; the input event itself creates no timer or fleet scan.
Window/focus parking Hidden window, unfocused host document, or active WEBVIEW/IFRAME Scheduler and queue share one event watcher. Once parking is observed, output cannot restart timer polling. Unpark events resume pending work.
Replacement paint Successful shown-pane recreation One synchronous full-viewport paint, proportional to rows × columns and glyph work. Clears the previously queued refresh span before painting; preserves later refresh requests/callbacks. No scrollback traversal.
Input/paste tracking Eight existing dispatch paths One clock read and scalar timestamp assignment per qualifying call/chunk. Paths may overlap through existing call layers, but cost follows call depth, not T.
Chat-cover recovery Cover cleanup or terminal identity change One layout-effect cleanup per cover, keyed by terminal. Weak lookup, visibility/liveness checks, and at most one attachment. No recurring effect work.
Diagnostic publication Nonempty batch admission One small record through the existing diagnostic/breadcrumb path, at most once per successful batch/cooldown. durationMs covers queue admission, excluding preceding atlas clear and later context recreation/paint.
Performance tests Test execution only No shipped runtime work. Mocks establish intended operation bounds, not driver costs or GPU reclamation.

The eight input paths are standalone typing, standalone paste chunks, captured-input dispatch, PTY paste writing, leaf input activity, pane PTY forwarding, runtime input send, and verified runtime input send. Existing provenance/driving-input gates avoid treating ordinary parser replies as typing.

At an assumed 60 Hz, K=300/3,000 successful queue steps require at least 5/50 seconds. These are scheduling calculations, before holds or throttling—not measured completion times.

New pointermove listener

terminal-webgl-atlas-rebuild-interaction.ts:37–45 adds one capture/passive listener per eligible Mac document, independent of T.

  • Trigger: every delivered host-document pointermove, including ordinary hover. Embedded-page movement does not traverse this document.
  • Rate: zero without movement; R callbacks/s at delivered movement rate R. PTY output creates none. Illustratively, 120/1,000 delivered events/s produce 120/1,000 callbacks/s at both T=300 and T=3,000.
  • Cost: hover performs one buttons comparison. Held-button movement additionally reads performance.now() and assigns one scalar. No DOM/layout read, allocation of per-terminal state, timer, IPC, publication, or terminal scan.
  • Lifetime: document lifetime; no per-pane registration or accumulation.
  • Disposition: necessary constant work to keep selection/divider drags holding recovery. No source-proven amplification or autonomous idle wakeup; handler duration was not measured.

Listener, subscription, and hook census

“Idle” means settled, without external events or pending recovery. Counts are source-derived ownership formulas, not measurements of a running window.

Added registration/hook Population and cleanup Idle / heavy-output rate
onAddTextureAtlasCanvas One application listener per addon: G total, including non-Mac addons. Existing atlas→renderer→addon forwarding fans events to sharing owners. Addon-owned emitter disposal releases listeners on teardown/failure. One production application subscription site found. Idle 0/s. Load: Σ(Gₐ × page-add eventsₐ/s), not P. Non-4096 events return without admitting recovery.
onChangeTextureAtlas One application listener per addon: G total. Same emitter lifetime. Continuation rechecks tracking before indexing. One application subscription site found. Idle 0/s. One callback plus microtask per forwarded identity change; unchanged-atlas output adds none.
Window pointerdown One Mac-document capture/passive listener Document lifetime. Idle/output-only 0/s; one timestamp update per delivered press.
Window wheel One Mac-document capture/passive listener Document lifetime. Idle/output-only 0/s; one timestamp update per delivered wheel event.
Window keydown One Mac-document capture/passive listener Document lifetime. Idle/output-only 0/s; one timestamp update per delivered keydown.
Window capture focus One Mac-document listener; capture can observe descendant focus events Document lifetime. Idle/output-only 0/s; one timestamp update per delivered focus event.
Window pointermove One Mac-document capture/passive listener Document lifetime. Idle/output-only 0/s; R comparisons/s during movement, plus R-held clock reads/writes.
Browser-page pointer IPC One added desktop consumer; existing active BrowserPaneOverlayLayer consumers B make total B+1. Returned unsubscriber is not retained for this document-lifetime consumer. Web implementation is a no-op. Idle/output-only 0 messages/s. Existing main producer sends once per admitted human guest mouse-down; PR adds one timestamp consumer, no producer.
Permanent park-visibility subscription One added document visibilitychange listener and one stale-recovery-set member Document lifetime. Idle/output-only 0/s; runs on visibility changes or stale-latch recovery.
Temporary unpark watcher At most one additional visibilitychange listener, stale-recovery member, window focus listener, and capture focusin listener, shared by scheduler/queue Removed before resuming callbacks. Parked idle 0 wakeups/s. Focus/visibility events check parking; no polling.
Unpark callback set Current production flow contributes at most scheduler callback plus one queue-resume closure Scheduler identity deduplicates repeated registration. Cleared on unpark; no periodic delivery.
Parsed-write completion One added bookkeeping call inside the existing completion; five call sites. No new onWriteParsed subscription. Idle 0/s; P calls/s under output. At an illustrative 100 completions/s per terminal: 30,000/300,000 calls/s for T=300/3,000, each addressing its own terminal.
Eight input/paste hooks Added calls inside existing handlers; zero new per-pane input subscriptions Idle/output-only 0/s; qualifying dispatch/chunk rate, potentially at several traversed layers. Existing handler disposal remains authoritative.
Chat-cover layout effect One cleanup registration per mounted cover Idle/output 0/s. Cleanup performs one lookup and possibly one attachment.
Rebuilder callback registration One module-level callback Renderer-module lifetime. Invoked once per admitted batch; registration creates no timer.

The park-visibility infrastructure already shares four bootstrap listeners: document keydown/pointerdown/visibilitychange and window focus. This PR adds recovery-set members, not another bootstrap per terminal.

Existing park subscribers include hibernation, warm-worktree subscriptions, RPC parking, deferred-connect waiters, plugin watchdogs, resource visibility, history-disk-usage hooks, and stream-visibility consumers for browser/emulator/session search. Hidden-output restoration also registers directly with stale recovery. With S existing park subscriptions and H direct recovery members, totals become:

  • Park subscriptions: S + 1 + parked
  • Recovery members: S + H + 1 + parked

Here parked is zero or one, not T.

Recreation also replaces existing addon/renderer listeners and observers. Disposal removes the old renderer’s registrations; the canvas-release path disconnects its resize/mutation observers and cancels its timeout. These are replacement lifetimes, not cumulative additions.

Idle and heavy-output rates

State Added activity
Settled idle Autonomous recovery wakeups: renderer 0 → 0/s, main 0 → 0/s, daemon 0 → 0/s. No new publication frames.
Continuous dense output into one due atlas P owner-local completion calls/s. No rebuild before output quiet. After cooldown, quiet-deadline rechecks are approximately 0.5 timer callbacks/s for this workload, each scanning A deadlines. This is not a global frequency cap for staggered atlases/deadlines.
Finite output burst After quiet/cooldown: one batch clears admitted atlases, then at most one queue context step per rAF.
Parked recovery An already-scheduled callback can observe parking; thereafter zero polling until unpark events.
Preflight synchronized-frame blockage Up to nine owner inspections per atlas episode, eight 250 ms retries, then abandonment until re-admitted. No indefinite idle cycle.
All-waiting queue Timeout+rAF rounds at approximately 3.76/s at 60 Hz, inspecting each remaining entry at most once per round. Entries retire after their 10-second wait cap on an eligible check.
Continuous interaction during queued recovery One remaining-hold timeout followed by rAF per check; repeated events update a scalar without creating per-event timers.
Diagnostics One small batch diagnostic per successful admission, bounded by the 60-second successful-attempt cooldown. No per-chunk diagnostic publication.

Newly exercised downstream costs and evidence gaps

Context replacement necessarily reaches GPU allocation/release, DOM-renderer transitions, renderer registration, viewport rasterization, and existing atlas-cache lookups.

The installed CharAtlasCache.acquireTextureAtlas() searches owner arrays. With one shared atlas and G owners recreated, the missing-owner acquisition searches alone inspect approximately G(G−1) entries: 89,700 at G=300; 8,997,000 at G=3,000, distributed across recovery frames. That implementation predates this diff, but this PR introduces an automatic route through it. Removal/configuration searches add further work.

Those counts are source-derived. They are not per-PTY-chunk fleet scans, and context replacement is required by the proposed memory-release mechanism. They also do not establish acceptable frame duration. The unresolved runtime candidate is a slow recovery step from context creation, cache searches, or full-viewport painting; the missing evidence is a real Mac frame trace during recovery at realistic attached-owner populations.

Likewise, atlas clear is synchronous across ready atlases and evicts pages/caches before the queue begins. Its duration and the actual retained-GPU-memory reduction were not measured. The admission diagnostic cannot supply either measurement.

Touched regression classes

Class Disposition
Hot-path rescans Earlier same-pane queue amplification fixed. Output bookkeeping is owner-local; recovery scans due owners/visible managers.
Fixed-cadence retries / idle wakeups Earlier indefinite loop fixed. Settled and parked recovery rates are zero; active retry episodes terminate.
Hidden/unobserved owners Parked window stops processing; hidden/covered panes drop contexts without immediate recreation or repaint. Reveal/fit/cover cleanup owns restoration.
Ownership multiplication / per-instance work Two addon listeners per owner; one shared scheduler/queue and one shared park watcher. No new upstream PTY subscription.
Per-entity state surviving teardown Explicit attached-owner removal; ownerless due removal; weak queue/covered references; temporary watcher cleanup inspected.
Queue/fanout growth Pane deduplication, weak references, stale retirement, and waiting caps inspected. Slots can remain while parked, but hold no output payload and draining resumes on unpark.
Streaming retention Original-string reference can survive alongside transformed input until existing write-buffer cleanup; no added copy, serialization, or history accumulator.
Newly reachable expensive work Context replacement, atlas eviction, cache searches, and paint priced above. Runtime frame/GPU cost remains unmeasured.
Eager startup imports Added renderer-module initialization and listener registration inspected; no new SDK, subprocess, disk probe, or database initialization found. Startup duration unmeasured.
React effect recreation Cover cleanup depends on terminal identity and synchronizes an external renderer; unchanged renders do not recreate it.

Six-question coverage

Question Disposition
Work before skip gates? Reviewed platform, attachment, page-size, output, quiet, focus, visibility, and synchronization gates. Ordinary parsed output performs constant owner-local bookkeeping.
Ownership multiplying work? Reviewed forwarding, subscriber sites, listener lifetimes, overlapping batches, and shared parking. Census above.
Which thread/storage pays? Renderer pays recovery CPU and synchronous painting. No added host subprocess/filesystem/SQLite work. Existing breadcrumb delivery is reached once per batch.
Growth and forward progress? Reviewed A/K/V/Q bounds, cooldown, deduplication, stale entries, retry exhaustion, and output-driven re-admission. Both earlier progress defects are fixed in source.
Execution-host differences? Eligible non-touch Mac desktop/browser gate and shared local/remote PTY paths inspected. Other platforms retain small hook/listener overhead but perform no atlas-memory rebuild. No platform runtime validation.
Obsolete work stops? Reviewed detach/failure/disposal, closed queued panes, window parking, chat-cover recovery, and bounded waits. Actual driver reclamation remains unverified.

Inspected all 21 changed files and supporting production/xterm paths. git diff --check passed. Tests, typechecks, builds, Electron, and benchmarks were not run: this scan remained read-only, and the required local test gate writes admission state. Accordingly, the evidence confirms source bounds and both fixes; it does not claim measured CPU, frame latency, or GPU-memory recovery.

@brennanb2025

Copy link
Copy Markdown
Contributor

Status: ready for review at f3bbeb2

Problem: on macOS, every terminal's WebGL context keeps the GPU memory from glyph-atlas uploads until the context is destroyed. Clearing the atlas frees none of it, so heavy colored output took the GPU process to many GB.

What changes for users (desktop macOS only):

  • After heavy, very colorful output, the terminals that share the grown glyph atlas are recreated, which gives the GPU memory back. The terminals look the same.
  • It waits for a quiet moment: output into that atlas has paused for 2 s, and there has been no typing, clicking, scrolling or dragging for 2 s. Attempts are at least 60 s apart.
  • It recreates one terminal per frame, never while the window is hidden or another app or an embedded browser page has focus.
  • Limitation: output that never pauses keeps its memory until it does, as before this change.

Fixed since the last status (782115b), by the review loop on this head:

  • A synchronized-output frame that never closed made the atlas retry forever: nine wakeups every 62 s on an idle renderer. It now stops after eight retries, and new output re-arms it (d1f302e).
  • Closed panes in the rebuild queue didn't use up the frame's look budget, so one waiting pane could be checked 300 times in a frame at 300 entries. Each entry now uses one look (f3bbeb2).
  • A pointer held down while it moves (drag-select, divider drag) now holds rebuilds (f3bbeb2).
  • The PR body now describes the real timing, and has the new Performance section.

Deferred (none blocking):

  • Pixel-ratio change while a rebuild is due drops the rebuild. Found in QA. If the device pixel ratio changes within the 2 s quiet window after heavy output, xterm swaps in a new atlas and the pending rebuild is dropped. Font-size and theme changes very likely take the same path; only the DPR case was reproduced. The old contexts keep their memory (about 1.8 GB in the repro) until the next large page triggers a rebuild. That is no worse than without this change.
  • A pointer held perfectly still for over 2 s mid-drag no longer holds rebuilds.
  • Hidden panes get WebGL back when another tab is revealed. This comes from existing hidden-pane retention; rendering was correct.

Verified on f3bbeb2ca6980c848955d7b8df4160cf313cfaa5:

  • CI is green. One flaky Codex shared-server test, which this PR doesn't touch, passed on rerun.
  • Blinded regression audit (Codex) on this head merged onto main: SAFE. The reviewer pair: Codex audit plus a terra review whose last pass was CLEAN.
  • Perf scan: no confirmed regression (comment above). Its two earlier findings were fixed in this head.
  • QA on the M4 MacBook Air: a production build of this head, run as a hidden test copy, with every rebuild proven by its diagnostic, new WebGL contexts and the atlas page count.

Glyph rendering after rebuilds. Each case got a before and after screenshot, a pixel diff of a fixed reference block, and a check of the terminal's text:

Case Diff Result
Long output (55k colored lines), rebuild mid-stream, then scrollback 0.000% no missing or garbled glyphs
Reference block: bold, italic, underline, dim, inverse, strike; 16, 256 and truecolor; CJK; emoji; combining marks; box, powerline and blocks; ligature candidates 0.000% identical
Font size 14 → 18 (Settings), then rebuild 0.000% crisp, no old-size glyphs
Theme Light → Dark (Settings), then rebuild 0.000% new palette, no old colors
Window resize before and after a rebuild 0.000% reflowed, nothing stretched or blurry
Pixel ratio 1 → 2 → 1 (emulated; a real display move isn't possible on the QA machine) 0.312% (crop offset) crisp at both; see the deferred item
12 terminals (6 worktrees × 2 splits) n/a none blank or half drawn
Hidden tabs and a collapsed split, then shown n/a WebGL back, fully drawn
Selection across a rebuild 0.106% (cursor blink) selection identical
Drag-select held 12 s while a rebuild was due n/a no rebuild during the drag; one 1.9 s after it

Typing and frames:

  • Keystroke echo p50/p95 was 10.2/19.6 ms when quiet and 10.5/17.4 ms with a rebuild due.
  • Rebuilds ran 2.0 s after the last keystroke.
  • The longest frame within 1 s of a rebuild was 167–243 ms, below the flood's own 472–533 ms.

GPU memory (2 visible panes):

  • Paced heavy bursts: 3 rebuilds, 66 s apart, each dropping the GPU process from 3.4–3.7 GB to 1.2–1.4 GB; about 540 MB once idle.
  • Non-stop heavy output: 3,841 → 541 MB, one rebuild 1.9 s after it stopped.
  • Realistic output: 0 rebuilds, 0 long tasks.

Benchmark: head=f3bbeb2ca6980c848955d7b8df4160cf313cfaa5 gate=PASS machine=macOS-arm64 listeners=terminal-output-scheduler,webgl-atlas-page,webgl-atlas-change heavy-pty-bursts: 3 rebuilds in pauses 65.7/66.0 s apart, GPU 3.4-3.7 GB -> 1.2-1.4 GB; heavy-pty-continuous-60s: 0 during, 1 at +1.9 s, 3841 -> 541 MB; realistic-pty-60s: 0 rebuilds, 0 long tasks; latency: echo p95 19.6 ms quiet vs 17.4 ms rebuild-due, max frame near a rebuild 243 ms vs flood 533 ms

Reference block before a rebuild:

reference block before

The same block after a rebuild (0.000% diff):

reference block after

All 12 terminals after a rebuild and reveal:

12 terminals after a rebuild

Collapsed split shown again after a rebuild:

hidden split revealed

Scrollback on the new context:

scrollback after rebuild

Theme switch, then rebuild:

theme after rebuild

Drag-select held the rebuild:

drag select

@brennanb2025
brennanb2025 merged commit 1560ff5 into stablyai:main Nov 23, 2026
104 of 107 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.

[Bug]: Orca Helper (GPU) still grows to ~6 GB on v1.4.261 — per-pane WebGL context memory from glyph-atlas uploads is never released

2 participants