Repository navigation
fix(session): defer session writes suppressed by a direct-SSH apply instead of dropping them - #16969
Conversation
00cbe46 to
348a086
Compare
|
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: 📥 CommitsReviewing files that changed from the base of the PR and between 6e28d699f1b950790919173d3e881ff20dfbfe91 and 7a5f1a8. 📒 Files selected for processing (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review. 📝 WalkthroughWalkthroughThe session write subscriber now retains pending changes while persistence is gated. It can re-arm its debounce timer when the gate opens. Direct SSH snapshot application now emits a one-shot notification after its write-suppression window ends. Application session persistence uses this notification. Tests cover deferred mutations, tombstones, debounce timing, gate wake-ups, timer behavior, unrelated worktrees, and the complete snapshot apply flow. Merge Risk: ⚪ Minimal · up to This change defers session writes during SSH applies without introducing an actionable merge-blocking risk; it is merge-ready after normal checks and review. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description is detailed and relevant. It explains the problem, cause, fix, testing, compatibility, and review findings. However, it omits the required Linked Issue entry, Visual Proof section with an explicit N/A justification, and the required checklist sections.
✨ 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 |
348a086 to
6e28d69
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/lib/session-write-subscriber.ts (1)
80-85: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCondense the added rationale comments. State each invariant in one short comment.
src/renderer/src/lib/session-write-subscriber.ts#L80-L85: reduce the gate-pairing explanation to its invariant.src/renderer/src/lib/session-write-subscriber.ts#L127-L130: reduce the pending-field lifecycle explanation.src/renderer/src/lib/session-write-subscriber.ts#L137-L148: reduce the flush and fresh-state explanation.src/renderer/src/lib/session-write-subscriber-deferred-persist.test.ts#L1-L12: reduce the test preamble.src/renderer/src/hooks/remote-workspace-snapshot-apply-deferred-session-write.test.ts#L1-L8: reduce the test preamble.As per coding guidelines, “DO NOT: be verbose” and “BE CONCISE. 1 LINE if possible.”
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 79c71c59-ac74-41fe-9456-861c345a3cd6
📥 Commits
Reviewing files that changed from the base of the PR and between 00cbe46f6c44f26ce357665bcd8b7c7daf44da93 and 6e28d699f1b950790919173d3e881ff20dfbfe91.
📒 Files selected for processing (5)
src/renderer/src/hooks/remote-workspace-snapshot-apply-deferred-session-write.test.tssrc/renderer/src/hooks/remote-workspace-snapshot-apply.tssrc/renderer/src/lib/session-write-subscriber-deferred-persist.test.tssrc/renderer/src/lib/session-write-subscriber.test.tssrc/renderer/src/lib/session-write-subscriber.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
The debounced session writer cleared its pending changed-field set whenever the persist gate was shut, after it had already advanced its identity-based detection baseline. Because detection is `prev[key] !== next[key]`, a field dropped there could never be re-detected, so a mutation made during an SSH apply (up to 30s plus a 1s tail, on every connect and reconnect) was lost for good — including a closed-tab tombstone, which is exactly the state that stops the host from resurrecting the tab. Keep the pending set instead, and add a one-shot wake-up from the gate owner so a deferred write is not stranded when the suppression tail expires with no store update behind it.
6e28d69 to
7a5f1a8
Compare
…tablyai#16969) The debounced session writer cleared its pending changed-field set whenever the persist gate was shut, after it had already advanced its identity-based detection baseline. Because detection is `prev[key] !== next[key]`, a field dropped there could never be re-detected, so a mutation made during an SSH apply (up to 30s plus a 1s tail, on every connect and reconnect) was lost for good — including a closed-tab tombstone, which is exactly the state that stops the host from resurrecting the tab. Keep the pending set instead, and add a one-shot wake-up from the gate owner so a deferred write is not stranded when the suppression tail expires with no store update behind it. (cherry picked from commit 6c58038)
…tablyai#16969) The debounced session writer cleared its pending changed-field set whenever the persist gate was shut, after it had already advanced its identity-based detection baseline. Because detection is `prev[key] !== next[key]`, a field dropped there could never be re-detected, so a mutation made during an SSH apply (up to 30s plus a 1s tail, on every connect and reconnect) was lost for good — including a closed-tab tombstone, which is exactly the state that stops the host from resurrecting the tab. Keep the pending set instead, and add a one-shot wake-up from the gate owner so a deferred write is not stranded when the suppression tail expires with no store update behind it.
Session writes suppressed during an SSH apply were discarded, not deferred
User-visible symptom
Close a terminal tab (or rename one, move one between groups, change the active workspace — any durable session edit) in the ~30 seconds after an SSH workspace connects or reconnects, and the edit could be silently lost. Nothing tells you: the UI shows the tab gone, the session file on disk still has it, and the next launch brings it back.
The worst version is the one PR #16752 just built machinery for. Closing an SSH tab writes two pieces of durable state: the tab's removal and a closed-tab tombstone, which is the client's only record that "the user closed this" for the direct-SSH pull merge. Both live in the same session state. A close made inside the suppression window lost both, so the tab came back on the next reconnect and the tombstone that was supposed to make the close stick was never written. That window is open on every connect and every reconnect — which is precisely when a user is looking at phantom tabs and cleaning them up.
Root cause
src/renderer/src/lib/session-write-subscriber.tsis the debounced Zustand → disk session writer. It tracks which session fields changed inpendingChangedFields, and detects change by object identity against a baseline:prev?.[key] !== next[key].On
origin/mainit advanced that baseline before consulting the persist gate:session-write-subscriber.ts:136—prev = nextsession-write-subscriber.ts:140-146— gate closed at change time →pendingChangedFields.clear()session-write-subscriber.ts:162-164— debounce fired butshouldPersistWorkspaceSession(fresh)false →pendingChangedFields.clear()session-write-subscriber.ts:165-168— debounce fired butshouldSchedulePersist()false →pendingChangedFields.clear()Once
prevhas advanced, the identity comparison for that field will never differ again. Clearing it from the pending set therefore does not delay the write — it destroys it. The only recovery is an unrelated future mutation of the same field, or a clean quit (the shutdown checkpoint writes the whole payload); a crash, kill, or forced update in between loses it for good.The gate that trips this is
shouldSchedulePersist: () => !isDirectSshRemoteWorkspaceApplyInProgress()(src/renderer/src/app-shell/use-app-session-persistence.ts:89), and it is closed for the whole snapshot apply — bounded bySNAPSHOT_TERMINAL_RECONNECT_TIMEOUT_MS(30s) — plus a 1sREMOTE_WORKSPACE_SNAPSHOT_WRITE_SUPPRESS_MStail (src/renderer/src/hooks/remote-workspace-snapshot-apply.ts:22-27).Cross-target variant: that flag is a module-level global, not per target. Target A reconnecting suppresses writes for every other target, so a tab closed on target B during A's apply is lost too, even though B was never involved.
The fix
Defer, never discard.
pendingChangedFieldsis no longer cleared on a closed gate. It is cleared only when a write is actually issued (or on unsubscribe). It is the sole record that a mutation still owes a write, and it is bounded bySESSION_RELEVANT_FIELDS(31 entries).changedFields.length === 0tochangedFields.length === 0 && pendingChangedFields.size === 0, so any subsequent store notification can wake a deferred write — not just one that touches the same field again.onDirectSshRemoteWorkspaceApplyWindowClosed(src/renderer/src/hooks/remote-workspace-snapshot-apply.ts) fires a singlesetTimeoutper apply, scheduled at the exact suppression deadline, anduse-app-session-persistence.tswires it into the subscriber assubscribeToPersistGateOpen.Values are never deferred — only the field selection is. Every flush rebuilds the patch from
store.getState(), so a deferred write publishes current post-merge state and can never resurrect a pre-apply value over what the host just sent.The three hazards, and which choice addresses each
The brief called these out explicitly, so here they are one by one.
1. No unbounded loop if the gate never opens. Nothing in
flushPendingWritere-arms. A timer is armed by exactly two things: a real session-field change, or the one-shot gate-open notice. IfshouldPersistWorkspaceSessionstays false forever (a hydration failure — issue #1158 says that state must never be written), the pending set just sits there costing nothing: no timer, no poll, no retry budget to get wrong. Locked by the testarms no timer while the gate stays closed, which assertsvi.getTimerCount() === 0after 10s with the gate shut.2. No lost wake-up when the gate opens with nothing else happening. The
shouldPersistWorkspaceSessiongate lives in store state, so its reopening is a store notification and (2) above catches it. The SSH gate does not: its tail expires on a wall clock with no store write behind it. That is why the notice is emitted by the gate owner rather than polled by the subscriber — it fires at the deadline, once, from the code that knows the deadline. Overlapping applies are safe: a notice that finds the window still shut returns without notifying, and the later apply schedules its own.3. No discarded mutation. The pending set is retired only on the path that calls
persist.Deliberately not built: a retry chain, a backoff ladder, an attempt budget, or a re-armed poll. This subsystem produced twelve defects across five review rounds in exactly that shape earlier today. There is one timer here and it is the pre-existing debounce.
Performance property preserved
The comment at the top of the subscriber documents why unrelated updates (agent status, usage refreshes, title ticks) must not reset the debounce: they used to, and the eventual payload build crossed 70-110ms and tripped
setTimeoutviolations. An unrelated update can now arm a flush when work is owed, butif (timer !== null && changedFields.length === 0) returnstops it from ever resetting one. Covered bydoes not let an unrelated update reset the debounce of a deferred write.ELI5
Think of the app as a person writing your notes into a notebook.
Every time you change something, they jot the change on a sticky note ("tab closed"), and a moment later copy it into the notebook. But while the app is syncing with an SSH machine, the notebook is held shut for up to half a minute.
The old behavior: they'd look at the shut notebook, throw the sticky note in the bin, and — this is the bad part — also tick the change off their checklist as handled. So when the notebook opened again, nobody remembered anything was owed. Your closed tab came back the next time you launched the app, as if you had never closed it.
The new behavior: they keep the sticky note. When the notebook opens, they write it in. And because the notebook can open on a timer with nothing else happening to remind them, the sync itself now taps them on the shoulder when it's done.
Two things it deliberately does not do: it doesn't keep knocking on a notebook that stays shut (no spinning retry loop), and it doesn't write down the old value — it looks at what's true now, so a note written before the sync can't undo what the sync brought in.
Fix evidence — the tests bite
Reverting
session-write-subscriber.tsandremote-workspace-snapshot-apply.tstoorigin/mainand re-running the new specs, unchanged:With the fix, all green:
Only one case in the whole change —
arms no timer while the gate stays closed— passes with and without the fix, by design: it is the guard rail on hazard 1 (no polling loop), not proof of the fix. The other ten bite.The integration spec drives the real
applyDirectSshRemoteWorkspaceSnapshotpath with the real subscriber wired exactly asuse-app-session-persistencewires it — real gate, real 1s suppression tail, real wake-up — and closes a tab on an unrelated target from inside the apply. That is requirement 3 (cross-target) end to end; the unit suite covers it at patch level too.Review round 1 (independent adversarial review)
An independent reviewer traced the overlapping-apply depth math, the
+1mstail arithmetic, re-entrancy ofpersist()into the subscriber, listener-set mutation during notification, staleness, cleanup, and StrictMode, and found no P0/P1. Two P2s, both fixed in this branch:shouldSchedulePersistwithoutsubscribeToPersistGateOpenand silently strand deferred writes again. They are now a single discriminated union (SessionWritePersistGate), so the unsafe combination does not typecheck. Call sites that reopen the gate through a store update pass an explicit no-op wake-up, which documents the choice at each site.origin/main.Also fixed:
cancels a pending debounce when shouldSchedulePersist returns falsehad a stale title and was silently inert — it lefthydrationSucceededfalse, so the outer hydration gate short-circuited before the schedule gate was ever consulted. It now opens both flags, exercises the change-time gate for real, and asserts the deferred write lands.Review round 2 (second independent reviewer)
A second reviewer independently cleared backward compatibility, the remote-push path, concurrency, the SSH execution boundary, and code organization, and found no P0/P1. It did find a real hole in my hazard-2 claim, now fixed:
The gate-open notice could still be dropped. The callback skipped when
isDirectSshRemoteWorkspaceApplyInProgress()was true, and my comment justified that with "an overlapping apply owns its own notice". That reasoning only coverssnapshotApplyDepth > 0. The other half of the predicate is the wall-clock tail — anddelayMsis wall-clock arithmetic handed to a monotonic timer, so a clock step back (NTP) can leave the deadline in the future when the timer fires. In that case the notice returned, nothing rescheduled, and the deferred write was stranded until the next store update: exactly the hole this PR exists to close.The two halves are now separated.
depth > 0still returns (that apply'sfinallyschedules the next notice); an outstanding tail re-arms for the time still left on it instead of giving up. This does not reintroduce hazard 1: the deadline only moves forward and each re-arm waits the exact remainder, so the wait converges rather than polling.still wakes the deferred write when the wall clock steps back during the tailcovers it, and it is targeted — it fails against the previous revision of this branch, not just againstmain:The same reviewer flagged the integration spec's ~1.2s of real-clock waiting as load-sensitive. It now runs on fake timers (vitest fakes
Datetoo, so theDate.now() < suppressUntilcomparison stays coherent): the file's test time went from ~1.4s of wall-clock waiting to 22ms, and thevi.waitFortimeout race is gone entirely.Backward compatibility
docs/reference/remote-wire-compatibility.mdthird case (what the host is published) does apply in one narrow sense and it is the point of the change: a tab close made during the apply window now reaches the host on the next debounced push, where it previously vanished. The payload shape is identical, it is scoped per target by the existingexportSessionForTarget, and an older host sees an ordinary session patch.closedTerminalTabTombstonesByTabIdand every other field keep their shapes; the fix only changes when a patch is emitted.subscribeToPersistGateOpenis optional onSessionWriteSubscriberDeps; existing call sites and tests that omit it behave exactly as before.Verification
pnpm tc— cleanoxlint+oxfmt --checkon all six changed files — cleanpnpm run check:code-quality:changed—0 new finding(s) across 6 changed file(s), React Doctor cleanpnpm test src/renderer/src/lib src/renderer/src/app-shell src/renderer/src/hooks— 610 files, 5404 passedpnpm test src/renderer/src/store— 304 files, 2983 passedmax-linesdisable added;session-write-subscriber.tsstays well inside the 300-line budget.On e2e
tests/e2e/ssh-cold-hydration-gap-tab-seeding.spec.tswas evaluated and deliberately not extended. Hitting this bug e2e requires closing a tab inside the suppression window, and the window's state is renderer-module-internal — a spec cannot observe it without a new test hook, so the timing would be a guess. The neighbouringremote-workspace-snapshot-local-tab-survival.test.tsdocuments the same trade for a sibling bug ("the end-to-end version of the same scenario only reproduces about one run in three"). The new integration spec drives the real apply path deterministically instead.