0.99.12: one failed show in a pool refresh keeps its previous copy instead of losing the whole refresh; retry in 6 hours
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 2m7s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m43s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-04 12:50:58 +00:00
co-authored by Claude Opus 5.5
parent 3903d73304
commit e552871589
8 changed files with 123 additions and 12 deletions
+2 -2
View File
@@ -9,8 +9,8 @@ android {
applicationId = "tv.orbit.classic"
minSdk = 26
targetSdk = 36
versionCode = 141
versionName = "0.99.11-planning-speed"
versionCode = 142
versionName = "0.99.12-safe-pool-refresh"
}
buildFeatures { compose = true }
compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }
@@ -332,6 +332,30 @@ internal fun turnOrder(pool: List<PoolSeries>, last: String?): List<PoolSeries>
return (0 until pool.size).map { pool[(after + it) % pool.size] }
}
/** How many shows' reads may fail in one refresh, each keeping its previous copy, before the refresh is abandoned as an outage. */
internal const val MAX_FAILED_READS = 3
/** A refresh that kept some previous copies is tried again after this long, rather than waiting a week. */
internal const val PARTIAL_POOL_RETRY_MS = 6 * 60 * 60_000L
/**
* A pool refresh where one show's read fails (a timeout, say): that show keeps its copy from the previous pool and the
* rest of the refresh stands. A show with no previous copy, a failure that isn't worth retrying, or more than
* [MAX_FAILED_READS] failures (the provider is down) abandons the refresh, so the whole previous pool is kept as before.
* Nothing is ever dropped from a pool because a read failed.
*/
internal class PartialRead(private val previous: List<PoolSeries>?, private val limit: Int = MAX_FAILED_READS) {
var carried = 0
private set
private var failures = 0
fun carry(key: String, failure: EmbyCheckException): PoolSeries {
failures++
if (!failure.retryable || failures > limit) throw failure
val kept = previous?.firstOrNull { seriesKey(it.title) == key || seriesKey(FilmIdentity.of(it.title).title) == key } ?: throw failure
carried++
return kept
}
}
/** A pool without the items taken off a channel by editorial decision ([ChannelProgramming.withdrawn]). */
internal fun withoutWithdrawn(pool: List<PoolSeries>, withdrawn: Set<String>): List<PoolSeries> =
if (withdrawn.isEmpty()) pool else pool.filter { show -> show.id !in withdrawn && show.episodes.none { it.id in withdrawn } }
@@ -102,11 +102,14 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl
if (cached == null || now - cached.fetchedAtMs >= POOL_REFRESH_MS || cached.signature != signature) {
val started = android.os.SystemClock.elapsedRealtime()
try {
val read = session.readChannelPool(programming, loop, choices, checkActive)
val read = session.readChannelPool(programming, loop, choices, checkActive, previous = cached?.series)
requests = read.requests
fetchMs = android.os.SystemClock.elapsedRealtime() - started
if (read.series.isNotEmpty()) {
pool = ScheduleStore.SavedPool(read.series, now, signature)
// A refresh that had to keep a few previous copies is tried again in a few hours rather than a week.
val fetched = if (read.carried > 0) now - POOL_REFRESH_MS + PARTIAL_POOL_RETRY_MS else now
if (read.carried > 0) Log.w("OrbitSchedule", "channel=$number poolRefreshPartial carried=${read.carried}")
pool = ScheduleStore.SavedPool(read.series, fetched, signature)
store.savePool(userId, number, pool)
}
} catch (failure: EmbyCheckException) {
@@ -66,7 +66,7 @@ internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUI
connection.connectTimeout = 10_000
connection.readTimeout = request.readTimeoutMs ?: if (request.path == "/Sessions/Logout") 5_000 else 15_000
connection.setRequestProperty("Accept", "application/json")
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.99.11\"")
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.99.12\"")
request.token?.let { connection.setRequestProperty("X-Emby-Token", it) }
if (request.method == "POST") {
val bytes = request.body.orEmpty().toByteArray(Charsets.UTF_8)
@@ -210,11 +210,16 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
}
}
internal class PoolRead(val series: List<PoolSeries>, val requests: Int)
internal class PoolRead(val series: List<PoolSeries>, val requests: Int,
/** Shows whose read failed this time and kept their copy from the previous pool instead. */
val carried: Int = 0)
/** The first shows in the channel's list that have episodes to schedule. */
fun readChannelPool(programming: ChannelProgramming, loop: SampleChannel?, choices: ChannelChoices = ChannelChoices(), checkActive: () -> Unit = {}): PoolRead {
fun readChannelPool(programming: ChannelProgramming, loop: SampleChannel?, choices: ChannelChoices = ChannelChoices(), checkActive: () -> Unit = {},
/** The pool being refreshed, so one show whose read fails can keep its copy rather than losing the whole refresh. */
previous: List<PoolSeries>? = null): PoolRead {
var requests = 0
val pool = mutableListOf<PoolSeries>()
val partial = PartialRead(previous)
if (programming.filmRestMs != null) {
// Films already in this channel's old line-up stay in it, unless the list now names another film of that title.
val listed = programming.searches.map { seriesKey(FilmIdentity.of(it).title) }.toSet()
@@ -226,7 +231,12 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
if (found >= programming.seriesCount) break
checkActive()
requests++
val lookup = findFilm(transport, userId, ::currentToken, entry, BoxDecoders::canDecode)
val lookup = try { findFilm(transport, userId, ::currentToken, entry, BoxDecoders::canDecode) } catch (failure: EmbyCheckException) {
android.util.Log.w("OrbitSchedule", "channel=${programming.number} film failed=${failure.javaClass.simpleName} status=${failure.httpStatus}")
val kept = partial.carry(seriesKey(FilmIdentity.of(entry).title), failure)
if (pool.none { it.id == kept.id }) { pool += kept; found++ }
continue
}
if (lookup.note.isNotEmpty()) android.util.Log.i("OrbitSchedule", "channel=${programming.number} ${lookup.note}")
val film = lookup.film ?: continue
if (pool.none { it.id == film.id }) { pool += film; found++ }
@@ -249,7 +259,11 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
fun <T> traced(step: String, block: () -> T): T = try { block() } catch (failure: Exception) {
android.util.Log.w("OrbitSchedule", "channel=${programming.number} listed=${index + 1} $step failed=${failure.javaClass.simpleName}"); throw failure
}
val candidates = traced("search") { searchSeries(transport, userId, ::currentToken, search).candidates }
val candidates = try { traced("search") { searchSeries(transport, userId, ::currentToken, search).candidates } } catch (failure: EmbyCheckException) {
val kept = partial.carry(seriesKey(search), failure)
if (pool.none { it.id == kept.id }) pool += kept
continue
}
val exact = candidates.count { seriesKey(it.title) == seriesKey(search) }
val match = bestSeriesMatch(search, if (programming.exactTitles) candidates.filter { seriesKey(it.title) == seriesKey(search) } else candidates)
// Counts only, never titles: which list entry found nothing, and at which step, so a missing show can be traced.
@@ -259,7 +273,12 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
// A library can hold several copies of one show, one with a single episode and another with the whole run.
// The copy with the most episodes this box can play is the one the channel uses.
val copies = (listOf(match) + candidates.filter { it.id != match.id && seriesKey(it.title) == seriesKey(match.title) }.sortedBy { it.year ?: Int.MAX_VALUE }).take(MAX_SERIES_COPIES)
val read = traced("read") { copies.map { copy -> readWholeSeries(transport, userId, ::currentToken, copy, checkActive, onRequest = { requests++ }, canDecode = BoxDecoders::canDecode, englishAudio = programming.englishAudio) } }
val read = try { traced("read") { copies.map { copy -> readWholeSeries(transport, userId, ::currentToken, copy, checkActive, onRequest = { requests++ }, canDecode = BoxDecoders::canDecode, englishAudio = programming.englishAudio) } } }
catch (failure: EmbyCheckException) {
val kept = partial.carry(seriesKey(match.title), failure)
if (pool.none { it.id == kept.id }) pool += kept
continue
}
val best = read.maxByOrNull { it.episodes.size }?.takeIf { it.episodes.isNotEmpty() }
if (best == null) { android.util.Log.i("OrbitSchedule", "channel=${programming.number} listed=${index + 1} matched copies=${copies.size} playableEpisodes=0"); continue }
if (copies.size > 1) android.util.Log.i("OrbitSchedule", "channel=${programming.number} copies=${copies.size} usedCopy=${read.indexOf(best) + 1} episodes=${read.map { it.episodes.size }}")
@@ -287,7 +306,7 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
}
}
// An editorial withdrawal takes that exact item out, however it arrived: list, old line-up or accepted suggestion.
return PoolRead(withoutWithdrawn(pool, programming.withdrawn), requests)
return PoolRead(withoutWithdrawn(pool, programming.withdrawn), requests, partial.carried)
}
fun suggestFor(rules: List<SuggestionRule>, alreadyInPool: Set<String>, rejected: Set<String>, takenTitles: Set<String> = emptySet(), checkActive: () -> Unit = {}) =
findSuggestions(transport, userId, ::currentToken, rules, alreadyInPool, rejected, checkActive, BoxDecoders::canDecode, takenTitles, englishAudio = true)
@@ -33,7 +33,7 @@ internal class SecureMediaDataSource(private val session: EmbySampleSession) : B
next.instanceFollowRedirects = false
next.connectTimeout = 10_000
next.readTimeout = 20_000
next.setRequestProperty("User-Agent", "OrbitTV/0.99.11")
next.setRequestProperty("User-Agent", "OrbitTV/0.99.12")
next.setRequestProperty("Accept-Encoding", "identity")
session.mediaHeaders(address).forEach { (key, value) -> next.setRequestProperty(key, value) }
if (dataSpec.position != 0L || dataSpec.length != C.LENGTH_UNSET.toLong()) {
@@ -0,0 +1,32 @@
package tv.orbit.classic
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertThrows
import org.junit.Test
/** One show's failed read keeps its previous copy; nothing is ever dropped, and an outage still keeps the whole old pool. */
class PartialPoolReadTest {
private fun show(title: String) = PoolSeries(title, title, listOf(PoolEpisode("$title-1", "s", EpisodeMark(1, 1), "E1", 1_800_000)))
private val previous = listOf(show("X-Men: The Animated Series"), show("Batman Beyond"), show("Halloween"))
private val timeout = EmbyCheckException("timed out", retryable = true)
@Test fun aFailedShowKeepsItsPreviousCopy() {
val read = PartialRead(previous)
assertSame(previous[0], read.carry(seriesKey("X-Men: The Animated Series"), timeout))
// A film named with its year finds its plain-titled copy.
assertSame(previous[2], read.carry(seriesKey(FilmIdentity.of("Halloween (1978)").title), timeout))
assertEquals(2, read.carried)
}
@Test fun nothingIsDroppedAndAnOutageAbandonsTheRefresh() {
// No previous copy: the refresh is abandoned rather than lose the show.
assertThrows(EmbyCheckException::class.java) { PartialRead(previous).carry(seriesKey("Static Shock"), timeout) }
// A failure not worth retrying: abandoned.
assertThrows(EmbyCheckException::class.java) { PartialRead(previous).carry(seriesKey("Batman Beyond"), EmbyCheckException("refused", 401)) }
// More than three failures in one refresh means the provider is down: abandoned, so the whole old pool stays.
val read = PartialRead(previous + (1..3).map { show("Show $it") })
(1..3).forEach { read.carry(seriesKey("Show $it"), timeout) }
assertThrows(EmbyCheckException::class.java) { read.carry(seriesKey("Batman Beyond"), timeout) }
}
}
+33
View File
@@ -0,0 +1,33 @@
# Orbit TV 0.99.12: a failed show no longer costs a whole pool refresh
This answers Paul's item 6 of 4 November 2026 at 12:37: whether a single failed series read can be handled safely without throwing away an otherwise valid refreshed pool. It changes how pools are read, not how programmes are scheduled. It includes 0.99.11.
## The problem
Under 0.99.10, Heroes' refresh failed twice at its 6th list entry, X-Men: The Animated Series, after about 18 seconds with no HTTP status. That's a transient timeout: the third attempt at 12:31 succeeded. Vortex, Terra and Riot had failed the same way once. One failed read abandoned the whole refresh, so every other show's fresh read was thrown away and the channel kept its old pool.
## What's in it
**`PartialRead` and `readChannelPool(previous = …)`.** When one listed show's search or episode read fails with a retryable error such as a timeout, that show keeps its copy from the previous pool and the rest of the refresh stands. Film channels work the same way, film by film.
**Safeguards (nothing is ever dropped because a read failed):**
- A show with no previous copy abandons the refresh, and the whole previous pool is kept, exactly as before.
- So does a failure that isn't worth retrying, such as an authorisation error.
- More than 3 failures in one refresh is treated as a provider outage and also abandons it.
**Retry.** A refresh that kept previous copies is saved as due again in 6 hours rather than a week, so the failed shows are retried soon.
**Logging.** The log notes `poolRefreshPartial carried=N`. Each failure is already logged by list position, step and kind.
## Checks before install
- **426 unit tests pass**, including the hand-run replays. Lint has no errors.
- **New PartialPoolReadTest:**
- A failed show keeps its previous copy (series, or a film named with its year).
- Nothing is dropped when no previous copy exists, or when the failure isn't retryable.
- More than three failures abandons the refresh.
- **Scheduling is unchanged:** a four-week replay of all 30 channels on box copies taken after 0.99.11 was installed gives the same fingerprints as the scheduling code before this change.
## Rollback
Install 0.99.11. Pools saved with an earlier retry time are simply read again, as 0.99.11 would anyway.