Skip to content

fix: salvage individual corrupt entries instead of resetting the whole workspace session - #12919

Closed
robertnisipeanu wants to merge 7 commits into
stablyai:mainfrom
robertnisipeanu:fix/workspace-session-salvage
Closed

robertnisipeanu wants to merge 7 commits into
stablyai:mainfrom
robertnisipeanu:fix/workspace-session-salvage

Conversation

@robertnisipeanu

Copy link
Copy Markdown
Contributor

Fixes #12918

Problem

parseWorkspaceSession validates 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 (new src/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 in src/main/persistence.ts use 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_salvaged telemetry event (host_kind, dropped_count — no paths). Session parsing runs inside the Store constructor, before initTelemetry wires track(), so the events are collected during load and flushed from src/main/index.ts right after initTelemetry(store), following the main_thread_hang_detected pattern.

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-wide oxlint, and oxfmt are clean.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Aug 6, 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: 537d47f2-32c4-476c-a235-f95581a5e14c

📥 Commits

Reviewing files that changed from the base of the PR and between 08047a6 and d2382d9.

📒 Files selected for processing (8)
  • src/main/persistence.ts
  • src/shared/workspace-session-browser-schema.ts
  • src/shared/workspace-session-salvage.test.ts
  • src/shared/workspace-session-salvage.ts
  • src/shared/workspace-session-schema.test.ts
  • src/shared/workspace-session-schema.ts
  • src/shared/workspace-session-terminal-schema.test.ts
  • src/shared/zod-salvage.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/persistence.ts

📝 Walkthrough

Walkthrough

Workspace-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 workspace_session_salvaged event. Hydration now restores empty browser pages, complete group layouts, and missing tab-group references. Tests cover these parser, persistence, telemetry, and hydration changes.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem, implementation, and testing, but omits the required Screenshots, AI Review Report, Security Audit, and Notes sections. Add all missing template sections, including a no-visual-change statement, AI review findings, security audit summary, and relevant notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 52.38% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: salvaging corrupt workspace-session entries instead of resetting the entire session.
Linked Issues check ✅ Passed The changes satisfy issue [#12918] by salvaging corrupt entries, preserving valid session data, and reserving defaults fallback for unsalvageable payloads.
Out of Scope Changes check ✅ Passed The schema, persistence, telemetry, reference repair, browser hydration, write-back, and test changes support the stated workspace-session recovery objectives.

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: 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_modules
  • src/main/index.ts
  • src/main/persistence.ts
  • src/shared/telemetry-events.ts
  • src/shared/workspace-session-salvage.test.ts
  • src/shared/workspace-session-salvage.ts

Comment thread src/main/persistence.ts Resolved
Comment thread src/shared/workspace-session-salvage.ts Resolved
…e workspace session

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@robertnisipeanu
robertnisipeanu force-pushed the fix/workspace-session-salvage branch from 87f49ba to 1663093 Compare August 6, 2026 17:47
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

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

Copy link
Copy Markdown
Contributor

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:

  • Salvage now drops every corrupt entry per pass, instead of one per re-validation. This is the one that mattered most: with MAX_SALVAGE_DROPS = 32, anything past 32 bad records fell back to the exact full reset this PR exists to remove — and the reporter's own scenario (~20 worktrees, one bad writer projecting the same wrong shape across many tabs) clears 32 easily. Each pass now resolves all issues to their smallest containing entry and applies them together, bounded by a pass count (8) rather than a drop count. Converges in 2–3 passes no matter how much is corrupt.
  • A corrupt required top-level field no longer resets everything. activeRepoId: 42 still cost you every worktree. Callers pass their defaults now, and a required top-level field we dropped falls back to its default — gated so a genuinely foreign payload still reports unsalvageable rather than posing as a repaired session.
  • Repaired the references partial salvage can leave dangling. If salvage drops a corrupt tab group while its tabs survive, the groupless tabs still count toward the renderable tab count, so the auto-create-first-terminal rescue never fires and the worktree body renders blank — permanently, since the repaired session gets written back to disk. Orphaned tabs are re-homed now. Two smaller cases of the same class: a dropped layout entry used to leaf to the first group and hide every other surviving group along with its tabs, and a dropped browser page left a dead about:blank tab behind.
  • Repair-path performance. Removed a redundant full re-parse of the session per repair, and applyDrops was one splice per element, i.e. quadratic in drops per array (100k interleaved drops: 289 ms → 14 ms). This runs synchronously in the Store constructor at startup, so it's on the launch path. Also wrapped the zod parse — safeParse is documented not to throw, but it can overflow the stack materialising an issue per field on a huge corrupt payload, and a RangeError escaping there is a launch failure a user can't recover from.
  • Telemetry accuracy, plus a red typecheck. dropped_count was counting issues rather than records (one bad record raises several nested issues), and salvage could still be reported for a load that ultimately fell through to defaults. Both fixed. Also removed a duplicate loadAndAwaitScheduledSave declaration — vitest passes it because esbuild strips types, but tsc fails.

Two asks:

  1. Could you refresh the PR description? It still documents MAX_SALVAGE_DROPS, the 32-drop bound and the one-drop-per-re-validation algorithm, all of which have been replaced, and it predates the reference repairs above.
  2. One thing I deliberately left out of scope, just so it isn't lost: fields that self-clean inside a zod preprocess — sleepingAgentSessionsByPaneKey and lastVisitedAtByWorktreeId — still drop bad entries silently, with no warning, no telemetry and no write-back, so they get re-dropped on every launch. Pre-existing behaviour, but worth a follow-up given One invalid field in one tab record wipes the entire persisted workspace session at startup #12918 involved sleeping-agent records specifically.

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.

@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/main/persistence.test.ts (1)

12248-12249: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert that the corruption step actually ran. Both tests inject the corrupt record through an optional-chained push. If canonicalize returns a different shape — for example after a schema rename or a migration that moves tabsByWorktree — the push is 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: read profile.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 for partitions?.['runtime:env-a'] and partitions?.['ssh:target-b']; assert both arrays exist before pushing runtime-corrupt and ssh-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

📥 Commits

Reviewing files that changed from the base of the PR and between 1663093 and 08047a6.

📒 Files selected for processing (10)
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/renderer/src/store/slices/browser.ts
  • src/renderer/src/store/slices/store-session-cascades.test.ts
  • src/renderer/src/store/slices/tab-group-reference-repair.ts
  • src/renderer/src/store/slices/tabs-hydration-group-validation.test.ts
  • src/renderer/src/store/slices/tabs-hydration.ts
  • src/shared/workspace-session-salvage.test.ts
  • src/shared/workspace-session-salvage.ts
  • src/shared/workspace-session-schema.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/persistence.ts

Comment on lines +33 to +56
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)]

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

Comment on lines +173 to +177
// 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)

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

Copy link
Copy Markdown
Contributor

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. salvagingArray/salvagingRecord drop the entries they can't parse, and each required top-level field declares its own fallback — so a drop can never leave a parent invalid and there is nothing to escalate. MAX_SALVAGE_PASSES, findDropTarget, applyDrops, pathKey, hasClaimedAncestor and the escalation-gated default restoration are gone, about 180 of the 245 salvage lines.

It also generalises an idiom the schema already had: lastVisitedAtByWorktreeId and sleepingAgentSessionsByPaneKey were both already dropping bad entries in place for exactly this reason.

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: parseWorkspaceSession is tolerant now too, so three existing tests that asserted a whole-session rejection for a single bad entry assert the drop instead; and lastVisitedAtByWorktreeId drops are now reported like every other field's rather than cleaned silently.

@robertnisipeanu

Copy link
Copy Markdown
Contributor Author

Superseded by #13431, which ships in v1.4.182: per-entry salvage with bounded diagnostics and a repair write-back covers the #12918 failure end to end. Closing in its favor.

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.

One invalid field in one tab record wipes the entire persisted workspace session at startup

3 participants