Skip to content

Fix native PTY I/O failures disabling session termination - #19523

Merged
AmethystLiang merged 2 commits into
mainfrom
debug-orca-perf-issue
Sep 8, 2026
Merged

AmethystLiang merged 2 commits into
mainfrom
debug-orca-perf-issue

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​309 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​309
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​113 $\color{#cf222e}{\Huge{\mathbf{−}}}$​12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​101

Problem

When a native PTY I/O operation (write or resize) fails, the subprocess handle sets a dead flag that blocks all subsequent operations—including termination. This prevents killing or force-killing the session until the process naturally exits.

Solution

Separate I/O failure handling from process exit:

  • ioFailed flag: Suppresses further I/O ops after transient errors, but keeps termination and producer flow control available
  • dead flag: Only set after the process actually exits, blocks reentrant signals from exit listeners
  • Move signal authority cleanup before exit events fire, preventing listeners from re-entering kill logic

What Changed

  • src/main/daemon/pty-subprocess/subprocess-handle.ts: Split ioFailed from dead; neutralize kill before exit events
  • src/main/daemon/pty-subprocess-io-failure-cleanup.test.ts: 24 tests covering write/resize failures across platforms, exit-listener reentrancy, and 32 failed-I/O create/close cycles
  • src/main/daemon/pty-subprocess-io-failure-native.test.ts: 4 native POSIX tests with real shells verifying PID reaping and fd closure
  • config/reliability-gates.jsonc: Reliability gate documenting coverage, invariants, and test commands

Why

I/O failures are transient communication issues, not evidence of process exit. Termination must remain available regardless. The fix ensures graceful and forced shutdown work until the process genuinely exits.

Linked Issue

Fixes #

Visual Proof

N/A — no UI change.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated: three test suites covering simulated failures (24 tests, 3.71s), native POSIX (4 tests, 2.52s), and related daemon cleanup (110 tests, 0.617s)

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and 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-platoform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • 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)

I/O failures on write or resize were incorrectly treated as exit evidence,
which disabled further termination attempts and producer flow control.
Separate ioFailed state from dead state; I/O errors suppress operations
but keep kill, forceKill, and signal available. Publish physical exit
before notifying listeners to prevent reentrant cleanup attempts from
accessing the retired native process.
@coderabbitai

coderabbitai Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

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: 432c63b0-42e8-497e-943a-ac38045bb30c

📥 Commits

Reviewing files that changed from the base of the PR and between 04c55f5 and 71a95f8.

📒 Files selected for processing (2)
  • config/reliability-gates.jsonc
  • src/main/daemon/pty-subprocess-io-failure-cleanup.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/daemon/pty-subprocess-io-failure-cleanup.test.ts
  • config/reliability-gates.jsonc

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


📝 Walkthrough

Walkthrough

The subprocess handle now tracks PTY I/O failure separately from physical process exit. Failed write, resize, and clear operations stop without disabling termination. Exit handling marks the process dead and suppresses reentrant termination before notifying listeners. New tests cover macOS, Linux, and Windows mocks, repeated cleanup cycles, ConPTY ownership, and native POSIX process and descriptor cleanup. A reliability gate documents the invariant, test commands, evidence, budgets, and known gaps.

Merge Risk: ⚪ Minimal · up to 71a95

