Skip to content

fix(realtime): back off failed generic event connections - #643

Closed
Quick104 wants to merge 4 commits into
mainfrom
fix/c31-event-socket-recovery-r2-repair
Closed

Quick104 wants to merge 4 commits into
mainfrom
fix/c31-event-socket-recovery-r2-repair

Conversation

@Quick104

@Quick104 Quick104 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Related issue: Silo-Server/silo-server#2727
Validation tasks: changes #315 C1-C3; changes #316 C1-C3; changes #332 C1; changes #333 C1; changes #347 C4-C5,C7,C9; changes #348 C4-C5,C7,C9 (generic refresh, reconnect and foreground lifecycle only).

Generic event consumers reset recovery on useful traffic and retry failed connections too quickly for staged socket admission. This gives Home and notifications one shared policy: failed or short attempts use 5/10/20/30-second floors; an accepted subscription lasting at least 30 seconds resets to one second. Jitter adds 0–50%, and readable Retry-After raises the floor.

Each actual attempt mints a fresh ticket. Bare, empty and all-rejected acknowledgements do not count as accepted uptime. Access changes retain immediate recovery. Foreground stop and identity replacement cancel the pending delay and collector; initial collection waits for identity mutation to complete. Rooms and playback retain their recovery.

Validation

  • Source review and finite in-process before/after fixtures; no live reproduction or network traffic. Two independently confirmed defects in the initial candidate were repaired: ACK qualification and observation before initial identity startup.
  • At 9c38a9a, 78 focused tests and 6,077 permitted nonnetwork unit tests passed. Supply-chain checks, required lint with unchanged baselines, and phone/TV debug assembly passed.
  • An earlier untouched settings test initially failed, then passed unchanged in isolation and in the permitted full retry. This is not claimed as a reproduced baseline failure.
  • Test-only follow-up 46d47bb adds one production-factory wiring fixture. All 2,478 inherited blobs equal reviewed 9c38. Removing only the production observer installer causes two intended failures; restoration passes all four cases. The follow-up has not been independently rereviewed.
  • Eleven existing real-network fixture classes were compiled but not executed. The literal network-inclusive unit gate remains unexecuted.
  • Direct case reads record Not run for the listed tasks. Project-wide passed-case lookup lacks read:project; mapping is not exhaustive. No human acceptance or validation record changed.

Evidence

Finite Kotlin fake-clock/flow fixtures, the real in-process identity barrier and Ktor engine/session fixtures verify the exercised paths. A resolved Ktor 3.1.2/OkHttp 4.12 fixture uses a stub WebSocket factory and terminal interceptor with DNS/socket guards to verify failed upgrade headers without network traffic. No rendered device evidence was captured under the finite verification boundary. Recovery can affect phone, tablet, foldable and TV; no form factor is claimed verified. Reviewers still need to assess the missing rendered evidence before release.

Evidence: https://evidence.siloserver.org/r/silo-android/event-socket-recovery/

Integration and release

Server preparation is Silo-Server/silo-server#2739. Startup observes thresholds only; issue #2727 remains unresolved. No deployment, pilot or enforcement occurred, and this local debug candidate is not a named compatible release.

Work-rate recovery remains separate in #642 at 54cf042. Owned composition c771d33c9b31f4af7142c42cbbeb104c12fea82c, tree bcaaa03710955f975d4bdf1c4e5016da85007839, has ordered parents work-rate 54cf042262afbd19d35f3f5f8f0a6d842440ff08 and C31 46d47bb4910f44ebe54aafb9bb2563e3ac6639bb. At that exact head, 114 focused tests in 12 suites and 6,182 permitted unit tests in 770 suites pass; the focused cases are included in the unit total. Supply-chain checks, five required lint tasks and phone/TV debug assembly pass. Parent verification checked 868 retained artifact hashes, four reconstructed patch trees and all 615 excluded room/playback blobs against the work-rate parent; it did not rerun tests. The initial SDK path mismatch stopped before testing and was corrected only in task subprocess variables. Known shield/unavailable reasons, selection floors, correlated refusal and authority fences precede generic fallback; structured refusal stays connected. The standalone PR imports no work-rate source. Independent review covers work-rate 46a and C31 9c38. The small 54cf production response, 46d test-only follow-up and c771 composition have not been independently rereviewed. Eleven network fixture classes remain unexecuted; the literal network-inclusive gate, rendered/device verification and a compatible released baseline are still missing. This is finite source/transport and build evidence, without combined server/native runtime or release clearance.

