Skip to content

fix(agent-session): restore a quarantined session record this build can read - #23589

Closed
brennanb2025 wants to merge 3 commits into
mainfrom
brennanb2025/sta-7446-requalify-quarantined-sessions
Closed

brennanb2025 wants to merge 3 commits into
mainfrom
brennanb2025/sta-7446-requalify-quarantined-sessions

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​121 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​120
Prod 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​80 $\color{#cf222e}{\Huge{\mathbf{−}}}$​28 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​52

What this fixes (scope)

Only structured (native) chat — the experimental Claude/Codex chat view. Nothing else reads or writes the store this PR changes: every caller is structured-chat code (src/main/claude/claude-structured-launch-resolution.ts, src/main/codex/codex-structured-launch-resolution.ts, and src/main/native-chat/agent-session-wire/*).

The bug: a structured chat disappears permanently after a downgrade followed by an upgrade. An older Orca build that cannot read a newer build's record for that chat sets the record aside as unreadable and saves that verdict; after updating again, the current build never re-checks it, so the chat never comes back even though the current build can read it.

Who can hit it: only someone who (1) has structured chat turned on, (2) installs an older Orca build and then updates again, and (3) had a structured chat whose record the older build can't read. The specific trigger in STA-7446 (a rewind in flight while downgrading to v1.4.199/200) is no longer realistically reachable; this fixes the mechanism for the next record-format change. No user report — found by a release scan and reproduced on a QA rig.

Not affected: terminal agents (Claude/Codex typed into a normal terminal pane), orchestration workers, and every structured chat whose record is readable (the normal case — the extra check only runs over the set-aside list, which is normally empty).

ELI5

Orca keeps a small file of every structured (native) chat session it owns. When a build cannot read one of those entries, it moves the entry into a "can't read" pile so it does not act on data it does not understand. Until now nothing ever took an entry back out of that pile, even after the user updated to a build that reads it fine. So a chat an older build could not read stayed gone for good. Now each load re-checks that pile and puts back every entry the running build can read.

What Changed

Before: if you rolled back to an older Orca while a chat was mid-rewind, the older build could not read that chat's record and moved it into the "unreadable" list in the session store. Once the older build had saved twice (which happens within seconds), rolling forward to a current build did not help: the chat tab never came back after a restart, and any attempt to take the session over was refused with execution_owner_reconciling, because the store reloaded that list word for word and never looked at it again. The only way back was reopening the conversation from history as a terminal session.

After: when the store loads, every entry in the unreadable list goes through the same check that entries in the main list do. An entry the running build can read is moved back into the main list and the store is saved, so the chat opens again. An entry the running build still cannot read stays where it was, with its original reason. The restored session's lease is treated like any other lease after a restart: it is marked unconfirmed and re-checked before anyone may write to it, and a rewind that was left half-done is settled by the existing rewind recovery the next time the chat opens.

Mechanism: the decode step for one stored entry (validate, map old lease values, compare the id to its key) moved into decodeStoredAgentSessionRecord, and parseState now runs it on both the main list and the unreadable list. Before, only the main list went through it.

Same session in both lists: the main-list entry wins, but its lowest next ownership number is raised above the unreadable copy's, and then the unreadable copy is dropped. Nothing can create a new entry under an id while that id is in the unreadable list, so both exist only when an older build recovered the main-list entry from the backup file, the save before the one it could not read. That means the unreadable copy can be the newer one and may already have handed out a higher ownership number (the counter that stops a stale owner from writing). Copying it over the main-list entry would throw away whatever the older build did since, and dropping it without looking could hand the same number out twice. Raising the floor, the same way the store already does after recovering from its backup file, avoids both. The unreadable copy is then dropped because this build can read it, so the "can't read this" label is no longer true.

Idempotent: once restored and saved, the next load finds the entry in the main list and nothing in the unreadable list, so nothing is rewritten.

Why

The unreadable list is a saved verdict ("this build can't read these bytes"), and only the build that wrote it made that call. Nothing ever checked that verdict again, so once it was written, no later build could clear it. Re-checking it on load, with the rules of the build that is actually running, means the verdict is only as old as the running build.

Alternatives considered: (1) salvaging from the backup file, which the store already does, doesn't work here, because after the older build saves twice the backup holds the same unreadable-only copy; (2) a one-time migration keyed on version would only fix the one known case, while re-checking on every load also covers any future field an older build can't read; (3) making an unreadable rewind section not invalidate the whole record prevents the older build from quarantining the record in the first place. That is a separate follow-up, and it only helps rollbacks to builds that already include it.

Mixed versions and remote hosts: nothing new is written to disk and nothing changes on the wire. An older build reading a store this build restored sees an ordinary record again. The session store lives on whichever machine runs the agent, including SSH hosts, and every host loads it through this same code, so a remote host picks up the fix when its Orca updates.

Linked Issue

Linear: STA-7446

Visual Proof

Live check on a separate Mac with an isolated profile. The session store was seeded the way an older build leaves it after saving twice: one Claude chat only in the unreadable list of both the main file and the backup, plus a second chat whose entry is still unreadable (unknown schema version). Both builds started from byte-identical store files.

Before (main): after launch the chat tab is missing; only the terminal is there.

before-00-launched.jpg

After (this branch): the chat comes back with its history and answers a new message. The store file now holds it in the main list and no longer in the unreadable list.

after-chat1-03-final.jpg

After a quit and relaunch, the restored chat still opens with its full history and answers again, next to a fresh chat created on this build.

after-relaunch-chat1.jpg

The still-unreadable chat stays in the unreadable list on both builds and does not come back, as before.

after-chat2-00-no-tab.jpg

Same session in both lists (live copy at ownership number 2, unreadable copy at 7): main granted 3 on the next send; this branch set the floor to 8 on load and the send was granted 8 and answered.

after-s6-chat1-final.jpg

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

New cases in src/main/runtime/agent-session-unreadable-record-salvage.test.ts:

  • A record held only in the unreadable list of both the main file and the backup (the state an older build leaves after saving twice) loads as a live record. The restore is saved to disk, ownership can be taken again after restart reconciliation, and a reload keeps it. Fails on main.
  • The same session in both lists keeps the main-list copy and drops the readable unreadable copy. Fails on main.
  • The same session in both lists, where the unreadable copy holds a higher ownership number than the main-list copy: after restart the next owner gets a number above it, never the same one twice. Fails without the floor.
  • An entry this build still cannot read stays in the unreadable list, the chat stays refused, and the file is not rewritten.

Ablation: with the fix reverted and the new tests kept, the restore test and the both-lists test fail and the still-unreadable test passes; with only the floor removed, the ownership-number test fails with the same number granted twice. pnpm exec vitest run --config config/vitest.config.ts passes for the agent-session and structured-agent-session suites under src/main/runtime, src/main/native-chat/agent-session-wire and src/shared (two timing-sensitive tests unrelated to the store flaked in the full parallel run and passed when rerun on their own). pnpm tc:node, pnpm tc:cli, pnpm run check:code-quality:changed and pnpm exec oxlint on the changed files all pass. Live Electron check above covers the seeded store on main and on this branch, plus a fresh Claude chat that still opens and answers across a relaunch. Not done: a live rollback to v1.4.200 and forward again, and a live Codex chat (the change is in the shared store load path, which the tests cover for every provider).

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Security: the restored record goes through the same validation as every other record, and its lease must be re-confirmed before anyone can write. Cross-platform: no path or platform code. SSH: covered above. Mobile: no change. Performance: one extra validation per unreadable entry at load, and that list is normally empty.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: e226ee8f-33a7-4e95-8b17-42c6ef0e39cc

📥 Commits

Reviewing files that changed from the base of the PR and between 45b5cc4 and 7ed08ac.

📒 Files selected for processing (1)
  • src/shared/agent-session-record.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/shared/agent-session-record.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.


📝 Walkthrough

Walkthrough

The change adds a decoder for stored agent-session records and uses it when loading records and quarantined values. Readable quarantined records can be restored. If a live record exists, the recovery path raises its minimum next fence when the recovered lease has a higher next fence. Tests cover restoration, unsupported schemas, stale quarantined copies, and fence preservation.

Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to 7ed08

The change is mergeable with awareness of a narrow edge case: a session at the maximum ownership number can become unreadable after another reservation. Guarding fence exhaustion would remove that risk.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 45b5c

Recovery restores sessions that a newer build can read, but an extreme fence value can be carried into a future ownership grant and leave the session unreadable after another restart. The effect appears limited to an affected session, not a new remote entrypoint.

Retained concerns

  • Medium · security · inferred: A readable quarantined copy at the maximum safe fence can give a retained live row an unsafe future-grant floor. A subsequent reservation can persist an unsafe runtime fence, breaking the persisted lease contract and quarantining the session on reload.
Security review details

Security Blast Radius

  • inferred — The identified failure affects the ownership and reloadability of a session whose stored copies reach the fence boundary. The inspected path reads a local store; it does not establish a new remote caller or cross-service exposure.

Security Findings and Attack Paths

  • inferred — A schema-valid quarantined lease at Number.MAX_SAFE_INTEGER, overlapping a live copy with a lower fence, can supply an unsafe future-grant floor. After an otherwise permitted reservation, that fence can be written as runtimeFence and rejected on the next load. The evidence does not establish a remote way to create that stored value.

Trust Boundaries and Controls

  • observed — Normal and quarantined values pass the same persisted-record and session-ID checks. Separately, acquisition refuses an unreconciled lease; its current-fence check does not validate the newly computed next fence.

Resilience and Maintainability Implications

  • observed — The separate backup-recovery fence path rejects an exhausted computed floor. The new overlapping-copy reconciliation helper has no equivalent safe-integer check.

Hardening Proposals

  • proposed — Reject fence exhaustion before publishing a recovered floor or assigning a new ownership fence, and exercise that boundary through reservation, persistence, and reload.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the primary change: restoring a quarantined session record that the current build can read.
Description check ✅ Passed The description is complete and directly addresses the bug, scope, behavior before and after, implementation, alternatives, testing, visual proof, compatibility, and performance. It also links issue S…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

… live row wins

When a session sits in both lists, the live row is the backup copy an older build salvaged, and the quarantined bytes are the newer commit it could not read. Dropping those bytes without looking at their lease could hand out a fence the newer copy already held. Keep the live row, but raise its next-fence floor above the quarantined copy's.

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

ℹ️ No critical issues — one comment-premise note inline.

Reviewed changes

  • Shared row decoder — the validate → map-legacy-lease → id-vs-key check moves out of parseState into a new decodeStoredAgentSessionRecord, with no change in verdicts.
  • Quarantine re-check on load — parseState now runs that decoder over unusableRecords too: a readable row is restored into records (and needsRewrite set so it persists), a row this build still cannot read keeps its original reason and the file is not rewritten.
  • Same-session collision — when a live record and a readable quarantined copy share an id, the live record wins and the quarantined copy is dropped.
  • Tests — three new cases in agent-session-unreadable-record-salvage.test.ts; I confirmed by ablation (reverting just the unusableRecords change) that the restore and live-wins cases fail on main's logic while the still-unreadable guard passes.

Local verification: targeted suites pass (salvage 5, record-store 45, unsupported-schema 2, backup-recovery 15); pnpm tc:node and pnpm run check:code-quality:changed pass.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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

ℹ️ Prior concern addressed; one new minor note inline.

Reviewed changes

  • Restored-row fence floor (45b5cc4) — when a live row wins over a readable quarantined copy, raiseAgentSessionFenceAboveSupersededCopy now raises the live lease's minimumNextFence to the superseded copy's next fence, so a fence the newer quarantined record already holds is never re-granted. This addresses the previous review's premise concern.
  • Test — a new case builds the live-from-backup / newer-quarantine ordering and asserts the next reservation lands above the quarantined copy's fence.

The remaining findings are unchanged from the prior review; the earlier inline comment is resolved by this commit.

Local verification: agent-session-unreadable-record-salvage.test.ts (6) and agent-session-backup-recovery.test.ts (15) pass; pnpm tc:node and pnpm run check:code-quality:changed pass.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +51 to +52
const floor = nextAgentSessionFence(superseded)
if (floor <= nextAgentSessionFence(record.lease)) {

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.

This helper can produce an unsafe floor where its sibling refuses. raiseAgentSessionFencesAfterBackupRecovery throws agent_session_fence_exhausted when its computed floor is not a safe integer, but here a quarantined row with runtimeFence: Number.MAX_SAFE_INTEGER (a value the record schema accepts) makes floor equal 2 ** 53, which is written to minimumNextFence; a later reservation then mints runtimeFence: 2 ** 53, and isPersistedAgentSessionRecord's safe-integer check quarantines the record on the next load.

Technical details
# Missing fence-exhaustion guard in `raiseAgentSessionFenceAboveSupersededCopy`

## Affected sites
- `src/main/runtime/agent-session-backup-recovery-fence.ts:51` — `floor = nextAgentSessionFence(superseded)` is used with no safe-integer check.
- `src/main/runtime/agent-session-backup-recovery-fence.ts:32` — the sibling path guards the same overflow via `Number.isSafeInteger` → `agent_session_fence_exhausted`.
- `src/shared/agent-session-record.ts:298` — `runtimeFence` is validated only as a safe integer, so `MAX_SAFE_INTEGER` is a legal stored value.

## Required outcome
- A superseded lease at the top of the fence range must not yield a `minimumNextFence` that a subsequent grant can turn into a non-safe `runtimeFence`.

## Suggested approach (optional)
- Mirror the sibling: `if (!Number.isSafeInteger(floor)) throw new Error('agent_session_fence_exhausted')` after computing `floor` (before comparing against the live lease).

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready to merge

Head 7ed08ac8595. Two independent review loops: the first found one real problem and fixed it, the second came back clean. Readiness checks at the start and end both passed with no blocking items. CI is green. tc:node passes.

Fixed during review (45b5cc40f99): when one session sits both in the main list and, as a newer copy this build can now read, in the unreadable list, the PR dropped the newer copy without looking at it. That copy can hold a higher ownership number, so the same number could be handed out twice after a restart. The main-list entry still wins, but its lowest next ownership number is now raised above the dropped copy's, the same way the store already does after recovering from its backup file. A new test fails without this and passes with it. 7ed08ac8595 only fixes the wording of the comment on that field.

Design check: the bug was a saved "can't read this" verdict that nothing ever re-checked. The PR removes that cause by re-checking the verdict against the stored bytes on every load, so it isn't another guard around the old behavior. No new stored field, no wire change, one extra validation per unreadable entry at load (normally none).

Live check (separate Mac, isolated profile, byte-identical seeded store on both builds): on main the affected chat's tab never comes back after restart. On this branch it comes back with its full history and answers new messages, including after another relaunch. An entry that is still unreadable stays in the unreadable list on both builds. A fresh Claude chat still opens and answers across a relaunch. The both-lists case gave ownership number 3 on main and 8 on this branch (the dropped copy was at 7). Screenshots are in the PR body.

Not covered: a real rollback to v1.4.200 and forward again, and a live Codex chat. The change sits in the store load path every provider shares, and the store tests cover it.

Follow-ups, not caused by this PR: (1) backup salvage, which already exists on main, adopts the backup copy without raising its ownership floor, which leaves a similar number-reuse gap in the older build; (2) the ticket's other fix, keeping the rewind section out of the whole-record validity check so an unreadable rewind costs only the rewind and not the session, only helps rollbacks to builds that already have it, and needs its own design for an in-flight rewind; (3) a session that is still unreadable disappears without any notice, on main and on this branch alike.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing without merging. This fixes a structured-chat record that an older build set aside as unreadable and that the current build never re-checks — reachable only after a downgrade followed by an upgrade, with no user report. The planned move of agent-session records into SQLite replaces the JSON record store this PR edits: it has no unreadable-record list, no .bak salvage, and older builds open the store read-only on a newer schema, so they can no longer set a record aside at all. Fixing it here would only cover the window until that lands. Tracked on STA-7446.

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.

1 participant