Skip to content

StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.

Add isolated Xtream live sync baseline harness

David Nashash87a865b6c839
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 220f0497..b918d3f4 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -36,7 +36,10 @@ if (localPropertiesFile.exists()) {
FileInputStream(localPropertiesFile).use(localProperties::load)
}
-fun localProp(key: String): String = localProperties.getProperty(key, "")
+// Opt-in performance APK has isolated app storage and never seeds real accounts.
+val xtreamSyncBenchmark = providers.gradleProperty("xtreamSyncBenchmark").orNull == "true"
+fun localProp(key: String): String =
+ if (xtreamSyncBenchmark) "" else localProperties.getProperty(key, "")
fun computeOfficialSigningCertSha256(): String {
if (!keystorePropertiesFile.exists()) return ""
@@ -109,7 +112,7 @@ android {
buildTypes {
debug {
- applicationIdSuffix = ".debug"
+ applicationIdSuffix = if (xtreamSyncBenchmark) ".syncbenchmark" else ".debug"
versionNameSuffix = "-debug"
buildConfigField("String", "XTREAM_DEV_SERVER", "\"${localProp("xtream.dev.server")}\"")
buildConfigField("String", "XTREAM_DEV_USERNAME", "\"${localProp("xtream.dev.username")}\"")
diff --git a/app/src/androidTest/java/com/streamvault/app/benchmark/XtreamLiveSyncBenchmarkTest.kt b/app/src/androidTest/java/com/streamvault/app/benchmark/XtreamLiveSyncBenchmarkTest.kt
new file mode 100644
index 00000000..6d1de3e9
--- /dev/null
+++ b/app/src/androidTest/java/com/streamvault/app/benchmark/XtreamLiveSyncBenchmarkTest.kt
@@ -0,0 +1,210 @@
+package com.streamvault.app.benchmark
+
+import android.app.ActivityManager
+import android.app.Application
+import android.os.Build
+import android.os.Debug
+import android.os.SystemClock
+import android.util.Log
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import com.streamvault.data.sync.SyncRepairSection
+import com.streamvault.domain.model.ProviderEpgSyncMode
+import com.streamvault.domain.model.ProviderXtreamLiveSyncMode
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.usecase.ValidateAndAddProviderResult
+import com.streamvault.domain.usecase.XtreamProviderSetupCommand
+import com.streamvault.domain.util.ProviderInputSanitizer
+import dagger.hilt.android.EntryPointAccessors
+import java.net.URI
+import java.util.UUID
+import java.util.concurrent.atomic.AtomicLong
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.NonCancellable
+import kotlinx.coroutines.async
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withContext
+import kotlinx.coroutines.withTimeout
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import org.json.JSONObject
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/**
+ * Runs the real setup and Settings-live engines against a synthetic local fixture.
+ * Explicitly opt-in; never uses/deletes an existing provider or clears app data.
+ * Backend timings do not claim first-screen readiness or playback validation.
+ */
+@RunWith(AndroidJUnit4::class)
+class XtreamLiveSyncBenchmarkTest {
+ @Test
+ fun measureInitialAndRefresh() = runBlocking<Unit> {
+ val args = InstrumentationRegistry.getArguments()
+ assumeTrue(args.getString("xtreamSyncBenchmark") == "true")
+ val app = ApplicationProvider.getApplicationContext<Application>()
+ check(app.packageName == "com.streamvault.app.syncbenchmark") {
+ "Use the isolated APK built with -PxtreamSyncBenchmark=true"
+ }
+ val endpoint = requireNotNull(args.getString("fixtureUrl"))
+ val uri = URI(endpoint)
+ require(uri.scheme == "http" && uri.host in setOf("127.0.0.1", "localhost", "10.0.2.2") &&
+ uri.rawUserInfo == null && uri.rawQuery == null && uri.rawFragment == null &&
+ uri.path in setOf("", "/")) { "Only the local synthetic fixture is supported" }
+ val fixture = withContext(Dispatchers.IO) {
+ OkHttpClient().newCall(Request.Builder().url(endpoint.trimEnd('/') + "/fixture").build())
+ .execute().use { response ->
+ check(response.isSuccessful)
+ JSONObject(requireNotNull(response.body).string())
+ }
+ }
+ check(fixture.getString("fixture") == "streamvault-xtream-sync-performance-v1")
+ val expected = fixture.getInt("expected_channels")
+ 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 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))
+ 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 manager = app.getSystemService(ActivityManager::class.java)
+ Log.i(TAG, JSONObject()
+ .put("event", "environment").put("package", app.packageName)
+ .put("sdk", Build.VERSION.SDK_INT).put("model", Build.MODEL)
+ .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 ->
+ val run = "bench_" + mode.name + "_" + UUID.randomUUID().toString().replace("-", "")
+ val name = benchmarkName(run)
+ val progress = mutableListOf<JSONObject>()
+ val start = SystemClock.elapsedRealtimeNanos()
+ var providerId: Long? = null
+ try {
+ val sample = sampleHeap {
+ withTimeout(600_000L) {
+ graph.setup().loginXtream(
+ XtreamProviderSetupCommand(
+ serverUrl = endpoint, username = run, password = "synthetic",
+ name = name, epgSyncMode = ProviderEpgSyncMode.SKIP,
+ xtreamLiveSyncMode = mode
+ ),
+ onProgress = { label ->
+ // Retain milestones, not every category label.
+ val phase = when (label) {
+ "Downloading Live TV..." -> "live-start"
+ "Saving Live TV channels..." -> "commit-start"
+ "Loading Movies categories..." -> "live-committed"
+ else -> null
+ }
+ if (phase != null && progress.none { it.optString("phase") == phase }) {
+ progress += JSONObject().put("phase", phase)
+ .put("elapsed_ms", (SystemClock.elapsedRealtimeNanos() - start) / 1_000_000.0)
+ }
+ }
+ )
+ }
+ }
+ val elapsed = (SystemClock.elapsedRealtimeNanos() - start) / 1_000_000.0
+ val result = sample.value
+ val provider = when (result) {
+ is ValidateAndAddProviderResult.Success -> result.provider
+ is ValidateAndAddProviderResult.SavedWithWarning -> result.provider
+ else -> error("Setup failed: " + result.javaClass.simpleName)
+ }
+ providerId = provider.id
+ val count = graph.database().channelDao().getCount(provider.id).first()
+ check(count == expected) { "Incomplete catalog: " + count + "/" + expected }
+ val state = graph.sync().currentSyncState(provider.id).javaClass.simpleName
+ Log.i(TAG, 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("peak_java_heap_bytes", sample.peakHeapBytes)
+ .put("gc_count_delta", sample.gcCountDelta ?: JSONObject.NULL)
+ .put("milestones", org.json.JSONArray(progress)).toString())
+ if (measureRefresh) {
+ val refreshStart = SystemClock.elapsedRealtimeNanos()
+ val refresh = sampleHeap {
+ withTimeout(600_000L) {
+ graph.sync().retrySection(provider.id, SyncRepairSection.LIVE)
+ }
+ }
+ 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)
+ .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("channels", refreshed).put("peak_java_heap_bytes", refresh.peakHeapBytes)
+ .put("gc_count_delta", refresh.gcCountDelta ?: JSONObject.NULL).toString())
+ }
+ } finally {
+ withContext(NonCancellable) {
+ // 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)
+ check(graph.providers().deleteProvider(saved.id) is Result.Success)
+ check(graph.providers().getProvider(saved.id) == null)
+ }
+ }
+ }
+ }
+ }
+ Log.i(TAG, JSONObject().put("event", "complete").toString())
+ }
+
+ private data class HeapSample<T>(val value: T, val peakHeapBytes: Long, val gcCountDelta: Long?)
+
+ private fun benchmarkName(run: String) =
+ ProviderInputSanitizer.normalizeProviderName("Xtream sync benchmark " + run)
+
+ private suspend fun <T> sampleHeap(block: suspend () -> T): HeapSample<T> = coroutineScope {
+ fun usedHeap() = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()
+ fun gcCount() = Debug.getRuntimeStat("art.gc.gc-count")?.toLongOrNull()
+ val beforeGc = gcCount()
+ val peak = AtomicLong(usedHeap())
+ val sampler = async(Dispatchers.Default) {
+ while (true) {
+ val used = usedHeap()
+ peak.updateAndGet { maxOf(it, used) }
+ delay(50)
+ }
+ }
+ try {
+ val result = block()
+ val used = usedHeap()
+ peak.updateAndGet { maxOf(it, used) }
+ val afterGc = gcCount()
+ HeapSample(result, peak.get(), if (beforeGc != null && afterGc != null) afterGc - beforeGc else null)
+ } finally {
+ sampler.cancel()
+ withContext(NonCancellable) { sampler.join() }
+ }
+ }
+
+ companion object {
+ private const val TAG = "XtreamSyncBenchmark"
+ }
+}
diff --git a/app/src/debug/java/com/streamvault/app/benchmark/XtreamSyncBenchmarkEntryPoint.kt b/app/src/debug/java/com/streamvault/app/benchmark/XtreamSyncBenchmarkEntryPoint.kt
new file mode 100644
index 00000000..b634db85
--- /dev/null
+++ b/app/src/debug/java/com/streamvault/app/benchmark/XtreamSyncBenchmarkEntryPoint.kt
@@ -0,0 +1,19 @@
+package com.streamvault.app.benchmark
+
+import com.streamvault.data.local.StreamVaultDatabase
+import com.streamvault.data.sync.ProviderSyncCommands
+import com.streamvault.domain.repository.ProviderRepository
+import com.streamvault.domain.usecase.ValidateAndAddProvider
+import dagger.hilt.EntryPoint
+import dagger.hilt.InstallIn
+import dagger.hilt.components.SingletonComponent
+
+/** Typed access to the production graph for the opt-in, isolated sync probe. */
+@EntryPoint
+@InstallIn(SingletonComponent::class)
+interface XtreamSyncBenchmarkEntryPoint {
+ fun setup(): ValidateAndAddProvider
+ fun providers(): ProviderRepository
+ fun sync(): ProviderSyncCommands
+ fun database(): StreamVaultDatabase
+}
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.kt
index 2ec166a6..57373614 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
@@ -324,6 +324,11 @@ class OkHttpXtreamApiService(
onItem: suspend (T) -> Unit
): Int = withContext(Dispatchers.IO) {
val descriptor = describeEndpoint(endpoint)
+ val timingEnabled = descriptor.action == "get_live_streams"
+ val startedNanos = if (timingEnabled) System.nanoTime() else 0L
+ var callbackNanos = 0L
+ var emittedRows = 0
+ var completed = false
val effectiveProfile = requestProfileFor(descriptor, profile)
val effectiveRequestProfile = requestProfile.mergedWithDefaults(defaultRequestProfile)
val request = Request.Builder()
@@ -360,8 +365,17 @@ class OkHttpXtreamApiService(
contentType = response.header("Content-Type"),
maxBytes = responseBudgetFor(descriptor),
deserializer = deserializer,
- onItem = onItem
- )
+ onItem = if (timingEnabled) { item ->
+ val callbackStart = System.nanoTime()
+ try {
+ onItem(item)
+ emittedRows++
+ Unit
+ } finally {
+ callbackNanos += System.nanoTime() - callbackStart
+ }
+ } else onItem
+ ).also { completed = true }
}
} catch (e: XtreamApiException) {
throw e
@@ -371,6 +385,12 @@ class OkHttpXtreamApiService(
"Xtream streamed request network failure for ${descriptor.hint} (${request.safeRequestIdentitySummary(effectiveRequestProfile)}): ${XtreamUrlFactory.sanitizeLogMessage(e.message ?: "Network request failed")}"
)
throw XtreamNetworkException(XtreamUrlFactory.sanitizeLogMessage(e.message ?: "Network request failed"), e)
+ } finally {
+ if (timingEnabled) {
+ // Wall time includes network waits and decoding; callback time
+ // includes downstream mapping/staging. Neither is CPU time.
+ Log.i("XtreamSyncTiming", "phase=live-response elapsed_ms=${(System.nanoTime() - startedNanos) / 1_000_000} callback_ms=${callbackNanos / 1_000_000} rows=$emittedRows completed=$completed")
+ }
}
}
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt
index ea687c5d..f830912f 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt
@@ -383,11 +383,11 @@ internal class SyncCatalogStore(
}
private suspend fun <T> timed(providerId: Long, stage: String, block: suspend () -> T): T {
- val startedAt = System.currentTimeMillis()
+ val startedAt = System.nanoTime()
return try {
block()
} finally {
- Log.i(TAG, "catalog timing provider=$providerId stage=$stage took=${System.currentTimeMillis() - startedAt}ms")
+ Log.i(TAG, "catalog timing provider=$providerId stage=$stage took=${(System.nanoTime() - startedAt) / 1_000_000}ms")
}
}
diff --git a/docs/XTREAM_LIVE_IMPORT_COMPARISON.md b/docs/XTREAM_LIVE_IMPORT_COMPARISON.md
new file mode 100644
index 00000000..e50662e8
--- /dev/null
+++ b/docs/XTREAM_LIVE_IMPORT_COMPARISON.md
@@ -0,0 +1,132 @@
+# Initial Xtream Live TV import comparison
+
+Inspected 2026-10-09. StreamVault source: `540ec30c`. Reference implementation
+revision: `b5271300b74eb6706293ceb8f3e70b62589e03ad`, inspected in a separate checkout.
+No application code was changed and no runtime speed comparison was performed.
+
+The user's priority is the initial live import on Add Provider. Work queued
+afterward, including EPG and movie/series indexing, is outside that slow phase.
+The earlier broad review remains useful for later work, but scheduling EPG
+after indexing cannot fix the time spent importing live channels first.
+
+## What the reference implementation actually does
+
+- `MainActivity.fetchXtreamChannels` authenticates, then launches live category
+ and full live stream requests concurrently. It calls getLiveStreams without
+ a category ID. When movies/series are enabled, their bulk lists and category
+ requests launch alongside these too.
+- XtreamClient.streamBulkArray uses Android JsonReader on the response stream.
+ It reads scalar fields into a small per-row map and immediately builds a
+ Channel. It does not turn every row into JSON text and decode that text again.
+- The reader accepts a root array and selected object-wrapped arrays. It maps
+ IDs represented as numbers or strings, handles category_ids fallback and
+ catch-up flags, and skips nested structures it does not consume.
+- Parsed Channels accumulate in an ArrayList proportional to catalog size.
+ Input JSON is streamed, but the entire output catalog is retained in memory.
+ Its OOM handling explicitly acknowledges that this list can still be too large.
+- The Xtream fetch returns the full enabled live/movie/series result. It does
+ not deliver a capped live preview or incremental live row callbacks to the UI.
+ The separate early live callback in this file belongs to Stalker.
+- On a successful provider fetch, loadAllConfiguredProviders merges the result
+ and calls renderLivePartial. That starts the live derivation/render path before
+ the final persistCatalog call. The catalog cache is a delimited text file,
+ written with a temporary file followed by rename; channel rows are not being
+ staged and indexed in Room during the download.
+- It still performs live filtering and grouping in deriveLiveHalf and caches
+ derived results. The absence of import-time Room writes does not mean it
+ performs no classification or caching work at all.
+
+Reference implementation inspected at the revision above; relevant components are the Xtream request orchestrator, direct streaming parser, catalog cache, and live rendering path.
+
+## Where StreamVault spends extra initial-live work
+
+| Stage | Reference implementation | StreamVault |
+| --- | --- | --- |
+| Live requests | One full stream-list request, categories overlap | AUTO chooses category requests on LOW and MID onboarding; categories precede stream loading |
+| Category path | Normal loader uses full list | Globally spaced request starts, 250 ms on healthy server; limited window concurrency |
+| Parsing | JsonReader fields → Channel | Gson tree → JSON text → kotlinx DTO → Channel |
+| Download/write overlap | Builds an in-memory output list | Mapping/staging callbacks suspend further reading |
+| Persistence before availability | Starts live rendering before final flat-file persistence | Stages the lineup and commits Room catalog plus FTS before provider setup finishes |
+| Import-time CPU | Basic row mapping; grouping performed in live derivation | Field cleanup, internal URL creation, full grouping classification, stage fingerprints |
+
+The largest structural distinction is the request topology. For 200 categories,
+our 250 ms request-start spacing alone implies about 49.75 seconds before the
+last request starts, even with a fast provider. LOW devices run one category
+request at a time; MID devices permit at most two. Grouped awaitAll windows
+prevent free slots from picking up more work while a slow request finishes.
+These are policy-derived costs, not an observed timing for the user's account.
+
+Our existing STREAM_ALL route already uses a thin live DTO and bounded staging.
+It is the foundation to improve; a new live sync engine from scratch is not
+required to adopt the useful ideas in the reference implementation.
+
+Our per-row getLogicalGroupId calls ChannelNormalizer.classify, calculating
+language, resolution, codec, transport, source tags and variant attributes in
+addition to the canonical group key. The import only retains the group ID.
+Consider a canonical/group-key-only method after checking equivalence with the
+existing classifier. Measure its CPU cost before deciding its priority.
+
+Staging batches are 100/300/500 by device tier. Each batch runs a transaction,
+checks workflow ownership, counts staged rows, deduplicates/fingerprints and
+writes them. Full live promotion rebuilds global channels_fts inside its
+transaction, although generated Room code has maintenance triggers. Avoiding
+the rebuild needs search-correctness validation; it is not safe to delete this
+call merely because it looks redundant.
+
+## Revised implementation proposal, live first
+
+1. Establish a live-only baseline: authentication → live categories → first
+ stream headers/row → completed transfer/staging → commit → live screen
+ ready. Compare AUTO and explicit STREAM_ALL on the same full channel lineup.
+ This separates request topology from parsing, mapping and persistence.
+2. Implement direct streaming field decoding into thin live rows. Preserve
+ StreamVault's current field semantics, lenient IDs/flags, provider headers,
+ category_ids, EPG IDs, channel numbers, catch-up and playback URL behavior.
+ Consume supported response shapes explicitly; report truncated/malformed
+ responses so they cannot be mistaken for complete deletion snapshots.
+3. Use a small bounded batch queue between the reader and a single DB writer.
+ Keep row/admission budgets and commit ownership. Tune batch sizes by measured
+ transaction duration and memory headroom; reduce growing COUNT queries with
+ safe incremental accounting and reconciliation on resume.
+4. Validate bulk ingestion under constrained heaps, then make AUTO prefer the
+ proven bulk path for healthy providers on LOW/MID too. Actual pressure and
+ observed bulk failures still trigger fallback. Keep explicit user modes.
+ Hidden categories can be filtered during bulk mapping, but that trades
+ network bytes against request count and must preserve required hidden rows.
+5. Reduce commit cost, including proving whether FTS trigger maintenance makes
+ the global rebuild unnecessary. Retain atomic promotion, stable local IDs,
+ favorites/protection and partial-import preservation.
+6. Improve category fallback with continuously filled slots and pacing driven
+ by server stress rather than a universal delay. Compare a new-provider fast
+ path and changed-row refresh path separately; neither should discard the
+ workflow/generation guarantees.
+
+Keep the initial live catalog persistent and queryable through existing Room
+interfaces. Adopting the reference implementation's all-in-memory catalog and file storage would change
+too many browse/search/state contracts and increase peak memory. Borrow its
+bulk request and single-parse approach while keeping bounded ingestion.
+
+A full-catalog-ready milestone should remain distinct from any future small
+preview milestone. Improving real complete-live throughput is the requested
+goal; changing the completion label is insufficient.
+
+## Evidence needed before calling a fix faster
+
+Use identical provider data, device, network and channel coverage. Record
+request count/bytes, end-to-end ingest, parse/map CPU, writer wait, stage totals,
+commit/FTS time, first live-screen readiness and peak heap/GC. Current full-path
+logs already report total ingest, mapping and staging time; commit logs report
+category staging/commit, channel apply and FTS rebuild. Add missing parser,
+request/header and readiness measurements. Current ingest elapsed includes
+callback DB work, so it is not pure network time.
+
+Test small/large lineups, many tiny categories, slow/throttled/bulk-rejecting
+providers, malformed rows, process-death/cancellation, and hidden categories.
+Verify complete channel counts, EPG IDs/numbers/catch-up flags, search,
+stable favorites/protection and playback URLs. No speed ratio is established
+by this source comparison. Playback bug validation, if a change affects it,
+must follow the repository's sustained screenshot/log instructions.
+
+The the reference implementation checkout was reviewed as a reference. No source was copied into
+StreamVault; the proposed changes are implementation ideas for our existing
+pipeline.
diff --git a/docs/XTREAM_SYNC_BENCHMARK.md b/docs/XTREAM_SYNC_BENCHMARK.md
new file mode 100644
index 00000000..3cf1ab7b
--- /dev/null
+++ b/docs/XTREAM_SYNC_BENCHMARK.md
@@ -0,0 +1,110 @@
+# Xtream live 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.
+
+## Run on the connected emulator
+
+From the repository root in PowerShell:
+
+```powershell
+.\gradlew.bat :app:assembleDebug :app:assembleDebugAndroidTest -PxtreamSyncBenchmark=true -PcompatAbi=x86_64 --console=plain
+adb -s emulator-5554 install -r app/build/outputs/apk/debug/app-debug.apk
+adb -s emulator-5554 install -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk
+python tools/xtream_sync_benchmark.py --channels 10000 --categories 100 --iterations 5 --warmups 1 --refresh
+```
+
+The build property creates `com.streamvault.app.syncbenchmark` with its own
+storage and disables developer account seeding. Ordinary debug builds keep
+their usual application ID and seeds. The instrumentation refuses to run
+against another application ID or a benchmark database containing providers.
+It creates synthetic accounts and removes only the exact account from each run.
+It never clears app data or removes the existing debug app. For an interrupted
+run, use `--cleanup-run <exact run token from report.json>`. The instrumentation
+checks that token, normalized benchmark name and local endpoint before removing
+that one provider; otherwise resolve it in the benchmark app before rerunning.
+
+The Python runner starts a fixture bound to loopback, temporarily reverses its
+port through adb, and removes that mapping when done. It refuses to reuse an
+existing reverse mapping; choose another `--port` if necessary. APK installation
+is explicit; the runner does not install, uninstall, or wipe an app.
+
+Results go to an ignored, unique `build/xtream-sync-performance/<timestamp>/`
+directory: `report.json`, structured `benchmark-log.txt`, and `requests.jsonl`.
+The report requires both successful instrumentation and a completion marker.
+An incomplete or failed run does not become a successful timing result.
+
+## What is measured
+
+The instrumentation invokes `ValidateAndAddProvider.loginXtream` using the
+production dependency graph. Optional `--refresh` invokes `retrySection(LIVE)`,
+the Settings live repair entry point. Runs cover AUTO, STREAM_ALL and
+CATEGORY_BY_CATEGORY unless `--modes` limits the selection. The stored choice
+is recorded alongside observed bulk/category request counts: STREAM_ALL can
+still be overridden by existing safety policy, and AUTO may behave differently
+for initial setup versus refresh.
+
+Each sample verifies the expected channel count after commit. Setup milestones
+record 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.
+
+`XtreamSyncTiming` reports each streamed live response's wall duration, callback
+duration, emitted row count and normal completion. Callback duration includes
+downstream mapping and staging; remaining wall time includes network waits,
+decode and request overhead. It is not parser CPU. Existing catalog timing
+records capture stage batches, category commit, channel promotion and FTS
+rebuild, now using a monotonic clock. The runner retains only structured
+benchmark data and explicitly recognized numeric timing lines. It never
+exports general provider logs, request URLs, response previews or passwords.
+
+Java heap is sampled every 50 ms, with ART GC count deltas where available.
+These are debug-emulator measurements, not release-device performance, native
+RSS or an allocation profile. A short heap peak may fall between samples.
+Production background jobs remain enabled and can contend with later samples.
+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.
+
+Examples (add normal iteration/mode options as needed):
+
+```powershell
+python tools/xtream_sync_benchmark.py --channels 50000 --categories 200 --header-delay-ms 100
+python tools/xtream_sync_benchmark.py --channels 10000 --categories 100 --category-delay-ms 1500
+python tools/xtream_sync_benchmark.py --channels 10000 --categories 100 --bytes-per-second 2000000
+python tools/xtream_sync_benchmark.py --bulk-status 503 --modes STREAM_ALL
+python tools/xtream_sync_benchmark.py --disconnect-after-rows 500 --modes STREAM_ALL
+```
+
+Also available: `--malformed-every`, `--throttle-every`, and `--seed`. Fault
+scenarios are diagnostic checks: current retry/fallback behavior may prevent
+completion, in which case the runner intentionally fails. A completed server
+response alone never proves a complete client catalog.
+
+Fixture/report tests:
+
+```powershell
+python -m unittest tools.tests.test_xtream_sync_perf_fixture tools.tests.test_xtream_sync_benchmark tools.tests.test_catalog_xtream_fixture
+```
+
+## Remaining measurement work
+
+This package is an initial backend baseline, not the full P0 gate. Follow-up
+work still needs precise headers/first-row and workflow-wait timings, attempt
+and 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. Queue occupancy and
+writer-drain timings apply once the bounded pipeline exists. Run the full
+five-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.
diff --git a/docs/XTREAM_SYNC_IMPROVEMENT_PLAN.md b/docs/XTREAM_SYNC_IMPROVEMENT_PLAN.md
new file mode 100644
index 00000000..99b1a0b6
--- /dev/null
+++ b/docs/XTREAM_SYNC_IMPROVEMENT_PLAN.md
@@ -0,0 +1,426 @@
+# Xtream sync improvement plan
+
+Status: proposed implementation plan; implementation has not started.
+Prepared 2026-10-09 against source revision `540ec30c`.
+
+Supporting evidence:
+
+- [Initial live import comparison](XTREAM_LIVE_IMPORT_COMPARISON.md)
+- [Current sync engine review](XTREAM_SYNC_PERFORMANCE_REVIEW.md)
+
+The reference implementation provides hypotheses to investigate, not a design
+authority or proof of correctness. Choose behavior for this app's measured
+performance, provider compatibility, persistent library and recovery guarantees.
+Keep, change or reject each reference idea independently. No performance claim
+from another app substitutes for our validation.
+
+## Outcome and scope
+
+Make the complete Xtream live lineup available substantially sooner when adding
+a provider. Apply the same ingestion improvements to Settings Live TV sync and
+automatic refresh. Then improve movie/series summary ingestion and background
+work using the proven components.
+
+Priority order:
+
+1. Initial Add Provider live import: request topology, parsing, mapping, staging
+ and promotion through the first usable live screen.
+2. Settings/manual/background live refresh, including unchanged catalogs.
+3. Movie/series summaries and index persistence.
+4. Background scheduling, EPG handoff and progress clarity.
+
+EPG scheduling does not explain the initial live import delay. Keep it outside
+the first performance milestone. Keep movie/series payloads and EPG out of the
+initial live bandwidth budget; retain their durable follow-up behavior.
+
+The milestone means the complete accepted live catalog is committed and
+browsable. A preview or earlier completion label does not count as faster full
+ingestion. Retain Room storage, provider configuration workflows and existing
+repository contracts. Other provider protocols receive regression coverage when
+shared helpers change; redesigning their ingestion is outside this plan.
+
+## Performance contract
+
+Capture baseline before changing behavior. Record both the entire Add Provider
+journey and its live segment: authentication, ingest, promotion and first live
+screen. Also report the time from live promotion to setup completion, so category
+shell or navigation costs cannot be silently attributed to live ingestion.
+
+Initial engineering targets, to calibrate against baseline measurements:
+
+| Scenario | Target |
+| --- | --- |
+| Many-category initial import on a healthy bulk-capable provider | At least 80% lower median complete-live time than current AUTO, a 5x improvement; 10x is a stretch target |
+| Parsing on identical bulk payload | At least 50% lower parser CPU time without changing accepted row semantics |
+| Existing healthy bulk route | Improve the dominant measured costs; no repeatable median or tail regression above 10% |
+| Unchanged live refresh | Skip unchanged catalog writes and eliminate unnecessary full index passes |
+| Memory | Bounded transient parse/map/write batches, no OOM on agreed LOW/MID/HIGH device scenarios |
+| Correctness | Same complete channel coverage and required fields; preserve stable IDs and user state |
+
+These are targets, not established results. Network-limited and bulk-rejecting
+providers need separate expectations. Freeze scenario-specific release gates
+after baseline; document a revised target if measurements show a different
+constraint. Count reduction alone is insufficient to establish a speedup.
+
+Use one warm-up and at least five measured runs for each main baseline/final
+comparison, report median and maximum; use a larger sample before claiming p95.
+Use the same fixture seed/provider snapshot, device, build type, network policy
+and hidden-category settings. Clean provider state for initial-import runs;
+preserve state for refresh runs. Separate emulator diagnostics from measurements
+on a physical TV-class device. Report setup/account validation latency separately
+from catalog speed when the server varies it.
+
+## Architecture decisions
+
+### Bulk first, provider-aware fallback
+
+AUTO should prefer the validated bounded bulk path for a healthy provider.
+Device tier controls resource budgets; LOW/MID alone should no longer force
+hundreds of requests once the new path passes constrained-device validation.
+Explicit CATEGORY_BY_CATEGORY remains a supported choice. Explicit STREAM_ALL
+continues to express a bulk preference, with failures surfaced or recovered
+according to a documented contract; do not silently label fallback as bulk.
+
+Persist observed bulk support/failure state with a cooldown and eventual probe.
+Existing liveAvoidFullUntil and health fields may be reused when their meaning
+matches. Do not conflate category throttling with proof that bulk is unsupported.
+Separate authentication failures, HTTP throttling, interrupted transfers,
+malformed shapes, size admission failures and actual memory pressure.
+
+For hidden categories, support early row filtering plus preservation of existing
+hidden content and required hidden rows. Full bulk still downloads hidden rows,
+so a provider with most categories hidden may benefit from selected categories.
+Use measured/known catalog coverage for that decision; a newly added provider
+has no reliable category size estimates. Keep destructive pruning confined to
+confirmed complete scopes.
+
+### Two concurrent live requests and a bounded pipeline
+
+After authentication and workflow acquisition, start live category retrieval
+and one bulk live-stream request concurrently. The same provider request budget
+governs both. Do not split one live array into arbitrary parallel downloads.
+
+The intended AUTO default is one complete live-list HTTP response, decoded
+incrementally as it arrives. Parallelism comes from fetching category metadata
+alongside it and overlapping decode with mapping/database staging. The current
+bulk request interface does not provide independently addressable row ranges;
+starting the same full request multiple times repeats data rather than divides
+work. Parallel category requests remain the fallback/selected-category strategy.
+
+Do not fetch movies/series in parallel with initial live ingestion by default:
+they compete for provider connections, bandwidth, CPU and memory while the
+priority is live readiness. Their later concurrency should be measured within
+the shared resource budget. Benchmark bounded concurrent category loading as
+an alternative to bulk too; if a provider handles categories substantially
+better, the provider-aware planner should use that evidence.
+
+```mermaid
+flowchart TD
+ A[Acquire provider workflow and resource budget] --> C[Fetch live categories]
+ A --> R[Fetch and decode full live array]
+ C --> M[Resolve immutable category context]
+ R --> Q[Bounded queue of thin row batches]
+ M --> W[One mapper and staging writer]
+ Q --> W
+ W --> V[Validate completed snapshot]
+ V --> P[Atomically promote catalog and required indexes]
+ P --> U[Publish live readiness]
+ U --> B[Durable catalog and guide follow-up work]
+```
+
+The reader produces thin rows. The consumer waits for category context before
+classification and staging; the queue may fill while categories are pending,
+but stays bounded. Category retrieval returns either authoritative context or
+an explicit failure result with existing fallback-category semantics. Resolve
+that result once; mapping must not trigger repeated category network fetches.
+
+Use structured coroutines: reader failure cancels/drains the consumer safely;
+writer failure cancels the HTTP call; parent cancellation closes response bodies
+and queues. Close normally only after valid end-of-document. Promotion waits
+for reader completion, queue drain and all durable writes.
+
+One writer owns counters, duplicate admission and session state. This avoids
+concurrent mutation and category-stage mutex contention. Bound queued batches,
+row field sizes according to existing admission rules, retained metadata and
+any producer concurrency. A bounded queue alone does not make an unbounded
+HashSet of all stream IDs or category cache bounded: account for these explicitly
+and evaluate stage-table uniqueness as an alternative deduplication mechanism.
+
+Initial tuning candidates, evaluated against current 100/300/500 batches:
+
+| Tier | Candidate row batch size | Maximum queued batches |
+| --- | --- | --- |
+| LOW | 128–256 | 1 |
+| MID | 512 | 1–2 |
+| HIGH | 1,024 | 2 |
+
+These are benchmark candidates, not production defaults. Count the producer's
+current batch and writer's current batch too. Select production values using
+allocation/heap headroom, row width, cancellation latency and transaction
+duration. Retain global size caps and bounded SQL parameter chunks. Parallel
+provider imports need an app-wide resource budget, not only per-provider limits.
+
+### Direct decoding and minimal mapping
+
+Introduce a live-specific direct token decoder, initially alongside the current
+path. The existing JsonReader infrastructure can be reused; avoid per-row Gson
+trees, JSON reserialization and second decoding. Return thin typed live rows,
+not a generic map retaining every scalar field. Skip irrelevant nested payloads.
+
+Support current numeric/string/null field variants, singular/plural category
+IDs, archive flags and provider text compatibility. Add deliberately supported
+root-array/wrapper shapes with explicit recognition. Authentication/error
+objects must never become successful empty catalogs. Distinguish a malformed
+row with valid structural boundaries from an invalid/truncated JSON document.
+Track skipped rows and prevent degraded coverage from being labeled complete.
+
+Preserve server ordering/num, EPG IDs, catch-up fields, adult/protection behavior,
+logo cleanup and internal stream URL semantics. Keep provider credentials out
+of logs. Retain custom headers and User-Agent on every request.
+
+Extract a group-key-only path from ChannelNormalizer after proving it produces
+the same logicalGroupId as classify. Avoid calculating unused resolution,
+language, codec and other variant attributes during import. Keep canonical key
+semantics stable, because changing grouping identity can affect the library.
+Compute row fingerprints once from normalized fields where practical.
+
+### Attempt isolation and durable snapshot rules
+
+Audit retry/fallback before introducing concurrency. Current full streaming
+keeps staging session, seen IDs and counters outside the retry block. New code
+must make ownership and reset behavior explicit; this observation is a risk to
+test, not a claim of a reproduced data-loss bug.
+
+Each bulk attempt owns a fresh session, counters and buffered batches. On a
+failed attempt, cancel/drain work and discard its session before retry. If a
+future resumable protocol is implemented, it needs explicit coverage/checkpoint
+semantics; concatenating two full responses is not a resume protocol.
+
+For category fallback, isolate category attempts too. Only successful category
+attempts contribute confirmed coverage; promote them into the import session
+without letting failed retries leave stale membership. Keep successful category
+results while retrying failed categories. This requires category-scoped attempt
+staging or equivalent provenance, not a shared dedup set alone.
+
+Persist complete-response status separately from staged row count. Recover and
+fully promote only a snapshot durably marked complete after writer drain. The
+current onboarding recovery must be checked because non-empty staged rows alone
+cannot prove the remote response finished. Incomplete bulk sessions restart or
+remain explicitly partial; they must never trigger full stale-row deletion.
+
+Retain configuration generation, workflow lease and commit fences in the same
+transaction as promotion. Recheck ownership for staging/commit under the existing
+contract; optimize query frequency only with equivalent supersession protection.
+If extra fields/tables are necessary, include Room migration and older-state
+recovery tests. Temporary failures leave the previous active catalog intact.
+
+### Efficient persistence and indexes
+
+Track accepted stage count in the session writer after successful writes;
+reconcile from the database when recovering. Enforce limits using admitted
+unique rows, and do not count duplicates as additional catalog coverage.
+Investigate bounded category SQL summaries instead of repeatedly materializing
+all fallback categories each batch. Keep transaction duration controlled.
+
+For first import, use staged bulk insertion and SQL promotion without loading
+the entire live lineup into Kotlin. For refresh, use fingerprints/changed-row
+diffs to avoid rewriting unchanged channels. Preserve local IDs, favorites,
+user protection, overrides and history. Optimize correlated changed-column
+lookups only after separating first-import and refresh measurements.
+
+Verify Room FTS maintenance triggers on fresh and upgraded databases. Remove
+the global rebuild from routine promotion only if integration tests prove search
+correctness for inserts, renames, removals, unchanged refresh and multiple
+providers. Retain an explicit repair/rebuild operation. Do not suppress triggers
+without a transactionally correct replacement.
+
+Replace the later whole-list Xtream live index backfill with SQL projection or
+bounded updates. Decide whether the auxiliary index is required for initial
+browsing/search; required indexes complete before their readiness milestone.
+Every index must use the same complete generation, including safe stale cleanup.
+Do not advertise search readiness while a required index remains queued.
+
+### Category fallback that stays busy
+
+Replace grouped awaitAll windows with a continuously filled bounded worker pool.
+Start conservatively and adapt request concurrency and spacing using measured
+provider stress. Retain a device/resource ceiling, honor usable Retry-After,
+back off on throttle/reset/timeout and stop pointless authentication retries.
+Healthy providers should not inherit a universal 250 ms request-start delay.
+
+Use one writer for all successful category producers. Persist category coverage
+and retry failed categories only. Avoid sharing unsafe modifications with other
+protocols. Keep non-retryable errors, valid emptiness and partial success distinct.
+Test the effect of UI priority requests without interrupting a coherent commit.
+
+## Implementation work packages
+
+Each package is a separately reviewable change with its own evidence. Run
+focused checks after each; run the complete relevant set at integration/release.
+Measurements can change tuning choices, but must not silently change coverage
+or completion semantics.
+
+| Package | Work and primary files | Depends on | Exit criteria |
+| --- | --- | --- | --- |
+| P0 | Baseline and scalable fixture; timing in OkHttpXtreamApiService, live strategy, SyncCatalogStore, setup/readiness; tools and benchmark harness | Inspection | Reproducible initial/refresh report with counts, strategy and stage/memory costs |
+| P1 | Attempt isolation, durable completion/coverage, cancellation; live strategy, catalog stager/store, onboarding state/DAO, commit fence | P0 | Truncation/retry/process-death cannot promote an incomplete full snapshot or lose active data |
+| P2 | Direct live token decoder and compatible thin rows; HTTP service, XtreamDtos, XtreamProvider, ChannelNormalizer | P1 | Field-equivalent output, correct errors and lower measured parse/map CPU |
+| P3 | Concurrent category/bulk retrieval and bounded reader/writer pipeline; live strategy/support, stager, runtime profile | P2 | Observable overlap, enforced queue/resource bounds, no extra category fetches, complete cancellation |
+| P4 | Stage accounting, promotion/FTS/index cost; catalog store/DAO, index DAO, live backfill | P3 | Lower stage/commit cost, unchanged rows avoided, verified search and stable user state |
+| P5 | Refilled category workers and adaptive pacing; XtreamFetcher, XtreamSupport, adaptive policy | P1 and P3 | Idle slots reused; isolated failed categories; reliable throttled/bulk-rejecting fallback |
+| P6 | AUTO strategy and unified live behavior; live policy/profile, metadata, full/section routing, setup and Settings progress | P4 and P5 | Bulk default passes LOW/MID/HIGH scenarios; explicit modes and hidden scopes work across entry points |
+| 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.
+
+## P0 measurement and fixture deliverables
+
+Add a dedicated configurable Xtream performance fixture; do not inflate the
+existing one-channel catalog correctness fixture or change its stable entries.
+Suggested artifacts: tools/xtream_sync_perf_fixture.py, fixture tests, and a
+connected benchmark driver writing ignored build/xtream-sync-performance files.
+Keep payload generation streaming too, so fixture memory/server generation does
+not dominate or mimic client performance. Record server request starts/ends,
+bytes and fixture seed. Use synthetic credentials only.
+
+Provide configurable channel/category counts, deterministic metadata, category
+distribution, bandwidth/header delay, category latency, throttling, bulk rejection,
+malformed rows and mid-response disconnects. Record the dataset checksum.
+
+Timing records use a monotonic clock, run ID, provider ID, configuration
+generation, section, attempt and strategy. Include:
+
+- Authentication, workflow wait and request start/header/first-row timestamps.
+- Categories ready, reader complete, writer drained, commit complete, setup
+ complete and first browsable live-screen timestamps.
+- Accepted/duplicate/skipped/hidden counts, confirmed category coverage, bytes,
+ requests, retries/fallback reasons and maximum active request count.
+- Parse/map/stage CPU or attributable duration, queue blocked time/high-water,
+ transaction/FTS/auxiliary-index durations, peak heap and GC activity.
+
+Overlapping stage durations cannot be summed to derive wall time. Reader
+completion includes backpressure; distinguish it from parser CPU and network
+waiting. Avoid claiming pure transfer time from the current full ingest timer.
+Log aggregate/batch summaries with throttling, never per channel. Export
+sanitized JSON and a compact Markdown comparison; no credential URLs or body
+previews in benchmark artifacts.
+
+## P6 behavior across entry points
+
+Add Provider uses the new pipeline and finishes after a coherent live catalog
+and existing required setup work. Publish live readiness immediately at the
+proper milestone; movie/series summaries and EPG remain durable follow-ups.
+Preserve provider activation and saved-with-warning behavior for empty or
+unavailable live-only/VOD-only providers. Navigation must not depend on an
+auxiliary background job that the live screen does not require.
+
+Settings TV, full refresh and background stale refresh share the same live
+planner and importer. Reason affects priority/refresh policy, rather than forcing
+category loading for every manual/background request. Explicitly map full and
+section requests so FOREGROUND does not hide a manual/background reason.
+Respect force versus freshness and cancellation. Unchanged refresh should keep
+the current catalog visible throughout.
+
+Progress phases: connecting, loading live channels, saving channels, live ready.
+Use item counts when the provider has no trustworthy total; do not manufacture
+a percentage. Category fallback may show confirmed categories/total. Progress
+and completion must represent committed rows, not only decoded or queued rows.
+Expose strategy/fallback details in diagnostics, with plain user-facing labels.
+
+## P7 remaining Xtream work
+
+Reuse direct-decoding and bounded-write components for movie/series summary
+streams after their live validation. Keep rich details and episodes on demand.
+Preserve existing hydrated fields, TMDB identities and watch progress during
+summary refresh. Skip unchanged rows, avoid read-after-write where stable ID
+mapping can be obtained cheaply, and maintain required indexes in bounded work.
+
+Replace the universal two-category worker slice with a measured time/row budget
+and durable per-category checkpoints. Guarantee forward progress under repeated
+failures and requested-category priority. Prune stale items only after confirmed
+complete section coverage, preserving hidden scopes and partial results.
+
+Schedule required catalog work ahead of delayed guide work in the existing
+provider workflow chain. Coalesce redundant pending work where possible. Do not
+create competing queues without addressing leases, locks and commit ownership.
+Guide retry/delay should not starve movie/series availability. Settings must
+distinguish category shells queued, summary catalog complete and guide complete.
+
+## Validation matrix
+
+| Area | Required scenarios and assertions |
+| --- | --- |
+| Dataset | Small 1k, typical 10k, large 50k/100k live rows within existing admission limits; 1/20/200/500 categories; uneven and empty categories; duplicate IDs |
+| Provider | Healthy bulk, slow headers/body, category-only, throttle with/without Retry-After, resets, authentication/error-object response, unsupported wrapper, oversized response |
+| Parser | String/number/null IDs and flags, category_ids, order/num, EPG IDs, catch-up, Unicode/text compatibility, unknown/nested fields, valid empty, semantic bad row, truncated JSON after staged batches |
+| Refresh | Zero/1%/30% changed rows, additions/removals/renames, multiple providers, hidden/protected/required categories, existing favorites and local overrides |
+| Lifecycle | Cancel during categories/reader/write/commit, writer failure, process death before/after completion receipt, retry after partial body, provider edit/delete/supersession, app restart |
+| Memory/concurrency | LOW/MID/HIGH, actual pressure, long/wide rows, full queue, slow writer, duplicate tracker growth, simultaneous provider work, cancellation while backpressured |
+| Entry points | Add Provider, Settings TV, full refresh/rebuild, automatic refresh, explicit AUTO/STREAM_ALL/CATEGORY_BY_CATEGORY, live-empty provider with other content |
+| Search/index | Insert/update/delete/unchanged results, old DB migration, global multiple-provider FTS correctness, incomplete/complete auxiliary index states |
+
+Extend existing focused tests: OkHttpXtreamApiServiceTest, XtreamDtoParsingTest,
+XtreamProviderTest, SyncManagerXtreamLiveStrategyTest, SyncManagerXtreamSupportTest,
+XtreamLiveSyncPolicyTest, SyncCatalogStoreTest, commit-fence/workflow tests and
+ChannelNormalizer tests. Add genuine backpressure/cancellation/attempt isolation
+tests with controllable producer/writer barriers. Do not use timing sleeps as
+the primary unit-test assertion for concurrency.
+
+Use Room instrumentation for actual FTS trigger/migration/promotion behavior,
+stable IDs and process-death recovery, extending CatalogSyncEquivalenceIntegrationTest
+and ProviderWorkflowIntegrationTest where appropriate. Extend setup/Settings
+tests for actual completion/warning/cancel semantics. Benchmark generated Room
+code on-device; mocked DAO timings are not persistence performance evidence.
+
+Run focused data/domain/feature Gradle test tasks as affected, followed by data
+connected instrumentation and the app/benchmark journey for the changed routes.
+Resolve exact test variants from the project at implementation time. No build,
+launch or single screenshot is sufficient evidence of an improved sync.
+
+After the final live change, select at least two representative live channels
+and validate actual playback in the emulator using repository instructions:
+61 screenshots per channel at 2-second intervals, unique hashes demonstrating
+continued progression, media-session PLAYING with error=null, and sanitized
+HLS/recovery logs with no fatal/stuck error or unintended MPEG-TS fallback.
+Report channel names, count/interval, unique hashes, media session and log findings.
+This verifies playable imported rows; fixture-only channel counts cannot replace
+it. Retain screenshot sequences and logs under ignored validation artifacts.
+
+## Rollout, rollback and completion
+
+Keep implementation changes separable from strategy selection. Use internal
+debug configuration for controlled comparisons; avoid exposing experimental
+parser/batch toggles to users. Ship the validated live path before expanding
+to other sections. Preserve explicit category mode as a compatibility escape
+route; actual rollback can revert AUTO selection independently of the parser.
+Prove migrations and session receipts remain readable by the supported rollback
+version, or document a version boundary before shipping schema changes.
+
+Completion checklist:
+
+- [ ] P0 baseline archived, bottleneck ranking and gates frozen.
+- [ ] P1–P5 correctness and performance evidence reviewed.
+- [ ] P6 live-only release meets agreed latency/memory/coverage gates.
+- [ ] Settings/background refresh passes the shared-path matrix.
+- [ ] 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,
+ counts, requests, medians/spread, heap/GC, fallback behavior and limitations.
+- [ ] AUTO rollout/rollback and any schema migration boundary documented.
+
+No package is marked complete until its evidence exists. The first P0 backend
+harness, 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.
diff --git a/docs/XTREAM_SYNC_INITIAL_BASELINE.md b/docs/XTREAM_SYNC_INITIAL_BASELINE.md
new file mode 100644
index 00000000..20c31683
--- /dev/null
+++ b/docs/XTREAM_SYNC_INITIAL_BASELINE.md
@@ -0,0 +1,98 @@
+# Initial Xtream live backend baseline
+
+Measured on 2026-10-09 using the first P0 implementation on
+`codex/xtream-live-sync-performance`, based on `develop` at `540ec30c`.
+This is the current importer with timing hooks, not an optimized implementation.
+Reproduction and limitations: [benchmark guide](XTREAM_SYNC_BENCHMARK.md).
+
+## Environment and dataset
+
+- Debug APK, Android TV x86_64 emulator, API 36,
+ model `sdk_google_atv64_x86_64`, memory class 192 MB, low-RAM flag false.
+- Maximum Java heap 201,326,592 bytes. Android's live low-memory signal can
+ change independently of heap occupancy or the low-RAM device flag.
+- 10,000 live rows, 100 categories, seed 1, no artificial network delay,
+ bandwidth cap, throttling, malformed rows or disconnects.
+- Live payload SHA-256:
+ `4dfbcaf7e39ce168eb4cd58e34b5d8c78dddf4592d6638cb46c76b0fb31d63a3`.
+- EPG skipped; movie/series shells empty. Production background jobs enabled.
+- One warmup and five measured initial imports per requested mode.
+
+```powershell
+python tools/xtream_sync_benchmark.py --channels 10000 --categories 100 --iterations 5 --warmups 1
+```
+
+## Results
+
+| Requested mode | Setup median | Setup max | Live-committed median | Saved channels | Observed measured live requests |
+| --- | ---: | ---: | ---: | ---: | --- |
+| AUTO | 25.300 s | 25.334 s | 25.240 s | 10,000 | 100 categories/import; zero bulk |
+| STREAM_ALL | 25.286 s | 25.293 s | 25.228 s | 10,000 | 100 categories/import; zero bulk |
+| CATEGORY_BY_CATEGORY | 25.282 s | 25.305 s | 25.224 s | 10,000 | 100 categories/import; zero bulk |
+
+All 18 imports, including warmups, passed expected channel counts and provider
+cleanup. Instrumentation passed, the completion marker was captured, all samples
+were recorded, and the bounded request-event history was not truncated. Global
+server request high-water was two, including background traffic; it is not proof
+of parallel live category downloads for an individual import.
+
+**This is not a bulk-versus-category performance comparison.** The current
+engine's strategy/safety checks redirected the requested STREAM_ALL runs to
+categories before a bulk request. Logs confirmed the full-catalog skip. AUTO
+also selects categories for this device's LOW tier. A valid bulk comparison
+requires an environment where the current guard permits a complete bulk attempt.
+
+Maximum sampled Java heap among measured samples: AUTO 14,443,440 bytes,
+STREAM_ALL 16,101,696 bytes, categories 12,169,536 bytes. ART GC count deltas
+ranged from 374–504, 359–370 and 356–361 respectively. These are process-wide
+debug values, including potential background work, not allocation measurements
+or evidence that Android's system-wide low-memory signal must be false.
+
+One representative measured import had 2,028 ms summed staging time across 100
+100-row batches. Final category staging/commit took 10/1 ms; channel promotion
+took 47 ms and FTS rebuild 8 ms. Most wall time precedes final promotion.
+The healthy category request spacing of 250 ms imposes a roughly 24.75-second
+floor for 100 sequential starts. Mapping and staging also occupy that interval;
+these overlapping costs must not be added as independent delays. Profile mapping
+and decoding further before assigning CPU percentages.
+
+## Settings refresh smoke check and recovery
+
+A separate 2,000-row/10-category run passed initial import and live Settings
+repair for every mode, with exact counts and cleanup. It is one sample per
+phase/mode with no warmup, so it is a functional smoke check, not a refresh
+performance gate. That run showed interrupted bulk attempts due to
+`LowMemoryCatalogAbortException` followed by category recovery. One completed
+bulk response also appeared in logs; concurrent follow-up work prevents using
+it as an isolated bulk latency sample.
+
+Queued follow-up work for a removed synthetic provider was observed trying
+categories after its workflow generation was superseded. Commit fencing rejected
+its writes, but the continuing request/fallback work needs investigation in P1.
+Superseded workflow ownership should terminate work rather than initiate decoder
+or category recovery. Background requests can affect account-level counts and
+later process-wide heap/GC samples.
+
+## Artifacts and remaining gates
+
+Local baseline artifacts are in:
+`build/xtream-sync-performance/20261009T165800195284Z/`.
+The successful refresh smoke check is in:
+`build/xtream-sync-performance/20261009T165718649672Z/`.
+Raw general logcat and provider credentials are not exported.
+
+Installed APK SHA-256 values for these successful runs:
+
+- App: `852b8b19bb3c108191a7fed204cea19708173ca988e758c054b2a83b74b24307`.
+- Instrumentation: `570084179468ca74554398f8d22b9e275f220ddc19f71c71ac511a19079fc06a`.
+
+Builds passed; nine Xtream HTTP tests and thirteen fixture/report tests passed.
+Provider accounts were synthetic and the existing debug application was retained.
+The comparator notes use a neutral filename and contain no reference app name.
+
+P0 remains open for an actual bulk comparison, representative device/release
+measurements, repeated refresh scenarios, row identity/field equivalence,
+allocation profiling, precise attempt/coverage diagnostics and UI readiness.
+No default, parser, worker-pool, snapshot receipt, or import semantics changed
+in this package. P1 correctness work precedes the planned P2–P6 performance
+changes. Performance gates are not frozen from this limited environment.
diff --git a/docs/XTREAM_SYNC_PERFORMANCE_REVIEW.md b/docs/XTREAM_SYNC_PERFORMANCE_REVIEW.md
new file mode 100644
index 00000000..3b150a18
--- /dev/null
+++ b/docs/XTREAM_SYNC_PERFORMANCE_REVIEW.md
@@ -0,0 +1,221 @@
+# Xtream sync performance review
+
+Inspected 2026-10-09 at commit `540ec30c`. Scope: adding a provider first,
+then Settings sync and the background work that makes the catalog usable.
+This is a source inspection, not a measured speedup or an implementation.
+
+Scope clarification: the reported primary delay is the initial Live TV import,
+before queued work. The EPG/continuation findings below concern later catalog
+availability and do not explain that initial live phase. See
+[the live-only import comparison](XTREAM_LIVE_IMPORT_COMPARISON.md) for the
+revised priority and concrete reference-code comparison.
+
+## Current execution
+
+ProviderSetupViewModel → ValidateAndAddProvider → ProviderRepositoryImpl:
+authenticate, save/stage configuration, run initial onboarding sync.
+SyncManager/SyncCoordinator route into XtreamCatalogSyncExecutor.syncFull.
+
+The foreground sequence is:
+
+1. Fetch live categories.
+2. Import the complete live lineup, with bulk or category requests; stage batches.
+3. Commit live rows and rebuild channel FTS.
+4. Fetch and commit movie category shells.
+5. Fetch and commit series category shells.
+6. Return continuation work for live index backfill, movie summaries, series
+ summaries, and EPG. Provider setup can finish before movie/series items exist.
+
+ProviderContinuationScheduler enqueues EPG first, then live, movie, and series
+index workers. All use `provider-workflow-<id>` with APPEND_OR_REPLACE.
+The EPG worker has a 30-second initial delay. Index workers behind it wait for
+that delay and guide execution, including any WorkManager retries.
+
+Settings Sync Now performs TV, Movies, Series, EPG section calls in sequence.
+Xtream movie/series section calls update category shells and queue indexing;
+they do not await the complete item catalog. Settings shares the executors, but
+its operation sequence and live policy differ from initial onboarding.
+Full refresh/rebuild routes use the full plan, whose non-onboarding live reason
+is FOREGROUND; they should not be confused with the Settings TV section route.
+
+## Findings supported by code
+
+### 1. AUTO often deliberately chooses the expensive request topology
+
+`data/.../sync/XtreamLiveSyncPolicy.kt:38` selects category loading for LOW tier,
+current low-memory state, hidden categories, remembered stress/full avoidance,
+MID onboarding, and MANUAL_SETTINGS/BACKGROUND_STALE.
+`CatalogSyncRuntimeProfile.kt` defines LOW as memory class <=192 MB or low-RAM,
+MID as <=320 MB. MID onboarding prefers categories and permits at most two
+category requests; LOW permits one. HIGH may use bulk.
+
+`XtreamAdaptiveSyncPolicy.kt` adds 250 ms between CATEGORY request starts even
+on a healthy provider. For 200 category requests, the healthy start-spacing
+floor alone is about 49.75 seconds, before the final request finishes. This is
+a theoretical floor from policy, not a recorded provider timing. Concurrency
+does not remove this global pacing floor.
+
+`SyncManagerXtreamSupport.executeCategoryRecoveryPlan` processes small windows
+with awaitAll before starting the next window. A slow category prevents idle
+slots from taking new work. Concurrency is selected initially; the window loop
+can downgrade to sequential but does not continuously refill or increase slots.
+
+### 2. Guide scheduling blocks catalog availability
+
+Sources: `ProviderContinuationScheduler.kt:18`, `ProviderWorkScheduling.kt`,
+`BackgroundEpgSyncWorker.kt:131`, and `XtreamIndexWorker.enqueue`.
+The 30-second EPG delay and serial queue are structural delays in the normal
+onboarding continuation path. Their actual contribution to an observed run
+still needs timing evidence. EPG SKIP bypasses this part.
+
+This can explain a provider becoming active while movie/series categories stay
+empty. First improvement: put catalog indexing before EPG in the existing
+durable queue. A later scheduler can prioritize requested categories and guide
+availability explicitly, while preserving generation/lease/commit ownership.
+Creating independent queues alone would not address the provider-wide lock.
+
+### 3. Streaming still parses every row twice
+
+`remote/xtream/OkHttpXtreamApiService.kt:496` reads each row through Gson's
+JsonParser, serializes the resulting tree via element.toString(), and parses
+that string with kotlinx.serialization at line 504. This applies to streaming
+live, movie, and series arrays. Thin live DTOs reduce retained fields but do
+not eliminate the first parse, tree allocation, or second parse.
+
+All streaming callbacks await mapping and DB writes before reading more rows.
+This keeps memory bounded, but puts transfer/parse and persistence in sequence.
+A bounded producer/consumer pipeline can overlap stages when their costs
+justify it; it does not guarantee a win when the provider/network dominates.
+
+### 4. Live import does substantial repeated and additional database work
+
+`SyncCatalogStore.stageChannelBatch:371` enters a fenced transaction, counts
+all staged channels for the session, deduplicates the batch, fingerprints it,
+and inserts rows. LOW/MID/HIGH batches are only 100/300/500 rows. A 50,000-row
+LOW import therefore performs approximately 500 staging transactions and
+growing stage-count queries. The cost of those queries needs measurement.
+
+`SyncCatalogStore.applyStagedLiveCatalog:163` applies categories/channels and
+rebuilds channel FTS inside the commit transaction. The DAO rebuild is global
+to channels_fts, so other providers contribute to its cost too.
+Entities declare Fts4 contentEntity links; existing generated release Room code
+confirms automatic channel insert/update/delete FTS triggers. This suggests
+redundant work, but removing rebuilds requires proving search correctness for
+every affected write path and supported DB upgrade path.
+
+`SyncManager.backfillXtreamLiveIndex:2115` later reads every provider channel,
+creates a second full list of index entities, deletes its previous Xtream live
+index rows, and rewrites them. This also weakens the bounded-memory story of
+the earlier streaming stage. Index maintenance could use SQL projection or
+bounded changed-row updates during catalog promotion instead.
+
+The live refresh SQL (`CatalogSyncDao.updateChangedChannelsFromStage`) uses a
+separate correlated stage lookup for each field of a changed channel. It skips
+matching fingerprints, so this primarily matters for changed rows; first-add
+timings must be considered separately from refresh timings.
+
+### 5. Movies/series already have a bulk path, with a costly fallback
+
+`XtreamIncrementalIndexExecutor.processSummary` first attempts one full summary
+stream for a fresh job. Therefore the whole Xtream engine is not universally
+category-by-category. The existing bulk path is worth improving and reusing.
+
+Full summaries use 500-row batches. Each batch reads existing rows, merges
+metadata, writes catalog rows, rereads persisted IDs, writes Xtream index rows,
+and updates the durable job. The path does not filter unchanged summaries
+before writing all merged rows. Rich movie/series details remain separate from
+this summary import; background "indexing" includes downloading basic catalog
+items, not just constructing a search index.
+
+When full streaming fails, summaries use a sequential category loop and the
+worker limits each invocation to two categories (`CATEGORY_SLICE_SIZE = 2`).
+Each slice schedules another durable worker. A 200-category fallback requires
+about 100 worker invocations, plus the failed bulk attempt. Fresh/full streams
+are not limited to two categories.
+
+Large bulk bodies have ceilings: live 96 MiB, movies 80 MiB, series 100 MiB
+(plus the configured headroom). A rejected oversized response can send work
+into the slower fallback. Preserve limits, but measure whether wire-size caps
+remain the right protection for a bounded streaming parser.
+
+### 6. Legacy settings are misleading foundations for optimization
+
+Provider setup and repository onboarding force xtreamFastSyncEnabled=false.
+Current syncFull already queues movie/series summaries instead of loading
+complete detail catalogs in the foreground. Toggling that legacy flag should
+not be assumed to activate a faster onboarding engine.
+
+## Proposed design
+
+Use one catalog ingestion pipeline, with different fetch strategies feeding
+it. Preserve existing configuration generations, commit fences, cancellation,
+hidden/protected categories, stable IDs, favorites and watch progress.
+
+- Fetch category metadata once per section and reuse it for classification.
+ Independent metadata requests can overlap under a modest provider budget.
+- Prefer streaming bulk for healthy providers when the new parser/pipeline has
+ demonstrated bounded memory on LOW devices too. Learn provider capability
+ and outcomes; retain explicit user modes and category fallback. Device tier
+ should primarily select memory/batch budgets, rather than decide request
+ count on its own.
+- Parse directly into thin rows with one parser; tolerate provider field
+ variants without reparsing whole responses. Map rows once.
+- Feed a bounded queue to one DB writer. Tune batch size by measured throughput,
+ row size, heap headroom and transaction duration. Maintain cheap incremental
+ counts, with durable reconciliation on resume and existing size limits.
+- Promote complete snapshots safely and avoid duplicate full index passes.
+ Refresh writes should skip unchanged records. A partial import must preserve
+ rows outside its confirmed scope; stale pruning follows complete generations.
+- For category fallback use a continuously refilled, bounded worker pool.
+ Adapt concurrency and pacing to observed server stress, including Retry-After
+ when supplied, and retry only failed categories with durable checkpoints.
+- Prioritize catalog availability before EPG and enrichment. Requested category
+ work should outrank background completion. Worker slices should have measured
+ time/row budgets rather than a universal two-category limit.
+- Keep details/episodes/enrichment on demand or in lower-priority background
+ work. Show separate live-ready, catalog-ready, search-ready and guide-ready
+ states instead of treating queued category shells as completed item sync.
+
+An optional small live preview could shorten first-playable time. Treat that
+as a separate product choice; it is not proof of faster complete ingestion and
+must not delete the rest of the lineup as if the preview were a full snapshot.
+
+## Implementation and measurement order
+
+1. Instrument baseline milestones and stage costs, then fix continuation order.
+2. Benchmark and replace the double parse; add the bounded writer pipeline.
+3. Reduce staging/query/index work and skip unchanged refresh writes.
+4. Validate bulk on constrained devices, then change AUTO and category workers.
+5. Align Settings completion/progress with the same readiness milestones.
+
+Measure request counts, bytes, response-header latency, end-to-end transfer,
+parse/map CPU, writer queue wait, staging, commit, FTS, Xtream index, scheduling
+wait, peak heap/GC, retry/fallback counts, and total elapsed time. End-to-end
+stream duration includes downstream callback work today; do not call that pure
+network time. Correlate sanitized records by run/provider/section/strategy.
+
+Compare both first usable live playback and full catalog/search completion.
+Use identical provider snapshot, device, section counts, network, hidden-category
+configuration, and metadata scope for this app and any reference implementation.
+Repeat runs and report median and spread. A 10x target remains unproven.
+
+Use synthetic small and large datasets (for example 50k live, 100k movies,
+20k series; many tiny categories and uneven large categories), low/mid/high
+device budgets, slow/rate-limited/bulk-rejecting servers, malformed rows,
+interrupted imports, and refreshes with zero/small/large changes. Verify counts,
+category coverage, playback URLs, search, preserved user state, process-death
+resume, provider edits/deletion and failed-snapshot preservation.
+
+The existing local catalog fixture is a correctness fixture: one live channel,
+63 movies and 63 series. It cannot establish large-catalog throughput. An
+emulator is connected, but its available filtered logcat contained no matching
+Xtream sync timing records during inspection. No add-provider operation or
+runtime benchmark was performed, and no playback validation is claimed.
+
+## Reference repository comparison
+
+Compare endpoint/request topology, parsing allocations, write and indexing
+strategy, readiness criteria, metadata scope, and recovery behavior before
+borrowing implementation ideas. Check its license before adapting source.
+Use its results to revise this proposal rather than committing to a rewrite
+based only on this initial inspection.
diff --git a/tools/tests/test_xtream_sync_benchmark.py b/tools/tests/test_xtream_sync_benchmark.py
new file mode 100644
index 00000000..8bfb4b67
--- /dev/null
+++ b/tools/tests/test_xtream_sync_benchmark.py
@@ -0,0 +1,66 @@
+import importlib.util
+import json
+import sys
+import unittest
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).parents[1]))
+SPEC = importlib.util.spec_from_file_location("xtream_sync_benchmark", Path(__file__).parents[1] / "xtream_sync_benchmark.py")
+BENCHMARK = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(BENCHMARK)
+
+
+class BenchmarkReportTest(unittest.TestCase):
+ def test_only_benchmark_records_are_retained(self):
+ log = '\n'.join([
+ 'I/OtherTag( 123): password=private',
+ 'I/XtreamSyncBenchmark( 123): {"event":"complete"}',
+ 'I/XtreamSyncBenchmark( 123): {"event":"unrelated","secret":"private"}',
+ ])
+ self.assertEqual([{"event": "complete"}], BENCHMARK.parse_records(log))
+ self.assertNotIn("private", json.dumps(BENCHMARK.parse_records(log)))
+
+ def test_warmups_are_excluded_and_request_scopes_are_distinguished(self):
+ records = [{"event": "sample", "run": "bench_test", "mode": "AUTO", "phase": "initial",
+ "warmup": warmup, "elapsed_ms": elapsed, "channels": 100,
+ "peak_java_heap_bytes": 1024, "milestones": [{"phase": "live-committed", "elapsed_ms": elapsed - 1}]}
+ for warmup, elapsed in [(True, 9000), (False, 100), (False, 200), (False, 300)]]
+ events = [{"event": "request_start", "request_id": index, "run": run,
+ "action": action, "category_id": category}
+ for index, (run, action, category) in enumerate([
+ ("bench_test", "get_live_streams", None),
+ ("bench_test", "get_live_streams", 1),
+ ("bench_test", "authenticate", None),
+ ("bench_other", "get_live_streams", 2)])]
+ report = BENCHMARK.summarize(records, events, {})
+ self.assertFalse(report["complete"])
+ self.assertEqual(3, report["groups"][0]["samples"])
+ self.assertEqual(200, report["groups"][0]["median_ms"])
+ self.assertEqual(199, report["groups"][0]["median_live_committed_ms"])
+ self.assertEqual(300, report["groups"][0]["max_ms"])
+ self.assertEqual(1, report["samples"][0]["account_bulk_requests"])
+ self.assertEqual(1, report["samples"][0]["account_category_requests"])
+
+ def test_warmups_alone_cannot_produce_a_result(self):
+ report = BENCHMARK.summarize([{"event": "sample", "run": "bench_test", "mode": "AUTO",
+ "phase": "initial", "warmup": True}], [], {})
+ self.assertEqual([], report["groups"])
+
+ def test_timings_are_numeric_and_prior_run_is_discarded(self):
+ log = '\n'.join([
+ 'I/XtreamSyncBenchmark( 123): {"event":"complete"}',
+ 'I/XtreamSyncBenchmark( 123): {"event":"environment"}',
+ 'I/XtreamSyncTiming( 123): phase=live-response elapsed_ms=100 callback_ms=60 rows=500 completed=true',
+ 'I/SyncCatalogStore( 123): catalog timing provider=5 stage=channel-staging-batch(300) took=5ms',
+ 'I/SyncCatalogStore( 123): unexpected credential=private',
+ ])
+ records = BENCHMARK.parse_records(log)
+ self.assertEqual(3, len(records))
+ self.assertEqual(60, records[1]["callback_ms"])
+ self.assertEqual(5, records[2]["provider_id"])
+ self.assertFalse(BENCHMARK.summarize(records, [], {})["complete"])
+ self.assertNotIn("private", json.dumps(records))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/tests/test_xtream_sync_perf_fixture.py b/tools/tests/test_xtream_sync_perf_fixture.py
new file mode 100644
index 00000000..3fd7aff4
--- /dev/null
+++ b/tools/tests/test_xtream_sync_perf_fixture.py
@@ -0,0 +1,109 @@
+import importlib.util
+import json
+import sys
+import threading
+import unittest
+from pathlib import Path
+from urllib.error import HTTPError
+from urllib.request import urlopen
+
+
+SPEC = importlib.util.spec_from_file_location(
+ "xtream_sync_perf_fixture", Path(__file__).parents[1] / "xtream_sync_perf_fixture.py"
+)
+FIXTURE = importlib.util.module_from_spec(SPEC)
+sys.modules[SPEC.name] = FIXTURE
+SPEC.loader.exec_module(FIXTURE)
+
+
+class XtreamSyncPerfFixtureTest(unittest.TestCase):
+ def test_category_partition_matches_bulk_without_losing_rows(self):
+ scenario = FIXTURE.Scenario(channels=103, categories=12)
+ bulk = list(scenario.rows())
+ partition = [row for category in range(1, 13) for row in scenario.rows(category)]
+ self.assertEqual(bulk, sorted(partition, key=lambda row: row["num"]))
+ self.assertEqual([], list(scenario.rows(999)))
+
+ def test_hash_is_deterministic_and_fault_admission_is_explicit(self):
+ scenario = FIXTURE.Scenario(channels=103, categories=12, malformed_every=10)
+ metadata = scenario.metadata()
+ self.assertEqual(93, metadata["expected_channels"])
+ self.assertEqual(metadata, scenario.metadata())
+ self.assertNotEqual(metadata["payload_sha256"],
+ FIXTURE.Scenario(channels=103, categories=12, seed=2).metadata()["payload_sha256"])
+ self.assertEqual(103, len(json.loads(b"".join(scenario.chunks()))))
+
+ 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)
+ thread.start()
+
+ def close():
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=3)
+
+ self.addCleanup(close)
+ return server, "http://127.0.0.1:" + str(server.server_address[1])
+
+ def get(self, base, path):
+ with urlopen(base + path, timeout=3) as response:
+ return json.load(response)
+
+ def test_http_stream_and_events_never_expose_credentials(self):
+ server, base = self.start_server(channels=103, categories=12)
+ body = self.get(base, "/player_api.php?action=get_live_streams&category_id=2"
+ "&username=private-user&password=do-not-log")
+ self.assertEqual(9, len(body))
+ events = self.get(base, "/events")
+ serialized = json.dumps(events)
+ self.assertNotIn("private-user", serialized)
+ self.assertNotIn("do-not-log", serialized)
+ self.assertEqual(2, events["events"][0]["category_id"])
+ self.assertEqual(len(body), events["events"][1]["rows"])
+ self.assertTrue(events["events"][1]["completed"])
+ self.assertEqual(103, self.get(base, "/fixture")["expected_channels"])
+ self.assertEqual(0, server.active)
+
+ def test_bulk_rejection_does_not_reject_categories(self):
+ _, base = self.start_server(channels=30, categories=3, bulk_status=503)
+ with self.assertRaises(HTTPError) as error:
+ self.get(base, "/player_api.php?action=get_live_streams")
+ self.assertEqual(503, error.exception.code)
+ error.exception.close()
+ self.assertEqual(10, len(self.get(base, "/player_api.php?action=get_live_streams&category_id=1")))
+
+ 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):
+ self.get(base, "/player_api.php?action=get_live_streams")
+ events = self.get(base, "/events")["events"]
+ self.assertEqual(5, events[-1]["rows"])
+ self.assertFalse(events[-1]["completed"])
+
+ def test_slow_response_allows_overlapping_http_requests(self):
+ _, base = self.start_server(channels=20, categories=2, header_delay_ms=50)
+ barrier = threading.Barrier(3)
+ errors = []
+
+ def fetch(action):
+ try:
+ barrier.wait(timeout=2)
+ self.get(base, "/player_api.php?action=" + action)
+ except Exception as error:
+ errors.append(error)
+
+ threads = [threading.Thread(target=fetch, args=(action,))
+ for action in ("get_live_categories", "get_live_streams")]
+ for thread in threads:
+ thread.start()
+ barrier.wait(timeout=2)
+ for thread in threads:
+ thread.join(timeout=3)
+ self.assertFalse(errors)
+ self.assertTrue(all(not thread.is_alive() for thread in threads))
+ self.assertEqual(2, self.get(base, "/events")["high_water"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/xtream_sync_benchmark.py b/tools/xtream_sync_benchmark.py
new file mode 100644
index 00000000..a871ead3
--- /dev/null
+++ b/tools/xtream_sync_benchmark.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python3
+"""Run the isolated Android sync benchmark against a local synthetic fixture."""
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import shutil
+import statistics
+import subprocess
+import threading
+from dataclasses import asdict
+from datetime import datetime, timezone
+from pathlib import Path
+
+from xtream_sync_perf_fixture import FixtureServer, Scenario
+
+
+PACKAGE = "com.streamvault.app.syncbenchmark"
+TEST_CLASS = "com.streamvault.app.benchmark.XtreamLiveSyncBenchmarkTest"
+MODES = {"AUTO", "STREAM_ALL", "CATEGORY_BY_CATEGORY"}
+
+
+def parse_records(log: str) -> list[dict]:
+ records = []
+ for line in log.splitlines():
+ # Only our JSON tag is retained; never copy unrelated provider logs.
+ match = re.search(r"\bXtreamSyncBenchmark\s*\([^)]*\):\s*(\{.*\})$", line)
+ if match:
+ value = json.loads(match[1])
+ if value.get("event") in {"environment", "sample", "complete"}:
+ if value["event"] == "environment":
+ records.clear() # Discard the previous run's last buffered line.
+ records.append(value)
+ continue
+ timing = re.search(r"\bXtreamSyncTiming\s*\([^)]*\): phase=live-response elapsed_ms=(\d+) callback_ms=(\d+) rows=(\d+) completed=(true|false)$", line)
+ if timing:
+ records.append({"event": "live-response", "elapsed_ms": int(timing[1]),
+ "callback_ms": int(timing[2]), "rows": int(timing[3]),
+ "completed": timing[4] == "true"})
+ stage = re.search(r"\bSyncCatalogStore\s*\([^)]*\): catalog timing provider=(\d+) stage=([a-z-]+(?:\(\d+\))?) took=(\d+)ms$", line)
+ if stage:
+ records.append({"event": "catalog-stage", "provider_id": int(stage[1]),
+ "stage": stage[2], "elapsed_ms": int(stage[3])})
+ return records
+
+
+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"]
+ 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.
+ requests = [event for event in starts.values() if event["run"] == sample["run"]]
+ live = [event for event in requests if event["action"] == "get_live_streams"]
+ 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)
+ 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"]]
+ if not selected:
+ continue
+ 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),
+ "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", "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."]}
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--adb", default=shutil.which("adb"))
+ parser.add_argument("--serial", default="emulator-5554")
+ parser.add_argument("--port", type=int, default=8766)
+ parser.add_argument("--modes", default="AUTO,STREAM_ALL,CATEGORY_BY_CATEGORY")
+ 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("--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():
+ parser.add_argument("--" + field.replace("_", "-"), type=int, default=default)
+ args = parser.parse_args()
+ if not args.adb or not set(args.modes.split(',')) <= MODES:
+ 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 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())})
+ output = args.output or Path(__file__).resolve().parents[1] / "build" / "xtream-sync-performance" / datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
+ output.mkdir(parents=True, exist_ok=False)
+ server = FixtureServer(("127.0.0.1", args.port), scenario, output / "requests.jsonl")
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ adb = [args.adb, "-s", args.serial]
+
+ def command(*parts):
+ return subprocess.run([*adb, *parts], capture_output=True, text=True, check=True).stdout
+
+ # Do not steal an existing reverse mapping or erase the device log buffer.
+ mapping = "tcp:" + str(args.port)
+ reversed_port = False
+ log_process = None
+ raw_log = output / "benchmark-log.txt"
+ try:
+ existing = command("reverse", "--list")
+ if any(mapping in line.split()[1:] for line in existing.splitlines()):
+ raise RuntimeError("Benchmark port already has an adb reverse mapping; use another --port")
+ check_package = command("shell", "pm", "path", PACKAGE).strip()
+ if not check_package.startswith("package:"):
+ raise RuntimeError("Install the isolated benchmark APK first")
+ command("reverse", mapping, mapping)
+ reversed_port = True
+ with raw_log.open("w", encoding="utf-8") as log:
+ log_process = subprocess.Popen([*adb, "logcat", "-T", "1", "-v", "brief", "-s",
+ "XtreamSyncBenchmark:I", "XtreamSyncTiming:I", "SyncCatalogStore:I"],
+ stdout=log, stderr=subprocess.PIPE, text=True)
+ result = subprocess.run([*adb, "shell", "am", "instrument", "-w", "-r",
+ "-e", "class", TEST_CLASS, "-e", "xtreamSyncBenchmark", "true",
+ "-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", "cleanupRun", args.cleanup_run] if args.cleanup_run else []),
+ PACKAGE + ".test/androidx.test.runner.AndroidJUnitRunner"],
+ capture_output=True, text=True)
+ log_process.terminate()
+ log_process.communicate(timeout=10)
+ # 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)}
+ 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")
+ with server.lock:
+ events = list(server.events)
+ request_events_truncated = server.sequence * 2 - server.active > len(events)
+ max_active_requests = server.high_water
+ report = summarize(records, events, server.metadata)
+ report["request_events_truncated"] = request_events_truncated
+ report["max_active_requests"] = max_active_requests
+ expected_samples = len(args.modes.split(',')) * (args.iterations + args.warmups) * (2 if args.refresh else 1)
+ report["expected_samples"] = expected_samples
+ report["all_samples_recorded"] = len(report["samples"]) == expected_samples
+ report["instrumentation"] = status
+ (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:
+ raise SystemExit("Benchmark failed; no successful performance result was recorded")
+ finally:
+ if log_process and log_process.poll() is None:
+ log_process.terminate()
+ log_process.communicate(timeout=10)
+ if reversed_port:
+ command("reverse", "--remove", mapping)
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=3)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/xtream_sync_perf_fixture.py b/tools/xtream_sync_perf_fixture.py
new file mode 100644
index 00000000..2ac38c3e
--- /dev/null
+++ b/tools/xtream_sync_perf_fixture.py
@@ -0,0 +1,271 @@
+#!/usr/bin/env python3
+"""Streaming, deterministic live-only Xtream fixture for sync measurements.
+
+No provider account is required. Payloads are generated a row at a time; events
+contain action/scope/count/timing only, never URLs or query credentials.
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import re
+import threading
+import time
+from collections import deque
+from dataclasses import asdict, dataclass
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Iterator
+from urllib.parse import parse_qs, urlparse
+
+
+@dataclass(frozen=True)
+class Scenario:
+ channels: int = 10_000
+ categories: int = 100
+ seed: int = 1
+ header_delay_ms: int = 0
+ category_delay_ms: int = 0
+ bytes_per_second: int = 0
+ bulk_status: int = 200
+ disconnect_after_rows: int = 0
+ malformed_every: int = 0
+ throttle_every: int = 0
+
+ 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")
+ 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")
+
+ def rows(self, category_id: int | None = None) -> Iterator[dict]:
+ # Jump directly to the selected category; no full-catalog scan per request.
+ start = 1 if category_id is None else category_id
+ step = 1 if category_id is None else self.categories
+ if category_id is not None and not 1 <= category_id <= self.categories:
+ return
+ for number in range(start, self.channels + 1, step):
+ category = (number - 1) % self.categories + 1
+ yield {
+ "num": number,
+ "name": f"Benchmark Channel {number:06d} HD",
+ "stream_id": None if self.malformed_every and number % self.malformed_every == 0 else 100_000 + number,
+ "stream_type": "live",
+ "stream_icon": "",
+ "epg_channel_id": f"benchmark-{self.seed}-{number}",
+ "category_id": str(category),
+ "container_extension": "m3u8",
+ "tv_archive": int(number % 7 == 0),
+ "tv_archive_duration": 3 if number % 7 == 0 else 0,
+ "is_adult": 0,
+ }
+
+ def chunks(self, category_id: int | None = None) -> Iterator[bytes]:
+ yield b"["
+ for index, row in enumerate(self.rows(category_id)):
+ if index:
+ yield b","
+ yield encode(row)
+ yield b"]"
+
+ def metadata(self) -> dict:
+ digest = hashlib.sha256()
+ size = 0
+ for chunk in self.chunks():
+ digest.update(chunk)
+ size += len(chunk)
+ 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),
+ "payload_sha256": digest.hexdigest(),
+ "payload_bytes": size,
+ "playback_media": False,
+ }
+
+
+def encode(value) -> bytes:
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
+
+
+class FixtureServer(ThreadingHTTPServer):
+ daemon_threads = True
+
+ def __init__(self, address, scenario: Scenario, event_log: Path | None = None):
+ super().__init__(address, Handler)
+ self.scenario = scenario
+ self.metadata = scenario.metadata()
+ self.events = deque(maxlen=20_000)
+ self.event_log = event_log
+ self.lock = threading.Lock()
+ self.sequence = 0
+ self.active = 0
+ self.high_water = 0
+ self.live_requests = 0
+ self.epoch = time.monotonic()
+ if event_log:
+ event_log.parent.mkdir(parents=True, exist_ok=True)
+
+ def record(self, event: dict) -> None:
+ # Caller holds lock.
+ self.events.append(event)
+ if self.event_log:
+ with self.event_log.open("a", encoding="utf-8") as output:
+ output.write(json.dumps(event, separators=(",", ":")) + "\n")
+
+ def begin(self, action: str, category_id: int | None, run: str) -> tuple[int, int]:
+ with self.lock:
+ self.sequence += 1
+ self.active += 1
+ self.high_water = max(self.high_water, self.active)
+ if action == "get_live_streams":
+ self.live_requests += 1
+ self.record({
+ "event": "request_start", "request_id": self.sequence,
+ "at_ms": round((time.monotonic() - self.epoch) * 1000, 3),
+ "run": run, "action": action, "category_id": category_id,
+ "active": self.active,
+ })
+ return self.sequence, self.live_requests
+
+ def finish(self, request_id: int, rows: int, size: int, status: int, started: float, completed: bool):
+ with self.lock:
+ self.active -= 1
+ self.record({
+ "event": "request_end", "request_id": request_id,
+ "at_ms": round((time.monotonic() - self.epoch) * 1000, 3),
+ "elapsed_ms": round((time.monotonic() - started) * 1000, 3),
+ "rows": rows, "bytes": size, "status": status,
+ "completed": completed,
+ })
+
+
+class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *_args):
+ pass
+
+ def json_response(self, body, status=200):
+ raw = encode(body)
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json; charset=utf-8")
+ self.send_header("Content-Length", str(len(raw)))
+ self.end_headers()
+ self.wfile.write(raw)
+ return len(raw)
+
+ def do_GET(self):
+ parsed = urlparse(self.path)
+ query = parse_qs(parsed.query)
+ server: FixtureServer = self.server
+ if parsed.path == "/fixture":
+ self.json_response(server.metadata)
+ return
+ if parsed.path == "/events":
+ with server.lock:
+ snapshot = {"events": list(server.events), "high_water": server.high_water}
+ self.json_response(snapshot)
+ return
+ if parsed.path != "/player_api.php":
+ self.json_response({"error": "not_found"}, 404)
+ return
+ action = query.get("action", ["authenticate"])[0]
+ if action not in {"authenticate", "get_live_categories", "get_live_streams",
+ "get_vod_categories", "get_vod_streams", "get_series_categories", "get_series"}:
+ self.json_response({"error": "unsupported_action"}, 400)
+ return
+ try:
+ category_id = int(query["category_id"][0]) if "category_id" in query else None
+ except ValueError:
+ self.json_response({"error": "invalid_category"}, 400)
+ return
+ username = query.get("username", [""])[0]
+ # Only synthetic benchmark tokens can appear in artifacts.
+ run = username if re.fullmatch(r"bench_[a-zA-Z0-9_]{1,100}", username) else "unlabelled"
+ started = time.monotonic()
+ request_id, request_number = server.begin(action, category_id, run)
+ size = rows = 0
+ status = 200
+ completed = False
+ try:
+ scenario = server.scenario
+ time.sleep(scenario.header_delay_ms / 1000)
+ if action == "authenticate":
+ size = self.json_response({
+ "user_info": {"auth": 1, "status": "Active", "max_connections": "4",
+ "allowed_output_formats": ["m3u8", "ts"]},
+ "server_info": {"version": "fixture-v1", "server_protocol": "http"},
+ })
+ elif action == "get_live_categories":
+ time.sleep(scenario.category_delay_ms / 1000)
+ size = self.json_response([
+ {"category_id": str(index), "category_name": f"Benchmark Group {index:04d}",
+ "parent_id": 0, "is_adult": 0}
+ for index in range(1, scenario.categories + 1)
+ ])
+ elif action == "get_live_streams":
+ status = scenario.bulk_status if category_id is None else 200
+ if scenario.throttle_every and request_number % scenario.throttle_every == 0:
+ status = 429
+ if status != 200:
+ size = self.json_response({"error": "configured_failure"}, status)
+ else:
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json; charset=utf-8")
+ # HTTP/1.0 close-delimited response supports incremental generation.
+ self.end_headers()
+ delivery_started = time.monotonic()
+ self.wfile.write(b"[")
+ size = 1
+ for row in scenario.rows(category_id):
+ chunk = (b"," if rows else b"") + encode(row)
+ self.wfile.write(chunk)
+ size += len(chunk)
+ rows += 1
+ if rows % 128 == 0:
+ self.wfile.flush()
+ if scenario.bytes_per_second:
+ wait = size / scenario.bytes_per_second - (time.monotonic() - delivery_started)
+ if wait > 0:
+ time.sleep(wait)
+ if scenario.disconnect_after_rows and rows == scenario.disconnect_after_rows:
+ self.wfile.flush()
+ self.close_connection = True
+ return
+ self.wfile.write(b"]")
+ self.wfile.flush()
+ size += 1
+ else:
+ # Isolate live ingestion from VOD/series/EPG work.
+ size = self.json_response([])
+ completed = True
+ except (BrokenPipeError, ConnectionResetError):
+ self.close_connection = True
+ finally:
+ server.finish(request_id, rows, size, status, started, completed)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--bind", default="127.0.0.1")
+ parser.add_argument("--port", type=int, default=8766)
+ parser.add_argument("--events", type=Path)
+ for field, default in asdict(Scenario()).items():
+ parser.add_argument("--" + field.replace("_", "-"), type=int, default=default)
+ args = parser.parse_args()
+ scenario = Scenario(**{field: getattr(args, field) for field in asdict(Scenario())})
+ server = FixtureServer((args.bind, args.port), scenario, args.events)
+ print(json.dumps({"listening_port": server.server_address[1], **server.metadata}), flush=True)
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ pass
+ finally:
+ server.server_close()
+
+
+if __name__ == "__main__":
+ main()