Skip to content

fix(terminal): release erased cell backing strings - #20992

Closed
OrcaWin wants to merge 25 commits into
np-oom-scan-contrast-cachefrom
np-oom-scan-terminal-cell-retention
Closed

OrcaWin wants to merge 25 commits into
np-oom-scan-contrast-cachefrom
np-oom-scan-terminal-cell-retention

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​473 $\color{#cf222e}{\Huge{\mathbf{−}}}$​8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​465
Prod 27 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2494 $\color{#cf222e}{\Huge{\mathbf{−}}}$​89 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2405

ELI5

Erasing terminal text can leave the old strings hidden in memory. This change releases those strings once they no longer belong to a live cell, so cleared output can release its memory too. Existing terminal text and scrollback capacity are preserved.

What Changed

The shared terminal line implementation clears invalid text caches, removed combining-character strings, unused extended attributes, and a temporary cell used while shifting columns. Valid cached text is invalidated only once per mutation burst. Desktop, daemon/headless, and mobile packages are regenerated from the same reviewed source changes.

This branch now includes the refreshed #20981 base. The malformed source-patch hunk counts, stale generated bundles/maps, mobile source mismatch, lockfile hashes, and generated mobile payload expectation are repaired. Both review-bot threads are addressed.

Why

In a synthetic combining-text fixture, erasing eight cells previously left about 42.9 MiB reachable; the fixed runs retain about 0.1–0.2 MiB. A live 100,001-character cell retains all its text. Ordinary short graphemes retain much less, so this demonstrates a leak mechanism rather than proving the cause of a production OOM.

Removing dead references preserves text and history, while imposing a text-length or scrollback limit would discard live content.

Tradeoff and current gate

Requires #20981 first. No text, color, or scrollback loss was found in the checked cases. Cleanup has a measurable CPU cost: the freshly rebuilt headless bundle parsed synthetic 1.2 MB ASCII writes in 8.04 ms versus 7.665 ms before, about 4.9% slower. That is roughly 0.38 ms per write in this fixture, not an application-wide slowdown estimate. This cost remains; the PR does not claim zero performance tradeoff.

Linked Issue

Related to #19768 and #19831 as memory hardening; neither incident is claimed resolved by this synthetic evidence.

Visual Proof

N/A — this changes internal ownership of erased strings. Automated live-cell comparisons and generated-mobile-engine tests cover the affected behavior; no running-app UI capture is claimed.

Testing

On macOS arm64 / Node 24.20.0:

  • Both complete desktop/headless and mobile patch --check rebuilds pass.
  • 62 patch-generation, source-map, and real headless-emulator tests pass.
  • All six generated mobile engine, contrast-cache, and payload tests pass. The mobile test-typecheck ratchet passes all 683 included test files outside its existing baseline.
  • All 70 isolated allocation cases were rerun across baseline and six installed module bundles.
  • 25,000 seeded source mutations preserve cells and translations; scratch-cell retention checks pass.
  • Source and emitted-bundle throughput evidence was regenerated; focused lint and both pnpm 12 frozen installations pass.
  • 47 shell-harness and real-zsh tests pass. A CI-only startup race is fixed: the test harness now waits for actual startup output before applying its quiet-period check, so a slow compinit prompt cannot consume a queued PS1 command. A deterministic delayed-startup regression covers that failure.

Current audit evidence

Review

The generated-artifact blockers are removed. Wait for current CI, and merge after #20981. The remaining decision is whether the measured parser cost is acceptable for reclaiming erased terminal text; evidence does not establish the frequency or size of this leak in ordinary user sessions.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes — this run reviewed the single commit adding the BufferLine retention patch across headless/desktop/mobile, the source-map provenance harness, and the new regression/audit evidence.

  • BufferLine patch (headless/desktop/mobile) — releases combined strings and unused extended attrs on overwrite/erase/shift; setters check the old _data flag before clearing, copyCellsFrom checks the destination map because the destination flags were already copied. Wide chars, protected cells, overlapping copies, reflow, and the deprecated set() path are preserved.
  • New @xterm/headless patch — headless ships no src/, so config/patches/xterm-upstream.json declares both published maps + prefixes and assertMappedSourcesMatch byte-compares every embedded source against the checkout before and after patching.
  • regenerate-xterm-patches.mjs — sourceRootFor/sourceDir rooting, generatedPaths-driven cleanup, and a sourceMaps branch that replaces the src-hunk comparison.
  • Mobile regeneration — MOBILE_SOURCES now selects ColorContrastCache.ts + BufferLine.ts; the mobile patch and lockfile are rekeyed.
  • Tests & audit — headless-cell-retention.test.ts (17 cases), the generated mobile WebView engine test, and the docs/audits/terminal-cell-retention/ reproductions.

Independently verified: patch hashes match both lockfiles, the headless bundle patch dry-runs clean against the pristine package and embeds source byte-identical to the .src.patch applied to the pristine map (semantic-results.json shas reproduced), the BufferLine stanza is identical across all three source patches, 45 harness tests pass, and the regression suite fails 15/17 on the reversed pristine engine while passing 17/17 patched.

Two non-blocking notes: the manifest carries no upstream pointer for this BufferLine fix (unlike the addon-search entry), so any future upstream fix would not be discoverable from the manifest; and the measured ~5% parse-path cost is a real, documented tradeoff rather than a free win.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes — this run re-reviewed the two commits pushed after the prior pullfrog review (43e0a96); both are test-side only, so production behavior is unchanged.

  • Mobile payload gate corrected — terminal-webview-payload-hash.test.ts now expects 241cb377…/731258, replacing the stale 25b800f3…/730472 that did not match the emitted document.
  • Typed test access — headless-cell-retention.test.ts replaces the Reflect.get chains with a typed buffer() helper, and line() now throws on a missing row instead of yielding undefined.

Independently verified this run: a frozen pnpm install in mobile/ regenerates terminal-webview-engine.generated.ts deterministically (identical sha on rebuild), and the new 241cb377…/731258 value matches the emitted document. The mobile payload-hash test, mobile terminal-webview-cell-retention.test.ts, and the 17-case root headless-cell-retention.test.ts all pass, with pnpm tc:node clean.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes — the only commit pushed since the prior pullfrog review (5b4b27d) is bb99800, and it is a zero-diff merge: git diff 5b4b27d bb99800 is empty, so no file content changed.

  • Base-branch sync — the base had advanced by one commit (05caeb6, which set the contrast-only payload expectation to bdd9b21a…/730693). The merge resolves the terminal-webview-payload-hash.test.ts conflict by keeping the PR's 241cb377…/731258, the correct expectation once the BufferLine change is folded into the contrast engine. That base commit touched only that same test file, so nothing else from the base was dropped.

Re-confirmed the merged head: the payload-hash test passes against a freshly regenerated mobile engine, and the merged tree is byte-identical to the already-verified 5b4b27d.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes — this run re-reviewed the one commit pushed after the prior pullfrog review (bb998003); it is audit-harness only, so no shipped patches, lockfiles, or CI-run tests change.

  • Audit fixture loading rewritten — semantic-review.cjs replaces its bespoke transformSync + new Function module loader with an esbuild bundle written to a temp file and required; the baseline and patched variants are pre-bundled once inside an async main() and the emitted code is passed into fixture/semanticCheck/retentionCheck.
  • Throughput bundle loading switched to real modules — throughput.cjs writes its esbuild output to a temp .cjs file and requires it (deleting the cache entry) instead of evaluating the bundle text through new Function.

No product or CI surface changed: docs/audits/terminal-cell-retention/ is a manual reproduction harness with no workflow or package-script reference, the retention assertions are unchanged, node --check passes on both scripts, and the bundle's auditScratchChars export still reaches the entry through export * from BufferLine.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

m4air added 2 commits September 17, 2026 02:20
Resolve mobile lock metadata with the pnpm 12 hash format while retaining all patch hashes.
Resolve mobile lock metadata with the pnpm 12 hash format while retaining all patch hashes.

@pullfrog pullfrog 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.

Important

The two new commits edit the hand-authored BufferLine source patches to guard the translated-line-cache clear behind _cacheValid, but the generated bundle patches, the derived mobile source patch, and both lockfiles were not regenerated. This breaks the test job (two unit tests fail) and both xterm_patch_sync checks, and the optimization never reaches the packages Orca installs. Regenerating all artifacts resolves it.

Reviewed changes — this run re-reviewed the two commits pushed after the prior pullfrog review (ccac7bb908); both change only the source-of-truth BufferLine patches, so no test, bundle, lockfile, or harness content changed.

  • Conditional cache invalidation — set, setCell, setCellFromCodepoint, addCodepointToCell, insertCells, deleteCells, replaceCells, resize, fill, and copyCellsFrom now run this._cache = '' only when this._cacheValid, collapsing repeated clears within one mutation burst into one.
  • Source patches only — config/patches/xterm-src/@[email protected] and config/patches/xterm-src/@[email protected] were edited; the corresponding generated bundles, mobile artifacts, and lockfile hashes were not touched.

The conditional itself is semantically equivalent to the unconditional clear: _cache is only non-empty while _cacheValid is true (only translateToString writes it non-empty and sets valid in the same expression; the constructor and copyFrom reset both together), so clearing on the first invalidation still releases the retained string.

ℹ️ Nitpicks

  • The audit evidence is now stale: docs/audits/terminal-cell-retention/semantic-results.json records patchedBufferLineSha256: 435b6bcc…, but semantic-review.cjs reads the source patch dynamically, so rerunning it after regeneration will record a different sha. Rerun the audit and update the recorded results.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the np-oom-scan-contrast-cache branch from 47bb299 to 94105d9 Compare September 19, 2026 03:15

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes — this run re-reviewed the merge 7bbfceb5c0 pushed after the prior pullfrog review (314fa9063c); it regenerates every generated xterm artifact from the already-reviewed conditional-cache source patches and refreshes the branch onto the current #20981 base.

  • All generated bundles rebuilt — the headless, desktop, and mobile .patch files now embed the conditional _cacheValid clear (10 methods × CJS+ESM = 20 occurrences each, zero unconditional), so the perf change actually reaches the packages Orca installs.
  • Lockfiles rekeyed — both pnpm-lock.yaml files carry hashes matching the committed patches (headless 0fb99f65…, desktop 83bc5c44…, mobile 4c96c6e1…).
  • Mobile artifacts regenerated — the generated WebView engine and its payload-hash expectation now read 87d7e96d…/731458 and pass.
  • Audit evidence refreshed — semantic-results.json records patchedBufferLineSha256: e521a463…, matching the source embedded in every bundle map, and diff is now a direct devDependency so the audit no longer relies on hoisting.
  • Docs and PR body updated — the audit README and PR description document the repair rather than the earlier malformed state.

Independently verified this run: every bundle map's embedded BufferLine.ts hashes to e521a463… (headless, desktop, and mobile, CJS and ESM); reverse-applying the headless source patch to that embedded source is clean and reproduces baseline 26551bd2…, so the hunk counts and src↔bundle provenance agree; all root and mobile lockfile patch hashes match; 62 patch-generation/source-map/headless-emulator tests and 17 mobile WebView tests pass after a frozen mobile install; working tree clean. Both prior-review inline threads were already resolved. The full xterm_patch_sync --check (which rebuilds pinned upstream) was not run here as it has no offline path, but the embedded-source, lockfile, and committed-artifact checks all agree.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes — this run re-reviewed the one commit pushed after the prior pullfrog review (7bbfceb5c0); it is test-infrastructure only, so no shipped patch, bundle, lockfile, or product behavior changes.

  • Zsh startup wait — runZshPty now awaits the shell's first byte (firstData) before starting its 250ms quiescence check, so silence during a slow startup no longer reads as a ready prompt and the queued PS1 command cannot be consumed by a late compinit question.
  • Deterministic regression test — the new zsh-startup-hook-pty-harness.test.ts mocks node-pty with fake timers, asserts nothing is written during 500ms of startup silence, then walks compinit, the prompt, and exit.
  • Mobile canvas mock cast — terminal-webview-contrast-cache.test.ts switches the getContext mock cast to as unknown as CanvasRenderingContext2D under its existing SAFETY: disable (compile-time only).

Verified this run: the new test fails against the pre-fix harness (it writes PS1 during startup silence) and passes at head, so it is a real regression guard; oxlint reports 0 warnings / 0 errors on all three changed files; working tree clean. Both prior-review inline threads were already resolved and remain so.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes — this run re-reviewed the three commits pushed after the prior pullfrog review (0fe628456e); all three register the new zsh startup harness test with the CI shell lane, so no product code or shipped xterm patch changed.

  • Shell lane registration — .github/workflows/pr.yml lists src/main/zsh-startup-hook-pty-harness.test.ts in the real-shell contract step, and .github/workflows/unit-tests.yml excludes it from the sharded suite.
  • Lane guard updated — config/scripts/pr-workflow-parallelism.test.mjs adds the file to shellContractFiles, which the keeps every real-zsh test in the dedicated shell lane glob asserts must exactly match the tests that import zsh-startup-hook-pty-harness. This fixes the guard, which failed at 0fe6284 once the new harness test existed but was absent from the lane list.

Verified this run: pr-workflow-parallelism.test.mjs passes 19/19 (including the real-zsh lane guard) and zsh-startup-hook-pty-harness.test.ts passes 1/1. The three registration sites are consistent and their placement matches the neighbouring entries.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the np-oom-scan-contrast-cache branch from 009e86a to 4f990f2 Compare September 20, 2026 01:01
@nwparker

Copy link
Copy Markdown
Contributor

Closing: the retained strings are capped at one per column per line and freed when the line leaves scrollback, so real-world memory is negligible. The fix costs ~4.9% parser throughput on every printed character. It also has no merge base with main, which has moved to xterm beta.304, and it bundles #20981 plus ~4.8k lines of audit artifacts.

@nwparker nwparker closed this Oct 14, 2026
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.

2 participants