Repository navigation
fix: salvage individual corrupt entries instead of resetting the whole workspace session - #12919
robertnisipeanu wants to merge 7 commits into
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (8)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughWorkspace-session loading now salvages valid entries from partially corrupt data. Invalid entries are removed through bounded repair passes, while wholly invalid data uses defaults. Repaired sessions are marked for persistence. Salvage counts are queued during store construction and emitted after telemetry initialization through the 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3d5491f8-bc91-4a9f-9fb2-43357070102d
📥 Commits
Reviewing files that changed from the base of the PR and between f713739 and 87f49ba08e52f03d55f4445034da3f16892535f1.
📒 Files selected for processing (6)
node_modulessrc/main/index.tssrc/main/persistence.tssrc/shared/telemetry-events.tssrc/shared/workspace-session-salvage.test.tssrc/shared/workspace-session-salvage.ts
…e workspace session Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
87f49ba to
1663093
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
…salvageable required fields - drop every entry zod reports in one pass instead of one per re-validation, so a systemic bad writer (N corrupt records, not one) still salvages; removes the 32-drop cap that fell back to a full reset above it - a required top-level field whose value we dropped now falls back to the caller's default instead of resetting every worktree's session
…c entry splice - reuse the initial safeParse for the first repair pass; re-validating a byte-identical clone cost a full multi-MB parse (~105ms on a deep layout tree) - collect array drops per parent and rebuild once instead of splicing each element (O(n) memmove each): 100k interleaved drops 289ms -> 14ms - guard the validator itself: zod overflows the stack materializing an issue per field on a huge corrupt payload, and this parse runs in the Store constructor where an escaping RangeError is an unrecoverable launch failure
Salvage drops individual corrupt records, which produces persisted shapes a full reset never could: a worktree whose only tab group was corrupt, a layout entry dropped while several groups survive, and a browser workspace left with a present-but-empty page list. Hydration tolerated most dangling references already but not these three, and the PR now writes the repaired session back to disk, so each one survived every relaunch: - groupless tabs still counted toward renderableTabCount, so the auto-create-first-terminal rescue never fired and the worktree body rendered blank with no way back but Cmd+T. Adopt them into a surviving or synthesized group instead. - the no-layout fallback leafed to the first group, hiding every other group and its tabs. Span all surviving groups. - `?? [synthetic page]` only fired on a missing key, so an emptied array restored a dead about:blank tab nothing prunes or reloads. Also report one repair per corrupt record rather than one per zod issue: a record's bad field and the parent it leaves incomplete are nested drops, and counting both inflated the warn log and `workspace_session_salvaged`'s dropped_count. Claiming targets shallowest-first makes the outermost entry own the repair and retires the slots nested ones held, which also makes applyDrops order-independent by construction — so the descending comparePaths sort (a comparator that was inconsistent for a number vs its numeric string, and provably behavior-neutral) is gone. Tests: the write-back test used flush(), which writes whatever is dirty regardless of whether a save was ever scheduled, so both `loadNeedsSave` lines could be deleted green. Canonicalize the profile first, then assert the debounced save the salvage itself schedules — separately for the local session and for host partitions — and pin the host_kind classification and the deferred telemetry flush.
…lemetry The previous commit left two identical `loadAndAwaitScheduledSave` declarations in one scope, which vitest happily runs (esbuild strips types) but `tsc` rejects with TS2393 — the typecheck CI gate would have gone red. A throw later in load()'s state literal — `sshTargets: 5` reaches `.map`, for instance — discards the parse and retries against a restored backup, but the discarded attempt's salvage events were already queued and still flush. Clear the queue when a load begins, so `workspace_session_salvaged` counts repairs that actually took effect rather than phantom rows on exactly the corrupt-profile population it measures. Also stop the dot-colliding-key test claiming a guarantee it does not enforce: joining path segments is observably equivalent here (it costs an extra repair pass, it does not lose an entry), so the test now pins the shape it really covers and the comment on pathKey says it is defending an identity invariant rather than a reachable exploit.
…aults The queue clear added last commit only covered the backup-recovery retry. When no usable backup exists, the discarded attempt falls through to getDefaultPersistedState — the user lost the whole session — yet the salvage events queued before the throw still flushed, claiming a repair for a profile that in fact reset. Clear on that branch too; both clears are now separately pinned. Also make canonicalize() prove its own premise: the save assertions only mean something if a clean load schedules nothing, so assert the file is byte-stable across a second load rather than assuming it. A future migration that dirtied every load would otherwise leave those tests silently vacuous.
|
Thanks for this — the whole-session reset in #12918 is a nasty failure mode, and per-entry salvage is the right shape for the fix. Heads up so it isn't a surprise: I've pushed five commits straight to your branch rather than leaving you a long list of review notes. It's a plain fast-forward, nothing of yours was rewritten. What changed and why:
Two asks:
Validated in a running app as well as in tests: seeded a real 3-worktree / 9-tab session, injected #12918's exact corruption, and confirmed exactly one tab is lost, everything else survives, and the bad record is gone from disk so it doesn't re-salvage each launch. The same fixture with the change reverted still empties the whole store. |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
src/main/persistence.test.ts (1)
12248-12249: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert that the corruption step actually ran. Both tests inject the corrupt record through an optional-chained
push. Ifcanonicalizereturns a different shape — for example after a schema rename or a migration that movestabsByWorktree— thepushis skipped, the loaded profile is clean, and the "salvage removed the corrupt tab" assertions still pass. The tests then silently stop covering write-back.
src/main/persistence.test.ts#L12248-L12249: readprofile.workspaceSession?.tabsByWorktree?.[worktreeId]into a local, assert it is defined, then push{ id: 'tab-corrupt' }onto it.src/main/persistence.test.ts#L12274-L12277: do the same forpartitions?.['runtime:env-a']andpartitions?.['ssh:target-b']; assert both arrays exist before pushingruntime-corruptandssh-corrupt.♻️ Proposed fix for the first site
- profile.workspaceSession?.tabsByWorktree?.[worktreeId]?.push({ id: 'tab-corrupt' }) + const canonicalTabs = profile.workspaceSession?.tabsByWorktree?.[worktreeId] + expect(canonicalTabs).toBeDefined() + canonicalTabs?.push({ id: 'tab-corrupt' })
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 25f184c2-b1c1-4a51-a3f4-7e795ab4c5d5
📒 Files selected for processing (10)
src/main/persistence.test.tssrc/main/persistence.tssrc/renderer/src/store/slices/browser.tssrc/renderer/src/store/slices/store-session-cascades.test.tssrc/renderer/src/store/slices/tab-group-reference-repair.tssrc/renderer/src/store/slices/tabs-hydration-group-validation.test.tssrc/renderer/src/store/slices/tabs-hydration.tssrc/shared/workspace-session-salvage.test.tssrc/shared/workspace-session-salvage.tssrc/shared/workspace-session-schema.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/persistence.ts
| for (const [worktreeId, tabs] of Object.entries(tabsByWorktree)) { | ||
| const groups = groupsByWorktree[worktreeId] ?? [] | ||
| const grouped = new Set(groups.flatMap((group) => group.tabOrder)) | ||
| const orphanIds = tabs.filter((tab) => !grouped.has(tab.id)).map((tab) => tab.id) | ||
| if (orphanIds.length === 0) { | ||
| continue | ||
| } | ||
| const host: TabGroup = groups[0] ?? { | ||
| id: createBrowserUuid(), | ||
| worktreeId, | ||
| activeTabId: null, | ||
| tabOrder: [], | ||
| recentTabIds: [] | ||
| } | ||
| const adopted: TabGroup = { | ||
| ...host, | ||
| tabOrder: [...host.tabOrder, ...orphanIds], | ||
| activeTabId: host.activeTabId ?? orphanIds[0] | ||
| } | ||
| const orphaned = new Set(orphanIds) | ||
| tabsByWorktree[worktreeId] = tabs.map((tab) => | ||
| orphaned.has(tab.id) ? { ...tab, groupId: adopted.id } : tab | ||
| ) | ||
| groupsByWorktree[worktreeId] = [adopted, ...groups.slice(1)] |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Repair stale Tab.groupId values.
If g1.tabOrder contains t1, but t1.groupId is dropped g2, Lines 35-36 classify t1 as grouped. Lines 53-55 do not rewrite its dangling groupId.
Build a tab-to-owning-group map from tabOrder. Rewrite every tab whose groupId differs from that owner. Add a hydration test for this case.
| // Why: the fallback must name every surviving group. A layout entry can be | ||
| // absent (legacy write) or dropped by session salvage while several groups | ||
| // survive; leafing to the first one alone renders the rest — and their tabs — | ||
| // nowhere, with nothing downstream to notice or heal it. | ||
| layoutByWorktree[worktreeId] = hydratedLayout ?? layoutSpanningGroups(hydratedGroups) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Repair incomplete non-null layouts.
pruneTabGroupLayoutForGroups() can return a non-null layout that omits a surviving group. This branch preserves that layout because it only falls back on null. The omitted group and its tabs remain unreachable.
After pruning, verify that the layout contains every hydratedGroupId. If any group is absent, rebuild or extend the layout with all surviving groups. Add a test with g1 and g2 surviving while the persisted layout contains only g1.
The salvage engine derived drop granularity at runtime from zod issue paths, in up to 8 re-validating passes with escalation slots and subsumption bookkeeping. Zod expresses the same thing declaratively: salvagingArray/salvagingRecord drop the entries they cannot parse, and each top-level field declares its own fallback. That removes the pass loop, findDropTarget, applyDrops, pathKey, hasClaimedAncestor and the escalation-gated default restoration. Behaviour is unchanged: outcomes were compared entry for entry and path for path against the previous implementation across a corrupt-session corpus. Per-entry drops, an unbounded drop count, the fallback for an unsalvageable required field, unsalvageable for a foreign payload, the write-back, the log line, the telemetry counter and the dangling reference repair all still hold. Generalises the idiom the schema already used at lastVisitedAtByWorktreeId and sleepingAgentSessionsByPaneKey. The browser sub-schemas move to their own file to keep workspace-session-schema.ts inside its max-lines budget.
|
Pushed a simplification of the salvage implementation. The diagnosis and the goal here were right and are what's shipping — one bad tab record must not cost every worktree its state, the repaired session gets written back, and the dangling-reference repair is load-bearing. Only the mechanism changed. The previous version validated the session as a unit and then reverse-engineered drop granularity from zod's issue paths, in a multi-pass re-validating loop with escalation slots and subsumption bookkeeping. Zod expresses this directly, which is how the problem is normally solved: declare the tolerance per field, at the point where the data is described. It also generalises an idiom the schema already had: Behaviour was checked rather than assumed — outcomes compared entry-for-entry and path-for-path against the previous implementation across a corrupt-session corpus, and the tests still cover per-entry drops, an unbounded drop count, the fallback for an unsalvageable required field, unsalvageable for a foreign payload, write-back, logging and the telemetry counter. Two knock-ons worth knowing: |
Fixes #12918
Problem
parseWorkspaceSessionvalidates the persisted workspace session as a unit: any single invalid field in any record makes both persistence call sites fall back to defaults for the entire local session (or an entire host partition), discarding every worktree's tabs, layouts, and sleeping-agent records over one bad entry.Change
parseWorkspaceSessionSalvaging(newsrc/shared/workspace-session-salvage.ts) validates against the same schema; on failure it drops the smallest self-contained entry containing each reported issue — the innermost array element on the issue path, else the map entry, else the top-level field — re-validating after each drop, bounded at 32 drops, and returns the dropped paths. Both call sites insrc/main/persistence.tsuse it, log the dropped entries at warn level, and keep the defaults fallback for payloads that cannot converge. Because zod reports union failures at the union's own path, a corrupt node inside a recursive layout tree salvages at the granularity of its containing map entry.Salvage events are counted via a new
workspace_session_salvagedtelemetry event (host_kind,dropped_count— no paths). Session parsing runs inside theStoreconstructor, beforeinitTelemetrywirestrack(), so the events are collected during load and flushed fromsrc/main/index.tsright afterinitTelemetry(store), following themain_thread_hang_detectedpattern.Testing
New
src/shared/workspace-session-salvage.test.ts(10 tests): valid passthrough; dropping a tab record with missing required fields while siblings survive; invalid unified-tab entry; corrupt map value; multiple corruptions across maps; non-object payload; unsalvageable required field; optional top-level field of wrong type; drop-budget exhaustion; recursive-union coarse drop.typecheck(node + web), repo-wideoxlint, andoxfmtare clean.🤖 Generated with Claude Code