Apple has no generic event consumer in reviewed main; prospective recovery requirements are tracked in Silo-Server/silo-apple#847. User manual: Silo-Server/siloserver.org#261 and draft docs PR Silo-Server/siloserver.org#262.

AI disclosure

  • Harness: T3 Code through Codex; Claude Code through T3 Code.
  • Tools: Codex, T3 delegated tasks, Claude Code, GitHub CLI, Gradle, Kotlin compiler and Silo evidence CLI.
  • Models: gpt-6.1-sol (xhigh); claude-opus-5-5 (high).
  • Involvement: AI-assisted at a maintainer's direction. No human acceptance or runtime verification is claimed.
  • Adversarial review: Claude Opus 5.5 reviewed the shared fresh-main plan and recovery policy. An isolated Sol 6.1 review confirmed two Android defects, both repaired. A separate prepared-checkout review found no new source defects and independently passed 15 finite helper checks at 31dc04b. Claude Opus 5.5 reviewed 31dc04b and found two recovery regressions and one upgrade-header gap: a rejected upgrade proof can park notifications, an inactive-server removal can leave collectors stale, and OkHttp hides longer upgrade Retry-After values from the current response hook. All three were repaired at 9c38a9a. Eight of 18 new finite regression cases failed before; 78 focused cases pass after. Upgrade refusal retries fresh tickets while mint authentication failures still park; actual OkHttp 429/503 headers preserve their floor; both consumers rebase through the real identity barrier. The final Claude Opus 5.5 review at 9c38a9a confirms all three production repairs after reading all required history and coordination inputs. It found one P3 coverage gap: the actual-engine fixture does not exercise installation through the production client factory. Test-only follow-up 46d47bb exercises that factory without installing the observer in the fixture. Removing only the production installer fails the two refusal-header cases; restoration passes four tests. No production source changed, and this test-only delta has not been independently rereviewed. No combined runtime or release clearance is claimed.

Note

Add shared backoff and Retry-After recovery for generic realtime events connections

Failed generic events connections now follow a shared recovery policy instead of local fixed backoff loops. The ladder uses 5/10/20/30 second floors, resets after 30 seconds of accepted uptime, honors Retry-After headers (delta-seconds or HTTP-date), and reconnects immediately for access changes.

  • Adds genericEventsConnection and GenericEventsAttempt in GenericEventsConnection.kt, with one ticket mint and one upgrade per attempt, ACK-based uptime, and a structured GenericEventsClose terminal event. HomeRealtimeClient and NotificationsRealtimeClient both use it.
  • Adds identity-scoped collectors via genericEventsForIdentity in GenericEventsRecovery.kt so no collector starts during an identity mutation; old collectors are joined and replaced only after the new generation is ready.
  • Adds an Android OkHttp interceptor in EventsUpgradeResponses.kt that converts non-101 events upgrade responses into EventsUpgradeFailure with status and Retry-After preserved, instead of being dropped by the WebSocket listener.
  • Behavioral Change: sessions count as healthy only after a non-empty subscription ACK; useful traffic without an ACK no longer resets the failure ladder. Ticket auth failures park until a new epoch rather than retrying. Tests exist for both.

Macroscope summarized 46d47bb.

@silo-triage silo-triage Bot added the size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. label Oct 20, 2026
@silo-kody

silo-kody Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@coderabbitai

coderabbitai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 1 second.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: cc517280-8d8b-475e-b6f2-5d757508d4ca
📥 Commits

Reviewing files that changed from the base of the PR and between b1e5774 and 46d47bb.

