Skip to content

fix(orchestration): revalidate an attempted Enter instead of resending it - #19911

Merged
brennanb2025 merged 1 commit into
mainfrom
brennanb2025/mailbox-pointer-enter-revalidate
Sep 10, 2026
Merged

brennanb2025 merged 1 commit into
mainfrom
brennanb2025/mailbox-pointer-enter-revalidate

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

This is a behavioral correctness fix, not a performance change.
Measured perf impact: −0.10 µs, inside noise. Nothing here is intended to make anything faster.
Scope: asynchronous PTY providers — including SSH and daemon-backed local PTYs. The window does not exist in the direct in-process LocalPtyProvider.

The bug

When a PTY retires mid-delivery, retirePty called markAsUndelivered on every staged message, clearing all pointer state and making the whole batch redeliverable.

That is correct for a pointer whose Enter never fired. It is wrong for one already at ENTER_ATTEMPTED: that Enter was written to the transport and may well have landed. Redelivering it types the same mail into the pane a second time.

Why it affects asynchronous providers

The vulnerable window is exactly mailbox-pointer-submit.ts:114 (the row reaches ENTER_ATTEMPTED) to :118 (await deps.writePty(ptyId, '\r') resolves). How wide that is depends entirely on the provider:

Provider writeWithSettlement Window
direct in-process local — local-pty-provider.ts:83 (id, data): WriteSettlement — synchronous effectively zero
daemon-backed local — daemon-pty-router.ts:97 (id, data): Promise<WriteSettlement> — daemon IPC one asynchronous settlement
SSH — ssh-pty-provider.ts:49 (id, data): Promise<WriteSettlement> — remote RPC one asynchronous settlement

On the direct in-process LocalPtyProvider, settlement is not a promise, so the await resolves on the next microtask. A PTY exit arrives as a libuv macrotask and cannot interleave with a microtask, so retirePty cannot observe the row at ENTER_ATTEMPTED.

For daemon-backed local PTYs and SSH PTYs, settlement crosses an asynchronous IPC/RPC boundary, and macrotasks — including the PTY exit event — can run while it is pending.

I did not measure live provider settlement latency, so no timing figure is quoted. The scope claim is structural, from the provider types and delivery path.

The fix

The Enter timer is cleared at the top of retirement, which is positive evidence about what happened:

Phase Meaning Before After
RESERVED claimed, nothing typed redeliverable redeliverable
WRITE_ATTEMPTED pointer typed, Enter never fired redeliverable redeliverable
ENTER_ATTEMPTED Enter written, settlement unknown cleared and resent left at phase for the resume path to revalidate

Only the ambiguous case changes. This matches what mailbox-pointer-submit.ts already documents for an unverifiable settlement — "neither settling it as delivered nor rolling it back ... is provable here" — and the execution-boundary rule that loss of contact is never evidence about what the remote process received. An Enter whose settlement never came back is unverifiable, not "never sent".

The flight now carries the process incarnation that staged it, so retirement can name exactly the rows it owns instead of clearing by message id alone. Where no incarnation is recorded, the previous markAsUndelivered path is kept.

Performance

Explicitly none, and measured rather than assumed. Against a copy of a real 368 MB orchestration database (50,866 messages), WAL + synchronous=NORMAL, statements prepared once, 500 warmup then 4,000 iterations × 7 reps, median, shared staging cost subtracted:

Arm Isolated call cost
markAsUndelivered (before) 26.69 µs
releaseMailboxPointerEnter (after) 26.59 µs

Delta −0.10 µs, identical WAL growth. Both are a single UPDATE inside a SAVEPOINT; the added fence predicates ride on a row lookup that already happens.

It also runs rarely: the changed code sits behind if (flight?.stagedMessageIds.length), so a working title frame with no airborne delivery does a Map lookup and returns without touching the database.

Validation

pnpm tc:node and oxlint clean. Orchestration and stale-leaf suites pass.

Two ablations confirm the new coverage is a real regression guard rather than a pin:

  • releasing ENTER_ATTEMPTED as well → the new test fails
  • reverting to main's blanket markAsUndelivered → the new test fails

