Shadow comparison: paced, cancellable, resumable, and stops when Orbit needs the room
At least 1.5 s between pages (5 s while a programme plays), never faster than the server answers. A failed page is retried once after 30 s. It stops by itself if Orbit closes, playback stalls 3 times, memory passes 80%, or the server takes over 20 s a page 3 times running. Stop and resume from adb. The report is written every 25 pages so a stop keeps the results. Rebuilt into 0.123.0 (never installed). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -26,6 +26,11 @@ internal object ProviderSwitches {
|
||||
* here touches CatalogueStore. It records time, memory and errors, writes a report, and keeps a sanitised copy of the
|
||||
* first raw pages (titles, people and ids outside Orbit replaced, structure kept) as a test fixture. Asked for from adb:
|
||||
* am start -n tv.orbit.classic/.MainActivity --ei orbit_shadow_catalogue <pages, 0 = the whole library>
|
||||
* am start -n tv.orbit.classic/.MainActivity --ez orbit_shadow_catalogue_stop true (stop at the next page)
|
||||
* am start -n tv.orbit.classic/.MainActivity --el orbit_shadow_from <position> --ei orbit_shadow_catalogue 0 (resume)
|
||||
* It is paced (at least 1.5 s between pages, 5 s while a programme plays, never faster than the server answers), tries a
|
||||
* failed page once more after 30 s, and stops by itself if Orbit closes, playback stalls three times, memory passes 80%
|
||||
* or the server takes over 20 s a page three times running. The report is rewritten every 25 pages, so a stop keeps it.
|
||||
* The report lands in Orbit's shared folder, shadow-catalogue/, for adb to pull. Counts and ids only; no titles.
|
||||
*/
|
||||
internal object CatalogueShadow {
|
||||
@@ -33,36 +38,92 @@ internal object CatalogueShadow {
|
||||
@Volatile var pending: Int? = null
|
||||
private const val FIXTURE_PAGES = 3
|
||||
|
||||
/** Set from adb (orbit_shadow_catalogue_stop) to end a running comparison at the next page; the report so far is kept. */
|
||||
@Volatile var cancel = false
|
||||
/** Where a resumed comparison starts (orbit_shadow_from), from an earlier report's positionReached. */
|
||||
@Volatile var from = 0L
|
||||
|
||||
fun runIfPending(session: EmbySampleSession, context: Context) {
|
||||
val pages = pending ?: return
|
||||
pending = null
|
||||
val out = File(context.getExternalFilesDir(null), "shadow-catalogue").apply { deleteRecursively(); mkdirs() }
|
||||
pending = null; cancel = false
|
||||
val startAt = from.also { from = 0L }
|
||||
val out = File(context.getExternalFilesDir(null), "shadow-catalogue").apply {
|
||||
// A resumed run keeps the earlier report beside its own; a fresh one starts clean.
|
||||
if (startAt > 0) File(this, "report.json").takeIf { it.exists() }?.renameTo(File(this, "report-before-$startAt.json")) else deleteRecursively()
|
||||
mkdirs() }
|
||||
val raw = mutableListOf<String>()
|
||||
val stallsAtStart = PlaybackHealth.stalls
|
||||
val runtime = Runtime.getRuntime()
|
||||
val report = compare(
|
||||
today = { start, size, withTotal -> session.cataloguePageRecorded(start, size, withTotal) { if (raw.size < FIXTURE_PAGES) raw += it } },
|
||||
viaProvider = { start, size, withTotal -> cataloguePageVia(session.provider(), start, size, withTotal) },
|
||||
maxPages = if (pages <= 0) CATALOGUE_PAGES_FULL_RUN else pages)
|
||||
maxPages = if (pages <= 0) CATALOGUE_PAGES_FULL_RUN else pages, startAt = startAt,
|
||||
shouldStop = {
|
||||
when {
|
||||
cancel -> "cancelled"
|
||||
!InstallSnapshot.screenOpen -> "Orbit closed"
|
||||
PlaybackHealth.stalls - stallsAtStart >= MAX_STALLS -> "playback stalled $MAX_STALLS times"
|
||||
runtime.totalMemory() - runtime.freeMemory() > runtime.maxMemory() * 8 / 10 -> "memory above 80%"
|
||||
else -> null
|
||||
}
|
||||
},
|
||||
pause = { ms -> Thread.sleep(ms) },
|
||||
gapMs = { pageMs -> maxOf(if (PlaybackHealth.playing) PLAYING_GAP_MS else IDLE_GAP_MS, pageMs) },
|
||||
onProgress = { File(out, "report.json").writeText(it.toString(2)) })
|
||||
File(out, "report.json").writeText(report.toString(2))
|
||||
raw.forEachIndexed { i, body -> File(out, "page-$i.json").writeText(sanitiseCataloguePage(body).toString()) }
|
||||
android.util.Log.i("OrbitProvider", "shadow catalogue pages=${report.optInt("pages")} same=${report.optBoolean("identical")} mismatches=${report.optInt("mismatches")}")
|
||||
android.util.Log.i("OrbitProvider", "shadow catalogue pages=${report.optInt("pages")} same=${report.optBoolean("identical")} mismatches=${report.optInt("mismatches")} stopped=${report.opt("stopped")}")
|
||||
}
|
||||
|
||||
/** Pacing: at least this long between pages, and never less than the last page took, so a slow server gets more room. */
|
||||
const val IDLE_GAP_MS = 1_500L
|
||||
const val PLAYING_GAP_MS = 5_000L
|
||||
/** A page this slow, three times running, means the server is struggling: stop. */
|
||||
const val SLOW_PAGE_MS = 20_000L
|
||||
const val SLOW_PAGES = 3
|
||||
/** A failed page is tried once more after this long; a second failure stops the run. */
|
||||
const val RETRY_AFTER_MS = 30_000L
|
||||
const val MAX_STALLS = 3
|
||||
/** The report is written this often while running, so a stop at any point leaves the results so far. */
|
||||
const val PROGRESS_EVERY = 25
|
||||
|
||||
/**
|
||||
* Reads [maxPages] pages from both paths, the same way today's import does (counted first page, CATALOGUE_PAGE_SIZE rows),
|
||||
* and compares them. Pure: pass any two readers. The report holds counts, timings, memory and the first mismatching ids.
|
||||
*/
|
||||
fun compare(today: (Long, Int, Boolean) -> CataloguePage, viaProvider: (Long, Int, Boolean) -> CataloguePage, maxPages: Int,
|
||||
heapUsed: () -> Long = { Runtime.getRuntime().let { it.totalMemory() - it.freeMemory() } }): JSONObject {
|
||||
var start = 0L; var pages = 0; var mismatches = 0; var records = 0
|
||||
heapUsed: () -> Long = { Runtime.getRuntime().let { it.totalMemory() - it.freeMemory() } },
|
||||
startAt: Long = 0L,
|
||||
/** A reason to stop now (cancelled, playback stalling, memory), or null to carry on. Checked before every page. */
|
||||
shouldStop: () -> String? = { null },
|
||||
pause: (Long) -> Unit = {},
|
||||
gapMs: (pageMs: Long) -> Long = { 0L },
|
||||
onProgress: (JSONObject) -> Unit = {},
|
||||
slowPageMs: Long = SLOW_PAGE_MS): JSONObject {
|
||||
var start = startAt; var pages = 0; var mismatches = 0; var records = 0; var retries = 0; var slowRun = 0
|
||||
var todayMs = 0L; var providerMs = 0L; var peakHeap = heapUsed(); val heapBefore = peakHeap
|
||||
val firstMismatches = JSONArray(); var error: String? = null; var total: Long? = null
|
||||
val firstMismatches = JSONArray(); var error: String? = null; var total: Long? = null; var stopped: String? = null
|
||||
fun report(running: Boolean) = JSONObject().put("pages", pages).put("records", records).put("startedAt", startAt).put("positionReached", start)
|
||||
.put("total", total ?: JSONObject.NULL).put("identical", mismatches == 0 && error == null).put("mismatches", mismatches)
|
||||
.put("firstMismatches", firstMismatches).put("todayMs", todayMs).put("providerMs", providerMs).put("retries", retries)
|
||||
.put("heapBeforeKb", heapBefore / 1024).put("heapPeakKb", peakHeap / 1024).put("error", error ?: JSONObject.NULL)
|
||||
.put("stopped", stopped ?: JSONObject.NULL).put("running", running).put("wroteCatalogue", false)
|
||||
while (pages < maxPages) {
|
||||
stopped = shouldStop(); if (stopped != null) break
|
||||
val withTotal = pages == 0
|
||||
val a: CataloguePage; val b: CataloguePage
|
||||
try {
|
||||
var t = System.nanoTime(); a = today(start, CATALOGUE_PAGE_SIZE, withTotal); todayMs += (System.nanoTime() - t) / 1_000_000
|
||||
t = System.nanoTime(); b = viaProvider(start, CATALOGUE_PAGE_SIZE, withTotal); providerMs += (System.nanoTime() - t) / 1_000_000
|
||||
} catch (f: Exception) { error = "${f.javaClass.simpleName} at position $start"; break }
|
||||
var a: CataloguePage? = null; var b: CataloguePage? = null; var pageMs = 0L
|
||||
for (attempt in 0..1) {
|
||||
try {
|
||||
var t = System.nanoTime(); a = today(start, CATALOGUE_PAGE_SIZE, withTotal); val ta = (System.nanoTime() - t) / 1_000_000
|
||||
t = System.nanoTime(); b = viaProvider(start, CATALOGUE_PAGE_SIZE, withTotal); val tb = (System.nanoTime() - t) / 1_000_000
|
||||
todayMs += ta; providerMs += tb; pageMs = ta + tb
|
||||
break
|
||||
} catch (f: Exception) {
|
||||
if (attempt == 1) { error = "${f.javaClass.simpleName} at position $start"; a = null }
|
||||
else { retries++; pause(RETRY_AFTER_MS); stopped = shouldStop(); if (stopped != null) break }
|
||||
}
|
||||
}
|
||||
if (a == null || b == null) break
|
||||
peakHeap = maxOf(peakHeap, heapUsed())
|
||||
if (withTotal) total = a.total
|
||||
val same = a.rawCount == b.rawCount && a.total == b.total && a.records == b.records
|
||||
@@ -76,14 +137,22 @@ internal object CatalogueShadow {
|
||||
records += a.records.size; pages++
|
||||
start += a.rawCount
|
||||
if (a.rawCount == 0 || total?.let { start >= it } == true) break
|
||||
slowRun = if (pageMs > slowPageMs) slowRun + 1 else 0
|
||||
if (slowRun >= SLOW_PAGES) { stopped = "server slow: $SLOW_PAGES pages running over ${slowPageMs / 1000} s"; break }
|
||||
if (pages % PROGRESS_EVERY == 0) onProgress(report(running = true))
|
||||
pause(gapMs(pageMs))
|
||||
}
|
||||
return JSONObject().put("pages", pages).put("records", records).put("positionReached", start).put("total", total ?: JSONObject.NULL)
|
||||
.put("identical", mismatches == 0 && error == null).put("mismatches", mismatches).put("firstMismatches", firstMismatches)
|
||||
.put("todayMs", todayMs).put("providerMs", providerMs).put("heapBeforeKb", heapBefore / 1024).put("heapPeakKb", peakHeap / 1024)
|
||||
.put("error", error ?: JSONObject.NULL).put("wroteCatalogue", false)
|
||||
return report(running = false)
|
||||
}
|
||||
}
|
||||
|
||||
/** What the full-screen player is doing, for background work that must give way to it (9 November 2026). */
|
||||
internal object PlaybackHealth {
|
||||
@Volatile var playing = false
|
||||
/** Times playback has stalled to rebuffer after it started, since Orbit opened. */
|
||||
@Volatile var stalls = 0
|
||||
}
|
||||
|
||||
/**
|
||||
* A raw catalogue page with the personal parts replaced and its structure kept (step 3 fixtures): every row, key and type
|
||||
* stays; titles become "Title n", original titles and tags keep their shape with neutral words, external ids keep their
|
||||
|
||||
@@ -265,6 +265,8 @@ internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPl
|
||||
}
|
||||
}
|
||||
override fun onPlaybackStateChanged(state: Int) {
|
||||
if (state == Player.STATE_BUFFERING && ready) PlaybackHealth.stalls++
|
||||
PlaybackHealth.playing = state == Player.STATE_READY || state == Player.STATE_BUFFERING
|
||||
buffering = state == Player.STATE_BUFFERING
|
||||
if (state == Player.STATE_ENDED && scheduled != null) onEndedEarly?.invoke()
|
||||
if (state == Player.STATE_READY) {
|
||||
@@ -281,6 +283,7 @@ internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPl
|
||||
player.addListener(listener)
|
||||
onDispose {
|
||||
val position = player.currentPosition
|
||||
PlaybackHealth.playing = false
|
||||
lifecycle.removeObserver(observer)
|
||||
player.removeListener(listener)
|
||||
if (handedBack) return@onDispose
|
||||
|
||||
@@ -73,6 +73,8 @@ class MainActivity : ComponentActivity() {
|
||||
// Player improvements (9 November 2026): frame-rate matching and AVI, each off until switched on.
|
||||
when (intent?.getStringExtra("orbit_frame_rate")) { "on" -> PlayerSwitches.setFrameRate(this, true); "off" -> PlayerSwitches.setFrameRate(this, false) }
|
||||
when (intent?.getStringExtra("orbit_avi")) { "on" -> PlayerSwitches.setAvi(this, true); "off" -> PlayerSwitches.setAvi(this, false) }
|
||||
if (intent?.getBooleanExtra("orbit_shadow_catalogue_stop", false) == true) CatalogueShadow.cancel = true
|
||||
if (intent?.hasExtra("orbit_shadow_from") == true) CatalogueShadow.from = intent.getLongExtra("orbit_shadow_from", 0L).coerceAtLeast(0L)
|
||||
if (intent?.hasExtra("orbit_shadow_catalogue") == true) CatalogueShadow.pending = intent.getIntExtra("orbit_shadow_catalogue", 5)
|
||||
}
|
||||
override fun onNewIntent(intent: android.content.Intent) { super.onNewIntent(intent); setIntent(intent); readAdbRequests(intent) }
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/** The overnight comparison gives way and stops cleanly (9 November 2026, Paul: cancellable, rate-limited, graceful). */
|
||||
class ShadowSafetyTest {
|
||||
private val total = 2_000L
|
||||
private fun page(start: Long) = CataloguePage(emptyList(), minOf(200L, total - start).toInt(), total)
|
||||
private val reader: (Long, Int, Boolean) -> CataloguePage = { s, _, _ -> page(s) }
|
||||
|
||||
@Test fun pacesEveryPageAndNeverFasterThanTheServer() {
|
||||
val pauses = mutableListOf<Long>()
|
||||
val r = CatalogueShadow.compare(reader, reader, 100, pause = { pauses += it }, gapMs = { maxOf(1_500L, it) })
|
||||
assertEquals(10, r.getInt("pages")); assertTrue(r.getBoolean("identical")); assertFalse(r.getBoolean("running"))
|
||||
assertEquals(9, pauses.size); assertTrue(pauses.all { it >= 1_500L }) // between pages, none after the last
|
||||
}
|
||||
|
||||
@Test fun stopsWhenAskedAndKeepsWhereItGot() {
|
||||
var pages = 0
|
||||
val r = CatalogueShadow.compare({ s, n, w -> pages++; reader(s, n, w) }, reader, 100, shouldStop = { if (pages >= 4) "cancelled" else null })
|
||||
assertEquals("cancelled", r.getString("stopped")); assertEquals(4, r.getInt("pages")); assertEquals(800L, r.getLong("positionReached"))
|
||||
}
|
||||
|
||||
@Test fun resumesFromAPosition() {
|
||||
val r = CatalogueShadow.compare(reader, reader, 100, startAt = 1_200L)
|
||||
assertEquals(4, r.getInt("pages")); assertEquals(1_200L, r.getLong("startedAt")); assertEquals(2_000L, r.getLong("positionReached"))
|
||||
}
|
||||
|
||||
@Test fun triesAFailedPageOnceMoreAfterAWait() {
|
||||
var calls = 0; val pauses = mutableListOf<Long>()
|
||||
val flaky: (Long, Int, Boolean) -> CataloguePage = { s, n, w -> calls++; if (calls == 3) throw java.io.IOException("blip") else reader(s, n, w) }
|
||||
val r = CatalogueShadow.compare(reader, flaky, 100, pause = { pauses += it })
|
||||
assertEquals(1, r.getInt("retries")); assertTrue(r.isNull("error")); assertEquals(10, r.getInt("pages"))
|
||||
assertTrue(CatalogueShadow.RETRY_AFTER_MS in pauses)
|
||||
}
|
||||
|
||||
@Test fun twoFailuresInARowStopWithTheError() {
|
||||
val r = CatalogueShadow.compare(reader, { s, n, w -> if (s >= 400) throw java.io.IOException("down") else reader(s, n, w) }, 100)
|
||||
assertEquals("IOException at position 400", r.getString("error")); assertEquals(2, r.getInt("pages")); assertFalse(r.getBoolean("identical"))
|
||||
}
|
||||
|
||||
@Test fun stopsWhenTheServerStruggles() {
|
||||
val slow: (Long, Int, Boolean) -> CataloguePage = { s, n, w -> if (s >= 600) Thread.sleep(30); reader(s, n, w) }
|
||||
val r = CatalogueShadow.compare(reader, slow, 100, slowPageMs = 20) // 20 ms stands in for the real 20 s
|
||||
assertTrue(r.getString("stopped").startsWith("server slow")); assertEquals(6, r.getInt("pages")); assertEquals(1_200L, r.getLong("positionReached"))
|
||||
val oneSlowPage = CatalogueShadow.compare(reader, { s, n, w -> if (s == 600L) Thread.sleep(30); reader(s, n, w) }, 100, slowPageMs = 20)
|
||||
assertTrue(oneSlowPage.isNull("stopped")); assertEquals(10, oneSlowPage.getInt("pages"))
|
||||
}
|
||||
|
||||
@Test fun writesProgressAsItGoes() {
|
||||
val progress = mutableListOf<Int>()
|
||||
CatalogueShadow.compare({ s, _, _ -> CataloguePage(emptyList(), 10, 1_000) }, { s, _, _ -> CataloguePage(emptyList(), 10, 1_000) }, 100,
|
||||
onProgress = { assertTrue(it.getBoolean("running")); progress += it.getInt("pages") })
|
||||
assertEquals(listOf(25, 50, 75), progress)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user