📒 Files selected for processing: 21
  • shared/src/androidMain/kotlin/org/siloserver/silo/network/EventsUpgradeResponses.kt
  • shared/src/androidMain/kotlin/org/siloserver/silo/network/SiloHttpClient.android.kt
  • shared/src/androidUnitTest/kotlin/org/siloserver/silo/network/apiv2/EventsUpgradeOkHttpTest.kt
  • shared/src/androidUnitTest/kotlin/org/siloserver/silo/network/apiv2/EventsUpgradeProductionWiringTest.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/GenericEventsRecovery.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/HomeRealtimeClient.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/NotificationsRealtimeClient.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/apiv2/EventsSocketV2Api.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/apiv2/EventsUpgradeFailure.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/apiv2/GenericEventsConnection.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/repository/HomeRealtimeCoordinator.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/repository/NotificationsRepository.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/network/GenericEventsGenerationTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/network/GenericEventsIdentityTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/network/GenericEventsRecoveryTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/network/IdentityStartupFixture.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/network/apiv2/GenericEventsTransportTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/repository/HomeGenericEventsRecoveryTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/repository/HomeRealtimeAccessChangeTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/repository/NotificationsRepositoryTest.kt
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@silo-triage silo-triage Bot added bug Something isn't working evidence-required Needs before-and-after evidence before the Evidence check passes priority: P2 Limited scope, workaround exists, or polish labels Oct 20, 2026
@silo-triage

silo-triage Bot commented Oct 20, 2026

Copy link
Copy Markdown

Rendered recovery evidence is still missing, as the PR notes. Please add before-and-after captures of Home refresh/reconnect on phone, tablet, foldable (folded and open), and TV, plus phone notifications, with short recordings showing retry timing. Name the build and device for each, or explain why a device is unaffected. The finite fixtures do not show these visible flows; CONTRIBUTING.md requires captures for affected surfaces.

AI-assisted triage: openai/gpt-6.1-sol via OpenClaw.

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adversarial review (claude-opus-5-5, reviewed 31dc04b)

Two new findings, both in how EventsSocketV2Api.frames handles a refused upgrade on the Android OkHttp engine. I also confirmed one existing bot finding.

New findings (inline):

  1. P2: a 401 on the WebSocket upgrade now stops notifications realtime until the app is backgrounded or the profile changes. The base revision retried it.
  2. P3: on OkHttp, a 429 or 503 upgrade refusal throws before the execute block runs, so the upgrade Retry-After is never read. The in-memory test engine does not reproduce this.

Confirmed existing finding (P2): Kody's comment on GenericEventsRecovery.kt:85 holds, judging by the source. AndroidServerRegistry.remove of an inactive server runs changing(SERVER_REMOVE) with affectsCurrentIdentity = false, which still advances the barrier generation. EncryptedTokenManagerImpl copies that generation into every scope snapshot, and AuthScopeSnapshot.isSameIdentityAs compares it. Home's owner.matches(..., OwnerPolicy.PROFILE) check then returns from the collector. Notifications' while (current(connectionViewer)) loop also exits. genericEventsForIdentity skips that transition, so neither consumer restarts until the next identity transition, profile reset, or foreground cycle. At the base revision both loops ran while (true) and took a fresh viewer each pass, so they recovered. I checked this by reading the source only; I did not execute it.

Checked, no finding: the 5/10/20/30 s ladder; reset only after at least 30 s of qualified acceptance, with 1 s plus jitter; 0–50% jitter; delta-seconds and HTTP-date Retry-After read at mint; overflow clamping on huge Retry-After; immediate access_changed; a fresh ticket per attempt; one consumer and one delay per identity; cancellation on identity replacement and when the app leaves the foreground. Also the two repaired issues: decoded nonempty WsSubscribed acceptance, and transition observation registered before guarded undispatched startup. Room and playback recovery are unchanged.

Method and limits: I read the 15-file diff against base b1e5774f, plus the Home (phone and TV) and phone notification call sites, the Ktor 3.1.2 and OkHttp 4.12.0 bytecode on the resolved classpath, and the server handlers that send these statuses. For the inline findings I compiled and ran a small JVM program, outside the repository, against the real Ktor OkHttp engine and WebSockets plugin. It uses a stub okhttp3.WebSocket.Factory that reports the handshake outcome the way RealWebSocket.checkUpgradeSuccess does, so it opens no socket and makes no network request. I did not run the Gradle suites, a device, or a live server.

