Skip to content

perf(android): stabilize startup, detail, and playback work - #97

Closed
RXWatcher wants to merge 30 commits into
Silo-Server:mainfrom
RXWatcher:perf/android-client-performance-stability-v2
Closed

RXWatcher wants to merge 30 commits into
Silo-Server:mainfrom
RXWatcher:perf/android-client-performance-stability-v2

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • bound and coalesce startup/home hydration across Android phone and TV
  • pause off-route detail enrichment and isolate playback-clock recomposition
  • make teardown and final-position persistence lifecycle- and identity-safe
  • preserve playback state across recreation and keep TV duration on the live clock

Verification

  • 2,516 unit tests passed across shared, Android shared, phone, and TV suites
  • phone and TV debug APKs assembled successfully
  • no SiloCast paths changed

CI

  • intentionally skipped per maintainer request; verified locally

Summary by CodeRabbit

  • New Features
    • Added reliable final playback-position saving across mobile and TV, with updates consolidated in the background.
    • Added scoped Home-section request reuse, refresh controls, and compatibility hydration for older responses.
  • Bug Fixes
    • Prevented stale playback, subtitle, and detail updates after navigation or account changes.
    • Improved playback continuity during configuration changes and asynchronous screen teardown.
  • Performance
    • Limited background loading for Home, recommendations, episode details, and artwork to reduce UI stalls.
  • Documentation
    • Added implementation plans and design specifications for Android performance and request handling improvements.

RXWatcher added 30 commits July 23, 2026 05:27
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds scoped Home request coalescing, bounded section hydration, durable final playback-position persistence, lifecycle-safe playback teardown, and route-aware Android mobile/TV detail and player updates. It also adds extensive unit and source-structure tests plus implementation plans and design specifications.

Changes

Android performance and request-flow remediation

