StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
Refill Xtream live category workers and honor provider pacing
David Nashash4c919f22bf63
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt b/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.ktindex c0227e58..8ecc0f3a 100644--- a/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt+++ b/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt@@ -234,7 +234,7 @@ class OkHttpXtreamApiService(}throw XtreamRequestException(response.code, message)}- in 500..599, 429 -> throw XtreamNetworkException(message)+ in 500..599, 429 -> throw XtreamNetworkException(message, statusCode = response.code, retryAfterMs = parseXtreamRetryAfter(response.header("Retry-After")))else -> throw XtreamRequestException(response.code, message)}}@@ -251,6 +251,7 @@ class OkHttpXtreamApiService(throw e} catch (e: IOException) {currentCoroutineContext().ensureActive()+ if (e is XtreamNetworkException) throw eLog.w(TAG,"Xtream request network failure for ${descriptor.hint} (${request.safeRequestIdentitySummary(effectiveRequestProfile)}): ${XtreamUrlFactory.sanitizeLogMessage(e.message ?: "Network request failed")}"@@ -364,7 +365,7 @@ class OkHttpXtreamApiService(}throw XtreamRequestException(response.code, message)}- in 500..599, 429 -> throw XtreamNetworkException(message)+ in 500..599, 429 -> throw XtreamNetworkException(message, statusCode = response.code, retryAfterMs = parseXtreamRetryAfter(response.header("Retry-After")))else -> throw XtreamRequestException(response.code, message)}}@@ -399,6 +400,7 @@ class OkHttpXtreamApiService(throw XtreamParsingException("Malformed JSON array from ${descriptor.hint}", e)} catch (e: IOException) {currentCoroutineContext().ensureActive()+ if (e is XtreamNetworkException) throw eLog.w(TAG,"Xtream streamed request network failure for ${descriptor.hint} (${request.safeRequestIdentitySummary(effectiveRequestProfile)}): ${XtreamUrlFactory.sanitizeLogMessage(e.message ?: "Network request failed")}"diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiExceptions.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiExceptions.ktindex 5c710e06..3398c218 100644--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiExceptions.kt+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiExceptions.kt@@ -8,7 +8,12 @@ sealed class XtreamApiException(message: String, cause: Throwable? = null) :Exception(message, cause),ProviderSetupFailure-class XtreamNetworkException(message: String, cause: Throwable? = null) :+class XtreamNetworkException(+ message: String,+ cause: Throwable? = null,+ override val statusCode: Int? = null,+ val retryAfterMs: Long? = null+) :IOException(message, cause),ProviderSetupFailure {override val kind: ProviderSetupFailureKind = ProviderSetupFailureKind.NETWORKdiff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamRetryAfter.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamRetryAfter.ktnew file mode 100644index 00000000..c64d34cc--- /dev/null+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamRetryAfter.kt@@ -0,0 +1,16 @@+package com.streamvault.data.remote.xtream++import java.time.ZonedDateTime+import java.time.format.DateTimeFormatter++internal fun parseXtreamRetryAfter(value: String?, nowMs: Long = System.currentTimeMillis()): Long? {+ val text = value?.trim()?.takeIf { it.isNotEmpty() } ?: return null+ text.toLongOrNull()?.let { seconds ->+ if (seconds < 0) return null+ return seconds.coerceAtMost(Long.MAX_VALUE / 1000) * 1000+ }+ return runCatching {+ (ZonedDateTime.parse(text, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant().toEpochMilli() - nowMs)+ .coerceAtLeast(0)+ }.getOrNull()+}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.ktindex aeb98c1c..0cb0a568 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt@@ -87,7 +87,7 @@ internal class SyncManagerXtreamFetcher(onAttemptReset()rawCount = 0mappedChannels = emptyList()- xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.CATEGORY) {+ xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.LIVE_CATEGORY) {val thinResult = runSuspendCatching {streamThinRowsInBatches()}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.ktindex bd78c295..a2712dbc 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt@@ -535,7 +535,7 @@ internal class SyncManagerXtreamLiveStrategy(providerId = provider.id,workloadSize = categories.size,preferSequential = preferSequential,- stage = XtreamAdaptiveSyncPolicy.Stage.CATEGORY+ stage = XtreamAdaptiveSyncPolicy.Stage.LIVE_CATEGORY)val concurrency = adaptiveConcurrency.coerceAtMost(runtimeProfile.maxCategoryConcurrency)progress(provider.id, onProgress, "Downloading Live TV by category 0/${categories.size}...")@@ -551,6 +551,7 @@ internal class SyncManagerXtreamLiveStrategy(sequentialModeWarning = liveCategorySequentialModeWarning,onProgress = onProgress,fetch = ::fetchCompletedCategory,+ refillWorkers = true,onCategoryCompleted = { completed, total, currentLabel ->// D6 — emission structuree en parallele du callback string deja emis par// `executeCategoryRecoveryPlan` via `progress(...)`. Le compteur cumulatifdiff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.ktindex c654f713..2ea2412c 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt@@ -14,6 +14,9 @@ import kotlinx.coroutines.asyncimport kotlinx.coroutines.awaitAllimport kotlinx.coroutines.coroutineScopeimport kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlinx.coroutines.cancel+import kotlinx.coroutines.channels.Channelimport kotlinx.coroutines.withTimeoutimport java.io.IOExceptionimport kotlin.random.Random@@ -37,11 +40,14 @@ internal class SyncManagerXtreamSupport(sequentialModeWarning: String,onProgress: ((String) -> Unit)?,fetch: suspend (XtreamCategory) -> TimedCategoryOutcome<T>,+ refillWorkers: Boolean = false,onCategoryCompleted: ((completed: Int, total: Int, currentLabel: String) -> Unit)? = null): CategoryExecutionPlan<T> {if (categories.isEmpty()) {return CategoryExecutionPlan(emptyList())}+ if (refillWorkers) return executeRefilledCategoryPlan(provider, categories, initialConcurrency,+ sectionLabel, sequentialModeWarning, onProgress, fetch, onCategoryCompleted)val outcomes = mutableListOf<TimedCategoryOutcome<T>>()val warnings = mutableListOf<String>()@@ -112,6 +118,71 @@ internal class SyncManagerXtreamSupport(return CategoryExecutionPlan(outcomes = outcomes, warnings = warnings.distinct())}+ private suspend fun <T> executeRefilledCategoryPlan(+ provider: Provider,+ categories: List<XtreamCategory>,+ initialConcurrency: Int,+ sectionLabel: String,+ sequentialModeWarning: String,+ onProgress: ((String) -> Unit)?,+ fetch: suspend (XtreamCategory) -> TimedCategoryOutcome<T>,+ onCategoryCompleted: ((Int, Int, String) -> Unit)?+ ): CategoryExecutionPlan<T> = coroutineScope {+ val limit = initialConcurrency.coerceIn(1, categories.size)+ val completed = Channel<Pair<Int, TimedCategoryOutcome<T>>>(limit)+ val results = mutableListOf<Pair<Int, TimedCategoryOutcome<T>>>()+ val warnings = mutableListOf<String>()+ var nextIndex = 0+ var active = 0+ var sequential = limit == 1+ var stopped = false+ var stressFailures = 0+ fun fillSlots() {+ val desired = if (sequential) 1 else limit+ while (!stopped && active < desired && nextIndex < categories.size) {+ val index = nextIndex+++ active+++ launch {+ try {+ completed.send(index to fetch(categories[index]))+ } catch (error: CancellationException) {+ [email protected](error)+ throw error+ }+ }+ }+ }+ try {+ fillSlots()+ while (active > 0) {+ val result = completed.receive()+ active--+ results += result+ val outcome = result.second.outcome+ val error = (outcome as? CategoryFetchOutcome.Failure)?.error+ progress(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 (!sequential && shouldRecoverRemainingCategoryRequests(categories.size, results.size, results.map { it.second.outcome })) {+ sequential = true+ warnings += sequentialModeWarning+ }+ if (sequential) {+ stressFailures = if (error != null && shouldRememberSequentialPreference(error)) stressFailures + 1 else 0+ if (stressFailures >= 3 && nextIndex < categories.size) {+ stopped = true+ warnings += "$sectionLabel $recoveryAbortWarningSuffix"+ }+ }+ // Already running attempts drain before a downgrade admits another.+ fillSlots()+ }+ } finally {+ completed.cancel()+ }+ CategoryExecutionPlan(results.sortedBy { it.first }.map { it.second }, warnings.distinct())+ }+suspend fun <T> retryTransient(maxAttempts: Int = 3,initialDelayMs: Long = 700L,@@ -246,7 +317,7 @@ internal class SyncManagerXtreamSupport(onCategoryRetried: ((completed: Int, total: Int, currentLabel: String) -> Unit)? = null): List<TimedCategoryOutcome<T>> {val failedCategories = timedOutcomes- .filter { it.outcome is CategoryFetchOutcome.Failure }+ .filter { it.outcome is CategoryFetchOutcome.Failure && it.outcome.error !is XtreamAuthenticationException }.map { it.category }if (failedCategories.isEmpty()) {return timedOutcomesdiff --git a/data/src/main/java/com/streamvault/data/sync/XtreamAdaptiveSyncPolicy.kt b/data/src/main/java/com/streamvault/data/sync/XtreamAdaptiveSyncPolicy.ktindex f44850c4..625b9901 100644--- a/data/src/main/java/com/streamvault/data/sync/XtreamAdaptiveSyncPolicy.kt+++ b/data/src/main/java/com/streamvault/data/sync/XtreamAdaptiveSyncPolicy.kt@@ -11,7 +11,7 @@ import kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.sync.Semaphoreimport kotlinx.coroutines.sync.withPermit-internal class XtreamAdaptiveSyncPolicy {+internal class XtreamAdaptiveSyncPolicy(private val nowMillis: () -> Long = System::currentTimeMillis) {private companion object {const val MAX_SEGMENTED_CONCURRENCY = 4}@@ -19,12 +19,14 @@ internal class XtreamAdaptiveSyncPolicy {enum class Stage(val timeoutMs: Long?) {LIGHTWEIGHT(15_000L),CATEGORY(35_000L),+ LIVE_CATEGORY(35_000L),HEAVY(null)}private data class ProviderHealth(val stressLevel: Int = 0,val backoffUntilMs: Long = 0L,+ val retryAfterUntilMs: Long = 0L,val successStreak: Int = 0,val timeoutStreak: Int = 0,val resetStreak: Int = 0,@@ -49,7 +51,8 @@ internal class XtreamAdaptiveSyncPolicy {if ((providerHealth[providerId]?.stressLevel ?: 0) > 0) 1 else 2suspend fun awaitTurn(providerId: Long, stage: Stage) {- val waitMs = (providerHealth[providerId]?.backoffUntilMs ?: 0L) - System.currentTimeMillis()+ val health = providerHealth[providerId]+ val waitMs = maxOf(health?.backoffUntilMs ?: 0L, health?.retryAfterUntilMs ?: 0L) - nowMillis()if (waitMs > 0L) {delay(waitMs)}@@ -59,12 +62,12 @@ internal class XtreamAdaptiveSyncPolicy {}val pacingState = providerPacing.computeIfAbsent(providerId) { ProviderPacingState() }pacingState.mutex.withLock {- val now = System.currentTimeMillis()+ val now = nowMillis()val pacingWaitMs = (pacingState.nextSegmentedRequestStartMs - now).coerceAtLeast(0L)if (pacingWaitMs > 0L) {delay(pacingWaitMs)}- pacingState.nextSegmentedRequestStartMs = System.currentTimeMillis() + requestSpacingMs+ pacingState.nextSegmentedRequestStartMs = nowMillis() + requestSpacingMs}}@@ -82,7 +85,7 @@ internal class XtreamAdaptiveSyncPolicy {val health = providerHealth[providerId] ?: ProviderHealth()val base = when (stage) {Stage.LIGHTWEIGHT -> 1- Stage.CATEGORY -> when {+ Stage.CATEGORY, Stage.LIVE_CATEGORY -> when {workloadSize <= 3 -> 1workloadSize <= 8 -> 2workloadSize <= 18 -> 2@@ -152,9 +155,13 @@ internal class XtreamAdaptiveSyncPolicy {signal == StressSignal.CONNECTION_RESET || signal == StressSignal.CONNECTION_FAILURE -> 250L * finalStresselse -> 0L}+ val now = nowMillis()+ val retryAfterMs = (error as? XtreamNetworkException)?.retryAfterMs ?: 0L+ val retryAfterUntil = now + retryAfterMs.coerceIn(0L, Long.MAX_VALUE - now)state.copy(stressLevel = finalStress,- backoffUntilMs = System.currentTimeMillis() + backoffMs,+ backoffUntilMs = maxOf(state.backoffUntilMs, now + backoffMs),+ retryAfterUntilMs = maxOf(state.retryAfterUntilMs, retryAfterUntil),successStreak = 0,timeoutStreak = nextTimeoutStreak,resetStreak = nextResetStreak,@@ -197,7 +204,8 @@ internal class XtreamAdaptiveSyncPolicy {private fun classify(error: Throwable): StressSignal {return when {- error is XtreamAuthenticationException -> StressSignal.THROTTLED+ error is XtreamAuthenticationException -> StressSignal.NONE+ error is XtreamNetworkException && error.statusCode == 429 -> StressSignal.THROTTLEDerror is XtreamRequestException && error.statusCode in setOf(403, 429) -> StressSignal.THROTTLEDmessageContains(error, "timeout") || messageContains(error, "timed out") -> StressSignal.TIMEOUTmessageContains(error, "connection reset") || messageContains(error, "reset by peer") -> StressSignal.CONNECTION_RESET@@ -211,12 +219,13 @@ internal class XtreamAdaptiveSyncPolicy {}private fun segmentedRequestSpacingFor(providerId: Long, stage: Stage): Long {- if (stage != Stage.CATEGORY) {+ if (stage != Stage.CATEGORY && stage != Stage.LIVE_CATEGORY) {return 0L}val health = providerHealth[providerId] ?: ProviderHealth()val baseSpacingMs = when (stage) {Stage.CATEGORY -> 250L+ Stage.LIVE_CATEGORY -> if (health.stressLevel > 0) 250L else 0Lelse -> 0L}val stressSpacingMs = when {diff --git a/data/src/test/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiServiceTest.kt b/data/src/test/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiServiceTest.ktindex e1416d0a..7a3e6579 100644--- a/data/src/test/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiServiceTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiServiceTest.kt@@ -37,6 +37,33 @@ import org.junit.Testclass OkHttpXtreamApiServiceTest {+ @Test+ fun `bulk and metadata responses retain throttling status and retry after`() = runTest {+ val client = OkHttpClient.Builder().addInterceptor { chain ->+ Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1)+ .code(429).message("Too Many Requests").header("Retry-After", "10")+ .body("".toResponseBody("application/json".toMediaType())).build()+ }.build()+ val service = OkHttpXtreamApiService(client, json)+ val metadata = runCatching { service.getLiveCategories("https://example.test/player_api.php?action=get_live_categories") }.exceptionOrNull()+ val bulk = runCatching { service.streamLiveStreamRows("https://example.test/player_api.php?action=get_live_streams") { } }.exceptionOrNull()+ for (failure in listOf(metadata, bulk)) {+ assertThat(failure).isInstanceOf(XtreamNetworkException::class.java)+ val network = failure as XtreamNetworkException+ assertThat(network.statusCode).isEqualTo(429)+ assertThat(network.retryAfterMs).isEqualTo(10_000L)+ }+ }++ @Test+ fun `retry after accepts seconds and HTTP dates without accepting malformed values`() {+ assertThat(parseXtreamRetryAfter("3", 0)).isEqualTo(3000L)+ assertThat(parseXtreamRetryAfter("Thu, 01 Jan 1970 00:00:10 GMT", 1000)).isEqualTo(9000L)+ assertThat(parseXtreamRetryAfter("Thu, 01 Jan 1970 00:00:00 GMT", 1000)).isEqualTo(0L)+ assertThat(parseXtreamRetryAfter("-1", 0)).isNull()+ assertThat(parseXtreamRetryAfter("garbage", 0)).isNull()+ }+@Testfun `pipeline writer supersession cancels a body blocked after its first row`() = runBlocking {withTimeout(5_000) {diff --git a/data/src/test/java/com/streamvault/data/sync/XtreamLiveCategorySchedulingTest.kt b/data/src/test/java/com/streamvault/data/sync/XtreamLiveCategorySchedulingTest.ktnew file mode 100644index 00000000..e5af365b--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/XtreamLiveCategorySchedulingTest.kt@@ -0,0 +1,98 @@+package com.streamvault.data.sync++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.remote.dto.XtreamCategory+import com.streamvault.data.remote.xtream.XtreamAuthenticationException+import com.streamvault.data.remote.xtream.XtreamNetworkException+import com.streamvault.domain.model.LegacyProvider+import com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.delay+import kotlinx.coroutines.awaitCancellation+import kotlinx.coroutines.test.runTest+import org.junit.Test++@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)+class XtreamLiveCategorySchedulingTest {+ private val provider = LegacyProvider(id = 7, name = "Fixture", type = ProviderType.XTREAM_CODES, serverUrl = "https://example.test")+ private val categories = (1..6).map { XtreamCategory(categoryId = "$it", categoryName = "Category $it") }+ private fun support() = SyncManagerXtreamSupport(XtreamAdaptiveSyncPolicy(), { it is java.io.IOException },+ { it?.message.orEmpty() }, { _, _, _ -> }, 60_000, 60_000, "aborted")++ @Test+ fun `freed workers refill before the slow category finishes and preserve result order`() = runTest {+ val events = mutableListOf<String>()+ var active = 0+ var peak = 0+ val plan = support().executeCategoryRecoveryPlan(provider, categories, 2, "Live", "sequential", null,+ fetch = { category ->+ active+++ peak = maxOf(peak, active)+ events += "start${category.categoryId}"+ delay(if (category.categoryId == "1") 1000 else 10)+ events += "end${category.categoryId}"+ active--+ TimedCategoryOutcome<String>(category, CategoryFetchOutcome.Empty(category.categoryName), 10)+ }, refillWorkers = true)+ assertThat(events.indexOf("start3")).isLessThan(events.indexOf("end1"))+ assertThat(peak).isEqualTo(2)+ assertThat(plan.outcomes.map { it.category.categoryId }).containsExactly("1", "2", "3", "4", "5", "6").inOrder()+ }++ @Test+ fun `authentication failure stops admission and drains already running categories`() = runTest {+ val started = mutableListOf<String>()+ val plan = support().executeCategoryRecoveryPlan(provider, categories, 2, "Live", "sequential", null,+ fetch = { category ->+ started += category.categoryId+ delay(if (category.categoryId == "1") 1 else 20)+ TimedCategoryOutcome<String>(category,+ CategoryFetchOutcome.Failure(category.categoryName, XtreamAuthenticationException(401, "authentication")), 1)+ }, refillWorkers = true)+ assertThat(started).containsExactly("1", "2")+ assertThat(plan.outcomes).hasSize(2)+ var retries = 0+ support().continueFailedCategoryOutcomes(provider, plan.outcomes, { retries++; it.let { category ->+ TimedCategoryOutcome<String>(category, CategoryFetchOutcome.Empty(category.categoryName), 0)+ } })+ assertThat(retries).isEqualTo(0)+ }++ @Test+ fun `healthy live categories have no pacing floor while provider retry after survives successes`() = runTest {+ val policy = XtreamAdaptiveSyncPolicy { testScheduler.currentTime }+ repeat(3) { policy.awaitTurn(7, XtreamAdaptiveSyncPolicy.Stage.LIVE_CATEGORY) }+ assertThat(testScheduler.currentTime).isEqualTo(0L)+ policy.recordFailure(7, XtreamNetworkException("HTTP 429", statusCode = 429, retryAfterMs = 10_000))+ repeat(4) { policy.recordSuccess(7) }+ policy.awaitTurn(7, XtreamAdaptiveSyncPolicy.Stage.LIVE_CATEGORY)+ assertThat(testScheduler.currentTime).isEqualTo(10_000L)+ }++ @Test+ fun `repeated stress drains active requests and stops before fetching every category`() = runTest {+ var started = 0+ val plan = support().executeCategoryRecoveryPlan(provider, categories, 2, "Live", "sequential", null,+ fetch = { category ->+ started+++ delay(10)+ TimedCategoryOutcome<String>(category, CategoryFetchOutcome.Failure(category.categoryName, java.io.IOException("timeout")), 10)+ }, refillWorkers = true)+ assertThat(started).isLessThan(categories.size)+ assertThat(plan.outcomes).hasSize(started)+ assertThat(plan.warnings).containsExactly("sequential", "Live aborted")+ }++ @Test+ fun `worker exception cancels and joins its sibling`() = runTest {+ var siblingJoined = false+ val failure = runCatching {+ support().executeCategoryRecoveryPlan<String>(provider, categories, 2, "Live", "sequential", null,+ fetch = { category ->+ if (category.categoryId == "1") { delay(10); error("writer failure") }+ try { awaitCancellation() } finally { siblingJoined = true }+ }, refillWorkers = true)+ }.exceptionOrNull()+ assertThat(failure).isInstanceOf(IllegalStateException::class.java)+ assertThat(siblingJoined).isTrue()+ }+}diff --git a/docs/XTREAM_SYNC_CATEGORY_IMPLEMENTATION.md b/docs/XTREAM_SYNC_CATEGORY_IMPLEMENTATION.mdnew file mode 100644index 00000000..7fc93bfb--- /dev/null+++ b/docs/XTREAM_SYNC_CATEGORY_IMPLEMENTATION.md@@ -0,0 +1,61 @@+# Xtream live category scheduling++P5 on `codex/xtream-live-sync-performance`.++Live category requests use a bounded refilled coordinator: completion frees a+slot immediately instead of waiting for the slowest category in a fixed window.+Outcomes retain provider category order, while progress reports completion order.+Runtime profile caps and the remembered sequential preference remain. Completed+attempts merge under the P1 fence; failed or cancelled attempts are discarded.++Stress downgrade stops refilling until already running attempts drain, then+admits 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+CancellationException explicitly cancels the coordinator too, including workflow+supersession. Scope exit joins workers before staging cleanup.++Healthy live-category requests no longer have the mandatory 250 ms start gap.+Remembered stress retains pacing and backoff. Movie/series category requests+retain their existing pacing and fixed-window behavior.++HTTP 429 and server failures retain their status and Retry-After in the existing+network exception type. Both regular and streamed responses preserve these+fields instead of wrapping the exception again. Retry-After accepts seconds or+an HTTP date. Provider-wide Retry-After deadlines survive successful concurrent+requests and stress recovery; the next request waits for the later of that+deadline and adaptive backoff. Authentication is not classified as throttling.++## Evidence++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+status/header propagation and deterministic Retry-After waiting.++The isolated API 36 emulator retained all expected channels and passed cleanup:++| Fixture | Measured pairs | Add Provider median | Live refresh median |+| --- | ---: | ---: | ---: |+| 2,000 rows / 10 categories | 5 plus 1 warmup | 1,277 ms | 1,199 ms |+| 10,000 rows / 100 categories | 2 plus 1 warmup | 8,059 ms | 7,766 ms |++Reports:+- `build/xtream-sync-performance/20261010T080155937054Z/report.json`+- `build/xtream-sync-performance/20261010T080311051489Z/report.json`++Earlier 2,000-row category checks took roughly 2.5–2.8 seconds. Their sample+counts and device states differ, so this comparison establishes removal of the+observed pacing cost rather than a controlled release-device speedup ratio.+This emulator uses LOW profile category concurrency one: parallel refill itself+is 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.++The bulk-HTTP-503 fallback fixture also passed both operations at 2,000 rows:+`build/xtream-sync-performance/20261010T080443490570Z/report.json`.+Initial completion took 10,102 ms and refresh 7,587 ms. Existing bulk retries+and stressed-provider backoff remain costly; faster healthy category pacing+does not bypass those failure safeguards.diff --git a/docs/XTREAM_SYNC_IMPROVEMENT_PLAN.md b/docs/XTREAM_SYNC_IMPROVEMENT_PLAN.mdindex 92529200..7ed19862 100644--- a/docs/XTREAM_SYNC_IMPROVEMENT_PLAN.md+++ b/docs/XTREAM_SYNC_IMPROVEMENT_PLAN.md@@ -12,6 +12,7 @@ Supporting evidence:- [Live parsing and group identity implementation](XTREAM_SYNC_PARSING_IMPLEMENTATION.md)- [Bounded live pipeline implementation](XTREAM_SYNC_PIPELINE_IMPLEMENTATION.md)- [Database write and search implementation](XTREAM_SYNC_DATABASE_IMPLEMENTATION.md)+- [Live category scheduling implementation](XTREAM_SYNC_CATEGORY_IMPLEMENTATION.md)The reference implementation provides hypotheses to investigate, not a designauthority or proof of correctness. Choose behavior for this app's measured@@ -290,7 +291,8 @@ 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 areimplemented with fresh/migrated Room checks and measured backend improvements.-P5–P8 remain pending.+P5 refilled live-category workers and adaptive pacing are implemented with+cancellation, authentication and Retry-After coverage. P6–P8 remain pending.The new measurements identify writer cost, slow fallback and extra completedimports during some refresh intervals as remaining priorities. Earlier runsalso showed memory-driven category fallback; the default-strategy gate has not