Skip to content

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

feat: Enhance Macrobenchmark with upstream stop tracking and process preservation

David Nashash9ede5f3314a3
diff --git a/benchmark/src/main/java/com/streamvault/benchmark/BenchmarkConfig.kt b/benchmark/src/main/java/com/streamvault/benchmark/BenchmarkConfig.kt
index 425d9458..3651ba1a 100644
--- a/benchmark/src/main/java/com/streamvault/benchmark/BenchmarkConfig.kt
+++ b/benchmark/src/main/java/com/streamvault/benchmark/BenchmarkConfig.kt
@@ -12,6 +12,7 @@ import java.util.regex.Pattern
internal const val RELEASE_TARGET_PACKAGE = "com.streamvault.app"
internal const val SEEDED_DEBUG_PACKAGE = "com.streamvault.app.debug"
private const val SEEDED_DEBUG_ACTIVITY = "$SEEDED_DEBUG_PACKAGE/com.streamvault.app.MainActivity"
+private const val CLEAR_TASK_NEW_TASK_FLAGS = "0x10008000"
internal const val BENCHMARK_ITERATIONS = 5
internal const val STARTUP_BENCHMARK_ITERATIONS = 10
internal const val UI_TIMEOUT_MS = 20_000L
@@ -60,6 +61,28 @@ internal fun MacrobenchmarkScope.startSeededDebugApp() {
device.waitForIdle()
}
+/**
+ * Brings the seeded debug fixture to the foreground without killing its process.
+ *
+ * Re-entry measurements use this setup so the application-lifetime category cache can survive
+ * between iterations while the measured block still owns the first Live TV subscription.
+ */
+internal fun MacrobenchmarkScope.startSeededDebugAppPreservingProcess() {
+ pressHome()
+ device.executeShellCommand(
+ "am start -W -f $CLEAR_TASK_NEW_TASK_FLAGS -n $SEEDED_DEBUG_ACTIVITY"
+ )
+ device.waitForIdle()
+}
+
+/** Recreates the seeded Activity task without stopping the application process or its cache. */
+internal fun MacrobenchmarkScope.restartSeededDebugTaskPreservingProcess() {
+ device.executeShellCommand(
+ "am start -W -a android.intent.action.VIEW -f $CLEAR_TASK_NEW_TASK_FLAGS -n $SEEDED_DEBUG_ACTIVITY"
+ )
+ device.waitForIdle()
+}
+
internal fun MacrobenchmarkScope.openTopLevelDestination(
label: String,
destinationTimeoutMs: Long = UI_TIMEOUT_MS,
diff --git a/benchmark/src/main/java/com/streamvault/benchmark/StreamVaultMacrobenchmark.kt b/benchmark/src/main/java/com/streamvault/benchmark/StreamVaultMacrobenchmark.kt
index 5cec40c4..c204ad16 100644
--- a/benchmark/src/main/java/com/streamvault/benchmark/StreamVaultMacrobenchmark.kt
+++ b/benchmark/src/main/java/com/streamvault/benchmark/StreamVaultMacrobenchmark.kt
@@ -77,31 +77,41 @@ class StreamVaultMacrobenchmark {
fun liveTvCategoryReentryCategoryBuild() = benchmarkRule.measureRepeated(
packageName = SEEDED_DEBUG_PACKAGE,
metrics = listOf(
+ // Interaction journeys launch the separately seeded .debug package while the
+ // macrobenchmark's tested APK remains the release package. Keep these trace metrics
+ // process-agnostic so the lifecycle sections from that fixture are observable.
TraceSectionMetric(
sectionName = "StreamVault.CategoryFlow.Build",
mode = TraceSectionMetric.Mode.Count,
- label = "categoryBuildCount",
- targetPackageOnly = true
+ label = "categoryBuildCount"
),
TraceSectionMetric(
sectionName = "StreamVault.CategoryFlow.UpstreamStart",
mode = TraceSectionMetric.Mode.Count,
- label = "categoryUpstreamStartCount",
- targetPackageOnly = true
+ label = "categoryUpstreamStartCount"
+ ),
+ TraceSectionMetric(
+ sectionName = "StreamVault.CategoryFlow.UpstreamStop",
+ mode = TraceSectionMetric.Mode.Count,
+ label = "categoryUpstreamStopCount"
),
FrameTimingMetric()
),
startupMode = StartupMode.WARM,
iterations = BENCHMARK_ITERATIONS,
setupBlock = {
- openTopLevelDestination("Live TV")
- waitForLiveCategoryAvailability()
+ startSeededDebugAppPreservingProcess()
+ navigateToTopLevelDestination("Home")
+ assertDestination("Home")
}
) {
- // Leave and re-enter the same route inside the measured block. The trace count records
- // category construction separately from frame timing, so a replay hit is observable
- // even when UI rendering is noisy on an emulator.
- navigateToTopLevelDestination("Home")
+ // Enter Live TV inside the measured block so the initial category subscription and any
+ // later upstream restart are included in the trace window. The setup leaves the process
+ // alive, allowing the application-lifetime cache to survive between iterations.
+ navigateToTopLevelDestination("Live TV")
+ assertDestination("Live TV")
+ waitForLiveCategoryAvailability()
+ restartSeededDebugTaskPreservingProcess()
assertDestination("Home")
navigateToTopLevelDestination("Live TV")
assertDestination("Live TV")
diff --git a/data/src/main/java/com/streamvault/data/repository/CategoryFlowTraceReporter.kt b/data/src/main/java/com/streamvault/data/repository/CategoryFlowTraceReporter.kt
index 19fff8aa..04e49bd5 100644
--- a/data/src/main/java/com/streamvault/data/repository/CategoryFlowTraceReporter.kt
+++ b/data/src/main/java/com/streamvault/data/repository/CategoryFlowTraceReporter.kt
@@ -18,7 +18,13 @@ class CategoryFlowTraceReporter @Inject constructor() {
Trace.endSection()
}
+ fun onUpstreamStop(_providerId: Long) {
+ Trace.beginSection(UPSTREAM_STOP_TRACE)
+ Trace.endSection()
+ }
+
companion object {
const val UPSTREAM_START_TRACE = "StreamVault.CategoryFlow.UpstreamStart"
+ const val UPSTREAM_STOP_TRACE = "StreamVault.CategoryFlow.UpstreamStop"
}
}
diff --git a/data/src/main/java/com/streamvault/data/repository/ChannelCategoryFlowCache.kt b/data/src/main/java/com/streamvault/data/repository/ChannelCategoryFlowCache.kt
index 03f35929..6d7dad65 100644
--- a/data/src/main/java/com/streamvault/data/repository/ChannelCategoryFlowCache.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ChannelCategoryFlowCache.kt
@@ -12,6 +12,7 @@ import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.shareIn
@@ -80,13 +81,24 @@ class ChannelCategoryFlowCache @Inject constructor(
return CacheEntry(
flow = builder()
.onStart { traceReporter.onUpstreamStart(providerId) }
+ .onCompletion { traceReporter.onUpstreamStop(providerId) }
.distinctUntilChanged()
.shareIn(
scope = entryScope,
- started = SharingStarted.WhileSubscribed(stopTimeoutMillis = 0L),
+ started = SharingStarted.WhileSubscribed(
+ stopTimeoutMillis = UPSTREAM_STOP_TIMEOUT_MILLIS
+ ),
replay = 1
),
scope = entryScope
)
}
+
+ companion object {
+ /**
+ * Keeps Room observation alive across the short Activity/navigation gaps used by TV
+ * re-entry while still releasing an idle provider flow promptly.
+ */
+ const val UPSTREAM_STOP_TIMEOUT_MILLIS = 30_000L
+ }
}
diff --git a/data/src/test/java/com/streamvault/data/repository/ChannelCategoryFlowCacheTest.kt b/data/src/test/java/com/streamvault/data/repository/ChannelCategoryFlowCacheTest.kt
index c985c96f..0aee77c3 100644
--- a/data/src/test/java/com/streamvault/data/repository/ChannelCategoryFlowCacheTest.kt
+++ b/data/src/test/java/com/streamvault/data/repository/ChannelCategoryFlowCacheTest.kt
@@ -21,6 +21,7 @@ import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.async
import kotlinx.coroutines.test.advanceUntilIdle
+import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import org.junit.Test
@@ -189,6 +190,44 @@ class ChannelCategoryFlowCacheTest {
cacheScope.cancel()
}
+ @Test
+ fun `cached upstream stop is reported when the shared flow is cancelled`() = runTest {
+ whenever(providerDao.getAll()).thenReturn(flowOf(listOf(provider(7L))))
+ val cacheScope = CoroutineScope(UnconfinedTestDispatcher(testScheduler))
+ val cache = ChannelCategoryFlowCache(providerDao, cacheScope, traceReporter)
+ val upstream = flow<List<Category>> { awaitCancellation() }
+ val subscription = launch { cache.getOrCreate(7L) { upstream }.collect() }
+ advanceUntilIdle()
+
+ subscription.cancel()
+ advanceUntilIdle()
+
+ verify(traceReporter, times(1)).onUpstreamStop(7L)
+ cacheScope.cancel()
+ }
+
+ @Test
+ fun `quick subscriber reentry keeps the shared upstream alive`() = runTest {
+ whenever(providerDao.getAll()).thenReturn(flowOf(listOf(provider(7L))))
+ val cacheScope = CoroutineScope(UnconfinedTestDispatcher(testScheduler))
+ val cache = ChannelCategoryFlowCache(providerDao, cacheScope, traceReporter)
+ val upstream = flow<List<Category>> { awaitCancellation() }
+ val cached = cache.getOrCreate(7L) { upstream }
+
+ val firstSubscription = launch { cached.collect() }
+ advanceUntilIdle()
+ firstSubscription.cancel()
+ advanceTimeBy(ChannelCategoryFlowCache.UPSTREAM_STOP_TIMEOUT_MILLIS - 1L)
+
+ val secondSubscription = launch { cached.collect() }
+ advanceUntilIdle()
+
+ verify(traceReporter, times(1)).onUpstreamStart(7L)
+ verify(traceReporter, times(0)).onUpstreamStop(7L)
+ secondSubscription.cancel()
+ cacheScope.cancel()
+ }
+
private fun provider(id: Long) = ProviderEntity(
id = id,
name = "Provider $id",
diff --git a/docs/COMPOSE_REDUCTION_AND_UI_ARCHITECTURE_PLAN.md b/docs/COMPOSE_REDUCTION_AND_UI_ARCHITECTURE_PLAN.md
index 567e0e08..7f715b30 100644
--- a/docs/COMPOSE_REDUCTION_AND_UI_ARCHITECTURE_PLAN.md
+++ b/docs/COMPOSE_REDUCTION_AND_UI_ARCHITECTURE_PLAN.md
@@ -1168,12 +1168,24 @@ diagnostic startup benefit. The Phase 2.5B physical-device and release-APK-size
gates remain open; generated profile output is therefore not yet a
release-approved artifact.
-Phase 2.5A measurement update (2026-08-22): the category re-entry
-Macrobenchmark now counts both category presentation builds and shared-flow
-upstream starts. Five seeded emulator iterations observed 0/0/0 for build and
-upstream-start min/median/max, with frame counts of 49/51/53. This confirms no
-restart in that journey but is not yet a quantified pre/post cache comparison;
-the direct Room-query and physical-device gates remain open.
+Phase 2.5A measurement update (2026-08-23): the category re-entry
+Macrobenchmark now counts category presentation builds plus shared-flow
+upstream starts and stops. The cache keeps each provider's Room observation
+alive for 30 seconds after its last subscriber, while provider removal cancels
+the entry immediately. The deterministic unit test confirms that a subscriber
+returning within that window replays the latest value without a second upstream
+start.
+
+The connected seeded-emulator task-reset journey was rerun after a clean debug
+process reset. Five iterations captured `2/2/1` for build/upstream-start/
+upstream-stop (min/median/max) and 83/87/90 frames. A controlled diagnostic run
+with the stop timeout set to zero captured the same `2/2/1` lifecycle counts,
+so this Activity-task boundary did not demonstrate a measurable cache win. The
+result is useful lifecycle evidence but not a quantified runtime reduction; a
+direct Room query-count or category-ready-latency benchmark remains open. The
+emulator and debuggable seeded target are diagnostic only, and the separate
+`.debug` interaction package is intentionally used to provide deterministic
+seeded data.
### 19.1 Baseline profile maintenance policy
diff --git a/docs/COMPOSE_REDUCTION_PHASE2_5A_REPORT.md b/docs/COMPOSE_REDUCTION_PHASE2_5A_REPORT.md
index a96911c7..ba648a04 100644
--- a/docs/COMPOSE_REDUCTION_PHASE2_5A_REPORT.md
+++ b/docs/COMPOSE_REDUCTION_PHASE2_5A_REPORT.md
@@ -1,6 +1,6 @@
# Compose Reduction Phase 2.5A Report
-Date: 2026-08-22
+Date: 2026-08-23
## Scope
@@ -17,6 +17,9 @@ included.
`ConcurrentHashMap`, uses the application repository scope, applies
`distinctUntilChanged()`, and observes `ProviderDao.getAll()` to evict deleted
providers.
+- The shared flow uses a 30-second `WhileSubscribed` stop timeout. That keeps
+ the Room observation alive across a short screen/task re-entry gap while
+ provider deletion still cancels the per-provider scope immediately.
- `ChannelRepositoryImpl` now keeps the original Room-backed category
construction in `buildCategoriesFlow(providerId)`. `getCategories()` uses the
shared replaying flow, while `getCategoriesSnapshot()` builds a fresh flow and
@@ -31,10 +34,11 @@ included.
- Added a separate `liveTvCategoryReentryCategoryBuild` journey. It leaves and
re-enters Live TV inside the measured block and reports both the
`StreamVault.CategoryFlow.Build` trace-section count and the new
- `StreamVault.CategoryFlow.UpstreamStart` count alongside frame timing. The
- latter is emitted at the shared-flow upstream boundary, so a non-zero value
- means that Room-backed category work restarted during re-entry. These traces
- are still not a substitute for a direct Room query-count measurement.
+ `StreamVault.CategoryFlow.UpstreamStart` and
+ `StreamVault.CategoryFlow.UpstreamStop` counts alongside frame timing. The
+ lifecycle hooks are emitted at the shared-flow upstream boundary, so they can
+ distinguish a restart from a retained subscription. These traces are still
+ not a substitute for a direct Room query-count measurement.
## Test coverage
@@ -48,6 +52,8 @@ Focused tests cover:
- provider deletion eviction and recreation without the old replay;
- fresh snapshot reads after the replayed result has become stale;
- category visibility/count changes after parental-control preference changes;
+- quick subscriber re-entry inside the stop timeout, proving that it does not
+ start a second Room observation;
- existing grouping, count, parental-filtering, and decorative-row behavior.
Validation completed:
@@ -99,23 +105,35 @@ emulator/debug target. The benchmark also carries the standard warnings that
an emulator and debuggable target are diagnostic only, not representative
release-device performance.
-The strengthened re-entry benchmark was run on
+The strengthened re-entry benchmark was rerun on
`Television_1080p(AVD) - 16` with five iterations using
`:benchmark:connectedBenchmarkBenchmarkAndroidTest` and the seeded debug
-fixture. The result was stable across all runs:
+fixture. The harness starts from Home without killing the debug process,
+performs the first Live TV entry inside the measured block, and leaves
+`targetPackageOnly` disabled because the interaction fixture is the separate
+`.debug` package. The latest run used the 30-second stop timeout and captured:
| Metric | Min | Median | Max |
| --- | ---: | ---: | ---: |
-| `categoryBuildCountCount` | 0 | 0 | 0 |
-| `categoryUpstreamStartCountCount` | 0 | 0 | 0 |
-| `frameCount` | 49 | 51 | 53 |
-
-The trace evidence shows no category recomputation or upstream restart during
-the measured re-entry journey. This is stronger than frame timing alone, but
-it is an after-only observation: a controlled no-cache/pre-2.5A run and direct
-Room query-count or category-ready-latency evidence are still required before
-claiming a quantified caching improvement. The result is also diagnostic only
-because it uses an emulator and a debuggable seeded target.
+| `categoryBuildCountCount` | 2 | 2 | 2 |
+| `categoryUpstreamStartCountCount` | 2 | 2 | 2 |
+| `categoryUpstreamStopCountCount` | 1 | 1 | 1 |
+| `frameCount` | 83 | 87 | 90 |
+
+For comparison, the same task-reset journey with the stop timeout temporarily
+set to zero also captured `2/2/1` for build/start/stop in every iteration. The
+30-second setting therefore did not produce a measurable reduction in this
+specific Activity-task reset; the boundary is longer or otherwise different
+from the short subscriber gap covered by the deterministic unit test. This is
+useful lifecycle evidence, but it is not a quantified cache win. A direct Room
+query-count or category-ready-latency benchmark remains open before claiming a
+runtime reduction. Both runs are diagnostic only because they use an emulator
+and a debuggable seeded target.
+
+The focused unit test is the stronger proof for the cache contract: a second
+subscriber arriving before the timeout observes the replay without a second
+upstream start or stop. Provider deletion and preference changes remain covered
+by the same test suite.
The benchmark harness now explicitly launches `com.streamvault.app.debug` for
interaction journeys while leaving release startup/profile checks on the