Layer / File(s) Summary
Scoped Home requests and refresh policy
shared/src/commonMain/kotlin/org/siloserver/silo/repository/..., shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt, shared/src/commonTest/..., docs/superpowers/...home-request...
Home requests now use auth scope, in-flight coalescing, freshness-based reuse, forced refresh handling, and bounded fallback hydration.
Bounded startup and section hydration
android-shared/src/androidMain/kotlin/.../startup/*, shared/src/commonMain/kotlin/.../model/section/*, android-shared/src/androidUnitTest/.../startup/*
Startup hydration normalizes response shapes, limits fallback concurrency to four, preserves order, and gates cache warming on complete resolution.
Scoped final playback persistence and teardown
shared/src/commonMain/kotlin/.../port/UserItemStatePort.kt, android-shared/src/androidMain/kotlin/.../player/*, androidApp/.../PlayerViewModel.kt, androidTvApp/.../TvPlayerViewModel.kt
Final playback writes carry identity scope, are validated and coalesced in an application-owned writer, and playback session stopping is coordinated asynchronously.
Mobile route-aware detail and player lifecycle
androidApp/src/androidMain/kotlin/.../detail/*, androidApp/src/androidMain/kotlin/.../player/*, androidApp/src/androidUnitTest/...
Mobile detail work pauses off-route and resumes when visible; player state, mounting, subtitle refresh, configuration disposal, and exit handling use explicit lifecycle gates.
TV detail, Home, shell, and player updates
androidTvApp/src/androidMain/kotlin/...
TV secondary work is bounded and generation-checked, Home resume refresh is persisted and gated, collection probes are cached by identity, and playback-clock state is isolated from structural player state.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

Suggested reviewers: quick104

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.30% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately summarizes the main Android performance stabilization work across startup, detail, and playback.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Choose a reason for hiding this comment

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

Actionable comments posted: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
shared/src/androidMain/kotlin/org/siloserver/silo/network/EncryptedTokenManagerImpl.kt (1)

300-325: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Make scope capture atomic with identity generation.

Lines 308 and 324 can observe a new generation after changing() begins but before the transition updates state under mutex. That produces an old scope labeled with the new generation; if identifiers are reused, the request/cache validation can accept pre-transition data. Capture the generation and scope state in one transition-protected transaction.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@shared/src/androidMain/kotlin/org/siloserver/silo/network/EncryptedTokenManagerImpl.kt`
around lines 300 - 325, Update snapshotCurrentScope so identity generation and
all scope fields are captured atomically under the same transition protection as
changing(). Ensure both the temporaryScope and active-scope branches read and
label their snapshot from the same captured generation/state transaction,
preventing an old scope from being paired with a newer identity generation.
🧹 Nitpick comments (2)
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt (1)

75-103: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Hydration/fallback algorithm duplicated with HomeViewModel.fetchSections.

This function reimplements the same unresolved-section filter → bounded-concurrency fetch → resolveHomeSectionItems → fully-resolved-tracking algorithm found in HomeViewModel.fetchSections (shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt lines ~137-159). This function's shape (a named data class + suspend function taking a fetchItems callback) is actually the cleaner candidate to promote into commonMain and reuse from both call sites.
See consolidated comment for the proposed extraction.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt`
around lines 75 - 103, The hydration algorithm in hydrateStartupHomeSections
duplicates HomeViewModel.fetchSections. Promote StartupHomeResolution and
hydrateStartupHomeSections into commonMain, preserving the unresolved filtering,
bounded-concurrency fetches, resolveHomeSectionItems usage, and fullyResolved
behavior, then update both call sites to reuse the shared implementation and
remove the duplicate logic.
shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt (1)

137-159: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Hydration fallback algorithm duplicated with StartupWarmup.hydrateStartupHomeSections.

This block reimplements the same unresolved-section filter → bounded-concurrency fetch → resolveHomeSectionItems → fully-resolved-tracking algorithm as hydrateStartupHomeSections in StartupWarmup.kt, just with a Pair<ResolvedSection, Boolean> shape instead of a named result type. Behavior is equivalent today but the duplication risks silent drift between the ViewModel and startup-warmup paths on future changes.
See consolidated comment for the proposed shared-function extraction.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt`
around lines 137 - 159, Extract the duplicated section-hydration workflow from
the HomeViewModel loading path into a shared function, then have both this flow
and StartupWarmup.hydrateStartupHomeSections use it. Preserve the existing
filtering, bounded concurrency, resolveHomeSectionItems fallback, and
fully-resolved status while replacing the local Pair<ResolvedSection, Boolean>
implementation with the shared result type.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepository.kt`:
- Around line 106-120: Make the scope check and final write in the repository
method containing snapshotProvider and recordPositionOwned execute under the
same generation gate or lock used by profile/credential transitions. Move or
coordinate validation with the Room transaction so an identity change cannot
occur between validation and commit; return false for stale scope, otherwise
complete the write before allowing the transition.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/FinalPlaybackPositionWriter.kt`:
- Around line 36-49: Update the worker loop in FinalPlaybackPositionWriter’s
init coroutine so failed write(snapshot) operations are retained instead of
being discarded after pending.clear(). Reinsert or otherwise preserve the latest
failed snapshots, retry them with bounded backoff, and keep the coroutine alive
while continuing to process wakeUp triggers and successful writes.

In
`@android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepositoryTest.kt`:
- Around line 245-265: Extend the repository tests around recordPosition to
cover a credential-generation mismatch for the same server and profile, varying
captured versus current credentialGenerationId while keeping identity otherwise
matching. Assert recordPosition rejects the stale write, both projection rows
remain absent as appropriate, and the outbox contains no SET_POSITION entry; use
the existing DAO/query helpers and test symbols.

In
`@android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycleLoggingTest.kt`:
- Around line 22-38: The current test only inspects source text instead of
validating lifecycle ordering. In PlaybackSessionLifecycleLoggingTest, add a
coroutine-based race test that blocks stopSession or its final flush, invokes
stopAsync(), verifies start() or adoptActiveSession() stays suspended, then
releases teardown and confirms the new session remains active. Replace or
supplement the substring assertions with this focused behavioral coverage.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt`:
- Around line 3141-3180: Update onExit() to explicitly cancel upNextCountdownJob
and resolveNextEpisodeJob, and clear showUpNext before exiting. Ensure
startUpNextCountdown() cannot continue or invoke advanceToNextEpisode() after
exit, while preserving the existing exit guard and cleanup behavior.

In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt`:
- Around line 479-485: Update the collection probe loop around runCatching in
the library identity-probe flow to rethrow CancellationException instead of
converting cancellation into a null result. Ensure the snapshot assignments to
librariesWithCollectionsSnapshot, probedCollectionsIdentityKey, and
probedCollectionLibraryIds occur only after a non-cancelled probe completes.

In
`@shared/src/commonTest/kotlin/org/siloserver/silo/model/section/HomeSectionHydrationTest.kt`:
- Around line 8-20: Update
topLevelItemsHydrateSectionMetadataWithDefaultZeroCount to assert that
resolved?.totalCount equals 0, verifying that resolveHomeSectionItems uses the
response metadata count instead of preserving original.totalCount.

---

Outside diff comments:
In
`@shared/src/androidMain/kotlin/org/siloserver/silo/network/EncryptedTokenManagerImpl.kt`:
- Around line 300-325: Update snapshotCurrentScope so identity generation and
all scope fields are captured atomically under the same transition protection as
changing(). Ensure both the temporaryScope and active-scope branches read and
label their snapshot from the same captured generation/state transaction,
preventing an old scope from being paired with a newer identity generation.

---

Nitpick comments:
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt`:
- Around line 75-103: The hydration algorithm in hydrateStartupHomeSections
duplicates HomeViewModel.fetchSections. Promote StartupHomeResolution and
hydrateStartupHomeSections into commonMain, preserving the unresolved filtering,
bounded-concurrency fetches, resolveHomeSectionItems usage, and fullyResolved
behavior, then update both call sites to reuse the shared implementation and
remove the duplicate logic.

In `@shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt`:
- Around line 137-159: Extract the duplicated section-hydration workflow from
the HomeViewModel loading path into a shared function, then have both this flow
and StartupWarmup.hydrateStartupHomeSections use it. Preserve the existing
filtering, bounded concurrency, resolveHomeSectionItems fallback, and
fully-resolved status while replacing the local Pair<ResolvedSection, Boolean>
implementation with the shared result type.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d6f939d2-f26c-42f7-94a6-5d55dce87cbb

📥 Commits

Reviewing files that changed from the base of the PR and between 428e967 and 25aa106.

📒 Files selected for processing (64)
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepository.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/di/PlayerInfraModule.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/FinalPlaybackPositionWriter.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycle.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepositoryTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/FinalPlaybackPositionWriterTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycleLoggingTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/startup/StartupHomeHydrationTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/startup/StartupWarmupSourceTest.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/ItemDetailScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/ItemDetailViewModel.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/SimilarRail.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt
  • androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/SharedStartupWarmupSourceTest.kt
  • androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/performance/MobileDetailOpenPerformanceSourceTest.kt
  • androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/performance/MobilePlayerLifecyclePerformanceSourceTest.kt
  • androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/detail/EpisodeRollupAccumulatorTest.kt
  • androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/MobilePlayerPresentationStateTest.kt
  • androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerScreenStartPositionTest.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvItemDetailScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvItemDetailViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/home/HomeResumeRefreshPolicy.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/SharedStartupWarmupSourceTest.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeedSourceTest.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/performance/TvDetailOpenPerformanceSourceTest.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/home/HomeResumeRefreshPolicyTest.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeScreenSourceTest.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerPresentationStateTest.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreenStartPositionTest.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModelPlaybackPositionTest.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvCollectionsPresenceCacheTest.kt
  • docs/superpowers/plans/2026-07-22-android-home-request-coalescing.md
  • docs/superpowers/plans/2026-07-22-android-mobile-performance-remediation.md
  • docs/superpowers/plans/2026-07-22-android-startup-home-fanout-remediation.md
  • docs/superpowers/plans/2026-07-22-android-tv-performance-remediation.md
  • docs/superpowers/specs/2026-07-22-android-home-request-coalescing-design.md
  • docs/superpowers/specs/2026-07-22-android-mobile-performance-remediation-design.md
  • docs/superpowers/specs/2026-07-22-android-startup-home-fanout-remediation-design.md
  • docs/superpowers/specs/2026-07-22-android-tv-performance-remediation-design.md
  • shared/src/androidMain/kotlin/org/siloserver/silo/network/EncryptedTokenManagerImpl.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/section/HomeSectionHydration.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/AuthScopeSnapshot.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/api/SectionApi.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/repository/HomeSectionsRequestGate.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/repository/port/UserItemStatePort.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/util/BoundedConcurrency.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/model/section/HomeSectionHydrationTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/network/SiloAuthPluginPinTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/repository/HomeSectionsRequestGateTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/util/BoundedConcurrencyTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeViewModelPerformanceSourceTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeViewModelRefreshPolicySourceTest.kt
💤 Files with no reviewable changes (1)
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt

Comment on lines +106 to +120
val current = snapshotProvider() ?: return false
if (current.serverId != scope.serverId ||
current.profileId != scope.profileId ||
current.credentialGenerationId != scope.credentialGenerationId ||
current.identityGeneration != scope.identityGeneration
) return false

return recordPositionOwned(
serverId = scope.serverId,
profileId = scope.profileId,
contentId = contentId,
fileId = fileId,
positionSeconds = positionSeconds,
durationSeconds = durationSeconds,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Make scope validation atomic with the final write.

Lines 106-111 validate identity before the Room transaction starts at Line 144. A profile/credential transition in that gap still allows this write to commit and return true after its captured identity is no longer current. Coordinate auth-scope transitions and this write through the same generation gate/lock so the write is either rejected or completes before the identity changes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepository.kt`
around lines 106 - 120, Make the scope check and final write in the repository
method containing snapshotProvider and recordPositionOwned execute under the
same generation gate or lock used by profile/credential transitions. Move or
coordinate validation with the Room transaction so an identity change cannot
occur between validation and commit; return false for stale scope, otherwise
complete the write before allowing the transition.

Comment on lines +36 to +49
init {
scope.launch {
for (ignored in wakeUp) {
while (true) {
val batch = synchronized(lock) {
if (pending.isEmpty()) {
emptyList()
} else {
pending.values.toList().also { pending.clear() }
}
}
if (batch.isEmpty()) break
batch.forEach { snapshot -> runCatching { write(snapshot) } }
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Do not discard failed final-position writes.

Line 48 swallows failures after Lines 40-45 clear pending, so a transient Room failure silently loses the final resume position and no later trigger retries it. Preserve the latest failed snapshot and retry with bounded backoff while keeping the worker alive.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/FinalPlaybackPositionWriter.kt`
around lines 36 - 49, Update the worker loop in FinalPlaybackPositionWriter’s
init coroutine so failed write(snapshot) operations are retained instead of
being discarded after pending.clear(). Reinsert or otherwise preserve the latest
failed snapshots, retry them with bounded backoff, and keep the coroutine alive
while continuing to process wakeUp triggers and successful writes.

Comment on lines +245 to +265
@Test
fun scopedPositionRejectsProfileThatIsNoLongerCurrent() = runTest {
val captured = PlaybackWriteScope("server", "profile-a", null, 4L)
currentSnapshot = authScope("server", "profile-b", generation = 5L)

assertFalse(repo.recordPosition(captured, "movie", 7, 42.0, 100.0))
assertNull(db.userItemStateDao().get("server", "profile-a", "movie", 7))
assertNull(db.userItemStateDao().get("server", "profile-b", "movie", 7))
}

@Test
fun scopedPositionWritesOnlyToMatchingCapturedIdentity() = runTest {
val captured = PlaybackWriteScope("server", "profile-a", null, 4L)
currentSnapshot = authScope("server", "profile-a", generation = 4L)

assertTrue(repo.recordPosition(captured, "movie", 7, 42.0, 100.0))
assertEquals(
42.0,
db.userItemStateDao().get("server", "profile-a", "movie", 7)?.positionSeconds,
)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Cover credential rotation and outbox suppression.

These cases never vary credentialGenerationId and only assert projection rows. Add a same-server/profile credential-generation mismatch case and assert no SET_POSITION outbox row is queued; otherwise a stale final-position write can still be synchronized after an identity change.

As per coding guidelines, “add focused tests for shared-logic changes only when behavior is critical or high-risk.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepositoryTest.kt`
around lines 245 - 265, Extend the repository tests around recordPosition to
cover a credential-generation mismatch for the same server and profile, varying
captured versus current credentialGenerationId while keeping identity otherwise
matching. Assert recordPosition rejects the stale write, both projection rows
remain absent as appropriate, and the outbox contains no SET_POSITION entry; use
the existing DAO/query helpers and test symbols.

Source: Coding guidelines

Comment on lines +22 to +38
@Test
fun aNewStartWaitsForAnAsynchronousStopToFinish() {
val text = source.joinToString("\n")

assertTrue(text.contains("private var pendingStopJob: Job?"))
assertTrue(text.contains("private suspend fun awaitPendingStop()"))
assertTrue(
text.substringAfter("suspend fun start(params: StartParams)")
.substringBefore("suspend fun adoptActiveSession(")
.contains("awaitPendingStop()"),
)
assertTrue(
text.substringAfter("suspend fun adoptActiveSession(")
.substringBefore("private suspend fun startInternal(")
.contains("awaitPendingStop()"),
)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

Test the lifecycle race behavior directly.

This only proves substrings exist. Add a coroutine test that holds stopSession/final flush, calls stopAsync(), verifies start() or adoptActiveSession() remains suspended, then releases teardown and verifies the new session survives. That validates the ordering this change is intended to guarantee.

As per coding guidelines, “add focused tests for shared-logic changes only when behavior is critical or high-risk.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycleLoggingTest.kt`
around lines 22 - 38, The current test only inspects source text instead of
validating lifecycle ordering. In PlaybackSessionLifecycleLoggingTest, add a
coroutine-based race test that blocks stopSession or its final flush, invokes
stopAsync(), verifies start() or adoptActiveSession() stays suspended, then
releases teardown and confirms the new session remains active. Replace or
supplement the substring assertions with this focused behavioral coverage.

Source: Coding guidelines

Comment on lines 3141 to 3180
/** Called when the user exits the player. */
fun onExit() {
if (!exitPrepared.compareAndSet(false, true)) return
resetPlaybackRecoveryState()
viewModelScope.launch {
// Track B: durably record the final position for both paths, then ask
// the outbox to drain promptly (covers the online offline-download case
// where there's no live session and no connectivity change to trigger it).
val cid = _uiState.value.contentId.takeIf { it.isNotBlank() }
val fid = currentFileId()
if (cid != null && fid != null) {
userItemStatePort.recordPosition(
cid,
fid,
_uiState.value.position,
_uiState.value.duration.takeIf { it > 0.0 },
)
outboxSyncScheduler.requestSync()
}
// Lifecycle.stop() handles: final progress report, snapshot via PersonalData,
// session stop, and reporter cancellation. The single call replaces the
// duplicated reportProgress/stopSession + syncProgressSnapshot flow.
sessionLifecycle.stop()
controlsHideJob?.cancel()
introObserverJob?.cancel()
searchJob?.cancel()
aiJobHandle?.cancel()
introAutoSkipController.reset()
_uiState.update {
it.copy(
isLoading = false,
sessionId = null,
playMethod = null,
playbackPlan = null,
delivery = null,
streamUrl = null,
container = null,
subtitleTracks = emptyList(),
isPaused = true,
isPlaying = false,
val state = _uiState.value
val cid = state.contentId.takeIf { it.isNotBlank() }
val fid = currentFileId()
val scope = finalPositionScope
if (scope != null && cid != null && fid != null) {
finalPlaybackPositionWriter.submit(
FinalPlaybackPosition(
scope = scope,
contentId = cid,
fileId = fid,
positionSeconds = state.position,
durationSeconds = state.duration.takeIf { it > 0.0 },
)
}
)
}
sessionLifecycle.stopAsync()
controlsHideJob?.cancel()
introObserverJob?.cancel()
searchJob?.cancel()
aiJobHandle?.cancel()
introAutoSkipController.reset()
_uiState.update {
it.copy(
isLoading = false,
sessionId = null,
playMethod = null,
playbackPlan = null,
delivery = null,
streamUrl = null,
container = null,
subtitleTracks = emptyList(),
isPaused = true,
isPlaying = false,
)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

onExit() doesn't stop the Up Next auto-advance, so a countdown can start a session that outlives the exit guard.

onExit()'s resetPlaybackRecoveryState() cancels recovery/seek jobs but not upNextCountdownJob or resolveNextEpisodeJob, and it never clears showUpNext. startUpNextCountdown()'s loop only bails on !state.showUpNext, which stays true after exit. If a user backs out while the (non-modal) Up Next countdown is running, the countdown can still fire advanceToNextEpisode() → loadContent() after onExit() already ran. Since exitPrepared is a one-shot latch with no reset, that newly-started session's final-position submit and sessionLifecycle.stopAsync() are permanently skipped on any later onExit()/onCleared() call — an orphaned session. Notably, loadContent() itself already treats upNextCountdownJob/resolveNextEpisodeJob as needing explicit cancellation on transitions; onExit() should do the same.

🔧 Proposed fix
     fun onExit() {
         if (!exitPrepared.compareAndSet(false, true)) return
+        upNextCountdownJob?.cancel()
+        upNextCountdownJob = null
+        resolveNextEpisodeJob?.cancel()
         resetPlaybackRecoveryState()
         val state = _uiState.value
         val cid = state.contentId.takeIf { it.isNotBlank() }
         val fid = currentFileId()
         val scope = finalPositionScope
         if (scope != null && cid != null && fid != null) {
             finalPlaybackPositionWriter.submit(
                 FinalPlaybackPosition(
                     scope = scope,
                     contentId = cid,
                     fileId = fid,
                     positionSeconds = state.position,
                     durationSeconds = state.duration.takeIf { it > 0.0 },
                 )
             )
         }
         sessionLifecycle.stopAsync()
         controlsHideJob?.cancel()
         introObserverJob?.cancel()
         searchJob?.cancel()
         aiJobHandle?.cancel()
         introAutoSkipController.reset()
         _uiState.update {
             it.copy(
                 isLoading = false,
                 sessionId = null,
                 playMethod = null,
                 playbackPlan = null,
                 delivery = null,
                 streamUrl = null,
                 container = null,
                 subtitleTracks = emptyList(),
                 isPaused = true,
                 isPlaying = false,
+                showUpNext = false,
+                upNextCountdownSeconds = null,
             )
         }
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/** Called when the user exits the player. */
fun onExit() {
if (!exitPrepared.compareAndSet(false, true)) return
resetPlaybackRecoveryState()
viewModelScope.launch {
// Track B: durably record the final position for both paths, then ask
// the outbox to drain promptly (covers the online offline-download case
// where there's no live session and no connectivity change to trigger it).
val cid = _uiState.value.contentId.takeIf { it.isNotBlank() }
val fid = currentFileId()
if (cid != null && fid != null) {
userItemStatePort.recordPosition(
cid,
fid,
_uiState.value.position,
_uiState.value.duration.takeIf { it > 0.0 },
)
outboxSyncScheduler.requestSync()
}
// Lifecycle.stop() handles: final progress report, snapshot via PersonalData,
// session stop, and reporter cancellation. The single call replaces the
// duplicated reportProgress/stopSession + syncProgressSnapshot flow.
sessionLifecycle.stop()
controlsHideJob?.cancel()
introObserverJob?.cancel()
searchJob?.cancel()
aiJobHandle?.cancel()
introAutoSkipController.reset()
_uiState.update {
it.copy(
isLoading = false,
sessionId = null,
playMethod = null,
playbackPlan = null,
delivery = null,
streamUrl = null,
container = null,
subtitleTracks = emptyList(),
isPaused = true,
isPlaying = false,
val state = _uiState.value
val cid = state.contentId.takeIf { it.isNotBlank() }
val fid = currentFileId()
val scope = finalPositionScope
if (scope != null && cid != null && fid != null) {
finalPlaybackPositionWriter.submit(
FinalPlaybackPosition(
scope = scope,
contentId = cid,
fileId = fid,
positionSeconds = state.position,
durationSeconds = state.duration.takeIf { it > 0.0 },
)
}
)
}
sessionLifecycle.stopAsync()
controlsHideJob?.cancel()
introObserverJob?.cancel()
searchJob?.cancel()
aiJobHandle?.cancel()
introAutoSkipController.reset()
_uiState.update {
it.copy(
isLoading = false,
sessionId = null,
playMethod = null,
playbackPlan = null,
delivery = null,
streamUrl = null,
container = null,
subtitleTracks = emptyList(),
isPaused = true,
isPlaying = false,
)
}
}
/** Called when the user exits the player. */
fun onExit() {
if (!exitPrepared.compareAndSet(false, true)) return
upNextCountdownJob?.cancel()
upNextCountdownJob = null
resolveNextEpisodeJob?.cancel()
resetPlaybackRecoveryState()
val state = _uiState.value
val cid = state.contentId.takeIf { it.isNotBlank() }
val fid = currentFileId()
val scope = finalPositionScope
if (scope != null && cid != null && fid != null) {
finalPlaybackPositionWriter.submit(
FinalPlaybackPosition(
scope = scope,
contentId = cid,
fileId = fid,
positionSeconds = state.position,
durationSeconds = state.duration.takeIf { it > 0.0 },
)
)
}
sessionLifecycle.stopAsync()
controlsHideJob?.cancel()
introObserverJob?.cancel()
searchJob?.cancel()
aiJobHandle?.cancel()
introAutoSkipController.reset()
_uiState.update {
it.copy(
isLoading = false,
sessionId = null,
playMethod = null,
playbackPlan = null,
delivery = null,
streamUrl = null,
container = null,
subtitleTracks = emptyList(),
isPaused = true,
isPlaying = false,
showUpNext = false,
upNextCountdownSeconds = null,
)
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt`
around lines 3141 - 3180, Update onExit() to explicitly cancel
upNextCountdownJob and resolveNextEpisodeJob, and clear showUpNext before
exiting. Ensure startUpNextCountdown() cannot continue or invoke
advanceToNextEpisode() after exit, while preserving the existing exit guard and
cleanup behavior.

Comment on lines 479 to +485
libraries.forEach { lib ->
val result = runCatching { sectionRepository.getLibraryCollections(lib.id) }.getOrNull()
if (result is ApiResult.Success && result.data.isNotEmpty()) ids += lib.id
}
librariesWithCollections = ids
librariesWithCollectionsSnapshot = ids.toIntArray()
probedCollectionsIdentityKey = collectionsIdentityKey
probedCollectionLibraryIds = currentLibraryIds

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not swallow cancellation from collection probes.

runCatching captures CancellationException. A cancelled prior identity probe can continue and overwrite the newer cache, leaving librariesWithCollections unknown or stale until the library list changes. Rethrow cancellation before committing the snapshot.

Proposed fix
-            val result = runCatching { sectionRepository.getLibraryCollections(lib.id) }.getOrNull()
+            val result = try {
+                sectionRepository.getLibraryCollections(lib.id)
+            } catch (error: CancellationException) {
+                throw error
+            } catch (_: Throwable) {
+                null
+            }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
libraries.forEach { lib ->
val result = runCatching { sectionRepository.getLibraryCollections(lib.id) }.getOrNull()
if (result is ApiResult.Success && result.data.isNotEmpty()) ids += lib.id
}
librariesWithCollections = ids
librariesWithCollectionsSnapshot = ids.toIntArray()
probedCollectionsIdentityKey = collectionsIdentityKey
probedCollectionLibraryIds = currentLibraryIds
libraries.forEach { lib ->
val result = try {
sectionRepository.getLibraryCollections(lib.id)
} catch (error: CancellationException) {
throw error
} catch (_: Throwable) {
null
}
if (result is ApiResult.Success && result.data.isNotEmpty()) ids += lib.id
}
librariesWithCollectionsSnapshot = ids.toIntArray()
probedCollectionsIdentityKey = collectionsIdentityKey
probedCollectionLibraryIds = currentLibraryIds
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt`
around lines 479 - 485, Update the collection probe loop around runCatching in
the library identity-probe flow to rethrow CancellationException instead of
converting cancellation into a null result. Ensure the snapshot assignments to
librariesWithCollectionsSnapshot, probedCollectionsIdentityKey, and
probedCollectionLibraryIds occur only after a non-cancelled probe completes.

Comment on lines +8 to +20
fun topLevelItemsHydrateSectionMetadataWithDefaultZeroCount() {
val original = section("original", totalCount = 1)
val metadata = section("server", totalCount = 0)
val item = SectionItem(contentId = "movie-1", type = "movie", title = "Movie")

val resolved = resolveHomeSectionItems(
originalSection = original,
response = HomeSectionItemsResponse(section = metadata, items = listOf(item)),
)

assertEquals("server", resolved?.id)
assertEquals(listOf("movie-1"), resolved?.items?.map { it.contentId })
}

Copy link
Copy Markdown

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

Assert the zero-count metadata contract.

This test passes if resolveHomeSectionItems keeps original.totalCount == 1, despite its stated purpose. Assert the resolved count is 0.

Proposed fix
         assertEquals("server", resolved?.id)
+        assertEquals(0, resolved?.totalCount)
         assertEquals(listOf("movie-1"), resolved?.items?.map { it.contentId })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fun topLevelItemsHydrateSectionMetadataWithDefaultZeroCount() {
val original = section("original", totalCount = 1)
val metadata = section("server", totalCount = 0)
val item = SectionItem(contentId = "movie-1", type = "movie", title = "Movie")
val resolved = resolveHomeSectionItems(
originalSection = original,
response = HomeSectionItemsResponse(section = metadata, items = listOf(item)),
)
assertEquals("server", resolved?.id)
assertEquals(listOf("movie-1"), resolved?.items?.map { it.contentId })
}
fun topLevelItemsHydrateSectionMetadataWithDefaultZeroCount() {
val original = section("original", totalCount = 1)
val metadata = section("server", totalCount = 0)
val item = SectionItem(contentId = "movie-1", type = "movie", title = "Movie")
val resolved = resolveHomeSectionItems(
originalSection = original,
response = HomeSectionItemsResponse(section = metadata, items = listOf(item)),
)
assertEquals("server", resolved?.id)
assertEquals(0, resolved?.totalCount)
assertEquals(listOf("movie-1"), resolved?.items?.map { it.contentId })
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@shared/src/commonTest/kotlin/org/siloserver/silo/model/section/HomeSectionHydrationTest.kt`
around lines 8 - 20, Update
topLevelItemsHydrateSectionMetadataWithDefaultZeroCount to assert that
resolved?.totalCount equals 0, verifying that resolveHomeSectionItems uses the
response metadata count instead of preserving original.totalCount.

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