Repository navigation
fix(orchestration): revalidate an attempted Enter instead of resending it - #19911
Conversation
…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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (5)
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughThe 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 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)
✅ Passed checks (3 passed)
Full details: Description checkExplanation 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 Resolution Add the missing template sections. Include a linked issue using the required
✨ 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.
✅ No new issues found.
Reviewed changes
- Phase-aware release at retirement —
retirePtynow records the staging incarnation on the flight and, when present, callsreleaseMailboxPointerEnterlimited toRESERVED/WRITE_ATTEMPTED, leavingENTER_ATTEMPTEDrows in place. Only the ambiguous phase keeps its state; the blanketmarkAsUndeliveredpath is retained as a fallback when no incarnation was recorded. - Flight shape —
OrchestrationMailboxDeliveryFlightgains an optionalprocessIncarnation, populated instageOrchestrationMailboxPointer. - Regression coverage — two new cases in
mailbox-pointer-stage.test.tspin the attempted-Enter (phase 3) stays and the never-fired Enter (phase 2) releases; the liveness stub and its assertions switch frommarkAsUndeliveredtoreleaseMailboxPointerEnter.
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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Measurements1. Cost of the fix — neutral
Delta: −0.10 µs. Inside run-to-run noise. WAL growth identical. The added fence predicates ( 2. How often it runs — once per interrupted delivery, not per frame
3. The window this closes — asynchronous PTY providersThe vulnerable window is exactly
On the direct in-process 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 changeThe 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 |
|
Validation evidence for
|
Final review status — LANDReviewed head Correctness and architectureThe failure was the blanket retirement rollback: it erased Scope is asynchronous PTY providers, including SSH and daemon-backed local PTYs. Direct in-process 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
Remaining gapsThe 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. |



The bug
When a PTY retires mid-delivery,
retirePtycalledmarkAsUndeliveredon 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 reachesENTER_ATTEMPTED) to:118(await deps.writePty(ptyId, '\r')resolves). How wide that is depends entirely on the provider:writeWithSettlementlocal-pty-provider.ts:83(id, data): WriteSettlement— synchronousdaemon-pty-router.ts:97(id, data): Promise<WriteSettlement>— daemon IPCssh-pty-provider.ts:49(id, data): Promise<WriteSettlement>— remote RPCOn the direct in-process
LocalPtyProvider, settlement is not a promise, so theawaitresolves on the next microtask. A PTY exit arrives as a libuv macrotask and cannot interleave with a microtask, soretirePtycannot observe the row atENTER_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:
RESERVEDWRITE_ATTEMPTEDENTER_ATTEMPTEDOnly the ambiguous case changes. This matches what
mailbox-pointer-submit.tsalready 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 isunverifiable, 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
markAsUndeliveredpath 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:markAsUndelivered(before)releaseMailboxPointerEnter(after)Delta −0.10 µs, identical WAL growth. Both are a single
UPDATEinside aSAVEPOINT; 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 aMaplookup and returns without touching the database.Validation
pnpm tc:nodeandoxlintclean. Orchestration and stale-leaf suites pass.Two ablations confirm the new coverage is a real regression guard rather than a pin:
ENTER_ATTEMPTEDas well → the new test failsmain's blanketmarkAsUndelivered→ the new test failsWorth flagging: the three existing
terminal-send-stale-leaf-livenesscases pass either way, because they all exercise aWRITE_ATTEMPTEDflight. 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
mainand is unrelated: theorchestration-cli-subprocesskeepalive 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
mainwith an identical query plan, and its incarnation fencing guarded a windowmarkAsUndeliveredalready closes. This is the one demonstrated improvement from that work, in 5 files. Full numbers are recorded on #19644.