StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
Implement Xtream sync improvements
David Nashash22101f5b6e8c
diff --git a/app/src/androidTest/java/com/streamvault/app/benchmark/XtreamLiveSyncBenchmarkTest.kt b/app/src/androidTest/java/com/streamvault/app/benchmark/XtreamLiveSyncBenchmarkTest.ktindex 6d1de3e9..222a3b9c 100644--- a/app/src/androidTest/java/com/streamvault/app/benchmark/XtreamLiveSyncBenchmarkTest.kt+++ b/app/src/androidTest/java/com/streamvault/app/benchmark/XtreamLiveSyncBenchmarkTest.kt@@ -6,25 +6,47 @@ import android.os.Buildimport android.os.Debugimport android.os.SystemClockimport android.util.Log+import androidx.test.core.app.ActivityScenarioimport androidx.test.core.app.ApplicationProviderimport androidx.test.ext.junit.runners.AndroidJUnit4import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.WorkInfo+import androidx.work.WorkManager+import com.streamvault.app.MainActivity+import com.streamvault.data.local.dao.CategoryDao+import com.streamvault.data.local.dao.ChannelDao+import com.streamvault.data.remote.xtream.XtreamStreamKind+import com.streamvault.data.remote.xtream.XtreamUrlFactory+import com.streamvault.data.sync.ProviderSyncWorkerimport com.streamvault.data.sync.SyncRepairSection+import com.streamvault.data.local.entity.PlaybackHistoryEntity+import com.streamvault.domain.model.AppLandingDestination+import com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.ProviderXtreamLiveSyncModeimport com.streamvault.domain.model.Result+import com.streamvault.domain.model.SyncMetadataimport com.streamvault.domain.usecase.ValidateAndAddProviderResultimport com.streamvault.domain.usecase.XtreamProviderSetupCommand+import com.streamvault.domain.util.ChannelNormalizerimport com.streamvault.domain.util.ProviderInputSanitizerimport dagger.hilt.android.EntryPointAccessorsimport java.net.URI+import java.util.concurrent.TimeUnitimport java.util.UUIDimport java.util.concurrent.atomic.AtomicLongimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.NonCancellableimport kotlinx.coroutines.async+import kotlinx.coroutines.cancelAndJoinimport kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.currentCoroutineContextimport kotlinx.coroutines.delay+import kotlinx.coroutines.ensureActiveimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.runBlockingimport kotlinx.coroutines.withContext@@ -65,23 +87,62 @@ class XtreamLiveSyncBenchmarkTest {}check(fixture.getString("fixture") == "streamvault-xtream-sync-performance-v1")val expected = fixture.getInt("expected_channels")+ val fixtureScenario = fixture.getJSONObject("scenario")+ val fixtureSourceChannelCount = fixtureScenario.getInt("channels")+ val fixtureCategoryCount = fixtureScenario.getInt("categories")+ val fixtureSeed = fixtureScenario.getInt("seed")+ val fixtureMalformedEvery = fixtureScenario.optInt("malformed_every", 0)+ val expectedMovies = fixture.optInt("expected_movies", 0)+ val expectedSeries = fixture.optInt("expected_series", 0)val modes = (args.getString("syncModes") ?: "AUTO,STREAM_ALL,CATEGORY_BY_CATEGORY").split(',').map { ProviderXtreamLiveSyncMode.valueOf(it) }val iterations = (args.getString("iterations") ?: "5").toInt().also { require(it in 1..20) }val warmups = (args.getString("warmups") ?: "1").toInt().also { require(it in 0..3) }val measureRefresh = args.getString("measureRefresh") == "true"+ val measureSummaryRefresh = args.getString("measureSummaryRefresh") == "true"+ val measureFirstBrowsableScreen = args.getString("measureFirstBrowsableScreen") == "true"+ val measureBackgroundWorker = args.getString("measureBackgroundWorker") == "true"+ val verifyChannelFields = args.getString("verifyChannelFields") == "true"+ val settleSeconds = (args.getString("settleSeconds") ?: "0").toInt().also { require(it in 0..120) }+ val runtimeTier = args.getString("runtimeTier") ?: "DEVICE"+ val stageBatchSize = args.getString("stageBatchSize")?.toIntOrNull()+ val experimentalAutoBulk = args.getString("experimentalAutoBulk") == "true"+ val hiddenCategoryPercent = (args.getString("hiddenCategoryPercent") ?: "0").toInt()+ val rememberSequentialStress = args.getString("rememberSequentialStress") == "true"+ val avoidFullCooldownSeconds = (args.getString("avoidFullCooldownSeconds") ?: "0").toInt()+ require(runtimeTier in setOf("DEVICE", "LOW", "MID", "HIGH"))+ require(stageBatchSize == null || stageBatchSize in setOf(100, 128, 256, 300, 500, 512, 1024))+ require(hiddenCategoryPercent in 0..100 && avoidFullCooldownSeconds in 0..86_400)+ val profileOverrides = app.getSharedPreferences("xtream_sync_benchmark_profile", 0)+ profileOverrides.edit().clear().commit()val graph = EntryPointAccessors.fromApplication(app, XtreamSyncBenchmarkEntryPoint::class.java)args.getString("cleanupRun")?.let { run ->require(run.matches(Regex("bench_[a-zA-Z0-9_]{1,100}")))val interrupted = graph.providers().getProviders().first().single { it.username == run }check(interrupted.serverUrl.trimEnd('/') == endpoint.trimEnd('/') &&interrupted.name == benchmarkName(run))+ graph.preferences().setHiddenCategoryIds(interrupted.id, ContentType.LIVE, emptySet())check(graph.providers().deleteProvider(interrupted.id) is Result.Success)check(graph.providers().getProvider(interrupted.id) == null)}check(graph.database().providerDao().getAllSync().isEmpty()) {"Benchmark storage must contain no providers; resolve an interrupted benchmark first"}+ val previousLandingDestination = if (measureFirstBrowsableScreen) {+ graph.preferences().appLandingDestination.first().also {+ graph.preferences().setAppLandingDestination(AppLandingDestination.LIVE_TV)+ }+ } else null+ val previousShowFavoritesCategory = if (measureFirstBrowsableScreen) {+ graph.preferences().showFavoritesCategory.first().also {+ graph.preferences().setShowFavoritesCategory(false)+ }+ } else null+ val previousShowRecentChannelsCategory = if (measureFirstBrowsableScreen) {+ graph.preferences().showRecentChannelsCategory.first().also {+ graph.preferences().setShowRecentChannelsCategory(false)+ }+ } else nullval manager = app.getSystemService(ActivityManager::class.java)Log.i(TAG, JSONObject().put("event", "environment").put("package", app.packageName)@@ -89,15 +150,61 @@ class XtreamLiveSyncBenchmarkTest {.put("memory_class_mb", manager.memoryClass).put("low_ram", manager.isLowRamDevice).put("max_heap_bytes", Runtime.getRuntime().maxMemory()).put("payload_sha256", fixture.getString("payload_sha256"))- .put("expected_channels", expected).toString())- for (mode in modes) {- repeat(iterations + warmups) { iteration ->+ .put("expected_channels", expected)+ .put("measure_first_browsable_screen", measureFirstBrowsableScreen)+ .put("measure_background_worker", measureBackgroundWorker)+ .put("verify_channel_fields", verifyChannelFields)+ .put("measure_summary_refresh", measureSummaryRefresh)+ .put("hide_empty_virtual_categories_for_browse", measureFirstBrowsableScreen)+ .put("runtime_tier_override", runtimeTier)+ .put("stage_batch_size_override", stageBatchSize ?: JSONObject.NULL)+ .put("experimental_auto_bulk", experimentalAutoBulk)+ .put("hidden_category_percent", hiddenCategoryPercent)+ .put("remember_sequential_stress", rememberSequentialStress)+ .put("avoid_full_cooldown_seconds", avoidFullCooldownSeconds).toString())+ try {+ for (mode in modes) {+ repeat(iterations + warmups) { iteration ->+ profileOverrides.edit().clear().also { editor ->+ if (runtimeTier != "DEVICE") editor.putString("tier", runtimeTier)+ if (stageBatchSize != null) editor.putInt("batch_size", stageBatchSize)+ editor.putBoolean("experimental_auto_bulk", experimentalAutoBulk)+ }.commit()val run = "bench_" + mode.name + "_" + UUID.randomUUID().toString().replace("-", "")val name = benchmarkName(run)val progress = mutableListOf<JSONObject>()- val start = SystemClock.elapsedRealtimeNanos()+ var start = 0L+ var firstBrowsableScreenElapsedMs: Double? = null+ var firstBrowsableScreenWaiter: kotlinx.coroutines.Deferred<Long>? = null+ var activityScenario: ActivityScenario<MainActivity>? = nullvar providerId: Long? = nulltry {+ if (measureFirstBrowsableScreen) {+ activityScenario = ActivityScenario.launch(MainActivity::class.java)+ val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())+ val welcomeReady = device.wait(+ Until.hasObject(By.text(app.getString(com.streamvault.feature.system.R.string.welcome_setup_provider))),+ 120_000L+ )+ check(welcomeReady) { "Synthetic first-screen run did not reach the empty-provider Welcome screen" }+ }+ start = SystemClock.elapsedRealtimeNanos()+ if (measureFirstBrowsableScreen) {+ val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())+ firstBrowsableScreenWaiter = async(Dispatchers.IO) {+ val selector = By.descContains(FIRST_LIVE_CHANNEL_NAME)+ val deadline = SystemClock.elapsedRealtime() + 600_000L+ while (SystemClock.elapsedRealtime() < deadline) {+ currentCoroutineContext().ensureActive()+ if (device.wait(Until.hasObject(selector), 100L)) break+ delay(25L)+ }+ check(device.hasObject(selector)) {+ "First synthetic live channel row did not become accessible"+ }+ SystemClock.elapsedRealtimeNanos()+ }+ }val sample = sampleHeap {withTimeout(600_000L) {graph.setup().loginXtream(@@ -109,8 +216,9 @@ class XtreamLiveSyncBenchmarkTest {onProgress = { label ->// Retain milestones, not every category label.val phase = when (label) {- "Downloading Live TV..." -> "live-start"+ "Loading Live TV channels..." -> "live-start""Saving Live TV channels..." -> "commit-start"+ "Live TV ready." -> "live-committed""Loading Movies categories..." -> "live-committed"else -> null}@@ -132,15 +240,223 @@ class XtreamLiveSyncBenchmarkTest {providerId = provider.idval count = graph.database().channelDao().getCount(provider.id).first()check(count == expected) { "Incomplete catalog: " + count + "/" + expected }+ var fixtureRowsChecked: Int? = null+ var fixtureCategoriesChecked: Int? = null+ var fixtureRowFieldVerificationMs: Double? = null+ if (verifyChannelFields) {+ val verificationStarted = SystemClock.elapsedRealtimeNanos()+ val verification = verifyFixtureChannelRows(+ channelDao = graph.database().channelDao(),+ categoryDao = graph.database().categoryDao(),+ providerId = provider.id,+ sourceChannelCount = fixtureSourceChannelCount,+ categoryCount = fixtureCategoryCount,+ seed = fixtureSeed,+ malformedEvery = fixtureMalformedEvery,+ expectedRows = expected+ )+ fixtureRowsChecked = verification.channelRows+ fixtureCategoriesChecked = verification.categories+ fixtureRowFieldVerificationMs =+ (SystemClock.elapsedRealtimeNanos() - verificationStarted) / 1_000_000.0+ }+ firstBrowsableScreenWaiter?.await()?.let { visibleAtNanos ->+ firstBrowsableScreenElapsedMs = (visibleAtNanos - start) / 1_000_000.0+ }+ var movieCount = 0+ var seriesCount = 0+ var movieIndexElapsedMs: Double? = null+ var movieAfterLiveElapsedMs: Double? = null+ var seriesIndexElapsedMs: Double? = null+ var seriesAfterLiveElapsedMs: Double? = null+ var movieIndexState = "NOT_REQUESTED"+ var seriesIndexState = "NOT_REQUESTED"+ var summaryPeakHeapBytes: Long? = null+ var summaryGcCountDelta: Long? = null+ var unchangedMovieRefreshElapsedMs: Double? = null+ var unchangedSeriesRefreshElapsedMs: Double? = null+ var unchangedVodRefreshElapsedMs: Double? = null+ var unchangedSummaryPeakHeapBytes: Long? = null+ var unchangedSummaryGcCountDelta: Long? = null+ val expectedIndexCounts = listOf(+ ContentType.MOVIE to expectedMovies,+ ContentType.SERIES to expectedSeries+ ).filter { (_, expectedCount) -> expectedCount > 0 }+ if (expectedIndexCounts.isNotEmpty()) {+ val indexSample = sampleHeap {+ withTimeout(600_000L) {+ graph.database().xtreamIndexJobDao().observeForProvider(provider.id).first { jobs ->+ expectedIndexCounts.all { (section, _) ->+ jobs.any { job ->+ job.section == section.name &&+ (job.state == "SUCCESS" || job.state.startsWith("FAILED"))+ }+ }+ }+ }+ }+ val terminalJobs = indexSample.value+ summaryPeakHeapBytes = indexSample.peakHeapBytes+ summaryGcCountDelta = indexSample.gcCountDelta+ val liveCommittedMs = progress.firstOrNull {+ it.optString("phase") == "live-committed"+ }?.optDouble("elapsed_ms", 0.0) ?: 0.0+ val movieJob = terminalJobs.firstOrNull { it.section == ContentType.MOVIE.name }+ if (expectedMovies > 0) {+ movieIndexState = movieJob?.state ?: "MISSING"+ check(movieIndexState == "SUCCESS") { "Movie summary index ended in $movieIndexState" }+ movieCount = graph.database().movieDao().countByProvider(provider.id)+ check(movieCount == expectedMovies) { "Incomplete movie catalog: $movieCount/$expectedMovies" }+ val movieIndexRows = graph.database().xtreamContentIndexDao()+ .countActiveRows(provider.id, ContentType.MOVIE.name)+ check(movieIndexRows == expectedMovies) { "Incomplete movie index: $movieIndexRows/$expectedMovies" }+ movieIndexElapsedMs = (SystemClock.elapsedRealtimeNanos() - start) / 1_000_000.0+ movieAfterLiveElapsedMs = (movieIndexElapsedMs - liveCommittedMs).coerceAtLeast(0.0)+ }+ val seriesJob = terminalJobs.firstOrNull { it.section == ContentType.SERIES.name }+ if (expectedSeries > 0) {+ seriesIndexState = seriesJob?.state ?: "MISSING"+ check(seriesIndexState == "SUCCESS") { "Series summary index ended in $seriesIndexState" }+ seriesCount = graph.database().seriesDao().countByProvider(provider.id)+ check(seriesCount == expectedSeries) { "Incomplete series catalog: $seriesCount/$expectedSeries" }+ val seriesIndexRows = graph.database().xtreamContentIndexDao()+ .countActiveRows(provider.id, ContentType.SERIES.name)+ check(seriesIndexRows == expectedSeries) { "Incomplete series index: $seriesIndexRows/$expectedSeries" }+ seriesIndexElapsedMs = (SystemClock.elapsedRealtimeNanos() - start) / 1_000_000.0+ seriesAfterLiveElapsedMs = (seriesIndexElapsedMs - liveCommittedMs).coerceAtLeast(0.0)+ }+ }+ if (measureSummaryRefresh) {+ check(expectedMovies > 0 && expectedSeries > 0) {+ "Repeated VOD refresh requires non-empty movie and series fixtures"+ }+ val refreshSample = sampleHeap {+ withTimeout(600_000L) {+ val movieStart = SystemClock.elapsedRealtimeNanos()+ check(graph.sync().processQueuedXtreamIndexJobs(+ providerId = provider.id,+ section = ContentType.MOVIE,+ force = true+ ) is Result.Success) { "Unchanged movie summary refresh failed" }+ val movieElapsed = (SystemClock.elapsedRealtimeNanos() - movieStart) / 1_000_000.0++ val seriesStart = SystemClock.elapsedRealtimeNanos()+ check(graph.sync().processQueuedXtreamIndexJobs(+ providerId = provider.id,+ section = ContentType.SERIES,+ force = true+ ) is Result.Success) { "Unchanged series summary refresh failed" }+ val seriesElapsed = (SystemClock.elapsedRealtimeNanos() - seriesStart) / 1_000_000.0+ movieElapsed to seriesElapsed+ }+ }+ unchangedMovieRefreshElapsedMs = refreshSample.value.first+ unchangedSeriesRefreshElapsedMs = refreshSample.value.second+ unchangedVodRefreshElapsedMs = refreshSample.value.first + refreshSample.value.second+ unchangedSummaryPeakHeapBytes = refreshSample.peakHeapBytes+ unchangedSummaryGcCountDelta = refreshSample.gcCountDelta+ check(graph.database().movieDao().countByProvider(provider.id) == expectedMovies)+ check(graph.database().seriesDao().countByProvider(provider.id) == expectedSeries)+ check(graph.database().xtreamContentIndexDao()+ .countActiveRows(provider.id, ContentType.MOVIE.name) == expectedMovies)+ check(graph.database().xtreamContentIndexDao()+ .countActiveRows(provider.id, ContentType.SERIES.name) == expectedSeries)+ }+ val roomPreservationVerified = iteration < warmups && expectedMovies > 0 && expectedSeries > 0+ if (roomPreservationVerified) {+ verifySummaryRoomPreservation(graph, provider.id)+ }val state = graph.sync().currentSyncState(provider.id).javaClass.simpleName- Log.i(TAG, JSONObject().put("event", "sample").put("run", run)+ if (settleSeconds > 0) {+ check(state in setOf("Success", "Partial")) { "Nonterminal setup state: $state" }+ repeat(settleSeconds) {+ delay(1_000L)+ check(graph.sync().currentSyncState(provider.id).javaClass.simpleName == state) {+ "Setup state changed after completion"+ }+ check(graph.database().channelDao().getCount(provider.id).first() == expected) {+ "Committed catalog changed after completion"+ }+ }+ }+ val backgroundWorkerSample = if (measureBackgroundWorker) {+ measureAutomaticProviderSyncWorker(app, graph, provider.id, expected)+ } else null+ val sampleRecord = JSONObject().put("event", "sample").put("run", run).put("provider_id", provider.id).put("mode", mode.name).put("phase", "initial").put("warmup", iteration < warmups).put("elapsed_ms", elapsed).put("channels", count).put("sync_state", state)+ .put("settle_seconds", settleSeconds)+ .put("movies", movieCount).put("series", seriesCount)+ .put("movie_index_state", movieIndexState).put("series_index_state", seriesIndexState).put("peak_java_heap_bytes", sample.peakHeapBytes).put("gc_count_delta", sample.gcCountDelta ?: JSONObject.NULL)- .put("milestones", org.json.JSONArray(progress)).toString())+ .put("runtime_tier_override", runtimeTier)+ .put("stage_batch_size_override", stageBatchSize ?: JSONObject.NULL)+ .put("experimental_auto_bulk", experimentalAutoBulk)+ .put("measure_summary_refresh", measureSummaryRefresh)+ .put("room_preservation_verified", roomPreservationVerified)+ .put("fixture_row_fields_verified", verifyChannelFields)+ .put("milestones", org.json.JSONArray(progress))+ fixtureRowsChecked?.let { sampleRecord.put("fixture_rows_checked", it) }+ fixtureCategoriesChecked?.let { sampleRecord.put("fixture_categories_checked", it) }+ fixtureRowFieldVerificationMs?.let {+ sampleRecord.put("fixture_row_field_verification_ms", it)+ }+ backgroundWorkerSample?.let {+ sampleRecord.put("background_worker_state", it.state)+ .put("background_worker_elapsed_ms", it.elapsedMs)+ .put("background_worker_channels", it.channels)+ .put("background_worker_last_live_success", it.lastLiveSuccess)+ }+ firstBrowsableScreenElapsedMs?.let {+ sampleRecord.put("first_browsable_screen_elapsed_ms", it)+ }+ summaryPeakHeapBytes?.let { sampleRecord.put("summary_peak_java_heap_bytes", it) }+ summaryGcCountDelta?.let { sampleRecord.put("summary_gc_count_delta", it) }+ unchangedMovieRefreshElapsedMs?.let {+ sampleRecord.put("unchanged_movie_refresh_elapsed_ms", it)+ }+ unchangedSeriesRefreshElapsedMs?.let {+ sampleRecord.put("unchanged_series_refresh_elapsed_ms", it)+ }+ unchangedVodRefreshElapsedMs?.let {+ sampleRecord.put("unchanged_vod_refresh_elapsed_ms", it)+ }+ unchangedSummaryPeakHeapBytes?.let {+ sampleRecord.put("unchanged_summary_peak_java_heap_bytes", it)+ }+ unchangedSummaryGcCountDelta?.let {+ sampleRecord.put("unchanged_summary_gc_count_delta", it)+ }+ movieIndexElapsedMs?.let { sampleRecord.put("movie_index_elapsed_ms", it) }+ movieAfterLiveElapsedMs?.let { sampleRecord.put("movie_after_live_elapsed_ms", it) }+ seriesIndexElapsedMs?.let { sampleRecord.put("series_index_elapsed_ms", it) }+ seriesAfterLiveElapsedMs?.let { sampleRecord.put("series_after_live_elapsed_ms", it) }+ Log.i(TAG, sampleRecord.toString())if (measureRefresh) {+ if (hiddenCategoryPercent > 0) {+ val categories = graph.database().categoryDao()+ .getByProviderAndTypeSync(provider.id, ContentType.LIVE.name)+ .sortedWith(compareBy({ it.providerOrder }, { it.categoryId }))+ check(categories.isNotEmpty()) { "Fixture returned no live categories" }+ val hiddenCount = ((categories.size * hiddenCategoryPercent) + 99) / 100+ val hiddenIds = categories.take(hiddenCount).map { it.categoryId }.toSet()+ graph.preferences().setHiddenCategoryIds(provider.id, ContentType.LIVE, hiddenIds)+ check(hiddenIds.size == hiddenCount)+ }+ if (rememberSequentialStress || avoidFullCooldownSeconds > 0) {+ val current = graph.syncMetadata().getMetadata(provider.id) ?: SyncMetadata(provider.id)+ graph.syncMetadata().updateMetadata(+ current.copy(+ liveSequentialFailuresRemembered = current.liveSequentialFailuresRemembered || rememberSequentialStress,+ liveHealthySyncStreak = if (rememberSequentialStress) 0 else current.liveHealthySyncStreak,+ liveAvoidFullUntil = if (avoidFullCooldownSeconds > 0) {+ System.currentTimeMillis() + avoidFullCooldownSeconds * 1_000L+ } else current.liveAvoidFullUntil+ )+ )+ }val refreshStart = SystemClock.elapsedRealtimeNanos()val refresh = sampleHeap {withTimeout(600_000L) {@@ -150,32 +466,351 @@ class XtreamLiveSyncBenchmarkTest {check(refresh.value is Result.Success)val refreshed = graph.database().channelDao().getCount(provider.id).first()check(refreshed == expected)- Log.i(TAG, JSONObject().put("event", "sample").put("run", run)+ val refreshElapsedMs =+ (SystemClock.elapsedRealtimeNanos() - refreshStart) / 1_000_000.0+ var refreshFixtureRowsChecked: Int? = null+ var refreshFixtureCategoriesChecked: Int? = null+ var refreshFixtureFieldVerificationMs: Double? = null+ if (verifyChannelFields) {+ val verificationStarted = SystemClock.elapsedRealtimeNanos()+ val verification = verifyFixtureChannelRows(+ channelDao = graph.database().channelDao(),+ categoryDao = graph.database().categoryDao(),+ providerId = provider.id,+ sourceChannelCount = fixtureSourceChannelCount,+ categoryCount = fixtureCategoryCount,+ seed = fixtureSeed,+ malformedEvery = fixtureMalformedEvery,+ expectedRows = expected+ )+ refreshFixtureRowsChecked = verification.channelRows+ refreshFixtureCategoriesChecked = verification.categories+ refreshFixtureFieldVerificationMs =+ (SystemClock.elapsedRealtimeNanos() - verificationStarted) / 1_000_000.0+ }+ val refreshSampleRecord = JSONObject().put("event", "sample").put("run", run).put("provider_id", provider.id).put("mode", mode.name).put("phase", "refresh").put("warmup", iteration < warmups)- .put("elapsed_ms", (SystemClock.elapsedRealtimeNanos() - refreshStart) / 1_000_000.0)+ .put("elapsed_ms", refreshElapsedMs).put("channels", refreshed).put("peak_java_heap_bytes", refresh.peakHeapBytes)- .put("gc_count_delta", refresh.gcCountDelta ?: JSONObject.NULL).toString())+ .put("gc_count_delta", refresh.gcCountDelta ?: JSONObject.NULL)+ .put("hidden_category_percent", hiddenCategoryPercent)+ .put("remember_sequential_stress", rememberSequentialStress)+ .put("avoid_full_cooldown_seconds", avoidFullCooldownSeconds)+ .put("fixture_row_fields_verified", verifyChannelFields)+ refreshFixtureRowsChecked?.let {+ refreshSampleRecord.put("fixture_rows_checked", it)+ }+ refreshFixtureCategoriesChecked?.let {+ refreshSampleRecord.put("fixture_categories_checked", it)+ }+ refreshFixtureFieldVerificationMs?.let {+ refreshSampleRecord.put("fixture_row_field_verification_ms", it)+ }+ Log.i(TAG, refreshSampleRecord.toString())}} finally {withContext(NonCancellable) {+ firstBrowsableScreenWaiter?.cancelAndJoin()+ activityScenario?.close()+ profileOverrides.edit().clear().commit()// Setup can save a provider before returning an error. Identify only// this exact synthetic run; never clean up unrelated provider rows.val saved = providerId?.let { graph.providers().getProvider(it) }?: graph.providers().getProviders().first().singleOrNull { it.name == name }if (saved != null) {check(saved.name == name)+ graph.preferences().setHiddenCategoryIds(saved.id, ContentType.LIVE, emptySet())check(graph.providers().deleteProvider(saved.id) is Result.Success)check(graph.providers().getProvider(saved.id) == null)}}}+ }}+ } finally {+ profileOverrides.edit().clear().commit()+ previousLandingDestination?.let { graph.preferences().setAppLandingDestination(it) }+ previousShowFavoritesCategory?.let { graph.preferences().setShowFavoritesCategory(it) }+ previousShowRecentChannelsCategory?.let { graph.preferences().setShowRecentChannelsCategory(it) }}Log.i(TAG, JSONObject().put("event", "complete").toString())}private data class HeapSample<T>(val value: T, val peakHeapBytes: Long, val gcCountDelta: Long?)+ private data class BackgroundWorkerSample(+ val state: String,+ val elapsedMs: Double,+ val channels: Int,+ val lastLiveSuccess: Long+ )++ private suspend fun verifyFixtureChannelRows(+ channelDao: ChannelDao,+ categoryDao: CategoryDao,+ providerId: Long,+ sourceChannelCount: Int,+ categoryCount: Int,+ seed: Int,+ malformedEvery: Int,+ expectedRows: Int+ ): FixtureFieldVerification {+ require(sourceChannelCount > 0 && categoryCount > 0)+ require(malformedEvery >= 0)+ val pageSize = 1_024+ var sourceNumber = 1+ var offset = 0+ var checkedRows = 0++ fun nextValidSourceNumber(): Int? {+ while (sourceNumber <= sourceChannelCount && malformedEvery > 0 &&+ sourceNumber % malformedEvery == 0+ ) {+ sourceNumber+++ }+ return sourceNumber.takeIf { it <= sourceChannelCount }?.also { sourceNumber++ }+ }++ while (true) {+ val page = channelDao.getByProviderPage(providerId, pageSize, offset).first()+ if (page.isEmpty()) break+ for (channel in page) {+ val number = nextValidSourceNumber()+ ?: error("Unexpected extra fixture channel at persisted row $checkedRows")+ val expectedName = "Benchmark Channel ${number.toString().padStart(6, '0')} HD"+ val expectedStreamId = 100_000L + number+ val expectedCategoryId = (number - 1) % categoryCount + 1+ // The live row omits category_name, so the row mapper stores its documented fallback.+ val expectedRowCategoryName = "Category $expectedCategoryId"+ val expectedEpgId = "benchmark-$seed-$number"+ val expectedCatchUp = number % 7 == 0++ assertFixtureField(number, "number", number, channel.number)+ assertFixtureField(number, "stream_id", expectedStreamId, channel.streamId)+ assertFixtureField(number, "name", expectedName, channel.name)+ assertFixtureField(number, "logo_url", null, channel.logoUrl)+ assertFixtureField(number, "group_title", null, channel.groupTitle)+ assertFixtureField(number, "category_id", expectedCategoryId.toLong(), channel.categoryId)+ assertFixtureField(number, "category_name", expectedRowCategoryName, channel.categoryName)+ assertFixtureField(number, "epg_channel_id", expectedEpgId, channel.epgChannelId)+ assertFixtureField(number, "catch_up_supported", expectedCatchUp, channel.catchUpSupported)+ assertFixtureField(number, "catch_up_days", if (expectedCatchUp) 3 else 0, channel.catchUpDays)+ assertFixtureField(number, "catch_up_source", null, channel.catchUpSource)+ assertFixtureField(number, "provider_id", providerId, channel.providerId)+ assertFixtureField(number, "is_adult", false, channel.isAdult)+ assertFixtureField(number, "is_user_protected", false, channel.isUserProtected)+ assertFixtureField(number, "logical_group_id",+ ChannelNormalizer.getLogicalGroupId(expectedName, providerId), channel.logicalGroupId)+ assertFixtureField(number, "error_count", 0, channel.errorCount)+ assertFixtureField(number, "quality_options_json", null, channel.qualityOptionsJson)+ assertFixtureField(number, "sync_fingerprint_present", true, channel.syncFingerprint.isNotBlank())+ assertFixtureField(number, "local_id_present", true, channel.id > 0)++ val streamToken = XtreamUrlFactory.parseInternalStreamUrl(channel.streamUrl)+ check(streamToken != null) { "Fixture mismatch at source row $number for stream_url" }+ assertFixtureField(number, "stream_url_provider_id", providerId, streamToken.providerId)+ assertFixtureField(number, "stream_url_kind", XtreamStreamKind.LIVE, streamToken.kind)+ assertFixtureField(number, "stream_url_stream_id", expectedStreamId, streamToken.streamId)+ assertFixtureField(number, "stream_url_extension", "m3u8", streamToken.containerExtension)+ assertFixtureField(number, "stream_url_direct_source", null, streamToken.directSource)+ checkedRows+++ }+ offset += page.size+ }++ val firstMissingSourceNumber = nextValidSourceNumber()+ check(firstMissingSourceNumber == null) {+ "Missing fixture channel source row $firstMissingSourceNumber after checking $checkedRows rows"+ }+ check(checkedRows == expectedRows) {+ "Fixture row-field verification covered $checkedRows/$expectedRows rows"+ }++ val categories = categoryDao.getByProviderAndTypeSync(providerId, ContentType.LIVE.name)+ check(categories.size == categoryCount) {+ "Fixture category verification found ${categories.size}/$categoryCount categories"+ }+ val categoriesById = categories.associateBy { it.categoryId }+ for (categoryId in 1..categoryCount) {+ val category = categoriesById[categoryId.toLong()]+ ?: error("Missing fixture category $categoryId")+ assertFixtureField(categoryId, "category_provider_id", providerId, category.providerId)+ assertFixtureField(categoryId, "category_name",+ "Benchmark Group ${categoryId.toString().padStart(4, '0')}", category.name)+ assertFixtureField(categoryId, "category_is_adult", false, category.isAdult)+ }+ return FixtureFieldVerification(checkedRows, categories.size)+ }++ private fun assertFixtureField(+ sourceNumber: Int,+ field: String,+ expected: Any?,+ actual: Any?+ ) {+ check(expected == actual) {+ "Fixture mismatch at source row $sourceNumber for $field: expected=$expected actual=$actual"+ }+ }++ private data class FixtureFieldVerification(+ val channelRows: Int,+ val categories: Int+ )++ private suspend fun measureAutomaticProviderSyncWorker(+ app: Application,+ graph: XtreamSyncBenchmarkEntryPoint,+ providerId: Long,+ expectedChannels: Int+ ): BackgroundWorkerSample {+ check(graph.providers().getActiveProvider().first()?.id == providerId) {+ "Automatic worker probe requires the synthetic provider to be active"+ }+ val staleTimestamp = 1L+ val previousMetadata = graph.syncMetadata().getMetadata(providerId) ?: SyncMetadata(providerId)+ graph.syncMetadata().updateMetadata(previousMetadata.copy(lastLiveSuccess = staleTimestamp))++ val workManager = WorkManager.getInstance(app)+ val request = OneTimeWorkRequestBuilder<ProviderSyncWorker>().build()+ val start = SystemClock.elapsedRealtimeNanos()+ withContext(Dispatchers.IO) {+ workManager.enqueue(request).result.get(30, TimeUnit.SECONDS)+ }+ val terminalInfo = withTimeout(600_000L) {+ var terminal: WorkInfo? = null+ while (terminal == null) {+ val info = withContext(Dispatchers.IO) {+ workManager.getWorkInfoById(request.id).get(30, TimeUnit.SECONDS)+ } ?: error("Automatic provider worker disappeared from WorkManager")+ if (info.state in setOf(WorkInfo.State.SUCCEEDED, WorkInfo.State.FAILED, WorkInfo.State.CANCELLED)) {+ terminal = info+ } else {+ delay(250L)+ }+ }+ requireNotNull(terminal)+ }+ check(terminalInfo.state == WorkInfo.State.SUCCEEDED) {+ "Automatic provider worker ended in ${terminalInfo.state}"+ }+ val channels = graph.database().channelDao().getCount(providerId).first()+ check(channels == expectedChannels) { "Background worker changed channel coverage: $channels/$expectedChannels" }+ val lastLiveSuccess = graph.syncMetadata().getMetadata(providerId)?.lastLiveSuccess ?: 0L+ check(lastLiveSuccess > staleTimestamp) { "Background worker did not advance live success metadata" }+ return BackgroundWorkerSample(+ state = terminalInfo.state.name,+ elapsedMs = (SystemClock.elapsedRealtimeNanos() - start) / 1_000_000.0,+ channels = channels,+ lastLiveSuccess = lastLiveSuccess+ )+ }++ private suspend fun verifySummaryRoomPreservation(+ graph: XtreamSyncBenchmarkEntryPoint,+ providerId: Long+ ) {+ val database = graph.database()+ val movie = requireNotNull(database.movieDao().getByStreamId(providerId, FIRST_MOVIE_STREAM_ID))+ val series = requireNotNull(database.seriesDao().getBySeriesId(providerId, FIRST_SERIES_ID))+ val movieHydratedAt = 1_700_100_001L+ val seriesHydratedAt = 1_700_100_002L+ val movieProgress = 123_456L+ val movieLastWatchedAt = 1_700_100_003L++ database.playbackHistoryDao().insertOrUpdate(+ PlaybackHistoryEntity(+ contentId = movie.id,+ contentType = ContentType.MOVIE,+ providerId = providerId,+ resumePositionMs = movieProgress,+ lastWatchedAt = movieLastWatchedAt,+ watchCount = 4+ )+ )+ database.movieDao().update(+ movie.copy(+ name = "Stale benchmark movie title",+ backdropUrl = "https://local.invalid/movie-backdrop",+ plot = "Locally hydrated movie plot",+ cast = "Local movie cast",+ director = "Local movie director",+ releaseDate = "1999-01-02",+ duration = "2h 10m",+ durationSeconds = 7_800,+ year = "1999",+ watchProgress = movieProgress,+ watchCount = 4,+ lastWatchedAt = movieLastWatchedAt,+ isUserProtected = true,+ cacheState = "DETAIL_HYDRATED",+ detailHydratedAt = movieHydratedAt,+ playbackMetadataJson = "{\"source\":\"local\"}"+ )+ )+ database.seriesDao().update(+ series.copy(+ name = "Stale benchmark series title",+ backdropUrl = "https://local.invalid/series-backdrop",+ plot = "Locally hydrated series plot",+ cast = "Local series cast",+ director = "Local series director",+ releaseDate = "1998-03-04",+ episodeRunTime = "52",+ isUserProtected = true,+ cacheState = "DETAIL_HYDRATED",+ detailHydratedAt = seriesHydratedAt+ )+ )++ check(graph.sync().processQueuedXtreamIndexJobs(+ providerId = providerId,+ section = ContentType.MOVIE,+ force = true+ ) is Result.Success) { "Movie summary preservation refresh failed" }+ check(graph.sync().processQueuedXtreamIndexJobs(+ providerId = providerId,+ section = ContentType.SERIES,+ force = true+ ) is Result.Success) { "Series summary preservation refresh failed" }++ val refreshedMovie = requireNotNull(database.movieDao().getByStreamId(providerId, FIRST_MOVIE_STREAM_ID))+ check(refreshedMovie.id == movie.id)+ check(refreshedMovie.name == FIRST_MOVIE_NAME)+ check(refreshedMovie.backdropUrl == "https://local.invalid/movie-backdrop")+ check(refreshedMovie.plot == "Locally hydrated movie plot")+ check(refreshedMovie.cast == "Local movie cast")+ check(refreshedMovie.director == "Local movie director")+ check(refreshedMovie.releaseDate == "1999-01-02")+ check(refreshedMovie.durationSeconds == 7_800)+ check(refreshedMovie.year == "1999")+ check(refreshedMovie.watchProgress == movieProgress)+ check(refreshedMovie.watchCount == 4)+ check(refreshedMovie.lastWatchedAt == movieLastWatchedAt)+ check(refreshedMovie.isUserProtected)+ check(refreshedMovie.cacheState == "DETAIL_HYDRATED")+ check(refreshedMovie.detailHydratedAt == movieHydratedAt)+ check(refreshedMovie.playbackMetadataJson == "{\"source\":\"local\"}")+ check(database.xtreamContentIndexDao()+ .getByRemoteId(providerId, ContentType.MOVIE.name, FIRST_MOVIE_STREAM_ID.toString())+ ?.detailHydratedAt == movieHydratedAt)++ val refreshedSeries = requireNotNull(database.seriesDao().getBySeriesId(providerId, FIRST_SERIES_ID))+ check(refreshedSeries.id == series.id)+ check(refreshedSeries.name == FIRST_SERIES_NAME)+ check(refreshedSeries.backdropUrl == "https://local.invalid/series-backdrop")+ check(refreshedSeries.plot == "Locally hydrated series plot")+ check(refreshedSeries.cast == "Local series cast")+ check(refreshedSeries.director == "Local series director")+ check(refreshedSeries.releaseDate == "1998-03-04")+ check(refreshedSeries.episodeRunTime == "52")+ check(refreshedSeries.isUserProtected)+ check(refreshedSeries.cacheState == "DETAIL_HYDRATED")+ check(refreshedSeries.detailHydratedAt == seriesHydratedAt)+ check(database.xtreamContentIndexDao()+ .getByRemoteId(providerId, ContentType.SERIES.name, FIRST_SERIES_ID.toString())+ ?.detailHydratedAt == seriesHydratedAt)+ }private fun benchmarkName(run: String) =ProviderInputSanitizer.normalizeProviderName("Xtream sync benchmark " + run)@@ -206,5 +841,10 @@ class XtreamLiveSyncBenchmarkTest {companion object {private const val TAG = "XtreamSyncBenchmark"+ private const val FIRST_MOVIE_STREAM_ID = 200_001L+ private const val FIRST_SERIES_ID = 300_001L+ private const val FIRST_MOVIE_NAME = "Benchmark Movie 000001"+ private const val FIRST_SERIES_NAME = "Benchmark Series 000001"+ private const val FIRST_LIVE_CHANNEL_NAME = "Benchmark Channel 000001 HD"}}diff --git a/app/src/debug/java/com/streamvault/app/benchmark/XtreamSyncBenchmarkEntryPoint.kt b/app/src/debug/java/com/streamvault/app/benchmark/XtreamSyncBenchmarkEntryPoint.ktindex b634db85..d19d7303 100644--- a/app/src/debug/java/com/streamvault/app/benchmark/XtreamSyncBenchmarkEntryPoint.kt+++ b/app/src/debug/java/com/streamvault/app/benchmark/XtreamSyncBenchmarkEntryPoint.kt@@ -2,6 +2,8 @@ package com.streamvault.app.benchmarkimport com.streamvault.data.local.StreamVaultDatabaseimport com.streamvault.data.sync.ProviderSyncCommands+import com.streamvault.domain.repository.SyncMetadataRepository+import com.streamvault.domain.settings.SettingsPreferencesimport com.streamvault.domain.repository.ProviderRepositoryimport com.streamvault.domain.usecase.ValidateAndAddProviderimport dagger.hilt.EntryPoint@@ -16,4 +18,6 @@ interface XtreamSyncBenchmarkEntryPoint {fun providers(): ProviderRepositoryfun sync(): ProviderSyncCommandsfun database(): StreamVaultDatabase+ fun preferences(): SettingsPreferences+ fun syncMetadata(): SyncMetadataRepository}diff --git a/core/ui/src/test/java/com/streamvault/core/ui/progress/ProgressFractionTest.kt b/core/ui/src/test/java/com/streamvault/core/ui/progress/ProgressFractionTest.ktindex f5f3d343..ad98eb59 100644--- a/core/ui/src/test/java/com/streamvault/core/ui/progress/ProgressFractionTest.kt+++ b/core/ui/src/test/java/com/streamvault/core/ui/progress/ProgressFractionTest.kt@@ -19,6 +19,11 @@ class ProgressFractionTest {assertThat(extractProgressFraction("Syncing provider")).isNull()}+ @Test+ fun bulkChannelCountKeepsUnknownTotalIndicator() {+ assertThat(extractProgressFraction("Loading Live TV channels...\n3,200 channels processed")).isNull()+ }+@Testfun nonPositiveTotalReturnsNull() {assertThat(extractProgressFraction("Syncing 1 / 0")).isNull()diff --git a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt b/data/src/main/java/com/streamvault/data/local/dao/Daos.ktindex e9973d1f..f443dc0a 100644--- a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt@@ -493,6 +493,9 @@ abstract class ChannelDao {@Query("SELECT COUNT(*) FROM channels WHERE provider_id = :providerId")abstract suspend fun countByProvider(providerId: Long): Int+ @Query("SELECT COUNT(*) FROM channels WHERE provider_id = :providerId AND category_id IN (:categoryIds)")+ abstract suspend fun countByProviderAndCategories(providerId: Long, categoryIds: List<Long>): Int+@Query("DELETE FROM channels WHERE provider_id = :providerId")abstract suspend fun deleteByProvider(providerId: Long)diff --git a/data/src/main/java/com/streamvault/data/local/dao/XtreamIndexDaos.kt b/data/src/main/java/com/streamvault/data/local/dao/XtreamIndexDaos.ktindex a3bc2a92..ead7dee6 100644--- a/data/src/main/java/com/streamvault/data/local/dao/XtreamIndexDaos.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/XtreamIndexDaos.kt@@ -38,6 +38,30 @@ abstract class XtreamContentIndexDao {remoteId: String): XtreamContentIndexEntity?+ @Query(+ """+ SELECT * FROM xtream_content_index+ WHERE provider_id = :providerId+ AND content_type = :contentType+ AND remote_id IN (:remoteIds)+ """+ )+ abstract suspend fun getByRemoteIds(+ providerId: Long,+ contentType: String,+ remoteIds: List<String>+ ): List<XtreamContentIndexEntity>++ @Query(+ """+ SELECT COUNT(*) FROM xtream_content_index+ WHERE provider_id = :providerId+ AND content_type = :contentType+ AND stale_state = 'ACTIVE'+ """+ )+ abstract suspend fun countActiveRows(providerId: Long, contentType: String): Int+@Insert(onConflict = OnConflictStrategy.REPLACE)abstract suspend fun upsert(entity: XtreamContentIndexEntity)@@ -238,6 +262,18 @@ interface XtreamIndexJobDao {@Query("SELECT * FROM xtream_index_jobs WHERE provider_id = :providerId AND section = :section")suspend fun get(providerId: Long, section: String): XtreamIndexJobEntity?+ @Query(+ """+ SELECT EXISTS(+ SELECT 1 FROM xtream_index_jobs+ WHERE provider_id = :providerId+ AND section IN ('LIVE', 'MOVIE', 'SERIES')+ AND state IN ('QUEUED', 'RUNNING')+ )+ """+ )+ suspend fun hasPendingCatalogWork(providerId: Long): Boolean+@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun upsert(entity: XtreamIndexJobEntity)diff --git a/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.ktindex de601482..b3b780ed 100644--- a/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt+++ b/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt@@ -7,6 +7,7 @@ import androidx.work.BackoffPolicyimport androidx.work.Constraintsimport androidx.work.CoroutineWorkerimport androidx.work.Data+import androidx.work.ExistingWorkPolicyimport androidx.work.NetworkTypeimport androidx.work.OneTimeWorkRequestBuilderimport androidx.work.WorkManager@@ -14,6 +15,9 @@ import androidx.work.WorkRequestimport androidx.work.WorkerParametersimport com.streamvault.data.local.entity.ProviderWorkflowPhaseimport com.streamvault.data.local.entity.ProviderWorkflowReason+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.XtreamIndexJobDao+import com.streamvault.domain.model.ProviderTypeimport dagger.hilt.EntryPointimport dagger.hilt.InstallInimport dagger.hilt.android.EntryPointAccessors@@ -30,6 +34,8 @@ class BackgroundEpgSyncWorker(interface BackgroundEpgSyncWorkerEntryPoint {fun syncCommands(): ProviderSyncCommandsfun providerWorkflowRunner(): ProviderWorkflowRunner+ fun providerDao(): ProviderDao+ fun xtreamIndexJobDao(): XtreamIndexJobDao}override suspend fun doWork(): Result {@@ -54,6 +60,13 @@ class BackgroundEpgSyncWorker(applicationContext,BackgroundEpgSyncWorkerEntryPoint::class.java)+ val provider = entryPoint.providerDao().getById(providerId)+ if (provider?.type == ProviderType.XTREAM_CODES &&+ entryPoint.xtreamIndexJobDao().hasPendingCatalogWork(providerId)+ ) {+ Log.i(TAG, "Deferring guide work for provider $providerId until queued catalog indexing completes")+ return Result.retry()+ }when (entryPoint.providerWorkflowRunner().execute(providerId = providerId,@@ -159,8 +172,8 @@ class BackgroundEpgSyncWorker(.build()WorkManager.getInstance(context).enqueueUniqueWork(- providerWorkUniqueName(providerId),- providerWorkExistingPolicy(supersede = false),+ providerEpgWorkUniqueName(providerId),+ ExistingWorkPolicy.KEEP,request)}@@ -168,7 +181,7 @@ class BackgroundEpgSyncWorker(fun cancel(context: Context, providerId: Long) {if (providerId <= 0L) returnrunCatching {- WorkManager.getInstance(context).cancelUniqueWork(providerWorkUniqueName(providerId))+ WorkManager.getInstance(context).cancelUniqueWork(providerEpgWorkUniqueName(providerId))}.onFailure { error ->Log.w(TAG, "Skipping background EPG cancellation for provider $providerId", error)}diff --git a/data/src/main/java/com/streamvault/data/sync/CatalogIndexJobStore.kt b/data/src/main/java/com/streamvault/data/sync/CatalogIndexJobStore.ktindex c20ac92c..78fc1134 100644--- a/data/src/main/java/com/streamvault/data/sync/CatalogIndexJobStore.kt+++ b/data/src/main/java/com/streamvault/data/sync/CatalogIndexJobStore.kt@@ -71,6 +71,9 @@ internal class CatalogIndexJobStore(internal fun shouldRunSummary(job: XtreamIndexJobEntity?): Boolean {if (job == null) return true+ // Rejected credentials require a configuration change or explicit forced retry,+ // rather than another launch/periodic attempt because lastSuccessAt is zero.+ if (job.state == "FAILED_PERMANENT") return falseif (job.state in setOf("QUEUED", "RUNNING", "PARTIAL", "STALE", "FAILED_RETRYABLE")) return truereturn ContentCachePolicy.shouldRefresh(job.lastSuccessAt, ContentCachePolicy.CATALOG_TTL_MILLIS)}diff --git a/data/src/main/java/com/streamvault/data/sync/CatalogSyncRuntimeProfile.kt b/data/src/main/java/com/streamvault/data/sync/CatalogSyncRuntimeProfile.ktindex 0a98c025..b967f6b9 100644--- a/data/src/main/java/com/streamvault/data/sync/CatalogSyncRuntimeProfile.kt+++ b/data/src/main/java/com/streamvault/data/sync/CatalogSyncRuntimeProfile.kt@@ -56,7 +56,9 @@ internal data class CatalogSyncRuntimeProfile(val maxCategoryConcurrency: Int,val preferSegmentedLiveOnboarding: Boolean,val deferBackgroundWorkOnLowMemory: Boolean,- val snapshot: SyncDeviceSnapshot+ val snapshot: SyncDeviceSnapshot,+ /** Production AUTO uses bulk-first; the isolated benchmark package can opt out for comparison. */+ val bulkFirstAutoEnabled: Boolean = true) {// Preserve existing row counts until on-device tuning. Wide rows flush by// estimated retained bytes first; LOW keeps only one queued batch.@@ -68,7 +70,8 @@ internal data class CatalogSyncRuntimeProfile(}val diagnosticsLabel: String- get() = "${tier.name.lowercase()} batch=$stageBatchSize memory=${snapshot.memoryClassMb}MB"+ get() = "${tier.name.lowercase()} batch=$stageBatchSize memory=${snapshot.memoryClassMb}MB" ++ if (bulkFirstAutoEnabled) " auto=bulk-first" else ""@Suppress("UNUSED_PARAMETER")fun shouldAttemptFullLiveCatalog(isInitialLiveOnboarding: Boolean): Boolean =@@ -77,39 +80,63 @@ internal data class CatalogSyncRuntimeProfile(companion object {fun from(context: Context): CatalogSyncRuntimeProfile {val snapshot = SyncDeviceSnapshot.from(context)- val tier = when {+ val detectedTier = when {snapshot.isLowRamDevice || snapshot.memoryClassMb <= LOW_MEMORY_CLASS_MB -> DeviceSyncTier.LOWsnapshot.memoryClassMb <= MID_MEMORY_CLASS_MB -> DeviceSyncTier.MIDelse -> DeviceSyncTier.HIGH}+ val benchmarkOverrides = if (context.packageName == BENCHMARK_APPLICATION_ID) {+ context.getSharedPreferences(BENCHMARK_PROFILE_PREFERENCES, Context.MODE_PRIVATE)+ } else {+ null+ }+ val tier = benchmarkOverrides?.getString(KEY_TIER, null)+ ?.let { value -> runCatching { DeviceSyncTier.valueOf(value) }.getOrNull() }+ ?: detectedTier+ val batchOverride = benchmarkOverrides?.getInt(KEY_BATCH_SIZE, 0)?.takeIf { it > 0 }+ ?.also { require(it in MIN_BENCHMARK_BATCH_SIZE..MAX_BENCHMARK_BATCH_SIZE) }+ // Use the new AUTO policy in normal app builds. The isolated benchmark package can+ // still turn it off to compare against the previous AUTO behavior.+ val bulkFirstAutoEnabled =+ benchmarkOverrides?.getBoolean(KEY_EXPERIMENTAL_AUTO_BULK, true) ?: truereturn when (tier) {DeviceSyncTier.LOW -> CatalogSyncRuntimeProfile(tier = tier,- stageBatchSize = LOW_STAGE_BATCH_SIZE,+ stageBatchSize = batchOverride ?: LOW_STAGE_BATCH_SIZE,maxCategoryConcurrency = 1,preferSegmentedLiveOnboarding = false,deferBackgroundWorkOnLowMemory = true,- snapshot = snapshot+ snapshot = snapshot,+ bulkFirstAutoEnabled = bulkFirstAutoEnabled)DeviceSyncTier.MID -> CatalogSyncRuntimeProfile(tier = tier,- stageBatchSize = MID_STAGE_BATCH_SIZE,+ stageBatchSize = batchOverride ?: MID_STAGE_BATCH_SIZE,maxCategoryConcurrency = 2,preferSegmentedLiveOnboarding = true,deferBackgroundWorkOnLowMemory = snapshot.isCurrentlyLowOnMemory,- snapshot = snapshot+ snapshot = snapshot,+ bulkFirstAutoEnabled = bulkFirstAutoEnabled)DeviceSyncTier.HIGH -> CatalogSyncRuntimeProfile(tier = tier,- stageBatchSize = HIGH_STAGE_BATCH_SIZE,+ stageBatchSize = batchOverride ?: HIGH_STAGE_BATCH_SIZE,maxCategoryConcurrency = Int.MAX_VALUE,preferSegmentedLiveOnboarding = false,deferBackgroundWorkOnLowMemory = false,- snapshot = snapshot+ snapshot = snapshot,+ bulkFirstAutoEnabled = bulkFirstAutoEnabled)}}+ private const val BENCHMARK_APPLICATION_ID = "com.streamvault.app.syncbenchmark"+ private const val BENCHMARK_PROFILE_PREFERENCES = "xtream_sync_benchmark_profile"+ private const val KEY_TIER = "tier"+ private const val KEY_BATCH_SIZE = "batch_size"+ private const val KEY_EXPERIMENTAL_AUTO_BULK = "experimental_auto_bulk"+ private const val MIN_BENCHMARK_BATCH_SIZE = 100+ private const val MAX_BENCHMARK_BATCH_SIZE = 1024private const val LOW_MEMORY_CLASS_MB = 192private const val MID_MEMORY_CLASS_MB = 320private const val LOW_STAGE_BATCH_SIZE = 100diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderContinuationScheduler.kt b/data/src/main/java/com/streamvault/data/sync/ProviderContinuationScheduler.ktindex defedf95..9cb73f46 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderContinuationScheduler.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderContinuationScheduler.kt@@ -15,10 +15,6 @@ internal class ProviderContinuationScheduler(// through the configuration-edit worker path (fresh providers have no revision row).workScheduler.scheduleProviderResume(providerId)}- if (work.any { it.operation == SyncContinuationOperation.REFRESH_GUIDE }) {- workScheduler.scheduleBackgroundEpg(providerId)- }-val indexWork = work.filter { it.operation == SyncContinuationOperation.INDEX_CATALOG }when (snapshot.provider.type) {ProviderType.XTREAM_CODES -> indexWork@@ -41,5 +37,10 @@ internal class ProviderContinuationScheduler("${snapshot.provider.type} declared unsupported catalog index continuation work"}}+ if (work.any { it.operation == SyncContinuationOperation.REFRESH_GUIDE }) {+ // Queue the guide after catalog continuations. The Xtream guide worker also defers+ // while durable live/movie/series index jobs remain queued or running.+ workScheduler.scheduleBackgroundEpg(providerId)+ }}}diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncPorts.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncPorts.ktindex babef5ea..bf20816b 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncPorts.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncPorts.kt@@ -95,6 +95,8 @@ interface ProviderSyncCommands {section: ContentType? = null,force: Boolean = false,maxCategoriesPerSection: Int? = null,+ maxRowsPerSection: Int? = null,+ maxDurationMillis: Long? = null,onProgress: ((String) -> Unit)? = null): Result<Unit>diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.ktindex 9a6c0764..be603496 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt@@ -121,6 +121,7 @@ internal fun shouldRunPersistedIndexJob(successTtlMillis: Long): Boolean {if (job == null) return true+ if (job.state == "FAILED_PERMANENT") return falseif (job.state in setOf("QUEUED", "PARTIAL", "STALE", "FAILED_RETRYABLE")) return trueif (job.state == "RUNNING") {return !isFreshRunningIndexJob(job.updatedAt, now, staleRunningAfterMillis)diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderWorkScheduling.kt b/data/src/main/java/com/streamvault/data/sync/ProviderWorkScheduling.ktindex 24752987..ef173797 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderWorkScheduling.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderWorkScheduling.kt@@ -3,12 +3,18 @@ package com.streamvault.data.syncimport androidx.work.ExistingWorkPolicyprivate const val PROVIDER_WORK_UNIQUE_PREFIX = "provider-workflow-"+private const val PROVIDER_EPG_WORK_UNIQUE_PREFIX = "provider-epg-"internal fun providerWorkUniqueName(providerId: Long): String {require(providerId > 0L) { "Provider work requires a positive provider ID." }return PROVIDER_WORK_UNIQUE_PREFIX + providerId}+internal fun providerEpgWorkUniqueName(providerId: Long): String {+ require(providerId > 0L) { "Provider EPG work requires a positive provider ID." }+ return PROVIDER_EPG_WORK_UNIQUE_PREFIX + providerId+}+internal fun providerWorkExistingPolicy(supersede: Boolean): ExistingWorkPolicy =if (supersede) {ExistingWorkPolicy.REPLACEdiff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.ktindex 67698e9f..1c135ad7 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt@@ -1193,12 +1193,26 @@ class SyncManager @Inject constructor(xtreamLiveOnboardingDao.getIncompleteByProvider(providerId) == null) {val metadata = syncMetadataRepository.getMetadata(providerId)- if (metadata?.lastSyncStatus == "SUCCESS" &&+ // A launch recovery worker can observe onboarding mid-sync and then wait on+ // this provider lock. If the foreground import completes while it waits, a+ // category fallback may leave the overall sync PARTIAL even though it committed+ // the full live catalog. Treat that completed onboarding as a reason to+ // coalesce the queued resume, provided the durable live snapshot is complete.+ val onboardingCompletedWhileQueued = trackInitialLiveOnboarding+ if (metadata != null &&+ (metadata.lastSyncStatus == "SUCCESS" || onboardingCompletedWhileQueued) &&!ContentCachePolicy.shouldRefresh(metadata.lastLiveSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, System.currentTimeMillis()) &&metadata.lastLiveSync <= metadata.lastLiveSuccess &&channelDao.countByProvider(providerId) == metadata.liveCount) {- Log.i(TAG, "Xtream primary resume coalesced provider=$providerId")+ Log.i(+ TAG,+ if (onboardingCompletedWhileQueued) {+ "Xtream primary resume coalesced provider=$providerId; onboarding completed while queued."+ } else {+ "Xtream primary resume coalesced provider=$providerId."+ }+ )return@lock Result.success(Unit)}}@@ -1470,6 +1484,8 @@ class SyncManager @Inject constructor(section: ContentType?,force: Boolean,maxCategoriesPerSection: Int?,+ maxRowsPerSection: Int?,+ maxDurationMillis: Long?,onProgress: ((String) -> Unit)?): com.streamvault.domain.model.Result<Unit> = withProviderLock(providerId) lock@{val providerEntity = providerDao.getById(providerId)@@ -1509,6 +1525,8 @@ class SyncManager @Inject constructor(api,contentType,maxCategoriesPerSection,+ maxRowsPerSection,+ maxDurationMillis,onProgress)ContentType.VOD,@@ -1518,7 +1536,7 @@ class SyncManager @Inject constructor(if (failure != null) {val state = XtreamIndexRecoveryPolicy.failureState(failure)val currentJob = xtreamIndexJobDao.get(providerId, contentType.name)- if (currentJob?.state != "PARTIAL") {+ if (currentJob?.state != "PARTIAL" || state == "FAILED_PERMANENT") {val failureAt = System.currentTimeMillis()upsertXtreamIndexJob(providerId = providerId,@@ -1869,26 +1887,58 @@ class SyncManager @Inject constructor(restoreWatchProgress: Boolean = true): Int {if (movies.isEmpty()) return 0- val incoming = movies.map { movie -> movie.toEntity().copy(cacheState = "SUMMARY_ONLY", detailHydratedAt = 0L, remoteStaleAt = 0L) }+ val incoming = movies.map { movie ->+ movie.toEntity().copy(+ cacheState = "SUMMARY_ONLY",+ detailHydratedAt = 0L,+ remoteStaleAt = 0L+ ).let { summary -> summary.copy(syncFingerprint = XtreamSummaryFingerprint.movie(summary)) }+ }val existingByStreamId = loadMoviesByStreamIds(providerId, incoming.map { it.streamId })val merged = incoming.map { summary ->val existing = existingByStreamId[summary.streamId]mergeMovieSummary(existing, summary)}- transactionRunner.inTransaction {- movieDao.insertAll(merged)- val persistedByStreamId = loadMoviesByStreamIds(providerId, merged.map { it.streamId })- xtreamContentIndexDao.upsertAll(- merged.map { movie ->- val persisted = persistedByStreamId[movie.streamId] ?: movie- movie.toXtreamIndexRow(providerId, persisted.id, indexedAt)+ val updatedMovies = merged.filter { movie -> existingByStreamId[movie.streamId] != movie }+ val indexRowsBefore = loadXtreamIndexRows(+ providerId,+ ContentType.MOVIE,+ merged.map { it.streamId.toString() }+ )+ val movieIndexChanged = merged.any { movie ->+ val localId = existingByStreamId[movie.streamId]?.id ?: movie.id+ val row = movie.toXtreamIndexRow(providerId, localId, indexedAt)+ val existing = indexRowsBefore[row.remoteId]+ existing == null || existing.copy(indexedAt = row.indexedAt) != row+ }+ if (updatedMovies.isNotEmpty() || movieIndexChanged) {+ transactionRunner.inTransaction {+ if (updatedMovies.isNotEmpty()) movieDao.insertAll(updatedMovies)+ val newlyInsertedStreamIds = updatedMovies+ .filter { existingByStreamId[it.streamId] == null }+ .map { it.streamId }+ val insertedByStreamId = if (newlyInsertedStreamIds.isEmpty()) {+ emptyMap()+ } else {+ loadMoviesByStreamIds(providerId, newlyInsertedStreamIds)}- )+ val indexRows = merged.distinctBy { it.streamId }.mapNotNull { movie ->+ val localId = existingByStreamId[movie.streamId]?.id?.takeIf { it > 0L }+ ?: insertedByStreamId[movie.streamId]?.id?.takeIf { it > 0L }+ ?: movie.id+ movie.toXtreamIndexRow(providerId, localId, indexedAt)+ }+ val indexUpdates = indexRows.filter { row ->+ val existing = indexRowsBefore[row.remoteId]+ existing == null || existing.copy(indexedAt = row.indexedAt) != row+ }+ if (indexUpdates.isNotEmpty()) xtreamContentIndexDao.upsertAll(indexUpdates)+ }}if (restoreWatchProgress) {movieDao.restoreWatchProgress(providerId)}- return merged.size+ return incoming.size}private suspend fun upsertXtreamSeriesSummaryBatch(@@ -1897,23 +1947,55 @@ class SyncManager @Inject constructor(indexedAt: Long): Int {if (series.isEmpty()) return 0- val incoming = series.map { item -> item.toEntity().copy(cacheState = "SUMMARY_ONLY", detailHydratedAt = 0L, remoteStaleAt = 0L) }+ val incoming = series.map { item ->+ item.toEntity().copy(+ cacheState = "SUMMARY_ONLY",+ detailHydratedAt = 0L,+ remoteStaleAt = 0L+ ).let { summary -> summary.copy(syncFingerprint = XtreamSummaryFingerprint.series(summary)) }+ }val existingBySeriesId = loadSeriesByIds(providerId, incoming.map { it.seriesId })val merged = incoming.map { summary ->val existing = existingBySeriesId[summary.seriesId]mergeSeriesSummary(existing, summary)}- transactionRunner.inTransaction {- seriesDao.insertAll(merged)- val persistedBySeriesId = loadSeriesByIds(providerId, merged.map { it.seriesId })- xtreamContentIndexDao.upsertAll(- merged.map { item ->- val persisted = persistedBySeriesId[item.seriesId] ?: item- item.toXtreamIndexRow(providerId, persisted.id, indexedAt)+ val updatedSeries = merged.filter { item -> existingBySeriesId[item.seriesId] != item }+ val indexRowsBefore = loadXtreamIndexRows(+ providerId,+ ContentType.SERIES,+ merged.map { it.providerSeriesId?.takeIf(String::isNotBlank) ?: it.seriesId.toString() }+ )+ val seriesIndexChanged = merged.any { item ->+ val localId = existingBySeriesId[item.seriesId]?.id ?: item.id+ val row = item.toXtreamIndexRow(providerId, localId, indexedAt)+ val existing = indexRowsBefore[row.remoteId]+ existing == null || existing.copy(indexedAt = row.indexedAt) != row+ }+ if (updatedSeries.isNotEmpty() || seriesIndexChanged) {+ transactionRunner.inTransaction {+ if (updatedSeries.isNotEmpty()) seriesDao.insertAll(updatedSeries)+ val newlyInsertedSeriesIds = updatedSeries+ .filter { existingBySeriesId[it.seriesId] == null }+ .map { it.seriesId }+ val insertedBySeriesId = if (newlyInsertedSeriesIds.isEmpty()) {+ emptyMap()+ } else {+ loadSeriesByIds(providerId, newlyInsertedSeriesIds)}- )+ val indexRows = merged.distinctBy { it.seriesId }.mapNotNull { item ->+ val localId = existingBySeriesId[item.seriesId]?.id?.takeIf { it > 0L }+ ?: insertedBySeriesId[item.seriesId]?.id?.takeIf { it > 0L }+ ?: item.id+ item.toXtreamIndexRow(providerId, localId, indexedAt)+ }+ val indexUpdates = indexRows.filter { row ->+ val existing = indexRowsBefore[row.remoteId]+ existing == null || existing.copy(indexedAt = row.indexedAt) != row+ }+ if (indexUpdates.isNotEmpty()) xtreamContentIndexDao.upsertAll(indexUpdates)+ }}- return merged.size+ return incoming.size}private suspend fun upsertVodDerivedSeriesSummaryBatch(@@ -1992,6 +2074,20 @@ class SyncManager @Inject constructor()}+ private suspend fun loadXtreamIndexRows(+ providerId: Long,+ contentType: ContentType,+ remoteIds: List<String>+ ): Map<String, XtreamContentIndexEntity> {+ val distinctIds = remoteIds.distinct()+ if (distinctIds.isEmpty()) return emptyMap()+ return distinctIds.chunked(XTREAM_SQLITE_LOOKUP_CHUNK_SIZE)+ .flatMap { chunk ->+ xtreamContentIndexDao.getByRemoteIds(providerId, contentType.name, chunk)+ }+ .associateBy { it.remoteId }+ }+private fun mergeMovieSummary(existing: MovieEntity?, summary: MovieEntity): MovieEntity {if (existing == null) return summaryval preserveDetails = existing.cacheState == "DETAIL_HYDRATED" && existing.detailHydratedAt > 0L@@ -2009,12 +2105,14 @@ class SyncManager @Inject constructor(year = if (preserveDetails) existing.year else summary.year,tmdbId = summary.tmdbId ?: existing.tmdbId,youtubeTrailer = summary.youtubeTrailer ?: existing.youtubeTrailer,+ syncFingerprint = summary.syncFingerprint.ifBlank { existing.syncFingerprint },watchProgress = existing.watchProgress,watchCount = existing.watchCount,lastWatchedAt = existing.lastWatchedAt,isUserProtected = existing.isUserProtected,cacheState = if (preserveDetails) existing.cacheState else "SUMMARY_ONLY",detailHydratedAt = if (preserveDetails) existing.detailHydratedAt else 0L,+ playbackMetadataJson = if (preserveDetails) existing.playbackMetadataJson else summary.playbackMetadataJson,remoteStaleAt = 0L)}@@ -2035,6 +2133,7 @@ class SyncManager @Inject constructor(tmdbId = summary.tmdbId ?: existing.tmdbId,youtubeTrailer = summary.youtubeTrailer ?: existing.youtubeTrailer,episodeRunTime = if (preserveDetails) existing.episodeRunTime else summary.episodeRunTime,+ syncFingerprint = summary.syncFingerprint.ifBlank { existing.syncFingerprint },isUserProtected = existing.isUserProtected,cacheState = if (preserveDetails) existing.cacheState else "SUMMARY_ONLY",detailHydratedAt = if (preserveDetails) existing.detailHydratedAt else 0L,diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.ktindex 294754fa..6d2f288c 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.kt@@ -145,9 +145,15 @@ internal data class TimedCategoryOutcome<T>(internal data class CategoryExecutionPlan<T>(val outcomes: List<TimedCategoryOutcome<T>>,- val warnings: List<String> = emptyList()+ val warnings: List<String> = emptyList(),+ val stopReason: CategoryExecutionStopReason? = null)+internal enum class CategoryExecutionStopReason {+ AUTHENTICATION,+ PROVIDER_STRESS+}+internal data class M3uImportStats(val header: M3uParser.M3uHeader,val liveCount: Int,diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.ktindex 0cb0a568..e5bc72e5 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt@@ -15,10 +15,25 @@ import com.streamvault.domain.model.Channelimport com.streamvault.domain.model.Movieimport com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.Series+import kotlinx.coroutines.CancellationExceptionimport kotlin.system.measureTimeMillisprivate const val XTREAM_FETCHER_TAG = "SyncManager"+/** Keeps callback failures out of transport retries and provider-health accounting. */+internal class XtreamLiveWriterException(val failure: Exception) :+ IllegalStateException("Live catalog writer failed", failure)++private suspend fun runLiveWriter(block: suspend () -> Unit) {+ try {+ block()+ } catch (error: CancellationException) {+ throw error+ } catch (error: Exception) {+ throw XtreamLiveWriterException(error)+ }+}+internal class SyncManagerXtreamFetcher(private val xtreamCatalogApiService: XtreamApiService,private val xtreamCatalogHttpService: OkHttpXtreamApiService,@@ -47,7 +62,7 @@ internal class SyncManagerXtreamFetcher(suspend fun emitMappedChannels(channels: List<Channel>) {if (channels.isEmpty()) return- onMappedBatch?.invoke(channels)+ onMappedBatch?.let { writer -> runLiveWriter { writer(channels) } }if (onMappedBatch == null) {mappedChannels = mappedChannels + channels}@@ -84,7 +99,7 @@ internal class SyncManagerXtreamFetcher(val elapsedMs = measureTimeMillis {when (val attempt = xtreamSupport.attemptNonCancellation {xtreamSupport.retryXtreamCatalogTransient(provider.id) {- onAttemptReset()+ runLiveWriter(onAttemptReset)rawCount = 0mappedChannels = emptyList()xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.LIVE_CATEGORY) {@@ -104,7 +119,7 @@ internal class SyncManagerXtreamFetcher("Xtream live category '${category.categoryName}' thin decode failed; retrying legacy decode: ${sanitizeThrowableMessage(error)}")}- onAttemptReset()+ runLiveWriter(onAttemptReset)val legacyStreams = xtreamCatalogApiService.getLiveStreams(endpoint)rawCount = legacyStreams.sizeemitMappedChannels(api.mapLiveStreamsResponse(legacyStreams))@@ -113,7 +128,11 @@ internal class SyncManagerXtreamFetcher(}}) {is Attempt.Success -> Unit- is Attempt.Failure -> categoryFailure = attempt.error+ is Attempt.Failure -> {+ val error = attempt.error+ if (error is XtreamLiveWriterException) throw error.failure+ categoryFailure = error+ }}}val outcome = when {diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.ktindex a2712dbc..831f4c8a 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt@@ -67,7 +67,6 @@ internal class SyncManagerXtreamLiveStrategy(// are unsealed attempts and cannot be reused by this import.syncCatalogStore.clearProviderStaging(provider.id)val shouldAttemptFullCatalog = effectiveLiveSyncMethod == EffectiveXtreamLiveSyncMethod.STREAM_ALL &&- hiddenLiveCategoryIds.isEmpty() &&runtimeProfile.shouldAttemptFullLiveCatalog(trackInitialLiveOnboarding)// A stressed provider gets one request at a time. Starting metadata first// also avoids a one-slot deadlock when the writer needs that context.@@ -107,9 +106,16 @@ internal class SyncManagerXtreamLiveStrategy(var fullPayload = CatalogSyncPayload<Channel>(catalogResult = CatalogStrategyResult.EmptyValid("full"), categories = null)if (shouldAttemptFullCatalog) {- progress(provider.id, onProgress, "Downloading Live TV...")+ progress(provider.id, onProgress, XtreamLiveProgressLabels.LOADING)fullPayload = requestSlots.withPermit {- loadXtreamLiveFull(provider, api, runtimeProfile, beforeMapping = { categoryContext.await() })+ loadXtreamLiveFull(+ provider,+ api,+ runtimeProfile,+ beforeMapping = { categoryContext.await() },+ excludedCategoryIds = hiddenLiveCategoryIds - requiredHiddenLiveCategoryIds,+ onProgress = onProgress+ )}}val (rawLiveCategories, resolvedCategories) = categoryContext.await()@@ -147,6 +153,13 @@ internal class SyncManagerXtreamLiveStrategy(fullCatalogUnsafe = false))+ is CatalogStrategyResult.Failure -> {+ // A different request topology cannot repair rejected credentials.+ // Keep the original failure so activation/recovery stays terminal.+ if (XtreamIndexRecoveryPolicy.isAuthenticationFailure(fullResult.error)) {+ return@coroutineScope fullPayload+ }+ }else -> Unit}} else {@@ -191,16 +204,20 @@ internal class SyncManagerXtreamLiveStrategy(provider: Provider,api: XtreamProvider,runtimeProfile: CatalogSyncRuntimeProfile,- beforeMapping: suspend () -> Unit = {}+ beforeMapping: suspend () -> Unit = {},+ excludedCategoryIds: Set<Long> = emptySet(),+ onProgress: ((String) -> Unit)? = null): CatalogSyncPayload<Channel> = xtreamAdaptiveSyncPolicy.withLivePipelinePermit {- loadXtreamLiveFullWithPermit(provider, api, runtimeProfile, beforeMapping)+ loadXtreamLiveFullWithPermit(provider, api, runtimeProfile, beforeMapping, excludedCategoryIds, onProgress)}private suspend fun loadXtreamLiveFullWithPermit(provider: Provider,api: XtreamProvider,runtimeProfile: CatalogSyncRuntimeProfile,- beforeMapping: suspend () -> Unit+ beforeMapping: suspend () -> Unit,+ excludedCategoryIds: Set<Long>,+ onProgress: ((String) -> Unit)?): CatalogSyncPayload<Channel> {val endpoint = XtreamUrlFactory.buildPlayerApiUrl(serverUrl = provider.serverUrl,@@ -218,7 +235,9 @@ internal class SyncManagerXtreamLiveStrategy(mapRawBatch = { batch -> api.mapLiveStreamsSequence(batch) },estimatedBytes = { it.estimatedBufferBytes() },beforeMapping = beforeMapping,- runtimeProfile = runtimeProfile+ runtimeProfile = runtimeProfile,+ excludedCategoryIds = excludedCategoryIds,+ onProgress = onProgress)}@@ -230,7 +249,9 @@ internal class SyncManagerXtreamLiveStrategy(mapRawBatch = { batch -> api.mapLiveStreamRowsSequence(batch) },estimatedBytes = { it.estimatedBufferBytes() },beforeMapping = beforeMapping,- runtimeProfile = runtimeProfile+ runtimeProfile = runtimeProfile,+ excludedCategoryIds = excludedCategoryIds,+ onProgress = onProgress)if (!thinPayload.shouldRetryLegacyFullDecode()) {return thinPayload@@ -248,7 +269,9 @@ internal class SyncManagerXtreamLiveStrategy(mapRawBatch = { batch -> api.mapLiveStreamsSequence(batch) },estimatedBytes = { it.estimatedBufferBytes() },beforeMapping = beforeMapping,- runtimeProfile = runtimeProfile+ runtimeProfile = runtimeProfile,+ excludedCategoryIds = excludedCategoryIds,+ onProgress = onProgress)}@@ -269,17 +292,21 @@ internal class SyncManagerXtreamLiveStrategy(mapRawBatch: suspend (Sequence<RawItem>) -> Sequence<Channel>,estimatedBytes: (RawItem) -> Long,beforeMapping: suspend () -> Unit,- runtimeProfile: CatalogSyncRuntimeProfile+ runtimeProfile: CatalogSyncRuntimeProfile,+ excludedCategoryIds: Set<Long>,+ onProgress: ((String) -> Unit)?): CatalogSyncPayload<Channel> {var fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.LIVE)val seenStreamIds = HashSet<Long>()var stagedSessionId: Long? = nullvar acceptedCount = 0var streamedRawCount = 0+ var filteredHiddenCount = 0var fullChannelsFailure: Throwable? = nullvar flushCount = 0var mappingElapsedMs = 0Lvar stagingElapsedMs = 0L+ val loadingProgress = XtreamLiveLoadingProgress { message -> progress(provider.id, onProgress, message) }suspend fun discardAttempt() {stagedSessionId?.let { syncCatalogStore.discardStagedImport(provider.id, it) }@@ -315,7 +342,12 @@ internal class SyncManagerXtreamLiveStrategy(if (rawBatch.isEmpty()) returnlateinit var mappedChannels: List<Channel>mappingElapsedMs += measureTimeMillis {- mappedChannels = mapRawBatch(rawBatch.asSequence()).toList()+ val mapped = mapRawBatch(rawBatch.asSequence()).toList()+ mappedChannels = mapped.filter { channel ->+ val excluded = channel.categoryId != null && channel.categoryId in excludedCategoryIds+ if (excluded) filteredHiddenCount+++ !excluded+ }}lateinit var staged: StagedCatalogSnapshotstagingElapsedMs += measureTimeMillis {@@ -333,16 +365,14 @@ internal class SyncManagerXtreamLiveStrategy(stagedSessionId = staged.sessionIdacceptedCount += staged.acceptedCountflushCount++- // D10 — mode HIGH (full catalog) : pas de count par categorie disponible,- // on emet en indetermine (`total = 0`) une fois par flush de batch (cadence- // <= 1/s en pratique, jamais par item). Le label reste vide car aucune- // categorie ne correspond a la fenetre courante.+ // Counts represent successful staging writes, not a committed/ready catalog.+ loadingProgress.batchStaged(acceptedCount)emitProgress(provider.id,SyncProgress(section = Section.LIVE,current = 0,total = 0,- currentLabel = "",+ currentLabel = XtreamLiveProgressLabels.LOADING,itemsIndexed = acceptedCount))@@ -352,6 +382,7 @@ internal class SyncManagerXtreamLiveStrategy(val fullChannelsElapsedMs = measureTimeMillis {when (val attempt = xtreamSupport.attemptNonCancellation {xtreamSupport.retryXtreamCatalogTransient(provider.id) {+ loadingProgress.startAttempt()streamedRawCount = 0flushCount = 0mappingElapsedMs = 0L@@ -408,12 +439,14 @@ internal class SyncManagerXtreamLiveStrategy()}- if (streamedRawCount > 0) {+ loadingProgress.readerDrained(acceptedCount)+ if (streamedRawCount > 0 && (acceptedCount > 0 || filteredHiddenCount > 0)) {Log.i(XTREAM_LIVE_STRATEGY_TAG,"Xtream live full catalog succeeded for provider ${provider.id} using $decoderLabel decoder in ${fullChannelsElapsedMs}ms " +"with $acceptedCount accepted items from $streamedRawCount raw items " +- "across $flushCount flushes; mapping=${mappingElapsedMs}ms staging=${stagingElapsedMs}ms profile=${runtimeProfile.diagnosticsLabel}."+ "across $flushCount flushes; hidden_filtered=$filteredHiddenCount " ++ "mapping=${mappingElapsedMs}ms staging=${stagingElapsedMs}ms profile=${runtimeProfile.diagnosticsLabel}.")if (acceptedCount == 0) {return CatalogSyncPayload(@@ -583,7 +616,7 @@ internal class SyncManagerXtreamLiveStrategy(categoryOutcomes)var fallbackWarnings = executionPlan.warnings- if (concurrency > 1 && catalogStrategySupport.shouldRetryFailedCategories(+ if (executionPlan.stopReason == null && concurrency > 1 && catalogStrategySupport.shouldRetryFailedCategories(categories.size,failureCount,downgradeRecommended,@@ -600,6 +633,7 @@ internal class SyncManagerXtreamLiveStrategy(provider = provider,timedOutcomes = timedOutcomes,fetchSequentially = ::fetchCompletedCategory,+ stopReason = executionPlan.stopReason,onCategoryRetried = { completed, total, _ ->progress(provider.id, onProgress, "Retrying failed Live TV categories $completed/$total...")}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.ktindex 2ea2412c..f9b69813 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt@@ -115,7 +115,11 @@ internal class SyncManagerXtreamSupport(}}- return CategoryExecutionPlan(outcomes = outcomes, warnings = warnings.distinct())+ return CategoryExecutionPlan(+ outcomes = outcomes,+ warnings = warnings.distinct(),+ stopReason = if (stoppedEarly) CategoryExecutionStopReason.PROVIDER_STRESS else null+ )}private suspend fun <T> executeRefilledCategoryPlan(@@ -135,11 +139,11 @@ internal class SyncManagerXtreamSupport(var nextIndex = 0var active = 0var sequential = limit == 1- var stopped = false+ var stopReason: CategoryExecutionStopReason? = nullvar stressFailures = 0fun fillSlots() {val desired = if (sequential) 1 else limit- while (!stopped && active < desired && nextIndex < categories.size) {+ while (stopReason == null && active < desired && nextIndex < categories.size) {val index = nextIndex++active++launch {@@ -162,16 +166,16 @@ internal class SyncManagerXtreamSupport(val error = (outcome as? CategoryFetchOutcome.Failure)?.errorprogress(provider.id, onProgress, "Downloading $sectionLabel by category ${results.size}/${categories.size}...")onCategoryCompleted?.invoke(results.size, categories.size, result.second.category.categoryName)- if (error is XtreamAuthenticationException) stopped = true+ if (error is XtreamAuthenticationException) stopReason = CategoryExecutionStopReason.AUTHENTICATIONif (!sequential && shouldRecoverRemainingCategoryRequests(categories.size, results.size, results.map { it.second.outcome })) {sequential = truewarnings += sequentialModeWarning}- if (sequential) {+ if (sequential && stopReason == null) {stressFailures = if (error != null && shouldRememberSequentialPreference(error)) stressFailures + 1 else 0- if (stressFailures >= 3 && nextIndex < categories.size) {- stopped = true- warnings += "$sectionLabel $recoveryAbortWarningSuffix"+ if (stressFailures >= 3) {+ stopReason = CategoryExecutionStopReason.PROVIDER_STRESS+ if (nextIndex < categories.size) warnings += "$sectionLabel $recoveryAbortWarningSuffix"}}// Already running attempts drain before a downgrade admits another.@@ -180,7 +184,7 @@ internal class SyncManagerXtreamSupport(} finally {completed.cancel()}- CategoryExecutionPlan(results.sortedBy { it.first }.map { it.second }, warnings.distinct())+ CategoryExecutionPlan(results.sortedBy { it.first }.map { it.second }, warnings.distinct(), stopReason)}suspend fun <T> retryTransient(@@ -246,6 +250,9 @@ internal class SyncManagerXtreamSupport()} catch (e: CancellationException) {throw e+ } catch (e: XtreamLiveWriterException) {+ // Local persistence is not a provider-health signal.+ throw e} catch (e: Exception) {adaptiveSyncPolicy.recordFailure(providerId, e)throw e@@ -314,25 +321,33 @@ internal class SyncManagerXtreamSupport(provider: Provider,timedOutcomes: List<TimedCategoryOutcome<T>>,fetchSequentially: suspend (XtreamCategory) -> TimedCategoryOutcome<T>,- onCategoryRetried: ((completed: Int, total: Int, currentLabel: String) -> Unit)? = null+ onCategoryRetried: ((completed: Int, total: Int, currentLabel: String) -> Unit)? = null,+ stopReason: CategoryExecutionStopReason? = null): List<TimedCategoryOutcome<T>> {+ if (stopReason != null || timedOutcomes.any {+ (it.outcome as? CategoryFetchOutcome.Failure)?.error is XtreamAuthenticationException+ }) {+ return timedOutcomes+ }val failedCategories = timedOutcomes- .filter { it.outcome is CategoryFetchOutcome.Failure && it.outcome.error !is XtreamAuthenticationException }+ .filter { it.outcome is CategoryFetchOutcome.Failure }.map { it.category }if (failedCategories.isEmpty()) {return timedOutcomes}val replacements = LinkedHashMap<String, TimedCategoryOutcome<T>>()- failedCategories.forEachIndexed { index, category ->- replacements[category.categoryId] = fetchSequentially(category)+ for ((index, category) in failedCategories.withIndex()) {+ val result = fetchSequentially(category)+ replacements[category.categoryId] = resultonCategoryRetried?.invoke(index + 1, failedCategories.size, category.categoryName)+ if ((result.outcome as? CategoryFetchOutcome.Failure)?.error is XtreamAuthenticationException) break}return timedOutcomes.map { existing ->replacements[existing.category.categoryId] ?: existing}.also {Log.i(XTREAM_SUPPORT_TAG,- "Xtream continuation fallback kept ${timedOutcomes.size - failedCategories.size} successful category results for provider ${provider.id} and retried only ${failedCategories.size} failed categories."+ "Xtream continuation fallback kept ${timedOutcomes.count { it.outcome !is CategoryFetchOutcome.Failure }} successful category results for provider ${provider.id} and retried ${replacements.size} failed categories.")}}@@ -378,11 +393,12 @@ internal class SyncManagerXtreamSupport(private fun isXtreamCatalogRetryable(error: Throwable, attempt: Int): Boolean {return when (error) {+ is XtreamLiveWriterException -> falseis XtreamAuthenticationException -> falseis XtreamResponseTooLargeException -> falseis XtreamParsingException -> attempt == 1is XtreamRequestException ->- error.statusCode in setOf(403, 408, 409, 429) || error.statusCode in 500..599+ error.statusCode in setOf(408, 409, 429) || error.statusCode in 500..599is XtreamNetworkException -> trueis IOException -> trueelse -> isRetryable(error)diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamCatalogSyncExecutor.kt b/data/src/main/java/com/streamvault/data/sync/XtreamCatalogSyncExecutor.ktindex cc873f54..50595789 100644--- a/data/src/main/java/com/streamvault/data/sync/XtreamCatalogSyncExecutor.kt+++ b/data/src/main/java/com/streamvault/data/sync/XtreamCatalogSyncExecutor.kt@@ -17,6 +17,7 @@ import com.streamvault.domain.model.Channelimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderEpgSyncMode+import com.streamvault.domain.model.ProviderXtreamLiveSyncModeimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.SyncMetadataimport com.streamvault.domain.model.VodSyncMode@@ -117,13 +118,20 @@ internal class XtreamCatalogSyncExecutor()val liveOutcome = runSuspendCatching {val recoveredLiveCommit = if (trackInitialLiveOnboarding) {- recoverOnboardingSession(provider, hiddenLiveCategoryIds, receiptGeneration, mappingProfile, afterCatalogApply)+ recoverOnboardingSession(+ provider,+ hiddenLiveCategoryIds,+ receiptGeneration,+ mappingProfile,+ afterCatalogApply,+ onProgress+ )} else {null}if (recoveredLiveCommit != null) {warnings += recoveredLiveCommit.warnings- val acceptedCount = recoveredLiveCommit.acceptedCount+ val acceptedCount = recoveredLiveCommit.committedChannelCountval completedAt = System.currentTimeMillis()recordOnboardingState(provider = provider,@@ -142,7 +150,7 @@ internal class XtreamCatalogSyncExecutor(liveCount = acceptedCount)syncMetadataRepository.updateMetadata(metadata)- activatedLiveMutations = acceptedCount+ activatedLiveMutations = recoveredLiveCommit.acceptedCountcatalogActivated = truereturn@runSuspendCatching acceptedCount}@@ -156,7 +164,7 @@ internal class XtreamCatalogSyncExecutor(runtimeProfile = runtimeProfile)}- progress(provider.id, onProgress, "Downloading Live TV...")+ progress(provider.id, onProgress, XtreamLiveProgressLabels.LOADING)val liveSyncResult = syncLiveCatalog(provider = provider,api = api,@@ -238,7 +246,7 @@ internal class XtreamCatalogSyncExecutor(warnings += it.warningsactivatedLiveMutations = it.acceptedCountcatalogActivated = true- }.acceptedCount+ }.committedChannelCount}is CatalogStrategyResult.Partial -> {recordCommitPhaseIfNeeded(@@ -259,7 +267,7 @@ internal class XtreamCatalogSyncExecutor(warnings += it.warningsactivatedLiveMutations = it.acceptedCountcatalogActivated = true- }.acceptedCount+ }.committedChannelCount}is CatalogStrategyResult.EmptyValid -> {preservedActiveCatalog = true@@ -285,7 +293,9 @@ internal class XtreamCatalogSyncExecutor(metadata = metadata.copy(lastLiveSync = now,- lastLiveSuccess = now,+ // Preserving old rows after failure/partial coverage is not a fresh+ // complete snapshot. Recovery must still see the unsuccessful attempt.+ lastLiveSuccess = if (liveSyncResult.catalogResult is CatalogStrategyResult.Success) now else metadata.lastLiveSuccess,liveCount = acceptedCount,liveAvoidFullUntil = liveAvoidFullUntil,liveSequentialFailuresRemembered = liveProviderAdaptation.rememberSequential,@@ -351,7 +361,18 @@ internal class XtreamCatalogSyncExecutor(now = now,onProgress = onProgress).getOrElse { error ->- warnings += "Movies categories could not be loaded; movie indexing will retry later."+ warnings += if (indexFailureState(error) == "FAILED_RETRYABLE") {+ "Movies categories could not be loaded; movie indexing will retry later."+ } else {+ "Movies categories were rejected; check provider credentials before retrying."+ }+ if (indexFailureState(error) == "FAILED_RETRYABLE") {+ continuationWork += SyncContinuation(+ operation = SyncContinuationOperation.INDEX_CATALOG,+ section = ContentType.MOVIE,+ reason = "retry movie category discovery in durable background work"+ )+ }updateIndexJob(XtreamIndexJobUpdate(providerId = provider.id,@@ -390,7 +411,18 @@ internal class XtreamCatalogSyncExecutor(now = now,onProgress = onProgress).getOrElse { error ->- warnings += "Series categories could not be loaded; series indexing will retry later."+ warnings += if (indexFailureState(error) == "FAILED_RETRYABLE") {+ "Series categories could not be loaded; series indexing will retry later."+ } else {+ "Series categories were rejected; check provider credentials before retrying."+ }+ if (indexFailureState(error) == "FAILED_RETRYABLE") {+ continuationWork += SyncContinuation(+ operation = SyncContinuationOperation.INDEX_CATALOG,+ section = ContentType.SERIES,+ reason = "retry series category discovery in durable background work"+ )+ }updateIndexJob(XtreamIndexJobUpdate(providerId = provider.id,@@ -494,7 +526,7 @@ internal class XtreamCatalogSyncExecutor(): SyncOutcome {val now = System.currentTimeMillis()val sectionWarnings = mutableListOf<String>()- progress(provider.id, onProgress, "Retrying Live TV...")+ progress(provider.id, onProgress, XtreamLiveProgressLabels.LOADING)val useTextClassification = preferencesRepository.useXtreamTextClassification.first()val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()val hiddenLiveCategoryIds = preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE).first()@@ -527,18 +559,18 @@ internal class XtreamCatalogSyncExecutor()when (val liveResult = liveSyncResult.catalogResult) {is CatalogStrategyResult.Success -> {- val acceptedCount = finalizeLiveCatalog(+ val commitResult = finalizeLiveCatalog(provider.id,liveSyncResult,hiddenLiveCategoryIds,onProgress- ).acceptedCount- activatedMutations = acceptedCount+ )+ activatedMutations = commitResult.acceptedCountsyncMetadataRepository.updateMetadata(currentMetadata.copy(lastLiveSync = now,lastLiveSuccess = now,- liveCount = acceptedCount,+ liveCount = commitResult.committedChannelCount,liveAvoidFullUntil = liveAvoidFullUntil,liveSequentialFailuresRemembered = liveProviderAdaptation.rememberSequential,liveHealthySyncStreak = liveProviderAdaptation.healthyStreak@@ -557,7 +589,7 @@ internal class XtreamCatalogSyncExecutor(syncMetadataRepository.updateMetadata(currentMetadata.copy(lastLiveSync = now,- liveCount = commitResult.acceptedCount,+ liveCount = commitResult.committedChannelCount,liveAvoidFullUntil = liveAvoidFullUntil,liveSequentialFailuresRemembered = currentMetadata.liveSequentialFailuresRemembered || liveSequentialStress,liveHealthySyncStreak = 0@@ -636,9 +668,28 @@ internal class XtreamCatalogSyncExecutor(trackInitialLiveOnboarding: Boolean,syncReason: XtreamLiveSyncReason): CatalogSyncPayload<Channel> {+ val hiddenLiveChannelFraction = if (+ provider.xtreamLiveSyncMode == ProviderXtreamLiveSyncMode.AUTO &&+ runtimeProfile.bulkFirstAutoEnabled &&+ hiddenLiveCategoryIds.isNotEmpty()+ ) {+ val totalChannels = channelDao.countByProvider(provider.id)+ if (totalChannels == 0) null else {+ channelDao.countByProviderAndCategories(provider.id, hiddenLiveCategoryIds.toList()).toFloat() /+ totalChannels.toFloat()+ }+ } else {+ null+ }emitProgress(provider.id,- SyncProgress(Section.LIVE, current = 0, total = 0, currentLabel = "", itemsIndexed = 0)+ SyncProgress(+ Section.LIVE,+ current = 0,+ total = 0,+ currentLabel = XtreamLiveProgressLabels.LOADING,+ itemsIndexed = 0+ ))val effectiveMethod = XtreamLiveSyncPolicy.resolve(userMode = provider.xtreamLiveSyncMode,@@ -646,7 +697,8 @@ internal class XtreamCatalogSyncExecutor(syncReason = syncReason,metadata = existingMetadata,now = System.currentTimeMillis(),- hiddenLiveCategoryIds = hiddenLiveCategoryIds+ hiddenLiveCategoryIds = hiddenLiveCategoryIds,+ hiddenLiveChannelFraction = hiddenLiveChannelFraction)Log.i(TAG,@@ -693,7 +745,8 @@ internal class XtreamCatalogSyncExecutor(hiddenLiveCategoryIds: Set<Long>,currentGeneration: Long?,mappingProfile: String,- afterCatalogApply: suspend () -> Unit+ afterCatalogApply: suspend () -> Unit,+ onProgress: ((String) -> Unit)?): XtreamLiveCommitResult? {val state = xtreamLiveOnboardingDao.getIncompleteByProvider(provider.id) ?: return nullval sessionId = state.stagedSessionId ?: return null@@ -743,7 +796,23 @@ internal class XtreamCatalogSyncExecutor(categories = stagedState.categories.takeIf { it.isNotEmpty() },afterCatalogApply = afterCatalogApply)- return XtreamLiveCommitResult(stagedState.channelCount, listOf("Live TV import resumed from saved staged session."))+ val committedChannelCount = stagedState.channelCount+ emitProgress(+ provider.id,+ SyncProgress(+ section = Section.LIVE,+ current = 1,+ total = 1,+ currentLabel = XtreamLiveProgressLabels.READY,+ itemsIndexed = committedChannelCount+ )+ )+ progress(provider.id, onProgress, XtreamLiveProgressLabels.READY)+ return XtreamLiveCommitResult(+ stagedState.channelCount,+ committedChannelCount,+ listOf("Live TV import resumed from saved staged session.")+ )}private suspend fun discardOnboardingSession(provider: Provider, sessionId: Long, reason: String) {@@ -821,7 +890,17 @@ internal class XtreamCatalogSyncExecutor(partialCompletionWarning: String? = null,afterCatalogApply: suspend () -> Unit = {}): XtreamLiveCommitResult {- progress(providerId, onProgress, "Saving Live TV channels...")+ progress(providerId, onProgress, XtreamLiveProgressLabels.SAVING)+ emitProgress(+ providerId,+ SyncProgress(+ section = Section.LIVE,+ current = 0,+ total = 0,+ currentLabel = XtreamLiveProgressLabels.SAVING,+ itemsIndexed = liveSyncResult.stagedAcceptedCount+ )+ )val warnings = buildList {addAll(liveSyncResult.warnings)addAll(catalogStrategySupport.strategyWarnings(liveSyncResult.catalogResult))@@ -873,7 +952,25 @@ internal class XtreamCatalogSyncExecutor("finalizeLiveCatalog only supports success or partial results")}- return XtreamLiveCommitResult(acceptedCount, warnings)+ val committedChannelCount = if (+ hiddenLiveCategoryIds.isNotEmpty() || liveSyncResult.catalogResult is CatalogStrategyResult.Partial+ ) {+ channelDao.countByProvider(providerId)+ } else {+ acceptedCount+ }+ emitProgress(+ providerId,+ SyncProgress(+ section = Section.LIVE,+ current = 1,+ total = 1,+ currentLabel = XtreamLiveProgressLabels.READY,+ itemsIndexed = committedChannelCount+ )+ )+ progress(providerId, onProgress, XtreamLiveProgressLabels.READY)+ return XtreamLiveCommitResult(acceptedCount, committedChannelCount, warnings)}private suspend fun mergeHiddenChannelsIntoStaging(@@ -948,6 +1045,7 @@ internal class XtreamCatalogSyncExecutor(private data class XtreamLiveCommitResult(val acceptedCount: Int,+ val committedChannelCount: Int,val warnings: List<String>)diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutor.kt b/data/src/main/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutor.ktindex 575bad4a..3b9f3bd9 100644--- a/data/src/main/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutor.kt+++ b/data/src/main/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutor.kt@@ -17,6 +17,8 @@ import com.streamvault.domain.model.Series* supplied through one narrow operations port so the coordinator does not regain those seams.*/internal interface XtreamIncrementalIndexOperations {+ fun monotonicTimeMillis(): Long = System.nanoTime() / 1_000_000L+suspend fun getCategories(providerId: Long, contentType: ContentType): List<CategoryEntity>suspend fun ensureCategoryShell(@@ -98,6 +100,8 @@ internal class XtreamIncrementalIndexExecutor(api: XtreamProvider,contentType: ContentType,maxCategories: Int?,+ maxRowsPerSlice: Int? = null,+ maxDurationMillis: Long? = null,onProgress: ((String) -> Unit)?) {require(contentType == ContentType.MOVIE || contentType == ContentType.SERIES) {@@ -137,6 +141,11 @@ internal class XtreamIncrementalIndexExecutor()) {is Result.Success -> returnis Result.Error -> {+ streamed.exception?.let { error ->+ if (XtreamIndexRecoveryPolicy.isAuthenticationFailure(error)) {+ throw error+ }+ }operations.log("Full ${contentType.name} stream index failed for provider ${provider.id}; falling back to category slices: ${streamed.message}")@@ -215,6 +224,8 @@ internal class XtreamIncrementalIndexExecutor(}}+ var rowsProcessedThisSlice = 0+ val sliceStartedAt = operations.monotonicTimeMillis()workLoop@ for (workItem in workItems) {val category = workItem.categoryoperations.progress(@@ -229,6 +240,7 @@ internal class XtreamIncrementalIndexExecutor(}when (val categoryOutcome = outcome.outcome) {is CategoryFetchOutcome.Success -> {+ rowsProcessedThisSlice += categoryOutcome.rawCountval accepted = when (contentType) {ContentType.MOVIE -> operations.upsertMovieSummaryBatch(providerId = provider.id,@@ -280,6 +292,9 @@ internal class XtreamIncrementalIndexExecutor(}}is CategoryFetchOutcome.Failure -> {+ if (XtreamIndexRecoveryPolicy.failureState(categoryOutcome.error) == "FAILED_PERMANENT") {+ throw categoryOutcome.error+ }failedCategories++lastError = categoryOutcome.error}@@ -301,6 +316,13 @@ internal class XtreamIncrementalIndexExecutor(if (outcome.outcome is CategoryFetchOutcome.Failure) {break@workLoop}+ val rowBudgetReached = maxRowsPerSlice+ ?.takeIf { it > 0 }+ ?.let { rowsProcessedThisSlice >= it } == true+ val durationBudgetReached = maxDurationMillis+ ?.takeIf { it > 0L }+ ?.let { operations.monotonicTimeMillis() - sliceStartedAt >= it } == true+ if (rowBudgetReached || durationBudgetReached) break@workLoop}val finishedAt = System.currentTimeMillis()diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamIndexRecoveryPolicy.kt b/data/src/main/java/com/streamvault/data/sync/XtreamIndexRecoveryPolicy.ktindex 387dd895..e49d6142 100644--- a/data/src/main/java/com/streamvault/data/sync/XtreamIndexRecoveryPolicy.kt+++ b/data/src/main/java/com/streamvault/data/sync/XtreamIndexRecoveryPolicy.kt@@ -5,6 +5,9 @@ import com.streamvault.data.remote.xtream.XtreamRequestException/** Classifies durable Xtream index failures for process-death and WorkManager recovery. */internal object XtreamIndexRecoveryPolicy {+ fun isAuthenticationFailure(error: Throwable): Boolean =+ generateSequence(error as Throwable?) { it.cause }.any { it is XtreamAuthenticationException }+fun failureState(error: Throwable): String {val chain = generateSequence(error as Throwable?) { it.cause }.toList()if (chain.any { it is XtreamAuthenticationException }) {diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamIndexSliceBudget.kt b/data/src/main/java/com/streamvault/data/sync/XtreamIndexSliceBudget.ktnew file mode 100644index 00000000..26d4667f--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/XtreamIndexSliceBudget.kt@@ -0,0 +1,35 @@+package com.streamvault.data.sync++/** Bounds fallback movie/series category work by rows and elapsed time, with a category safety cap. */+internal data class XtreamIndexSliceBudget(+ val maxCategories: Int,+ val maxRows: Int,+ val maxDurationMillis: Long+) {+ init {+ require(maxCategories > 0)+ require(maxRows > 0)+ require(maxDurationMillis > 0L)+ }++ companion object {+ /** Conservative initial budgets; tune these with VOD fixtures on target devices. */+ fun forTier(tier: DeviceSyncTier): XtreamIndexSliceBudget = when (tier) {+ DeviceSyncTier.LOW -> XtreamIndexSliceBudget(+ maxCategories = 4,+ maxRows = 1_000,+ maxDurationMillis = 10_000L+ )+ DeviceSyncTier.MID -> XtreamIndexSliceBudget(+ maxCategories = 8,+ maxRows = 3_000,+ maxDurationMillis = 20_000L+ )+ DeviceSyncTier.HIGH -> XtreamIndexSliceBudget(+ maxCategories = 16,+ maxRows = 8_000,+ maxDurationMillis = 30_000L+ )+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.kt b/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.ktindex 1aac57b5..1a856fcc 100644--- a/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.kt+++ b/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.kt@@ -49,6 +49,9 @@ class XtreamIndexWorker(val force = inputData.getBoolean(KEY_FORCE, false)val requestedProviderId = inputData.getLong(KEY_PROVIDER_ID, INVALID_PROVIDER_ID)val requestedSection = inputData.getString(KEY_SECTION)?.toContentTypeOrNull()+ val sliceBudget = XtreamIndexSliceBudget.forTier(+ CatalogSyncRuntimeProfile.from(applicationContext).tier+ )return try {val entryPoint = EntryPointAccessors.fromApplication(@@ -77,7 +80,9 @@ class XtreamIndexWorker(providerId = provider.id,section = requestedSection,force = force,- maxCategoriesPerSection = CATEGORY_SLICE_SIZE+ maxCategoriesPerSection = sliceBudget.maxCategories,+ maxRowsPerSection = sliceBudget.maxRows,+ maxDurationMillis = sliceBudget.maxDurationMillis)) {is com.streamvault.domain.model.Result.Error -> {Log.w(TAG, "Xtream index worker failed for provider ${provider.id}: ${result.message}")@@ -105,11 +110,7 @@ class XtreamIndexWorker(}}- when {- sawRetryableFailure -> Result.retry()- sawPermanentFailure -> Result.failure()- else -> Result.success()- }+ xtreamIndexWorkResult(requestedProviderId, sawRetryableFailure, sawPermanentFailure)} catch (cancelled: kotlinx.coroutines.CancellationException) {throw cancelled} catch (error: Exception) {@@ -128,7 +129,6 @@ class XtreamIndexWorker(private const val KEY_SECTION = "section"private const val KEY_FORCE = "force"private const val INVALID_PROVIDER_ID = -1L- private const val CATEGORY_SLICE_SIZE = 2private const val UNIQUE_LAUNCH_WORK_NAME = "xtream-index-launch-stale-check"private const val UNIQUE_PERIODIC_WORK_NAME = "xtream-index-periodic-worker"@@ -217,3 +217,14 @@ class XtreamIndexWorker(}}}++/** Durable section/workflow status carries permanent failures; do not poison appended sections. */+internal fun xtreamIndexWorkResult(+ requestedProviderId: Long,+ sawRetryableFailure: Boolean,+ sawPermanentFailure: Boolean+): androidx.work.ListenableWorker.Result = when {+ sawRetryableFailure -> androidx.work.ListenableWorker.Result.retry()+ sawPermanentFailure && requestedProviderId <= 0L -> androidx.work.ListenableWorker.Result.failure()+ else -> androidx.work.ListenableWorker.Result.success()+}diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamLiveLoadingProgress.kt b/data/src/main/java/com/streamvault/data/sync/XtreamLiveLoadingProgress.ktnew file mode 100644index 00000000..f3d0a22c--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/XtreamLiveLoadingProgress.kt@@ -0,0 +1,34 @@+package com.streamvault.data.sync++import java.text.NumberFormat++/** Unknown-total progress for the setup callback; readiness belongs to catalog promotion. */+internal class XtreamLiveLoadingProgress(+ private val clockMillis: () -> Long = { System.nanoTime() / 1_000_000L },+ private val publish: (String) -> Unit+) {+ private val numberFormat = NumberFormat.getIntegerInstance()+ private var lastPublishedAt: Long? = null+ private var lastPublishedCount = 0++ fun startAttempt() {+ lastPublishedAt = null+ lastPublishedCount = 0+ publish(XtreamLiveProgressLabels.LOADING)+ }++ fun batchStaged(count: Int) = publishCount(count, force = false)++ fun readerDrained(count: Int) = publishCount(count, force = true)++ private fun publishCount(count: Int, force: Boolean) {+ if (count <= 0 || count == lastPublishedCount) return+ val now = clockMillis()+ val previous = lastPublishedAt+ if (!force && previous != null && now - previous < 250L) return+ lastPublishedAt = now+ lastPublishedCount = count+ val noun = if (count == 1) "channel" else "channels"+ publish("${XtreamLiveProgressLabels.LOADING}\n${numberFormat.format(count)} $noun processed")+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamLiveProgressLabels.kt b/data/src/main/java/com/streamvault/data/sync/XtreamLiveProgressLabels.ktnew file mode 100644index 00000000..14636757--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/XtreamLiveProgressLabels.kt@@ -0,0 +1,8 @@+package com.streamvault.data.sync++/** Shared user-facing milestones for Add Provider, Settings, and background live sync. */+internal object XtreamLiveProgressLabels {+ const val LOADING = "Loading Live TV channels..."+ const val SAVING = "Saving Live TV channels..."+ const val READY = "Live TV ready."+}diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamLiveSyncPolicy.kt b/data/src/main/java/com/streamvault/data/sync/XtreamLiveSyncPolicy.ktindex 940f296f..29419532 100644--- a/data/src/main/java/com/streamvault/data/sync/XtreamLiveSyncPolicy.kt+++ b/data/src/main/java/com/streamvault/data/sync/XtreamLiveSyncPolicy.kt@@ -22,7 +22,8 @@ internal object XtreamLiveSyncPolicy {syncReason: XtreamLiveSyncReason,metadata: SyncMetadata,now: Long,- hiddenLiveCategoryIds: Set<Long>+ hiddenLiveCategoryIds: Set<Long>,+ hiddenLiveChannelFraction: Float? = null): EffectiveXtreamLiveSyncMethod = when (userMode) {ProviderXtreamLiveSyncMode.CATEGORY_BY_CATEGORY -> EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORYProviderXtreamLiveSyncMode.STREAM_ALL -> EffectiveXtreamLiveSyncMethod.STREAM_ALL@@ -31,7 +32,9 @@ internal object XtreamLiveSyncPolicy {syncReason = syncReason,metadata = metadata,now = now,- hiddenLiveCategoryIds = hiddenLiveCategoryIds+ hiddenLiveCategoryIds = hiddenLiveCategoryIds,+ hiddenLiveChannelFraction = hiddenLiveChannelFraction,+ bulkFirstAutoEnabled = runtimeProfile.bulkFirstAutoEnabled)}@@ -40,8 +43,24 @@ internal object XtreamLiveSyncPolicy {syncReason: XtreamLiveSyncReason,metadata: SyncMetadata,now: Long,- hiddenLiveCategoryIds: Set<Long>+ hiddenLiveCategoryIds: Set<Long>,+ hiddenLiveChannelFraction: Float?,+ bulkFirstAutoEnabled: Boolean): EffectiveXtreamLiveSyncMethod {+ if (bulkFirstAutoEnabled) {+ // Prefer the bounded bulk route across tiers. Actual low memory, an active cooldown,+ // or a large hidden share still selects category retrieval. Category stress alone+ // does not mean the provider cannot serve a bulk catalog.+ if (runtimeProfile.snapshot.isCurrentlyLowOnMemory) return EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORY+ if (metadata.liveAvoidFullUntil > now) return EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORY+ if (hiddenLiveCategoryIds.isNotEmpty() &&+ hiddenLiveChannelFraction != null &&+ hiddenLiveChannelFraction >= HIDDEN_LIVE_CATEGORY_FRACTION_FOR_CATEGORY_MODE+ ) {+ return EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORY+ }+ return EffectiveXtreamLiveSyncMethod.STREAM_ALL+ }if (hiddenLiveCategoryIds.isNotEmpty()) return EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORYif (runtimeProfile.tier == DeviceSyncTier.LOW) return EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORYif (runtimeProfile.snapshot.isCurrentlyLowOnMemory) return EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORY@@ -57,4 +76,6 @@ internal object XtreamLiveSyncPolicy {XtreamLiveSyncReason.FOREGROUND -> EffectiveXtreamLiveSyncMethod.STREAM_ALL}}++ private const val HIDDEN_LIVE_CATEGORY_FRACTION_FOR_CATEGORY_MODE = 0.60f}diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamSummaryFingerprint.kt b/data/src/main/java/com/streamvault/data/sync/XtreamSummaryFingerprint.ktnew file mode 100644index 00000000..d17cd153--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/XtreamSummaryFingerprint.kt@@ -0,0 +1,80 @@+package com.streamvault.data.sync++import com.streamvault.data.local.entity.MovieEntity+import com.streamvault.data.local.entity.SeriesEntity+import java.security.MessageDigest++/** Fingerprints only remote summary fields; hydration and local playback state are excluded. */+internal object XtreamSummaryFingerprint {+ private const val HEX_DIGITS = "0123456789abcdef"++ fun movie(movie: MovieEntity): String = digest(+ movie.streamId,+ movie.name,+ movie.posterUrl,+ movie.backdropUrl,+ movie.categoryId,+ movie.categoryName,+ movie.streamUrl,+ movie.containerExtension,+ movie.plot,+ movie.cast,+ movie.director,+ movie.genre,+ movie.releaseDate,+ movie.duration,+ movie.durationSeconds,+ movie.rating,+ movie.year,+ movie.tmdbId,+ movie.youtubeTrailer,+ movie.isAdult,+ movie.addedAt+ )++ fun series(series: SeriesEntity): String = digest(+ series.seriesId,+ series.providerSeriesId,+ series.name,+ series.posterUrl,+ series.backdropUrl,+ series.categoryId,+ series.categoryName,+ series.plot,+ series.cast,+ series.director,+ series.genre,+ series.releaseDate,+ series.rating,+ series.tmdbId,+ series.youtubeTrailer,+ series.episodeRunTime,+ series.lastModified,+ series.isAdult+ )++ private fun digest(vararg values: Any?): String {+ val digest = MessageDigest.getInstance("SHA-256")+ values.forEach { value ->+ if (value == null) {+ digest.update(0)+ } else {+ val bytes = value.toString().toByteArray(Charsets.UTF_8)+ digest.update(1)+ digest.update((bytes.size ushr 24).toByte())+ digest.update((bytes.size ushr 16).toByte())+ digest.update((bytes.size ushr 8).toByte())+ digest.update(bytes.size.toByte())+ digest.update(bytes)+ }+ }+ val hash = digest.digest()+ val encoded = CharArray(hash.size * 2)+ hash.forEachIndexed { index, byte ->+ val unsigned = byte.toInt() and 0xff+ encoded[index * 2] = HEX_DIGITS[unsigned ushr 4]+ encoded[index * 2 + 1] = HEX_DIGITS[unsigned and 0x0f]+ }+ return String(encoded)+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/CatalogIndexJobStoreTest.kt b/data/src/test/java/com/streamvault/data/sync/CatalogIndexJobStoreTest.ktindex 89f3bb3b..972be3c4 100644--- a/data/src/test/java/com/streamvault/data/sync/CatalogIndexJobStoreTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/CatalogIndexJobStoreTest.kt@@ -21,6 +21,15 @@ import org.mockito.kotlin.verifyimport org.mockito.kotlin.wheneverclass CatalogIndexJobStoreTest {+ @Test+ fun `permanent rejection with no previous success does not restart automatically`() {+ assertThat(store.shouldRunSummary(+ XtreamIndexJobEntity(1L, "MOVIE", state = "FAILED_PERMANENT", lastSuccessAt = 0L)+ )).isFalse()+ assertThat(store.shouldRunSummary(+ XtreamIndexJobEntity(1L, "MOVIE", state = "FAILED_RETRYABLE", lastSuccessAt = 0L)+ )).isTrue()+ }private val providerDao = mock<ProviderDao>()private val xtreamDao = mock<XtreamIndexJobDao>()private val stalkerDao = mock<StalkerIndexJobDao>()diff --git a/data/src/test/java/com/streamvault/data/sync/CatalogSyncRuntimeProfileTest.kt b/data/src/test/java/com/streamvault/data/sync/CatalogSyncRuntimeProfileTest.ktnew file mode 100644index 00000000..33d57c3a--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/CatalogSyncRuntimeProfileTest.kt@@ -0,0 +1,42 @@+package com.streamvault.data.sync++import android.content.Context+import android.content.ContextWrapper+import com.google.common.truth.Truth.assertThat+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment++@RunWith(RobolectricTestRunner::class)+class CatalogSyncRuntimeProfileTest {+ @Test+ fun `normal application profile enables bulk first auto`() {+ val context = RuntimeEnvironment.getApplication()++ assertThat(context.packageName).isNotEqualTo(BENCHMARK_APPLICATION_ID)+ assertThat(CatalogSyncRuntimeProfile.from(context).bulkFirstAutoEnabled).isTrue()+ }++ @Test+ fun `benchmark UI defaults to bulk first and comparisons can explicitly opt out`() {+ val app = RuntimeEnvironment.getApplication()+ val benchmarkContext = object : ContextWrapper(app) {+ override fun getPackageName(): String = BENCHMARK_APPLICATION_ID+ }+ val preferences = app.getSharedPreferences("xtream_sync_benchmark_profile", Context.MODE_PRIVATE)+ preferences.edit().clear().commit()++ assertThat(CatalogSyncRuntimeProfile.from(benchmarkContext).bulkFirstAutoEnabled).isTrue()++ preferences.edit().putBoolean("experimental_auto_bulk", false).commit()+ assertThat(CatalogSyncRuntimeProfile.from(benchmarkContext).bulkFirstAutoEnabled).isFalse()++ preferences.edit().putBoolean("experimental_auto_bulk", true).commit()+ assertThat(CatalogSyncRuntimeProfile.from(benchmarkContext).bulkFirstAutoEnabled).isTrue()+ }++ private companion object {+ const val BENCHMARK_APPLICATION_ID = "com.streamvault.app.syncbenchmark"+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderContinuationSchedulerTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderContinuationSchedulerTest.ktindex 0d525d07..f369c632 100644--- a/data/src/test/java/com/streamvault/data/sync/ProviderContinuationSchedulerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/ProviderContinuationSchedulerTest.kt@@ -3,11 +3,13 @@ package com.streamvault.data.syncimport com.streamvault.domain.model.Providerimport com.streamvault.domain.model.ProviderSnapshotimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.XtreamConfigimport com.streamvault.domain.model.StalkerConfigimport com.streamvault.domain.model.StalkerDeviceIdentityimport kotlinx.coroutines.test.runTestimport org.junit.Testimport org.mockito.kotlin.mock+import org.mockito.kotlin.inOrderimport org.mockito.kotlin.verifyclass ProviderContinuationSchedulerTest {@@ -36,4 +38,44 @@ class ProviderContinuationSchedulerTest {verify(workScheduler).scheduleProviderResume(7L)}++ @Test+ fun `Xtream movie and series indexes are queued before delayed guide work`() = runTest {+ val workScheduler = mock<ProviderSyncWorkScheduler>()+ val snapshot = ProviderSnapshot(+ provider = Provider(id = 9L, name = "Xtream", type = ProviderType.XTREAM_CODES),+ configuration = XtreamConfig(+ serverUrl = "https://example.com",+ username = "user",+ password = "password"+ ),+ configurationGeneration = 1L+ )++ ProviderContinuationScheduler(workScheduler).schedule(+ snapshot,+ listOf(+ SyncContinuation(+ operation = SyncContinuationOperation.REFRESH_GUIDE,+ reason = "guide follows catalog availability"+ ),+ SyncContinuation(+ operation = SyncContinuationOperation.INDEX_CATALOG,+ section = com.streamvault.domain.model.ContentType.MOVIE,+ reason = "movie summary"+ ),+ SyncContinuation(+ operation = SyncContinuationOperation.INDEX_CATALOG,+ section = com.streamvault.domain.model.ContentType.SERIES,+ reason = "series summary"+ )+ )+ )++ inOrder(workScheduler) {+ verify(workScheduler).scheduleXtreamIndex(9L, com.streamvault.domain.model.ContentType.MOVIE, false)+ verify(workScheduler).scheduleXtreamIndex(9L, com.streamvault.domain.model.ContentType.SERIES, false)+ verify(workScheduler).scheduleBackgroundEpg(9L)+ }+ }}diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.ktindex 7b392dde..770e4929 100644--- a/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.kt@@ -30,6 +30,13 @@ import org.mockito.kotlin.verifyimport org.mockito.kotlin.wheneverclass ProviderSyncWorkerTest {+ @Test+ fun `permanent index rejection is not retried merely because success timestamp is absent`() {+ assertThat(shouldRunPersistedIndexJob(+ XtreamIndexJobEntity(1L, "MOVIE", state = "FAILED_PERMANENT"),+ 100_000L, 1_000L, 86_400_000L+ )).isFalse()+ }private val providerDao: ProviderDao = mock()private val categoryDao: CategoryDao = mock()private val channelDao: ChannelDao = mock()diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.ktindex 2fd4b17b..04035360 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt@@ -266,6 +266,7 @@ class SyncManagerTest {// Mockito mocks — all return defaults (null/0/Unit), which will cause// the sync pipeline to throw and transition to Error state.private val channelDao: ChannelDao = mock()+ private val workScheduler: ProviderSyncWorkScheduler = mock()private val movieDao: MovieDao = mock()private val seriesDao: SeriesDao = mock()private val episodeDao: EpisodeDao = mock()@@ -387,6 +388,7 @@ class SyncManagerTest {org.mockito.kotlin.whenever(catalogSyncDao.countCategoryStages(any(), any(), any())).thenReturn(0)org.mockito.kotlin.whenever(catalogSyncDao.getChannelStageCategorySummaries(any(), any())).thenReturn(emptyList())org.mockito.kotlin.whenever(xtreamContentIndexDao.pruneStaleLocalContentRows(any(), any())).thenReturn(0)+ org.mockito.kotlin.whenever(xtreamContentIndexDao.getByRemoteIds(any(), any(), any())).thenReturn(emptyList())// Default stubs for the streamed Stalker API methods. The tests in this file// generally don't stress live-stream streaming directly; without these defaults// the unstubbed mock returns null which crashes the `when (val streamResult)`@@ -568,7 +570,7 @@ class SyncManagerTest {providerWorkLocks = ProviderWorkLockRegistry(),providerSyncLocks = ProviderSyncLockRegistry(),stalkerPlaybackCapabilityCache = com.streamvault.data.provider.StalkerPlaybackCapabilityCache(typedProviderClientFactory),- providerSyncWorkScheduler = mock()+ providerSyncWorkScheduler = workScheduler)}@@ -853,6 +855,30 @@ class SyncManagerTest {assertThat(xtreamBackend.requestedActions).contains("get_live_streams")}+ @Test+ fun `completed fallback catalog coalesces queued onboarding recovery despite warnings`() = runTest {+ val mgr = buildManager(providerEntity = sampleProvider().copy(status = com.streamvault.domain.model.ProviderStatus.PARTIAL))+ val now = System.currentTimeMillis()+ syncMetadataRepo.updateMetadata(SyncMetadata(providerId = 1, lastLiveSync = now, lastLiveSuccess = now,+ liveCount = 1, lastSyncStatus = "PARTIAL"))+ org.mockito.kotlin.whenever(channelDao.countByProvider(1)).thenReturn(1)+ assertThat(mgr.resumePrimaryCatalog(1, true).isSuccess).isTrue()+ assertThat(xtreamBackend.requestedActions).isEmpty()+ }++ @Test+ fun `onboarding recovery does not coalesce a newer failed live attempt`() = runTest {+ val mgr = buildManager(providerEntity = sampleProvider().copy(status = com.streamvault.domain.model.ProviderStatus.PARTIAL))+ val now = System.currentTimeMillis()+ syncMetadataRepo.updateMetadata(SyncMetadata(providerId = 1, lastLiveSync = now, lastLiveSuccess = now - 1000,+ liveCount = 1, lastSyncStatus = "PARTIAL"))+ org.mockito.kotlin.whenever(channelDao.countByProvider(1)).thenReturn(1)+ stubXtreamLiveCatalog()+ stubXtreamEmptyVodAndSeriesCategories()+ mgr.resumePrimaryCatalog(1, true)+ assertThat(xtreamBackend.requestedActions).contains("get_live_streams")+ }+@Testfun `sync_xtream_withFreshCache_andForceFalse_runs_index_first_shell`() = runTest {val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)@@ -1101,6 +1127,24 @@ class SyncManagerTest {assertThat(updated?.lastLiveSuccess ?: 0L).isGreaterThan(0L)}+ @Test+ fun `failed full live refresh preserves library without marking it freshly successful`() = runTest {+ val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)+ val previousSuccess = System.currentTimeMillis() - 60_000L+ syncMetadataRepo.updateMetadata(SyncMetadata(providerId = 1L, liveCount = 7,+ lastLiveSync = previousSuccess, lastLiveSuccess = previousSuccess))+ org.mockito.kotlin.whenever(channelDao.getCount(1L)).thenReturn(flowOf(7))+ xtreamBackend.respond(action = "get_live_categories", body = "[]")+ xtreamBackend.respond(action = "get_live_streams", body = "{}", code = 401)+ stubXtreamEmptyVodAndSeriesCategories()+ assertThat(mgr.sync(1L, force = true).isSuccess).isTrue()+ val metadata = syncMetadataRepo.getMetadata(1L)!!+ assertThat(metadata.lastLiveSuccess).isEqualTo(previousSuccess)+ assertThat(metadata.lastLiveSync).isGreaterThan(previousSuccess)+ assertThat(metadata.liveCount).isEqualTo(7)+ verify(catalogSyncDao, org.mockito.kotlin.never()).deleteStaleChannelsForStage(any(), any())+ }+@Testfun `retrySection_live_xtream_full_success_keeps_staged_live_count`() = runTest {val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)@@ -1147,7 +1191,7 @@ class SyncManagerTest {}@Test- fun `retrySection_live_xtream_auto_manual_sync_uses_category_mode_on_mid_profile`() = runTest {+ fun `retrySection live auto manual sync uses one bulk request on mid profile`() = runTest {val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)xtreamBackend.respond(action = "get_live_categories",@@ -1178,8 +1222,8 @@ class SyncManagerTest {advanceUntilIdle()assertThat(result.isSuccess).isTrue()- assertThat(xtreamBackend.requestedActions.count { it == "get_live_streams" }).isEqualTo(2)- assertThat(xtreamBackend.requestedActions.first()).isEqualTo("get_live_categories")+ assertThat(xtreamBackend.requestedActions.count { it == "get_live_streams" }).isEqualTo(1)+ assertThat(xtreamBackend.requestedActions).contains("get_live_categories")}@Test@@ -1217,7 +1261,7 @@ class SyncManagerTest {val result = mgr.sync(1L, force = false)advanceUntilIdle()- assertThat(result.isSuccess).isTrue()+ if (!result.isSuccess) throw AssertionError("Unexpected sync result: $result")assertThat(xtreamBackend.requestedActions.count { it == "get_live_streams" }).isEqualTo(2)assertThat(xtreamBackend.requestedActions).contains("get_vod_categories")assertThat(xtreamBackend.requestedActions).contains("get_series_categories")@@ -1340,6 +1384,7 @@ class SyncManagerTest {)))+ org.mockito.kotlin.whenever(channelDao.countByProvider(1L)).thenReturn(2)}xtreamBackend.respond(action = "get_live_categories",@@ -1394,6 +1439,7 @@ class SyncManagerTest {org.mockito.kotlin.whenever(categoryDao.getByProviderAndTypeSync(1L, ContentType.LIVE.name)).thenReturn(emptyList())org.mockito.kotlin.whenever(channelDao.getByProviderSync(1L)).thenReturn(emptyList())+ org.mockito.kotlin.whenever(channelDao.countByProvider(1L)).thenReturn(1)xtreamBackend.respond(action = "get_live_categories",body = """@@ -1523,6 +1569,31 @@ class SyncManagerTest {val jobs = argumentCaptor<XtreamIndexJobEntity>()verify(xtreamIndexJobDao, atLeastOnce()).upsert(jobs.capture())assertThat(jobs.allValues.last { it.section == "MOVIE" }.state).isEqualTo("FAILED_RETRYABLE")+ verify(workScheduler).scheduleXtreamIndex(1L, ContentType.MOVIE, false)+ }++ @Test+ fun `series category discovery failure queues durable recovery`() = runTest {+ val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)+ stubXtreamLiveCatalog()+ xtreamBackend.respond(action = "get_vod_categories", body = "[]")+ xtreamBackend.respond(action = "get_series_categories", body = "{}", code = 503)+ assertThat(mgr.sync(1L, force = false).isSuccess).isTrue()+ verify(workScheduler).scheduleXtreamIndex(1L, ContentType.SERIES, false)+ assertThat(xtreamBackend.requestedActions).doesNotContain("get_series")+ }++ @Test+ fun `rejected movie category credentials are not queued for automatic recovery`() = runTest {+ val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)+ stubXtreamLiveCatalog()+ xtreamBackend.respond(action = "get_vod_categories", body = "{}", code = 401)+ xtreamBackend.respond(action = "get_series_categories", body = "[]")+ assertThat(mgr.sync(1L, force = false).isSuccess).isTrue()+ verify(workScheduler, org.mockito.kotlin.never()).scheduleXtreamIndex(1L, ContentType.MOVIE, false)+ val jobs = argumentCaptor<XtreamIndexJobEntity>()+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(jobs.capture())+ assertThat(jobs.allValues.last { it.section == "MOVIE" }.state).isEqualTo("FAILED_PERMANENT")}@Test@@ -1693,6 +1764,24 @@ class SyncManagerTest {).isTrue()}+ @Test+ fun `permanent category rejection replaces previous partial job without queuing continuation`() = runBlocking {+ val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)+ org.mockito.kotlin.whenever(categoryDao.getByProviderAndTypeSync(1L, ContentType.MOVIE.name)).thenReturn(+ listOf(CategoryEntity(categoryId = 42L, name = "Action", type = ContentType.MOVIE, providerId = 1L)))+ org.mockito.kotlin.whenever(xtreamIndexJobDao.get(1L, ContentType.MOVIE.name)).thenReturn(+ XtreamIndexJobEntity(1L, "MOVIE", state = "PARTIAL", totalCategories = 1, failedCategories = 1))+ xtreamBackend.respond(action = "get_vod_streams", body = "{}", code = 401)+ val result = mgr.processQueuedXtreamIndexJobs(1L, ContentType.MOVIE, maxCategoriesPerSection = 2)+ assertThat(xtreamBackend.requestedActions).contains("get_vod_streams")+ val jobs = argumentCaptor<XtreamIndexJobEntity>()+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(jobs.capture())+ com.google.common.truth.Truth.assertWithMessage("Job states/errors: %s", jobs.allValues.map { it.state to it.lastError })+ .that(jobs.allValues.last().state).isEqualTo("FAILED_PERMANENT")+ assertThat(result.isSuccess).isFalse()+ verify(workScheduler, org.mockito.kotlin.never()).scheduleXtreamIndex(1L, ContentType.MOVIE, false)+ }+@Testfun `processQueuedXtreamIndexJobs streams full movie index before category fallback`() = runTest {val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategyTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategyTest.ktindex 96c23c15..e32df346 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategyTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategyTest.kt@@ -42,6 +42,39 @@ import org.mockito.kotlin.wheneverclass SyncManagerXtreamLiveStrategyTest {+ @Test+ fun `bulk authentication rejection does not start category fallback or stage rows`() = verifyBulkRejection(401, 1)++ @Test+ fun `action specific bulk forbidden response still tries category fallback`() = verifyBulkRejection(403, 2)++ private fun verifyBulkRejection(status: Int, expectedRequests: Int) = runBlocking {+ val requests = AtomicInteger()+ val httpService = OkHttpXtreamApiService(+ client = OkHttpClient.Builder().addInterceptor { chain ->+ requests.incrementAndGet()+ Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1)+ .code(status).message("Rejected")+ .body("{}".toResponseBody("application/json".toMediaType())).build()+ }.build(), json = json+ )+ val apiService = FakeXtreamApiService(listOf(XtreamCategory("12", "News")))+ val provider = Provider(id = 42L, name = "Test", type = ProviderType.XTREAM_CODES,+ serverUrl = "https://example.test", username = "user", password = "pass")+ val strategy = createStrategy(apiService, httpService,+ stageChannelItems = { _, _, _, _, _ -> error("Rejected catalog must not be staged") })+ val payload = strategy.syncXtreamLiveCatalog(+ provider, XtreamProvider(provider.id, apiService, provider.serverUrl, provider.username, provider.password),+ SyncMetadata(provider.id), emptySet(), null, testRuntimeProfile(), false+ )+ val failure = payload.catalogResult as CatalogStrategyResult.Failure+ if (status == 401) {+ assertThat(failure.error).isInstanceOf(com.streamvault.data.remote.xtream.XtreamAuthenticationException::class.java)+ }+ assertThat(requests.get()).isEqualTo(expectedRequests)+ assertThat(payload.stagedSessionId).isNull()+ }+private val json = Json {ignoreUnknownKeys = trueisLenient = true@@ -119,7 +152,14 @@ class SyncManagerXtreamLiveStrategyTest {})- val payload = strategy.loadXtreamLiveFull(provider, xtreamProvider, testRuntimeProfile(batchSize = 2))+ val progressMessages = mutableListOf<String>()+ val payload = strategy.loadXtreamLiveFull(+ provider, xtreamProvider, testRuntimeProfile(batchSize = 2),+ onProgress = progressMessages::add+ )++ assertThat(progressMessages.last()).isEqualTo("${XtreamLiveProgressLabels.LOADING}\n1 channel processed")+ assertThat(progressMessages).doesNotContain(XtreamLiveProgressLabels.READY)assertThat(payload.catalogResult).isInstanceOf(CatalogStrategyResult.Success::class.java)assertThat(payload.stagedSessionId).isNotNull()@@ -636,19 +676,18 @@ class SyncManagerXtreamLiveStrategyTest {requestCount.incrementAndGet()val categoryId = chain.request().url.queryParameter("category_id")requestedCategoryIds += categoryId- val body = """- [- {- "num": "9",- "name": "Category Live $categoryId",- "stream_id": "${if (categoryId == "12") "912" else "913"}",- "stream_icon": "https://img.example.test/category-$categoryId.png",- "category_id": "$categoryId",- "category_name": "${if (categoryId == "12") "News" else "Sports"}",- "container_extension": "ts"- }- ]- """.trimIndent()+ val body = if (categoryId == null) {+ """+ [+ {"num":"9","name":"News Live","stream_id":"912","category_id":"12","category_name":"News","container_extension":"ts"},+ {"num":"10","name":"Sports Live","stream_id":"913","category_id":"13","category_name":"Sports","container_extension":"ts"}+ ]+ """.trimIndent()+ } else {+ """+ [{"num":"9","name":"Category Live $categoryId","stream_id":"${if (categoryId == "12") "912" else "913"}","stream_icon":"https://img.example.test/category-$categoryId.png","category_id":"$categoryId","category_name":"${if (categoryId == "12") "News" else "Sports"}","container_extension":"ts"}]+ """.trimIndent()+ }Response.Builder().request(Request.Builder().url(chain.request().url).build()).protocol(Protocol.HTTP_1_1)@@ -733,7 +772,7 @@ class SyncManagerXtreamLiveStrategyTest {)assertThat(restorePayload.stagedAcceptedCount).isEqualTo(2)- assertThat(requestedCategoryIds).containsExactly("12", "13")+ assertThat(requestedCategoryIds).containsExactly(null)Unit}@@ -916,7 +955,7 @@ class SyncManagerXtreamLiveStrategyTest {}@Test- fun `hidden categories skip full catalog even when effective method is stream all`() = runBlocking {+ fun `explicit stream all filters hidden rows and still uses the full catalog`() = runBlocking {val requestCount = AtomicInteger(0)val requestedCategoryIds = mutableListOf<String?>()val httpService = OkHttpXtreamApiService(@@ -925,19 +964,18 @@ class SyncManagerXtreamLiveStrategyTest {requestCount.incrementAndGet()val categoryId = chain.request().url.queryParameter("category_id")requestedCategoryIds += categoryId- val body = """- [- {- "num": "8",- "name": "Visible Live",- "stream_id": "888",- "stream_icon": "https://img.example.test/live.png",- "category_id": "$categoryId",- "category_name": "News",- "container_extension": "m3u8"- }- ]- """.trimIndent()+ val body = if (categoryId == null) {+ """+ [+ {"num":"8","name":"Visible Live","stream_id":"888","category_id":"12","category_name":"News","container_extension":"m3u8"},+ {"num":"9","name":"Hidden Live","stream_id":"999","category_id":"13","category_name":"Sports","container_extension":"m3u8"}+ ]+ """.trimIndent()+ } else {+ """+ [{"num":"8","name":"Visible Live","stream_id":"888","category_id":"$categoryId","category_name":"News","container_extension":"m3u8"}]+ """.trimIndent()+ }Response.Builder().request(Request.Builder().url(chain.request().url).build()).protocol(Protocol.HTTP_1_1)@@ -972,10 +1010,12 @@ class SyncManagerXtreamLiveStrategyTest {password = provider.password,allowedOutputFormats = provider.allowedOutputFormats)+ val stagedStreamIds = mutableListOf<Long>()val strategy = createStrategy(apiService = apiService,httpService = httpService,stageChannelItems = { _, channels, _, _, sessionId ->+ stagedStreamIds += channels.map { it.streamId }StagedCatalogSnapshot(sessionId = sessionId ?: 66L, acceptedCount = channels.size, fallbackCategories = null)})@@ -996,10 +1036,11 @@ class SyncManagerXtreamLiveStrategyTest {)assertThat(payload.catalogResult).isInstanceOf(CatalogStrategyResult.Success::class.java)- assertThat(payload.strategyFeedback.attemptedFullCatalog).isFalse()- assertThat(payload.strategyFeedback.preferredSegmentedFirst).isTrue()+ assertThat(payload.strategyFeedback.attemptedFullCatalog).isTrue()+ assertThat(payload.strategyFeedback.preferredSegmentedFirst).isFalse()assertThat(payload.stagedAcceptedCount).isEqualTo(1)- assertThat(requestedCategoryIds).containsExactly("12")+ assertThat(stagedStreamIds).containsExactly(888L)+ assertThat(requestedCategoryIds).containsExactly(null)assertThat(requestCount.get()).isEqualTo(1)}diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamSupportTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamSupportTest.ktindex fe37d2e2..35baa6e8 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamSupportTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamSupportTest.kt@@ -2,6 +2,7 @@ package com.streamvault.data.syncimport com.google.common.truth.Truth.assertThatimport com.streamvault.data.remote.dto.XtreamCategory+import com.streamvault.data.remote.xtream.XtreamAuthenticationExceptionimport com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport java.io.IOException@@ -12,6 +13,14 @@ import org.junit.Testclass SyncManagerXtreamSupportTest {+ private val provider = Provider(id = 7, name = "Test Xtream", type = ProviderType.XTREAM_CODES,+ serverUrl = "https://example.test")++ private fun failure(id: String, error: Exception): TimedCategoryOutcome<String> {+ val category = XtreamCategory(id, "Category $id")+ return TimedCategoryOutcome(category, CategoryFetchOutcome.Failure(category.categoryName, error), 0)+ }+private val adaptiveSyncPolicy = XtreamAdaptiveSyncPolicy()private val support = SyncManagerXtreamSupport(@@ -88,4 +97,42 @@ class SyncManagerXtreamSupportTest {assertThat(progress).containsExactly("1/1:Sports")assertThat(retried.last().outcome).isInstanceOf(CategoryFetchOutcome.Success::class.java)}++ @Test+ fun `authentication in mixed outcomes prevents all continuation requests`() = runTest {+ val original = listOf(failure("1", IOException("timeout")),+ failure("2", XtreamAuthenticationException(401, "authentication")))+ var requests = 0+ var progress = 0+ val result = support.continueFailedCategoryOutcomes(provider, original, fetchSequentially = { category ->+ requests+++ TimedCategoryOutcome(category, CategoryFetchOutcome.Empty(category.categoryName), 0)+ }, onCategoryRetried = { _, _, _ -> progress++ })+ assertThat(requests).isEqualTo(0)+ assertThat(progress).isEqualTo(0)+ assertThat(result).isSameInstanceAs(original)+ }++ @Test+ fun `authentication during continuation stops admissions and keeps completed and untouched outcomes`() = runTest {+ val completed = TimedCategoryOutcome(XtreamCategory("0", "Completed"),+ CategoryFetchOutcome.Success("Completed", listOf("retained")), 0)+ val original = listOf(completed, failure("1", IOException("timeout")),+ failure("2", IOException("timeout")), failure("3", IOException("timeout")))+ val requests = mutableListOf<String>()+ val progress = mutableListOf<Int>()+ val authentication = XtreamAuthenticationException(401, "authentication")+ val result = support.continueFailedCategoryOutcomes(provider, original, fetchSequentially = { category ->+ requests += category.categoryId+ if (category.categoryId == "1") {+ TimedCategoryOutcome(category, CategoryFetchOutcome.Success(category.categoryName, listOf("retried")), 0)+ } else failure(category.categoryId, authentication)+ }, onCategoryRetried = { current, _, _ -> progress += current })+ assertThat(requests).containsExactly("1", "2").inOrder()+ assertThat(progress).containsExactly(1, 2).inOrder()+ assertThat(result[0]).isSameInstanceAs(completed)+ assertThat(result[1].outcome).isInstanceOf(CategoryFetchOutcome.Success::class.java)+ assertThat((result[2].outcome as CategoryFetchOutcome.Failure).error).isSameInstanceAs(authentication)+ assertThat(result[3]).isSameInstanceAs(original[3])+ }}diff --git a/data/src/test/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutorTest.kt b/data/src/test/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutorTest.ktindex eb89ee39..7f289b31 100644--- a/data/src/test/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutorTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutorTest.kt@@ -17,6 +17,36 @@ import org.junit.Testimport org.mockito.kotlin.mockclass XtreamIncrementalIndexExecutorTest {+ @Test+ fun `authentication rejected full summary does not fetch categories or schedule continuation`() = runTest {+ val rejection = com.streamvault.data.remote.xtream.XtreamAuthenticationException(401, "Rejected")+ val operations = FakeOperations(listOf(category(1L)), streamMovieResult = Result.error("Rejected", rejection))+ try {+ XtreamIncrementalIndexExecutor(operations).processSummary(provider(), mock(), ContentType.MOVIE, 2, onProgress = null)+ error("Expected authentication rejection")+ } catch (error: com.streamvault.data.remote.xtream.XtreamAuthenticationException) {+ assertThat(error).isSameInstanceAs(rejection)+ }+ assertThat(operations.fetchedCategoryIds).isEmpty()+ assertThat(operations.scheduled).isEmpty()+ assertThat(operations.updates.none { it.state == "QUEUED" }).isTrue()+ }++ @Test+ fun `authentication rejected category stops cursor and does not schedule continuation`() = runTest {+ val rejection = com.streamvault.data.remote.xtream.XtreamAuthenticationException(401, "Rejected")+ val operations = FakeOperations(listOf(category(1L), category(2L)),+ streamMovieResult = Result.error("Unavailable"), failureCategoryId = 1L, categoryFailure = rejection)+ try {+ XtreamIncrementalIndexExecutor(operations).processSummary(provider(), mock(), ContentType.MOVIE, 2, onProgress = null)+ error("Expected authentication rejection")+ } catch (error: com.streamvault.data.remote.xtream.XtreamAuthenticationException) {+ assertThat(error).isSameInstanceAs(rejection)+ }+ assertThat(operations.fetchedCategoryIds).containsExactly(1L)+ assertThat(operations.scheduled).isEmpty()+ assertThat(operations.updates.none { (it.nextCategoryIndex ?: 0) > 0 }).isTrue()+ }@Testfun `successful full stream completes section and publishes metadata`() = runTest {val operations = FakeOperations(@@ -156,17 +186,83 @@ class XtreamIncrementalIndexExecutorTest {assertThat(operations.updates.last().failedCategories).isEqualTo(0)}+ @Test+ fun `row budget stops after a committed category and resumes from its durable cursor`() = runTest {+ val operations = FakeOperations(+ categories = listOf(category(1L), category(2L), category(3L)),+ job = XtreamIndexJobEntity(+ providerId = 1L,+ section = ContentType.MOVIE.name,+ state = "QUEUED"+ ),+ streamMovieResult = Result.error("stream unavailable"),+ movieRowsByCategory = mapOf(1L to 3, 2L to 2)+ )++ XtreamIncrementalIndexExecutor(operations).processSummary(+ provider = provider(),+ api = mock(),+ contentType = ContentType.MOVIE,+ maxCategories = 10,+ maxRowsPerSlice = 4,+ onProgress = null+ )++ assertThat(operations.fetchedCategoryIds).containsExactly(1L, 2L).inOrder()+ assertThat(operations.updates.last().state).isEqualTo("QUEUED")+ assertThat(operations.updates.last().nextCategoryIndex).isEqualTo(2)+ assertThat(operations.updates.last().completedCategories).isEqualTo(2)+ assertThat(operations.updates.last().indexedRows).isEqualTo(5)+ assertThat(operations.scheduled).containsExactly(ContentType.MOVIE)+ }++ @Test+ fun `duration budget stops only after current category checkpoint is persisted`() = runTest {+ val operations = FakeOperations(+ categories = listOf(category(1L), category(2L)),+ job = XtreamIndexJobEntity(+ providerId = 1L,+ section = ContentType.MOVIE.name,+ state = "QUEUED"+ ),+ streamMovieResult = Result.error("stream unavailable"),+ movieRowsByCategory = mapOf(1L to 1, 2L to 1),+ categoryDurationMillis = 6_000L+ )++ XtreamIncrementalIndexExecutor(operations).processSummary(+ provider = provider(),+ api = mock(),+ contentType = ContentType.MOVIE,+ maxCategories = 10,+ maxDurationMillis = 5_000L,+ onProgress = null+ )++ assertThat(operations.fetchedCategoryIds).containsExactly(1L)+ assertThat(operations.updates.last().state).isEqualTo("QUEUED")+ assertThat(operations.updates.last().nextCategoryIndex).isEqualTo(1)+ assertThat(operations.updates.last().completedCategories).isEqualTo(1)+ assertThat(operations.scheduled).containsExactly(ContentType.MOVIE)+ }+private class FakeOperations(private val categories: List<CategoryEntity>,private val job: XtreamIndexJobEntity? = null,private val streamMovieResult: Result<Int> = Result.success(0),private val failureCategoryId: Long? = null,- private val cancelCategoryId: Long? = null+ private val categoryFailure: Throwable = IOException("category failed"),+ private val cancelCategoryId: Long? = null,+ private val movieRowsByCategory: Map<Long, Int> = emptyMap(),+ private val categoryDurationMillis: Long = 1L) : XtreamIncrementalIndexOperations {val updates = mutableListOf<CatalogIndexJobUpdate>()val fetchedCategoryIds = mutableListOf<Long>()val metadataUpdates = mutableListOf<Any>()val scheduled = mutableListOf<ContentType>()+ private var elapsedRealtimeMillis = 0L++ override fun monotonicTimeMillis() = elapsedRealtimeMillisoverride suspend fun getCategories(providerId: Long, contentType: ContentType) = categories@@ -194,10 +290,29 @@ class XtreamIncrementalIndexExecutorTest {if (category.categoryId == failureCategoryId) {return TimedCategoryOutcome(category = category.asXtreamCategory(),- outcome = CategoryFetchOutcome.Failure(category.name, IOException("category failed")),+ outcome = CategoryFetchOutcome.Failure(category.name, categoryFailure),elapsedMs = 1L)}+ val rowCount = movieRowsByCategory[category.categoryId] ?: 0+ elapsedRealtimeMillis += categoryDurationMillis+ if (rowCount > 0) {+ val items = List(rowCount) { index ->+ val streamId = category.categoryId * 1_000L + index + 1L+ Movie(+ id = streamId,+ name = "Movie $streamId",+ streamId = streamId,+ providerId = 1L,+ categoryId = category.categoryId+ )+ }+ return TimedCategoryOutcome(+ category = category.asXtreamCategory(),+ outcome = CategoryFetchOutcome.Success(category.name, items, rowCount),+ elapsedMs = categoryDurationMillis+ )+ }return TimedCategoryOutcome(category = category.asXtreamCategory(),outcome = CategoryFetchOutcome.Empty(category.name),diff --git a/data/src/test/java/com/streamvault/data/sync/XtreamIndexWorkerTest.kt b/data/src/test/java/com/streamvault/data/sync/XtreamIndexWorkerTest.ktnew file mode 100644index 00000000..abca43ad--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/XtreamIndexWorkerTest.kt@@ -0,0 +1,25 @@+package com.streamvault.data.sync++import androidx.work.ListenableWorker+import com.google.common.truth.Truth.assertThat+import org.junit.Test++class XtreamIndexWorkerTest {+ @Test+ fun `recorded permanent section failure releases appended provider work`() {+ assertThat(xtreamIndexWorkResult(7L, false, true))+ .isInstanceOf(ListenableWorker.Result.Success::class.java)+ }++ @Test+ fun `transient failure keeps backoff even alongside a permanent failure`() {+ assertThat(xtreamIndexWorkResult(7L, true, true))+ .isInstanceOf(ListenableWorker.Result.Retry::class.java)+ }++ @Test+ fun `standalone periodic batch reports permanent failure`() {+ assertThat(xtreamIndexWorkResult(-1L, false, true))+ .isInstanceOf(ListenableWorker.Result.Failure::class.java)+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/XtreamLiveAttemptIsolationTest.kt b/data/src/test/java/com/streamvault/data/sync/XtreamLiveAttemptIsolationTest.ktindex aee5417f..0dce89fa 100644--- a/data/src/test/java/com/streamvault/data/sync/XtreamLiveAttemptIsolationTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/XtreamLiveAttemptIsolationTest.kt@@ -17,8 +17,12 @@ import com.streamvault.domain.model.SyncMetadataimport java.util.concurrent.CountDownLatchimport java.util.concurrent.TimeUnitimport java.util.concurrent.atomic.AtomicInteger+import java.io.IOExceptionimport kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.awaitCancellationimport kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeoutimport kotlinx.serialization.json.Jsonimport okhttp3.MediaType.Companion.toMediaTypeimport okhttp3.OkHttpClient@@ -31,6 +35,12 @@ import org.junit.Testimport org.junit.runner.RunWithimport org.robolectric.RobolectricTestRunnerimport org.robolectric.RuntimeEnvironment+import org.mockito.kotlin.any+import org.mockito.kotlin.anyOrNull+import org.mockito.kotlin.doSuspendableAnswer+import org.mockito.kotlin.mock+import org.mockito.kotlin.whenever+import com.streamvault.data.remote.xtream.XtreamAuthenticationException@RunWith(RobolectricTestRunner::class)class XtreamLiveAttemptIsolationTest {@@ -180,6 +190,153 @@ class XtreamLiveAttemptIsolationTest {assertThat(totalStages()).isEqualTo(0)}+ @Test+ fun `local writer failure discards completed and unfinished stages without retrying or changing active catalog`() = runBlocking<Unit> {+ db.channelDao().insertAll(listOf(ChannelEntity(streamId = 900, name = "Existing", providerId = provider.id)))+ val requests = AtomicInteger()+ val error = IOException("network connection failed in local writer")+ val policy = XtreamAdaptiveSyncPolicy()+ val (strategy, api) = engine(policy = policy, beforeStage = { channels ->+ if (channels.any { it.streamId == 202L }) throw error+ }) { category ->+ requests.incrementAndGet()+ if (category == "1") array(row(101)) else array(row(201, category = 2), row(202, category = 2))+ }+ val failure = runCatching {+ strategy.loadXtreamLiveByCategory(provider, api, categories(), null, true, profile())+ }.exceptionOrNull()+ assertThat(failure).isInstanceOf(error.javaClass)+ assertThat(failure).hasMessageThat().isEqualTo(error.message)+ assertThat(requests.get()).isEqualTo(2)+ assertThat(totalStages()).isEqualTo(0)+ assertThat(db.channelDao().getByProviderSync(provider.id).map { it.streamId }).containsExactly(900L)+ assertThat(policy.concurrencyFor(provider.id, 10, false, XtreamAdaptiveSyncPolicy.Stage.LIVE_CATEGORY)).isEqualTo(2)+ }++ @Test+ fun `real category writer failure cancels and joins its sibling before cleanup`() = runBlocking<Unit> {+ val siblingEntered = CompletableDeferred<Unit>()+ val siblingJoined = CompletableDeferred<Unit>()+ val requests = AtomicInteger()+ val error = IllegalStateException("writer invariant broken")+ val (strategy, api) = engine(beforeStage = { channels ->+ if (channels.single().streamId == 101L) {+ siblingEntered.await()+ throw error+ } else {+ try {+ siblingEntered.complete(Unit)+ awaitCancellation()+ } finally {+ siblingJoined.complete(Unit)+ }+ }+ }) { category ->+ requests.incrementAndGet()+ array(row(if (category == "1") 101 else 202, category = category!!.toInt()))+ }+ val failure = runCatching {+ withTimeout(5_000) {+ strategy.loadXtreamLiveByCategory(provider, api, manyCategories(), null, false,+ profile().copy(maxCategoryConcurrency = 2))+ }+ }.exceptionOrNull()+ assertThat(failure).isInstanceOf(error.javaClass)+ assertThat(failure).hasMessageThat().isEqualTo(error.message)+ assertThat(siblingJoined.isCompleted).isTrue()+ assertThat(requests.get()).isEqualTo(2)+ assertThat(totalStages()).isEqualTo(0)+ }++ @Test+ fun `legacy decoder writer failure does not restart the category request`() = runBlocking<Unit> {+ val requests = AtomicInteger()+ val error = IOException("database write failed")+ val (strategy, api) = engine(beforeStage = { throw error }) {+ if (requests.incrementAndGet() == 1) "{}" else array(row(101))+ }+ val failure = runCatching {+ strategy.loadXtreamLiveByCategory(provider, api, categories(), null, true, profile())+ }.exceptionOrNull()+ assertThat(failure).isInstanceOf(error.javaClass)+ assertThat(failure).hasMessageThat().isEqualTo(error.message)+ assertThat(requests.get()).isEqualTo(2)+ assertThat(totalStages()).isEqualTo(0)+ }++ @Test+ fun `local attempt reset failure escapes before any HTTP request`() = runBlocking<Unit> {+ val requests = AtomicInteger()+ val http = OkHttpXtreamApiService(OkHttpClient.Builder().addInterceptor {+ requests.incrementAndGet()+ error("HTTP must not start after a local reset failure")+ }.build(), Json { ignoreUnknownKeys = true })+ val api = XtreamProvider(provider.id, http, provider.serverUrl, provider.username, provider.password)+ val policy = XtreamAdaptiveSyncPolicy()+ val support = SyncManagerXtreamSupport(policy, { false }, { it?.message.orEmpty() },+ { _, _, _ -> }, 60_000, 60_000, "stopped")+ val fetcher = SyncManagerXtreamFetcher(http, http, support, { it?.message.orEmpty() })+ val failure = runCatching {+ fetcher.fetchLiveCategoryOutcome(provider, api, categories().first(), onAttemptReset = {+ throw IOException("local reset failed")+ })+ }.exceptionOrNull()+ assertThat(failure).isInstanceOf(IOException::class.java)+ assertThat(failure).hasMessageThat().isEqualTo("local reset failed")+ assertThat(requests.get()).isEqualTo(0)+ }++ @Test+ fun `live strategy does not restart requests after the coordinator aborts for stress`() = runBlocking<Unit> {+ for (categoryCount in listOf(4, 6)) {+ val requests = AtomicInteger()+ val fetcher = mock<SyncManagerXtreamFetcher>()+ whenever(fetcher.fetchLiveCategoryOutcome(any(), any(), any(), anyOrNull(), anyOrNull(), any()))+ .doSuspendableAnswer { invocation ->+ requests.incrementAndGet()+ val category = invocation.getArgument<XtreamCategory>(2)+ TimedCategoryOutcome<com.streamvault.domain.model.Channel>(category,+ CategoryFetchOutcome.Failure(category.categoryName, IOException("timeout")), 0)+ }+ val (strategy, api) = engine(fetcherOverride = fetcher, shouldRememberStress = { it is IOException }) {+ error("mocked category outcome must not use HTTP")+ }+ val result = strategy.loadXtreamLiveByCategory(provider, api, manyCategories().take(categoryCount), null, false,+ profile().copy(maxCategoryConcurrency = 2))+ assertThat(result.catalogResult).isInstanceOf(CatalogStrategyResult.Failure::class.java)+ if (categoryCount == 6) {+ assertThat((result.catalogResult as CatalogStrategyResult.Failure).warnings).contains("Live TV stopped")+ }+ assertThat(requests.get()).isEqualTo(4)+ assertThat(totalStages()).isEqualTo(0)+ }+ }++ @Test+ fun `live strategy drains mixed authentication failure without starting continuation`() = runBlocking<Unit> {+ val authenticationProcessed = CompletableDeferred<Unit>()+ val requests = AtomicInteger()+ val fetcher = mock<SyncManagerXtreamFetcher>()+ whenever(fetcher.fetchLiveCategoryOutcome(any(), any(), any(), anyOrNull(), anyOrNull(), any()))+ .doSuspendableAnswer { invocation ->+ requests.incrementAndGet()+ val category = invocation.getArgument<XtreamCategory>(2)+ val error = if (category.categoryId == "1") XtreamAuthenticationException(401, "authentication")+ else { authenticationProcessed.await(); IOException("timeout") }+ TimedCategoryOutcome<com.streamvault.domain.model.Channel>(category,+ CategoryFetchOutcome.Failure(category.categoryName, error), 0)+ }+ val (strategy, api) = engine(fetcherOverride = fetcher) { error("must not use HTTP") }+ val result = withTimeout(5_000) {+ strategy.loadXtreamLiveByCategory(provider, api, manyCategories(), { message ->+ if (message == "Downloading Live TV by category 1/6...") authenticationProcessed.complete(Unit)+ }, false, profile().copy(maxCategoryConcurrency = 2))+ }+ assertThat(result.catalogResult).isInstanceOf(CatalogStrategyResult.Failure::class.java)+ assertThat(requests.get()).isEqualTo(2)+ assertThat(totalStages()).isEqualTo(0)+ }+@Testfun `sealed snapshot and metadata survive closing the database before promotion`() = runBlocking<Unit> {val context = RuntimeEnvironment.getApplication()@@ -239,10 +396,13 @@ class XtreamLiveAttemptIsolationTest {private fun array(vararg rows: String) = rows.joinToString(",", "[", "]")private fun categories() = listOf(XtreamCategory("1", "One"), XtreamCategory("2", "Two"))+ private fun manyCategories() = (1..6).map { XtreamCategory("$it", "Category $it") }private suspend fun engine(failWriter: Boolean = false, failOnStreamId: Long? = null,primeCategories: Boolean = true, categoryStatus: Int = 200, categoryResponse: (() -> String)? = null,policy: XtreamAdaptiveSyncPolicy = XtreamAdaptiveSyncPolicy(),+ fetcherOverride: SyncManagerXtreamFetcher? = null,+ shouldRememberStress: (Throwable) -> Boolean = { false },beforeStage: suspend (List<com.streamvault.domain.model.Channel>) -> Unit = {},response: (String?) -> String): Pair<SyncManagerXtreamLiveStrategy, XtreamProvider> {val http = OkHttpXtreamApiService(OkHttpClient.Builder().addInterceptor { chain ->@@ -255,10 +415,11 @@ class XtreamLiveAttemptIsolationTest {if (primeCategories) api.mapCategories(ContentType.LIVE, categories())val progress: (Long, ((String) -> Unit)?, String) -> Unit = { _, callback, label -> callback?.invoke(label) }val sanitize: (Throwable?) -> String = { it?.javaClass?.simpleName.orEmpty() }- val support = SyncManagerXtreamSupport(policy, { false }, sanitize, progress, 60_000, 60_000, "stopped")+ val support = SyncManagerXtreamSupport(policy, shouldRememberStress, sanitize, progress, 60_000, 60_000, "stopped")val stager = SyncManagerCatalogStager(store, 1)- return SyncManagerXtreamLiveStrategy(http, http, policy, support, SyncManagerXtreamFetcher(http, http, support, sanitize),- SyncManagerCatalogStrategySupport({ false }, 60_000), store, progress, sanitize,+ return SyncManagerXtreamLiveStrategy(http, http, policy, support,+ fetcherOverride ?: SyncManagerXtreamFetcher(http, http, support, sanitize),+ SyncManagerCatalogStrategySupport(shouldRememberStress, 60_000), store, progress, sanitize,{ _, _ -> "full failed" }, { _, _, _ -> "category failed" }, "sequential", stageChannelItems = { id, channels, seen, collector, session ->beforeStage(channels)if (failWriter || channels.any { it.streamId == failOnStreamId }) throw ProviderWorkflowSupersededException(id, 1)diff --git a/data/src/test/java/com/streamvault/data/sync/XtreamLiveCategorySchedulingTest.kt b/data/src/test/java/com/streamvault/data/sync/XtreamLiveCategorySchedulingTest.ktindex 82f62144..31aad94a 100644--- a/data/src/test/java/com/streamvault/data/sync/XtreamLiveCategorySchedulingTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/XtreamLiveCategorySchedulingTest.kt@@ -51,6 +51,7 @@ class XtreamLiveCategorySchedulingTest {}, refillWorkers = true)assertThat(started).containsExactly("1", "2")assertThat(plan.outcomes).hasSize(2)+ assertThat(plan.stopReason).isEqualTo(CategoryExecutionStopReason.AUTHENTICATION)var retries = 0support().continueFailedCategoryOutcomes(provider, plan.outcomes, { retries++; it.let { category ->TimedCategoryOutcome<String>(category, CategoryFetchOutcome.Empty(category.categoryName), 0)@@ -93,6 +94,24 @@ class XtreamLiveCategorySchedulingTest {assertThat(started).isLessThan(categories.size)assertThat(plan.outcomes).hasSize(started)assertThat(plan.warnings).containsExactly("sequential", "Live aborted")+ assertThat(plan.stopReason).isEqualTo(CategoryExecutionStopReason.PROVIDER_STRESS)+ val beforeContinuation = started+ support().continueFailedCategoryOutcomes(provider, plan.outcomes, fetchSequentially = { category ->+ started+++ TimedCategoryOutcome(category, CategoryFetchOutcome.Empty(category.categoryName), 0)+ }, stopReason = plan.stopReason)+ assertThat(started).isEqualTo(beforeContinuation)+ }++ @Test+ fun `stress on the final category remains a terminal continuation stop`() = runTest {+ val plan = support().executeCategoryRecoveryPlan(provider, categories.take(4), 2,+ "Live", "sequential", null, fetch = { category ->+ TimedCategoryOutcome<String>(category,+ CategoryFetchOutcome.Failure(category.categoryName, java.io.IOException("timeout")), 0)+ }, refillWorkers = true)+ assertThat(plan.outcomes).hasSize(4)+ assertThat(plan.stopReason).isEqualTo(CategoryExecutionStopReason.PROVIDER_STRESS)}@Testdiff --git a/data/src/test/java/com/streamvault/data/sync/XtreamLiveLoadingProgressTest.kt b/data/src/test/java/com/streamvault/data/sync/XtreamLiveLoadingProgressTest.ktnew file mode 100644index 00000000..2471ec9a--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/XtreamLiveLoadingProgressTest.kt@@ -0,0 +1,35 @@+package com.streamvault.data.sync++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class XtreamLiveLoadingProgressTest {+ @Test+ fun `batch notifications are throttled and final drained count is retained`() {+ var now = 0L+ val messages = mutableListOf<String>()+ val progress = XtreamLiveLoadingProgress({ now }, messages::add)+ progress.startAttempt()+ progress.batchStaged(100)+ now = 100L+ progress.batchStaged(200)+ progress.readerDrained(250)+ assertThat(messages).hasSize(3)+ assertThat(messages.last()).endsWith("250 channels processed")+ assertThat(messages.none { it.contains("ready", ignoreCase = true) || it.contains('%') }).isTrue()+ progress.readerDrained(250)+ assertThat(messages).hasSize(3)+ }++ @Test+ fun `retry clears discarded attempt count and immediately shows new staged rows`() {+ val messages = mutableListOf<String>()+ val progress = XtreamLiveLoadingProgress({ 0L }, messages::add)+ progress.startAttempt()+ progress.batchStaged(900)+ progress.startAttempt()+ progress.batchStaged(100)+ assertThat(messages[2]).isEqualTo(XtreamLiveProgressLabels.LOADING)+ assertThat(messages.last()).endsWith("100 channels processed")+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/XtreamLiveSyncPolicyTest.kt b/data/src/test/java/com/streamvault/data/sync/XtreamLiveSyncPolicyTest.ktindex fd62f2ba..d65cb6af 100644--- a/data/src/test/java/com/streamvault/data/sync/XtreamLiveSyncPolicyTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/XtreamLiveSyncPolicyTest.kt@@ -7,7 +7,7 @@ import org.junit.Testclass XtreamLiveSyncPolicyTest {@Test- fun `auto uses category by category for low devices`() {+ fun `production auto uses bulk on low tier when memory is healthy`() {val method = XtreamLiveSyncPolicy.resolve(userMode = ProviderXtreamLiveSyncMode.AUTO,runtimeProfile = runtimeProfile(DeviceSyncTier.LOW),@@ -17,11 +17,11 @@ class XtreamLiveSyncPolicyTest {hiddenLiveCategoryIds = emptySet())- assertThat(method).isEqualTo(EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORY)+ assertThat(method).isEqualTo(EffectiveXtreamLiveSyncMethod.STREAM_ALL)}@Test- fun `auto uses category by category for manual and background sync`() {+ fun `production auto uses bulk for manual and background sync`() {val profile = runtimeProfile(DeviceSyncTier.HIGH)val metadata = SyncMetadata(providerId = 1L)@@ -34,7 +34,7 @@ class XtreamLiveSyncPolicyTest {now = 1_000L,hiddenLiveCategoryIds = emptySet())- ).isEqualTo(EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORY)+ ).isEqualTo(EffectiveXtreamLiveSyncMethod.STREAM_ALL)assertThat(XtreamLiveSyncPolicy.resolve(@@ -45,7 +45,7 @@ class XtreamLiveSyncPolicyTest {now = 1_000L,hiddenLiveCategoryIds = emptySet())- ).isEqualTo(EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORY)+ ).isEqualTo(EffectiveXtreamLiveSyncMethod.STREAM_ALL)}@Test@@ -91,14 +91,15 @@ class XtreamLiveSyncPolicyTest {}@Test- fun `auto uses category by category when hidden categories exist`() {+ fun `production auto uses categories when most known live rows are hidden`() {val method = XtreamLiveSyncPolicy.resolve(userMode = ProviderXtreamLiveSyncMode.AUTO,runtimeProfile = runtimeProfile(DeviceSyncTier.HIGH),syncReason = XtreamLiveSyncReason.FOREGROUND,metadata = SyncMetadata(providerId = 1L),now = 1_000L,- hiddenLiveCategoryIds = setOf(42L)+ hiddenLiveCategoryIds = setOf(42L),+ hiddenLiveChannelFraction = 0.75f)assertThat(method).isEqualTo(EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORY)@@ -119,7 +120,7 @@ class XtreamLiveSyncPolicyTest {}@Test- fun `auto uses category by category when provider stress is remembered`() {+ fun `production auto retries bulk when category stress is remembered`() {val method = XtreamLiveSyncPolicy.resolve(userMode = ProviderXtreamLiveSyncMode.AUTO,runtimeProfile = runtimeProfile(DeviceSyncTier.HIGH),@@ -133,11 +134,11 @@ class XtreamLiveSyncPolicyTest {hiddenLiveCategoryIds = emptySet())- assertThat(method).isEqualTo(EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORY)+ assertThat(method).isEqualTo(EffectiveXtreamLiveSyncMethod.STREAM_ALL)}@Test- fun `auto uses category by category for segmented onboarding preference`() {+ fun `production auto uses bulk for segmented onboarding preference`() {val method = XtreamLiveSyncPolicy.resolve(userMode = ProviderXtreamLiveSyncMode.AUTO,runtimeProfile = runtimeProfile(@@ -150,13 +151,108 @@ class XtreamLiveSyncPolicyTest {hiddenLiveCategoryIds = emptySet())+ assertThat(method).isEqualTo(EffectiveXtreamLiveSyncMethod.STREAM_ALL)+ }++ @Test+ fun `production bulk first auto prefers bulk across device tiers and entry points`() {+ DeviceSyncTier.entries.forEach { tier ->+ XtreamLiveSyncReason.entries.forEach { reason ->+ assertThat(+ XtreamLiveSyncPolicy.resolve(+ userMode = ProviderXtreamLiveSyncMode.AUTO,+ runtimeProfile = runtimeProfile(tier),+ syncReason = reason,+ metadata = SyncMetadata(providerId = 1L),+ now = 1_000L,+ hiddenLiveCategoryIds = emptySet()+ )+ ).isEqualTo(EffectiveXtreamLiveSyncMethod.STREAM_ALL)+ }+ }+ }++ @Test+ fun `bulk first auto distinguishes hidden coverage and remembered category stress`() {+ val candidate = runtimeProfile(DeviceSyncTier.MID, bulkFirstAutoEnabled = true)+ val base = SyncMetadata(providerId = 1L, liveSequentialFailuresRemembered = true)++ assertThat(+ XtreamLiveSyncPolicy.resolve(+ userMode = ProviderXtreamLiveSyncMode.AUTO,+ runtimeProfile = candidate,+ syncReason = XtreamLiveSyncReason.MANUAL_SETTINGS,+ metadata = base,+ now = 1_000L,+ hiddenLiveCategoryIds = setOf(13L),+ hiddenLiveChannelFraction = 0.10f+ )+ ).isEqualTo(EffectiveXtreamLiveSyncMethod.STREAM_ALL)++ assertThat(+ XtreamLiveSyncPolicy.resolve(+ userMode = ProviderXtreamLiveSyncMode.AUTO,+ runtimeProfile = candidate,+ syncReason = XtreamLiveSyncReason.BACKGROUND_STALE,+ metadata = base,+ now = 1_000L,+ hiddenLiveCategoryIds = setOf(13L),+ hiddenLiveChannelFraction = 0.75f+ )+ ).isEqualTo(EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORY)++ assertThat(+ XtreamLiveSyncPolicy.resolve(+ userMode = ProviderXtreamLiveSyncMode.AUTO,+ runtimeProfile = candidate,+ syncReason = XtreamLiveSyncReason.FOREGROUND,+ metadata = base.copy(liveAvoidFullUntil = 2_000L),+ now = 1_000L,+ hiddenLiveCategoryIds = emptySet()+ )+ ).isEqualTo(EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORY)+ }++ @Test+ fun `bulk first auto falls back to categories during actual low memory`() {+ val method = XtreamLiveSyncPolicy.resolve(+ userMode = ProviderXtreamLiveSyncMode.AUTO,+ runtimeProfile = runtimeProfile(+ tier = DeviceSyncTier.HIGH,+ currentlyLowMemory = true,+ bulkFirstAutoEnabled = true+ ),+ syncReason = XtreamLiveSyncReason.FOREGROUND,+ metadata = SyncMetadata(providerId = 1L),+ now = 1_000L,+ hiddenLiveCategoryIds = emptySet()+ )++ assertThat(method).isEqualTo(EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORY)+ }++ @Test+ fun `benchmark can opt out to compare the previous auto policy`() {+ val method = XtreamLiveSyncPolicy.resolve(+ userMode = ProviderXtreamLiveSyncMode.AUTO,+ runtimeProfile = runtimeProfile(+ tier = DeviceSyncTier.HIGH,+ bulkFirstAutoEnabled = false+ ),+ syncReason = XtreamLiveSyncReason.MANUAL_SETTINGS,+ metadata = SyncMetadata(providerId = 1L),+ now = 1_000L,+ hiddenLiveCategoryIds = emptySet()+ )+assertThat(method).isEqualTo(EffectiveXtreamLiveSyncMethod.CATEGORY_BY_CATEGORY)}private fun runtimeProfile(tier: DeviceSyncTier,currentlyLowMemory: Boolean = false,- preferSegmentedLiveOnboarding: Boolean = false+ preferSegmentedLiveOnboarding: Boolean = false,+ bulkFirstAutoEnabled: Boolean = true): CatalogSyncRuntimeProfile = CatalogSyncRuntimeProfile(tier = tier,stageBatchSize = when (tier) {@@ -186,6 +282,7 @@ class XtreamLiveSyncPolicyTest {manufacturer = "test",model = "test",sdkInt = 35- )+ ),+ bulkFirstAutoEnabled = bulkFirstAutoEnabled)}diff --git a/data/src/test/java/com/streamvault/data/sync/XtreamSummaryFingerprintTest.kt b/data/src/test/java/com/streamvault/data/sync/XtreamSummaryFingerprintTest.ktnew file mode 100644index 00000000..75d4f215--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/XtreamSummaryFingerprintTest.kt@@ -0,0 +1,53 @@+package com.streamvault.data.sync++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.entity.MovieEntity+import com.streamvault.data.local.entity.SeriesEntity+import org.junit.Test++class XtreamSummaryFingerprintTest {+ @Test+ fun `movie fingerprint tracks summary while ignoring local watch and hydration state`() {+ val summary = MovieEntity(+ streamId = 42L,+ providerId = 7L,+ name = "Example",+ posterUrl = "poster.jpg",+ categoryId = 3L,+ categoryName = "Movies"+ )++ assertThat(XtreamSummaryFingerprint.movie(summary.copy(+ watchProgress = 90_000L,+ watchCount = 3,+ lastWatchedAt = 123L,+ isUserProtected = true,+ cacheState = "DETAIL_HYDRATED",+ detailHydratedAt = 456L,+ remoteStaleAt = 789L,+ playbackMetadataJson = "{\"userAgent\":\"custom\"}"+ ))).isEqualTo(XtreamSummaryFingerprint.movie(summary))+ assertThat(XtreamSummaryFingerprint.movie(summary.copy(name = "Renamed")))+ .isNotEqualTo(XtreamSummaryFingerprint.movie(summary))+ }++ @Test+ fun `series fingerprint ignores local protection and hydration timestamps`() {+ val summary = SeriesEntity(+ seriesId = 84L,+ providerId = 7L,+ providerSeriesId = "84",+ name = "Example Series",+ categoryId = 5L+ )++ assertThat(XtreamSummaryFingerprint.series(summary.copy(+ isUserProtected = true,+ cacheState = "DETAIL_HYDRATED",+ detailHydratedAt = 456L,+ remoteStaleAt = 789L+ ))).isEqualTo(XtreamSummaryFingerprint.series(summary))+ assertThat(XtreamSummaryFingerprint.series(summary.copy(name = "Renamed Series")))+ .isNotEqualTo(XtreamSummaryFingerprint.series(summary))+ }+}diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 6f5177b7..d4e23216 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -11,6 +11,7 @@ All notable product changes are recorded in this document.### Fixed+- Fixed successful new-provider setup staying on Add Provider; new providers now navigate to Home, while edits return to the previous screen.- Fixed repeated stream restarts during network outages and unnecessary recovery from nonfatal audio errors.- Fixed stalled live playback recovery to refresh the live window without interrupting active network retries.- Fixed adaptive playback failing to try another available rendition after eligible server or missing-segment errors.@@ -27,6 +28,9 @@ All notable product changes are recorded in this document.### Changed+- 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.+- Reduced repeated Xtream movie/series summary work with fingerprint checks and bounded resumable indexing; prioritized catalog work before guide refreshes and coalesced duplicate imports.- Improved playback buffer memory limits based on stream bitrate, device memory, and multiview usage.- Prioritized active playback over adjacent-item preloading and removed startup thumbnail warmup.- Improved seek previews with request-header support and cancellation when seeking or leaving the player.diff --git a/docs/XTREAM_SYNC_BENCHMARK.md b/docs/XTREAM_SYNC_BENCHMARK.mdindex c185b240..d75fbdb0 100644--- a/docs/XTREAM_SYNC_BENCHMARK.md+++ b/docs/XTREAM_SYNC_BENCHMARK.md@@ -1,8 +1,10 @@-# Xtream live sync benchmark+# Xtream sync benchmark-This is the first implementation package of the-[improvement plan](XTREAM_SYNC_IMPROVEMENT_PLAN.md). It measures the current-engine before changing its defaults, decoding, concurrency or commit behavior.+This guide documents the benchmark harness for the+[Xtream sync improvement plan](XTREAM_SYNC_IMPROVEMENT_PLAN.md). Initial runs+captured the pre-change engine; the current branch's ordinary app now uses+bulk-first AUTO, while the isolated benchmark build keeps a policy override for+repeatable comparisons.## Run on the connected emulator@@ -25,6 +27,14 @@ run, use `--cleanup-run <exact run token from report.json>`. The instrumentationchecks that token, normalized benchmark name and local endpoint before removingthat one provider; otherwise resolve it in the benchmark app before rerunning.+On this branch, ordinary `com.streamvault.app.debug` builds use bulk-first+`AUTO` by default; the isolated benchmark package retains its explicit policy+override for comparisons. To build the ordinary x86_64-compatible APK for+manual provider testing, use `:app:assembleDebug -PcompatAbi=x86_64` and install+it without clearing data. The exact saved APK, package verification, and+emulator install/launch record are in the+[P6 tuning report](XTREAM_SYNC_P6_TUNING_REPORT.md).+The Python runner starts a fixture bound to loopback, temporarily reverses itsport through adb, and removes that mapping when done. It refuses to reuse anexisting reverse mapping; choose another `--port` if necessary. APK installation@@ -45,13 +55,64 @@ is recorded alongside observed bulk/category request counts: STREAM_ALL canstill be overridden by existing safety policy, and AUTO may behave differentlyfor initial setup versus refresh.+Optional `--first-browsable-screen` launches the isolated app on the empty+Welcome screen, routes its startup landing destination to Live TV, and times+from the production setup use case starting until the first synthetic channel+row is accessible in the real Live screen. For a deterministic real-row target,+it temporarily hides the empty virtual Favorites and Recent categories, then+restores those preferences and the prior landing destination. The report+includes median and max for measured samples. It covers app navigation and row+readiness, but drives the production use case directly instead of interacting+with the provider form; it is emulator evidence, not a release-device+comparison. The option still deletes only its synthetic provider.++Optional `--verify-channel-fields` pages through the persisted live rows after+each setup and, with `--refresh`, after each Settings-style Live refresh. It+checks every row against the deterministic fixture: source order,+stream identity, name, category ID, the row's expected fallback category name,+EPG ID, archive fields, adult/protection state, logical group ID, fingerprint+presence, and the internal live URL token. Because fixture live rows omit+`category_name`, it separately checks the persisted category table against the+category-list names. The check uses 1,024-row pages and skips fixture rows+intentionally marked malformed. It runs after the relevant sync timer stops, so+its elapsed time is reported separately and is not included in import or+refresh latency.++Optional `--background-worker` marks the synthetic provider's last successful+Live timestamp stale, then queues a one-time no-ID `ProviderSyncWorker` through+WorkManager. It waits for terminal state and verifies the worker succeeded,+updated live-success metadata, and retained the exact channel count. This runs+the same provider-enumeration stale-refresh branch used by periodic and+launch-stale work; it does not wait for the periodic interval or validate its+network/battery scheduling constraints.+Each sample verifies the expected channel count after commit. Setup milestonesrecord live download start, save start, and the transition to movie category-shells after live commit. The total setup time includes authentication, initial-workflow work, live import and existing category-shell completion. Refresh time-ends when the existing live repair command returns. Warmups are excluded from-medians and maxima. Request counts belong to the synthetic account's full-lifecycle and include both phases when refresh is enabled.+shells after live commit. When synthetic movie/series summaries are configured,+the harness also waits for both durable index jobs to finish and checks Room+summary and active-index counts. The total setup time includes authentication,+initial workflow work, live import and existing category-shell completion;+summary indexing is reported separately. Refresh time ends when the existing+live repair command returns. Warmups are excluded from medians and maxima.+Request counts belong to the synthetic account's full lifecycle and include+both phases when refresh is enabled.++Optional `--repeat-vod-refresh` invokes the existing forced summary-index command+once for movies and then once for series after the initial jobs succeed. The+fixture and local rows are unchanged. It records per-section and combined+sequential elapsed time plus Java heap/ART GC samples for those direct refresh+calls, then verifies both Room and active-index counts again. This isolates an+unchanged summary refresh from setup and live import. It does not measure UI+readiness, playback, native RSS, or release-device performance. The P7 report+uses this option for its pre/post comparison.++When both movie and series fixtures are non-empty and at least one warmup is+configured, the first warmup seeds hydrated details, movie watch history,+protection flags and local playback metadata, then forces summary reindexing.+It checks that remote titles refresh while local IDs, hydrated fields, watch+state, protection, playback metadata and hydrated index timestamps survive.+The check is reported as `room_preservation_verified` and stays outside measured+samples when the configured warmup count is nonzero.`XtreamSyncTiming` reports each streamed live response's wall duration, callbackduration, emitted row count and normal completion. Callback duration includes@@ -76,11 +137,13 @@ Record environment, payload checksum and scenario with every comparison.## Fixture scenarios-The fixture generates JSON incrementally without retaining the live list. The-same deterministic live rows are partitioned across categories. Metadata records-seed, payload checksum, byte size and expected admitted channel count. Empty-VOD/series shells and EPG skip keep this measurement focused on live ingestion.-The fixture supplies no playable media.+The fixture generates deterministic live, movie and series rows. Live JSON is+streamed without retaining the live list, and each catalog type can be+partitioned across categories. Metadata records seed, payload checksums, byte+sizes and expected counts. `--bulk-vod-status` and `--bulk-series-status` can+reject full responses while category requests succeed, exercising summary+fallback. EPG remains outside the benchmark. The fixture supplies no playable+media.Examples (add normal iteration/mode options as needed):@@ -90,8 +153,23 @@ python tools/xtream_sync_benchmark.py --channels 10000 --categories 100 --categopython tools/xtream_sync_benchmark.py --channels 10000 --categories 100 --bytes-per-second 2000000python tools/xtream_sync_benchmark.py --bulk-status 503 --modes STREAM_ALLpython tools/xtream_sync_benchmark.py --disconnect-after-rows 500 --modes STREAM_ALL+python tools/xtream_sync_benchmark.py --channels 1000 --categories 20 --disconnect-after-rows 500 --modes AUTO --experimental-auto-bulk --iterations 1 --warmups 0 --verify-channel-fields --settle-seconds 30+python tools/xtream_sync_benchmark.py --channels 1000 --categories 10 --movies 2000 --movie-categories 20 --series-items 1000 --series-categories 10 --bulk-vod-status 503 --bulk-series-status 503 --runtime-tier LOW --stage-batch-size 256 --modes STREAM_ALL --iterations 5 --warmups 1+python tools/xtream_sync_benchmark.py --channels 1000 --categories 10 --movies 2000 --movie-categories 20 --series-items 1000 --series-categories 10 --runtime-tier LOW --modes STREAM_ALL --iterations 5 --warmups 1 --repeat-vod-refresh+python tools/xtream_sync_benchmark.py --channels 1000 --categories 10 --movies 2000 --movie-categories 20 --series-items 1000 --series-categories 10 --bulk-vod-status 503 --bulk-series-status 503 --runtime-tier LOW --modes STREAM_ALL --iterations 5 --warmups 1 --repeat-vod-refresh+python tools/xtream_sync_benchmark.py --channels 1000 --categories 10 --movies 8000 --movie-categories 80 --series-items 4000 --series-categories 40 --runtime-tier DEVICE --stage-batch-size 256 --modes STREAM_ALL --iterations 3 --warmups 1+python tools/xtream_sync_benchmark.py --channels 1000 --categories 10 --movies 8000 --movie-categories 80 --series-items 4000 --series-categories 40 --bulk-vod-status 503 --bulk-series-status 503 --runtime-tier LOW --stage-batch-size 256 --modes STREAM_ALL --iterations 2 --warmups 1+python tools/xtream_sync_benchmark.py --channels 1000 --categories 10 --modes STREAM_ALL --iterations 1 --warmups 0 --first-browsable-screen+python tools/xtream_sync_benchmark.py --channels 10000 --categories 100 --modes STREAM_ALL --iterations 1 --warmups 1 --background-worker```+These examples exercise synthetic category fallback and larger catalog sizes.+They are emulator evidence only; they do not measure playback, native RSS,+real-provider behavior, or physical-device performance. The P7 report records+the completed tier and route comparison matrix plus the unchanged VOD+pre-change comparison. That route-specific emulator comparison does not replace+the P0 release-device baseline or physical-device acceptance gate.+Also available: `--malformed-every`, `--throttle-every`, and `--seed`. Faultscenarios are diagnostic checks: current retry/fallback behavior may preventcompletion, in which case the runner intentionally fails. A completed server@@ -109,9 +187,13 @@ This package is an initial backend baseline, not the full P0 gate. Follow-upwork still needs precise headers/first-row and workflow-wait timings, attemptand generation identifiers, row identity/field equivalence beyond counts,skipped/duplicate/hidden coverage, parser CPU/allocation profiling, auxiliary-index readiness, and a first-browsable-screen measurement. Pipeline byte-high-water and writer-drain timings now exist; actual heap/allocation attribution-and queue occupancy over time remain open. Run the full+index readiness, release-build/device first-screen comparison, and full+WorkManager scheduling-constraint validation. Synthetic first-browsable and+no-ID background-worker measurements are available now. Pipeline byte high-water+and writer-drain timings now exist; actual heap/allocation attribution and queue+occupancy over time remain open. Run the fullfive-sample scenario matrix and representative release-device measurements-before freezing production tuning or claiming a speedup. Playback validation-is separate and follows AGENTS.md's sustained capture/log requirements.+before freezing production live-sync tuning. The P7 unchanged-summary result is+route-specific and stays separate from the release-device gate. Playback+validation is separate and follows AGENTS.md's sustained capture/log+requirements.diff --git a/docs/XTREAM_SYNC_CATEGORY_IMPLEMENTATION.md b/docs/XTREAM_SYNC_CATEGORY_IMPLEMENTATION.mdindex fda1c7a1..1e36e65e 100644--- a/docs/XTREAM_SYNC_CATEGORY_IMPLEMENTATION.md+++ b/docs/XTREAM_SYNC_CATEGORY_IMPLEMENTATION.md@@ -10,11 +10,25 @@ attempts merge under the P1 fence; failed or cancelled attempts are discarded.Stress downgrade stops refilling until already running attempts drain, thenadmits one at a time. Repeated sequential stress stops further admissions.-Authentication failures stop admissions and are excluded from failed-category-continuation retries. Unexpected worker failure cancels siblings; worker+Authentication failures stop admissions and block provider continuation, including+when authentication fails during a sequential continuation request. The coordinator+returns a structured authentication/stress stop reason so continuation cannot undo+a terminal stop. Completed outcomes remain available for partial promotion.++Local staging and attempt-reset exceptions bypass transport retries and provider+health accounting, then escape the fetcher with their original failure type and+message. This also applies to legacy decoder fallback. Unexpected worker failure+cancels siblings; workerCancellationException explicitly cancels the coordinator too, including workflowsupersession. Scope exit joins workers before staging cleanup.+Regression tests use the real HTTP fetcher, mapper, staging writer, coordinator+and Room store to verify local-failure propagation, sibling cancellation,+discarded staging and preservation of the active catalog. Strategy tests also+verify that stress/authentication stops suppress continuation, and continuation+tests preserve completed and unattempted outcomes when a later request loses+authentication.+Healthy live-category requests no longer have the mandatory 250 ms start gap.Remembered stress retains pacing and backoff. Movie/series category requestsretain their existing pacing and fixed-window behavior.@@ -31,6 +45,13 @@ that extension.## Evidence+After the failure-handling review fixes, 314 sync/HTTP Kotlin unit tests passed+with zero failures or errors. Nine new regression tests cover local writer and+attempt-reset failures, real-fetcher sibling cancellation and staging cleanup,+legacy fallback, authentication before/during continuation, and terminal stress+on both an intermediate and the final category. Existing shared-helper and+other-protocol sync tests remain in that passing set.+42 focused Kotlin tests passed, including refilled slots with a slow category,bounded concurrency, stable result order, stress downgrade/abort, authentication,sibling cancellation, real attempt supersession, failed-scope isolation, HTTP@@ -53,9 +74,12 @@ observed pacing cost rather than a controlled release-device speedup ratio.This emulator uses LOW profile category concurrency one: parallel refill itselfis verified by deterministic tests, not a device concurrency measurement.-AUTO selection remains unchanged until P6. Bulk rejection, broader runtime-tier-acceptance and redundant background imports require the following gates. These-fixtures contain no playable media and do not validate playback.+At the time of this P5 report, production AUTO selection was unchanged. P6 later+enabled bulk-first AUTO in normal app profiles on this branch for direct testing.+The release gate remains open because tier overrides ran on one emulator and did+not measure physical devices or first-screen readiness. See the+[P6 tuning report](XTREAM_SYNC_P6_TUNING_REPORT.md).+The synthetic fixtures contain no playable media and do not validate playback.The bulk-HTTP-503 fallback fixture also passed both operations at 2,000 rows:`build/xtream-sync-performance/20261010T080443490570Z/report.json`.diff --git a/docs/XTREAM_SYNC_DATABASE_IMPLEMENTATION.md b/docs/XTREAM_SYNC_DATABASE_IMPLEMENTATION.mdindex d5ba7b62..ba1b5d3f 100644--- a/docs/XTREAM_SYNC_DATABASE_IMPLEMENTATION.md+++ b/docs/XTREAM_SYNC_DATABASE_IMPLEMENTATION.md@@ -92,5 +92,7 @@ The final run contained no global channel FTS rebuild timing events.This is backend debug-emulator evidence. The emulator was restarted to resolvethe test installation investigation, and repeated runs can differ in devicestate. Release-device end-to-end readiness, LOW/MID/HIGH acceptance and sustained-real-channel playback remain open. AUTO remains unchanged until P6. These-results do not establish a tenfold overall improvement.+real-channel playback remain open. At the time of this P4 report, AUTO had not+yet changed; P6 later enabled bulk-first AUTO in normal app profiles on this+branch for direct testing. These results do not establish a tenfold overall+improvement.diff --git a/docs/XTREAM_SYNC_FAILURE_HARDENING.md b/docs/XTREAM_SYNC_FAILURE_HARDENING.mdnew file mode 100644index 00000000..58f3da04--- /dev/null+++ b/docs/XTREAM_SYNC_FAILURE_HARDENING.md@@ -0,0 +1,104 @@+# Xtream failure handling and continuation queues++Date: 2026-10-10. Branch: `codex/xtream-live-sync-performance`.++## Changes++- A rejected bulk Live TV request no longer starts category-stream fallback for+ authentication failures. An already-started category metadata request may finish.+ Action-specific HTTP 403 remains eligible for category fallback: denying a full+ catalog request does not by itself prove that the credentials were rejected.+ HTTP 403 no longer spends three transient retries repeating the denied catalog+ request before switching topology; transport/throttle retries retain backoff.+- Full sync preserves the previous Live success timestamp after failed or partial+ coverage. Keeping the old channel library does not prove a fresh complete import.+ A complete category fallback still counts as success despite bulk-path warnings.+- Retryable movie/series category discovery failures now produce durable index+ continuations immediately. The worker retries category discovery before summaries.+ Rejected credentials produce permanent job status and no automatic continuation.+- Authentication failures in full summary streams or category slices terminate+ the section without scheduling more categories. A permanent rejection replaces+ an older PARTIAL job, so recovery cannot repeatedly reuse that partial status.+- Launch/periodic summary admission does not restart FAILED_PERMANENT jobs merely+ because they have no successful timestamp. Explicit forced operations can retry.+- Provider-specific index workers complete their WorkManager node after a recorded+ permanent section failure, allowing already-appended sections to execute. The+ durable index job and workflow retain the failure. Transient failures still use+ WorkManager retry/backoff; standalone periodic batch failures still report failure.++## VOD and EPG ordering++Continue using durable queues. Add Provider commits Live TV first, then fetches+movie and series category shells before returning. Summary payloads and hydrated+details are outside initial Live ingestion; details remain on demand.+The category shells also identify VOD-only providers when Live TV is empty, so+this pass retains their existing setup/activation behavior.++The provider catalog continuation chain runs Live auxiliary index backfill, movie+summaries, and series summaries. Category slices checkpoint completed work and+enqueue continuation nodes. This is serialized provider work, not simultaneous+full Live/VOD/guide downloads. Category-shell failure now has an immediate durable+recovery path rather than depending on a later periodic check.++EPG is scheduled only when enabled, in a separate unique chain with the existing+30-second initial delay. It checks queued/running catalog jobs and defers with+backoff while they remain. Guide retries therefore do not occupy the catalog chain.+Transient catalog failures can delay subsequent catalog jobs; permanent failures+release the chain and remain visible in durable section state. This change does+not introduce parallel full VOD downloads or alter slice/batch budgets.++## Verification++Focused tests cover rejected Live bulk requests, rejected summary/category+requests, permanent-state admission, transient discovery continuations, previous+PARTIAL status replacement, recovery coalescing and failed-live freshness.++The benchmark's optional `--settle-seconds 30` observes terminal setup state and+channel counts every second after completion, before synthetic-provider cleanup.+Its request report rejects bulk requests occurring after category fallback begins.+Use setup-only runs; explicit refresh/background probes intentionally issue requests+and cannot be combined with this assertion. The observation window is bounded and+does not establish indefinite quiescence or playback health.++Two setup-only fault scenarios passed on the API 36 Android TV emulator, using+the isolated benchmark package with bulk-first AUTO explicitly enabled:++| Scenario | Live requests | Result | Observation |+| --- | --- | --- | --- |+| 1,000 channels / 20 categories, bulk disconnected after 500 rows | 4 incomplete bulk attempts, then 20 categories | Partial; all 1,000 rows and 20 category records matched fixture fields | 30 seconds of stable terminal state/count; zero bulk requests after fallback |+| Same Live catalog, bulk HTTP 503; 200 movies / 100 series with full summary HTTP 503 | 3 rejected Live bulk attempts, then 20 categories | Partial; exact Live fields; movie/series jobs SUCCESS with exact Room/index counts | 30 seconds of stable terminal state/count; zero bulk requests after fallback |++Reports are retained locally under ignored build directories:++- `build/xtream-sync-performance/hardening-truncated-bulk-1k/report.json`+- `build/xtream-sync-performance/hardening-503-bulk-vod-1k/report.json`++The earlier `hardening-truncated-1k` and `hardening-503-vod-1k` runs used the+benchmark's historical AUTO policy opt-out and made no bulk Live requests. They+passed category-route checks but are not evidence of bulk failure recovery.+Both corrected runs completed instrumentation successfully and recorded complete+request traces. Synthetic providers and reverse mappings were cleaned afterward.+EPG was SKIP in these fixtures; no guide download or playable media was tested.++Fixture/report/catalog-fixture Python tests passed (17 tests). The final Gradle+run passed 196 JVM tests: 181 focused sync tests and 15 backup manager tests+included by the test-name filter. This includes the HTTP 401/403 distinction,+attempt isolation, category scheduling, provider recovery and continuation tests.+Both isolated app and instrumentation APKs assembled successfully; their package+IDs were checked before installation. `git diff --check` passed.++Queue completion/admission policy has focused unit coverage. The emulator VOD+run exercises successful continuation after transient bulk rejection; it does+not exercise a permanent-failure WorkManager dependency chain or EPG fetching.+Real-provider sync, guide acceptance, sustained playback and other fault profiles+remain separate release gates.++## Manual testing default follow-up++The isolated benchmark package formerly defaulted to the historical AUTO policy+whenever its override preferences were absent. After instrumentation cleaned the+preferences, a manual Add Provider run in that same app therefore selected+category mode on LOW devices. The emulator log and foreground package identified+this mismatch. Its ordinary UI now defaults to bulk-first like normal packages.+The instrumentation harness writes an explicit true/false override for route+comparisons and clears it afterward; historical opt-out comparisons remain available.diff --git a/docs/XTREAM_SYNC_IMPROVEMENT_PLAN.md b/docs/XTREAM_SYNC_IMPROVEMENT_PLAN.mdindex e84feed2..d5f871dd 100644--- a/docs/XTREAM_SYNC_IMPROVEMENT_PLAN.md+++ b/docs/XTREAM_SYNC_IMPROVEMENT_PLAN.md@@ -14,6 +14,30 @@ Supporting evidence:- [Database write and search implementation](XTREAM_SYNC_DATABASE_IMPLEMENTATION.md)- [Live category scheduling implementation](XTREAM_SYNC_CATEGORY_IMPLEMENTATION.md)- [Completed primary resume coalescing](XTREAM_SYNC_RESUME_IMPLEMENTATION.md)+- [P6 live strategy and tuning report](XTREAM_SYNC_P6_TUNING_REPORT.md)+- [P7 summary and background implementation](XTREAM_SYNC_P7_IMPLEMENTATION.md)+- [P0 50k scale and batch sweep](XTREAM_SYNC_P0_SCALE_REPORT.md)+- [Failure handling and continuation queues](XTREAM_SYNC_FAILURE_HARDENING.md)++## Current status (2026-10-10)++| Work item | Status | Done | Remaining |+| --- | --- | --- | --- |+| P0 baseline | In progress | Synthetic backend fixture, initial baseline, synthetic first-browsable-row probe, controlled 50k-row scale/batch sweep, repeated/randomized 10k route comparisons across simulated LOW/MID/HIGH policies, field equivalence after both routes, hidden-scope refresh and fallback, and a verified 503 fallback terminal-state/retry-quiescence fix | Other fixture/provider profiles, terminal-state and retry-quiescence behavior for truncated-body and other failure paths, broader refresh cases, attributable allocation/CPU profile, release-build/device comparison and frozen acceptance gates |+| P0 50k scale and batch sweep | Done | Six API 36 emulator batch profiles plus a matched 50k route comparison; 50,000/50,000 rows committed; same fixture hash | Exploratory only; no repeatable batch-size gain; see linked report |+| P0 10k route comparisons | Done | Three alternating-order LOW/100 pairs plus three seeded randomized pairs per simulated LOW/MID/HIGH policy; complete samples and request logs; see the P0 report | One synthetic fixture and emulator only; other provider distributions remain open; this sweep did not change stage-batch defaults |+| P0 persisted row/field equivalence | Done | All 50,000 rows and 200 category records checked after both routes; malformed rows, hidden-category refresh on both routes, and exact fields after HTTP 503/truncated-body category fallback checked; 10k HTTP 503 fallback now settles at Partial without post-fallback bulk retries | Synthetic emulator only; other failure paths and provider distributions remain open; see linked report |+| P1–P5 | Done | Implementation and focused correctness/performance evidence are recorded in the linked reports | P6/P8 release acceptance still depends on these components passing the full matrix |+| Failure handling and continuation queues | Done | Live/VOD authentication termination, durable category-discovery retries, failed-live freshness correction, permanent section queue handling, and 30-second truncated/503 fallback checks | Other fault/provider profiles, longer retry observation and real EPG/playback acceptance remain open; see linked report |+| P6 implementation and emulator exploration | Done | Bulk-first AUTO is active in normal app profiles on this branch; hidden-scope behavior, progress labels, and synthetic 10k-row tuning matrix are implemented | Physical-device/provider acceptance remains open; stage batch defaults are unchanged |+| P6 emulator follow-up | Done | Fresh benchmark APK exercised 10k-channel AUTO bulk success and HTTP 503 category fallback; prior Settings refresh, Welcome-to-Live first-row, and no-ID stale-worker checks also passed on API 36 emulator | Physical LOW/MID/HIGH, real-provider and sustained-playback validation remain deferred |+| P6 physical-device/provider validation | Deferred | No physical devices are available; the branch debug APK is installed and launched for user-side provider testing | Run and record the real-provider sync/playback check; physical LOW/MID/HIGH validation stays deferred |+| P7 implementation | Done | Summary diffing/fingerprints, checkpointed row/time slices, catalog-before-guide scheduling, focused unit coverage, and fingerprint allocation reduction | Bulk-refresh gain is route-specific; physical tuning remains open |+| P7 emulator summary matrix | Done | 2k/1k category fallback under LOW/MID/HIGH/DEVICE; bulk-success comparison; 8k/4k bulk-success and LOW fallback; Room counts and warmup preservation checks passed | Physical tuning is tracked separately |+| P7 before/after unchanged VOD refresh comparison | Done | Pre-P7 commit compared with P7 working tree on the same API 36 emulator, fixture, LOW policy and 100-row stage batch; ten measured bulk-success samples and five fallback samples per build | Bulk success was 59.69% faster; fallback was effectively unchanged; sampled heap increased, so no blanket speedup claim |+| P7 fingerprint allocation follow-up | Done | Removed per-field length-buffer and per-byte formatter allocations while preserving persisted SHA-256 encoding; repeated emulator runs passed for bulk success and category fallback | Sampled refresh peak fell 32.4% on bulk success and 25.5% on fallback versus P7; physical tuning is still required |+| P7 physical-device tuning | Deferred | Not run; no physical devices are available | Resume if target hardware becomes available |+| P8 end-to-end release validation | Pending | — | Real-provider two-channel sustained playback and rollout/rollback evidence |The reference implementation provides hypotheses to investigate, not a designauthority or proof of correctness. Choose behavior for this app's measured@@ -279,28 +303,91 @@ or completion semantics.| P7 | Movie/series summaries reuse and background priority; incremental executor, worker, continuation scheduler, summary DB writes | P6 | Faster summaries, preserved hydrated details, catalog-before-guide scheduling, bounded completion jobs || P8 | End-to-end acceptance, sustained playback, rollout and report | P6; P7 for full Xtream release | Gates met, evidence archived, rollback path proven |-P6 is the first live performance release milestone; P7 follows it. Keep actual-production AUTO behavior unchanged until the P6 gate. Experiments before then-use explicit STREAM_ALL or debug configuration, with identical data coverage.--Implementation progress on 2026-10-10: P0 has an initial backend baseline and-isolated fixture; its complete release-device/readiness comparison remains open.-P1 attempt isolation and conservative receipt-based recovery are implemented and-validated. P2 direct live decoding and cheaper group identity are implemented-with field-equivalence checks and measured component CPU reductions. P3 retrieval-overlap and a bounded reader/writer pipeline are implemented with cancellation,-resource-bound and real-graph setup/refresh evidence. P4 stage accounting,-fingerprint costs, SQL live-index projection and trigger-maintained search are-implemented with fresh/migrated Room checks and measured backend improvements.-P5 refilled live-category workers and adaptive pacing are implemented with-cancellation, authentication and Retry-After coverage. P6–P8 remain pending.-Targeted primary recovery now rechecks completion under the provider lock to-coalesce already successful foreground imports; its observed duplicate-refresh-route has regression and fixture coverage.-The new measurements identify writer cost, slow fallback and extra completed-imports during some refresh intervals as remaining priorities. Earlier runs-also showed memory-driven category fallback; the default-strategy gate has not-been met. See the implementation reports linked above for evidence and limits.+P6 is the first live performance release milestone; P7 follows it. Normal app+builds on this branch now use bulk-first AUTO so the changed sync can be tested+directly. Keep the measured stage-batch defaults until physical-device evidence+supports a retune. The isolated benchmark package can still compare the prior+AUTO policy with the bulk-first policy using identical data coverage.++Implementation progress on 2026-10-10: P0 has an initial backend baseline,+isolated fixture, synthetic first-browsable-row probe, controlled 50k-row+scale/batch sweep, matched bulk/category comparison, all-row field equivalence+for both initial-import routes, malformed-row handling, a hidden-scope live+refresh check on both routes, 503 and truncated-body category fallback field+checks, and repeated/randomized 10k route comparisons across simulated+LOW/MID/HIGH policies. Larger batch profiles did not show a repeatable+elapsed-time gain, so production batch defaults remain unchanged. The original+503 run exposed `Syncing` plus three later bulk retries after full category+coverage. After updating queued onboarding recovery coalescing, a repeat 10k+HTTP 503 run verified 10,000 fields and 100 categories, settled at `Partial`,+made only the three initial bulk attempts and zero post-fallback bulk requests;+the log confirmed the queued recovery was coalesced after onboarding completed.+The truncated-body run showed `Partial` after full row coverage but has not been+rerun after this change. Other fixture/provider comparisons, lifecycle checks+for other failure paths, broader refresh cases, attributable allocation/CPU+profiling, release-build/device comparison and frozen acceptance gates remain+open; see the+[P0 scale report](XTREAM_SYNC_P0_SCALE_REPORT.md). P1 attempt isolation and conservative receipt-based+recovery are implemented and validated. P2 direct live decoding and cheaper+group identity are implemented with field-equivalence checks and measured+component CPU reductions. P3 retrieval overlap and a bounded reader/writer+pipeline are implemented with cancellation, resource-bound and real-graph+setup/refresh evidence. P4 stage accounting, fingerprint costs, SQL live-index+projection and trigger-maintained search are implemented with fresh/migrated+Room checks and measured backend improvements. P5 refilled live-category+workers and adaptive pacing are implemented with cancellation, authentication+and Retry-After coverage. Targeted primary recovery now rechecks completion+under the provider lock and coalesces already successful foreground imports.++Bulk loading progress follow-up (2026-10-10): the Add Provider callback now+reports the accepted channel count after successful staging writes, for example+`Loading Live TV channels...` followed by `3,200 channels processed`. Updates+are throttled to 250 ms, with the final drained count always published. A new+attempt clears the discarded count. The bar remains indeterminate because+the bulk endpoint supplies no reliable total; Saving and Ready remain tied to+catalog promotion. Focused reporter, strategy callback and progress-parser+tests cover these behaviors; no real-provider UI acceptance is claimed here.++P6 bulk-first AUTO behavior, hidden-category routing and user-facing progress+are implemented. Normal app profiles now enable bulk-first AUTO; the isolated+benchmark package retains an explicit policy override for comparisons. Batch+and policy measurements cover one synthetic API 36 emulator, 10,000 rows and+five measured runs, but tier values were simulated. A fresh build was reinstalled+and rerun on the emulator: AUTO retained and field-verified all 10,000 channels+with one bulk request; a second AUTO run with three HTTP 503 bulk rejections+completed all 100 category requests, retained and field-verified all 10,000+channels, and emitted no post-fallback bulk retries. The synthetic setup-to-first-row+measurement exercises the real Welcome-to-Live UI with a synthetic channel, and the no-ID+ProviderSyncWorker stale-refresh branch succeeds through WorkManager with+preserved 10k catalog coverage. These are emulator evidence, not physical-device+or release-build comparisons; WorkManager interval/constraint scheduling,+real-provider behavior and sustained playback remain open. The P6 release gate+therefore remains open even though bulk-first AUTO is now active on this branch.+Production stage-batch defaults remain unchanged. P7 summary deduplication,+bounded category slices,+catalog-before-guide scheduling and separate guide work are implemented with+focused tests. The API 36 emulator completed the synthetic VOD/series matrix:+2k/1k category fallback under LOW/MID/HIGH/DEVICE, a bulk-success comparison,+and 8k/4k bulk-success and LOW fallback runs. Counts, index jobs, and warmup+Room preservation checks passed. A separate unchanged-summary refresh+comparison against pre-P7 commit+`2af03f5149e888d25307457d4cce82fab3de74d9` used ten measured bulk-success+samples and five fallback samples per build. Median time was 59.69% lower on+the bulk-success route, while category fallback was effectively unchanged+(0.89% lower). Maximum sampled Java heap rose from 10.09 to 17.19 MiB on bulk+success and from 9.01 to 10.83 MiB on fallback. The full bulk sample set is+reported because baseline timings settled during measurement; no samples were+trimmed. The result supports only a bulk-success refresh gain; fallback and+memory observations remain open for physical-device tuning. A follow-up removed+per-field length-buffer and per-byte formatter allocations while retaining the+same fingerprint encoding. Repeated unchanged-refresh runs reduced the sampled+peak by 32.4% on bulk success and 25.5% on category fallback versus P7; fallback+timing remained effectively unchanged. The bulk peak remains 1.52 MiB above+the pre-P7 maximum, and all results are from one emulator. Physical tuning is+deferred because no physical devices are available. P8 is pending because+real-provider sustained playback and rollout/rollback validation have not been+performed. The status table above marks completed work separately from open+acceptance. Reports linked above record the evidence and limits.## P0 measurement and fixture deliverables@@ -434,19 +521,22 @@ Completion checklist:- [ ] Required browse/search indexes and user state remain correct.- [ ] Retry/cancel/death/edit/delete preserve coherent catalog ownership.- [ ] Two-channel sustained playback report recorded.-- [ ] P7 catalog/guide follow-up improvements verified independently.-- [ ] Before/after report includes build revisions, device/runtime, data seed,+- [x] P7 catalog/guide follow-up improvements verified independently.+- [x] Before/after report includes build revisions, device/runtime, data seed,counts, requests, medians/spread, heap/GC, fallback behavior and limitations.-- [ ] AUTO rollout/rollback and any schema migration boundary documented.+- [x] Branch AUTO activation/default behavior, direct-test APK and current+ validation limits documented.+- [ ] Release rollout/rollback and supported schema migration compatibility+ proven.No package is marked complete until its evidence exists. The first P0 backendharness, timing hooks and measurements are implemented on`codex/xtream-live-sync-performance`. See the[benchmark guide](XTREAM_SYNC_BENCHMARK.md) and-[initial baseline](XTREAM_SYNC_INITIAL_BASELINE.md) for measured results and-the remaining P0 gates. The available emulator redirected all measured modes-to categories, so an actual bulk comparison remains open. Follow-up work also-showed requests continuing after workflow supersession: include prompt-termination of that work in P1 before introducing more concurrency. Measured-bottlenecks guide tuning while the correctness and complete-live outcome above-remain fixed.+[initial baseline](XTREAM_SYNC_INITIAL_BASELINE.md) for the initial redirected+category-only runs and remaining P0 gates. Later P6 candidate runs exercised+the synthetic bulk route; they do not replace physical-device, provider, or+first-screen measurements. Follow-up work also showed requests continuing+after workflow supersession; prompt termination and joined cleanup are covered+by P1. Measured bottlenecks guide tuning while the correctness and complete-live+outcome above remain fixed.diff --git a/docs/XTREAM_SYNC_P0_SCALE_REPORT.md b/docs/XTREAM_SYNC_P0_SCALE_REPORT.mdnew file mode 100644index 00000000..2e4c337e--- /dev/null+++ b/docs/XTREAM_SYNC_P0_SCALE_REPORT.md@@ -0,0 +1,269 @@+# Xtream sync 50k scale and batch sweep++Status: **Done** for an exploratory synthetic emulator sweep. This does not+close P0 or establish a release performance result.++Measured 2026-10-10 on the API 36 Android TV x86_64 emulator using the isolated+`com.streamvault.app.syncbenchmark` package. Each profile used one warmup and+three measured imports of the same deterministic 50,000-channel, 200-category+fixture (seed 1). The live payload was 12,250,789 bytes with SHA-256+`fb0b72467c66305c3780a9ff1b23fe5d4bd0ad3d8a03b0d34e8082558e02e073`.+Every measured import committed exactly 50,000 rows through one complete live+bulk request and made zero per-category live requests. The API 36 emulator had+a 192 MiB memory class and 201,326,592-byte maximum Java heap. Tier and batch+settings below are benchmark overrides on this one emulator; they do not+represent physical LOW/MID/HIGH devices.++## Results++| Profile | Stage batch / queue | Staged batches | Setup median / max | Live commit median | Max sampled Java heap | Measured GC delta range |+| --- | ---: | ---: | ---: | ---: | ---: | ---: |+| LOW / 100 | 100 / 1 | 500 | 19.446 / 20.781 s | 19.364 s | 13.21 MiB | 431–436 |+| LOW / 256 | 256 / 1 | 196 | 20.339 / 20.817 s | 20.247 s | 13.25 MiB | 367–372 |+| LOW / 512 | 512 / 1 | 114 | 20.175 / 25.303 s | 20.072 s | 13.93 MiB | 321–328 |+| MID / 512 | 512 / 2 | 98 | 18.627 / 23.591 s | 18.544 s | 15.96 MiB | 308–318 |+| HIGH / 500 | 500 / 2 | 100 | 21.030 / 24.338 s | 20.927 s | 14.21 MiB | 311–320 |+| HIGH / 1,024 | 1,024 / 2 | 49 | 24.470 / 24.614 s | 24.357 s | 16.38 MiB | 293–296 |++LOW/256, LOW/512 and HIGH/500 were respectively 4.6%, 3.8% and 8.1% slower+by median setup time than LOW/100. MID/512 was 4.2% faster by median, but its+23.591 s maximum was 13.5% above the LOW/100 maximum and its 15.96 MiB sampled+heap was 20.8% higher. That three-sample, single-emulator median does not+establish a safe improvement. HIGH/1,024 was 25.8% slower by median than+LOW/100 and had a 16.38 MiB sampled peak. Larger batches reduced staging batch+and sampled GC counts, but did not provide a repeatable elapsed-time gain;+several profiles had higher maxima. Sampled heap is process telemetry, not an+allocation profile or device memory-pressure measurement. The one-off 50k+smoke run without warmup took 29.515 s and is excluded from the controlled+comparison as an outlier.++## Matched bulk and category route comparison++The same fixture, emulator build, LOW runtime override and batch size 100 were+also measured using explicit `CATEGORY_BY_CATEGORY` mode (one warmup plus three+measured imports). Both runs used the same payload hash, committed exactly+50,000 rows, completed every live response, and retained full request logs.++| Live route | Live requests per import | Rows per response | Setup median / max | Live commit median | Max sampled Java heap |+| --- | ---: | ---: | ---: | ---: | ---: |+| STREAM_ALL bulk | 1 | 50,000 | 19.446 / 20.781 s | 19.364 s | 13.21 MiB |+| CATEGORY_BY_CATEGORY | 200 | 250 | 25.950 / 28.739 s | 25.878 s | 9.62 MiB |++On this synthetic LOW profile, category mode was 33.5% slower by median setup+time and had a 38.3% higher maximum. It had a 27.2% lower maximum sampled heap.+The request trace showed a maximum of one active server request during category+mode. This supports the bulk route for this healthy, zero-delay fixture, while+also showing the category route's lower sampled heap in this run. It does not+establish behavior for real providers, different category distributions,+throttling, physical devices or release builds. The run order was not+randomized, so treat the comparison as exploratory rather than a frozen release+gate.++### Repeated alternating-order 10k follow-up++To reduce simple run-order bias, the same API 36 emulator and LOW/100 profile+ran three paired blocks against a deterministic 10,000-channel, 100-category+fixture. Each route had one warmup and one measured import per block. Route+order alternated bulk-first, category-first, bulk-first. All reports used the+same payload SHA-256 (`4dfbcaf7e39ce168eb4cd58e34b5d8c78dddf4592d6638cb46c76b0fb31d63a3`),+recorded all expected samples, passed instrumentation, and retained complete+request-event logs. Every measured import committed all 10,000 rows.++| Paired block | Order | STREAM_ALL setup | CATEGORY_BY_CATEGORY setup | Bulk faster in pair |+| --- | --- | ---: | ---: | ---: |+| 1 | Bulk first | 5.482 s | 6.971 s | 21.4% |+| 2 | Category first | 5.181 s | 8.847 s | 41.4% |+| 3 | Bulk first | 4.534 s | 6.709 s | 32.4% |++Across the three measured imports per route, `STREAM_ALL` had a 5.181 s median+and 5.482 s maximum setup time; `CATEGORY_BY_CATEGORY` had a 6.971 s median+and 8.847 s maximum. Bulk was faster in all three pairs. Maximum sampled Java+heap was 11.08 MiB for bulk and 9.93 MiB for category mode. Each bulk import+made one live request; each category import made 100. These samples support a+bulk latency advantage on this specific synthetic fixture, with lower sampled+heap for category mode. The sequence was alternating rather than randomized,+and the category-first block had the slowest category-mode sample; bulk ranged+from 4.534 to 5.482 s. Run-to-run and ordering effects remain plausible. This+exploratory result alone did not justify a production AUTO/default decision or+replace measurements on other fixtures, release builds, physical devices or+real providers. Bulk-first AUTO was subsequently enabled on this branch for+direct testing; the activation and fresh synthetic checks are recorded in the+[P6 tuning report](XTREAM_SYNC_P6_TUNING_REPORT.md).++### Seeded randomized comparisons across simulated tiers++A follow-up used the same 10k/100 fixture, payload hash, API 36 Android TV+x86_64 emulator and isolated benchmark package. We ran three paired blocks per+simulated tier with one warmup and one measured import per route in every+block. Both tier and route order were shuffled with seed `20261010`; each tier+had two bulk-first and one category-first pair. Tier overrides select the+application policy only: these are not physical LOW/MID/HIGH devices. The+profile's default stage batch sizes were LOW/100, MID/300 and HIGH/500. All+reports were complete, instrumentation passed, measured rows were exactly+10,000, hashes matched, and request-event logs were not truncated.++Positive paired advantage means bulk had lower setup time; a negative value+means category mode was faster.++| Run order | Tier / pair | First route | STREAM_ALL setup | CATEGORY_BY_CATEGORY setup | Bulk paired advantage |+| ---: | --- | --- | ---: | ---: | ---: |+| 1 | LOW / 1 | Bulk | 6.308 s | 8.685 s | +27.4% |+| 2 | MID / 1 | Bulk | 5.651 s | 6.269 s | +9.9% |+| 3 | HIGH / 1 | Category | 5.345 s | 5.352 s | +0.1% |+| 4 | LOW / 3 | Bulk | 4.559 s | 6.814 s | +33.1% |+| 5 | MID / 2 | Category | 5.468 s | 6.540 s | +16.4% |+| 6 | MID / 3 | Bulk | 5.499 s | 6.224 s | +11.7% |+| 7 | HIGH / 2 | Bulk | 5.622 s | 5.217 s | -7.8% |+| 8 | HIGH / 3 | Bulk | 4.436 s | 5.042 s | +12.0% |+| 9 | LOW / 2 | Category | 5.756 s | 8.618 s | +33.2% |++| Simulated tier / default batch | Route | Setup median / max | Faster in paired blocks | Max sampled Java heap |+| --- | --- | ---: | ---: | ---: |+| LOW / 100 | STREAM_ALL | 5.756 / 6.308 s | 3 / 3 | 11.71 MiB |+| LOW / 100 | CATEGORY_BY_CATEGORY | 8.618 / 8.685 s | — | 9.66 MiB |+| MID / 300 | STREAM_ALL | 5.499 / 5.651 s | 3 / 3 | 12.19 MiB |+| MID / 300 | CATEGORY_BY_CATEGORY | 6.269 / 6.540 s | — | 13.92 MiB |+| HIGH / 500 | STREAM_ALL | 5.345 / 5.622 s | 2 / 3 | 12.45 MiB |+| HIGH / 500 | CATEGORY_BY_CATEGORY | 5.217 / 5.352 s | — | 21.21 MiB |++Bulk won all six LOW and MID paired blocks. At HIGH, category mode won one+pair and the median route times were close (bulk 5.345 s; category 5.217 s).+Bulk made one live request per import; category mode made 100. The measured+heap direction varied by tier, with the category route's HIGH-profile maximum+the largest sample in this sweep. This matrix suggests the route advantage can+depend on the simulated policy tier and does not support a universal AUTO+choice. All runs used one emulator with the same 192 MiB memory class; results+do not establish behavior on physical devices, release builds or real providers.++The bulk per-run request trace confirms one complete `get_live_streams`+response, zero per-category live requests, and exact row counts. The request+also fetches authentication/category metadata and empty movie/series category+shells. One representative LOW/100 measured run spent 14.2 s in the live HTTP+response and 19.8 s in the instrumented streaming callback; these overlap with+decode, mapping, and staging and must not be summed as separate wall-time+costs. The pipeline trace records substantial producer send-wait, but this+sweep alone does not isolate a safe optimization target.++## Persisted row and field equivalence++The benchmark now has an opt-in `--verify-channel-fields` pass. After setup+timing stops, it walks Room in 1,024-row pages and checks fixture-derived source+order, stream IDs, names, category IDs and the row fallback category name, EPG+IDs, archive support/duration, provider/adult/protection fields, logical group+IDs, internal URL tokens, and required local/fingerprint fields. It separately+checks the persisted category table against the category-list names. The channel+rows intentionally omit `category_name`, so their expected row value is the+existing `Category N` fallback; the authoritative `Benchmark Group NNNN`+values are verified in category records.++| Route / fixture | Persisted rows checked | Category records checked | Verification time (outside setup timing) | Result |+| --- | ---: | ---: | ---: | --- |+| STREAM_ALL / 50k | 50,000 | 200 | 10.883 s | Pass |+| CATEGORY_BY_CATEGORY / 50k | 50,000 | 200 | 14.756 s | Pass |+| STREAM_ALL / 103 rows, every tenth malformed | 93 | 12 | 0.038 s | Pass |+| STREAM_ALL / 10k initial + hidden 20% refresh | 10,000 after each phase | 100 after each phase | 2.581 / 2.464 s | Pass |+| CATEGORY_BY_CATEGORY / 10k initial + hidden 20% refresh | 10,000 after each phase | 100 after each phase | 2.750 / 2.595 s | Pass |+| STREAM_ALL / HTTP 503 then category fallback | 10,000 | 100 | 2.693 s initial / 3.449 s follow-up | Fields pass; follow-up settled Partial with no post-fallback bulk retry |+| STREAM_ALL / truncated body then category fallback | 1,000 | 20 | 0.293 s | Fields pass; final state Partial |++Each 50k route check was one no-warmup correctness run, not a timing sample. The+bulk run made one complete live request; the category run made 200 complete+category requests. All live response rows summed to 50,000 and request-event+logs were not truncated. The malformed smoke confirms the checker skips the+fixture's invalid stream-ID rows and covers the remaining 93 persisted rows.+The 10k refresh probe hid 20% of categories before the Settings-style live+refresh; both phases retained all expected rows and categories, and the verifier+matched every row after refresh. Each phase made one complete bulk request and+zero category-stream requests. This is one synthetic correctness sample per+phase, not refresh performance evidence.++The explicit category-mode refresh retained the same 10,000 rows and 100+category records after hiding 20% of categories; fixture comparison passed+after both setup and refresh. It made 100 category requests for setup and 80+visible-category requests for refresh. The original 10k HTTP 503 run retried+the bulk endpoint, then completed all 100 category responses and verified every+persisted field, but its state snapshot was `Syncing` and three later bulk+requests followed the fallback. This exposed a queued onboarding recovery that+could rerun completed primary work when fallback left the overall sync+`PARTIAL`.++After updating `resumePrimaryCatalog` to coalesce a queued initial-onboarding+resume when onboarding completed and the durable live snapshot is fresh and+complete, a follow-up 10k HTTP 503 run passed instrumentation and verified all+10,000 rows and 100 categories. It made three bulk attempts, all HTTP 503,+followed by 100 successful category requests; there were zero bulk requests+after fallback. The sampled sync state was `Partial`, and logcat recorded+`Xtream primary resume coalesced ... onboarding completed while queued.` The+request trace was complete. Setup took 17.841 s and the post-setup field check+took 3.449 s; this is one emulator verification run, not evidence for other+failed-response shapes. The 1k truncated-body run made four+incomplete 500-row bulk attempts, completed 20 category responses, and verified+all 1,000 persisted fields; its state snapshot was `Partial`. It has not been+rerun after the coalescing change.++## Decision and limits++Follow-up on 2026-10-10: the corrected bulk-first truncated-response scenario+and an HTTP 503 scenario with VOD/series fallback now pass a 30-second terminal+state/count observation with zero bulk Live requests after category fallback.+See [failure handling and continuation queues](XTREAM_SYNC_FAILURE_HARDENING.md).+This closes that bounded truncated-response observation; other failures and+longer retry windows remain open. The earlier evidence below stays historical.++- **Done:** Synthetic 50k-row scale smoke and six-profile batch-size comparison;+ all measured samples completed with exact fixture counts.+- **No default change:** Existing tier-specific production batch defaults stay+ unchanged. The larger candidates did not show a repeatable end-to-end gain.+- **Done:** Three paired, alternating-order synthetic LOW/100 comparisons and+ three seeded randomized pairs per simulated LOW/MID/HIGH policy at 10k rows.+ Bulk won all LOW/MID pairs; HIGH was mixed and close by median. The separate+ 50k comparison also favored bulk by median.+- **Done:** All-row field equivalence for both initial-import routes on the+ 50k fixture, a malformed-row smoke check, and a 10k hidden-category refresh+ check on both live routes, plus field checks after 503 and truncated-body+ category fallback.+- **Still open:** Route comparisons across other fixture/provider profiles;+ terminal-state/retry-quiescence behavior for truncated-body and other failure+ paths; broader refresh/failure cases; attributable+ allocation/CPU profiling; release-build and representative device+ measurements; finalized P0 gates.+- **Deferred:** Physical LOW/MID/HIGH tuning and real-provider/playback checks.+ No physical devices are available. The synthetic fixture has no playable+ media; a branch debug APK is now installed for the user to run against their+ provider, but that validation has not yet been performed.++Raw local reports (ignored build artifacts):++- `build/xtream-sync-performance/20261010T140737945520Z/report.json`+- `build/xtream-sync-performance/20261010T140737945520Z/requests.jsonl`+- `build/xtream-sync-performance/p0-scale-50k-low-batch100-3x1/report.json`+- `build/xtream-sync-performance/p0-scale-50k-low-batch256-3x1/report.json`+- `build/xtream-sync-performance/p0-scale-50k-low-batch512-3x1/report.json`+- `build/xtream-sync-performance/p0-scale-50k-mid-batch512-3x1/report.json`+- `build/xtream-sync-performance/p0-scale-50k-high-batch500-3x1/report.json`+- `build/xtream-sync-performance/p0-scale-50k-high-batch1024-3x1/report.json`+- `build/xtream-sync-performance/p0-scale-50k-low-category-3x1/report.json`+- `build/xtream-sync-performance/p0-field-equivalence-50k-verified/report.json`+- `build/xtream-sync-performance/p0-field-equivalence-50k-category-verified/report.json`+- `build/xtream-sync-performance/p0-field-equivalence-malformed-103/report.json`+- `build/xtream-sync-performance/p0-field-equivalence-10k-hidden-refresh/report.json`+- `build/xtream-sync-performance/p0-field-equivalence-10k-category-hidden-refresh/report.json`+- `build/xtream-sync-performance/p0-field-equivalence-10k-bulk-503-fallback/report.json`+- `build/xtream-sync-performance/p0-field-equivalence-1k-partial-disconnect-fallback/report.json`+- `build/xtream-sync-performance/p0-route-pair1-bulkfirst/report.json`+- `build/xtream-sync-performance/p0-route-pair2-categoryfirst/report.json`+- `build/xtream-sync-performance/p0-route-pair3-bulkfirst/report.json`+- `build/xtream-sync-performance/p0-route-randomized-LOW-pair1-bulkfirst/report.json`+- `build/xtream-sync-performance/p0-route-randomized-LOW-pair2-categoryfirst/report.json`+- `build/xtream-sync-performance/p0-route-randomized-LOW-pair3-bulkfirst/report.json`+- `build/xtream-sync-performance/p0-route-randomized-MID-pair1-bulkfirst/report.json`+- `build/xtream-sync-performance/p0-route-randomized-MID-pair2-categoryfirst/report.json`+- `build/xtream-sync-performance/p0-route-randomized-MID-pair3-bulkfirst/report.json`+- `build/xtream-sync-performance/p0-route-randomized-HIGH-pair1-categoryfirst/report.json`+- `build/xtream-sync-performance/p0-route-randomized-HIGH-pair2-bulkfirst/report.json`+- `build/xtream-sync-performance/p0-route-randomized-HIGH-pair3-bulkfirst/report.json`++Reproduction uses the commands documented in+[`XTREAM_SYNC_BENCHMARK.md`](XTREAM_SYNC_BENCHMARK.md), with+`--channels 50000 --categories 200 --modes STREAM_ALL --iterations 3+--warmups 1` and the recorded tier/batch overrides.diff --git a/docs/XTREAM_SYNC_P6_TUNING_REPORT.md b/docs/XTREAM_SYNC_P6_TUNING_REPORT.mdnew file mode 100644index 00000000..d6657c7e--- /dev/null+++ b/docs/XTREAM_SYNC_P6_TUNING_REPORT.md@@ -0,0 +1,238 @@+# P6 live strategy and tuning report++Status: bulk-first AUTO is enabled in normal app profiles on this branch for+direct testing. Stage-batch defaults remain unchanged. Real-provider and+physical-device acceptance for P6 remain open.++| State | Work |+| --- | --- |+| Done | Bulk-first AUTO policy, hidden-category routing, progress changes, and the synthetic 10k-row matrix across batch sizes and policy overrides |+| Done | Synthetic setup-to-first-browsable-row timing through the real Welcome-to-Live screen on API 36 emulator |+| Done | No-ID stale `ProviderSyncWorker` refresh through WorkManager with catalog and metadata assertions |+| Done | Fresh APK emulator check: 10k-channel AUTO bulk success and 503-to-category fallback with full field verification |+| Done | Normal app debug APK installed and launched on the API 36 x86_64 emulator with app data preserved |+| Done | Successful new-provider completion now routes all setup protocols to Home; edited providers retain their prior return behavior |+| Deferred | Physical LOW/MID/HIGH-device acceptance; no physical devices are available |+| Pending | User real-provider compatibility and sustained-playback run, release-device comparison, and release rollout evidence |++Date: 2026-10-10+Branch: `codex/xtream-live-sync-performance`++## Implementation exercised++- Normal app packages now use bulk-first AUTO by default. The isolated+ `com.streamvault.app.syncbenchmark` package can opt into this policy for the+ benchmark run or retain the previous policy for comparison.+- Bulk-first AUTO tests remembered category stress independently from+ bulk failure, honors an active full-catalog cooldown, and considers known+ hidden-category coverage. With at least 60% of known live channels hidden, it+ avoids downloading a full list for a selected-category refresh.+- Bulk results are filtered before staging for hidden categories, while+ previously committed hidden rows and required hidden rows are retained.+- Add Provider and Settings Live refresh use the same live strategy. Progress+ labels now distinguish loading, saving/committing, and committed Live TV.+ Committed row counts are reported after catalog promotion.+- Newly added Xtream providers use the bulk-first strategy when live sync is+ left at the default `AUTO` mode.+- Explicit category mode and bulk-failure fallback remain available.++## Branch activation and fresh-build verification (2026-10-10)++The normal debug APK was built from this branch and verified as+`com.streamvault.app.debug`, version `1.0.19-debug` (version code 21). It was+built with `-PcompatAbi=x86_64`; package inspection confirmed native ABIs+`arm64-v8a`, `armeabi-v7a`, and `x86_64`. The saved APK is+`build/xtream-sync-performance/streamvault-bulk-first-debug.apk`. It was+installed on `emulator-5554` with `adb install -r --no-streaming`, preserving+app data; `pm path` confirmed the installed package, and+`monkey -p com.streamvault.app.debug 1` launched it successfully. This is the+branch's ordinary debug app, not the isolated benchmark package or a Play Store+release. It is ready for the user to enter a real provider. No real-provider+credentials or provider requests were used in this validation.++The focused `XtreamLiveSyncPolicyTest` and `CatalogSyncRuntimeProfileTest`+passed, including the normal-package bulk-first default. The isolated benchmark+app and test APKs were then rebuilt, installed without clearing app data, and+rerun against the deterministic local fixture using AUTO with the LOW tier+profile simulated on the API 36 Android TV emulator (192 MB memory class).+Existing per-tier stage-batch sizes were kept.++The provider-completion navigation follow-up uses the shared setup route, so+Xtream, M3U, Stalker, Jellyfin, QR pairing, and backup import all send a newly+created provider to Home. Editing an existing provider still returns to its+launching screen. `ProviderGraphNavigationTest` covers the add-versus-edit+navigation rule. The ordinary debug APK was rebuilt and reinstalled after this+change; the install preserved app data. Real-provider behavior has not yet been+tested.++Build and launch the ordinary branch APK with:++```powershell+.\gradlew.bat :app:assembleDebug -PcompatAbi=x86_64 --console=plain+New-Item -ItemType Directory -Force build/xtream-sync-performance | Out-Null+Copy-Item app/build/outputs/apk/debug/app-debug.apk build/xtream-sync-performance/streamvault-bulk-first-debug.apk -Force+adb -s emulator-5554 install -r --no-streaming build/xtream-sync-performance/streamvault-bulk-first-debug.apk+adb -s emulator-5554 shell monkey -p com.streamvault.app.debug 1+```++| Scenario | State | Coverage | Live requests | Setup elapsed |+| --- | --- | --- | --- | ---: |+| Bulk succeeds | Success | 10,000/10,000 channels and all fixture fields verified; 100 categories | 1 bulk, 0 category | 7.00 s ([report](../build/xtream-sync-performance/20261010T142614124918Z/report.json)) |+| Bulk HTTP 503, then fallback | Partial after complete live fallback | 10,000/10,000 channels and all fixture fields verified; 100 categories | 3 bulk attempts (503), 100 category successes, no post-fallback bulk retries | 16.77 s ([report](../build/xtream-sync-performance/20261010T142632162841Z/report.json)) |++Both runs completed instrumentation successfully. The second run also logged+that queued onboarding recovery was coalesced after the category fallback.+These are single-run synthetic diagnostics, not a performance comparison or a+real-provider/playback acceptance result. The fixture contains no playable+media; sustained playback validation is still deferred.++## Benchmark setup++The isolated debug and Android test APKs were built with:++```powershell+.\gradlew.bat :app:assembleDebug :app:assembleDebugAndroidTest `+ -PxtreamSyncBenchmark=true -PcompatAbi=x86_64+```++The generated application IDs were `com.streamvault.app.syncbenchmark` and+`com.streamvault.app.syncbenchmark.test`. The APKs were installed with+`adb install -r --no-streaming`; application data was not cleared. The device+was the API 36 Android TV emulator (`sdk_google_atv64_x86_64`), with a 192 MB+memory class and a 192 MiB maximum Java heap. All measurements used the debug+benchmark package, a local synthetic provider, 10,000 channels, 100 categories,+and the same 2,426,989-byte fixture payload (`4dfbcaf7…31d63a3`). The fixture+contains no playable media.++Each table row below has one warm-up and five measured setup/refresh pairs.+Request counts are per synthetic account and include both setup and Settings+refresh. Timings cover backend setup or refresh completion; they do not measure+the first usable screen. Java heap is sampled by instrumentation and excludes+native RSS.++## Stage batch exploration++These runs used explicit `STREAM_ALL`. Tier names are policy overrides on one+emulator, not measurements from physical LOW/MID/HIGH devices.++| Tier override | Batch rows | Add Provider median / max (ms) | Settings refresh median / max (ms) | Max sampled Java heap (MB) | Evidence |+| --- | ---: | ---: | ---: | ---: | --- |+| LOW | 100 | 5,726 / 5,777 | 5,541 / 5,657 | 11.3 | [report](../build/xtream-sync-performance/20261010T093957897893Z/report.json) |+| LOW | 128 | 5,518 / 5,529 | 5,223 / 5,393 | 11.6 | [report](../build/xtream-sync-performance/20261010T094107248725Z/report.json) |+| LOW | 256 | 5,255 / 5,446 | 5,092 / 5,137 | 11.6 | [report](../build/xtream-sync-performance/20261010T094217729971Z/report.json) |+| MID | 300 | 5,279 / 5,317 | 5,057 / 5,121 | 12.7 | [report](../build/xtream-sync-performance/20261010T094326043505Z/report.json) |+| MID | 512 | 5,156 / 5,311 | 4,985 / 5,037 | 11.9 | [report](../build/xtream-sync-performance/20261010T094434065503Z/report.json) |+| HIGH | 500 | 4,964 / 5,424 | 4,896 / 5,021 | 13.9 | [report](../build/xtream-sync-performance/20261010T094540490695Z/report.json) |+| HIGH | 1,024 | 3,877 / 3,987 | 3,656 / 3,776 | 12.9 | [report](../build/xtream-sync-performance/20261010T094643512690Z/report.json) |++Every measured operation retained all 10,000 channels and used two bulk live+requests per account, with no category requests. Larger batches were faster in+these sequential runs. The emulator, run order, and synthetic provider limit+that observation; no production batch size is promoted from this result.++## Candidate AUTO and behavior checks++| Scenario | Tier / batch | Add Provider median (ms) | Settings refresh median (ms) | Live requests per account | Evidence |+| --- | --- | ---: | ---: | --- | --- |+| Candidate AUTO | LOW / 256 | 5,043 | 4,932 | 2 bulk, 0 category | [report](../build/xtream-sync-performance/20261010T094742058234Z/report.json) |+| Candidate AUTO | MID / 512 | 5,200 | 4,945 | 2 bulk, 0 category | [report](../build/xtream-sync-performance/20261010T094841875839Z/report.json) |+| Candidate AUTO | HIGH / 1,024 | 5,159 | 4,911 | 2 bulk, 0 category | [report](../build/xtream-sync-performance/20261010T094948164463Z/report.json) |+| 80% hidden before refresh | LOW / 256 | 3,856 | 2,263 | 1 bulk, 20 category | [report](../build/xtream-sync-performance/20261010T095100069509Z/report.json) |+| 80% hidden before refresh | MID / 512 | 3,833 | 1,983 | 1 bulk, 20 category | [report](../build/xtream-sync-performance/20261010T095141776371Z/report.json) |+| 80% hidden before refresh | HIGH / 1,024 | 5,114 | 2,506 | 1 bulk, 20 category | [report](../build/xtream-sync-performance/20261010T095221680576Z/report.json) |+| Remembered category stress | HIGH / 1,024 | 3,663 | 3,516 | 2 bulk, 0 category | [report](../build/xtream-sync-performance/20261010T095319396060Z/report.json) |+| Full-catalog cooldown active | HIGH / 1,024 | 5,053 | 4,676 | 1 bulk, 100 category | [report](../build/xtream-sync-performance/20261010T095408941106Z/report.json) |++Every operation in these groups recorded the expected 10,000-channel count.+The hidden-category runs retained hidden rows while using the 20 visible+categories for the Settings refresh. Remembered category stress did not force+the candidate into category mode. An active bulk cooldown did select category+mode for refresh.++### Bulk HTTP 503 fallback++The 10,000-channel HIGH candidate run with bulk HTTP 503 completed all sample+iterations and preserved the 10,000-row count. Per account, instrumentation+recorded six bulk attempts and 200 category requests across setup and refresh;+the initial phase retried/recovered through category requests, and the active+cooldown kept refresh on categories. The resulting sync state was `Partial`+because the failed bulk attempt remained a warning, despite complete row-count+assertions. Treat this as evidence of data retention and fallback execution,+not a clean-success status.++[Bulk 503 report](../build/xtream-sync-performance/20261010T095515495918Z/report.json)++All reports have `complete=true`, `request_events_truncated=false`, and five+measured samples per phase. The benchmark runner checked instrumentation exit+status and exact row counts. These checks establish the synthetic backend path;+they do not establish provider compatibility or production-device readiness.++## Invalid preliminary batch++The first set of batch measurements ran before the newly built isolated APK was+installed, so its runtime tier and batch overrides were not active. Reports+from `20261010T092817951398Z` through `20261010T093826139108Z` were discarded+and are not used in the tables. The APK was then installed without a data wipe,+and a smoke run confirmed the HIGH candidate settings and two-request route+before collecting the reported measurements.++## Synthetic first-browsable-screen check++The opt-in UI probe launched the isolated app on Welcome, ran the production+`ValidateAndAddProvider.loginXtream` use case against the local fixture, and+waited for the first channel row to become accessible in Live TV. It temporarily+hid empty virtual Favorites and Recent categories so the initial selection was+All Channels, then restored the prior landing and category preferences. This+drives the real navigation and screen but does not interact with the provider+form.++| Fixture / device | Runs | Setup median / max | First browsable row median / max | Channels retained |+| --- | ---: | ---: | ---: | ---: |+| 10,000 live rows / 100 categories; API 36 Android TV emulator; DEVICE policy | 1 warmup + 5 measured | 5.71 / 5.77 s | 6.71 / 6.87 s | 10,000 / 10,000 |++The run peaked at 36,060,832 sampled Java-heap bytes, observed at most two+simultaneous synthetic HTTP requests, recorded all expected samples, and had no+truncated request events. The setup median is backend setup completion; the+first-row median includes navigation and screen readiness. These are debug+emulator measurements, not a physical-device or release-build comparison, and+do not validate media playback.++[First-browsable report](../build/xtream-sync-performance/20261010T113111995992Z/report.json)++## Synthetic background-worker check++The opt-in `--background-worker` probe created one active synthetic provider,+set only its `lastLiveSuccess` metadata stale, and enqueued an actual+no-provider-ID `ProviderSyncWorker` request through WorkManager. This exercises+the provider-enumeration stale-refresh branch used by periodic and launch-stale+work. It waited for the work's terminal state, required `SUCCEEDED`, checked+that all 10,000 channels remained, and required `lastLiveSuccess` to advance.++| Fixture / device | Runs | Worker median / max | Work state | Channels retained |+| --- | ---: | ---: | --- | ---: |+| 10,000 live rows / 100 categories; API 36 Android TV emulator; DEVICE policy | 1 warmup + 1 measured | 5.80 / 5.80 s | SUCCEEDED for both | 10,000 / 10,000 |++The measured synthetic account made two bulk live-list requests (initial setup+and worker refresh), no category-scoped live-list requests, and the fixture+recorded no truncated request events. This validates the worker execution path+and catalog preservation on the debug emulator; it does not validate WorkManager+six-hour scheduling constraints, real-provider behavior, physical devices, or+playback.++[Background-worker report](../build/xtream-sync-performance/20261010T113351914960Z/report.json)++## Direct-test status and release gate++The exploratory data does not meet the P6 release gate. It is from one debug+emulator with simulated policy tiers and a synthetic provider. Bulk-first AUTO+is active in normal app packages on this branch for direct testing.+An opt-in+setup-to-first-browsable-row check now exercises the real Welcome-to-Live UI on+that emulator, but physical LOW, MID, and HIGH device measurements,+release-build memory and first-screen readiness comparison, the user's+real-provider compatibility run, and WorkManager scheduling-constraint+validation remain open. The required two-channel sustained+playback validation also remains open: the fixture has no media, and no real+provider has yet been tested. Follow the repository live-TV validation+instructions for that playback run. Stage-batch defaults stay unchanged pending+broader device evidence.diff --git a/docs/XTREAM_SYNC_P7_IMPLEMENTATION.md b/docs/XTREAM_SYNC_P7_IMPLEMENTATION.mdnew file mode 100644index 00000000..acbe9f00--- /dev/null+++ b/docs/XTREAM_SYNC_P7_IMPLEMENTATION.md@@ -0,0 +1,241 @@+# P7 Xtream summary and background work++Status: P7 implementation, the synthetic emulator matrix, the pre-change+unchanged-refresh comparison, and the fingerprint-allocation follow-up are+complete. Physical-device tuning is deferred; full release validation remains+pending.++| Work item | Status | Evidence / remaining |+| --- | --- | --- |+| P7 implementation | Done | Summary diffing/fingerprints, local and hydrated state preservation, checkpointed tier slices, catalog-before-guide scheduling, focused tests, and APK builds |+| Small-catalog bulk-fallback tier sweep | Done | 2,000 movies / 1,000 series; LOW, MID, HIGH, and DEVICE profiles; five measured runs per profile |+| Bulk-success and larger-catalog comparisons | Done | 2k/1k DEVICE bulk success (five runs), 8k/4k DEVICE bulk success (three runs), and 8k/4k LOW bulk fallback (two runs) |+| Emulator Room preservation check | Done | Each run's warmup refreshed stale titles while retaining local IDs, hydrated fields, watch history, protection flags, playback metadata, and hydrated index timestamps |+| Fingerprint allocation follow-up | Done | Replaced per-byte formatter and per-field ByteBuffer allocations without changing digest bytes; sampled unchanged-refresh heap fell on both tested routes |+| Physical-device tuning | Deferred | No physical devices are available |+| Before/after unchanged VOD refresh comparison | Done | Ten measured bulk-success runs and five measured fallback runs per build on the same API 36 emulator; bulk success was about 60% faster, category fallback was effectively unchanged, and sampled Java heap increased |+| P8 end-to-end release validation | Pending | Real-provider validation and sustained live playback remain outstanding |++Date: 2026-10-10+Branch: `codex/xtream-live-sync-performance`++## Summary indexing++The existing summary executor continues to stream full movie/series responses+first and fall back to category work when full streaming fails or a priority+category is requested. Category work now receives a device-tier slice budget:++| Tier | Categories per slice | Target rows | Target duration |+| --- | ---: | ---: | ---: |+| LOW | 4 | 1,000 | 10 s |+| MID | 8 | 3,000 | 20 s |+| HIGH | 16 | 8,000 | 30 s |++The executor checkpoints `nextCategoryIndex` after each completed category and+schedules continuation work when categories remain. A fetch is atomic at the+category boundary, so one unusually large or slow category can exceed its row+or time target before the next checkpoint. The budgets are conservative initial+values, not measured production tuning.++Summary persistence computes stable remote-field fingerprints, compares+existing movie/series rows, and writes only changed summaries. Index projections+are compared without the changing `indexedAt` field, so unchanged refreshes do+not rewrite the same index rows. Existing local IDs, movie watch state,+protection, TMDB identity, hydrated detail fields and local playback metadata+are preserved. The summary fingerprint excludes local watch, protection,+hydration and playback-metadata state.++## Scheduling and guide handoff++Xtream movie and series indexing continuations are scheduled before guide work.+Guide work uses a separate unique WorkManager chain and defers while any Xtream+LIVE, MOVIE or SERIES index job is queued or running. This keeps guide retries+from occupying the provider catalog continuation chain. Settings can continue+to report the durable live/movie/series index state separately from EPG state.++## Verification completed++- `XtreamIncrementalIndexExecutorTest`: row and duration budget checkpoint+ coverage passed.+- `XtreamSummaryFingerprintTest`: remote summary changes affect fingerprints;+ local watch, hydration, protection and playback-metadata changes do not.+- `ProviderContinuationSchedulerTest`: catalog continuations precede guide+ work.+- Focused `SyncManagerTest` passed all 98 tests, including changed-row and+ index-projection cases. `SyncManagerXtreamLiveStrategyTest` also passed.+- The app and benchmark debug APKs assembled successfully with the new worker+ interfaces and instrumentation sources.+- The synthetic performance fixture now supports deterministic movie and+ series summaries, independent category counts and payload hashes, and+ configurable bulk VOD/series rejection with category fallback.+- Fixture and report tests passed: `python -m unittest+ tools.tests.test_xtream_sync_perf_fixture+ tools.tests.test_xtream_sync_benchmark` (13 tests).+- The API 36 Android TV emulator completed a LOW-tier scenario with 1,000 live+ channels, 2,000 movies across 20 categories, and 1,000 series across 10+ categories. Bulk movie and series requests returned 503, then category+ fallback completed all sections. One warmup plus five measured runs were+ recorded; all six instrumentation samples completed and request events were+ not truncated.+- On each measured run, live import committed 1,000 rows, movie and series+ jobs ended in `SUCCESS`, and both Room entities and active index projections+ matched the expected 2,000 movie / 1,000 series counts. Median index+ completion was 8.593 s for movies and 8.594 s for series from setup start;+ median completion after Live TV commit was 7.930 s and 7.931 s respectively.+ Each measured account used 1 bulk plus 20 category movie requests, and 1 bulk+ plus 10 category series requests.+- The warmup Room check deliberately seeded an old title, hydrated detail,+ protection state, playback metadata, and playback-history progress, then+ forced both summary sections to reindex. The remote titles refreshed while+ stable IDs and local/hydrated fields remained intact. Both Xtream content+ index rows retained the hydrated timestamp. This check does not use playable+ media.+- The harness sampled Java heap and ART GC during summary indexing; aggregate+ maxima across all profiles and catalog sizes are recorded below.++## Emulator matrix results++All runs used the API 36 Android TV x86_64 emulator (192 MB memory class,+201,326,592-byte Java max heap), synthetic data, and a stage batch override of+256. LOW/MID/HIGH are simulated policy budgets on that same emulator. Times are+from setup start; the after-Live column subtracts the recorded Live commit+milestone. Each report completed every expected instrumentation sample without+truncated request events. Every measured sample reached `SUCCESS` for both+summary jobs and had Room row counts matching its fixture. Each configured+warmup reported `room_preservation_verified=true`.++Small catalog, category fallback (one bulk request rejected with 503, then one+request per category):++| Profile | Measured runs | Movie median (s) | Movie after Live (s) | Series median (s) | Series after Live (s) | Max sampled summary heap (MB) | Max GC delta |+| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |+| LOW | 5 | 8.593 | 7.930 | 8.594 | 7.931 | 12.78 | 35 |+| DEVICE | 5 | 7.961 | 7.507 | 7.963 | 7.509 | 10.70 | 35 |+| MID | 5 | 7.946 | 7.500 | 7.947 | 7.502 | 11.29 | 34 |+| HIGH | 5 | 7.961 | 7.509 | 7.962 | 7.510 | 10.02 | 32 |++Bulk-success and larger-catalog comparisons:++| Scenario | Measured runs | Movies / series | Movie median (s) | Series median (s) | Requests per measured sample (movie / series) |+| --- | ---: | ---: | ---: | ---: | --- |+| DEVICE, bulk success | 5 | 2,000 / 1,000 | 1.856 | 1.857 | 1 full + 0 category / 1 full + 0 category |+| DEVICE, bulk success | 3 | 8,000 / 4,000 | 5.241 | 5.243 | 1 full + 0 category / 1 full + 0 category |+| LOW, category fallback | 2 | 8,000 / 4,000 | 30.596 | 30.598 | 1 rejected full + 80 category / 1 rejected full + 40 category |++For the small fixture, the synthetic bulk-success path completed sooner than+fallback: about 1.86 s versus 7.95–8.59 s across the tested fallback profiles.+For the larger fixture, LOW-tier fallback completed all rows and checkpoints+in about 30.6 s. These are path and policy observations on one debug emulator;+they are not a before/after optimization result or production-device targets.+The largest measured summary heap sample was 12.89 MB, and the largest ART GC+count delta was 148 in the 8k/4k LOW fallback run. Heap sampling was every 50 ms+and does not include native RSS or allocation attribution.++## Pre-change comparison: unchanged VOD refresh++The probe first imports one deterministic catalog and waits for successful+movie/series jobs. It then invokes the existing forced summary-index command+once for movies and once for series, sequentially, without changing the fixture+or local rows. The reported combined time is the per-sample sum of those two+calls; it excludes setup, authentication and live import. Each sample verifies+the movie/series Room row counts and active search-index counts afterward.++Both builds used the API 36 Android TV x86_64 emulator (192 MB memory class,+201,326,592-byte Java max heap), LOW policy and 100-row stage batches. The+pre-change build is commit `2af03f5149e888d25307457d4cce82fab3de74d9`; P7 was+built from the same base commit plus the current uncommitted working-tree+changes. Each run used one warmup and five measured accounts, the same seed,+the same 1,000-channel / 2,000-movie / 1,000-series fixture, identical movie+and series payload hashes, and successful instrumentation. Bulk success used+three warmups and ten measured accounts per build. Category fallback used one+warmup and five measured accounts per build. All samples completed; medians+below exclude the warmups. Bulk success returned HTTP 200. Fallback returned+HTTP 503 for both full summary requests, then served the categories.++| Route | Build | Movie refresh median (s) | Series refresh median (s) | Sequential VOD median (s) | Max sampled heap (MiB) | Max ART GC delta |+| --- | --- | ---: | ---: | ---: | ---: | ---: |+| Bulk success, 10 measured | Pre-P7 | 0.886 | 0.883 | 1.769 | 10.09 | 23 |+| Bulk success, 10 measured | P7 | 0.478 | 0.234 | 0.713 | 17.19 | 24 |+| Category fallback, 5 measured | Pre-P7 | 5.232 | 2.688 | 7.906 | 9.01 | 21 |+| Category fallback, 5 measured | P7 | 5.212 | 2.628 | 7.836 | 10.83 | 31 |++On bulk success, the unchanged sequential refresh median fell by 59.69% (2.48x+faster). The full ten-sample series is retained because baseline refresh times+settled during the measured run even after three warmups; no measured samples+were trimmed. Category fallback fell by 0.89%, which is effectively unchanged+at this sample size and should not be presented as a fallback speedup. Request+counts matched between builds: bulk success used two full movie and two full+series requests per account; fallback used two rejected full requests plus 40+movie-category and 20 series-category requests per account. Those totals cover+initial indexing plus the explicit repeated refresh.++The refresh-path maximum sampled Java heap rose from 10.09 to 17.19 MiB on bulk+success and from 9.01 to 10.83 MiB on fallback; maximum ART GC deltas were 24+and 31 for P7. This is an observed emulator memory tradeoff to carry into+physical-device tuning. Java heap is sampled every 50 ms and is not native RSS+or allocation attribution. These results support a route-specific bulk-refresh+gain, not a general VOD speedup claim or a release-device conclusion.++All four reports show successful instrumentation, complete request events and+exact Room/index coverage. The P7 working-tree build is identified by app APK+SHA-256 `FA643853B4CA8008F3FB68B61A7C7D1EC41D76B21145AF7D6022D8F296FA07E7`;+the pre-change app APK is `29E1238BEE4AFAF70CE161A18296AD0AF55E32574BF094413646DF9B468438C9`.+The baseline probe source is retained in the temporary baseline checkout at+`build/xtream-sync-p7-baseline/app/src/androidTest/java/com/streamvault/app/benchmark/XtreamLiveSyncBenchmarkTest.kt`.++## Fingerprint allocation follow-up++Inspection of `XtreamSummaryFingerprint` found repeated allocation in the hot+path: each non-null field created a `ByteBuffer` for its four-byte length+prefix, and every output digest byte called `String.format`. The implementation+now writes the same big-endian length prefix directly and encodes the digest+with a fixed lowercase hexadecimal lookup table. Field order, null markers,+UTF-8 field bytes, SHA-256, and persisted fingerprint values remain unchanged.++The optimized build was compared with the recorded P7 build using the same API+36 Android TV x86_64 emulator, LOW policy, 100-row stage batch, seed, and+2,000-movie / 1,000-series payload hashes. Bulk success used three warmups and+ten measured runs; fallback used one warmup and five measured runs. All+instrumentation samples completed, request events were not truncated, and+Room plus active-index counts matched the fixture.++| Route | Build | Movie median (s) | Series median (s) | Sequential VOD median (s) | Max sampled heap (MiB) | Max ART GC delta |+| --- | --- | ---: | ---: | ---: | ---: | ---: |+| Bulk success, 10 measured | P7 | 0.478 | 0.234 | 0.713 | 17.19 | 24 |+| Bulk success, 10 measured | Fingerprint allocation follow-up | 0.447 | 0.206 | 0.652 | 11.61 | 15 |+| Category fallback, 5 measured | P7 | 5.212 | 2.628 | 7.836 | 10.83 | 31 |+| Category fallback, 5 measured | Fingerprint allocation follow-up | 5.232 | 2.629 | 7.857 | 8.07 | 18 |++The sampled refresh peak fell by 32.4% on bulk success and 25.5% on fallback+relative to P7. Bulk refresh time was 8.5% lower in this follow-up run; the+fallback time was 0.27% higher and remains effectively unchanged. Treat these+time differences as emulator observations, not a new speed claim. Compared+with the pre-P7 build, bulk sampled peak remains 1.52 MiB higher while fallback+is 0.94 MiB lower. Heap is sampled every 50 ms and this does not attribute+allocations or measure native RSS.++The optimized app APK SHA-256 is+`A77C0E63F0172C6C91EE91DEEE57B61C3A6BEEB46821E68196EB8C2B7D18E783`. Reports:++- `build/xtream-sync-performance/p7-post-fingerprint-optimized-bulk-2k-1k-low-10x3/report.json`+- `build/xtream-sync-performance/p7-post-fingerprint-optimized-fallback-2k-1k-low-5x1/report.json`++Local full reports are stored under the following ignored build directories:++- `build/xtream-sync-performance/20261010T111134999266Z/report.json` — LOW fallback.+- `build/xtream-sync-performance/20261010T111449834886Z/report.json` — DEVICE fallback.+- `build/xtream-sync-performance/20261010T111551636742Z/report.json` — MID fallback.+- `build/xtream-sync-performance/20261010T111652926306Z/report.json` — HIGH fallback.+- `build/xtream-sync-performance/20261010T111807126816Z/report.json` — DEVICE bulk success.+- `build/xtream-sync-performance/20261010T111829207899Z/report.json` — 8k/4k DEVICE bulk success.+- `build/xtream-sync-performance/20261010T111935389752Z/report.json` — 8k/4k LOW fallback.+- `build/xtream-sync-performance/p7-pre-change-phase-aligned-bulk-2k-1k-10x3/report.json` — pre-P7 unchanged bulk refresh, ten measured runs.+- `build/xtream-sync-performance/p7-post-change-refresh-bulk-2k-1k-low-10x3/report.json` — P7 unchanged bulk refresh, ten measured runs.+- `build/xtream-sync-performance/p7-pre-change-refresh-fallback-2k-1k/report.json` — pre-P7 unchanged fallback refresh.+- `build/xtream-sync-performance/p7-post-change-refresh-fallback-2k-1k-low/report.json` — P7 unchanged fallback refresh.++These synthetic runs used no real provider or playable media. Physical-device+tuning is deferred because no physical devices are available. The branch debug+APK is now installed for user-side provider testing, but live playback has not+yet been validated. Follow the sustained capture and log requirements in+`AGENTS.md` when recording that run.diff --git a/docs/XTREAM_SYNC_RESUME_IMPLEMENTATION.md b/docs/XTREAM_SYNC_RESUME_IMPLEMENTATION.mdindex 8b7a32f5..a86ae47e 100644--- a/docs/XTREAM_SYNC_RESUME_IMPLEMENTATION.md+++ b/docs/XTREAM_SYNC_RESUME_IMPLEMENTATION.md@@ -66,4 +66,6 @@ final sync state was Success.Large-catalog writer cost remains substantial. This work removes duplicateprimary retrieval; it does not claim to meet the complete latency target.-AUTO strategy selection and the complete P6 acceptance matrix remain open.+Normal app builds on this branch now use bulk-first AUTO. The policy change and+fresh synthetic rechecks are documented in the [P6 tuning report](XTREAM_SYNC_P6_TUNING_REPORT.md);+physical-device and first-screen acceptance remain open.diff --git a/feature/provider/src/main/java/com/streamvault/feature/provider/navigation/ProviderGraph.kt b/feature/provider/src/main/java/com/streamvault/feature/provider/navigation/ProviderGraph.ktindex e59eb1eb..52ab83fb 100644--- a/feature/provider/src/main/java/com/streamvault/feature/provider/navigation/ProviderGraph.kt+++ b/feature/provider/src/main/java/com/streamvault/feature/provider/navigation/ProviderGraph.kt@@ -7,6 +7,7 @@ import androidx.navigation.compose.composableimport androidx.navigation.navArgumentimport com.streamvault.core.navigation.AppDestinationimport com.streamvault.core.navigation.NavigationActions+import com.streamvault.core.navigation.NavigationOptionsimport com.streamvault.feature.provider.api.ProviderBackupPreviewContentimport com.streamvault.feature.provider.setup.ProviderSetupScreen@@ -31,7 +32,9 @@ fun NavGraphBuilder.registerProviderGraph(onBack = { actions.back() },backupPreviewContent = backupPreviewContent,onProviderAdded = dropUnlessResumed {- completeProviderSetup(actions) {+ // All create-provider protocols finish through this shared route.+ // Only edits return to the screen that launched setup.+ completeProviderSetup(actions, isEditing = providerId != null) {onStartupNavigationRequested(AppDestination.ProviderSetup())}}@@ -41,9 +44,19 @@ fun NavGraphBuilder.registerProviderGraph(internal fun completeProviderSetup(actions: NavigationActions,+ isEditing: Boolean,onStartupNavigationRequested: () -> Unit) {- if (!actions.back()) {+ if (!isEditing) {+ actions.navigate(+ AppDestination.Home,+ NavigationOptions(+ launchSingleTop = true,+ popUpTo = AppDestination.ProviderSetup(),+ inclusive = true+ )+ )+ } else if (!actions.back()) {onStartupNavigationRequested()}}diff --git a/feature/provider/src/test/java/com/streamvault/feature/provider/navigation/ProviderGraphNavigationTest.kt b/feature/provider/src/test/java/com/streamvault/feature/provider/navigation/ProviderGraphNavigationTest.ktindex a988bc65..41149071 100644--- a/feature/provider/src/test/java/com/streamvault/feature/provider/navigation/ProviderGraphNavigationTest.kt+++ b/feature/provider/src/test/java/com/streamvault/feature/provider/navigation/ProviderGraphNavigationTest.kt@@ -12,12 +12,12 @@ class ProviderGraphNavigationTest {fun completedProviderSetup_popsBackToSettingsWhenLaunchedFromSettings() {var backCalls = 0var startupRequests = 0- val actions = fakeNavigationActions {+ val actions = fakeNavigationActions(onBack = {backCalls++true- }+ })- completeProviderSetup(actions) { startupRequests++ }+ completeProviderSetup(actions, isEditing = true) { startupRequests++ }assertThat(backCalls).isEqualTo(1)assertThat(startupRequests).isEqualTo(0)@@ -26,16 +26,42 @@ class ProviderGraphNavigationTest {@Testfun completedProviderSetup_usesStartupNavigationWhenItHasNoBackStackEntry() {var startupRequests = 0- val actions = fakeNavigationActions { false }+ val actions = fakeNavigationActions(onBack = { false })- completeProviderSetup(actions) { startupRequests++ }+ completeProviderSetup(actions, isEditing = true) { startupRequests++ }assertThat(startupRequests).isEqualTo(1)}- private fun fakeNavigationActions(onBack: () -> Boolean): NavigationActions =+ @Test+ fun completedNewProviderSetup_navigatesHomeAndRemovesSetupRoute() {+ var backCalls = 0+ var startupRequests = 0+ var navigation: Pair<AppDestination, NavigationOptions>? = null+ val actions = fakeNavigationActions(+ onBack = {+ backCalls+++ true+ },+ onNavigate = { destination, options -> navigation = destination to options }+ )++ completeProviderSetup(actions, isEditing = false) { startupRequests++ }++ assertThat(backCalls).isEqualTo(0)+ assertThat(startupRequests).isEqualTo(0)+ assertThat(navigation?.first).isEqualTo(AppDestination.Home)+ assertThat(navigation?.second?.popUpTo).isEqualTo(AppDestination.ProviderSetup())+ assertThat(navigation?.second?.inclusive).isTrue()+ }++ private fun fakeNavigationActions(+ onBack: () -> Boolean,+ onNavigate: (AppDestination, NavigationOptions) -> Unit = { _, _ -> }+ ): NavigationActions =object : NavigationActions {- override fun navigate(destination: AppDestination, options: NavigationOptions) = Unit+ override fun navigate(destination: AppDestination, options: NavigationOptions) =+ onNavigate(destination, options)override fun openPlayer(request: PlayerNavigationRequest) = Unitoverride fun back(): Boolean = onBack()override fun returnTo(destination: AppDestination?): Boolean = falsediff --git a/feature/system/src/androidTest/java/com/streamvault/feature/system/presentation/welcome/WelcomePresentationTest.kt b/feature/system/src/androidTest/java/com/streamvault/feature/system/presentation/welcome/WelcomePresentationTest.ktindex 284c6769..855399ce 100644--- a/feature/system/src/androidTest/java/com/streamvault/feature/system/presentation/welcome/WelcomePresentationTest.kt+++ b/feature/system/src/androidTest/java/com/streamvault/feature/system/presentation/welcome/WelcomePresentationTest.kt@@ -91,6 +91,6 @@ class WelcomePresentationTest {composeRule.onNodeWithText("VOD").assertIsDisplayed()composeRule.onNodeWithText("Movies").assertIsDisplayed()- composeRule.onNodeWithText("44 items indexed").assertIsDisplayed()+ composeRule.onNodeWithText("44 items prepared").assertIsDisplayed()}}diff --git a/feature/system/src/main/res/values-ar/strings.xml b/feature/system/src/main/res/values-ar/strings.xmlindex 1f8947d2..533c5ab5 100644--- a/feature/system/src/main/res/values-ar/strings.xml+++ b/feature/system/src/main/res/values-ar/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">البث المباشر</string><string name="sync_section_vod">الأفلام والمسلسلات</string><string name="sync_section_series">المسلسلات</string>- <string name="sync_items_indexed_format">تمت فهرسة %1$d عنصرًا</string>+ <string name="sync_items_indexed_format">تم تجهيز %1$d عنصرًا</string><string name="welcome_tagline">تجربة IPTV متميّزة مصمَّمة لشاشة غرفة المعيشة</string><string name="welcome_subtitle">ارجع إلى القنوات المباشرة وتابع ما بدأت مشاهدته واستكشف الأفلام والمسلسلات بتجربة Android TV أصيلة.</string><string name="settings_cancel">إلغاء</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-cs/strings.xml b/feature/system/src/main/res/values-cs/strings.xmlindex abb9dda6..f7a519a9 100644--- a/feature/system/src/main/res/values-cs/strings.xml+++ b/feature/system/src/main/res/values-cs/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">Prémiové IPTV do obýváku</string><string name="welcome_subtitle">Pohodlně si užijte živé kanály, zpětné sledování, filmy a seriály v nativním prostředí Android TV.</string><string name="settings_cancel">Zrušit</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-da/strings.xml b/feature/system/src/main/res/values-da/strings.xmlindex 25455d7f..984333b3 100644--- a/feature/system/src/main/res/values-da/strings.xml+++ b/feature/system/src/main/res/values-da/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">Premium IPTV til stuen</string><string name="welcome_subtitle">Læn dig tilbage til livekanaler, catch-up, film og serier med en førsteparts Android TV-oplevelse.</string><string name="settings_cancel">Annuller</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-de/strings.xml b/feature/system/src/main/res/values-de/strings.xmlindex 90a2543b..94409d81 100644--- a/feature/system/src/main/res/values-de/strings.xml+++ b/feature/system/src/main/res/values-de/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">Premium-IPTV für das Wohnzimmer</string><string name="welcome_subtitle">Lehnen Sie sich zurück und genießen Sie Live-Kanäle, Catch-up, Filme und Serien mit einer erstklassigen Android-TV-Erfahrung.</string><string name="settings_cancel">Abbrechen</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-el/strings.xml b/feature/system/src/main/res/values-el/strings.xmlindex b12e46b9..c587ac5e 100644--- a/feature/system/src/main/res/values-el/strings.xml+++ b/feature/system/src/main/res/values-el/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">Premium IPTV για το σαλόνι</string><string name="welcome_subtitle">Χαλαρώστε με ζωντανά κανάλια, catch-up προβολή, ταινίες και σειρές με μια εμπειρία Android TV πρώτης κατηγορίας.</string><string name="settings_cancel">Ακύρωση</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-es/strings.xml b/feature/system/src/main/res/values-es/strings.xmlindex de0e2526..53191ed6 100644--- a/feature/system/src/main/res/values-es/strings.xml+++ b/feature/system/src/main/res/values-es/strings.xml@@ -7,8 +7,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">IPTV premium para la sala</string><string name="welcome_subtitle">Vuelve a disfrutar de canales en vivo, ponte al día, películas y series con una experiencia de Android TV propia.</string><string name="settings_cancel">Cancelar</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-fi/strings.xml b/feature/system/src/main/res/values-fi/strings.xmlindex c2449604..553b7709 100644--- a/feature/system/src/main/res/values-fi/strings.xml+++ b/feature/system/src/main/res/values-fi/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">Premium IPTV olohuoneeseen</string><string name="welcome_subtitle">Nojaa takaisin live-kanaviin, katseluhetkiin, elokuviin ja sarjoihin ensimmäisen osapuolen Android TV -kokemuksella.</string><string name="settings_cancel">Peruuta</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-fr/strings.xml b/feature/system/src/main/res/values-fr/strings.xmlindex f1665445..5838e1aa 100644--- a/feature/system/src/main/res/values-fr/strings.xml+++ b/feature/system/src/main/res/values-fr/strings.xml@@ -7,8 +7,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Séries</string>- <string name="sync_items_indexed_format">%1$d éléments indexés</string>+ <string name="sync_items_indexed_format">%1$d éléments préparés</string><string name="welcome_tagline">IPTV premium pour le salon</string><string name="welcome_subtitle">Profitez des chaînes en direct, du visionnage de rattrapage, des films et des séries avec une expérience Android TV propriétaire.</string><string name="settings_cancel">Annuler</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-hu/strings.xml b/feature/system/src/main/res/values-hu/strings.xmlindex 762eb141..edc994de 100644--- a/feature/system/src/main/res/values-hu/strings.xml+++ b/feature/system/src/main/res/values-hu/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">Prémium IPTV a nappaliba</string><string name="welcome_subtitle">Dőlj hátra élő csatornák, visszanézés, filmek és sorozatok között egy Android TV-élménnyel.</string><string name="settings_cancel">Mégse</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-in/strings.xml b/feature/system/src/main/res/values-in/strings.xmlindex aae0321d..546e8b0f 100644--- a/feature/system/src/main/res/values-in/strings.xml+++ b/feature/system/src/main/res/values-in/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">IPTV premium untuk ruang tamu</string><string name="welcome_subtitle">Nikmati kembali saluran langsung, tayangan lanjutan, film, dan serial dengan pengalaman Android TV pihak pertama.</string><string name="settings_cancel">Batalkan</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-it/strings.xml b/feature/system/src/main/res/values-it/strings.xmlindex 008c68b6..4be5c959 100644--- a/feature/system/src/main/res/values-it/strings.xml+++ b/feature/system/src/main/res/values-it/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">IPTV premium per il soggiorno</string><string name="welcome_subtitle">Rilassati sui canali live, sulla visione di recupero, sui film e sulle serie con un\'esperienza Android TV proprietaria.</string><string name="settings_cancel">Annulla</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-iw/strings.xml b/feature/system/src/main/res/values-iw/strings.xmlindex 917d5ddd..4119b9ab 100644--- a/feature/system/src/main/res/values-iw/strings.xml+++ b/feature/system/src/main/res/values-iw/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">IPTV פרימיום לסלון</string><string name="welcome_subtitle">הישען אחורה אל ערוצים חיים, צפייה בהתעדכנות, סרטים וסדרות עם חווית Android TV של צד ראשון.</string><string name="settings_cancel">בטל</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-ja/strings.xml b/feature/system/src/main/res/values-ja/strings.xmlindex c781df36..1aa22495 100644--- a/feature/system/src/main/res/values-ja/strings.xml+++ b/feature/system/src/main/res/values-ja/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">リビング向けのプレミアムIPTV</string><string name="welcome_subtitle">ライブチャンネル、見逃し視聴、映画、シリーズを、Android TVの純正体験でゆったり楽しめます。</string><string name="settings_cancel">キャンセル</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-ko/strings.xml b/feature/system/src/main/res/values-ko/strings.xmlindex 6ca7e90f..ba0ed4c9 100644--- a/feature/system/src/main/res/values-ko/strings.xml+++ b/feature/system/src/main/res/values-ko/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">거실을 위한 프리미엄 IPTV</string><string name="welcome_subtitle">라이브 채널, 다시보기, 영화, 시리즈를 Android TV에 최적화된 환경으로 편하게 즐기세요.</string><string name="settings_cancel">취소</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-nb/strings.xml b/feature/system/src/main/res/values-nb/strings.xmlindex e60f2c14..fe45d9ef 100644--- a/feature/system/src/main/res/values-nb/strings.xml+++ b/feature/system/src/main/res/values-nb/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">Premium IPTV for stuen</string><string name="welcome_subtitle">Len deg tilbake med direktesendte kanaler, opptak, filmer og serier med en førsteparts Android TV-opplevelse.</string><string name="settings_cancel">Avbryt</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-nl/strings.xml b/feature/system/src/main/res/values-nl/strings.xmlindex 6205e410..48953dca 100644--- a/feature/system/src/main/res/values-nl/strings.xml+++ b/feature/system/src/main/res/values-nl/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">Premium IPTV voor de woonkamer</string><string name="welcome_subtitle">Geniet van live kanalen, terugblik, films en series met een eersteklas Android TV-ervaring.</string><string name="settings_cancel">Annuleer</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-pl/strings.xml b/feature/system/src/main/res/values-pl/strings.xmlindex 3e0b68d3..c0f8fe2f 100644--- a/feature/system/src/main/res/values-pl/strings.xml+++ b/feature/system/src/main/res/values-pl/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">Premium IPTV do salonu</string><string name="welcome_subtitle">Oglądaj kanały na żywo, catch-up, filmy i seriale w natywnym doświadczeniu Android TV.</string><string name="settings_cancel">Anuluj</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-pt/strings.xml b/feature/system/src/main/res/values-pt/strings.xmlindex b1515b4f..c4bef15a 100644--- a/feature/system/src/main/res/values-pt/strings.xml+++ b/feature/system/src/main/res/values-pt/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">IPTV premium para a sala</string><string name="welcome_subtitle">Aproveite os canais ao vivo, assista a filmes e séries com uma experiência Android TV original.</string><string name="settings_cancel">Cancelar</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-ro/strings.xml b/feature/system/src/main/res/values-ro/strings.xmlindex d7ea218f..6e5394f4 100644--- a/feature/system/src/main/res/values-ro/strings.xml+++ b/feature/system/src/main/res/values-ro/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">IPTV premium pentru camera de zi</string><string name="welcome_subtitle">Retrăiește-te la canalele live, la vizionarea de recăpătare, la filme și la seriale cu o experiență Android TV originală.</string><string name="settings_cancel">Anulează</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-ru/strings.xml b/feature/system/src/main/res/values-ru/strings.xmlindex a01b7aaf..e87940f6 100644--- a/feature/system/src/main/res/values-ru/strings.xml+++ b/feature/system/src/main/res/values-ru/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">Премиум IPTV для гостиной</string><string name="welcome_subtitle">Откиньтесь и смотрите прямые каналы, архив, фильмы и сериалы в нативном Android TV-интерфейсе.</string><string name="settings_cancel">Отмена</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-sv/strings.xml b/feature/system/src/main/res/values-sv/strings.xmlindex 5e292a90..11e4cf57 100644--- a/feature/system/src/main/res/values-sv/strings.xml+++ b/feature/system/src/main/res/values-sv/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">Premium-IPTV för vardagsrummet</string><string name="welcome_subtitle">Slappna av med livekanaler, reprisvisning, filmer och serier med en förstklassig Android TV-upplevelse.</string><string name="settings_cancel">Avbryt</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-tr/strings.xml b/feature/system/src/main/res/values-tr/strings.xmlindex e69256b2..cecedc82 100644--- a/feature/system/src/main/res/values-tr/strings.xml+++ b/feature/system/src/main/res/values-tr/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">Oturma odası için premium IPTV</string><string name="welcome_subtitle">Canlı kanallar, geri sarma izleme, filmler ve dizilerle Android TV\'ye özel bir deneyimde rahatlayın.</string><string name="settings_cancel">İptal</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-uk/strings.xml b/feature/system/src/main/res/values-uk/strings.xmlindex d8dc6b60..482f08bd 100644--- a/feature/system/src/main/res/values-uk/strings.xml+++ b/feature/system/src/main/res/values-uk/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">Преміум IPTV для вітальні</string><string name="welcome_subtitle">Відпочивайте, переглядаючи прямі канали, архів, фільми та серіали в нативному досвіді Android TV.</string><string name="settings_cancel">Скасувати</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-vi/strings.xml b/feature/system/src/main/res/values-vi/strings.xmlindex f7fe7746..0efbb420 100644--- a/feature/system/src/main/res/values-vi/strings.xml+++ b/feature/system/src/main/res/values-vi/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">IPTV cao cấp cho phòng khách</string><string name="welcome_subtitle">Thư giãn với kênh trực tiếp, xem lại, phim và series với trải nghiệm Android TV chính chủ.</string><string name="settings_cancel">Hủy</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values-zh/strings.xml b/feature/system/src/main/res/values-zh/strings.xmlindex 192a9f75..46c85965 100644--- a/feature/system/src/main/res/values-zh/strings.xml+++ b/feature/system/src/main/res/values-zh/strings.xml@@ -6,8 +6,8 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">客厅里的高级 IPTV</string><string name="welcome_subtitle">轻松观看直播频道、回看、电影和剧集,享受原生 Android TV 体验。</string><string name="settings_cancel">取消</string>-</resources>\ No newline at end of file+</resources>diff --git a/feature/system/src/main/res/values/strings.xml b/feature/system/src/main/res/values/strings.xmlindex b02043f8..0ec0d591 100644--- a/feature/system/src/main/res/values/strings.xml+++ b/feature/system/src/main/res/values/strings.xml@@ -8,7 +8,7 @@<string name="sync_section_live">Live</string><string name="sync_section_vod">VOD</string><string name="sync_section_series">Series</string>- <string name="sync_items_indexed_format">%1$d items indexed</string>+ <string name="sync_items_indexed_format">%1$d items prepared</string><string name="welcome_tagline">Premium IPTV for the living room</string><string name="welcome_subtitle">Lean back into live channels, catch-up viewing, movies, and series with a first-party Android TV experience.</string><string name="settings_cancel">Cancel</string>@@ -33,4 +33,4 @@<string name="download_resume">Resume</string><string name="download_delete">Delete</string><string name="downloads_resumed">Download resumed</string>-</resources>\ No newline at end of file+</resources>diff --git a/tools/tests/test_xtream_sync_benchmark.py b/tools/tests/test_xtream_sync_benchmark.pyindex f98d8897..d6eb9eb2 100644--- a/tools/tests/test_xtream_sync_benchmark.py+++ b/tools/tests/test_xtream_sync_benchmark.py@@ -11,6 +11,18 @@ SPEC.loader.exec_module(BENCHMARK)class BenchmarkReportTest(unittest.TestCase):+ def test_quiescence_detects_bulk_restarted_after_category_fallback(self):+ samples = [{"event": "sample", "run": "bench_test", "mode": "AUTO", "phase": "initial",+ "warmup": False, "elapsed_ms": 1, "channels": 1, "peak_java_heap_bytes": 1,+ "settle_seconds": 30}]+ events = [{"event": "request_start", "request_id": i, "run": "bench_test",+ "action": "get_live_streams", "category_id": category}+ for i, category in enumerate([None, None, 1, 2, None], 1)]+ report = BENCHMARK.summarize(samples, events, {})+ self.assertEqual(1, report["samples"][0]["bulk_requests_after_fallback"])+ report = BENCHMARK.summarize(samples, events[:-1], {})+ self.assertEqual(0, report["samples"][0]["bulk_requests_after_fallback"])+def test_pipeline_metrics_are_numeric_and_exact_format_only(self):log = '\n'.join(['I/XtreamSyncTiming( 123): phase=live-pipeline rows=100 batches=10 reader_ms=20 drain_ms=3 send_wait_ms=8 outstanding_batch_bytes=1024 queue_capacity=1 batch_byte_limit=4096',diff --git a/tools/tests/test_xtream_sync_perf_fixture.py b/tools/tests/test_xtream_sync_perf_fixture.pyindex 3fd7aff4..2cf69694 100644--- a/tools/tests/test_xtream_sync_perf_fixture.py+++ b/tools/tests/test_xtream_sync_perf_fixture.py@@ -33,6 +33,25 @@ class XtreamSyncPerfFixtureTest(unittest.TestCase):FIXTURE.Scenario(channels=103, categories=12, seed=2).metadata()["payload_sha256"])self.assertEqual(103, len(json.loads(b"".join(scenario.chunks()))))+ def test_vod_and_series_rows_partition_and_hash_deterministically(self):+ scenario = FIXTURE.Scenario(+ channels=12, categories=3, movies=31, movie_categories=4,+ series_items=19, series_categories=3+ )+ movie_bulk = list(scenario.movie_rows())+ movie_partition = [row for category in range(1, 5) for row in scenario.movie_rows(category)]+ series_bulk = list(scenario.series_rows())+ series_partition = [row for category in range(1, 4) for row in scenario.series_rows(category)]+ self.assertEqual(movie_bulk, sorted(movie_partition, key=lambda row: row["num"]))+ self.assertEqual(series_bulk, sorted(series_partition, key=lambda row: row["series_id"]))+ metadata = scenario.metadata()+ self.assertEqual(31, metadata["expected_movies"])+ self.assertEqual(19, metadata["expected_series"])+ self.assertEqual(metadata["movie_payload_sha256"], scenario.metadata()["movie_payload_sha256"])+ self.assertEqual(metadata["series_payload_sha256"], scenario.metadata()["series_payload_sha256"])+ with self.assertRaises(ValueError):+ FIXTURE.Scenario(movies=1)+def start_server(self, **options):server = FIXTURE.FixtureServer(("127.0.0.1", 0), FIXTURE.Scenario(**options))thread = threading.Thread(target=server.serve_forever, daemon=True)@@ -73,6 +92,26 @@ class XtreamSyncPerfFixtureTest(unittest.TestCase):error.exception.close()self.assertEqual(10, len(self.get(base, "/player_api.php?action=get_live_streams&category_id=1")))+ def test_vod_and_series_streams_support_full_rejection_and_category_fallback(self):+ _, base = self.start_server(+ channels=12, categories=3, movies=31, movie_categories=4,+ series_items=19, series_categories=3,+ bulk_vod_status=503, bulk_series_status=503+ )+ for action in ("get_vod_streams", "get_series"):+ with self.assertRaises(HTTPError) as error:+ self.get(base, "/player_api.php?action=" + action)+ self.assertEqual(503, error.exception.code)+ error.exception.close()+ movies = [row for category in range(1, 5) for row in self.get(+ base, f"/player_api.php?action=get_vod_streams&category_id={category}")]+ series = [row for category in range(1, 4) for row in self.get(+ base, f"/player_api.php?action=get_series&category_id={category}")]+ self.assertEqual(31, len(movies))+ self.assertEqual(19, len(series))+ self.assertEqual(4, len(self.get(base, "/player_api.php?action=get_vod_categories")))+ self.assertEqual(3, len(self.get(base, "/player_api.php?action=get_series_categories")))+def test_disconnect_is_a_truncated_document_and_incomplete_event(self):_, base = self.start_server(channels=20, categories=2, disconnect_after_rows=5)with self.assertRaises(json.JSONDecodeError):diff --git a/tools/xtream_sync_benchmark.py b/tools/xtream_sync_benchmark.pyindex 04aa9603..cc4c5851 100644--- a/tools/xtream_sync_benchmark.py+++ b/tools/xtream_sync_benchmark.py@@ -54,6 +54,7 @@ def parse_records(log: str) -> list[dict]:def summarize(records: list[dict], events: list[dict], metadata: dict) -> dict:starts = {event["request_id"]: event for event in events if event["event"] == "request_start"}samples = [dict(record) for record in records if record.get("event") == "sample"]+ environment = next((r for r in records if r.get("event") == "environment"), None)for sample in samples:# The same account is used for refresh: request counts cover the entire# account lifecycle, and must not be attributed to one phase alone.@@ -62,6 +63,24 @@ def summarize(records: list[dict], events: list[dict], metadata: dict) -> dict:sample["account_live_requests"] = len(live)sample["account_bulk_requests"] = sum(event["category_id"] is None for event in live)sample["account_category_requests"] = sum(event["category_id"] is not None for event in live)+ if sample.get("settle_seconds", 0) > 0:+ first_category = next((event["request_id"] for event in live if event["category_id"] is not None), None)+ sample["bulk_requests_after_fallback"] = sum(+ event["category_id"] is None and event["request_id"] > first_category+ for event in live+ ) if first_category is not None else 0+ for section, actions in {+ "movie": {"get_vod_streams"},+ "series": {"get_series"},+ }.items():+ section_requests = [event for event in requests if event["action"] in actions]+ sample[f"account_{section}_requests"] = len(section_requests)+ sample[f"account_{section}_full_requests"] = sum(+ event["category_id"] is None for event in section_requests+ )+ sample[f"account_{section}_category_requests"] = sum(+ event["category_id"] is not None for event in section_requests+ )groups = []for mode, phase in sorted({(s["mode"], s["phase"]) for s in samples}):selected = [s for s in samples if s["mode"] == mode and s["phase"] == phase and not s["warmup"]]@@ -70,18 +89,90 @@ def summarize(records: list[dict], events: list[dict], metadata: dict) -> dict:elapsed = [s["elapsed_ms"] for s in selected]live_ready = [milestone["elapsed_ms"] for s in selected for milestone in s.get("milestones", [])if milestone["phase"] == "live-committed"]- groups.append({"mode": mode, "phase": phase, "samples": len(selected),- "median_ms": statistics.median(elapsed), "max_ms": max(elapsed),- "median_live_committed_ms": statistics.median(live_ready) if live_ready else None,- "max_sampled_java_heap_bytes": max(s["peak_java_heap_bytes"] for s in selected),- "channel_counts": sorted({s["channels"] for s in selected})})- return {"fixture": metadata, "environment": next((r for r in records if r["event"] == "environment"), None),+ first_browsable = [s["first_browsable_screen_elapsed_ms"] for s in selected+ if "first_browsable_screen_elapsed_ms" in s]+ background_elapsed = [s["background_worker_elapsed_ms"] for s in selected+ if "background_worker_elapsed_ms" in s]+ group = {"mode": mode, "phase": phase, "samples": len(selected),+ "median_ms": statistics.median(elapsed), "max_ms": max(elapsed),+ "median_live_committed_ms": statistics.median(live_ready) if live_ready else None,+ "max_sampled_java_heap_bytes": max(s["peak_java_heap_bytes"] for s in selected),+ "channel_counts": sorted({s["channels"] for s in selected})}+ if environment and environment.get("verify_channel_fields"):+ checked_samples = [s for s in selected if "fixture_row_fields_verified" in s]+ group["fixture_row_fields_verified"] = (+ len(checked_samples) == len(selected) and+ all(s["fixture_row_fields_verified"] for s in checked_samples)+ )+ group["fixture_rows_checked"] = sorted({+ s.get("fixture_rows_checked", 0) for s in checked_samples+ })+ group["fixture_categories_checked"] = sorted({+ s.get("fixture_categories_checked", 0) for s in checked_samples+ })+ verification_times = [s["fixture_row_field_verification_ms"] for s in checked_samples+ if "fixture_row_field_verification_ms" in s]+ if verification_times:+ group["median_fixture_row_field_verification_ms"] = statistics.median(verification_times)+ if first_browsable:+ group["median_first_browsable_screen_ms"] = statistics.median(first_browsable)+ group["max_first_browsable_screen_ms"] = max(first_browsable)+ if background_elapsed:+ group["median_background_worker_ms"] = statistics.median(background_elapsed)+ group["max_background_worker_ms"] = max(background_elapsed)+ group["background_worker_states"] = sorted({+ s.get("background_worker_state", "MISSING") for s in selected+ if "background_worker_elapsed_ms" in s+ })+ group["background_worker_channel_counts"] = sorted({+ s.get("background_worker_channels", 0) for s in selected+ if "background_worker_elapsed_ms" in s+ })+ summary_heap = [s["summary_peak_java_heap_bytes"] for s in selected+ if "summary_peak_java_heap_bytes" in s]+ if summary_heap:+ group["max_summary_sampled_java_heap_bytes"] = max(summary_heap)+ group["max_summary_gc_count_delta"] = max(+ s.get("summary_gc_count_delta", 0) for s in selected+ )+ for field in ("unchanged_movie_refresh_elapsed_ms", "unchanged_series_refresh_elapsed_ms",+ "unchanged_vod_refresh_elapsed_ms"):+ values = [s[field] for s in selected if field in s]+ if values:+ group["median_" + field] = statistics.median(values)+ group["max_" + field] = max(values)+ unchanged_summary_heap = [s["unchanged_summary_peak_java_heap_bytes"] for s in selected+ if "unchanged_summary_peak_java_heap_bytes" in s]+ if unchanged_summary_heap:+ group["max_unchanged_summary_sampled_java_heap_bytes"] = max(unchanged_summary_heap)+ group["max_unchanged_summary_gc_count_delta"] = max(+ s.get("unchanged_summary_gc_count_delta", 0) for s in selected+ )+ for section in ("movie", "series"):+ for field in (f"{section}_index_elapsed_ms", f"{section}_after_live_elapsed_ms"):+ values = [s[field] for s in selected if field in s]+ if values:+ group[f"median_{field}"] = statistics.median(values)+ group[f"max_{field}"] = max(values)+ counts = [s.get("movies" if section == "movie" else "series", 0) for s in selected]+ group[f"{section}_counts"] = sorted(set(counts))+ groups.append(group)+ limits = ["Debug APK, synthetic local server, Java heap sampled every 50 ms.",+ "Native RSS and playback are not measured.",+ "Refresh shares an account with setup; account request counts include both phases.",+ "Warmups excluded; queued real background work may contend with later samples."]+ if environment and environment.get("verify_channel_fields"):+ limits.append("Persisted fixture rows and categories are checked in bounded database pages after setup and after refresh when requested; verification time is excluded from sync timing.")+ if any("first_browsable_screen_elapsed_ms" in sample for sample in samples):+ limits.append("First browsable timing uses the real Welcome-to-Live UI and synthetic channel row, but invokes setup through the production use case rather than form interaction.")+ else:+ limits.append("No UI readiness measurement; pass --first-browsable-screen to measure the first accessible synthetic live row.")+ if any("background_worker_elapsed_ms" in sample for sample in samples):+ limits.append("Background probe enqueues one immediate no-ID ProviderSyncWorker request; WorkManager interval and scheduling constraints are not measured.")+ return {"fixture": metadata, "environment": environment,"complete": any(r["event"] == "complete" for r in records), "groups": groups, "samples": samples,"timings": [r for r in records if r["event"] in {"live-response", "live-pipeline", "catalog-stage"}],- "limits": ["Debug APK, synthetic local server, Java heap sampled every 50 ms.",- "Backend completion only; no UI readiness, native RSS, or playback measurement.",- "Refresh shares an account with setup; account request counts include both phases.",- "Warmups excluded; queued real background work may contend with later samples."]}+ "limits": limits}def main():@@ -93,6 +184,27 @@ def main():parser.add_argument("--iterations", type=int, default=5)parser.add_argument("--warmups", type=int, default=1)parser.add_argument("--refresh", action="store_true")+ parser.add_argument("--settle-seconds", type=int, default=0,+ help="Observe terminal setup state/catalog and reject bulk retries after fallback")+ parser.add_argument("--repeat-vod-refresh", action="store_true",+ help="Force unchanged movie and series summary reindexing after the initial catalog is complete.")+ parser.add_argument("--first-browsable-screen", action="store_true",+ help="Launch the real app Welcome screen before setup and measure the first accessible Live channel row.")+ parser.add_argument("--verify-channel-fields", action="store_true",+ help="Compare every persisted live row with deterministic fixture fields after setup, outside import timing.")+ parser.add_argument("--background-worker", action="store_true",+ help="Run the no-provider-ID ProviderSyncWorker against a deliberately stale synthetic live catalog.")+ parser.add_argument("--runtime-tier", choices=["DEVICE", "LOW", "MID", "HIGH"], default="DEVICE",+ help="Simulated resource-policy tier; device memory remains the connected emulator's real memory.")+ parser.add_argument("--stage-batch-size", type=int, choices=[100, 128, 256, 300, 500, 512, 1024])+ parser.add_argument("--experimental-auto-bulk", action="store_true",+ help="Enable bulk-first AUTO in the isolated benchmark app; normal app builds already use it.")+ parser.add_argument("--hidden-category-percent", type=int, default=0,+ help="Hide this percentage of returned live categories before refresh.")+ parser.add_argument("--remember-sequential-stress", action="store_true",+ help="Seed the synthetic provider with remembered category stress before refresh.")+ parser.add_argument("--avoid-full-cooldown-seconds", type=int, default=0,+ help="Seed the full-catalog cooldown before refresh.")parser.add_argument("--cleanup-run", help="Exact synthetic run token to remove after an interrupted benchmark")parser.add_argument("--output", type=Path)for field, default in asdict(Scenario()).items():@@ -102,6 +214,12 @@ def main():parser.error("adb and valid sync modes are required")if not 1 <= args.iterations <= 20 or not 0 <= args.warmups <= 3:parser.error("iterations must be 1..20 and warmups 0..3")+ if not 0 <= args.settle_seconds <= 120 or (args.settle_seconds and (args.refresh or args.background_worker)):+ parser.error("settle-seconds must be 0..120 and requires setup-only runs")+ if not 0 <= args.hidden_category_percent <= 100 or not 0 <= args.avoid_full_cooldown_seconds <= 86_400:+ parser.error("hidden-category-percent must be 0..100 and avoid-full-cooldown-seconds 0..86400")+ if (args.hidden_category_percent or args.remember_sequential_stress or args.avoid_full_cooldown_seconds) and not args.refresh:+ parser.error("hidden scopes and remembered-failure inputs require --refresh")if args.cleanup_run and not re.fullmatch(r"bench_[a-zA-Z0-9_]{1,100}", args.cleanup_run):parser.error("cleanup-run must be an exact synthetic benchmark token")scenario = Scenario(**{field: getattr(args, field) for field in asdict(Scenario())})@@ -138,18 +256,31 @@ def main():"-e", "fixtureUrl", "http://127.0.0.1:" + str(args.port),"-e", "syncModes", args.modes, "-e", "iterations", str(args.iterations),"-e", "warmups", str(args.warmups), "-e", "measureRefresh", str(args.refresh).lower(),+ "-e", "measureSummaryRefresh", str(args.repeat_vod_refresh).lower(),+ "-e", "measureFirstBrowsableScreen", str(args.first_browsable_screen).lower(),+ "-e", "verifyChannelFields", str(args.verify_channel_fields).lower(),+ "-e", "settleSeconds", str(args.settle_seconds),+ "-e", "measureBackgroundWorker", str(args.background_worker).lower(),*(["-e", "cleanupRun", args.cleanup_run] if args.cleanup_run else []),+ "-e", "runtimeTier", args.runtime_tier,+ "-e", "experimentalAutoBulk", str(args.experimental_auto_bulk).lower(),+ "-e", "hiddenCategoryPercent", str(args.hidden_category_percent),+ "-e", "rememberSequentialStress", str(args.remember_sequential_stress).lower(),+ "-e", "avoidFullCooldownSeconds", str(args.avoid_full_cooldown_seconds),+ *( ["-e", "stageBatchSize", str(args.stage_batch_size)] if args.stage_batch_size is not None else [] ),PACKAGE + ".test/androidx.test.runner.AndroidJUnitRunner"],capture_output=True, text=True)log_process.terminate()log_process.communicate(timeout=10)+ instrumentation_output = result.stdout + "\n" + result.stderr# Keep only instrumentation status/failure class, never exception text:# network errors from the app can contain request identities.status = {"exit_code": result.returncode,- "ok": bool(re.search(r"OK \(1 test\)", result.stdout)),- "status_codes": re.findall(r"INSTRUMENTATION_STATUS_CODE: (-?\d+)", result.stdout),- "exception_classes": sorted(set(re.findall(r"(?:^|\n|Caused by: )([\w.$]+(?:Exception|Error))(?::|\s|$)", result.stdout))),- "failure": next(iter(re.findall(r"^INSTRUMENTATION_STATUS: (?:Error|shortMsg)=(\w[\w.$]*)", result.stdout, re.M)), None)}+ "ok": bool(re.search(r"OK \(1 test\)", instrumentation_output)),+ "test_started": "INSTRUMENTATION_STATUS: test=" in instrumentation_output,+ "status_codes": re.findall(r"INSTRUMENTATION_STATUS_CODE: (-?\d+)", instrumentation_output),+ "exception_classes": sorted(set(re.findall(r"(?:^|\n|Caused by: )([\w.$]+(?:Exception|Error))(?::|\s|$)", instrumentation_output))),+ "failure": next(iter(re.findall(r"^INSTRUMENTATION_STATUS: (?:Error|shortMsg)=(\w[\w.$]*)", instrumentation_output, re.M)), None)}records = parse_records(raw_log.read_text(encoding="utf-8"))# Replace raw tag output with structured benchmark records only.raw_log.write_text("".join(json.dumps(r) + "\n" for r in records), encoding="utf-8")@@ -164,10 +295,14 @@ def main():report["expected_samples"] = expected_samplesreport["all_samples_recorded"] = len(report["samples"]) == expected_samplesreport["instrumentation"] = status+ report["background_worker_requested"] = args.background_worker+ report["retry_quiescence_passed"] = all(+ s.get("bulk_requests_after_fallback", 0) == 0 for s in report["samples"]+ ) if args.settle_seconds else None(output / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")print(json.dumps({"report": str(output / "report.json"), "groups": report["groups"],"complete": report["complete"], "instrumentation": status}), flush=True)- if not status["ok"] or not report["complete"] or not report["all_samples_recorded"] or request_events_truncated:+ if not status["ok"] or not report["complete"] or not report["all_samples_recorded"] or request_events_truncated or report["retry_quiescence_passed"] is False:raise SystemExit("Benchmark failed; no successful performance result was recorded")finally:if log_process and log_process.poll() is None:diff --git a/tools/xtream_sync_perf_fixture.py b/tools/xtream_sync_perf_fixture.pyindex 2ac38c3e..76895885 100644--- a/tools/xtream_sync_perf_fixture.py+++ b/tools/xtream_sync_perf_fixture.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Streaming, deterministic live-only Xtream fixture for sync measurements.+"""Streaming, deterministic Xtream fixture for sync measurements.No provider account is required. Payloads are generated a row at a time; eventscontain action/scope/count/timing only, never URLs or query credentials.@@ -24,11 +24,17 @@ from urllib.parse import parse_qs, urlparseclass Scenario:channels: int = 10_000categories: int = 100+ movies: int = 0+ movie_categories: int = 0+ series_items: int = 0+ series_categories: int = 0seed: int = 1header_delay_ms: int = 0category_delay_ms: int = 0bytes_per_second: int = 0bulk_status: int = 200+ bulk_vod_status: int = 200+ bulk_series_status: int = 200disconnect_after_rows: int = 0malformed_every: int = 0throttle_every: int = 0@@ -36,11 +42,20 @@ class Scenario:def __post_init__(self):if not 1 <= self.channels <= 500_000 or not 1 <= self.categories <= 10_000:raise ValueError("channels/categories are outside fixture limits")+ if not 0 <= self.movies <= 500_000 or not 0 <= self.series_items <= 500_000:+ raise ValueError("movies/series_items are outside fixture limits")+ if not 0 <= self.movie_categories <= 10_000 or not 0 <= self.series_categories <= 10_000:+ raise ValueError("movie/series categories are outside fixture limits")+ if self.movies and not self.movie_categories:+ raise ValueError("movie_categories is required when movies are configured")+ if self.series_items and not self.series_categories:+ raise ValueError("series_categories is required when series items are configured")for name, value in asdict(self).items():if value < 0:raise ValueError(name + " must be nonnegative")- if not 100 <= self.bulk_status <= 599:- raise ValueError("bulk_status must be an HTTP status")+ if any(not 100 <= status <= 599 for status in+ (self.bulk_status, self.bulk_vod_status, self.bulk_series_status)):+ raise ValueError("bulk statuses must be HTTP statuses")def rows(self, category_id: int | None = None) -> Iterator[dict]:# Jump directly to the selected category; no full-catalog scan per request.@@ -72,18 +87,88 @@ class Scenario:yield encode(row)yield b"]"+ def movie_rows(self, category_id: int | None = None) -> Iterator[dict]:+ if not self.movie_categories:+ return+ start = 1 if category_id is None else category_id+ step = 1 if category_id is None else self.movie_categories+ if category_id is not None and not 1 <= category_id <= self.movie_categories:+ return+ for number in range(start, self.movies + 1, step):+ category = (number - 1) % self.movie_categories + 1+ yield {+ "num": number,+ "name": f"Benchmark Movie {number:06d}",+ "stream_type": "movie",+ "stream_id": 200_000 + number,+ "stream_icon": "",+ "category_id": str(category),+ "container_extension": "mp4",+ "added": str(1_700_000_000 + number),+ "rating": "7.5",+ "rating_5based": "3.75",+ "tmdb": str(500_000 + number),+ "youtube_trailer": "",+ "is_adult": 0,+ }++ def series_rows(self, category_id: int | None = None) -> Iterator[dict]:+ if not self.series_categories:+ return+ start = 1 if category_id is None else category_id+ step = 1 if category_id is None else self.series_categories+ if category_id is not None and not 1 <= category_id <= self.series_categories:+ return+ for number in range(start, self.series_items + 1, step):+ category = (number - 1) % self.series_categories + 1+ yield {+ "series_id": 300_000 + number,+ "name": f"Benchmark Series {number:06d}",+ "cover": "",+ "cover_big": "",+ "category_id": str(category),+ "genre": "Benchmark",+ "rating": "7.0",+ "episode_run_time": "45",+ "last_modified": str(1_700_000_000 + number),+ "is_adult": 0,+ }++ @staticmethod+ def payload_info(rows: Iterator[dict]) -> tuple[str, int]:+ digest = hashlib.sha256()+ digest.update(b"[")+ size = 1+ first = True+ for row in rows:+ chunk = (b"" if first else b",") + encode(row)+ first = False+ digest.update(chunk)+ size += len(chunk)+ digest.update(b"]")+ size += 1+ return digest.hexdigest(), size+def metadata(self) -> dict:digest = hashlib.sha256()size = 0for chunk in self.chunks():digest.update(chunk)size += len(chunk)+ movie_hash, movie_size = self.payload_info(self.movie_rows())+ series_hash, series_size = self.payload_info(self.series_rows())return {"fixture": "streamvault-xtream-sync-performance-v1","scenario": asdict(self),"expected_channels": self.channels - (self.channels // self.malformed_every if self.malformed_every else 0),+ "expected_movies": self.movies,+ "expected_series": self.series_items,"payload_sha256": digest.hexdigest(),"payload_bytes": size,+ "movie_payload_sha256": movie_hash,+ "movie_payload_bytes": movie_size,+ "series_payload_sha256": series_hash,+ "series_payload_bytes": series_size,"playback_media": False,}@@ -238,8 +323,41 @@ class Handler(BaseHTTPRequestHandler):self.wfile.write(b"]")self.wfile.flush()size += 1+ elif action in {"get_vod_categories", "get_series_categories"}:+ time.sleep(scenario.category_delay_ms / 1000)+ category_count = (scenario.movie_categories if action == "get_vod_categories"+ else scenario.series_categories)+ size = self.json_response([+ {"category_id": str(index),+ "category_name": f"Benchmark {('Movie' if action == 'get_vod_categories' else 'Series')} Group {index:04d}",+ "parent_id": 0, "is_adult": 0}+ for index in range(1, category_count + 1)+ ])+ elif action in {"get_vod_streams", "get_series"}:+ is_movie = action == "get_vod_streams"+ status = (scenario.bulk_vod_status if is_movie else scenario.bulk_series_status) \+ if category_id is None else 200+ if status != 200:+ size = self.json_response({"error": "configured_failure"}, status)+ else:+ source = scenario.movie_rows(category_id) if is_movie else scenario.series_rows(category_id)+ self.send_response(200)+ self.send_header("Content-Type", "application/json; charset=utf-8")+ self.end_headers()+ self.wfile.write(b"[")+ size = 1+ for row in source:+ chunk = (b"," if rows else b"") + encode(row)+ self.wfile.write(chunk)+ size += len(chunk)+ rows += 1+ if rows % 128 == 0:+ self.wfile.flush()+ self.wfile.write(b"]")+ self.wfile.flush()+ size += 1else:- # Isolate live ingestion from VOD/series/EPG work.+ # EPG remains outside the catalog benchmark.size = self.json_response([])completed = Trueexcept (BrokenPipeError, ConnectionResetError):