Skip to content

fix(persistence): salvage corrupt workspace session entries - #13431

Merged
Jinwoo-H merged 6 commits into
mainfrom
jinwoo/sta-3604-one-invalid-field-in-one-tab-record-wipes-the-entire
Aug 10, 2026
Merged

Jinwoo-H merged 6 commits into
mainfrom
jinwoo/sta-3604-one-invalid-field-in-one-tab-record-wipes-the-entire

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #12918 / STA-3604.

A single malformed record in the persisted workspace session previously made startup discard the entire session, including unrelated worktrees, tabs, layouts, browser state, and sleeping-agent resume records. Workspace-session schemas now salvage invalid array/map entries independently, log bounded diagnostics, and schedule a write-back so the repaired profile does not need to be salvaged again.

Partial salvage can leave dangling references, so hydration also re-homes tabs whose group was dropped, lays out every surviving group, and synthesizes a browser page when its persisted page list was emptied.

The original producer of the reported seven-field tab remains unproven. Direct SSH relay snapshots are a demonstrated ingress path because individual remote tab records are not runtime-validated, but this PR deliberately fixes the persistence blast radius for every corruption source rather than assuming a specific writer.

Screenshots

No product visual change. Headful Electron restart proof: #13431 (comment)

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test — repository-wide run completed with 48,919 passing and 12 failures in five unrelated, untouched macOS/PTY/IME/relay test files; affected suites are green
  • pnpm build
  • Added or updated high-quality tests that would catch regressions

Focused verification:

  • 578 tests passed across persistence, workspace-session schema/salvage, sleeping-agent, terminal schema, browser, and tab-group hydration suites.
  • A real two-launch Electron restart E2E passes headful and headless: it renders two surviving terminal tabs after injecting one truncated persisted sibling and verifies durable on-disk repair. The spec is included in normal headless E2E discovery.
  • The deterministic regression test fails on main: one truncated terminal tab rejects the complete session. It passes here and preserves every valid sibling/worktree.
  • Local, runtime-host, and SSH-namespaced host-partition fixtures verify repair plus durable write-back; this covers persisted partition behavior, not live SSH transport.
  • Valid sessions, foreign payload rejection, unbounded corrupt-entry counts, browser-page repair, stale group references, partial layouts, and groupless tabs are covered.

AI Review Report

Two independent post-implementation audits found no actionable correctness or regression issues. Reviews explicitly checked the old failure on main, per-entry recovery, host partition isolation, write-back scheduling, dangling-reference repair, bounded diagnostics, exception cleanup, and foreign-payload rejection.

Cross-platform review found no shortcut, label, path, shell, native-module, or Electron platform behavior changes. The implementation is platform-neutral TypeScript and applies identically to local, folder-workspace, runtime-host, and SSH partitions.

Security Audit

The diff adds no command execution, network endpoint, authentication, secret, dependency, IPC/RPC, or filesystem-path behavior. Persisted input continues through Zod validation; invalid entries are dropped, record reconstruction uses a null-prototype accumulator to prevent __proto__ poisoning, validator exceptions are contained, and diagnostic paths are capped at 100 without logging persisted values.

Notes

The corrupt entry itself is intentionally lost; this changes the failure mode from losing the complete session to losing only data that cannot satisfy its schema. Tolerant parsing can make the original writer less visible, so salvage emits bounded warning diagnostics.

No mobile-facing protocol, RPC, pairing, route, relay-wire, or persisted mobile state is changed. Validating Direct SSH tab entries before renderer hydration is useful defense-in-depth but is separate from this recovery fix and is not required for persisted-state safety.