AI disclosure: Claude Code with Claude Opus 5.5 (claude-opus-5-5), running in the T3 Code harness, wrote this review. No other AI tools were used.

@macroscopeapp

macroscopeapp Bot commented Oct 20, 2026

Copy link
Copy Markdown

Home recovery changes when Home sections refresh after a socket reconnect (shared/src/commonMain/kotlin/org/siloserver/silo/repository/HomeRealtimeCoordinator.kt); the PR declares no rendered captures for phone, tablet, foldable folded/open, or TV. The evidence page should show a short recording of the reconnect-triggered refresh on each.
Notifications recovery changes when inbox rows and unread state catch up (shared/src/commonMain/kotlin/org/siloserver/silo/repository/NotificationsRepository.kt); the PR declares no rendered captures for phone, tablet, or foldable folded/open. The evidence page should show a short recording of notification recovery on those devices.

Suggested fix: No diff; add the rendered recordings to the evidence page.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@silo-kody

silo-kody Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@macroscopeapp

macroscopeapp Bot commented Oct 20, 2026

Copy link
Copy Markdown

The latest changes alter user-visible recovery after refused upgrades and identity-generation changes, while the Evidence section says no rendered captures were made.

  • Home reconnect refresh and retry timing (HomeRealtimeCoordinator.kt, GenericEventsRecovery.kt): the evidence page should show a short recording of the refresh after reconnect on an Android phone, tablet, foldable folded and open, and Android TV.
  • Notifications inbox and unread-state recovery (NotificationsRepository.kt, GenericEventsRecovery.kt): the evidence page should show a short recording of recovery on an Android phone, tablet, and foldable folded and open; notifications realtime is not wired to the active TV UI.

Suggested fix: No diff; add the rendered recordings to the evidence page.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adversarial review (claude-opus-5-5, reviewed 9c38a9a)

All three findings from the 31dc04b round are fixed at this head. I found one new P3, inline: nothing executed checks that the production HTTP client installs the new eventsUpgradeResponses() interceptor.

Repairs checked:

  • Upgrade 401/403 now throws EventsUpgradeFailure and closes as socket_error, so it takes the 5 s failed-attempt floor and mints a fresh ticket. Mint 401/403 still closes as ticket_error_401/_403 and parks notifications.
  • The interceptor acts only on /api/v2/events/ws with the silo.events.v2 subprotocol and a non-101 status. It closes the response and keeps only the status and the parsed Retry-After. A 101 passes through unchanged, and room and playback sockets do not match. LocalRouteInterceptor never routes WebSocket upgrades (LocalRouteInterceptor.kt:113), so its fallback cannot replay a spent ticket. EventsUpgradeFailure is an IOException, so OkHttp reports it through onFailure.
  • In the resolved Ktor 3.1.2 bytecode, OkHttpEngine applies the config {} block to every client it derives and uses that client as the WebSocket factory when none is configured. The interceptor is therefore on the production upgrade path.
  • Generation rebasing: both barrier phases carry the new generation, so WILL_CHANGE cancels the collector and DID_CHANGE restarts it under the barrier. Inactive-server removal is the only producer of affectsCurrentIdentity = false, so the extra reconnects are rare and user-initiated. The ACK qualification and observe-before-start repairs are unchanged.

For later work on this boundary: the interceptor closes the refusal body. A future client that needs structured refusal details from a 429 or 503 body has to read them here.

Method and limits: I read the full diff against b1e5774f, the 31dc04b..9c38a9a repair, the Home and notification call sites, the HTTP client and local-route wiring, and the Ktor OkHttp engine bytecode. I did not run Gradle, a device or a live server. Test results cited in the PR are the author's runs, not mine.

AI disclosure: Claude Code with Claude Opus 5.5 (claude-opus-5-5), running in the T3 Code harness, wrote this review. No other AI tools were used.

@silo-kody

silo-kody Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104 Quick104 closed this Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working evidence-required Needs before-and-after evidence before the Evidence check passes priority: P2 Limited scope, workaround exists, or polish size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant