Skip to content

fix(pty): delete the reply-withholding scheduler - #15578

Merged
nwparker merged 5 commits into
mainfrom
nwparker/delete-echo-withholding
Aug 20, 2026
Merged

nwparker merged 5 commits into
mainfrom
nwparker/delete-echo-withholding

Conversation

@nwparker

@nwparker nwparker commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 16 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​688 $\color{#cf222e}{\Huge{\mathbf{−}}}$​631 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​57
Prod 19 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​435 $\color{#cf222e}{\Huge{\mathbf{−}}}$​570 $\color{#cf222e}{\Huge{\mathbf{−}}}$​135

Supersedes #15567. Alternative to making the ECHO probe fast: remove the thing the probe existed to serve.

Net: −583 lines. pty-startup-reply-delivery.ts goes 452 → 148. No packaging, native or CI surface is touched — the node-pty patch and lockfile are byte-identical to main.

How the code got this way

PtyStartupReplyDelivery was born in #12202, fixing #12112, as two commits in one PR:

  1. Added both deferral and echo projections at once — "POSIX defers the write off the query's turn and recognizes its own echo anywhere in a span."
  2. Then added the ECHO probe explicitly to replace the projections' guesswork — "the reply now waits until the ECHO bit is observably clear instead of guessing at echo shapes."

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

raw-mode switch receives a reply written while cooked
TCSANOW / TCSADRAIN (libuv's setRawMode, so every Node agent) yes
TCSAFLUSH no

So the only exposure is a program that queries while cooked and then flushes its own input.

And that case self-heals. answerQuery declines 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 -echoctl shape.

Deleted

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 leave in call order by construction, so ordering needs no machinery.

Kept: the echo projections, the pre-write registration (node-pty can re-enter onData inside 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 cover createSttyProbe, 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.

nwparker and others added 3 commits August 19, 2026 23:34
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.
@coderabbitai

coderabbitai Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 17b15147-cce3-49a5-895b-8299dd6648ad

📥 Commits

Reviewing files that changed from the base of the PR and between e38741d and 77f9fe5.

📒 Files selected for processing (2)
  • .github/workflows/pr.yml
  • config/scripts/pr-workflow-parallelism.test.mjs

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


📝 Walkthrough

Walkthrough

The 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the implementation and rationale in detail, but it omits most required template sections and checklist information. Add the required ELI5, What Changed, Why, Linked Issue, Visual Proof, Testing, Review, Notes, boundary, and Checklist sections.
✅ Passed checks (3 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 identifies the main change: removing the PTY reply-withholding scheduler.
✨ 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: 3

🧹 Nitpick comments (1)
src/shared/terminal-query-reply-delivery.ts (1)

7-19: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2e895da and a102bc8.

📒 Files selected for processing (34)
  • config/reliability-gates.jsonc
  • config/scripts/pr-workflow-parallelism.test.mjs
  • config/scripts/wsl-git-shell-benchmark.mjs
  • package.json
  • src/main/daemon/session-subprocess-handle.ts
  • src/main/daemon/session.test.ts
  • src/main/daemon/session.ts
  • src/main/ipc/pty-dispatcher-handshake-osc-answers.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/relay/pty-handler.ts
  • src/renderer/src/components/WorktreeJumpPalette.test.tsx
  • src/renderer/src/components/settings/CliSkillRuntimeSetup.test.tsx
  • src/renderer/src/components/settings/CliSkillRuntimeSetup.tsx
  • src/renderer/src/components/terminal-pane/issue-12112-agent-pane-startup-color-reply-leak.repro.test.ts
  • src/renderer/src/components/terminal-pane/pty-input-write-queue.test.ts
  • src/renderer/src/components/terminal-pane/pty-input-write-queue.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-batching.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-batching.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-input-coalescing.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/shared/fish-query-reply-child-stdin.node-pty.test.ts
  • src/shared/pty-slave-line-discipline-echo.test.ts
  • src/shared/pty-slave-line-discipline-echo.ts
  • src/shared/pty-startup-ingress-contract.ts
  • src/shared/pty-startup-ingress-live-query-reply.test.ts
  • src/shared/pty-startup-ingress.test.ts
  • src/shared/pty-startup-ingress.ts
  • src/shared/pty-startup-reply-delivery.ts
  • src/shared/pty-startup-reply-echo-shapes.ts
  • src/shared/terminal-query-reply-delivery.ts
  • src/shared/terminal-query-reply.test.ts
  • src/shared/terminal-query-reply.ts
  • tests/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.

Comment thread src/relay/pty-handler.ts
Comment on lines 1880 to +1881
// 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).

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.

📐 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

Comment on lines +251 to +264
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()

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.

🎯 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.

Suggested change
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()

Comment on lines +28 to +31
let accepted = false
for (const reply of replies) {
accepted = delivery.answer(reply) || accepted
}

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.

🗄️ 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.

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

🧹 Nitpick comments (2)
src/shared/pty-slave-line-discipline-echo.test.ts (1)

51-52: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten 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 value

Reduce 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

📥 Commits

Reviewing files that changed from the base of the PR and between a102bc8 and e38741d.

📒 Files selected for processing (2)
  • src/shared/pty-slave-line-discipline-echo.test.ts
  • src/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.
@nwparker
nwparker merged commit c92f394 into main Aug 20, 2026
56 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
* 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]>
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
* 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]>
williamfligor added a commit to williamfligor/orca that referenced this pull request Sep 11, 2026
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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* 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]>
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