This change separates PTY I/O failure handling from process-exit state so failed I/O no longer prevents termination and cleanup. No actionable merge-blocking risk remains in the supplied change context.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem, solution, scope, testing, and lack of UI changes. However, the required Linked Issue field is incomplete because it contains only Fixes #. The ELI5 section is a… Add the complete linked issue reference after Fixes #. Add a short ELI5 explanation. Confirm or explain the unchecked Agent skill boundary and validation checklist items, including lint, typecheck, test, and build results or CI coverage.
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 3 functions across 3 files. (1 skipped: 1 … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: preventing native PTY I/O failures from disabling session termination.
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.
Full details: Description check

Explanation

The description explains the problem, solution, scope, testing, and lack of UI changes. However, the required Linked Issue field is incomplete because it contains only Fixes #. The ELI5 section is also not explicitly provided, and several checklist items remain unchecked.

Full details: Docstring Coverage

Explanation

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 3 functions across 3 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 78385c77-6532-4574-8c10-e2193c90d76e

📥 Commits

Reviewing files that changed from the base of the PR and between 1a8640a and 04c55f5.

📒 Files selected for processing (4)
  • config/reliability-gates.jsonc
  • src/main/daemon/pty-subprocess-io-failure-cleanup.test.ts
  • src/main/daemon/pty-subprocess-io-failure-native.test.ts
  • src/main/daemon/pty-subprocess/subprocess-handle.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 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.

Caution

This PR breaks pnpm lint: the new reliability gate was inserted inside the previous gate object, leaving config/reliability-gates.jsonc as invalid JSONC.

Reviewed changes

  • ioFailed / dead split — src/main/daemon/pty-subprocess/subprocess-handle.ts now tracks I/O failure separately from process exit, so write/resize/clear are suppressed after a native error while kill/forceKill/signal stay available until the process actually exits.
  • Exit-listener reentrancy fence — the merged onExit handler now marks dead, neutralizes nativeProc.kill (non-Windows), and markDead()s the foreground tracker before acceptExit notifies listeners, so a listener re-entering kill/forceKill/signal can no longer signal a retired PID.
  • Two new test suites — a fault-injected suite (write/resize failures across simulated platforms, 32-cycle reap loop, reentrancy) and a native POSIX suite (real shells, ESRCH + EBADF assertions).
  • Reliability gate — a new terminal-session.io-failure-cleanup experimental gate documents the contract.

The core handle change is correct and well-tested; the only blocking issue is the malformed gate manifest below.

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

Comment thread config/reliability-gates.jsonc Resolved
- Fixed missing closing brace and comma in reliability-gates.jsonc
- Added clear() operation to PTY mock fixture and test coverage
- Enhanced assertions to verify operation suppression during I/O failures
- Improved kill operation error handling with better promise-chain assertions
- Updated test result summaries in reliability gate documentation
@AmethystLiang
AmethystLiang merged commit 31b84cc into main Sep 8, 2026
6 of 7 checks passed
fabolivark added a commit to ab2webco/orca-oss that referenced this pull request Sep 9, 2026
…uld not be killed (upstream ports) (#370)

* perf(terminal): skip the partial-escape-tail walk on ESC-free PTY chunks (#18748)

`advancePartialEscapeTail` runs once per PTY chunk, on the main thread, for every terminal —
visible, hidden or parked — inside `HeadlessEmulator`'s write path. It unconditionally
concatenated the pending tail with the whole chunk and then walked the result one code unit at
a time through a VT500 state machine.

`extractPartialEscapeTail` only leaves `ground` on an ESC byte, so with no pending tail and no
ESC in the chunk the answer is always ''. Taking that case up front skips both the full-chunk
concat and the walk. `String.prototype.includes` is a native scan, so the gate costs
essentially nothing on the chunks it does not short-circuit.

This is the same gate its two neighbours on the very same ingest path already apply —
`TerminalOscCwdTitleScanner.scan` and `TerminalMouseModeMirror.scan`, both carrying a comment
citing their measured share of a 2.2x ingest regression. This call was simply missed.

Measured by `pnpm bench:terminal-partial-escape-tail` over 640 x 16 KB chunks (10 MB), median
of 7 rounds:

| stream shape | before | after | |
| --- | --- | --- | --- |
| ESC-free (build logs, `cat`, piped output) | 40.3 ms | 0.19 ms | 213x |
| SGR-coloured output (gate does not apply) | 30.6 ms | 32.1 ms | 1.0x |

The benchmark proves equivalence over a 226-case corpus before timing, and a new unit test
pairs every pending-tail state the scanner can be left in against every chunk shape, asserting
the gate is indistinguishable from the unconditional fold.

(cherry picked from commit c36dd5f)

* fix(terminal): fold-safe CAN/SUB and double-ESC handling in partial-escape tail (#19521)

`extractPartialEscapeTail` broke its own fold invariant
(extract(a + b) === extract(extract(a) + b)) in the oscEsc/stringEsc states,
so a PTY read that split there produced a different pending tail than the
same bytes delivered whole — the tail snapshots append after a restore.

Two causes, both in the "ESC did not terminate the string" branch:

- CAN/SUB were routed through `stateAfterEscByte`, which maps them back to
  `esc` instead of aborting to ground. `extractPartialEscapeTail('\x1bPx\x1b\x18X0abc')`
  returned '\x1b\x18X0abc'; the chunk-split fold returned ''.
- A second ESC opened its new sequence at `i - 1` rather than at itself.
  `extractPartialEscapeTail('\x1b] \x1b\x1b^')` returned '\x1b\x1b^' whole but
  '\x1b^' folded. The fold was right — xterm starts the sequence at the second ESC.

The existing fuzz only asserted the fold as `advance(extract(pending), chunk)`,
which is a tautology because every PENDINGS entry is already a tail. Replaced
with a sweep that re-splits the combined stream at every code-unit boundary,
and extended the alphabet (NUL, 0x20 intermediate, CJK) and SEQUENCES with
CAN/SUB and doubled-ESC-inside-string cases. A 1.25M-split fold fuzz over a
VT alphabet goes from 421 failures to 0.

(cherry picked from commit ed88188)

* fix(pty): un fallo de I/O no es evidencia de exit (upstream #19523)

Port de stablyai/orca#19523. Un throw en `write` o `resize` ponia `dead = true`
—el mismo flag que pone un exit real— y con eso quedaban deshabilitados `kill`,
`forceKill`, `signal` y el flow control del productor: la sesion ya no se podia
terminar nunca. Nuestras dos lineas del bug eran identicas a las que upstream
borra (`pty-subprocess.ts` 1175 y 1188).

Separa `ioFailed` de `dead`, con las mismas tres guardas que upstream
(`write`, `resize`, `pause`); `resume` queda sin tocar, igual que alla.

Los tests de upstream no se pueden portar: reciben un `pty.IPty` ya creado
porque alla extrajeron `createDaemonPtySubprocessHandle` a un modulo aparte, y
nuestro `createPtySubprocess` spawnea el proceso el mismo. Se escriben tres
contra nuestro seam, con el harness que ya existe. Dos de los tres se
verificaron fallando al revertir el arreglo.

* fix(terminal): quitar los panes fantasma que el host ya retiro (upstream #19365)

Port de stablyai/orca#19365. Al reconciliador de layout host-autoritativo le
faltaba el camino de REMOCION: solo materializaba panes que el host nombraba,
nunca desmontaba uno que el host dejo de nombrar. Un pane cuyo PTY termino queda
de fantasma —no renderiza nada y, cuando es el ultimo, se come el siguiente
cierre de la pestaña. Es el sintoma de "pestañas espejadas que se duplican o
desincronizan" en un split remoto.

Los tres helpers (`planTerminalLiveLayoutRemovals`, `selectRetiredPaneIds`,
`trackRetiredLeafIds`) entran tal cual. Lo que hubo que portar es el cableado:
upstream lo consume desde `use-terminal-pane-reconciliation.ts`, un hook que
extrajo despues de nuestra divergencia y que aca no existe, asi que va en el
mismo effect de `TerminalPane.tsx` que ya aplicaba las inserciones. Sus dos
archivos propios se descartan por eso.

Un leaf solo cuenta como retirado contra el layout que el host nombro ANTES, asi
que los dos refs del hook (`hostLayoutLeafIdsRef`, `retiredLeafIdsRef`) van
junto a los otros refs de pane. `ptyRecoveryStatesByPaneId` entra a las deps
porque es lo que re-corre el effect cuando el PTY de un pane retirado termina
de cerrarse.

25 tests del reconciliador y 4317 de terminal-pane en verde. El warning de
react-doctor en ese archivo es previo: verificado con stash sobre main.

* test(e2e): traer el fixture que el spec de panes fantasma importa

El spec e2e de #19365 importa `paired-browser-placement-fixture`, que upstream
agrego despues de nuestra divergencia: sin el, `playwright --list` falla con
"Cannot find module" y tumba el job de static analysis entero — no solo ese
spec.

Se trae del upstream tal cual. Sus tres dependencias (`orca-app`,
`headless-paired-runtime-host`, `paired-electron-client`) ya existen aca, asi
que no arrastra nada mas. Verificado: `playwright --list` vuelve a resolver los
591 tests.

* test(e2e): declarar el spec de panes fantasma en el ratchet de conteo

El spec que trae upstream #19365 sube el conteo de electron-headless de 590 a
591, y el ratchet exige declararlo a proposito. Es el unico spec que agrega la
tanda.

---------

Co-authored-by: Neil <[email protected]>
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