Skip to content

Fix flaky terminal column-desync E2E tests under CI load - #7501

Closed
brennanb2025 wants to merge 2 commits into
mainfrom
brennanb2025/sta-1351-terminal-getsize-desync
Closed

brennanb2025 wants to merge 2 commits into
mainfrom
brennanb2025/sta-1351-terminal-getsize-desync

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

What changes

Makes the two flakiest cases in terminal-column-desync-repro.spec.ts reliable under CI load by polling for the PTY↔xterm re-sync instead of asserting an exact match after a fixed 400–500ms wait. Test-only: no product code changes.

  • :129 (visible resize) and :169 (pty:getSize applied size) now poll until the columns agree, bounded at 20s.

What this does NOT do / why it's not a product change

This is not a product bug fix. Investigation (below) concluded the failure was a fragile test, not a defect — so nothing in the terminal/PTY code changes, and the poll still fails if a PTY genuinely never re-syncs (it does not paper over the real column-desync bug this suite guards).

Background — was it a real bug or a bad test?

terminal-column-desync:169 was failing on ~3 of 4 loaded scheduled Linux runs (garbled-TUI repro suite), but passing on lighter runs and locally. Investigation:

  • The originally-scoped product fix would have been a no-op. The idea was to make the daemon's pty:getSize return node-pty's proc.cols instead of the emulator dims. But Session.resize advances the emulator and subprocess atomically, and node-pty caches the requested size in proc.cols — the CI trace shows getSize=72 vs real kernel 117, so returning proc.cols would still report 72. A staff-level design review (three converging reviewers) caught this before any code was written.
  • Evidence it's a fragile test, not a persistent desync: the sibling tests in the same file (:189/:228/:325/:398) deliberately drop resizes and assert the PTY re-syncs, using longer waits (500–900ms) and reload-loops — and they pass on CI. Only :169/:129 failed, and they're the two with the shortest fixed waits and the simplest scenario — they sampled before the async re-sync completed under load. The PTY does re-sync (the whole file passes); the assertion just fired too early.

The fix aligns :169/:129 with how the rest of the file already tolerates the async re-sync.

Design-review outcome

Review correctly blocked the initial product-fix plan as a likely no-op and drove the pivot to the evidence-based test-hardening. Diagnosis was then confirmed empirically (below).

Headline behavior status

Implemented — the two flaky tests are hardened; a genuinely stuck PTY still fails. No product behavior changes.

Validation

  • Local: full file 7/7 (macOS, electron-headless, workers=1); the two hardened tests pass.
  • CI (Linux/xvfb) — the decisive gate: dispatched E2E on this branch (run 28767012980); all 8 terminal-column-desync tests passed under real shard load, including the previously-flaky :169/:129, which converged in ~15s (the old 500ms wait was far too short under load). The 20s poll budget gives headroom over the observed ~15s. (The overall run stays red only on the separately-deferred Batch-3 perf/app-instability groups.)

Perf

Test-only. The poll returns on first convergence and is bounded at 20s (paid only while a resize is still propagating). No product hot path; net suite time neutral (replaces a flaky failure+retry with a bounded settle).

Risks / non-goals

  • If a resize ever takes >20s to reach the PTY, the test fails — intentional: that would be an effectively-stuck PTY (the real bug), not a slow-but-correct re-sync.
  • Does not touch the daemon getSize/emulator asymmetry (a real but separate code smell — daemon reports emulator dims, local reports proc.cols); noted as a possible follow-up, but it is not what reddens these tests and a correct product fix there needs the true kernel winsize (TIOCGWINSZ), which node-pty doesn't expose.
  • Part of STA-1351 (make E2E green); the remaining reds are the deferred Batch-3 perf/app-instability cluster.

brennanb2025 and others added 2 commits July 5, 2026 21:05
The two shortest-wait cases (:129 visible resize, :169 pty:getSize applied
size) asserted an exact match after a fixed 400-500ms wait. The PTY re-sync
after a resize is async (renderer fit -> pty:resize -> daemon -> ioctl); under
CI load it lands later than the fixed wait, so the exact check sampled mid-flight
and flaked. Poll until the sizes agree (bounded 15s). A genuinely dropped resize
that never re-syncs still fails, matching the sibling re-sync tests in this file
that already tolerate async timing with longer waits.

Co-authored-by: Orca <help@stably.ai>
The Linux dispatch converged in ~15s under shard load; 20s gives headroom
while still failing a PTY that genuinely never re-syncs.

Co-authored-by: Orca <help@stably.ai>
@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR updates an end-to-end test file for PTY column desynchronization by adding two polling-based helper functions, waitForPtyColsToMatchXterm and waitForReportedColsToMatchPty, along with a new timeout constant. These helpers repeatedly poll for column-value equality between PTY and xterm state instead of relying on fixed delays. Two existing test scenarios—the visible-resize test and the pty:getSize contract test—are updated to use these new polling helpers in place of prior fixed waitForTimeout calls with single-shot equality assertions.

Changes

Cohort / File(s) Summary
Polling helpers (tests/e2e/terminal-column-desync-repro.spec.ts) Adds COLUMN_RESYNC_TIMEOUT_MS and two polling helper functions for column synchronization checks
Test usage updates (tests/e2e/terminal-column-desync-repro.spec.ts) Replaces fixed-delay waits with polling helper calls in the visible-resize and pty:getSize contract tests

Related PRs: None identified.

Suggested labels: tests, e2e

Suggested reviewers: None identified.

