Skip to content

fix: stop stale runtime event work after renderer cleanup - #23066

Merged
OrcaWin merged 9 commits into
mainfrom
nwparker/perf-09-25-runtime-event-ownership
Sep 26, 2026
Merged

OrcaWin merged 9 commits into
mainfrom
nwparker/perf-09-25-runtime-event-ownership

Conversation

@nwparker

@nwparker nwparker commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​510 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​508
Prod 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​138 $\color{#cf222e}{\Huge{\mathbf{−}}}$​49 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​89

ELI5

An old listener now checks that it still owns a connection before acting on delayed messages. Closing or replacing it stops obsolete refresh work immediately, even when setup has not finished.

What Changed

Runtime-event delivery and reconnect recovery reuse the subscription manager's existing attempt token and stop generation. Initial messages still arrive before setup finishes for the current owner. Stopped, removed or replaced owners cannot start new work, and late setup handles still dispose. Cleanup also handles a synchronous stop/restart without deleting the new owner's subscription.

The WebRTC packaging probe now records its current phase when it reaches its existing deadline, so failures no longer end with an unexplained missing result. Its timeout and all network-security assertions are unchanged.

Why

Previously, ownership was checked when setup returned, leaving a window where a closed listener could keep clearing caches and dispatching provider reads. Waiting to accept messages until setup finishes would lose valid initial frames. Reusing the existing token avoids scanning host lists or adding a cache, timer or wire protocol.

Linked Issue

Fixes #23065

Visual Proof

N/A — internal subscription ownership; no layout or interaction flow changed. No app was launched, and rendered latency remains unmeasured.

Performance proof

A composed test using the actual bridge, manager, runtime adapter, preload dispatcher and Linear actions holds fake IPC setup, closes the bridge, then sends 100 stale messages: 100→0 provider-read dispatches and 100→0 cache publications. Both versions dispose the late handle. These are measured application operations, not external network-request or frame-time claims.

Shared hourly CI prerequisite

The branch also carries the shared hourly-build fixture correction from #23274. Historical package-version inputs are explicit, with exact version/build-number assertions retained and a newer-package control. Default build commands still read package.json; the dedicated no-module-mocking lint rule stays enabled.

Testing

  • Automated acceptance tests added. Against original source, 12 of 13 new tests fail; all pass with the fix.
  • 41 tests across six suites pass, independently repeated. Another 11 independent adverse cases pass, including same-ID re-pair, early messages, old rejection, unsubscribe reentry, sibling hosts, stop/restart and folder refresh forwarding.
  • Web typecheck, focused lint, React Doctor, formatting and changed-code quality pass. The isolated reliability manifest validates with only this PR's new gate.
  • Reproduce: ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/runtime-client-events-sync-ownership.test.ts src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge-ownership.test.ts src/renderer/src/hooks/runtime-client-events-sync.test.ts src/renderer/src/hooks/ipc-events/runtime-reconnect-host-status.test.ts src/renderer/src/runtime/runtime-client-events.test.ts src/preload/runtime-environment-subscriptions.test.ts.
  • macOS unit/IPC simulation only. Native Windows/Linux/WSL, live SSH/remote peers, rendered lifecycle, real provider requests and heap impact remain untested.

The previous Linux package run stopped inside the baseline WebRTC probe after 20 seconds, before testing the protected guest. The exact stalled phase was absent from that log. The new diagnostics pass local lint, formatting, and generated-code syntax checks; hosted validation is pending. This diagnostic change is not a claimed fix for the original timeout.

Reentrant ownership validation

Nested synchronization now supersedes the older reconciliation pass before it can create or remove further subscriptions. Stop detaches the old handles before calling their disposers, preserving subscriptions started reentrantly by cleanup. Four regression cases fail on the prior code; all 45 related tests, web typecheck, changed-code quality, and the dedicated anti-slop check pass. Independent review also checked same-ID replacement and retry ownership.

Review

Merge risk: low to medium. Subscription ownership and reconnect ordering are sensitive. Independent review caught a reentrant restart edge; the corrected implementation passes both permanent and independent regressions. Current same-ID re-pair recovery still works after generation-only SSH invalidation.

Negative user-facing trade-offs — isolated in this PR: each live event adds a constant ownership check (at most two map lookups), and a settled subscription retains a token reference plus an attempt guard closure. A paired synthetic benchmark measured about +0.026 ms per 10,000 pending events and +0.062 ms per 10,000 settled events. Those tiny timing differences can include noise; the added operations are the reliable cost. No UI slowdown or heap-size benefit is claimed.

Obsolete one-shot events are ignored and are not replayed by this fix. Work admitted before cleanup can still finish; physical pending listeners still wait for setup settlement or timeout, and pending error callbacks can still log.

Reliability: experimental gate runtime-events.renderer-subscription-ownership requires zero obsolete dispatch/publication/recovery, valid early/current delivery, independent host survival and late handle disposal. Evidence is deterministic callback/resource counts; no new telemetry. The gate records missing native/rendered/live-peer coverage and requires CI soak before promotion.

Agent skill upstream boundary

  • Not applicable; no skill source changed.

Notes

No producer, message shape, execution-host authority, PTY state, Git provider, path or keyboard behavior changes. Folder and Git workspaces share the same owner check; folder refresh forwarding has an independent composed test.

Checklist

  • Separate trade-off PR with mechanism, ELI5, rationale, measured proof and risks.
  • Independent review and adverse lifecycle tests complete.
  • Visual proof N/A; platform and measurement limits documented.
  • Full application/platform matrix; focused local checks above pass and CI covers this branch.

@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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

📝 Walkthrough

Walkthrough

The runtime event sync manager tracks subscription attempt ownership and stops stale attempts from delivering events. The IPC bridge skips replay invalidation for subscriptions that are no longer current. New tests cover setup, cleanup, replacement, restart, and replay scenarios. A reliability gate records the ownership invariant, test evidence, budgets, known gaps, and promotion and demotion criteria.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to d98e2

A reentrant runtime update can still process work for an environment that is no longer desired and discard the replacement subscription. The Japanese and Korean prompts also misstate who the note is for; resolve the stale-work issue before merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to d98e2

The change prevents outdated runtime subscriptions from starting new refresh work. No new security exposure was identified, but live and cross-platform lifecycle behavior remains incompletely verified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The affected work is renderer-side and selected by runtime environment. The examined change narrows stale-message effects rather than adding a new provider, credential, or service authority.

Trust Boundaries and Controls

  • observed — Runtime responses enter through an environment-selected subscription. Before renderer event handling, the bridge checks transport generations and the manager checks that the pending or active attempt still owns that environment.

Resilience and Maintainability Implications

  • observed — Replacement removes the old active owner before unsubscribe, while stop increments the generation and clears pending attempts and retry timers. A late setup result is disposed instead of installed.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The runtime subscription changes, reliability gate, and tests support the historical stale-work behavior. The additions to en.json, es.json, fr.json, ja.json, ko.json, and zh.json add note… Remove the unrelated locale changes from this pull request, or provide a directly linked active coding objective that requires the note-action labels.
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 4 files. (6 skipped: 6… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Issue #23065 is closed and supplies historical context only. No active directly linked issue remains, so this pull request has no linked-issue coding requirements. The runtime event ownership changes …
Title check ✅ Passed The title clearly and concisely describes the primary change: preventing stale runtime event work after renderer cleanup.
Description check ✅ Passed The description is complete and closely follows the repository template. It explains the user impact, mechanism, rationale, linked issue, visual proof, testing, risks, limitations, and checklist statu…
Full details: Out of Scope Changes check

Explanation

The runtime subscription changes, reliability gate, and tests support the historical stale-work behavior. The additions to en.json, es.json, fr.json, ja.json, ko.json, and zh.json add note-action labels and have no demonstrated connection to runtime event cleanup or subscription ownership. These locale changes are unrelated to the reviewed scope.

Full details: Docstring Coverage

Explanation

Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 4 files. (6 skipped: 6 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch nwparker/perf-09-25-runtime-event-ownership

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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 1694b180-92e3-4481-8649-dfc66adb6933

📥 Commits

Reviewing files that changed from the base of the PR and between 067975b and 6f7d64c.

📒 Files selected for processing (5)
  • config/reliability-gates.jsonc
  • src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge-ownership.test.ts
  • src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge.ts
  • src/renderer/src/hooks/runtime-client-events-sync-ownership.test.ts
  • src/renderer/src/hooks/runtime-client-events-sync.ts

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

Comment on lines +248 to +249
if (syncGeneration !== generation) {
return

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 | 🏗️ Heavy lift

Stop an outer sync when a nested sync replaces its desired set.

If A's initial event changes the desired IDs from ['A', 'B'] to ['C'] and calls sync(), the nested pass starts C. Neither pass changes generation. The outer pass then starts B and deletes C from pending using its stale desiredIds. C's late handle is disposed, while B can deliver an initial event after B is no longer desired. Track sync invocations separately from the stop generation, and end the outer pass when a nested pass takes ownership. Apply that check before starting further subscriptions and before pending cleanup.

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

Reviewed changes

  • Ownership token replaces ad-hoc checks — createRuntimeClientEventsSync now stores a shared SubscriptionToken ({key, generation}) in pending and on each settled subscriptions entry, and exposes isCurrent() to the caller's subscribe.
  • Event delivery gated on ownership — the onEvent wrapper only calls deps.onEvent when isCurrent() is true, so an initial frame still arrives before setup settles, but a stopped/replaced/rekeyed attempt cannot dispatch.
  • Replay recovery gated on ownership — runtime-client-ipc-bridge.ts returns early from the reconnect/replay invalidateRuntimeClientEventReplay(...) callback when !isCurrent().
  • Reentrant reconcile hardening — sync() captures syncGeneration and aborts both reconcile loops if a synchronous stop()/restart bumps generation, and teardown now deletes from subscriptions before calling unsubscribe() so a callback that reenters delivery is rejected.
  • New regression tests + reliability gate — two focused test files and the runtime-events.renderer-subscription-ownership experimental gate; node config/scripts/check-reliability-gates.mjs passes.

I traced the isCurrent predicate against the stop, same-ID re-pair, rekey, late-rejection, overwrite-orphan, and synchronous-stop/restart paths. It correctly admits synchronous initial frames and settled live frames while dropping every non-owning attempt, and the syncGeneration early return leaves the latest store-driven reconcile in charge. The added tests use exact assertions (not.toHaveBeenCalled, toEqual) rather than loose ones, so they pin the behavior they claim. The focused suites pass locally (25 tests across 3 files).

The gate's knownGaps already document the missing native/live-peer/rendered coverage and the fact that already-admitted async handlers are not canceled.

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

@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: Advanced

Run ID: a7c1ca4e-df5f-4a0d-aed1-e374d6f0cca0

📥 Commits

Reviewing files that changed from the base of the PR and between 38c6963 and d98e245.

📒 Files selected for processing (6)
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/fr.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json

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

"c845170b3b": "行 {{value0}}-{{value1}}",
"commentTooLarge": "コメントが大きすぎるため安全に送信できません。"
"commentTooLarge": "コメントが大きすぎるため安全に送信できません。",
"f6c449191e": "AI に関するメモを追加",

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 | 🟡 Minor | ⚡ Quick win

Clarify that the note is for the AI.

Line 15500, AI に関するメモを追加, reads as “Add a note about AI.” The placeholder should tell users that the note is for the AI. Consider AIへのメモを追加.

"c845170b3b": "라인 {{value0}}-{{value1}}",
"commentTooLarge": "댓글이 너무 길어 안전하게 제출할 수 없습니다."
"commentTooLarge": "댓글이 너무 길어 안전하게 제출할 수 없습니다.",
"f6c449191e": "AI에 대한 메모 추가",

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 | 🟡 Minor | ⚡ Quick win

Use wording that means “a note for the AI.”

AI에 대한 메모 추가 can read as “add a note about AI.” Replace it with AI에게 남길 메모.

@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 issues in the runtime-event ownership changes — the new delta is an unrelated locale merge. One process note and a translation nitpick below.

Reviewed changes

Re-reviewed the commits landed since the last Pullfrog review (6f7d64ccb3..3e272a479f) against base main (668fa71906).

  • Verified the ownership code is unchanged — runtime-client-events-sync.ts, runtime-client-ipc-bridge.ts, and both ownership test files are byte-identical to the previously reviewed 6f7d64ccb3, so the prior review of the ownership logic still stands.
  • Re-confirmed the reliability gate survived the merge — the runtime-events.renderer-subscription-ownership block is byte-identical to 6f7d64ccb3 (an earlier main merge briefly dropped it; 3e272a479f restores it) and check-reliability-gates.mjs passes (129 gates).
  • Swept in unrelated locale entries — a merge of branch ci/fix-note-catalog added diff-comment note keys to the six locale files (see below).

ℹ️ An unrelated open PR's commit is merged into this branch

Commit 21741ca353 (fix(i18n): restore diff note draft catalog entries) is the head of open PR #23256 on branch ci/fix-note-catalog, and it entered this branch through the merge d98e245b9a. That commit is the source of all six locale-file changes in this PR's diff; they are unrelated to runtime event ownership. If this merges first it lands #23256's content and that PR will need to rebase or close — better to drop the commit from this branch, or confirm the restore is intended here.

Technical details
# Unrelated locale changes carried by this PR

## Affected sites
- `src/renderer/src/i18n/locales/{en,es,fr,ja,ko,zh}.json` — adds `f6c449191e` ("Add note for the AI"), `5fa4bfebaa` ("Add note") and `5e9b3d0c2e` ("Adding...") under `DiffCommentPopover`, and adds the trailing comma to `commentTooLarge`.

## Provenance
- `d98e245b9a`'s second parent is `21741ca353`, which is the head of open PR #23256 (`ci/fix-note-catalog`).
- `git diff 6f7d64ccb3 HEAD -- <runtime files>` is empty; only the locale files differ from the prior reviewed revision.

## Required outcome
- This PR's diff should contain only runtime-event ownership changes, or the locale restore should be explicitly owned here.

## Open questions for the human
- Was `ci/fix-note-catalog` merged deliberately, or swept in by a `main` merge?

ℹ️ Nitpicks

  • ja.json:15500 and ko.json:15500 render "Add note for the AI" as a note about the AI (AI に関する… / AI에 대한…). If the restore is kept in this PR, AI へメモを追加 / AI를 위한 메모 추가 matches a note addressed to the agent.

Pullfrog  | Fix it ➔ | 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.

✅ No new issues found.

Reviewed changes

Re-reviewed the commits landed since the last Pullfrog review (3e272a479f..11c7d0e857) against base main (abc4cb0f32).

  • Dropped the unrelated locale merge — the six i18n files from #23256 are no longer in the PR diff, resolving the scope contamination flagged in the prior review.
  • Preserved every reliability gate through the main merge — verified HEAD carries exactly main's 129 gate ids plus runtime-events.renderer-subscription-ownership (130 total, no duplicates), and node config/scripts/check-reliability-gates.mjs passes; the terminal-preview.connection-settings-ownership gate from main and the PR's own gate both survive.
  • Added phase diagnostics to the WebRTC packaging probe — the inline Electron script now records the last-entered phase and protectedGuest, and writes them into result.json on the existing 20s deadline and on error, so a stalled probe reports where it stopped. The timeout and network-security assertions are unchanged; the generated script still parses.

The runtime-event ownership source, its two ownership test files, and the gate definition remain byte-identical to the previously reviewed 6f7d64ccb3, so the earlier review of that logic still stands. The six ownership suites pass locally (41 tests).

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

✅ No new issues found.

Reviewed changes

Re-reviewed the commits landed since the last Pullfrog review (11c7d0e857..f864537cca) against base main.

  • Made nested reconciliation last-writer-wins — sync() now stamps a monotonic syncInvocation and each of its loops returns once a reentrant sync() has started, so the outer pass stops acting on its stale desiredIds instead of deleting the nested pass's new pending/subscription entries.
  • Detached stopped handles before disposing them — stop() snapshots and clears subscriptions/pending before calling unsubscribe, so a subscription a cleanup callback starts reentrantly is retained rather than wiped by a later clear().
  • Added four regression tests — nested desired replacement (single and multi environment), empty-desired with a reentrant restore, and stop/restart reentrancy. I confirmed these fail against 11c7d0e857's source (4 failed / 10 passed) and pass with the fix.
  • Isolated the hourly-build identity tests — getHourlyBuildIdentity accepts an injectable packageVersion, so the identity tests no longer read the real package.json, with a new base-floor case. The production CLI entrypoint is unchanged.

The ownership source, bridge, gate definition, and WebRTC probe diagnostics are unchanged from the previously reviewed 11c7d0e857. Focused suites pass locally (34 tests / 3 files).

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

@OrcaWin
OrcaWin merged commit 3ab183d into main Sep 26, 2026
33 checks passed
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.

Disposed renderer runtime listeners can keep starting refresh work

2 participants