Worth flagging: the three existing terminal-send-stale-leaf-liveness cases pass either way, because they all exercise a WRITE_ATTEMPTED flight. The phase-3 behavior was previously unguarded entirely, which is why this adds coverage for it directly rather than relying on those.

One pre-existing failure reproduces on main and is unrelated: the orchestration-cli-subprocess keepalive assertion.

Context

Supersedes #19644, which bundled this fix into a much larger restructuring of mailbox pointer recovery. Measurement did not support that restructuring: its per-frame change saved 1.84 µs with zero I/O difference, the partial index it claimed to enable was already in use on main with an identical query plan, and its incarnation fencing guarded a window markAsUndelivered already closes. This is the one demonstrated improvement from that work, in 5 files. Full numbers are recorded on #19644.

…g it

When a PTY retires mid-delivery, every staged message was marked undelivered,
which made all of them redeliverable. That is right for a pointer whose Enter
never fired, but an Enter that was already written may have landed: redelivering
it types the same mail into the pane a second time.

The Enter timer is cleared at the top of retirement, so a RESERVED or
WRITE_ATTEMPTED pointer provably never submitted and is released. An
ENTER_ATTEMPTED pointer is ambiguous and now stays at its phase for the resume
path to revalidate, matching the policy mailbox-pointer-submit.ts already
documents for an unverifiable settlement.
@coderabbitai

coderabbitai Bot commented Sep 10, 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: b0b32db0-0e3d-42ee-bb91-407dea5acde6

📥 Commits

Reviewing files that changed from the base of the PR and between 26f9fd8 and 7e89bb1.

📒 Files selected for processing (5)
  • src/main/runtime/orchestration/mailbox-pointer-delivery.ts
  • src/main/runtime/orchestration/mailbox-pointer-stage.test.ts
  • src/main/runtime/orchestration/mailbox-pointer-stage.ts
  • src/main/runtime/orchestration/mailbox-pointer-state.ts
  • src/main/runtime/terminal-send-stale-leaf-liveness.test.ts

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


📝 Walkthrough

Walkthrough

The change records the target process incarnation on mailbox pointer delivery flights. During PTY retirement, reserved or write-attempted pointer entries are released when ownership checks succeed. Entries with unsettled Enter writes remain pending for resume validation. When database or incarnation data is unavailable, the existing undelivered fallback remains active. Tests cover both retirement states and related stale-leaf cleanup paths.

Merge Risk: ⚪ Minimal · up to 7e89b

The change prevents duplicate terminal input after PTY retirement while releasing only reservations that are safe to retry. Regression coverage and reported checks support merging with no current actionable risk.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description provides a detailed explanation of the bug, fix, scope, performance impact, testing, and known unrelated failure. However, it does not follow several required template sections, includ… Add the missing template sections. Include a linked issue using the required Fixes #... format, state N/A with a reason under Visual Proof if no visual change exists, complete the applicable AI Disclosure and Agent skill upstream bounda…
✅ 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 describes the primary behavior fix: preserving attempted Enter submissions for revalidation instead of resending them.
Full details: Description check

Explanation

The description provides a detailed explanation of the bug, fix, scope, performance impact, testing, and known unrelated failure. However, it does not follow several required template sections, including the explicit Linked Issue format, Visual Proof or N/A statement, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist.

Resolution

Add the missing template sections. Include a linked issue using the required Fixes #... format, state N/A with a reason under Visual Proof if no visual change exists, complete the applicable AI Disclosure and Agent skill upstream boundary sections, add the required Notes and Review content, and mark or explain the Checklist items.

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Phase-aware release at retirement — retirePty now records the staging incarnation on the flight and, when present, calls releaseMailboxPointerEnter limited to RESERVED/WRITE_ATTEMPTED, leaving ENTER_ATTEMPTED rows in place. Only the ambiguous phase keeps its state; the blanket markAsUndelivered path is retained as a fallback when no incarnation was recorded.
  • Flight shape — OrchestrationMailboxDeliveryFlight gains an optional processIncarnation, populated in stageOrchestrationMailboxPointer.
  • Regression coverage — two new cases in mailbox-pointer-stage.test.ts pin the attempted-Enter (phase 3) stays and the never-fired Enter (phase 2) releases; the liveness stub and its assertions switch from markAsUndelivered to releaseMailboxPointerEnter.