Reliability Contract

  • Invariant (workspace-session.valid-sibling-preservation): one malformed independent persisted record may remove only itself, never valid sibling records or host partitions; surviving tabs, groups, layouts, and browser pages remain reachable, and repaired state is written once.
  • Failure source: STA-3604 / One invalid field in one tab record wipes the entire persisted workspace session at startup #12918, where one truncated terminal tab made whole-session validation discard unrelated persisted workspace state.
  • Oracle: the test-only reproduction commit 2beaf6af21 fails under the old all-or-nothing parser. The final branch preserves valid sibling worktrees and partitions, repairs references after partial salvage, and proves the repaired file is stable on a second load.
  • Gate: startup-upgrade.persisted-session-corpus (experimental, no protection or executable command on main). Accepted gap: the reported producer and immutable production-fixture provenance remain unknown, so the PR uses deterministic schema and persistence fixtures rather than claiming production-corpus coverage.
  • Provider/platform coverage: local, runtime-host, and SSH-namespaced persistence partitions plus renderer terminal/browser hydration are covered. The implementation is platform-neutral TypeScript. Live SSH transport, daemon, WSL, mobile/relay, and Linux/Windows Electron execution are unaffected by protocol/runtime changes and remain unproved for this exact corruption fixture.
  • Performance budget: parsing and repair are one startup-only O(serialized session entries + hydrated tabs/groups) pass. Warm valid-session measurements were 0.021 ms for 10 tabs, 0.060 ms for 100, and 0.414 ms for 1,000; a 200,000-invalid-entry adversarial case completed in about 1.8 seconds. No polling, timers, IPC/RPC, subprocesses, listeners, or render hot-path work was added.
  • Diagnostics: drop examples are capped at 100 and drop paths are reduced to top-level field names; logs retain the normalized host-partition ID but include no filesystem/worktree paths or persisted values; successful salvage and wholly invalid host-partition removal schedule durable write-back.
  • Residual gaps: the original corrupt-record writer is unproven, and the existing persisted-session corpus gate has no immutable old-production fixture.

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Workspace session parsing now salvages valid fields and entries from partially corrupt data. Local and host-partitioned repairs are logged and persisted. Browser hydration creates a fallback page when persisted pages are empty. Tab hydration repairs missing group ownership and expands incomplete layouts. Tests cover parser salvage, persistence repair, browser fallback pages, and tab-group restoration.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 47.62% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes satisfy #12918 by salvaging invalid entries independently, preserving valid session data and partitions, and retaining fallback for unsalvageable payloads.
Out of Scope Changes check ✅ Passed All production changes support corruption salvage, durable repair, or hydration of partially salvaged state; no unrelated behavior is evident.
Description check ✅ Passed The description includes the required summary, screenshots statement, testing results, AI review, security audit, notes, and reliability details.
Title check ✅ Passed The title clearly and concisely describes the primary change: salvaging corrupt workspace session entries during persistence loading.
✨ 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.

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

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

Add coverage for a wholly unsalvageable partition.

This test proves the write-back for partitions that salvage successfully. No test covers the branch where parseWorkspaceSessionSalvaging returns ok: false for a partition. That branch skips the partition without setting salvaged, so the corrupt partition is never removed from disk. See the comment on src/main/persistence.ts Line 576 for the root cause.

Add a case that writes a non-object partition value, then asserts the profile file no longer contains that host key after loadAndAwaitScheduledSave().

src/shared/zod-salvage.ts (1)

8-27: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Make collector state reentrant-safe.

collectSalvageDrops saves a single global collector/path and clears them in finally. If parsed schema combinators nested these combinators, saving and parsing nested state would disconnect later diagnostics from the outer parse. Save and restore the previous dropCollector and dropPath stack around the inner parse instead.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a0e49f6c-4743-4875-8510-b4998c4d5a5d

📥 Commits

Reviewing files that changed from the base of the PR and between 934faae and 8c5fd76.

📒 Files selected for processing (14)
  • 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-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

Comment thread src/main/persistence.ts Resolved
Comment thread src/main/persistence.ts Resolved
Comment thread src/shared/workspace-session-schema.ts Resolved
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Electron restart E2E proof

A headful Electron test launched Orca with an isolated profile, created two named terminal tabs, shut down gracefully, injected one truncated sibling tab into the persisted workspace session, and relaunched the same profile.

After restart, both valid tabs remained visibly rendered, the active terminal was usable, the main process emitted the bounded salvage warning, and the corrupt record was durably removed while the unified tabs remained on disk. The scenario passed twice consecutively.

STA-3604 survivor tabs after corrupt-session restart

Remaining gap: this uses a local Electron profile and deterministic corruption injection; it does not reproduce the unknown original writer or exercise a live SSH transport.

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

🧹 Nitpick comments (1)
tests/e2e/workspace-session-corrupt-tab-salvage.spec.ts (1)

126-130: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Compare the survivor IDs without depending on array order.

toEqual on unifiedTabIds requires the persisted order to match creation order. Tab reordering or sort-order changes then fail the test without a real regression.

♻️ Order-independent comparison
     await expect
       .poll(() => persistedSessionEvidence(session.userDataDir, worktreeId), {
         timeout: 30_000
       })
-      .toEqual({ corruptLegacyTabPresent: false, unifiedTabIds: survivorIds })
+      .toEqual({
+        corruptLegacyTabPresent: false,
+        unifiedTabIds: [...survivorIds].sort()
+      })

Sort inside persistedSessionEvidence as well so both sides use the same order.

     unifiedTabIds: unifiedTabs
       .map((tab) => tab.id)
       .filter((id): id is string => typeof id === 'string')
+      .sort()

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0b761b5e-c818-4ea6-a313-49325adce3b5

📥 Commits

Reviewing files that changed from the base of the PR and between 470dcca and ab3d221.

📒 Files selected for processing (1)
  • tests/e2e/workspace-session-corrupt-tab-salvage.spec.ts

@Jinwoo-H
Jinwoo-H merged commit d9e84d8 into main Aug 10, 2026
47 checks passed
@Jinwoo-H
Jinwoo-H deleted the jinwoo/sta-3604-one-invalid-field-in-one-tab-record-wipes-the-entire branch August 10, 2026 04:43
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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

1 participant