Skip to content

fix(runtime): split the host-contact epoch out of the connection generation - #20359

Merged
nwparker merged 3 commits into
mainfrom
astra/mirror-epoch-split-on-20096
Sep 17, 2026
Merged

nwparker merged 3 commits into
mainfrom
astra/mirror-epoch-split-on-20096

Conversation

@nwparker

@nwparker nwparker commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​441 $\color{#cf222e}{\Huge{\mathbf{−}}}$​53 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​388
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​70 $\color{#cf222e}{\Huge{\mathbf{−}}}$​22 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​48

Fixes a regression that the combined PR set re-introduces: after any brief network flap on a paired remote session, the session-tabs mirror is re-keyed and rebuilt — the original #19647 symptom, on a set that already contains its own fix.

Why the collision existed

Two PRs in the same set were each correct about their own half, and the value they shared carried two meanings.

connectionGeneration means both "which socket epoch is this" and "invalidate the mirror."

So the bump #20085 introduced as a resubscribe signal is the same value the others identify as the thing that rebuilds the mirror. One value, two meanings, so one consumer is always wrong.

The counterfactual, measured rather than assumed

#20085's comment claims that without the bump the subscription is dead after recovery. That was a comment, not a measurement, so it was tested first — deleting the bump would have made this much simpler.

Harness: useWebSessionTabsSync over the real store, driven connect → stream end + unverifiable probe → recovery.

subscribeAll calls after recovery mirror key across recovery
combined set (bump present) 1 → 2, old handle unsubscribed changes — the #19647 defect
bump deleted (counterfactual) 1 → 1, zero resubscribes holds

The claim is true, and the same run found why, which had not been established anywhere:

  • global-session-subscription.ts registers only onResponse/onError, no onClose, so the terminal close that main sends on transport loss (src/main/ipc/runtime-environments.ts) is silently dropped.
  • An end frame falls through handleGlobalSessionEvent without resubscribing.
  • installWindowVisibilitySubscriptionParking retries only a rejected subscribe; once a handle has resolved, startEntry returns early forever.

So a trigger genuinely has to exist. It just must not be the cache key.

The fix: two values, one meaning each

  • connectionGeneration returns to identity only — a new runtime session, a re-pair, an explicit clear. A same-runtime return no longer moves it, so no stamp, settle fence, or retained retirement proof is invalidated by a flap.
  • hostContactEpoch (new, on the store entry) counts "the host answered again after we lost contact." It is read only as a dependency of the two subscription effects in use-web-session-tabs-sync.ts — never passed to an installer, never part of environmentKey. It is structurally unable to become a stamp, rather than merely documented as not being one.

useRuntimeSessionMirrorEnvironmentKey becomes useRuntimeSessionMirrorEnvironmentKeys, returning environmentKey (identity) and resubscribeSignal (the epoch edge) from the one target scan, so the hot ownership scan is not doubled.

No third predicate was added: the reconnect condition moved intact from one value to the other.

Two-direction mutation table

Each direction is pinned by its own test. Disjoint in both directions — if one mutation killed both, the two meanings would still be entangled under new names.

mutation fails passes
drop resubscribeSignal / activeWorktreeRuntimeHostContactEpoch from the effect deps reinstalls both session-tabs subscriptions when the host answers again both stability tests
restore the reconnect bump on connectionGeneration holds the mirror environment key across the outage and the recovery, advances the contact epoch, not the connection generation, when a host answers again, represents failed verification honestly without manufacturing a session restart or toast the resubscribe test

Verification

On this base (nwparker/status-writer-one-nulling-rule @ 323fa135f10):

  • src/renderer/src/runtime, src/renderer/src/store/slices, src/renderer/src/lib — 1061 files / 10085 tests, 0 failures
  • tsc --noEmit -p config/tsconfig.tc.web.json — clean
  • oxlint src/renderer/src — clean

The end-to-end gate this restores is tests/e2e/paired-remote-terminal-tab-switch-reconnect.spec.ts, whose writer contract asserts the connection generation holds across a flap (1 -> 1). On the combined set it measured 1 -> 2 on real hardware, deterministically, twice.

Note on scope

This is the same root cause identified independently in several other places across this codebase: one value carrying several meanings, so some consumer is always reading the wrong one. This instance is the sharpest, because both sides of the collision were already fixes.

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

Important

The split is sound for the mirror, but connectionGeneration had one other edge consumer besides the mirror — the setup-script prompt revalidation — and it still reads the generation. Details inline.

Reviewed changes

This run reviewed the full 18-file diff at 73b036b9bd:

  • Split the two meanings of connectionGeneration — the generation returns to connection identity only (runtime-session start, re-pair, removal); the new per-entry hostContactEpoch counts a same-runtime return after a loss of contact.
  • One hook, two keys — useRuntimeSessionMirrorEnvironmentKeys returns environmentKey (identity) and resubscribeSignal (environmentId + epoch) from a single target scan, so the hot ownership scan is not doubled.
  • Subscription effects take the epoch as a dependency only — the global effect depends on resubscribeSignal; the active effect adds activeWorktreeRuntimeHostContactEpoch to its dep array without passing it to the installer.
  • Store wiring — setRuntimeEnvironmentStatus computes the epoch from the null→non-null status transition, and the snapshot path preserves it across an unverifiable probe.
  • Tests — a new reconnect/resubscribe suite plus reworked key/snapshot tests pin each direction of the split.

I traced the production status path: snapshot updates always win (getStatusSnapshots exists in preload, main, and web), lastVerifiedRuntimeStatus reads the retained snapshot.status, so runtimeSessionStarted is false on a same-runtime return and the generation genuinely holds. runtimeEnvironmentStatusesEqual compares hostContactEpoch, so the epoch change forces the Map write and the memoized keys recompute — the resubscribe effects do reinstall. The core mechanics check out.

One consumer was left behind; see the inline comment.

ℹ️ Nitpicks

  • The legacy snapshotless setRuntimeEnvironmentStatus path still advances connectionGeneration on a same-runtime recovery (because lastVerifiedRuntimeStatus returns null without a snapshot), which is why runtime-status.test.ts:521 and runtime-status-first-publication.test.ts:63 still pin the old "recovery advances" behavior. That path is unreachable while getStatusSnapshots exists, but the two tests now read as contradicting the new model — worth a comment or a note that they cover the fallback only.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

// mirror is keyed on. It still needs its own "the host is back" edge: the streams died with
// the transport, an 'end' frame resubscribes nothing, and the parking layer retries only a
// rejected subscribe. This counter is that edge, read only as a subscription-effect dep.
const reconnectedAfterLostContact = status.status !== null && previous?.status === null

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.

Moving the reconnect edge onto hostContactEpoch leaves useSetupScriptPromptRevalidation behind. It still detects a reconnect with repoConnectionGeneration > previousConnectionGenerationRef.current (src/renderer/src/components/sidebar/useSetupScriptPromptRevalidation.ts:81), and on this base the reconnectedAfterLostContact term you removed here was the only thing that advanced connectionGeneration on a same-runtime return. After this change a flap no longer re-runs the setup-script inspection, so a host that made orca.yaml unreadable can keep a stale prompt — the regression the hook exists to clear.

Technical details
# Setup-script prompt no longer revalidates on a same-runtime reconnect

## Affected sites
- `src/renderer/src/store/slices/runtime-status.ts:201` — `connectionChanged` drops the same-runtime recovery edge, so `connectionGeneration` now holds across a flap.
- `src/renderer/src/components/sidebar/useSetupScriptPromptRevalidation.ts:81` — still reads only `connectionGeneration` (`repoConnectionGeneration > previousConnectionGenerationRef.current`) as its reconnect signal; nothing subscribes it to `hostContactEpoch`.
- `src/renderer/src/components/sidebar/useSetupScriptPromptRevalidation.test.tsx:264` — simulates the reconnect by writing `connectionGeneration` straight into the store, so it stays green even though the production trigger no longer fires.

## Required outcome
- A paired-runtime repo whose host answers again after contact was lost must still re-run the setup-script inspection — or the PR must state why a same-runtime return should no longer do so and update the hook's comment/tests to match.

## Suggested approach (optional)
- Read `hostContactEpoch` alongside `connectionGeneration` in the hook (`reconnected = repoConnectionGeneration > prev || repoHostContactEpoch > prevEpoch`), since the epoch is exactly "the host answered again". If more consumers need this, expose one shared host-contact-edge selector rather than each reading the generation.

## Open questions for the human (optional)
- Was the setup-script revalidation on same-runtime recovery intended to be dropped, or only incidental to #20085's mirror bump? The hook's comment ("a runtime reconnect can turn an unreadable orca.yaml into a readable one") and #12469 suggest it is trying to catch exactly this case.

@nwparker
nwparker force-pushed the nwparker/status-writer-one-nulling-rule branch from 323fa13 to 5b1df3f Compare September 17, 2026 06:58
@nwparker
nwparker force-pushed the astra/mirror-epoch-split-on-20096 branch from 73b036b to affbc7e Compare September 17, 2026 06:58

@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 new issues found in the test-only commits.

Reviewed changes

This run re-reviewed the two commits added since the prior pullfrog review at 73b036b9bd — both test-only, no production lines changed:

  • Hydration-verdict test for a host flap — new host-session-mirror-flap-hydration.test.ts asserts the mirror's hydrated verdict (stamped with the connection generation) survives an unverifiable probe on the same runtime and is discarded when the runtime id is replaced.
  • Real RuntimeStatus fixtures — a makeStatus helper builds complete status objects in the new test and in web-session-tabs-sync-reconnect-resubscribe.test.tsx, replacing the partial as RuntimeStatus / as RuntimeHostStatusSnapshot['status'] casts and dropping the now-unneeded AppState import.
  • SAFETY-scoped assertions — the remaining whole-state casts in both test files now carry line-scoped SAFETY: suppressions.

I checked the new hydration test is not theatre: restoring the pre-split reconnect bump to connectionChanged in runtime-status.ts makes keeps the mirror hydrated across an unverifiable probe on the same runtime fail (expected 1 to be +0 at line 103), then reverts clean. Both files pass pnpm run test and oxlint is clean.

The one open concern from the prior review — useSetupScriptPromptRevalidation still keys its reconnect on connectionGeneration — is untouched by these test commits and remains open on the PR.

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

…ration

`connectionGeneration` carried two meanings and one reader was always wrong.
holding the session mirror through an outage leaves its subscriptions stranded
and that edge was the only thing left to revive them. But the same value is the
mirror's cache key -- use-runtime-session-mirror-environment-key.ts keys the
subscription effect on it, every published frame is stamped with it, and
web-session-terminal-retirement-proof-ledger.ts drops retained proofs when it
moves. So the bump #20085 needed as a resubscribe signal re-keyed and rebuilt
the mirror after any brief flap, which is the #19647 symptom #19873/#20059 fix.

Measured first: with the reconnect bump deleted, an ended stream followed by
recovery issues zero resubscribes, and the mirror's subscribe call registers no
`onClose`, so main's terminal close is dropped. #20085's claim is true -- the
subscription really is dead after recovery -- so the trigger has to exist. It
just must not be the cache key.

Give each meaning its own value:

- `connectionGeneration` returns to identity only: a new runtime session, a
  re-pair, an explicit clear. A same-runtime return no longer moves it, so no
  stamp, fence or retained proof is invalidated by a flap.
- `hostContactEpoch` counts "the host answered again after we lost contact". It
  lives on the store entry and is read only as a dependency of the two
  subscription effects in use-web-session-tabs-sync.ts -- never passed to an
  installer, never part of `environmentKey`, so it cannot become a stamp.

`useRuntimeSessionMirrorEnvironmentKey` becomes
`useRuntimeSessionMirrorEnvironmentKeys`, returning `environmentKey` (identity)
and `resubscribeSignal` (the epoch edge) from the one target scan, so the hot
ownership scan is not doubled.

Each direction is pinned by its own test: removing the resubscribe dependency
fails only 'reinstalls both session-tabs subscriptions when the host answers
again'; restoring the reconnect bump fails only the two key-stability tests.
The generation tests assert the key string; this asserts what the user feels.
The mirror's hydration verdict is stamped with the connection generation, so any
bump discards it and every mirrored pane re-parks -- the tab-list rebuild. Held
across an unverifiable probe, still discarded when the runtime id actually moved.
@nwparker
nwparker force-pushed the astra/mirror-epoch-split-on-20096 branch from 7641f12 to 1d7567d Compare September 17, 2026 09:07
@nwparker
nwparker changed the base branch from nwparker/status-writer-one-nulling-rule to main September 17, 2026 09:07
@nwparker
nwparker merged commit 96eb97a into main Sep 17, 2026
3 of 4 checks passed
@coderabbitai

coderabbitai Bot commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: ecd70dcf-b727-4756-9c75-80639e4dee82

📥 Commits

Reviewing files that changed from the base of the PR and between 851befa and 1d7567d.

📒 Files selected for processing (19)
  • src/renderer/src/lib/runtime-session-mirror-targets.test.ts
  • src/renderer/src/lib/runtime-session-mirror-targets.ts
  • src/renderer/src/lib/runtime-session-mirror-unverifiable-host.test.ts
  • src/renderer/src/runtime/host-session-mirror-flap-hydration.test.ts
  • src/renderer/src/runtime/host-session-mirror-hydration-frame-ordering.test.tsx
  • src/renderer/src/runtime/host-session-mirror-settle-receipt-frames.test.tsx
  • src/renderer/src/runtime/use-runtime-session-mirror-environment-key.test.ts
  • src/renderer/src/runtime/use-runtime-session-mirror-environment-key.ts
  • src/renderer/src/runtime/web-session-tabs-sync-reconnect-resubscribe.test.tsx
  • src/renderer/src/runtime/web-session-tabs-sync-unverifiable-host.test.tsx
  • src/renderer/src/runtime/web-session-tabs-sync-visibility-collision.test.tsx
  • src/renderer/src/runtime/web-session-tabs-sync-window-visibility.test.tsx
  • src/renderer/src/runtime/web-session-tabs-sync/use-web-session-tabs-sync.ts
  • src/renderer/src/store/slices/runtime-status-reconnect-connection-generation.test.ts
  • src/renderer/src/store/slices/runtime-status-snapshot.test.ts
  • src/renderer/src/store/slices/runtime-status-snapshot.ts
  • src/renderer/src/store/slices/runtime-status.test.ts
  • src/renderer/src/store/slices/runtime-status.ts
  • src/shared/runtime-host-status.ts

📝 Walkthrough

Walkthrough

The runtime status model now separates connection generations from host contact epochs. Same-runtime recovery preserves connection identity and increments the contact epoch. Mirror key generation returns separate identity and resubscription values. Session-tab synchronization uses these values to reinstall subscriptions after host recovery. Mirror targets now include the contact epoch. Tests cover recovery, hydration, replacement runtimes, target shapes, and updated hook mocks.

✨ Finishing Touches
📝 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.

ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…ration (stablyai#20359)

* fix(runtime): split the host-contact epoch out of the connection generation

`connectionGeneration` carried two meanings and one reader was always wrong.
holding the session mirror through an outage leaves its subscriptions stranded
and that edge was the only thing left to revive them. But the same value is the
mirror's cache key -- use-runtime-session-mirror-environment-key.ts keys the
subscription effect on it, every published frame is stamped with it, and
web-session-terminal-retirement-proof-ledger.ts drops retained proofs when it
moves. So the bump stablyai#20085 needed as a resubscribe signal re-keyed and rebuilt
the mirror after any brief flap, which is the stablyai#19647 symptom stablyai#19873/stablyai#20059 fix.

Measured first: with the reconnect bump deleted, an ended stream followed by
recovery issues zero resubscribes, and the mirror's subscribe call registers no
`onClose`, so main's terminal close is dropped. stablyai#20085's claim is true -- the
subscription really is dead after recovery -- so the trigger has to exist. It
just must not be the cache key.

Give each meaning its own value:

- `connectionGeneration` returns to identity only: a new runtime session, a
  re-pair, an explicit clear. A same-runtime return no longer moves it, so no
  stamp, fence or retained proof is invalidated by a flap.
- `hostContactEpoch` counts "the host answered again after we lost contact". It
  lives on the store entry and is read only as a dependency of the two
  subscription effects in use-web-session-tabs-sync.ts -- never passed to an
  installer, never part of `environmentKey`, so it cannot become a stamp.

`useRuntimeSessionMirrorEnvironmentKey` becomes
`useRuntimeSessionMirrorEnvironmentKeys`, returning `environmentKey` (identity)
and `resubscribeSignal` (the epoch edge) from the one target scan, so the hot
ownership scan is not doubled.

Each direction is pinned by its own test: removing the resubscribe dependency
fails only 'reinstalls both session-tabs subscriptions when the host answers
again'; restoring the reconnect bump fails only the two key-stability tests.

* test(runtime): pin the mirror hydration verdict across a host flap

The generation tests assert the key string; this asserts what the user feels.
The mirror's hydration verdict is stamped with the connection generation, so any
bump discards it and every mirrored pane re-parks -- the tab-list rebuild. Held
across an unverifiable probe, still discarded when the runtime id actually moved.

* test(runtime): build real host statuses instead of casting partials
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