The safety of the release predicate rests on submitOrchestrationMailboxPointer calling markMailboxPointerEnterAttempted (phase 2→3) synchronously before writePty('\r'), so a row in phase 1/2 provably has had no Enter initiated. I verified that ordering holds, and that flight.processIncarnation is always truthy for a live flight (resolveSubmitTarget returns null and stage bails early when it isn't), so the fallback is only defensive. The resume path already revalidates ENTER_ATTEMPTED rows — settling them as delivered on a same-pty/same-incarnation restore and releasing them on a pty mismatch — which is exactly the behavior this change leans on.

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

@brennanb2025

brennanb2025 commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Measurements

1. Cost of the fix — neutral

retirePty swaps one markAsUndelivered for one releaseMailboxPointerEnter. Both are a single UPDATE inside a SAVEPOINT, so the shapes match. Measured against a copy of a real 368 MB orchestration database (50,866 messages), WAL + synchronous=NORMAL, statements prepared once, 500 warmup then 4,000 iterations × 7 reps, median, with the shared staging cost subtracted:

Arm Isolated call cost
markAsUndelivered (before) 26.69 µs
releaseMailboxPointerEnter (after) 26.59 µs

Delta: −0.10 µs. Inside run-to-run noise. WAL growth identical. The added fence predicates (pointer_pty_id, pointer_process_incarnation, pointer_enter_pending IN (?,?)) cost nothing measurable — they are all covered by the row lookup that already happens.

2. How often it runs — once per interrupted delivery, not per frame

retirePty is reached from a PTY exit (orca-runtime-on-pty-exit.ts:176) and from observeAgentWorking (mailbox-pointer-delivery.ts:198), so it is called on working title frames. But the changed code sits behind if (flight?.stagedMessageIds.length), so a frame with no airborne delivery does a Map lookup and returns without touching the database. The 26 µs above is paid only when a delivery is actually interrupted.

3. The window this closes — asynchronous PTY providers

The vulnerable window is exactly mailbox-pointer-submit.ts:114 (row reaches ENTER_ATTEMPTED) to :118 (await deps.writePty(ptyId, '\r') resolves). Its width is decided by the provider:

Provider writeWithSettlement Window
direct in-process local (local-pty-provider.ts:83) (id, data): WriteSettlement — synchronous effectively zero
daemon-backed local (daemon-pty-router.ts:97) (id, data): Promise<WriteSettlement> — daemon IPC one asynchronous settlement
SSH (ssh-pty-provider.ts:49) (id, data): Promise<WriteSettlement> — remote RPC one asynchronous settlement

On the direct in-process LocalPtyProvider, settlement is not a promise at all, so the await resolves on the next microtask. A PTY exit arrives as a libuv macrotask and cannot interleave with a microtask, so the row cannot be observed at ENTER_ATTEMPTED by retirePty.

For daemon-backed local PTYs and SSH PTYs, settlement crosses an asynchronous IPC/RPC boundary, during which macrotasks — including the PTY exit event — can run.

So this is an asynchronous-provider fix, including SSH and daemon-backed local PTYs. I did not measure live provider settlement latency, so I am not quoting a timing figure; the claim is structural, from the provider types and delivery path.

What this means for the change

The fix is free, runs rarely, and closes a window that exists on asynchronous PTY providers. That is a narrow but real correctness gain, and it is consistent with the execution-boundary rule that loss of contact is never evidence about what the remote process received — an Enter whose settlement never came back is unverifiable, not "never sent".

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Validation evidence for 7e89bb15e92aad55a8c6ef2721351b42875c47bb — land.

  • SSH / visible product path: pnpm build:relay passed before connection. I verified the hidden CDP-attached app identity as frigatebird @ brennanb2025/mailbox-pointer-enter-revalidate, connected Orca to a throwaway Debian 12 arm64 Docker SSH target, and registered the real stablyai/demo-project repo at 4d6a7ec73eb38d164f2e6dd9f191caef8d4ef084. The remote host HTTPS clone required credentials, so I used an authenticated local clone and transferred a HEAD-only git bundle. Through the rendered Orca terminal surface I launched an idle Codex-like receiver, then sent msg_f7935c7ee390 from a second visible SSH terminal. The host-side stdin ledger recorded one mailbox pointer and one synthesized \r, and the visible result reports exactly one submission.
  • Backing evidence: the mailbox row settled as read=0, non-null delivered_at, pointer_enter_pending=0; the remote repo stayed clean on pr19911-validation, and relay/SSH process state stayed on the throwaway host. I also exercised the daemon-backed local async-provider path: the receiver process was a descendant of the isolated Orca daemon, its ledger recorded one pointer and one Enter, and msg_fa3d3f628315 settled with the same DB state.
  • Race and logs: 41/41 targeted tests passed across mailbox-pointer-stage, mailbox-pointer-submit, transport settlement, and stale-leaf liveness, including the deterministic unresolved Enter-settlement + PTY-retirement case. I did not force that exact settlement boundary in live SSH because the provider acknowledgement boundary is not safely or deterministically externally controllable; the screenshots prove adjacent end-to-end delivery while the deterministic test covers the race itself. CDP reported zero console errors; app, daemon, relay, and sshd logs showed successful deploy/handshake/delivery with no relevant mailbox or SSH failure.
  • Cleanup: stopped only the two instrumented receivers and isolated app/daemon/PTYs started here; reset and removed the test SSH target/relay; removed the remote branch/repo, container/image, temporary key/profile, and CDP session. Tracked worktree state is clean, with the two pre-existing untracked ORCA reports preserved.

Clean attached instance:
ssh-attached.png

Single-submit result in surrounding Orca context:
ssh-mailbox-single-submit.png

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Final review status — LAND

Reviewed head 7e89bb15e92aad55a8c6ef2721351b42875c47bb against main. The independent adversarial review and both readiness passes are clean, with zero P0/P1/P2 findings and no in-scope code changes required.

Correctness and architecture

The failure was the blanket retirement rollback: it erased ENTER_ATTEMPTED even though an asynchronous provider may already have delivered Enter, making duplicate submission eligible. This change removes that failure mechanism at the lifecycle owner by recording the process incarnation, releasing only RESERVED/WRITE_ATTEMPTED under exact PTY+incarnation fencing, and preserving phase 3 for resume-time revalidation.

Scope is asynchronous PTY providers, including SSH and daemon-backed local PTYs. Direct in-process LocalPtyProvider settlement is synchronous and unaffected. The PR body and measurement note have been corrected accordingly.

The implementation reuses the existing delivery state machine and resume policy. It adds no polling, retry loop, subprocess, listener, fanout, persistent cache, or unbounded state; retirement remains one bounded SQL update and retains only one process-incarnation string per active flight.

Validation

  • 1,710 tests passed with 1 skip in the readiness gate.
  • Focused settlement/race suite: 41/41 passed.
  • Broader mailbox/provider reliability suite: 269/269 passed.
  • tc:node, changed-code-quality, React Doctor, git diff --check, macOS packaging, Windows packaging, and all current PR CI checks passed.
  • Hidden/background Electron validation attached to this exact branch through CDP. On a throwaway Debian 12 SSH target, the host-side ledger recorded one pointer and one Enter and the mailbox row settled with zero pending phase. The daemon-backed local async-provider path produced the same result.
  • Two full-app, uncropped screenshots are attached in the preceding evidence comment: fix(orchestration): revalidate an attempted Enter instead of resending it #19911 (comment)
  • All run-owned Electron, daemon, PTY, SSH, Docker, key/profile, and CDP resources were cleaned up. Tracked worktree state is clean.

Remaining gaps

The exact unresolved Enter-settlement/retirement boundary was not forced in live SSH because that acknowledgement boundary is not safely deterministic externally; the deterministic unresolved-settlement regression test covers the race, while the live SSH and daemon runs cover adjacent end-to-end behavior. No native Windows/WSL live race run was performed, but the changed TypeScript/SQLite path has no platform branch and Windows package CI passed.

Verdict: land.

@brennanb2025
brennanb2025 merged commit 6e9de5f into main Sep 10, 2026
29 checks passed
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