Skip to content

Bound terminal contrast-color caches - #20981

Closed
OrcaWin wants to merge 10 commits into
mainfrom
np-oom-scan-contrast-cache
Closed

OrcaWin wants to merge 10 commits into
mainfrom
np-oom-scan-contrast-cache

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​306 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​304
Prod 20 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3927 $\color{#cf222e}{\Huge{\mathbf{−}}}$​64 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3863

ELI5

The terminal adjusts text colors when needed to make them readable against the background. It remembers each answer so it can reuse it. Output with endlessly changing colors could make that collection grow forever.

What Changed

Each normal and dim contrast cache now holds at most 4,096 saved answers. When the limit is reached, the cache is cleared; the same color is recomputed if it returns later. Text, themes, colors, and scrollback capacity remain unchanged across desktop and mobile terminals.

Why

Existing glyph cleanup does not clear these color calculations. Bounding them prevents memory growth with every new foreground/background combination.

Synthetic 100,000-redraw tests reduced heap growth from roughly 4–5.5 MB to 0.3–0.4 MB. This demonstrates retention, not the cause of a particular production OOM.

User impact

There is no intended visible difference. Desktop WebGL/DOM and generated mobile WebView controls produced the same colors and pixels after eviction. Workloads cycling through more than 4,096 pairs do more recomputation, so zero CPU cost is not claimed.

Linked Issue

Related to #19831 as memory hardening; incident causality is not established.

Visual Proof

N/A — no intended visual change; before/after colors and pixels match.

Testing

Recorded desktop/mobile rendering, DOM color, patch-sync, typecheck, lint, and cache-overflow controls passed. Audit evidence is in terminal-contrast-cache-retention.

Review

Rebased onto current main at c455f5c669; the follow-up audit now forces contrast-cache repopulation. #20992 and #21112 are stacked on this PR.

@OrcaWin
OrcaWin marked this pull request as ready for review September 16, 2026 07:08
@coderabbitai

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Important

Review skipped

We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 28b5adbb-ee76-440e-88e0-b5a7762d5595

📥 Commits

Reviewing files that changed from the base of the PR and between 696a500 and 05caeb6.

📒 Files selected for processing (1)
  • mobile/src/terminal/terminal-webview-payload-hash.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.


📝 Walkthrough

Walkthrough

The change limits desktop and mobile xterm contrast caches to 4096 entries and adds tests for eviction and reset behavior. It adds mobile patch profile and regeneration support, parameterizes patch generation inputs, and verifies both patch sets in CI. New DOM and WebGL audits measure cache retention and rendering behavior before and after the change. Documentation records the mobile patch process and audit results.

Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to 05cae

The payload expectation change is narrow, but the supporting WebGL audit still lacks verified evidence that contrast is recalculated after cache clearing.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: bounding terminal contrast-color caches.
Description check ✅ Passed The description covers the required high-level explanation, changes, rationale, issue reference, visual proof, testing, and review context. It is mostly complete, although it does not include the temp…
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Warning

Git: CodeRabbit could not clone the repository, so clone-backed analysis was skipped and this review may be incomplete. Verify repository clone access, such as SSH credentials, before requesting another full review. If clone access is intentionally unavailable, use path_filters to narrow the review scope.


Comment @coderabbitai help to get the list of available commands.

@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

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 89ea4405-5896-46ac-9cac-cafeb9858ba8

📥 Commits

Reviewing files that changed from the base of the PR and between 16ac901 and 696a500.

⛔ Files ignored due to path filters (2)
  • mobile/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (20)
  • .github/workflows/mobile.yml
  • .github/workflows/pr.yml
  • config/patches/@[email protected]
  • config/patches/xterm-src/@[email protected]
  • config/scripts/pr-code-change-scope.test.mjs
  • config/scripts/regenerate-xterm-patches-mobile.mjs
  • config/scripts/regenerate-xterm-patches-mobile.test.mjs
  • config/scripts/regenerate-xterm-patches.mjs
  • config/scripts/xterm-contrast-cache.test.mjs
  • docs/audits/terminal-contrast-cache-retention/README.md
  • docs/audits/terminal-contrast-cache-retention/reproduce-dom.mjs
  • docs/audits/terminal-contrast-cache-retention/reproduce.mjs
  • docs/audits/terminal-contrast-cache-retention/results-dom.json
  • docs/audits/terminal-contrast-cache-retention/results-mobile-dom.json
  • docs/audits/terminal-contrast-cache-retention/results.json
  • docs/reference/xterm-patch-regeneration.md
  • mobile/patches/@[email protected]
  • mobile/patches/xterm-src/@[email protected]
  • mobile/pnpm-workspace.yaml
  • mobile/src/terminal/terminal-webview-contrast-cache.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.

@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 full 22-file diff: the vendored xterm ColorContrastCache bound, the regenerated desktop and mobile patches, the mobile patch-variant generator, the CI wiring, and the new tests and audit artifacts.

  • Contrast-cache bound — ColorContrastCache admits at most 4096 combined color/CSS entries per instance, flushes on overflow, and resets its counter on clear(); the desktop and mobile source and bundle patches are regenerated together with lockfile hashes.
  • Mobile patch variant — regenerate-xterm-patches-mobile.mjs derives a contrast-only profile from the desktop manifest and source, and regenerate-xterm-patches.mjs gains injectable manifest/lockfileRelativePath parameters; mobile excludes the desktop IME/SortedList hunks.
  • CI wiring — pr.yml runs desktop and mobile --check in one xterm_patch_sync step; mobile.yml adds a standalone mobile check.
  • Tests and audit — unit coverage for the bound and the generator, a generated-engine mobile test, and reproduction scripts/results under docs/audits/terminal-contrast-cache-retention/.

I verified the fix is real rather than asserted: the patched package installs and lib/xterm.js carries the bound, xterm-contrast-cache.test.mjs fails with the admit logic removed (2 of 3 tests) and passes with it, the generator and change-scope suites pass, the _entryCount invariant is exact (never more than 4096 entries, no stale values returned), and the mobile patch contains exactly the expected four bundle/map hunks plus the source stanza with no desktop-only changes.

ℹ️ Edits to the shared patch-text layer bypass the patch-sync checks

config/scripts/xterm-patch-text.mjs drives both generators' patch formatting and stanza selection, and this PR newly makes the mobile generator depend on it, but it matches neither XTERM_PREFIXES nor mobile.yml paths. This predates the PR, so it is not a blocker, but it is worth knowing: a change to that file alone schedules no pinned-build --check.

Technical details
# xterm-patch-text.mjs is not a patch-sync trigger

## Affected sites
- `config/scripts/pr-code-change-scope.mjs:69-74` — `XTERM_PREFIXES` lists `config/patches/xterm-upstream.json`, `config/patches/@xterm`, `config/patches/xterm-src/`, `config/scripts/regenerate-xterm-patches`; `xterm-patch-text.mjs` matches none.
- `.github/workflows/mobile.yml:10-19` — `paths` is `mobile/**` plus named shared files; nothing under `config/scripts/`.

## Why it matters
`splitPatchEntries`/`selectPatchEntries` choose the mobile contrast stanza, and
`normalizePnpmDiff`/`PNPM_DIFF_FLAGS`/`CHECKOUT_DIFF_FLAGS` define the emitted patch
bytes. Editing any of those with no accompanying `config/patches` change schedules
neither `pr.yml` `xterm_patch_sync` nor the new `mobile.yml` step, so the committed
`.patch` files and their lockfile hashes can drift from what the generator now emits
with no failing gate.

## Note on the added classification test
`config/scripts/pr-code-change-scope.test.mjs:183-185` asserts
`config/scripts/regenerate-xterm-patches-mobile.mjs` is `xterm_patch_sync: true`, but
`matchesPrefix` uses `startsWith` and the pre-existing prefix
`config/scripts/regenerate-xterm-patches` already matches that file, so the assertion
passes before and after this PR.

## Suggested approach (optional)
If coverage here is desired: add `config/scripts/xterm-patch-text` to `XTERM_PREFIXES`
and to the `mobile.yml` `paths` list. Not required for this PR.

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 reviewed the single commit added since the prior pullfrog review (05caeb6df1): a test-only update to the mobile WebView payload guard that tracks the contrast-patched engine shipped by the earlier commits.

  • Payload hash guard re-pinned — mobile/src/terminal/terminal-webview-payload-hash.test.ts:9-10 updates the expected XTERM_HTML SHA256 (25b800f… → bdd9b21…) and length (730472 → 730693) for the contrast-only mobile engine. The exact toBe assertions mean the guard still fails on any unintended document change.

Verified against the real toolchain: pnpm install --frozen-lockfile in mobile/ applies the contrast-only patch (mobile ColorContrastCache.ts carries CONTRAST_CACHE_MAX_ENTRIES = 4096), rebuilds the engine, and the updated test passes with the new constants.

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 reviewed the single commit added since the prior pullfrog review (c455f5c669): a test-only change that decouples the mobile contrast-cache test from the generated WebView engine bundle.

  • Mobile cache test imports the package directly — mobile/src/terminal/terminal-webview-contrast-cache.test.ts now imports Terminal from @xterm/xterm instead of evaluating the gitignored terminal-webview-engine.generated.ts bundle through node:vm, matching the two sibling terminal tests that already import the package this way. All assertions are unchanged and exact, and the shipped WebView document stays pinned by terminal-webview-payload-hash.test.ts.

Verified in this environment: a mobile install applies the contrast-only patch (_admitNewEntry / _entryCount / 4096 present in node_modules/@xterm/xterm/lib/xterm.js), the test passes 3/3, and the file is clean under oxlint and typecheck:tests (the 508 other errors there are pre-existing).

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 reviewed the single commit added since the prior pullfrog review (00ed3625f8): trigger coverage for the shared xterm patch-text generator, plus an audit-script recompute check.

  • Patch-text generator now a patch-sync trigger — config/scripts/xterm-patch-text.mjs is added to XTERM_PREFIXES (config/scripts/pr-code-change-scope.mjs:77) and to the Mobile Checks paths filters (.github/workflows/mobile.yml:12, :50), so editing the shared patch formatter schedules both the xterm_patch_sync job (desktop and mobile --check) and the mobile workflow. This closes the informational finding from the earlier pullfrog review.
  • Classification test added — config/scripts/pr-code-change-scope.test.mjs:184-186 pins xterm-patch-text.mjs to xterm_patch_sync: true. The assertion is real (it fails without the new prefix), and the suite passes 38/38 here.
  • Audit recompute check — docs/audits/terminal-contrast-cache-retention/reproduce.mjs:174-188 clears the glyph atlas before re-rendering after cache.clear() and asserts the contrast cache repopulates (afterRecompute > 0), matching the CodeRabbit proposal; review-validation.json records the fresh results.
  • Docs — README.md and xterm-patch-regeneration.md describe the new trigger and the mobile contrast-only variant.

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.

Important

The mobile WebView payload guard is stale, so Mobile Checks / verify is red on this head. The regenerated mobile contrast patch changed the generated engine, but terminal-webview-payload-hash.test.ts still pins the previous document (AssertionError: expected 730692 to be 730693). Re-pin it before merge.

Reviewed changes

This run reviewed the three commits added since the prior pullfrog review (00ed3625f8): the contrast-cache admission refactor, its regression test, and the widened Mobile Checks trigger.

  • Admission counts a pair once — _admitPair replaces the per-map _admitNewEntry, so one (bg, fg) pair consumes one of the 4096 slots rather than two. The intermediate _seen map was dropped in favor of reading the two maps, which are only written through the admitting setters and only ever clear together.
  • Regression test added — config/scripts/xterm-contrast-cache.test.mjs pins single-count admission across both setters; it fails under the previous per-map logic.
  • Patches and lockfiles regenerated — the desktop and mobile source/bundle patches and both lockfile patch_hashes track the new admission code (hashes verified against the committed patch files).
  • Mobile Checks trigger widened — mobile.yml now runs on config/patches/xterm-src/** and config/patches/xterm-upstream.json, which the mobile patch generator reads.

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

m4air and others added 10 commits September 19, 2026 17:54
`_admitNewEntry` fired from both `setCss` and `setColor`, so one (bg, fg)
pair consumed two of the 4096 slots and the cache actually wiped at ~2048
pairs. Track admission in a `_seen` TwoKeyMap keyed by the pair, cleared
with the other maps, so the bound matches the documented constant.

Regenerated the desktop and mobile bundle patches and both lockfile hashes.
regenerate-xterm-patches-mobile.mjs derives the mobile patch from the desktop
`ColorContrastCache.ts` stanza and `xterm-upstream.json`, so an edit to either
changes what the mobile patch check expects while mobile.yml never triggers.
The admission set was a third bounded map inside a patch whose purpose is
capping memory. The color and CSS maps only ever clear together, so either
one already holding the pair proves it was counted.
The rebase took main's side for the generated bundle patch and lockfile, so
this rebuilds both from the merged source stanzas (contrast cap plus main's
CJK preedit WidthCache hunk).

Also re-pins the mobile WebView payload hash: the _seen-map removal changed
the minified engine by one character and the pin was never updated, so the
branch head was already failing that test before the rebase.
@nwparker
nwparker force-pushed the np-oom-scan-contrast-cache branch from 009e86a to 4f990f2 Compare September 20, 2026 01:01

@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 delta since the prior pullfrog review (009e86addc): a rebase onto current main, regeneration of the desktop xterm bundle patch, and the mobile WebView payload re-pin that fixes the prior review's blocking finding.

  • Rebased onto main — the branch adopts main's query-string: 9.5.1 mobile override and main's CJK preedit WidthCache hunk in the desktop source patch; the mobile source patch stays contrast-only, so the mobile engine payload is unchanged apart from the already-pinned _seen removal.
  • Desktop bundle patch and root lockfile regenerated — config/patches/@[email protected] is rebuilt from the merged source stanzas and the root pnpm-lock.yaml patch hash moves to ee817998…, matching the committed file.
  • Mobile payload guard re-pinned — mobile/src/terminal/terminal-webview-payload-hash.test.ts:9-10 now pins d04f3370…/730692 for the _seen-removal engine, resolving the prior [!IMPORTANT] finding. Verified locally: the payload test passes 1/1 and the mobile contrast-cache test passes 3/3.
  • Mobile patch registration — mobile/pnpm-workspace.yaml and mobile/pnpm-lock.yaml register '@xterm/[email protected]': 45b11f5c… in pnpm 12's single-line patchedDependencies form, with every importer/snapshot reference carrying the same hash.

Verified against the pinned toolchain at head 4f990f2b30: the committed desktop and mobile patch sha256 values match their lockfile patchedDependencies; a fresh root pnpm install --frozen-lockfile applies the combined patch, and xterm-contrast-cache.test.mjs (4), regenerate-xterm-patches-mobile.test.mjs (5, including the committed-patch/lockfile-hash consistency assertion) and pr-code-change-scope.test.mjs (38) pass 47/47. CI xterm patch sync is green on this head.

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

@nwparker

Copy link
Copy Markdown
Contributor

Closing: this conflicts with main and targets xterm beta.303, while main is on beta.304. The real fix is ~20 lines, but it ships with ~4k lines of audit artifacts, mobile patch tooling, CI edits and lockfile churn. Its own synthetic test needed 100k redraws to grow the heap ~5 MB per terminal. If wanted, this should come back as a ~20-line patch to the beta.304 desktop patch only.

@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