Repository navigation
fix(pty): delete the reply-withholding scheduler - #15578
Conversation
Root-cause follow-up to #15559, which stopped a CPR overtaking a deferred colour reply but left the deferral itself in place. Orca answers terminal queries by writing to the PTY master, which a line discipline in ECHO copies straight back out as junk on a cooked prompt (#12112). The guard was to withhold the write until an `stty` subprocess proved ECHO clear — and forking is what forced the decision to be async. Any deferral, however short, lets a reply written later in the same turn overtake this one, so the async probe was the bug's root cause. Read the bit synchronously instead. Linux and the BSDs redirect a master's mode ioctls to the slave, so a `tcgetattr` on the master fd node-pty already owns answers for the slave with no fork: measured 0.26us against 2403us for the subprocess. With a verdict available inline, a querying program that already cleared ECHO — every raw-mode prober, including the colour probe behind the `gh auth login` report — is answered in its own turn and can never be reordered. The deferral stays for the genuinely cooked case, and the ordering guarantee stays underneath it: hosts whose node-pty predates this patch get no sync probe and fall back to the deferred path, which mixed client/host versions make a live production path. Reply routing is all-or-nothing: a payload needing neither containment nor ordering stays on the host's own path, so a CPR answered during shell startup cannot pass the daemon's post-ready flush gate and splice into the buffered startup command. Native side is fail-safe: a kernel that did not redirect would answer from the master's own termios, whose ECHO defaults set, so the degraded verdict is "echoing" — never a false "quiet". The JS half ships in the pnpm patch while the binding needs a source build, so ORCA_REQUIRE_NODE_PTY_ECHO_STATE=1 makes CI fail rather than silently skip when it is handed an upstream prebuild. Co-authored-by: Brennan <[email protected]>
Three defects found in external review of the reply-ordering work. node-pty delivers onData inside the master write, so a query can be answered while the queue is mid-flush. `flushPendingWrites` spliced the array off before writing, so that reply saw an empty queue, took the same-turn path, and landed ahead of entries the loop had not written yet — reproduced as 01, 99, 02, 03. It now shifts one entry at a time so a re-entrant reply queues behind the rest, bounded by the length at entry so a re-entrant push cannot spin the loop. An overflow flush can re-enter as far as teardown. `answer` did not re-check `closed` afterwards, so it queued behind a closed delivery, returned true, and the reply was never written and never reported. The payload router's ownership comment overstated its guarantee. The `any` semantics are deliberate — returning false after a constituent was already written would have the caller re-write the whole payload and duplicate it into the child's stdin — so the residual mixed-failure drop is now documented rather than implied away.
Orca answered a terminal query by withholding the write until a probe proved the slave's ECHO bit was clear. That was the wrong mechanism, and it is now gone: replies are written in the caller's turn and their echo is contained on the output side, where it always was. Withholding never removed an echo. The wait was bounded and always ended in a write, so the output-side projections were doing the work the whole time — including the readline rewrite, which happens with the tty already raw and which therefore no reading of the ECHO bit can predict. What withholding did add was an asynchronous write path, and that is what let one reply overtake another and land in the next program's stdin (#15559), what produced a re-entrancy inversion inside its own flush, and what four rounds of regressions have lived in. The last thing it covered was the verbatim echo of a `stty -echoctl` tty. That shape is now projected directly. It starts with ESC, so it is matched only when complete and never held as a partial: holding it would take a bare trailing ESC from the query parser and an expired hold would release it raw, so a query torn at its own ESC would never be answered. Complete-match-only is what makes the shape safe to project at all. Measured on a real pty: a cooked-mode master write is both echoed AND delivered — ECHO copies the bytes without consuming them from the slave's input queue, so a program arming raw mode with TCSANOW/TCSADRAIN (libuv's setRawMode, hence every Node agent) still reads them. Only a TCSAFLUSH switcher discards it, which it does on every terminal, none of which gates a reply on termios state. Deletes the pending-write queue, the async stty probe, the poll budget and probe rate limit, the deadline-driven flush, and the answer/ answerInOrder split. Replies now leave in call order by construction. No packaging, native or CI surface is touched.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review. 📝 WalkthroughWalkthroughThe change replaces PTY slave ECHO probing and deferred query-reply writes with synchronous reply delivery and output-side echo projection matching. Terminal query parsing now supports consecutive replies. Local and remote PTY paths preserve reply atomicity, ordering, and bounded buffering. New tests cover DA1, CPR, OSC, remote validation, viewport claims, Fish child-stdin handoff, and SSH relays. Reliability-gate and workflow configuration now include the expanded coverage. Minor formatting and build-script updates are also included. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
src/shared/terminal-query-reply-delivery.ts (1)
7-19: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winShorten the affected comments to concise, non-obvious invariants. Keep the regression purpose and issue reference in the Fish test; elsewhere retain only the behavior or invariant that is not obvious from the code. Move walkthroughs, terminal-mode detail, and extended rationale into tests or documentation where needed.
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 20b27ca4-aebb-4d8b-96e3-c3d79c35b1fa
📒 Files selected for processing (34)
config/reliability-gates.jsoncconfig/scripts/pr-workflow-parallelism.test.mjsconfig/scripts/wsl-git-shell-benchmark.mjspackage.jsonsrc/main/daemon/session-subprocess-handle.tssrc/main/daemon/session.test.tssrc/main/daemon/session.tssrc/main/ipc/pty-dispatcher-handshake-osc-answers.test.tssrc/main/providers/local-pty-provider.tssrc/relay/pty-handler.tssrc/renderer/src/components/WorktreeJumpPalette.test.tsxsrc/renderer/src/components/settings/CliSkillRuntimeSetup.test.tsxsrc/renderer/src/components/settings/CliSkillRuntimeSetup.tsxsrc/renderer/src/components/terminal-pane/issue-12112-agent-pane-startup-color-reply-leak.repro.test.tssrc/renderer/src/components/terminal-pane/pty-input-write-queue.test.tssrc/renderer/src/components/terminal-pane/pty-input-write-queue.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-batching.test.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-batching.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport-input-coalescing.test.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.tssrc/shared/fish-query-reply-child-stdin.node-pty.test.tssrc/shared/pty-slave-line-discipline-echo.test.tssrc/shared/pty-slave-line-discipline-echo.tssrc/shared/pty-startup-ingress-contract.tssrc/shared/pty-startup-ingress-live-query-reply.test.tssrc/shared/pty-startup-ingress.test.tssrc/shared/pty-startup-ingress.tssrc/shared/pty-startup-reply-delivery.tssrc/shared/pty-startup-reply-echo-shapes.tssrc/shared/terminal-query-reply-delivery.tssrc/shared/terminal-query-reply.test.tssrc/shared/terminal-query-reply.tstests/e2e/pty-input-write-queue-ssh.spec.ts
💤 Files with no reviewable changes (1)
- src/shared/pty-startup-ingress-contract.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| // Relay PTYs need the local provider's cooked-echo containment (#13137). | ||
| if (takeLiveQueryReply(managed.startupIngress, data)) { | ||
| // DA1/CPR stay immediate unless an echo-risk reply is already held (#13892, #15559). |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Update the write-path comments: no reply is held any more. This PR removed the pending-write queue and the deferral mechanism, so both comments describe a hold that no longer exists. answerLiveQueryReply now writes every accepted reply synchronously, and echo containment happens through the output-side projections.
src/relay/pty-handler.ts#L1880-L1881: replace "unless an echo-risk reply is already held (#13892,#15559)" with a statement that replies are written in call order and their echoes are suppressed on the output side.src/main/providers/local-pty-provider.ts#L1189-L1190: apply the same correction to "unless one of those is still held, which they must not overtake (#13137,#7329,#15559)".
📍 Affects 2 files
src/relay/pty-handler.ts#L1880-L1881(this comment)src/main/providers/local-pty-provider.ts#L1189-L1190
| it('applies the same bound to DA1 replies kept atomic for ordering', async () => { | ||
| const { writes, pendingYields, queue } = createParkedQueue() | ||
| const replies = Array.from({ length: 10_000 }, (_, index) => `\x1b[?${index};2c`) | ||
|
|
||
| for (const reply of replies) { | ||
| expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true) | ||
| } | ||
| expect(queue.enqueue('pty-1', 'k')).toBe(true) | ||
|
|
||
| await Promise.resolve() | ||
| for (let turn = 0; turn < PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES; turn += 1) { | ||
| await releaseNextWrite(writes, pendingYields) | ||
| } | ||
| await queue.waitForDrain() |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Release the final queued write before waitForDrain.
The first reply writes before the loop starts. The 64 releases drain the retained replies. The last reply then yields because k is still pending. waitForDrain() waits for that unresolved yield and the test times out.
Proposed fix
for (let turn = 0; turn < PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES; turn += 1) {
await releaseNextWrite(writes, pendingYields)
}
+ await releaseNextWrite(writes, pendingYields)
await queue.waitForDrain()📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| it('applies the same bound to DA1 replies kept atomic for ordering', async () => { | |
| const { writes, pendingYields, queue } = createParkedQueue() | |
| const replies = Array.from({ length: 10_000 }, (_, index) => `\x1b[?${index};2c`) | |
| for (const reply of replies) { | |
| expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true) | |
| } | |
| expect(queue.enqueue('pty-1', 'k')).toBe(true) | |
| await Promise.resolve() | |
| for (let turn = 0; turn < PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES; turn += 1) { | |
| await releaseNextWrite(writes, pendingYields) | |
| } | |
| await queue.waitForDrain() | |
| it('applies the same bound to DA1 replies kept atomic for ordering', async () => { | |
| const { writes, pendingYields, queue } = createParkedQueue() | |
| const replies = Array.from({ length: 10_000 }, (_, index) => `\x1b[?${index};2c`) | |
| for (const reply of replies) { | |
| expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true) | |
| } | |
| expect(queue.enqueue('pty-1', 'k')).toBe(true) | |
| await Promise.resolve() | |
| for (let turn = 0; turn < PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES; turn += 1) { | |
| await releaseNextWrite(writes, pendingYields) | |
| } | |
| await releaseNextWrite(writes, pendingYields) | |
| await queue.waitForDrain() |
| let accepted = false | ||
| for (const reply of replies) { | ||
| accepted = delivery.answer(reply) || accepted | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Do not report a partially delivered payload as handled.
If an earlier delivery.answer(reply) succeeds and a later one fails, accepted remains true. answerLiveQueryReply then prevents the host path from writing the payload, so the failed reply suffix is dropped.
Return per-reply delivery status and forward only the unaccepted suffix. Do not replay replies that already reached the PTY. Add a regression test where the second write fails.
Archaeology on how withholding got here, and what its tests were really protecting. Deleting the ECHO probe took four tests with it that were not about the probe at all: they cover createSttyProbe, which the shell-readiness line-editor probe still uses — in-flight sharing, the per-platform stty flag, and transient-versus-permanent failure latching. Restored against the line-editor probe, which is now their only caller. Also pins the property that answers the one case an immediate write cannot serve. A program that queries while cooked and then arms raw mode with TCSAFLUSH discards the reply with the rest of its input queue. Nothing can prevent that from the terminal side, and no terminal tries. What matters is that such a program re-queries after its own timeout: the ingress declines to answer an already-answered slot but forwards the duplicate downstream, so the renderer's emulator answers the retry, by which point the program is raw. The retry path is the recovery, not withholding.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/shared/pty-slave-line-discipline-echo.test.ts (1)
51-52: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten the test comments.
Keep the non-obvious retry rationale. Remove the detailed explanation that the test names and assertions already show.
Proposed cleanup
- // These cover createSttyProbe, which the line-editor probe shares. The ECHO probe that - // used to exercise them is gone, but the subprocess machinery under it is still live. + // The line-editor probe still exercises createSttyProbe. ... - // Why: a multi-pane restore forks these in a burst, so EAGAIN and the timeout kill - // are contention — condemning the pty to guessing for its whole life on one of - // those is the failure mode, not the protection. + // Keep transient subprocess failures retryable.As per coding guidelines, comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.
Also applies to: 79-81
Source: Coding guidelines
src/shared/pty-startup-ingress-live-query-reply.test.ts (1)
162-167: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReduce the setup comment to the required condition.
State the TCSAFLUSH fallback and the downstream retry behavior. The current comment repeats details that the test name and assertions show.
Proposed cleanup
- // The self-heal for the one case an immediate write cannot serve: a program that - // queries while cooked and then arms raw mode with TCSAFLUSH discards the reply along - // with the rest of its input queue. Measured on a real pty; TCSANOW/TCSADRAIN (libuv, - // so every Node agent) keep it. Such a program re-queries after its own timeout, and - // the re-query must NOT be swallowed as already-answered — it is passed downstream so - // the renderer's emulator answers it, by which point the program is raw. + // Forward a retry when TCSAFLUSH discards the immediate reply.As per coding guidelines, comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 2f4a6b20-a92c-4aa6-a45d-20d783c9b2bf
📒 Files selected for processing (2)
src/shared/pty-slave-line-discipline-echo.test.tssrc/shared/pty-startup-ingress-live-query-reply.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
Reverting pr.yml to main dropped the exclusion for the fish query-reply test, which this branch keeps, so it would have run in the sharded lane as well. Restores it to the shell-contracts include list and the shard exclude list, and drops the parallelism expectations for the deleted cooked-querier suite and the echo-state env guard.
* fix(pty): answer a terminal colour query in its own turn Root-cause follow-up to stablyai#15559, which stopped a CPR overtaking a deferred colour reply but left the deferral itself in place. Orca answers terminal queries by writing to the PTY master, which a line discipline in ECHO copies straight back out as junk on a cooked prompt (stablyai#12112). The guard was to withhold the write until an `stty` subprocess proved ECHO clear — and forking is what forced the decision to be async. Any deferral, however short, lets a reply written later in the same turn overtake this one, so the async probe was the bug's root cause. Read the bit synchronously instead. Linux and the BSDs redirect a master's mode ioctls to the slave, so a `tcgetattr` on the master fd node-pty already owns answers for the slave with no fork: measured 0.26us against 2403us for the subprocess. With a verdict available inline, a querying program that already cleared ECHO — every raw-mode prober, including the colour probe behind the `gh auth login` report — is answered in its own turn and can never be reordered. The deferral stays for the genuinely cooked case, and the ordering guarantee stays underneath it: hosts whose node-pty predates this patch get no sync probe and fall back to the deferred path, which mixed client/host versions make a live production path. Reply routing is all-or-nothing: a payload needing neither containment nor ordering stays on the host's own path, so a CPR answered during shell startup cannot pass the daemon's post-ready flush gate and splice into the buffered startup command. Native side is fail-safe: a kernel that did not redirect would answer from the master's own termios, whose ECHO defaults set, so the degraded verdict is "echoing" — never a false "quiet". The JS half ships in the pnpm patch while the binding needs a source build, so ORCA_REQUIRE_NODE_PTY_ECHO_STATE=1 makes CI fail rather than silently skip when it is handed an upstream prebuild. Co-authored-by: Brennan <[email protected]> * fix(pty): keep the flush ordered under synchronous re-entry Three defects found in external review of the reply-ordering work. node-pty delivers onData inside the master write, so a query can be answered while the queue is mid-flush. `flushPendingWrites` spliced the array off before writing, so that reply saw an empty queue, took the same-turn path, and landed ahead of entries the loop had not written yet — reproduced as 01, 99, 02, 03. It now shifts one entry at a time so a re-entrant reply queues behind the rest, bounded by the length at entry so a re-entrant push cannot spin the loop. An overflow flush can re-enter as far as teardown. `answer` did not re-check `closed` afterwards, so it queued behind a closed delivery, returned true, and the reply was never written and never reported. The payload router's ownership comment overstated its guarantee. The `any` semantics are deliberate — returning false after a constituent was already written would have the caller re-write the whole payload and duplicate it into the child's stdin — so the residual mixed-failure drop is now documented rather than implied away. * fix(pty): delete the reply-withholding scheduler Orca answered a terminal query by withholding the write until a probe proved the slave's ECHO bit was clear. That was the wrong mechanism, and it is now gone: replies are written in the caller's turn and their echo is contained on the output side, where it always was. Withholding never removed an echo. The wait was bounded and always ended in a write, so the output-side projections were doing the work the whole time — including the readline rewrite, which happens with the tty already raw and which therefore no reading of the ECHO bit can predict. What withholding did add was an asynchronous write path, and that is what let one reply overtake another and land in the next program's stdin (stablyai#15559), what produced a re-entrancy inversion inside its own flush, and what four rounds of regressions have lived in. The last thing it covered was the verbatim echo of a `stty -echoctl` tty. That shape is now projected directly. It starts with ESC, so it is matched only when complete and never held as a partial: holding it would take a bare trailing ESC from the query parser and an expired hold would release it raw, so a query torn at its own ESC would never be answered. Complete-match-only is what makes the shape safe to project at all. Measured on a real pty: a cooked-mode master write is both echoed AND delivered — ECHO copies the bytes without consuming them from the slave's input queue, so a program arming raw mode with TCSANOW/TCSADRAIN (libuv's setRawMode, hence every Node agent) still reads them. Only a TCSAFLUSH switcher discards it, which it does on every terminal, none of which gates a reply on termios state. Deletes the pending-write queue, the async stty probe, the poll budget and probe rate limit, the deadline-driven flush, and the answer/ answerInOrder split. Replies now leave in call order by construction. No packaging, native or CI surface is touched. * test(pty): restore stty-probe coverage and pin the duplicate-query retry Archaeology on how withholding got here, and what its tests were really protecting. Deleting the ECHO probe took four tests with it that were not about the probe at all: they cover createSttyProbe, which the shell-readiness line-editor probe still uses — in-flight sharing, the per-platform stty flag, and transient-versus-permanent failure latching. Restored against the line-editor probe, which is now their only caller. Also pins the property that answers the one case an immediate write cannot serve. A program that queries while cooked and then arms raw mode with TCSAFLUSH discards the reply with the rest of its input queue. Nothing can prevent that from the terminal side, and no terminal tries. What matters is that such a program re-queries after its own timeout: the ingress declines to answer an already-answered slot but forwards the duplicate downstream, so the renderer's emulator answers the retry, by which point the program is raw. The retry path is the recovery, not withholding. * ci(pty): keep the fish real-PTY test in the shell-contracts lane only Reverting pr.yml to main dropped the exclusion for the fish query-reply test, which this branch keeps, so it would have run in the sharded lane as well. Restores it to the shell-contracts include list and the shard exclude list, and drops the parallelism expectations for the deleted cooked-querier suite and the echo-state env guard. --------- Co-authored-by: Brennan <[email protected]>
* fix(pty): answer a terminal colour query in its own turn Root-cause follow-up to stablyai#15559, which stopped a CPR overtaking a deferred colour reply but left the deferral itself in place. Orca answers terminal queries by writing to the PTY master, which a line discipline in ECHO copies straight back out as junk on a cooked prompt (stablyai#12112). The guard was to withhold the write until an `stty` subprocess proved ECHO clear — and forking is what forced the decision to be async. Any deferral, however short, lets a reply written later in the same turn overtake this one, so the async probe was the bug's root cause. Read the bit synchronously instead. Linux and the BSDs redirect a master's mode ioctls to the slave, so a `tcgetattr` on the master fd node-pty already owns answers for the slave with no fork: measured 0.26us against 2403us for the subprocess. With a verdict available inline, a querying program that already cleared ECHO — every raw-mode prober, including the colour probe behind the `gh auth login` report — is answered in its own turn and can never be reordered. The deferral stays for the genuinely cooked case, and the ordering guarantee stays underneath it: hosts whose node-pty predates this patch get no sync probe and fall back to the deferred path, which mixed client/host versions make a live production path. Reply routing is all-or-nothing: a payload needing neither containment nor ordering stays on the host's own path, so a CPR answered during shell startup cannot pass the daemon's post-ready flush gate and splice into the buffered startup command. Native side is fail-safe: a kernel that did not redirect would answer from the master's own termios, whose ECHO defaults set, so the degraded verdict is "echoing" — never a false "quiet". The JS half ships in the pnpm patch while the binding needs a source build, so ORCA_REQUIRE_NODE_PTY_ECHO_STATE=1 makes CI fail rather than silently skip when it is handed an upstream prebuild. Co-authored-by: Brennan <[email protected]> * fix(pty): keep the flush ordered under synchronous re-entry Three defects found in external review of the reply-ordering work. node-pty delivers onData inside the master write, so a query can be answered while the queue is mid-flush. `flushPendingWrites` spliced the array off before writing, so that reply saw an empty queue, took the same-turn path, and landed ahead of entries the loop had not written yet — reproduced as 01, 99, 02, 03. It now shifts one entry at a time so a re-entrant reply queues behind the rest, bounded by the length at entry so a re-entrant push cannot spin the loop. An overflow flush can re-enter as far as teardown. `answer` did not re-check `closed` afterwards, so it queued behind a closed delivery, returned true, and the reply was never written and never reported. The payload router's ownership comment overstated its guarantee. The `any` semantics are deliberate — returning false after a constituent was already written would have the caller re-write the whole payload and duplicate it into the child's stdin — so the residual mixed-failure drop is now documented rather than implied away. * fix(pty): delete the reply-withholding scheduler Orca answered a terminal query by withholding the write until a probe proved the slave's ECHO bit was clear. That was the wrong mechanism, and it is now gone: replies are written in the caller's turn and their echo is contained on the output side, where it always was. Withholding never removed an echo. The wait was bounded and always ended in a write, so the output-side projections were doing the work the whole time — including the readline rewrite, which happens with the tty already raw and which therefore no reading of the ECHO bit can predict. What withholding did add was an asynchronous write path, and that is what let one reply overtake another and land in the next program's stdin (stablyai#15559), what produced a re-entrancy inversion inside its own flush, and what four rounds of regressions have lived in. The last thing it covered was the verbatim echo of a `stty -echoctl` tty. That shape is now projected directly. It starts with ESC, so it is matched only when complete and never held as a partial: holding it would take a bare trailing ESC from the query parser and an expired hold would release it raw, so a query torn at its own ESC would never be answered. Complete-match-only is what makes the shape safe to project at all. Measured on a real pty: a cooked-mode master write is both echoed AND delivered — ECHO copies the bytes without consuming them from the slave's input queue, so a program arming raw mode with TCSANOW/TCSADRAIN (libuv's setRawMode, hence every Node agent) still reads them. Only a TCSAFLUSH switcher discards it, which it does on every terminal, none of which gates a reply on termios state. Deletes the pending-write queue, the async stty probe, the poll budget and probe rate limit, the deadline-driven flush, and the answer/ answerInOrder split. Replies now leave in call order by construction. No packaging, native or CI surface is touched. * test(pty): restore stty-probe coverage and pin the duplicate-query retry Archaeology on how withholding got here, and what its tests were really protecting. Deleting the ECHO probe took four tests with it that were not about the probe at all: they cover createSttyProbe, which the shell-readiness line-editor probe still uses — in-flight sharing, the per-platform stty flag, and transient-versus-permanent failure latching. Restored against the line-editor probe, which is now their only caller. Also pins the property that answers the one case an immediate write cannot serve. A program that queries while cooked and then arms raw mode with TCSAFLUSH discards the reply with the rest of its input queue. Nothing can prevent that from the terminal side, and no terminal tries. What matters is that such a program re-queries after its own timeout: the ingress declines to answer an already-answered slot but forwards the duplicate downstream, so the renderer's emulator answers the retry, by which point the program is raw. The retry path is the recovery, not withholding. * ci(pty): keep the fish real-PTY test in the shell-contracts lane only Reverting pr.yml to main dropped the exclusion for the fish query-reply test, which this branch keeps, so it would have run in the sharded lane as well. Restores it to the shell-contracts include list and the shard exclude list, and drops the parallelism expectations for the deleted cooked-querier suite and the echo-state env guard. --------- Co-authored-by: Brennan <[email protected]>
The contrast floor is user-configurable upstream (stablyai#18126) and the POSIX query-reply ordering fix shipped as stablyai#15559/stablyai#15578, so neither needs tracking anymore.
* fix(pty): answer a terminal colour query in its own turn Root-cause follow-up to stablyai#15559, which stopped a CPR overtaking a deferred colour reply but left the deferral itself in place. Orca answers terminal queries by writing to the PTY master, which a line discipline in ECHO copies straight back out as junk on a cooked prompt (stablyai#12112). The guard was to withhold the write until an `stty` subprocess proved ECHO clear — and forking is what forced the decision to be async. Any deferral, however short, lets a reply written later in the same turn overtake this one, so the async probe was the bug's root cause. Read the bit synchronously instead. Linux and the BSDs redirect a master's mode ioctls to the slave, so a `tcgetattr` on the master fd node-pty already owns answers for the slave with no fork: measured 0.26us against 2403us for the subprocess. With a verdict available inline, a querying program that already cleared ECHO — every raw-mode prober, including the colour probe behind the `gh auth login` report — is answered in its own turn and can never be reordered. The deferral stays for the genuinely cooked case, and the ordering guarantee stays underneath it: hosts whose node-pty predates this patch get no sync probe and fall back to the deferred path, which mixed client/host versions make a live production path. Reply routing is all-or-nothing: a payload needing neither containment nor ordering stays on the host's own path, so a CPR answered during shell startup cannot pass the daemon's post-ready flush gate and splice into the buffered startup command. Native side is fail-safe: a kernel that did not redirect would answer from the master's own termios, whose ECHO defaults set, so the degraded verdict is "echoing" — never a false "quiet". The JS half ships in the pnpm patch while the binding needs a source build, so ORCA_REQUIRE_NODE_PTY_ECHO_STATE=1 makes CI fail rather than silently skip when it is handed an upstream prebuild. Co-authored-by: Brennan <[email protected]> * fix(pty): keep the flush ordered under synchronous re-entry Three defects found in external review of the reply-ordering work. node-pty delivers onData inside the master write, so a query can be answered while the queue is mid-flush. `flushPendingWrites` spliced the array off before writing, so that reply saw an empty queue, took the same-turn path, and landed ahead of entries the loop had not written yet — reproduced as 01, 99, 02, 03. It now shifts one entry at a time so a re-entrant reply queues behind the rest, bounded by the length at entry so a re-entrant push cannot spin the loop. An overflow flush can re-enter as far as teardown. `answer` did not re-check `closed` afterwards, so it queued behind a closed delivery, returned true, and the reply was never written and never reported. The payload router's ownership comment overstated its guarantee. The `any` semantics are deliberate — returning false after a constituent was already written would have the caller re-write the whole payload and duplicate it into the child's stdin — so the residual mixed-failure drop is now documented rather than implied away. * fix(pty): delete the reply-withholding scheduler Orca answered a terminal query by withholding the write until a probe proved the slave's ECHO bit was clear. That was the wrong mechanism, and it is now gone: replies are written in the caller's turn and their echo is contained on the output side, where it always was. Withholding never removed an echo. The wait was bounded and always ended in a write, so the output-side projections were doing the work the whole time — including the readline rewrite, which happens with the tty already raw and which therefore no reading of the ECHO bit can predict. What withholding did add was an asynchronous write path, and that is what let one reply overtake another and land in the next program's stdin (stablyai#15559), what produced a re-entrancy inversion inside its own flush, and what four rounds of regressions have lived in. The last thing it covered was the verbatim echo of a `stty -echoctl` tty. That shape is now projected directly. It starts with ESC, so it is matched only when complete and never held as a partial: holding it would take a bare trailing ESC from the query parser and an expired hold would release it raw, so a query torn at its own ESC would never be answered. Complete-match-only is what makes the shape safe to project at all. Measured on a real pty: a cooked-mode master write is both echoed AND delivered — ECHO copies the bytes without consuming them from the slave's input queue, so a program arming raw mode with TCSANOW/TCSADRAIN (libuv's setRawMode, hence every Node agent) still reads them. Only a TCSAFLUSH switcher discards it, which it does on every terminal, none of which gates a reply on termios state. Deletes the pending-write queue, the async stty probe, the poll budget and probe rate limit, the deadline-driven flush, and the answer/ answerInOrder split. Replies now leave in call order by construction. No packaging, native or CI surface is touched. * test(pty): restore stty-probe coverage and pin the duplicate-query retry Archaeology on how withholding got here, and what its tests were really protecting. Deleting the ECHO probe took four tests with it that were not about the probe at all: they cover createSttyProbe, which the shell-readiness line-editor probe still uses — in-flight sharing, the per-platform stty flag, and transient-versus-permanent failure latching. Restored against the line-editor probe, which is now their only caller. Also pins the property that answers the one case an immediate write cannot serve. A program that queries while cooked and then arms raw mode with TCSAFLUSH discards the reply with the rest of its input queue. Nothing can prevent that from the terminal side, and no terminal tries. What matters is that such a program re-queries after its own timeout: the ingress declines to answer an already-answered slot but forwards the duplicate downstream, so the renderer's emulator answers the retry, by which point the program is raw. The retry path is the recovery, not withholding. * ci(pty): keep the fish real-PTY test in the shell-contracts lane only Reverting pr.yml to main dropped the exclusion for the fish query-reply test, which this branch keeps, so it would have run in the sharded lane as well. Restores it to the shell-contracts include list and the shard exclude list, and drops the parallelism expectations for the deleted cooked-querier suite and the echo-state env guard. --------- Co-authored-by: Brennan <[email protected]>
Supersedes #15567. Alternative to making the ECHO probe fast: remove the thing the probe existed to serve.
Net: −583 lines.
pty-startup-reply-delivery.tsgoes 452 → 148. No packaging, native or CI surface is touched — the node-pty patch and lockfile are byte-identical tomain.How the code got this way
PtyStartupReplyDeliverywas born in #12202, fixing #12112, as two commits in one PR:Deferral was therefore never validated as necessary on its own; it shipped alongside projections, and the probe was layered on because shape-matching felt like guessing. What made it guessing was the single shape that couldn't be safely matched: the ESC-initial verbatim form. This PR closes that gap rather than discarding the original reasoning.
Why withholding was the wrong mechanism
It never removed an echo. The wait was bounded and always ended in a write, so the projections were doing the work the whole time.
What it did add was an asynchronous write path — which is what let one reply overtake another and land in the next program's stdin (#15559), what produced a re-entrancy inversion inside its own flush, and what four rounds of regressions have lived in.
The probe couldn't even see the echo source that matters most: readline rewrites and echoes a master write while the tty is already raw with ECHO off, so no reading of the ECHO bit predicts it. That shape was always covered by a projection.
The last hole is closed, not accepted
The one thing withholding covered was the verbatim echo of a
stty -echoctltty. That shape is now projected directly.It starts with ESC, so it is matched only when complete and never held as a partial. That distinction is the whole safety argument: holding it would take a bare trailing ESC — how any read can end — away from the query parser, and an expired hold releases its bytes raw, so a query torn at its own ESC would never be answered. Complete-match-only never diverts a prefix, so there is nothing to steal and nothing to replay. Pinned by a test that tears a query at its own ESC and asserts it is still answered.
What this costs, measured
A cooked-mode master write is both echoed and delivered — ECHO copies the bytes to the master without consuming them from the slave's input queue. Measured on a real pty:
TCSANOW/TCSADRAIN(libuv'ssetRawMode, so every Node agent)TCSAFLUSHSo the only exposure is a program that queries while cooked and then flushes its own input.
And that case self-heals.
answerQuerydeclines an already-answered slot but the ingress forwards the duplicate query downstream, so the renderer's emulator answers the retry — by which point the program is raw. The retry path is the recovery; withholding never needed to be. Pinned by a test.For context, that case loses the reply on every terminal in existence: no reference terminal gates a reply write on termios state (every ECHO read in the reference implementations drives a password-input heuristic, never a write decision), and the protocol specs state an unconditional obligation — "the terminal must respond".
Two tests asserted a cooked write is echoed instead of delivered. That is measurably wrong for
TCSANOW; they now match the real pty.Even after this, Orca remains more protective than the reference behaviour, because it suppresses its own echo at all — including the
-echoctlshape.Deleted
The pending-write queue, the async
sttyprobe, the poll budget and probe rate limit, the deadline-driven flush, and theanswer/answerInOrdersplit. Replies leave in call order by construction, so ordering needs no machinery.Kept: the echo projections, the pre-write registration (node-pty can re-enter
onDatainside the write), and the bounded projection budget so an unmatched shape ages out instead of shadowing the session.Test archaeology
All 85 tests added by the two originating commits (#12202, #13309) were diffed against this branch. 55 survive; of the 30 missing, most are renames of rewritten tests or cover the deleted mechanism itself.
Four were a genuine regression and are restored:
shares one in-flight stty process per PTY,passes the device with the flag its own platform understands, and the transient-versus-permanent failure latching cases. Those never tested the ECHO probe — they covercreateSttyProbe, which the shell-readiness line-editor probe still uses. They are retargeted to that remaining caller.Verification
34,068 tests pass. Typecheck (node + web), oxlint, the max-lines ratchet and the reliability-gate manifest are clean. The gate's invariant is rewritten to describe call-order writes and complete-match-only verbatim projection rather than withholding.