StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
Fix Stalker VOD hydration ownership and provider dialogs
David Nashash76833b387f0b
diff --git a/core/ui/src/main/java/com/streamvault/core/ui/components/dialogs/PremiumDialog.kt b/core/ui/src/main/java/com/streamvault/core/ui/components/dialogs/PremiumDialog.ktindex 98fe21e3..c8b96412 100644--- a/core/ui/src/main/java/com/streamvault/core/ui/components/dialogs/PremiumDialog.kt+++ b/core/ui/src/main/java/com/streamvault/core/ui/components/dialogs/PremiumDialog.kt@@ -75,6 +75,7 @@ fun PremiumDialog(onDismissRequest: () -> Unit,modifier: Modifier = Modifier,widthFraction: Float = 0.42f,+ smallScreenWidthFraction: Float = 0.9f,heightFraction: Float? = 0.88f,bodyHeightFraction: Float = 0.5f,bodyScrollHint: String? = null,@@ -163,7 +164,7 @@ fun PremiumDialog(contentAlignment = Alignment.Center) {val resolvedWidthFraction = when {- maxWidth < 700.dp -> 0.9f+ maxWidth < 700.dp -> smallScreenWidthFractionmaxWidth < 1000.dp -> maxOf(widthFraction, 0.62f)else -> widthFraction}diff --git a/data/src/androidTest/java/com/streamvault/data/local/StalkerVodHydrationIntegrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/StalkerVodHydrationIntegrationTest.ktindex 3c7b0fbd..0abe05c7 100644--- a/data/src/androidTest/java/com/streamvault/data/local/StalkerVodHydrationIntegrationTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/StalkerVodHydrationIntegrationTest.kt@@ -12,10 +12,12 @@ import com.streamvault.data.local.entity.MovieEntityimport com.streamvault.data.local.entity.PlaybackHistoryEntityimport com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.local.entity.SeriesEntity+import com.streamvault.data.local.entity.StalkerIndexJobEntityimport com.streamvault.data.local.entity.VodCategoryHydrationEntityimport com.streamvault.data.local.entity.VodCatalogEntryEntityimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.StalkerIndexStateimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.test.runTestimport org.junit.Test@@ -23,6 +25,101 @@ import org.junit.runner.RunWith@RunWith(AndroidJUnit4::class)class StalkerVodHydrationIntegrationTest {+ @Test+ fun persistedPageAndIndexContinuationSurviveReopenAndCascadeOnProviderDeletion() = runTest {+ val context = ApplicationProvider.getApplicationContext<Context>()+ val databaseName = "stalker-vod-restart-integration.db"+ context.deleteDatabase(databaseName)+ var db = Room.databaseBuilder(context, StreamVaultDatabase::class.java, databaseName)+ .allowMainThreadQueries()+ .build()+ try {+ val providerId = db.providerDao().insert(+ ProviderEntity(name = "VOD restart fixture", type = ProviderType.STALKER_PORTAL)+ )+ val categoryId = 73L+ db.movieDao().upsertCategoryPage(+ providerId,+ listOf(+ MovieEntity(+ streamId = 7301L,+ name = "Committed page one",+ categoryId = categoryId,+ providerId = providerId+ )+ )+ )+ db.vodCatalogEntryDao().replacePage(+ providerId,+ categoryId,+ 1,+ listOf(+ VodCatalogEntryEntity(+ providerId = providerId,+ categoryId = categoryId,+ rawItemId = "7301",+ itemType = ContentType.MOVIE,+ targetId = 7301L,+ rawPage = 1,+ rawIndex = 0+ )+ )+ )+ db.vodCategoryHydrationDao().upsert(+ VodCategoryHydrationEntity(+ providerId = providerId,+ categoryId = categoryId,+ lastLoadedPage = 1,+ lastAttemptedPage = 2,+ lastSuccessfulPage = 1,+ totalPages = 3,+ advertisedTotalPages = 3,+ itemCount = 1,+ lastStatus = "FAILED_RETRYABLE",+ lastError = "temporary page two failure"+ )+ )+ db.stalkerIndexJobDao().upsert(+ StalkerIndexJobEntity(+ providerId = providerId,+ section = ContentType.MOVIE,+ state = StalkerIndexState.PARTIAL,+ totalCategories = 4,+ completedCategories = 1,+ nextCategoryIndex = 1,+ indexedRows = 1+ )+ )++ db.close()+ db = Room.databaseBuilder(context, StreamVaultDatabase::class.java, databaseName)+ .allowMainThreadQueries()+ .build()++ val resumedHydration = db.vodCategoryHydrationDao().get(providerId, categoryId)+ assertThat(resumedHydration?.lastSuccessfulPage).isEqualTo(1)+ assertThat(resumedHydration?.lastAttemptedPage).isEqualTo(2)+ assertThat(resumedHydration?.lastStatus).isEqualTo("FAILED_RETRYABLE")+ assertThat(db.vodCatalogEntryDao().countByCategory(providerId, categoryId)).isEqualTo(1)+ assertThat(db.movieDao().getByProviderSync(providerId).single().name)+ .isEqualTo("Committed page one")+ val resumedJob = db.stalkerIndexJobDao().get(providerId, ContentType.MOVIE.name)+ assertThat(resumedJob?.state).isEqualTo(StalkerIndexState.PARTIAL)+ assertThat(resumedJob?.nextCategoryIndex).isEqualTo(1)++ db.providerDao().delete(providerId)++ assertThat(db.providerDao().getById(providerId)).isNull()+ assertThat(db.vodCategoryHydrationDao().get(providerId, categoryId)).isNull()+ assertThat(db.vodCatalogEntryDao().countByCategory(providerId, categoryId)).isEqualTo(0)+ assertThat(db.movieDao().getByProviderSync(providerId)).isEmpty()+ assertThat(db.stalkerIndexJobDao().get(providerId, ContentType.MOVIE.name)).isNull()+ } finally {+ db.close()+ context.deleteDatabase(databaseName)+ }+ }+@Testfun roomPageCommitKeepsProtectionIdentityFavoritesProgressAndCatalogOrder() = runTest {val context = ApplicationProvider.getApplicationContext<Context>()@@ -161,6 +258,9 @@ class StalkerVodHydrationIntegrationTest {assertThat(refreshedMovie.name).isEqualTo("Updated movie")assertThat(refreshedMovie.isUserProtected).isTrue()assertThat(refreshedMovie.watchProgress).isEqualTo(31_500L)+ assertThat(db.movieDao().search(providerId, "updated", 10).first().map { it.name })+ .containsExactly("Updated movie")+ assertThat(db.movieDao().search(providerId, "before", 10).first()).isEmpty()assertThat(db.favoriteDao().getGlobalByType(providerId, ContentType.MOVIE.name).first().map(FavoriteEntity::contentId)@@ -176,6 +276,35 @@ class StalkerVodHydrationIntegrationTest {assertThat(hydration?.lastSuccessfulPage).isEqualTo(2)assertThat(hydration?.totalPages).isEqualTo(2)assertThat(hydration?.isComplete).isTrue()++ val failedTransaction = runCatching {+ db.withTransaction {+ db.movieDao().upsertCategoryPage(+ providerId,+ listOf(+ MovieEntity(+ streamId = 101L,+ name = "Rolled back title",+ categoryId = categoryId,+ providerId = providerId+ )+ )+ )+ db.vodCategoryHydrationDao().upsert(+ requireNotNull(db.vodCategoryHydrationDao().get(providerId, categoryId)).copy(+ lastSuccessfulPage = 3,+ isComplete = false+ )+ )+ error("abort test transaction")+ }+ }+ assertThat(failedTransaction.exceptionOrNull()).isInstanceOf(IllegalStateException::class.java)+ assertThat(db.movieDao().getByProviderSync(providerId).single { it.streamId == 101L }.name)+ .isEqualTo("Updated movie")+ val durableHydration = db.vodCategoryHydrationDao().get(providerId, categoryId)+ assertThat(durableHydration?.lastSuccessfulPage).isEqualTo(2)+ assertThat(durableHydration?.isComplete).isTrue()} finally {db.close()}diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.ktindex 6bfe8614..ec6a3ddd 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt@@ -768,7 +768,15 @@ internal companion object {api.getVodStreams(session, profile, rawCategoryId)}return mapResolvedItems(ContentType.SERIES, vodResult) { item ->- if (item.isSeries) toSeries(item, requestedCategoryId = categoryId) else null+ if (item.isSeries) {+ toSeries(+ item,+ requestedCategoryId = categoryId,+ origin = SeriesCatalogOrigin.VOD_DERIVED+ )+ } else {+ null+ }}}return mapped@@ -783,7 +791,15 @@ internal companion object {val vodPage = mapPagedItems(ContentType.SERIES, categoryId) { session, profile, rawCategoryId ->api.getVodStreamsPage(session, profile, rawCategoryId, page)}.let { result -> mapResolvedPage(ContentType.SERIES, result) { item ->- if (item.isSeries) toSeries(item, requestedCategoryId = categoryId) else null+ if (item.isSeries) {+ toSeries(+ item,+ requestedCategoryId = categoryId,+ origin = SeriesCatalogOrigin.VOD_DERIVED+ )+ } else {+ null+ }} }return vodPage}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.ktindex ba9bbae7..3c4526c9 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt@@ -304,9 +304,15 @@ class SyncManager @Inject constructor(getHydration = stalkerIndexCheckpointStore::getHydrationSnapshot,currentIndexedRowCount = ::currentStalkerIndexedRowCount,pruneStaleRows = { providerId, contentType ->- xtreamContentIndexDao.pruneStaleLocalContentRows(providerId, contentType.name)+ inFencedStalkerIndexTransaction(providerId) {+ xtreamContentIndexDao.pruneStaleLocalContentRows(providerId, contentType.name)+ }+ },+ updateSummaryMetadata = { providerId, contentType, indexedRows, finalState, now ->+ inFencedStalkerIndexTransaction(providerId) {+ updateStalkerSummaryMetadata(providerId, contentType, indexedRows, finalState, now)+ }},- updateSummaryMetadata = ::updateStalkerSummaryMetadata,fetchSummaryPage = { provider, api, contentType, categoryId, page ->withStalkerFetchPermit(provider, contentType, categoryId, page) {fetchStalkerSummaryPageWithRecovery(@@ -323,9 +329,35 @@ class SyncManager @Inject constructor(fetchStalkerWildcardSummaryPageWithRecovery(api, contentType, categoryId, page)}},- markAttemptStarted = stalkerIndexCheckpointStore::markAttemptStarted,- markAttemptSucceeded = stalkerIndexCheckpointStore::markAttemptSucceeded,- markAttemptFailed = stalkerIndexCheckpointStore::markAttemptFailed,+ markAttemptStarted = { providerId, contentType, categoryId, hydration, attemptedPage, now ->+ inFencedStalkerIndexTransaction(providerId) {+ stalkerIndexCheckpointStore.markAttemptStarted(+ providerId, contentType, categoryId, hydration, attemptedPage, now+ )+ }+ },+ markAttemptSucceeded = { providerId, contentType, categoryId, hydration, attemptedPage,+ now, itemCount, totalPages, pageSize, advertisedTotalItems,+ advertisedTotalPages, pageComplete, truncated,+ terminationReason, pageFingerprint ->+ inFencedStalkerIndexTransaction(providerId) {+ stalkerIndexCheckpointStore.markAttemptSucceeded(+ providerId, contentType, categoryId, hydration, attemptedPage, now,+ itemCount, totalPages, pageSize, advertisedTotalItems,+ advertisedTotalPages, pageComplete, truncated, terminationReason,+ pageFingerprint+ )+ }+ },+ markAttemptFailed = { providerId, contentType, categoryId, hydration, attemptedPage,+ now, message, retryable, pageFingerprint ->+ inFencedStalkerIndexTransaction(providerId) {+ stalkerIndexCheckpointStore.markAttemptFailed(+ providerId, contentType, categoryId, hydration, attemptedPage, now,+ message, retryable, pageFingerprint+ )+ }+ },upsertMovieSummaryBatch = { providerId, movies, indexedAt ->upsertXtreamMovieSummaryBatch(providerId, movies, indexedAt, restoreWatchProgress = false)},@@ -342,8 +374,16 @@ class SyncManager @Inject constructor(StalkerIndexRecoveryPolicy.failureState(error, ::sanitizeThrowableMessage)},progress = ::progress,- restoreMovieWatchProgress = { providerId -> movieDao.restoreWatchProgress(providerId) },- upsertJob = catalogIndexJobStore::upsert,+ restoreMovieWatchProgress = { providerId ->+ inFencedStalkerIndexTransaction(providerId) {+ movieDao.restoreWatchProgress(providerId)+ }+ },+ upsertJob = { update ->+ inFencedStalkerIndexTransaction(update.providerId) {+ catalogIndexJobStore.upsert(update)+ }+ },log = { message -> Log.i(TAG, message) }))@@ -1847,6 +1887,19 @@ class SyncManager @Inject constructor()}+ /**+ * Keep Stalker index writes inside the workflow generation that fetched them. The fence and+ * mutation share one Room transaction, so a configuration supersession cannot slip between+ * the ownership check and a checkpoint, prune, or job-state write.+ */+ private suspend fun <T> inFencedStalkerIndexTransaction(+ providerId: Long,+ block: suspend () -> T+ ): T = transactionRunner.inTransaction {+ providerWorkflowCommitFence.assertCanCommit(providerId)+ block()+ }+private suspend fun upsertXtreamMovieSummaryBatch(providerId: Long,movies: List<Movie>,@@ -1880,6 +1933,7 @@ class SyncManager @Inject constructor(}if (updatedMovies.isNotEmpty() || movieIndexChanged) {transactionRunner.inTransaction {+ providerWorkflowCommitFence.assertCanCommit(providerId)if (updatedMovies.isNotEmpty()) movieDao.insertAll(updatedMovies)val newlyInsertedStreamIds = updatedMovies.filter { existingByStreamId[it.streamId] == null }@@ -1940,6 +1994,7 @@ class SyncManager @Inject constructor(}if (updatedSeries.isNotEmpty() || seriesIndexChanged) {transactionRunner.inTransaction {+ providerWorkflowCommitFence.assertCanCommit(providerId)if (updatedSeries.isNotEmpty()) seriesDao.insertAll(updatedSeries)val newlyInsertedSeriesIds = updatedSeries.filter { existingBySeriesId[it.seriesId] == null }@@ -1981,6 +2036,7 @@ class SyncManager @Inject constructor(}var accepted = emptyList<SeriesEntity>()transactionRunner.inTransaction {+ providerWorkflowCommitFence.assertCanCommit(providerId)val existing = seriesDao.getBySeriesIds(providerId, incoming.map { it.seriesId }).associateBy { it.seriesId }accepted = incoming.mapNotNull { summary ->diff --git a/data/src/main/java/com/streamvault/data/sync/VodCategoryHydrationCoordinator.kt b/data/src/main/java/com/streamvault/data/sync/VodCategoryHydrationCoordinator.ktindex d5b8131b..d2b06bfe 100644--- a/data/src/main/java/com/streamvault/data/sync/VodCategoryHydrationCoordinator.kt+++ b/data/src/main/java/com/streamvault/data/sync/VodCategoryHydrationCoordinator.kt@@ -118,7 +118,12 @@ internal class VodCategoryHydrationCoordinator(}val pageFingerprint = page.items.joinToString("|") { it.rawItemId }.takeIf(String::isNotEmpty)- if (pageFingerprint != null && !seenPageFingerprints.add(pageFingerprint)) {+ if (hasRepeatedPageFingerprint(+ seenFingerprints = seenPageFingerprints,+ previousFingerprint = hydration?.lastPageFingerprint,+ currentFingerprint = pageFingerprint+ )+ ) {val prior = hydration ?: VodCategoryHydrationEntity(providerId, categoryId)hydration = prior.copy(lastAttemptedPage = page.page,@@ -332,7 +337,12 @@ internal class VodCategoryHydrationCoordinator(}val pageFingerprint = page.items.joinToString("|") { it.rawItemId }.takeIf(String::isNotEmpty)- if (pageFingerprint != null && !seenPageFingerprints.add(pageFingerprint)) {+ if (hasRepeatedPageFingerprint(+ seenFingerprints = seenPageFingerprints,+ previousFingerprint = hydration?.lastPageFingerprint,+ currentFingerprint = pageFingerprint+ )+ ) {val prior = hydration ?: MovieCategoryHydrationEntity(providerId, movieCategoryId)hydration = prior.copy(lastAttemptedPage = page.page,@@ -496,3 +506,12 @@ internal class VodCategoryHydrationCoordinator(return hydrateSplitVodCategory(providerId, movieCategoryId, request, ContentType.SERIES)}}++private fun hasRepeatedPageFingerprint(+ seenFingerprints: MutableSet<String>,+ previousFingerprint: String?,+ currentFingerprint: String?+): Boolean {+ if (currentFingerprint == null) return false+ return previousFingerprint == currentFingerprint || !seenFingerprints.add(currentFingerprint)+}diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.ktindex d7b68419..e0b8fe26 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt@@ -13,6 +13,8 @@ import com.streamvault.domain.model.CatalogLayoutimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.PlaybackTransportModeimport com.streamvault.domain.model.Result+import com.streamvault.domain.model.SeriesCatalogOrigin+import com.streamvault.domain.model.VodCatalogItemimport com.streamvault.domain.provider.GuideRequestimport com.streamvault.domain.model.StalkerBootstrapRecipeimport com.streamvault.domain.model.StalkerTransportGrant@@ -501,6 +503,95 @@ class StalkerProviderTest {assertThat(series.data.totalPages).isEqualTo(1)}+ @Test+ fun splitVodPage_keepsMixedOrder_andMarksVodDerivedSeries() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ vodCategories = listOf(StalkerCategoryRecord("124", "Mixed")),+ vodPageItems = listOf(+ StalkerItemRecord(+ id = "100",+ name = "Movie A",+ streamUrl = "https://cdn.example.com/movie-a.mp4",+ isSeries = false+ ),+ StalkerItemRecord(+ id = "200",+ name = "Derived Series",+ streamUrl = "https://cdn.example.com/series.mp4",+ isSeries = true+ ),+ StalkerItemRecord(+ id = "300",+ name = "Movie B",+ streamUrl = "https://cdn.example.com/movie-b.mp4",+ isSeries = false+ )+ )+ )+ val provider = categoryReuseProvider(api)+ val movieCategory = (provider.getVodCategories() as Result.Success).data.single()+ val seriesCategoryId = checkNotNull(provider.projectVodCategoryToSeries(movieCategory.id))++ val page = (provider.getSplitVodPage(movieCategory.id, seriesCategoryId, 1) as Result.Success).data++ assertThat(page.items.map { it.rawItemId }).containsExactly("100", "200", "300").inOrder()+ assertThat(page.items.map { entry ->+ when (entry.item) {+ is VodCatalogItem.MovieItem -> "movie"+ is VodCatalogItem.SeriesItem -> "series"+ }+ }).containsExactly("movie", "series", "movie").inOrder()+ val derivedSeries = (page.items[1].item as VodCatalogItem.SeriesItem).series+ assertThat(derivedSeries.categoryId).isEqualTo(seriesCategoryId)+ assertThat(derivedSeries.catalogOrigin).isEqualTo(SeriesCatalogOrigin.VOD_DERIVED)+ }++ @Test+ fun seriesPage_fallsBackToVodItemsMarkedAsSeries_whenNativePageIsEmpty() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ vodItems = listOf(+ StalkerItemRecord(+ id = "100",+ name = "Movie",+ streamUrl = "https://cdn.example.com/movie.mp4",+ isSeries = false+ ),+ StalkerItemRecord(+ id = "200",+ name = "Derived Series",+ streamUrl = "https://cdn.example.com/series.mp4",+ isSeries = true+ )+ ),+ vodPageItems = listOf(+ StalkerItemRecord(+ id = "100",+ name = "Movie",+ streamUrl = "https://cdn.example.com/movie.mp4",+ isSeries = false+ ),+ StalkerItemRecord(+ id = "200",+ name = "Derived Series",+ streamUrl = "https://cdn.example.com/series.mp4",+ isSeries = true+ )+ )+ )+ val provider = categoryReuseProvider(api)++ val page = (provider.getSeriesListPage(categoryId = null, page = 1) as Result.Success).data++ assertThat(page.items.map { it.name }).containsExactly("Derived Series")+ assertThat(page.items.single().catalogOrigin).isEqualTo(SeriesCatalogOrigin.VOD_DERIVED)++ val listed = (provider.getSeriesList(categoryId = null) as Result.Success).data+ assertThat(listed.map { it.name }).containsExactly("Derived Series")+ assertThat(listed.single().catalogOrigin).isEqualTo(SeriesCatalogOrigin.VOD_DERIVED)+ }+@Testfun unifiedVodPage_keepsMixedProviderOrder_andDefaultsMissingMarkerToMovie() = runTest {val api = FakeStalkerApiService(@@ -1741,6 +1832,7 @@ class StalkerProviderTest {private val seriesCategoriesResult: Result<List<StalkerCategoryRecord>>? = null,private val vodPageItems: List<StalkerItemRecord> = emptyList(),private val seriesPageItems: List<StalkerItemRecord> = emptyList(),+ private val vodItems: List<StalkerItemRecord> = emptyList(),private val shortEpgByChannel: Map<String, List<StalkerProgramRecord>> = emptyMap(),private val shortEpgResultsByChannel: Map<String, Result<List<StalkerProgramRecord>>> = emptyMap(),private val epgByChannel: Map<String, List<StalkerProgramRecord>> = emptyMap(),@@ -1817,7 +1909,7 @@ class StalkerProviderTest {session: StalkerSession,profile: StalkerDeviceProfile,categoryId: String?- ) = Result.success(emptyList<StalkerItemRecord>())+ ) = Result.success(vodItems)override suspend fun getVodStreamsPage(session: StalkerSession,diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.ktindex fba0e4b8..31b20cda 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt@@ -15,6 +15,8 @@ import com.streamvault.data.local.dao.MovieCategoryHydrationDaoimport com.streamvault.data.local.dao.MovieDaoimport com.streamvault.data.local.dao.ProgramDaoimport com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.ProviderWorkflowDao+import com.streamvault.data.local.dao.ProviderWorkflowLeaseimport com.streamvault.data.local.dao.SeriesCategoryHydrationDaoimport com.streamvault.data.local.dao.SeriesDaoimport com.streamvault.data.local.dao.StalkerIndexJobDao@@ -32,6 +34,7 @@ import com.streamvault.data.local.entity.ChannelGuideSyncEntityimport com.streamvault.data.local.entity.MovieCategoryHydrationEntityimport com.streamvault.data.local.entity.MovieEntityimport com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.ProviderWorkflowPhaseimport com.streamvault.data.mapper.toEntityimport com.streamvault.data.provider.toProviderSnapshotimport com.streamvault.data.provider.TypedProviderClientFactory@@ -448,7 +451,8 @@ class SyncManagerTest {providerPresent: Boolean = true,providerEntity: Provider? = null,readinessTracker: StalkerReadinessTracker = StalkerReadinessTracker(),- portalStateStore: com.streamvault.data.remote.stalker.StalkerPortalStateStore = mock()+ portalStateStore: com.streamvault.data.remote.stalker.StalkerPortalStateStore = mock(),+ commitFence: ProviderWorkflowCommitFence = ProviderWorkflowCommitFence()): SyncManager {val configuredProvider = if (providerPresent) providerEntity ?: sampleProvider(providerType) else null// Keep the existing sync fixtures on the streaming fallback contract while their@@ -599,7 +603,7 @@ class SyncManagerTest {stalkerRequestCoordinator = com.streamvault.data.remote.stalker.StalkerRequestCoordinator(),stalkerPortalStateStore = portalStateStore,stalkerReadinessTracker = readinessTracker,- providerWorkflowCommitFence = ProviderWorkflowCommitFence(),+ providerWorkflowCommitFence = commitFence,typedProviderClientFactory = typedProviderClientFactory,providerSnapshotRepository = object : ProviderSnapshotRepository {override suspend fun getSnapshot(providerId: Long) =@@ -1988,6 +1992,7 @@ class SyncManagerTest {verify(xtreamIndexJobDao, atLeastOnce()).upsert(jobs.capture())val finalMovieJob = jobs.allValues.last { it.section == ContentType.MOVIE.name }assertThat(finalMovieJob.state).isEqualTo("SUCCESS")+ verify(xtreamContentIndexDao).pruneStaleLocalContentRows(1L, ContentType.MOVIE.name)}@Test@@ -2610,6 +2615,113 @@ class SyncManagerTest {assertThat(requestedPages).contains(5)}+ @Test+ fun `superseded Stalker movie index cannot commit fetched page rows or checkpoint`() = runTest {+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(+ serverUrl = "http://example.com",+ username = "",+ password = "",+ stalkerMacAddress = "00:11:22:33:44:55",+ epgSyncMode = ProviderEpgSyncMode.SKIP,+ maxConnections = 1+ )+ val categoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.MOVIE, "5")+ val workflowDao = mock<ProviderWorkflowDao>()+ org.mockito.kotlin.whenever(+ workflowDao.isCurrentOwner(+ providerId = eq(providerEntity.id),+ generation = eq(9L),+ phase = eq(ProviderWorkflowPhase.MOVIE_INDEX),+ token = eq("superseded-lease")+ )+ ).thenReturn(1, 1, 0)+ val manager = buildManager(+ providerType = ProviderType.STALKER_PORTAL,+ providerEntity = providerEntity,+ commitFence = ProviderWorkflowCommitFence(workflowDao)+ )++ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(+ Result.success(+ StalkerSession(+ loadUrl = "http://example.com/stalker_portal/server/load.php",+ portalReferer = "http://example.com/stalker_portal/c/",+ token = "token"+ ) to StalkerProviderProfile(accountName = "Stalker")+ )+ )+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(+ Result.success(listOf(StalkerCategoryRecord(id = "5", name = "Action")))+ )+ org.mockito.kotlin.whenever(categoryDao.getByProviderAndTypeSync(providerEntity.id, ContentType.MOVIE.name)).thenReturn(+ listOf(+ CategoryEntity(+ categoryId = categoryId,+ name = "Action",+ type = ContentType.MOVIE,+ providerId = providerEntity.id+ )+ )+ )+ org.mockito.kotlin.whenever(xtreamIndexJobDao.get(providerEntity.id, ContentType.MOVIE.name)).thenReturn(+ XtreamIndexJobEntity(+ providerId = providerEntity.id,+ section = ContentType.MOVIE.name,+ state = "QUEUED",+ totalCategories = 1+ )+ )+ org.mockito.kotlin.whenever(movieDao.getByStreamIds(eq(providerEntity.id), any())).thenReturn(emptyList())+ org.mockito.kotlin.whenever(movieDao.getCount(providerEntity.id)).thenReturn(flowOf(0))+ org.mockito.kotlin.whenever(movieDao.getCountByCategory(providerEntity.id, categoryId)).thenReturn(flowOf(0))+ org.mockito.kotlin.whenever(+ stalkerApiService.getVodStreamsPage(any(), any(), eq("5"), eq(1))+ ).thenReturn(+ Result.success(+ StalkerPagedItems(+ items = listOf(+ StalkerItemRecord(+ id = "501",+ name = "Fetched before edit",+ categoryId = "5",+ cmd = "ffmpeg http://example.com/501.ts"+ )+ ),+ page = 1,+ totalPages = 1,+ pageSize = 1+ )+ )+ )+ val lease = ProviderWorkflowLease(+ providerId = providerEntity.id,+ generation = 9L,+ phase = ProviderWorkflowPhase.MOVIE_INDEX,+ token = "superseded-lease",+ expiresAt = Long.MAX_VALUE+ )++ val failure = runCatching {+ kotlinx.coroutines.withContext(ProviderWorkflowExecutionContext(lease)) {+ manager.processQueuedStalkerIndexJobs(+ providerId = providerEntity.id,+ section = ContentType.MOVIE,+ maxCategoriesPerSection = 1+ )+ }+ }.exceptionOrNull()++ assertThat(failure).isInstanceOf(ProviderWorkflowSupersededException::class.java)+ verify(stalkerApiService).getVodStreamsPage(any(), any(), eq("5"), eq(1))+ verify(movieDao, org.mockito.kotlin.never()).insertAll(any())+ val attemptedCheckpoint = argumentCaptor<MovieCategoryHydrationEntity>()+ verify(movieCategoryHydrationDao).upsert(attemptedCheckpoint.capture())+ assertThat(attemptedCheckpoint.firstValue.lastStatus).isEqualTo("RUNNING")+ assertThat(attemptedCheckpoint.firstValue.lastSuccessfulPage).isEqualTo(0)+ verify(xtreamContentIndexDao, org.mockito.kotlin.never())+ .upsertAll(any())+ }+@Testfun `processQueuedStalkerIndexJobs serializes movie and series sections for one connection provider`() = runTest {val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(@@ -2898,6 +3010,97 @@ class SyncManagerTest {assertThat(movieHydrationByCategory.getValue(movieCategoryId).isComplete).isTrue()}+ @Test+ fun `processQueuedStalkerIndexJobs does not publish coverage or prune when empty-page retry fails`() = runTest {+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(+ serverUrl = "http://example.com",+ username = "",+ password = "",+ stalkerMacAddress = "00:11:22:33:44:55",+ epgSyncMode = ProviderEpgSyncMode.SKIP,+ maxConnections = 1+ )+ val movieCategoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.MOVIE, "5")+ val manager = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = providerEntity)++ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(+ Result.success(+ StalkerSession(+ loadUrl = "http://example.com/stalker_portal/server/load.php",+ portalReferer = "http://example.com/stalker_portal/c/",+ token = "token"+ ) to StalkerProviderProfile(accountName = "Stalker")+ )+ )+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(+ Result.success(listOf(StalkerCategoryRecord(id = "5", name = "Action")))+ )+ org.mockito.kotlin.whenever(categoryDao.getByProviderAndTypeSync(1L, ContentType.MOVIE.name)).thenReturn(+ listOf(+ CategoryEntity(+ categoryId = movieCategoryId,+ name = "Action",+ type = ContentType.MOVIE,+ providerId = 1L+ )+ )+ )+ org.mockito.kotlin.whenever(xtreamIndexJobDao.get(1L, ContentType.MOVIE.name)).thenReturn(+ XtreamIndexJobEntity(+ providerId = 1L,+ section = ContentType.MOVIE.name,+ state = "QUEUED",+ totalCategories = 1+ )+ )+ val movieHydrationByCategory = mutableMapOf<Long, MovieCategoryHydrationEntity>()+ org.mockito.kotlin.whenever(movieCategoryHydrationDao.get(eq(1L), any())).thenAnswer { invocation ->+ movieHydrationByCategory[invocation.getArgument<Long>(1)]+ }+ org.mockito.kotlin.whenever(movieCategoryHydrationDao.upsert(any())).thenAnswer { invocation ->+ val entity = invocation.getArgument<MovieCategoryHydrationEntity>(0)+ movieHydrationByCategory[entity.categoryId] = entity+ Unit+ }+ org.mockito.kotlin.whenever(movieDao.getByStreamIds(eq(1L), any())).thenReturn(emptyList())+ org.mockito.kotlin.whenever(movieDao.getCount(1L)).thenReturn(flowOf(0), flowOf(0), flowOf(0))+ org.mockito.kotlin.whenever(movieDao.getCountByCategory(1L, movieCategoryId)).thenReturn(flowOf(0))+ org.mockito.kotlin.whenever(+ xtreamContentIndexDao.pruneStaleLocalContentRows(1L, ContentType.MOVIE.name)+ ).thenReturn(0)+ org.mockito.kotlin.whenever(+ stalkerApiService.getVodStreamsPage(any(), any(), eq("5"), eq(1))+ ).thenReturn(+ Result.success(+ StalkerPagedItems(+ items = emptyList(),+ page = 1,+ totalPages = 1,+ pageSize = 0,+ hasAdvertisedTotal = false+ )+ ),+ Result.error("temporary retry failure")+ )++ val result = manager.processQueuedStalkerIndexJobs(+ providerId = 1L,+ section = ContentType.MOVIE,+ maxCategoriesPerSection = 1+ )++ assertThat(result.isSuccess).isTrue()+ verify(stalkerApiService, org.mockito.kotlin.atLeast(2))+ .getVodStreamsPage(any(), any(), eq("5"), eq(1))+ verify(stalkerApiService, org.mockito.kotlin.never()).getVodStreams(any(), any(), eq("5"))+ verify(movieDao, org.mockito.kotlin.never()).insertAll(any())+ verify(xtreamContentIndexDao, org.mockito.kotlin.never())+ .pruneStaleLocalContentRows(1L, ContentType.MOVIE.name)+ val failedHydration = movieHydrationByCategory[movieCategoryId]+ assertThat(failedHydration?.lastSuccessfulPage ?: 0).isEqualTo(0)+ assertThat(failedHydration?.isComplete ?: false).isFalse()+ }+@Testfun `processQueuedStalkerIndexJobs uses wildcard movie indexing when wildcard category is the only visible category`() = runTest {val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(@@ -3072,6 +3275,8 @@ class SyncManagerTest {verify(stalkerApiService, org.mockito.kotlin.times(0)).streamEpg(any(), any(), any(), any(), any())verify(stalkerApiService, org.mockito.kotlin.times(0)).getVodStreams(any(), any(), anyOrNull())verify(stalkerApiService, org.mockito.kotlin.times(0)).getSeries(any(), any(), anyOrNull())+ verify(stalkerApiService, org.mockito.kotlin.never()).getVodStreamsPage(any(), any(), anyOrNull(), any())+ verify(stalkerApiService, org.mockito.kotlin.never()).getSeriesPage(any(), any(), anyOrNull(), any())}@Testdiff --git a/data/src/test/java/com/streamvault/data/sync/VodCategoryHydrationCoordinatorTest.kt b/data/src/test/java/com/streamvault/data/sync/VodCategoryHydrationCoordinatorTest.ktindex cde8fb07..b5eae34b 100644--- a/data/src/test/java/com/streamvault/data/sync/VodCategoryHydrationCoordinatorTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/VodCategoryHydrationCoordinatorTest.kt@@ -10,6 +10,7 @@ import com.streamvault.data.local.dao.SeriesDaoimport com.streamvault.data.local.dao.VodCategoryHydrationDaoimport com.streamvault.data.local.dao.VodCatalogEntryDaoimport com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.local.entity.VodCategoryHydrationEntityimport com.streamvault.data.remote.stalker.StalkerPagedResultimport com.streamvault.data.remote.stalker.StalkerProviderimport com.streamvault.data.remote.stalker.StalkerVodCatalogItem@@ -23,8 +24,10 @@ import com.streamvault.domain.model.VodCategoryHydrationRequestimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.test.runTestimport org.junit.Test+import org.mockito.kotlin.anyimport org.mockito.kotlin.eqimport org.mockito.kotlin.mock+import org.mockito.kotlin.timesimport org.mockito.kotlin.verifyimport org.mockito.kotlin.whenever@@ -142,6 +145,168 @@ class VodCategoryHydrationCoordinatorTest {)}+ @Test+ fun `failed next page resumes from last commit and repeated page does not advance coverage`() = runTest {+ val hydrationDao = mock<VodCategoryHydrationDao>()+ var savedHydration: VodCategoryHydrationEntity? = null+ whenever(hydrationDao.get(7L, 11L)).thenAnswer { savedHydration }+ whenever(hydrationDao.upsert(any())).thenAnswer { invocation ->+ savedHydration = invocation.getArgument(0)+ Unit+ }+ val movieDao = mock<MovieDao>()+ val catalogEntryDao = mock<VodCatalogEntryDao>()+ whenever(catalogEntryDao.countByCategory(7L, 11L)).thenReturn(1)+ val api = mock<StalkerProvider>()+ whenever(api.getUnifiedVodPage(11L, 1)).thenReturn(Result.success(moviePage(1L, "movie-1", 1, 3)))+ whenever(api.getUnifiedVodPage(11L, 2)).thenReturn(+ Result.error("temporary page failure"),+ Result.success(moviePage(2L, "movie-2", 2, 3))+ )+ whenever(api.getUnifiedVodPage(11L, 3)).thenReturn(Result.success(moviePage(2L, "movie-2", 3, 3)))+ val coordinator = coordinator(+ api = api,+ movieDao = movieDao,+ hydrationDao = hydrationDao,+ catalogEntryDao = catalogEntryDao+ ) { block -> block() }++ val opened = coordinator.hydrateUnifiedVodCategory(7L, 11L, VodCategoryHydrationRequest.OPEN)+ assertThat(opened.isSuccess).isTrue()+ assertThat(savedHydration?.lastSuccessfulPage).isEqualTo(1)++ val failedNextPage = coordinator.hydrateUnifiedVodCategory(+ 7L,+ 11L,+ VodCategoryHydrationRequest.NEXT_PAGE+ )+ assertThat(failedNextPage).isInstanceOf(Result.Error::class.java)+ assertThat(savedHydration?.lastSuccessfulPage).isEqualTo(1)+ assertThat(savedHydration?.lastAttemptedPage).isEqualTo(2)+ assertThat(savedHydration?.lastStatus).isEqualTo("FAILED_RETRYABLE")++ val retriedNextPage = coordinator.hydrateUnifiedVodCategory(+ 7L,+ 11L,+ VodCategoryHydrationRequest.NEXT_PAGE+ )+ assertThat(retriedNextPage.isSuccess).isTrue()+ assertThat(savedHydration?.lastSuccessfulPage).isEqualTo(2)++ val repeatedPage = coordinator.hydrateUnifiedVodCategory(+ 7L,+ 11L,+ VodCategoryHydrationRequest.NEXT_PAGE+ )+ assertThat(repeatedPage).isInstanceOf(Result.Error::class.java)+ assertThat(savedHydration?.lastSuccessfulPage).isEqualTo(2)+ assertThat(savedHydration?.lastStatus).isEqualTo("ANOMALY")+ assertThat(savedHydration?.lastError).contains("repeated")+ verify(api, times(2)).getUnifiedVodPage(11L, 2)+ verify(api).getUnifiedVodPage(11L, 3)+ verify(movieDao, times(2)).upsertCategoryPage(eq(7L), any())+ verify(catalogEntryDao, times(2)).replacePage(eq(7L), eq(11L), any(), any())+ }++ @Test+ fun `complete request fetches pages sequentially through the advertised terminal page`() = runTest {+ val hydrationDao = mock<VodCategoryHydrationDao>()+ var savedHydration: VodCategoryHydrationEntity? = null+ whenever(hydrationDao.get(7L, 11L)).thenAnswer { savedHydration }+ whenever(hydrationDao.upsert(any())).thenAnswer { invocation ->+ savedHydration = invocation.getArgument(0)+ Unit+ }+ val requestedPages = mutableListOf<Int>()+ val api = mock<StalkerProvider>()+ whenever(api.getUnifiedVodPage(eq(11L), any())).thenAnswer { invocation ->+ val page = invocation.getArgument<Int>(1)+ requestedPages += page+ val response: StalkerPagedResult<StalkerVodCatalogItem> = if (page == 1) {+ moviePage(1L, "movie-1", 1, 2)+ } else {+ StalkerPagedResult(+ items = emptyList(),+ page = page,+ totalPages = 2,+ pageSize = 1,+ advertisedTotalPages = 2+ )+ }+ Result.success(response)+ }+ val coordinator = coordinator(api, hydrationDao = hydrationDao) { block -> block() }++ val result = coordinator.hydrateUnifiedVodCategory(7L, 11L, VodCategoryHydrationRequest.COMPLETE)++ assertThat(result.isSuccess).isTrue()+ assertThat(requestedPages).containsExactly(1, 2).inOrder()+ assertThat(savedHydration?.lastSuccessfulPage).isEqualTo(2)+ assertThat(savedHydration?.isComplete).isTrue()+ }++ @Test+ fun `changing advertised page total does not replace the last successful receipt`() = runTest {+ val hydrationDao = mock<VodCategoryHydrationDao>()+ var savedHydration: VodCategoryHydrationEntity? = null+ whenever(hydrationDao.get(7L, 11L)).thenAnswer { savedHydration }+ whenever(hydrationDao.upsert(any())).thenAnswer { invocation ->+ savedHydration = invocation.getArgument(0)+ Unit+ }+ val api = mock<StalkerProvider>()+ whenever(api.getUnifiedVodPage(11L, 1)).thenReturn(Result.success(moviePage(1L, "movie-1", 1, 3)))+ whenever(api.getUnifiedVodPage(11L, 2)).thenReturn(Result.success(moviePage(2L, "movie-2", 2, 4)))+ val movieDao = mock<MovieDao>()+ val coordinator = coordinator(api, movieDao = movieDao, hydrationDao = hydrationDao) { block -> block() }++ assertThat(coordinator.hydrateUnifiedVodCategory(7L, 11L, VodCategoryHydrationRequest.OPEN).isSuccess).isTrue()+ val changedTotal = coordinator.hydrateUnifiedVodCategory(+ 7L,+ 11L,+ VodCategoryHydrationRequest.NEXT_PAGE+ )++ assertThat(changedTotal).isInstanceOf(Result.Error::class.java)+ assertThat(savedHydration?.lastSuccessfulPage).isEqualTo(1)+ assertThat(savedHydration?.lastStatus).isEqualTo("ANOMALY")+ verify(movieDao).upsertCategoryPage(eq(7L), any())+ }++ @Test+ fun `complete request marks the page batch limit as truncated coverage`() = runTest {+ val hydrationDao = mock<VodCategoryHydrationDao>()+ var savedHydration: VodCategoryHydrationEntity? = null+ whenever(hydrationDao.get(7L, 11L)).thenAnswer { savedHydration }+ whenever(hydrationDao.upsert(any())).thenAnswer { invocation ->+ savedHydration = invocation.getArgument(0)+ Unit+ }+ val api = mock<StalkerProvider>()+ whenever(api.getUnifiedVodPage(eq(11L), any())).thenAnswer { invocation ->+ val page = invocation.getArgument<Int>(1)+ Result.success(+ StalkerPagedResult<StalkerVodCatalogItem>(+ items = emptyList(),+ page = page,+ totalPages = 201,+ pageSize = 100,+ advertisedTotalPages = 201+ )+ )+ }+ val coordinator = coordinator(api, hydrationDao = hydrationDao) { block -> block() }++ val result = coordinator.hydrateUnifiedVodCategory(7L, 11L, VodCategoryHydrationRequest.COMPLETE)++ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat(savedHydration?.lastSuccessfulPage).isEqualTo(200)+ assertThat(savedHydration?.isComplete).isFalse()+ assertThat(savedHydration?.lastStatus).isEqualTo("TRUNCATED")+ assertThat(savedHydration?.lastError).isEqualTo("page_limit")+ verify(api, times(200)).getUnifiedVodPage(eq(11L), any())+ }+private suspend fun successfulEmptyPageApi(): StalkerProvider = mock<StalkerProvider>().also { api ->whenever(api.getUnifiedVodPage(11L, 1)).thenReturn(Result.success(@@ -155,10 +320,35 @@ class VodCategoryHydrationCoordinatorTest {)}+ private fun moviePage(+ movieId: Long,+ rawItemId: String,+ page: Int,+ totalPages: Int,+ isTruncated: Boolean = false+ ) = StalkerPagedResult(+ items = listOf(+ StalkerVodCatalogItem(+ rawItemId = rawItemId,+ item = VodCatalogItem.MovieItem(+ Movie(id = movieId, streamId = movieId, name = "Movie $movieId")+ )+ )+ ),+ page = page,+ totalPages = totalPages,+ pageSize = 1,+ advertisedTotalPages = totalPages,+ isTruncated = isTruncated+ )++private suspend fun coordinator(api: StalkerProvider,categoryDao: CategoryDao? = null,movieDao: MovieDao = mock(),+ hydrationDao: VodCategoryHydrationDao = mock(),+ catalogEntryDao: VodCatalogEntryDao? = null,transaction: suspend (suspend () -> Unit) -> Unit): VodCategoryHydrationCoordinator {val resolvedCategoryDao = categoryDao ?: mock<CategoryDao>().also {@@ -170,17 +360,18 @@ class VodCategoryHydrationCoordinatorTest {type = ProviderType.STALKER_PORTAL,serverUrl = "http://portal.test")+ val resolvedCatalogEntryDao = catalogEntryDao ?: mock<VodCatalogEntryDao>().also {+ whenever(it.countByCategory(7L, 11L)).thenReturn(0)+ }return VodCategoryHydrationCoordinator(providerSyncLocks = ProviderSyncLockRegistry(),categoryDao = resolvedCategoryDao,movieCategoryHydrationDao = mock<MovieCategoryHydrationDao>(),seriesCategoryHydrationDao = mock<SeriesCategoryHydrationDao>(),- vodCategoryHydrationDao = mock<VodCategoryHydrationDao>(),+ vodCategoryHydrationDao = hydrationDao,movieDao = movieDao,seriesDao = mock<SeriesDao>(),- vodCatalogEntryDao = mock<VodCatalogEntryDao>().also {- whenever(it.countByCategory(7L, 11L)).thenReturn(0)- },+ vodCatalogEntryDao = resolvedCatalogEntryDao,transactionRunner = object : DatabaseTransactionRunner {override suspend fun <T> inTransaction(block: suspend () -> T): T {var result: T? = nulldiff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex eed92e2f..6d25aa00 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -8,6 +8,7 @@ All notable product changes are recorded in this document.- Added temporary automatic quality reduction for supported adaptive streams when decoding struggles, with gradual restoration and respect for manual quality choices.- Added AVC/H.264 fallback for eligible HEVC episodes, preserving playback position, audio, subtitles, and episode history.+- Added durable retries for failed Stalker live categories, scoped to the current provider configuration and visible categories, with retry promotion and cleanup committed atomically (Room migration v80 to v81).### Fixed@@ -23,6 +24,7 @@ All notable product changes are recorded in this document.- Fixed Xtream playlist setup ignoring the requested HLS or MPEG-TS format when playback format is set to Auto.- Fixed matching AVC/H.264 and HEVC/H.265 movie versions failing to group together.- Fixed newly imported movie summaries skipping detail loading.+- Fixed Stalker add-provider security and verification dialogs stretching to near full screen; they now size to their content and use a narrower width on compact screens.- Fixed Xtream series losing some or all of their episodes after another series was opened (#166). Episode ids are now unique per series instead of per provider, and series cached before the fix are re-fetched the next time they are opened.- Fixed M3U channels sharing a `tvg-id` but using different stream URLs or Acestream hashes from being incorrectly treated as the same channel (#231).- Fixed background movie refresh crashes when saved provider credentials cannot be decrypted.@@ -33,6 +35,8 @@ All notable product changes are recorded in this document.- Reduced duplicate category requests and per-row identity database work during Stalker provider setup, preserving portal verification and stable catalog IDs.- Added direct Stalker live-row decoding and bounded ingestion with isolated authorization retries; incomplete responses cannot promote a full catalog, and bootstrap prefixes do not certify bulk catalog fidelity.- Overlapped Stalker live-category and bulk requests when provider admission allows it; category fallback now streams isolated attempts, preserves failed scopes, stops bootstrap after its accepted prefix, and leaves incomplete live coverage eligible for durable refresh.+- Improved Stalker VOD recovery and hydration: an empty first page retries through the paged API without accumulating a whole category, page provenance and durable continuation remain accurate, and category protection is read in the page commit transaction.+- Fenced Stalker index row, checkpoint, metadata, and prune writes by the active provider-workflow lease; preserved mixed movie/native-series/VOD-derived-series classification and page ordering.- Reworked Xtream Live sync with streamed decoding and bounded staging, and made bulk-first `AUTO` the normal-build default with category fallback for safety conditions and bulk failures.- Applied the Xtream live strategy to Add Provider and Settings refresh, including hidden-category routing and clearer sync progress.diff --git a/docs/STALKER_VOD_IMPROVEMENT_PLAN.md b/docs/STALKER_VOD_IMPROVEMENT_PLAN.mdindex fa9ff084..425eaa11 100644--- a/docs/STALKER_VOD_IMPROVEMENT_PLAN.md+++ b/docs/STALKER_VOD_IMPROVEMENT_PLAN.md@@ -1,7 +1,8 @@# Stalker VOD ingestion improvement planStatus: V1 and V2 are implemented; focused unit, Room, and app-build validation-passed. Real-provider browsing and playback remain unverified.+passed, including page-limit and resume coverage. Real-provider browsing and+playback remain unverified.Prepared: 2026-10-10 against the current working tree.Related: [Stalker live improvements](STALKER_SYNC_IMPROVEMENT_PLAN.md).Implementation evidence: [V1/V2 implementation notes](STALKER_VOD_V1_V2_IMPLEMENTATION.md).@@ -119,14 +120,13 @@ weakening ordering, scheduling, or retry behavior.- [x] Document category/duplicate precedence and page transaction ownership first.- [x] Decide whether to retain windows or use admitted fetches feeding a singlewriter through a bounded queue. Record the decision and reason in this document.-- [ ] If adopted, keep pages sequential within each category, preserve category- precedence independently of completion order, and bound any reorder buffer.-- [ ] Include producer, queue, writer, mapped rows, and active request responses- in retained-memory accounting; bound row/byte payloads explicitly.-- [ ] Release network permits before waiting on writer backpressure. Verify the- single-permit case, stress downgrade, cancellation, and authentication retry.-- [ ] Advance each checkpoint only after its page commit. Respect slice deadlines,- interactive priority, cooldowns, and durable continuation without losing pages.+- [x] Not applicable: a fetch/write pipeline was not adopted; the existing bounded+ windows and deterministic category order were retained.+- [x] Not applicable: no producer queue or reorder buffer was introduced.+- [x] Not applicable: network-permit/backpressure behavior was unchanged.+- [x] Summary row batches and checkpoint/job/prune writes now assert workflow+ ownership inside their Room transactions; checkpoints still advance only after+ durable row commits. Bounded windows retain their existing scheduling behavior.Acceptance: failure in one category cannot corrupt another; cancellation joinsall work; committed pages resume correctly; queue pressure cannot block a portal@@ -143,11 +143,9 @@ but the live reader is not a drop-in replacement for movie and series metadata.- [x] Audit all retained fields consumed by movie, native-series, and classifiedVOD mappers, including playback descriptors and mixed item classification.- [x] Decide whether direct decoding is warranted after V1-V3; record the decision.-- [ ] If adopted, preserve pagination metadata, wrappers/keyed shapes, aliases,- coercion, duplicate keys, portal errors, malformed/truncated-document semantics,- and cancellation. Keep generic detail/episode/guide decoding outside this scope.-- [ ] Retain an internal legacy comparison path until differential fixtures pass;- do not add a user-facing decoder switch.+- [x] Not applicable: direct VOD decoding was deferred; the generic decoder remains+ in use and its parsing behavior was not changed.+- [x] Not applicable: no differential decoder path or user-facing switch was added.Acceptance: equivalent item fields, classification, ordering, and paginationevidence. A malformed response must never become complete coverage.@@ -169,21 +167,44 @@ Do not use elapsed-time performance assertions.- [x] V2 targeted protection lookup and transaction placement verified.- [x] V3 decision documented; bounded windows retained, no pipeline adopted.- [x] V4 decision documented; direct decoder deferred.-- [ ] Split and unified VOD, mixed movie/series, native and derived series verified.-- [ ] Empty/repeated/changing-total/truncated pages and page limits verified.-- [ ] Retry after committed pages resumes correctly; failed attempts do not advance- checkpoints or delete verified rows.+- [x] Split and unified VOD, mixed movie/series, native and derived series verified.+- [x] Empty, repeated, changing-total, truncated-page, and page-limit behavior+ verified in focused provider and coordinator tests.+- [x] Retry after committed pages resumes from the next durable page; failed page+ attempts do not advance the successful checkpoint or write rows.+- [x] Failed empty-first-page recovery leaves successful coverage unchanged and+ skips stale-row pruning.- [x] Room verifies page ordering, stable identity, favorites, protection, watchprogress, and successful-page coverage checkpoints.-- [ ] Room rollback, search updates, and coverage-safe pruning verified.-- [ ] Add Provider deferral, interactive OPEN/NEXT_PAGE/COMPLETE, background- continuation, edit/supersession, cancellation, restart, and deletion verified.+- [x] Room rollback preserves the last committed rows and coverage receipt.+- [x] Room search indexes reflect page updates, and stale-row pruning runs only+ after complete coverage, not after a failed empty-page retry.+- [x] Interactive OPEN/NEXT_PAGE/COMPLETE, cancellation boundaries, and durable+ retry after a failed page verified.+- [x] Add Provider setup creates VOD/Series category shells without requesting+ VOD or Series item pages.+- [x] Background index continuation resumes from persisted category checkpoints;+ a focused test resumes a fresh RUNNING job at its next stored page. Interactive+ next-page retry after failure is covered separately above.+- [x] A Stalker page-fetch test invalidates the workflow lease after the response+ arrives and verifies that neither rows nor its successful-page checkpoint commit.+ The ownership check shares each Room write transaction with its mutation.+- [x] Room reopen verifies durable VOD page and index continuation state, and+ provider deletion cascades through VOD hydration, catalog entries, movies, and+ the Stalker index job.+- [ ] One scenario combining an actual provider edit, active page work,+ supersession, and process restart is not covered; real-provider validation+ remains separate below.- [x] Focused unit/instrumentation checks and app build pass.- [ ] Real-provider VOD browsing, continuation, and representative movie/seriesplayback verified where changed; unavailable access recorded as a validation gap.-- [ ] If shared live playback behavior is touched, required sustained multi-channel- validation from `AGENTS.md` completed; build/synthetic tests do not substitute.+- [x] Shared live playback behavior was not touched; sustained multi-channel+ validation from `AGENTS.md` is not applicable to this VOD work.- [x] Implementation notes list completed stages, evidence, and remaining gaps.-Implement V1, then V2. Resolve V3/V4 decisions before expanding scope. Update-checkboxes as work lands; preserve unrelated dirty changes and existing live work.+V1 and V2 implementation is complete. V3/V4 were evaluated and deferred as+conditional expansions. Focused tests cover the durable continuation pieces and+the shared workflow supersession fence, but do not combine a background run,+provider edit, and process restart in one scenario. Real-provider VOD browsing,+continuation, and playback remain unverified. Preserve unrelated dirty changes+and existing live work.diff --git a/docs/STALKER_VOD_V1_V2_IMPLEMENTATION.md b/docs/STALKER_VOD_V1_V2_IMPLEMENTATION.mdindex 538a4841..353f9934 100644--- a/docs/STALKER_VOD_V1_V2_IMPLEMENTATION.md+++ b/docs/STALKER_VOD_V1_V2_IMPLEMENTATION.md@@ -49,6 +49,21 @@ durable progress and concurrent workers. Summary rows commit before theirsuccessful-page checkpoint is advanced; a crash in between replays an idempotentpage rather than skipping uncommitted data.+The interactive coordinator now compares each response fingerprint with both+pages seen during the current COMPLETE request and the last committed page+fingerprint. This catches a portal repeating the last page across separate+NEXT_PAGE calls without replacing the durable successful-page checkpoint. Native+Series-page fallback to VOD is explicitly marked `VOD_DERIVED` in both paged and+legacy list APIs; focused tests cover split mixed-order mapping, unified mixed+mapping, and the fallback classification.++Stalker background index mutations now assert the active provider-workflow lease+inside their Room transactions. This covers summary row/index writes, hydration+attempt and success/failure checkpoints, job state, summary metadata, watch-progress+restoration, and stale-row pruning. A focused test lets a page fetch finish, marks+the lease superseded before its row transaction, and verifies that rows and the+successful-page checkpoint remain unchanged.+## V3/V4 decisionsV3 keeps the existing bounded fetch windows. `awaitAll` preserves the requested@@ -70,18 +85,42 @@ the separate decoder work is not required for this change.It covers empty-first-page retry call counts, actual page provenance, nowhole-list fallback call, and targeted protection lookup inside the committransaction.+- The focused tests also cover resume after a failed NEXT_PAGE, a repeated page+ across calls, a changed advertised page total, successful sequential COMPLETE,+ and the 200-page COMPLETE limit remaining `TRUNCATED` and incomplete. A failed+ empty-first-page retry also leaves the successful checkpoint unchanged, avoids+ movie row writes, and does not run stale-row pruning.- Room instrumentation run passed:`:data:connectedDebugAndroidTest` with`-Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.data.local.StalkerVodHydrationIntegrationTest`- passed on the `Television_4K_2(AVD) - 16` emulator. It covers mixed- movie/series page order, category protection, stable movie IDs, favorites,- watch progress, and the completed-page checkpoint.+ passed on the `Television_4K_2(AVD) - 16` emulator against the current database+ schema. It covers mixed movie/series page order, category protection, stable+ movie IDs, favorites, watch progress, updated movie FTS results, the+ completed-page checkpoint, and transaction rollback after a simulated failure.+- A Room lifecycle instrumentation case now closes and reopens the database,+ verifies the committed VOD page checkpoint and partial Stalker index job are+ still available for continuation, then deletes the provider and verifies Room+ cascades clear its hydration, catalog entries, movie rows, and index job.+- Focused SyncManager tests cover resuming a fresh RUNNING Stalker job from its+ next persisted page. Shared provider workflow integration tests cover lease+ supersession. A Stalker page test also checks lease validity at the page commit+ boundary after the response has been fetched. There is not yet one combined+ scenario spanning an actual configuration edit, active background write, and+ process restart.+- The supersession case passed with:+ `:data:testDebugUnitTest --tests '*SyncManagerTest.superseded Stalker movie index cannot commit fetched page rows or checkpoint'`.+ The full `*SyncManagerTest` class also passed after adding transaction fences.+- A focused initial-sync test verifies Add Provider stores the VOD and Series+ category shells but does not request VOD or Series item pages. Indexing remains+ deferred.- App debug build and `git diff --check` passed. The diff check emitted onlyexisting working-tree LF/CRLF normalization warnings.- Real-provider VOD browsing and representative playback: not available in thisworkspace; record as a validation gap.-- Split/unified end-to-end behavior, retry failure after earlier committed pages,- rollback, search updates, safe pruning, cancellation/restart, and provider edit- or deletion behavior were not covered by these focused checks.+- Background continuation, persisted restart state, stale-lease write fencing,+ and provider deletion now have focused component/instrumentation coverage. A+ combined provider-edit/supersession/restart scenario and real-provider behavior+ remain unverified end to end. Unit checks verify pruning occurs after full+ coverage and is skipped after failed first-page recovery.- No live playback path was changed. No before/after measurements or performancebenchmark suite was run.diff --git a/feature/provider/src/main/java/com/streamvault/feature/provider/setup/ProviderSetupScreen.kt b/feature/provider/src/main/java/com/streamvault/feature/provider/setup/ProviderSetupScreen.ktindex be056267..d4966800 100644--- a/feature/provider/src/main/java/com/streamvault/feature/provider/setup/ProviderSetupScreen.kt+++ b/feature/provider/src/main/java/com/streamvault/feature/provider/setup/ProviderSetupScreen.kt@@ -628,6 +628,8 @@ uiState.stalkerTransportChallenge?.let { challenge ->title = title,subtitle = body,onDismissRequest = viewModel::dismissStalkerTransportChallenge,+ smallScreenWidthFraction = 0.84f,+ heightFraction = null,content = {},footer = {PremiumDialogFooterButton(@@ -648,6 +650,8 @@ uiState.stalkerTransportChallenge?.let { challenge ->title = stringResource(R.string.stalker_verification_inconclusive_title),subtitle = stringResource(R.string.stalker_verification_inconclusive_body),onDismissRequest = viewModel::dismissStalkerVerificationInconclusive,+ smallScreenWidthFraction = 0.84f,+ heightFraction = null,content = {},footer = {PremiumDialogFooterButton(