Poem
A rabbit hopped through terminal rows,
Where columns drift and timing goes,
No more fixed waits, just patient polls,
Until PTY and xterm reach their goals,
Then twitched its nose — the tests now flow. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the fix and validation, but it doesn't follow the required template or include several mandatory sections. Add the missing template sections: Summary, Screenshots, Testing checklist, AI Review Report, Security Audit, and Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main change: hardening flaky terminal column-desync E2E tests under CI load.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch brennanb2025/sta-1351-terminal-getsize-desync

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

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

🧹 Nitpick comments (1)
tests/e2e/terminal-column-desync-repro.spec.ts (1)

115-157: 📐 Maintainability & Code Quality | 🔵 Trivial

Consider expect.poll() instead of hand-rolled do-while polling.

Both helpers reimplement a manual polling loop (do {...} while (Date.now() < deadline) + page.waitForTimeout(500)) — duplicated across the two functions. Playwright's expect.poll() (available in the project's 1.59.1) is built exactly for this: configurable timeout/intervals, automatic retry, and integrated failure reporting, and would let the two helpers collapse into one shared polling call each, removing the duplication and the manual deadline bookkeeping.

♻️ Sketch using `expect.poll`
 async function waitForPtyColsToMatchXterm(
   page: Page,
   ptyId: string,
   label: string,
   timeoutMs = COLUMN_RESYNC_TIMEOUT_MS
 ): Promise<void> {
-  const deadline = Date.now() + timeoutMs
-  let snapshot: ColumnSnapshot = { xtermCols: -1, ptyCols: -1 }
-  do {
-    snapshot = await readColumnSnapshot(page, ptyId)
-    if (snapshot.ptyCols === snapshot.xtermCols) {
-      return
-    }
-    await page.waitForTimeout(500)
-  } while (Date.now() < deadline)
-  throw new Error(
-    `${label}: PTY cols (${snapshot.ptyCols}) never re-synced to xterm cols (${snapshot.xtermCols}) ` +
-      `within ${timeoutMs}ms; a stale PTY width that never re-syncs is the column-desync bug`
-  )
+  let last: ColumnSnapshot = { xtermCols: -1, ptyCols: -1 }
+  await expect
+    .poll(
+      async () => {
+        last = await readColumnSnapshot(page, ptyId)
+        return last.ptyCols === last.xtermCols
+      },
+      {
+        timeout: timeoutMs,
+        intervals: [500],
+        message: () =>
+          `${label}: PTY cols (${last.ptyCols}) never re-synced to xterm cols (${last.xtermCols}) ` +
+          `within ${timeoutMs}ms; a stale PTY width that never re-syncs is the column-desync bug`
+      }
+    )
+    .toBe(true)
 }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 8b79234d-1359-4460-9fde-2fa47821496b

📥 Commits

Reviewing files that changed from the base of the PR and between 638a8f7 and ff4ec71.

📒 Files selected for processing (1)
  • tests/e2e/terminal-column-desync-repro.spec.ts

Comment on lines +108 to +157
// Why: the PTY re-sync after a resize is async (renderer fit → pty:resize →
// daemon → ioctl); a fixed wait then exact check samples mid-flight and flakes
// under CI load. Poll until the sizes agree — a genuinely dropped resize that
// never re-syncs still fails (the real column-desync bug), a slow-but-correct
// propagation no longer does.
const COLUMN_RESYNC_TIMEOUT_MS = 20_000

async function waitForPtyColsToMatchXterm(
page: Page,
ptyId: string,
label: string,
timeoutMs = COLUMN_RESYNC_TIMEOUT_MS
): Promise<void> {
const deadline = Date.now() + timeoutMs
let snapshot: ColumnSnapshot = { xtermCols: -1, ptyCols: -1 }
do {
snapshot = await readColumnSnapshot(page, ptyId)
if (snapshot.ptyCols === snapshot.xtermCols) {
return
}
await page.waitForTimeout(500)
} while (Date.now() < deadline)
throw new Error(
`${label}: PTY cols (${snapshot.ptyCols}) never re-synced to xterm cols (${snapshot.xtermCols}) ` +
`within ${timeoutMs}ms; a stale PTY width that never re-syncs is the column-desync bug`
)
}

async function waitForReportedColsToMatchPty(
page: Page,
ptyId: string,
timeoutMs = COLUMN_RESYNC_TIMEOUT_MS
): Promise<void> {
const deadline = Date.now() + timeoutMs
let reportedCols = -1
let ptyCols = -1
do {
ptyCols = await readPtyCols(page, ptyId)
reportedCols = await readReportedPtyCols(page, ptyId)
if (reportedCols === ptyCols) {
return
}
await page.waitForTimeout(500)
} while (Date.now() < deadline)
throw new Error(
`pty:getSize reported ${reportedCols} but the PTY's process.stdout.columns is ${ptyCols} and ` +
`never re-synced within ${timeoutMs}ms; getSize must reflect the APPLIED size so the ` +
`drift-check can detect a dropped resize`
)
}

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect waitForPtyColumnsAtMost to see its actual retry/backoff behavior
rg -n -B2 -A25 'function waitForPtyColumnsAtMost' tests/e2e/terminal-column-desync-repro.spec.ts
rg -n 'READ_ANY_COLS' tests/e2e/terminal-column-desync-repro.spec.ts

Repository: stablyai/orca

Length of output: 256


Bound the PTY probe to the 20s wrapper A single poll can still block for up to 30s inside readPtyCols(), so the 20s timeout here is not a real ceiling and the thrown error can understate the wall-clock cost. Tighten the inner budget or switch this check to expect.poll().

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing as redundant. main already contains the same convergence-poll fix for these tests (:129 / :169) via #7470 ("stabilize chronically-failing e2e suite"), which landed the identical "poll to convergence instead of a fixed wait" approach for terminal-column-desync. This branch was based on the pre-#7470 file, hence the merge conflict. No unique change remains to land.

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.

1 participant