From bce2b99147610206eac507d4f9addac3895db1de Mon Sep 17 00:00:00 2001 From: Pauljd Date: Thu, 26 Nov 2026 15:44:01 +0000 Subject: [PATCH] Channel lists refresh entry by entry, resumably, with a fair share of the hour A changed list reads only what its saved pool lacks and drops what the list no longer names; a failed read keeps the old copy. Progress is saved after every entry and resumed across rounds and restarts. Each refreshing channel gets an equal share of the hour's budget, a tenth kept for the rest of the round; the weekly re-read waits while changes are catching up. Settings shows how the lists stand. Tests and a two-TV simulation from the 26 November snapshot. Co-Authored-By: Claude Opus 5.5 --- .../java/tv/orbit/classic/ChannelScheduler.kt | 110 ++++++++- .../tv/orbit/classic/EmbyConnectionScreen.kt | 2 + .../tv/orbit/classic/EmbyPlaybackProtocol.kt | 2 +- .../main/java/tv/orbit/classic/PoolRefresh.kt | 223 ++++++++++++++++++ .../java/tv/orbit/classic/ScheduleStore.kt | 45 +++- .../main/java/tv/orbit/classic/Settings.kt | 3 + .../java/tv/orbit/classic/PoolRefreshTest.kt | 175 ++++++++++++++ .../tv/orbit/classic/RefreshSimulationTest.kt | 168 +++++++++++++ docs/roadmap.md | 13 + 9 files changed, 722 insertions(+), 19 deletions(-) create mode 100644 android/app/src/main/java/tv/orbit/classic/PoolRefresh.kt create mode 100644 android/app/src/test/java/tv/orbit/classic/PoolRefreshTest.kt create mode 100644 android/app/src/test/java/tv/orbit/classic/RefreshSimulationTest.kt diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt index a81b872f..6d25e87c 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -351,6 +351,94 @@ internal class ChannelScheduler(private val store: ScheduleStore, Unplayable.take(itemId)?.let { (title, channel, reason) -> runCatching { store.unplayable().add(itemId, title, channel, reason, clock()) } } } + /** Channels with a list refresh to do this round, not yet served: how a channel's share of the hour is worked out. */ + private val refreshWaiting = HashSet() + @Volatile private var changesWaiting = false + + /** + * At the start of the background round: which channels have a list refresh to do, so each gets an equal share of the + * hour's budget rather than the first in the order taking it all ([refreshShare]). + */ + fun beginRound(userId: String, programmings: List) { + val waiting = programmings.filter { p -> + runCatching { enabled(userId, p.number) && (store.loadRefresh(userId, p.number) != null || + store.loadPool(userId, p.number)?.let { it.signature != "${p.signature}#${store.loadChoices(userId, p.number).tag}" } == true) }.getOrDefault(false) + }.map { it.number } + synchronized(refreshWaiting) { refreshWaiting.clear(); refreshWaiting += waiting } + // A routine weekly re-read waits while any list has a change to catch up on, so edits reach the screen first. + changesWaiting = waiting.isNotEmpty() + if (waiting.isNotEmpty()) Log.i("OrbitSchedule", "refreshRound waiting=${waiting.size} budget=${BackgroundPacing.budget} used=${BackgroundPacing.usedThisHour()}") + } + + /** One entry of a list, read on its own by the same code a whole read uses. */ + private fun readEntry(session: EmbySampleSession, programming: ChannelProgramming, choices: ChannelChoices, entry: RefreshEntry, checkActive: () -> Unit): Pair { + val films = programming.filmRestMs != null + val one = when (entry.kind) { + RefreshEntry.Kind.FILM -> if (films) programming.copy(searches = listOf(entry.text), filmSeries = emptyList(), channelFilms = emptyList(), seriesCount = 1) + else programming.copy(searches = emptyList(), filmSeries = emptyList(), channelFilms = listOf(entry.text)) + RefreshEntry.Kind.SERIES -> if (films) programming.copy(searches = emptyList(), filmSeries = listOf(entry.text), channelFilms = emptyList()) + else programming.copy(searches = listOf(entry.text), filmSeries = emptyList(), channelFilms = emptyList(), seriesCount = 1) + RefreshEntry.Kind.CHOSEN -> programming.copy(searches = emptyList(), filmSeries = emptyList(), channelFilms = emptyList()) + } + val picked = if (entry.kind == RefreshEntry.Kind.CHOSEN) ChannelChoices(choices.accepted.filter { it.id == entry.text }, choices.rejected) else ChannelChoices() + val read = session.readChannelPool(one, null, picked, checkActive) + return read to read.requests + } + + /** + * A list refresh in the background round ([PoolRefresh]): reads this channel's share of the entries it still needs, saves + * how far it got, and serves the pool as it now stands. Returns that pool and the requests it took. + */ + private fun refreshStepwise(session: EmbySampleSession, userId: String, programming: ChannelProgramming, loop: SampleChannel, choices: ChannelChoices, + cached: ScheduleStore.SavedPool, signature: String, resuming: RefreshProgress?, now: Long, checkActive: () -> Unit): Pair { + val number = programming.number + // A list that changed reads only what its pool lacks; the routine weekly refresh reads everything again. + val full = resuming?.full ?: (cached.signature == signature) + if (resuming == null && full) lastRoutineRefreshMs = now + val start = resuming ?: RefreshProgress(signature, full, now) + val refresh = PoolRefresh(programming, choices, cached.series, earlierFilms(loop)) + val waiting = synchronized(refreshWaiting) { refreshWaiting.size + if (number in refreshWaiting) 0 else 1 } + val share = refreshShare(BackgroundPacing.budget, BackgroundPacing.usedThisHour(), waiting) + val step = try { + refresh.step(start, share, now, pacedOut = { refreshPacedOut(BackgroundPacing.budget, BackgroundPacing.usedThisHour()) }, + read = { entry -> checkActive(); readEntry(session, programming, choices, entry, checkActive) }, + save = { store.saveRefresh(userId, number, it) }) + } catch (failure: EmbyCheckException) { + Log.w("OrbitSchedule", "channel=$number poolReadFailed status=${failure.httpStatus} retryable=${failure.retryable} keptCache=true") + return cached to 0 + } finally { synchronized(refreshWaiting) { refreshWaiting -= number } } + val dropped = refresh.dropped.size + if (step.pool.isEmpty()) { + // Nothing at all: never an empty channel. The saved pool stays, and the refresh starts again later. + Log.w("OrbitSchedule", "channel=$number poolRefreshEmpty stop=${step.stop} keptCache=true") + if (step.finished) { store.deleteRefresh(number); routineQueue.failed(number, now) } + return cached to step.spent + } + val result = if (step.finished) { + // Every entry read: the pool takes the list's signature. One that had to keep an old copy is tried again in a few hours. + val carried = step.progress.carried.size + val fetched = if (carried > 0) now - POOL_REFRESH_MS + PARTIAL_POOL_RETRY_MS else now + val signed = keepRefound(userId, programming, EmbySampleSession.PoolRead(step.pool, step.progress.requests, carried, step.progress.refound)) + ScheduleStore.SavedPool(step.pool, fetched, signed).also { + store.savePool(userId, number, it); store.deleteRefresh(number); routineQueue.note(number, fetched, now) + Log.i("OrbitSchedule", "channel=$number poolRefreshDone full=$full entries=${refresh.entries.size} read=${step.progress.done.size} carried=$carried dropped=$dropped requests=${step.progress.requests} rounds=${step.progress.rounds}") + } + } else { + // Part-way: the pool on air takes what's been read so far, and keeps its old signature and time until it's done. + Log.i("OrbitSchedule", "channel=$number poolRefreshPartial stop=${step.stop} full=$full read=${step.read} pending=${step.pending} share=$share spent=${step.spent} dropped=$dropped rounds=${step.progress.rounds}") + ScheduleStore.SavedPool(step.pool, cached.fetchedAtMs, cached.signature).also { + if (it.series.map { s -> s.id to s.episodes.size } != cached.series.map { s -> s.id to s.episodes.size }) store.savePool(userId, number, it) + } + } + // Stage C, report only: episodes a show here didn't have before this step. Never touches the plan. + runCatching { + val found = newEpisodes(number, cached.series, result.series, now) + if (found.isNotEmpty()) { store.saveNewEpisodes(userId, mergeNewEpisodes(store.loadNewEpisodes(userId), found, now)); Log.i("OrbitSchedule", "channel=$number newEpisodes=${found.size}") } + } + RefreshStatus.note(number, result.fetchedAtMs, if (step.finished) 0 else step.pending, if (step.finished) null else step.progress.startedMs) + return result to step.spent + } + /** * Approvals found again under a new ID keep it, so the next read asks for them directly (18 November 2026), whichever * read found them (22 November 2026: a channel's first read didn't keep them). Returns the pool's signature to save. @@ -412,13 +500,20 @@ internal class ChannelScheduler(private val store: ScheduleStore, !IdRepairs.coolingDown(a.type, a.ref, now) } // The routine refresh goes to the most overdue list, not the first in the round's order ([RoutineQueue]). if (cached != null) routineQueue.note(number, cached.fetchedAtMs, now) - val routineDue = cached != null && poolRefreshDue(cached.fetchedAtMs, number, now) && now - lastRoutineRefreshMs >= POOL_ROUTINE_GAP_MS && + val routineDue = cached != null && poolRefreshDue(cached.fetchedAtMs, number, now) && now - lastRoutineRefreshMs >= POOL_ROUTINE_GAP_MS && !changesWaiting && routineQueue.isNext(number, now) - val due = cached == null || cached.signature != signature || waiting || routineDue - if (due) { - // Due only for approvals still waiting: those alone are read, and the rest of the pool stays as it is. A read like - // that is small, so it doesn't use up the routine slot. - val onlyWaiting = waiting && cached != null && cached.signature == signature && !routineDue + // A refresh part-way through for this list carries on; one for an older list is set aside ([PoolRefresh]). + val saved = if (cached != null) store.loadRefresh(userId, number) else null + if (saved != null && saved.target != signature) { store.deleteRefresh(number); Log.i("OrbitSchedule", "channel=$number poolRefreshSuperseded rounds=${saved.rounds} read=${saved.done.size}") } + val resuming = saved?.takeIf { it.target == signature } + val due = cached == null || cached.signature != signature || waiting || routineDue || resuming != null + // Due only for approvals still waiting: those alone are read, and the rest of the pool stays as it is. A read like + // that is small, so it doesn't use up the routine slot. + val onlyWaiting = waiting && cached != null && cached.signature == signature && !routineDue && resuming == null + if (due && cached != null && !onlyWaiting && BackgroundPacing.active) { + // In the background round, a list already on the box is refreshed entry by entry, a fair share at a time. + pool = refreshStepwise(session, userId, programming, loop, choices, cached, signature, resuming, now, checkActive).also { requests = it.second }.first + } else if (due) { if (routine && !onlyWaiting) lastRoutineRefreshMs = now val started = android.os.SystemClock.elapsedRealtime() try { @@ -434,6 +529,8 @@ internal class ChannelScheduler(private val store: ScheduleStore, val signed = keepRefound(userId, programming, read) pool = ScheduleStore.SavedPool(read.series, fetched, signed) store.savePool(userId, number, pool) + // A whole read supersedes any refresh part-way through. + if (!onlyWaiting) store.deleteRefresh(number) routineQueue.note(number, fetched, now) // Stage C, report only: episodes a show here didn't have at the previous read. Never touches the plan. if (cached != null) runCatching { @@ -451,6 +548,7 @@ internal class ChannelScheduler(private val store: ScheduleStore, throw other } } + if (!(due && cached != null && !onlyWaiting && BackgroundPacing.active)) pool?.let { RefreshStatus.note(number, it.fetchedAtMs, 0, null) } val started = android.os.SystemClock.elapsedRealtime() val progress = store.loadProgress(userId, number) val base = progress?.aired ?: ScheduleCursor() diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt index 657e6009..aa4deaa5 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt @@ -439,6 +439,8 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea // Shared by every TV in the house on this server (1.0 RC3): the rooms this TV is linked to or set up. BackgroundPacing.tvs = 1 + (RoomLinks.links.map { it.room } + Rooms.joined.map { it.first }).distinct().size BackgroundPacing.budget = BackgroundPacing.share(if (quiet) QUIET_START_BUDGET else BackgroundPacing.HOURLY_BUDGET) + // Which lists have a refresh to do, so each gets a fair share of the hour (26 November 2026: 22 lists starved). + withContext(Dispatchers.IO) { runCatching { scheduler.beginRound(active.accountId, SmartChannels) } } for (programming in SmartChannels) { val loop = smartLoop(programming) ?: run { // A channel of your own that is switched on but whose first plan never finished (an update arrived mid-read, diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt index c6236ccc..05bde34d 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt @@ -394,7 +394,7 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v 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() - val earlier = loop?.lineup.orEmpty().filter { it.item.type == "Movie" }.map { PoolSeries(it.item.id, it.item.title, listOf(PoolEpisode(it.item.id, it.sourceId, EpisodeMark(1, 1), it.item.title, it.durationMs)), ref = it.item.ref, year = it.item.year) } + val earlier = earlierFilms(loop) pool += earlier.filter { seriesKey(it.title) !in listed } // The limit counts films found from the list, so films carried over from the old line-up can't crowd the list out. var found = 0 diff --git a/android/app/src/main/java/tv/orbit/classic/PoolRefresh.kt b/android/app/src/main/java/tv/orbit/classic/PoolRefresh.kt new file mode 100644 index 00000000..cac9d89d --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/PoolRefresh.kt @@ -0,0 +1,223 @@ +package tv.orbit.classic + +/* + * Reading a channel's list a little at a time (Paul, 26 November 2026: a 1.0 reliability priority). + * + * Before this, a changed list was read again from the top in one go. The hourly round goes through the channels in a fixed + * order on a shared budget (200 an hour, 100 each with two TVs), so the first changed list spent it, every channel after it + * was paced out after a few titles, gave up and kept its old list, and the next round started the same read from the top + * again. On 26 November 22 of the 42 lists had been stuck like that for days (Chicken Run still on Wonder). + * + * Now a refresh is a list of entries, each read on its own: + * - a changed list reads only the entries its saved pool doesn't already hold; titles no longer on the list are dropped, + * because that is an editorial decision. A server failure never drops anything: the entry keeps its old copy; + * - what has been read is saved after every entry, with the list it was reading for, so a refresh carries on across + * rounds and restarts rather than starting again; + * - each channel gets a fair share of what's left of the hour's budget, so no channel can starve the rest; + * - the pool on air takes each entry as it is read, and the refresh only finishes once every entry is done. + * The routine weekly re-read works the same way, entry by entry, over as many rounds as it needs. + */ + +/** A film channel's films from its old line-up, as pool entries: they stay unless the list now names another film of that title. */ +internal fun earlierFilms(loop: SampleChannel?): List = loop?.lineup.orEmpty().filter { it.item.type == "Movie" } + .map { PoolSeries(it.item.id, it.item.title, listOf(PoolEpisode(it.item.id, it.sourceId, EpisodeMark(1, 1), it.item.title, it.durationMs)), ref = it.item.ref, year = it.item.year) } + +/** One thing a channel's list asks for: a film, a series, or a title chosen from the Director's Chair. */ +internal data class RefreshEntry(val kind: Kind, val text: String, val group: Int) { + enum class Kind { FILM, SERIES, CHOSEN } + /** How progress names it: stable across rounds and restarts. */ + val id get() = "${kind.name.lowercase()}:$text" +} + +/** A list's groups, in pool order, and how many found titles each may hold (null: all of them). */ +internal class RefreshGroup(val kind: RefreshEntry.Kind, val limit: Int?) + +internal fun refreshGroups(programming: ChannelProgramming): List = + if (programming.filmRestMs != null) listOf(RefreshGroup(RefreshEntry.Kind.FILM, programming.seriesCount), RefreshGroup(RefreshEntry.Kind.SERIES, null), RefreshGroup(RefreshEntry.Kind.CHOSEN, null)) + else listOf(RefreshGroup(RefreshEntry.Kind.SERIES, programming.seriesCount), RefreshGroup(RefreshEntry.Kind.FILM, null), RefreshGroup(RefreshEntry.Kind.CHOSEN, null)) + +/** Every entry of a list, in the order a whole read takes them. */ +internal fun refreshEntries(programming: ChannelProgramming, choices: ChannelChoices): List { + val (first, second) = if (programming.filmRestMs != null) programming.searches to programming.filmSeries else programming.searches to programming.channelFilms + val groups = refreshGroups(programming) + return first.distinct().map { RefreshEntry(groups[0].kind, it, 0) } + second.distinct().map { RefreshEntry(groups[1].kind, it, 1) } + + choices.accepted.distinctBy { it.id }.map { RefreshEntry(RefreshEntry.Kind.CHOSEN, it.id, 2) } +} + +/** + * The saved pool's copy of each entry, where it has one: a film by its IMDb ID where both know it, else by its name and year; + * a series by its name (or the name with something after it, as a whole read matches it); a chosen title by its item or name. + */ +internal fun cachedCopies(entries: List, cached: List, choices: ChannelChoices): Map { + val out = HashMap() + val used = HashSet() + val accepted = choices.accepted.associateBy { it.id } + fun filmMatches(entry: String, item: PoolSeries): Boolean { + val identity = FilmIdentity.of(entry) + val imdb = identity.imdb?.lowercase() + val ref = item.ref.lowercase().removePrefix("imdb.").takeIf { item.ref.lowercase().startsWith("imdb.") } + if (imdb != null && ref != null) return imdb == ref + if (seriesKey(item.title) != seriesKey(identity.title)) return false + return identity.year == null || item.year == null || kotlin.math.abs(item.year - identity.year) <= 1 + } + // Exact matches first, so a looser one can't take a show another entry names exactly. + for (pass in 0..1) for (entry in entries) { + if (entry.id in out) continue + val item = cached.firstOrNull { it.id !in used && when (entry.kind) { + RefreshEntry.Kind.FILM -> filmMatches(entry.text, it) + RefreshEntry.Kind.SERIES -> if (pass == 0) seriesKey(it.title) == seriesKey(entry.text) else seriesKey(it.title).startsWith(seriesKey(entry.text) + " ") + RefreshEntry.Kind.CHOSEN -> accepted[entry.text]?.let { a -> it.id == a.id || (pass == 1 && seriesKey(it.title) == seriesKey(a.title)) } == true + } } ?: continue + out[entry.id] = item; used += item.id + } + return out +} + +/** + * How far a refresh has got, saved after every entry. [target] is the list (and choices) it is reading for: a refresh for an + * older list is never resumed. [done] holds what each entry read found (empty: the server answered and has nothing for it). + */ +internal class RefreshProgress(val target: String, val full: Boolean, val startedMs: Long, + val done: Map> = emptyMap(), + /** Entries whose read failed and kept their old copy: the finished refresh is tried again in a few hours, not a week. */ + val carried: Set = emptySet(), + /** Chosen titles found again under a new item, old to new. */ + val refound: Map = emptyMap(), + val requests: Int = 0, val rounds: Int = 0, val lastMs: Long = startedMs) + +/** Why a refresh step stopped. */ +internal enum class RefreshStop { FINISHED, SHARE, PACED, FAILING } + +internal class RefreshStep(val progress: RefreshProgress, val pool: List, val stop: RefreshStop, val spent: Int, val read: Int, val pending: Int) { + val finished get() = stop == RefreshStop.FINISHED +} + +/** A channel's share of what's left of the hour: shared equally by the channels still refreshing, never less than [REFRESH_MIN_SHARE]. */ +internal const val REFRESH_MIN_SHARE = 8 +/** The part of each hour's budget list refreshes leave for the rest of the round: the Drive-In, the evidence and the catalogue. */ +internal fun refreshReserve(budget: Int) = budget / 10 +/** Whether list refreshes have used what they may of the hour. */ +internal fun refreshPacedOut(budget: Int, used: Int) = used >= budget - refreshReserve(budget) +internal fun refreshShare(budget: Int, used: Int, waiting: Int): Int = maxOf(REFRESH_MIN_SHARE, (budget - refreshReserve(budget) - used) / waiting.coerceAtLeast(1)) + +/** + * One channel's refresh, from its saved pool and its progress. Pure apart from [read], which reads one entry from the + * server, so the planning can be tested and simulated without one. + */ +internal class PoolRefresh(private val programming: ChannelProgramming, private val choices: ChannelChoices, + private val cached: List, + /** A film channel's films carried over from its old line-up ([EmbySampleSession.readChannelPool]): they need no reading. */ + private val earlier: List = emptyList()) { + val entries = refreshEntries(programming, choices) + private val groups = refreshGroups(programming) + val copies = cachedCopies(entries, cached, choices) + /** Saved titles no list entry names any more: taken off the channel. */ + val dropped: List get() { val kept = copies.values.mapTo(HashSet()) { it.id } + earlier.map { it.id }; return cached.filter { it.id !in kept } } + + /** Whether [entry] still needs reading: a full refresh reads everything; a changed list only what the saved pool lacks. */ + private fun needs(entry: RefreshEntry, progress: RefreshProgress) = entry.id !in progress.done && (progress.full || entry.id !in copies) + + /** What an entry gives the pool now: what its read found, else its saved copy while it waits. */ + private fun itemsFor(entry: RefreshEntry, progress: RefreshProgress): List = progress.done[entry.id] ?: listOfNotNull(copies[entry.id]) + + /** The next entry to read, in list order, or null when the refresh is done. A group that has its titles reads no further. */ + fun next(progress: RefreshProgress): RefreshEntry? { + for ((index, group) in groups.withIndex()) { + var count = 0 + for (entry in entries.filter { it.group == index }) { + if (group.limit != null && count >= group.limit) break + if (needs(entry, progress)) return entry + if (itemsFor(entry, progress).isNotEmpty()) count++ + } + } + return null + } + + /** Entries still to read, as far as can be told now (a limited group may need fewer once its earlier entries are found). */ + fun pending(progress: RefreshProgress): Int = entries.count { needs(it, progress) } + + /** The pool as it stands: the list's titles in order, with what each entry has so far, then the chosen titles. */ + fun pool(progress: RefreshProgress): List { + val listed = programming.searches.map { seriesKey(FilmIdentity.of(it).title) }.toSet() + val out = ArrayList() + if (programming.filmRestMs != null) out += earlier.filter { seriesKey(it.title) !in listed } + for ((index, group) in groups.withIndex()) { + var count = 0 + for (entry in entries.filter { it.group == index }) { + if (group.limit != null && count >= group.limit) break + var added = false + for (item in itemsFor(entry, progress)) { + val seen = out.any { it.id == item.id || ((group.kind == RefreshEntry.Kind.SERIES || group.kind == RefreshEntry.Kind.CHOSEN) && seriesKey(it.title) == seriesKey(item.title)) } + if (!seen) { out += item; added = true } + } + if (added) count++ + } + } + return withoutWithdrawn(out, programming.withdrawn) + } + + /** + * Reads entries until the refresh is done, its [share] is spent, the hour's budget runs out, or the server keeps failing. + * [read] returns what one entry found and the requests it took, and throws [EmbyCheckException] if the server failed; + * [pacedOut] says whether the hour's budget has run out (a read that found nothing then can't be trusted, so it waits). + * [save] is called after every entry, so nothing read is lost. + */ + fun step(start: RefreshProgress, share: Int, nowMs: Long, pacedOut: () -> Boolean, + read: (RefreshEntry) -> Pair, save: (RefreshProgress) -> Unit = {}): RefreshStep { + var progress = RefreshProgress(start.target, start.full, start.startedMs, start.done, start.carried, start.refound, start.requests, start.rounds + 1, nowMs) + var spent = 0; var count = 0; var failures = 0 + var stop = RefreshStop.FINISHED + while (true) { + val entry = next(progress) ?: break + if (spent >= share) { stop = RefreshStop.SHARE; break } + if (pacedOut()) { stop = RefreshStop.PACED; break } + val result = try { read(entry) } catch (failure: EmbyCheckException) { + if (failure is PacedOut) { stop = RefreshStop.PACED; break } + // Signed out, or a failure not worth retrying: stop here, keeping everything. + if (!failure.retryable || failure.httpStatus == 401 || failure.httpStatus == 403) throw failure + // One entry's read failed: it keeps its saved copy (never dropped), and is tried again at the next refresh. + // Several in a row is the server struggling, so this round stops; the refresh carries on later. + if (++failures > MAX_FAILED_READS) { stop = RefreshStop.FAILING; break } + progress = RefreshProgress(progress.target, progress.full, progress.startedMs, progress.done + (entry.id to listOfNotNull(copies[entry.id])), + progress.carried + entry.id, progress.refound, progress.requests, progress.rounds, nowMs) + save(progress); count++ + continue + } + val (found, requests) = result + spent += requests + // Found nothing just as the budget ran out: the read may have been cut short (a chosen title's lookup gives up + // quietly), so it isn't trusted; the entry is read again next time. + if (found.series.isEmpty() && pacedOut()) { stop = RefreshStop.PACED; break } + // A chosen title the server didn't answer for keeps its saved copy: only the list can take a choice off. + val items = if (entry.kind == RefreshEntry.Kind.CHOSEN && found.series.isEmpty()) listOfNotNull(copies[entry.id]) else found.series + progress = RefreshProgress(progress.target, progress.full, progress.startedMs, progress.done + (entry.id to items), + progress.carried, progress.refound + found.refound, progress.requests + requests, progress.rounds, nowMs) + save(progress); count++ + } + return RefreshStep(progress, pool(progress), stop, spent, count, pending(progress)) + } +} + +/** + * How each channel's list stands, for Settings (Paul, 26 November 2026: "diagnostics showing the last refresh"): when it was + * last read in full, and how many entries a refresh still has to read. Kept in memory by the background round; counts only. + */ +internal object RefreshStatus { + class Line(val fetchedAtMs: Long, val pending: Int, val sinceMs: Long?) + private val lines = java.util.concurrent.ConcurrentHashMap() + fun note(number: Int, fetchedAtMs: Long, pending: Int, sinceMs: Long?) { lines[number] = Line(fetchedAtMs, pending, sinceMs) } + fun snapshot(): Map = HashMap(lines) + internal fun clearForTest() = lines.clear() +} + +/** Settings' line about the channel lists, from [RefreshStatus]. */ +internal fun refreshStatusLine(lines: Map, nowMs: Long, name: (Int) -> String = { "channel $it" }): String { + if (lines.isEmpty()) return "Not checked yet: the lists are looked at in the background, once an hour." + fun ago(ms: Long): String { val h = ((nowMs - ms) / 3_600_000L).coerceAtLeast(0); return if (h < 1) "under an hour ago" else if (h < 48) "$h hour${if (h == 1L) "" else "s"} ago" else "${h / 24} days ago" } + val catching = lines.filterValues { it.pending > 0 } + val oldest = lines.minByOrNull { it.value.fetchedAtMs }!! + val head = if (catching.isEmpty()) "All ${lines.size} channel lists are up to date." + else "${catching.size} of ${lines.size} channel lists are catching up, ${catching.values.sumOf { it.pending }} titles still to read, a fair share each hour" + + (catching.values.mapNotNull { it.sinceMs }.minOrNull()?.let { "; the longest has been going since ${ago(it)}" } ?: "") + "." + return "$head Each list is read again about once a week; the longest since its last full read is ${name(oldest.key)}, ${ago(oldest.value.fetchedAtMs)}." +} diff --git a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt index 438517da..24024786 100644 --- a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt @@ -162,27 +162,48 @@ internal class ScheduleStore(private val directory: File) { SavedProgress(root.getBoolean("enabled"), decodeCursor(root.getJSONObject("aired"))) } - fun savePool(userId: String, number: Int, pool: SavedPool) { + private fun encodeSeries(list: List): JSONArray { val series = JSONArray() - pool.series.forEach { show -> + list.forEach { show -> val episodes = JSONArray() show.episodes.forEach { e -> episodes.put(JSONArray().put(e.id).put(e.sourceId).put(e.mark.season).put(e.mark.episode).put(e.title).put(e.durationMs)) } series.put(JSONObject().put("id", show.id).put("title", show.title).put("episodes", episodes).put("group", show.group).put("ref", show.ref).apply { show.year?.let { put("year", it) } }) } - write(file("episodes", number), root(userId, number).put("fetched", pool.fetchedAtMs).put("signature", pool.signature).put("series", series)) + return series } + private fun decodeSeries(rows: JSONArray): List = (0 until rows.length()).map { index -> + val show = rows.getJSONObject(index) + val episodes = show.getJSONArray("episodes") + PoolSeries(validId(show.getString("id")), show.getString("title"), (0 until episodes.length()).map { row -> + val e = episodes.getJSONArray(row) + PoolEpisode(validId(e.getString(0)), validId(e.getString(1)), EpisodeMark(e.getInt(2), e.getInt(3)), e.getString(4), validDuration(e.getLong(5))) + }.also { require(it.isNotEmpty()) }, show.optString("group"), show.optString("ref").takeIf { REF.matches(it) }.orEmpty(), show.optInt("year", 0).takeIf { it in 1800..2200 }) + } + + fun savePool(userId: String, number: Int, pool: SavedPool) = + write(file("episodes", number), root(userId, number).put("fetched", pool.fetchedAtMs).put("signature", pool.signature).put("series", encodeSeries(pool.series))) fun loadPool(userId: String, number: Int): SavedPool? = read(file("episodes", number), userId, number) { root -> - val rows = root.getJSONArray("series") - SavedPool((0 until rows.length()).map { index -> - val show = rows.getJSONObject(index) - val episodes = show.getJSONArray("episodes") - PoolSeries(validId(show.getString("id")), show.getString("title"), (0 until episodes.length()).map { row -> - val e = episodes.getJSONArray(row) - PoolEpisode(validId(e.getString(0)), validId(e.getString(1)), EpisodeMark(e.getInt(2), e.getInt(3)), e.getString(4), validDuration(e.getLong(5))) - }.also { require(it.isNotEmpty()) }, show.optString("group"), show.optString("ref").takeIf { REF.matches(it) }.orEmpty(), show.optInt("year", 0).takeIf { it in 1800..2200 }) - }, root.getLong("fetched"), root.optString("signature")) + SavedPool(decodeSeries(root.getJSONArray("series")), root.getLong("fetched"), root.optString("signature")) } + /** A channel's list refresh part-way through ([PoolRefresh]), so it carries on across rounds and restarts. */ + fun saveRefresh(userId: String, number: Int, progress: RefreshProgress) { + val done = JSONObject().also { d -> progress.done.forEach { (id, items) -> d.put(id, encodeSeries(items)) } } + write(file("refresh", number), root(userId, number).put("target", progress.target).put("full", progress.full).put("started", progress.startedMs) + .put("last", progress.lastMs).put("requests", progress.requests).put("rounds", progress.rounds).put("done", done) + .put("carried", JSONArray(progress.carried.toList())).put("refound", JSONObject(progress.refound as Map<*, *>))) + } + fun loadRefresh(userId: String, number: Int): RefreshProgress? = read(file("refresh", number), userId, number) { root -> + val done = root.getJSONObject("done"); val carried = root.getJSONArray("carried"); val refound = root.getJSONObject("refound") + RefreshProgress(root.getString("target"), root.getBoolean("full"), root.getLong("started"), + done.keys().asSequence().associateWith { decodeSeries(done.getJSONArray(it)) }, + (0 until carried.length()).map { carried.getString(it) }.toSet(), + refound.keys().asSequence().associateWith { validId(refound.getString(it)) }, + root.getInt("requests"), root.getInt("rounds"), root.optLong("last", root.getLong("started"))) + } + /** A finished or abandoned refresh: its file and the last good copy both go, so it can't come back. */ + fun deleteRefresh(number: Int) { file("refresh", number).delete(); File(directory, "refresh-$number.json.prev").delete() } + /** Files that wouldn't play on this box, across every channel. Never planned again. */ fun unplayable() = UnplayableLog(File(directory, "failed-reasons-0.json")) /** Films you've looked at and let through despite an odd running time ([RuntimeReview]). */ diff --git a/android/app/src/main/java/tv/orbit/classic/Settings.kt b/android/app/src/main/java/tv/orbit/classic/Settings.kt index dffe8723..45f0f5a2 100644 --- a/android/app/src/main/java/tv/orbit/classic/Settings.kt +++ b/android/app/src/main/java/tv/orbit/classic/Settings.kt @@ -504,6 +504,9 @@ private fun AccountDetail(server: String, titles: Long?, onSignOut: () -> Unit, val ceilingHit = remember { BackgroundPacing.ceilingHitMs?.let { java.text.SimpleDateFormat("HH:mm", java.util.Locale.UK).format(java.util.Date(it)) } } SettingLine("Requests to your server", "This hour: $requestsHour. Last 24 hours: $requestsDay. Counted on this TV only; nothing is sent anywhere. Background reading keeps to $BACKGROUND_BUDGET_LINE, " + "and stops whenever this TV has made ${BackgroundPacing.ceiling} requests in an hour" + (if (BackgroundPacing.tvs > 1) " (shared with ${BackgroundPacing.tvs - 1} other TV${if (BackgroundPacing.tvs > 2) "s" else ""} in the house)." else ".") + (ceilingHit?.let { " It last stopped at $it; watching carried on." } ?: "")) {} + // Each channel list's last refresh, and any still catching up (26 November 2026: 22 lists starved for days unseen). + val listsLine = remember { refreshStatusLine(RefreshStatus.snapshot(), System.currentTimeMillis()) { n -> SmartChannels.firstOrNull { it.number == n }?.name ?: "channel $n" } } + SettingLine("Channel lists", listsLine) {} // Credits for the sounds Paul chose (8 November 2026): royalty-free effects, named with thanks (design/channels/sound/samples). Text("Sound credits: VHS, Horror, After Dark, Vortex, Heroes, Riot, Paradox and Ring X use royalty-free effects from Pixabay by " + "freesound_community, jusatti890, tomas_herudek, audiopapkin, vishiv and other Pixabay creators, mastered for Orbit. Thank you.", diff --git a/android/app/src/test/java/tv/orbit/classic/PoolRefreshTest.kt b/android/app/src/test/java/tv/orbit/classic/PoolRefreshTest.kt new file mode 100644 index 00000000..e627041e --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/PoolRefreshTest.kt @@ -0,0 +1,175 @@ +package tv.orbit.classic + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +/** + * The entry-by-entry list refresh (Paul, 26 November 2026): a changed list reads only what it lacks, drops what the list no + * longer names, never drops anything because the server failed, carries on where it stopped, and takes only its share. + */ +class PoolRefreshTest { + @get:Rule val folder = TemporaryFolder() + + private var nextId = 1000 + private fun film(title: String, year: Int? = null, ref: String = "") = (nextId++).toString().let { id -> + PoolSeries(id, title, listOf(PoolEpisode(id, "9$id", EpisodeMark(1, 1), title, 5_400_000)), ref = ref, year = year) } + private fun show(title: String, episodes: Int = 3) = (nextId++).toString().let { id -> + PoolSeries(id, title, (1..episodes).map { PoolEpisode("$id$it", "9$id$it", EpisodeMark(1, it), "E$it", 1_800_000) }) } + private fun filmChannel(vararg films: String, count: Int = 99) = ChannelProgramming(950, "Test films", films.toList(), count, filmRestMs = 7 * 24 * 3_600_000L) + private fun seriesChannel(vararg shows: String, count: Int = 99) = ChannelProgramming(951, "Test shows", shows.toList(), count) + private fun read(found: Map>, cost: Int = 1, log: MutableList = mutableListOf(), fail: Set = emptySet(), paceAfter: Int = Int.MAX_VALUE): (RefreshEntry) -> Pair = { entry -> + if (log.size >= paceAfter) throw PacedOut() + log += entry.text + if (entry.text in fail) throw EmbyCheckException("timed out", retryable = true) + EmbySampleSession.PoolRead(found[entry.text].orEmpty(), cost) to cost + } + + @Test fun aChangedListReadsOnlyWhatItLacksAndDropsWhatItNoLongerNames() { + val dam = film("The Dam Busters", 1955); val zulu = film("Zulu", 1964); val chicken = film("Chicken Run", 2000) + val refresh = PoolRefresh(filmChannel("The Dam Busters (1955)", "Zulu (1964)", "Paddington (2014)"), ChannelChoices(), listOf(dam, chicken, zulu)) + val paddington = film("Paddington", 2014) + val log = mutableListOf() + val step = refresh.step(RefreshProgress("new", false, 0), 50, 0, { false }, read(mapOf("Paddington (2014)" to listOf(paddington)), log = log)) + assertEquals(listOf("Paddington (2014)"), log) + assertTrue(step.finished) + assertEquals(listOf(dam, zulu, paddington).map { it.id }, step.pool.map { it.id }) + assertEquals(listOf(chicken.id), refresh.dropped.map { it.id }) + } + + @Test fun aDroppedTitleLeavesAtOnceEvenBeforeTheRestIsRead() { + val dam = film("The Dam Busters", 1955); val chicken = film("Chicken Run", 2000) + val refresh = PoolRefresh(filmChannel("The Dam Busters (1955)", "Paddington (2014)"), ChannelChoices(), listOf(dam, chicken)) + val step = refresh.step(RefreshProgress("new", false, 0), 50, 0, { false }, read(emptyMap(), paceAfter = 0)) + assertEquals(RefreshStop.PACED, step.stop) + assertEquals(listOf(dam.id), step.pool.map { it.id }) + } + + @Test fun aFilmNamedWithAYearIsNotTakenForAnotherFilmOfThatName() { + val remake = film("Halloween", 2018) + val refresh = PoolRefresh(filmChannel("Halloween (1978)"), ChannelChoices(), listOf(remake)) + assertNull(refresh.copies["film:Halloween (1978)"]) + assertEquals("Halloween (1978)", refresh.next(RefreshProgress("t", false, 0))?.text) + } + + @Test fun aServerFailureNeverDropsATitle() { + val a = show("Batman Beyond"); val b = show("ThunderCats") + val refresh = PoolRefresh(seriesChannel("Batman Beyond", "ThunderCats"), ChannelChoices(), listOf(a, b)) + // The weekly re-read: ThunderCats' read fails, so it keeps its saved copy, and the refresh is tried again in a few hours. + val step = refresh.step(RefreshProgress("same", true, 0), 50, 0, { false }, read(mapOf("Batman Beyond" to listOf(show("Batman Beyond", 5))), fail = setOf("ThunderCats"))) + assertTrue(step.finished) + assertEquals(listOf("Batman Beyond", "ThunderCats"), step.pool.map { it.title }) + assertEquals(5, step.pool[0].episodes.size) + assertEquals(b.id, step.pool[1].id) + assertEquals(setOf("series:ThunderCats"), step.progress.carried) + } + + @Test fun aStrugglingServerStopsTheRoundButKeepsEverything() { + val shows = (1..6).map { show("Show $it") } + val refresh = PoolRefresh(seriesChannel(*shows.map { it.title }.toTypedArray()), ChannelChoices(), shows) + val step = refresh.step(RefreshProgress("same", true, 0), 50, 0, { false }, read(emptyMap(), fail = shows.map { it.title }.toSet())) + assertEquals(RefreshStop.FAILING, step.stop) + assertEquals(shows.map { it.id }, step.pool.map { it.id }) + assertFalse(step.finished) + } + + @Test fun signedOutStopsAtOnce() { + val refresh = PoolRefresh(seriesChannel("A"), ChannelChoices(), listOf(show("A"))) + assertThrows(EmbyCheckException::class.java) { + refresh.step(RefreshProgress("same", true, 0), 50, 0, { false }, { throw EmbyCheckException("signed out", 401) }) + } + } + + @Test fun aRefreshCarriesOnWhereItStoppedAndReadsNothingTwice() { + val titles = (1..10).map { "Film $it" } + val refresh = PoolRefresh(filmChannel(*titles.toTypedArray()), ChannelChoices(), emptyList()) + val found = titles.associateWith { listOf(film(it)) } + val log = mutableListOf() + var progress = RefreshProgress("t", false, 0) + var rounds = 0 + while (true) { + rounds++ + val step = refresh.step(progress, 3, rounds * 3_600_000L, { false }, read(found, log = log)) + progress = step.progress + if (step.finished) break + assertEquals(RefreshStop.SHARE, step.stop) + } + assertEquals(titles, log) + assertEquals(4, rounds) + assertEquals(4, progress.rounds) + assertEquals(10, progress.requests) + } + + @Test fun progressSurvivesARestart() { + val dir = folder.newFolder(); val store = ScheduleStore(dir) + val titles = (1..6).map { "Film $it" } + val found = titles.withIndex().associate { (i, t) -> t to listOf(film(t, ref = "imdb.tt00000${i + 1}")) } + val refresh = PoolRefresh(filmChannel(*titles.toTypedArray()), ChannelChoices(), emptyList()) + val first = refresh.step(RefreshProgress("sig", false, 0), 50, 0, { false }, read(found, paceAfter = 2), save = { store.saveRefresh("u", 950, it) }) + assertEquals(RefreshStop.PACED, first.stop) + // The TV restarts: the next round reads the saved progress and carries on from the third film. + val saved = ScheduleStore(dir).loadRefresh("u", 950)!! + assertEquals("sig", saved.target) + assertEquals(setOf("film:Film 1", "film:Film 2"), saved.done.keys) + assertEquals("imdb.tt000001", saved.done["film:Film 1"]!!.single().ref) + val log = mutableListOf() + val second = refresh.step(saved, 50, 1, { false }, read(found, log = log), save = { store.saveRefresh("u", 950, it) }) + assertEquals(titles.drop(2), log) + assertTrue(second.finished) + store.deleteRefresh(950) + assertNull(store.loadRefresh("u", 950)) + } + + @Test fun aReadThatFoundNothingAsTheBudgetRanOutIsTriedAgain() { + val refresh = PoolRefresh(filmChannel("A", "B"), ChannelChoices(), emptyList()) + var used = 0 + val step = refresh.step(RefreshProgress("t", false, 0), 50, 0, { used >= 1 }, { used++; EmbySampleSession.PoolRead(emptyList(), 1) to 1 }) + assertEquals(RefreshStop.PACED, step.stop) + assertTrue(step.progress.done.isEmpty()) + } + + @Test fun aSeriesChannelStopsReadingOnceItHasItsShows() { + val x = show("X"); val z = show("Z") + val refresh = PoolRefresh(seriesChannel("X", "Y", "Z", "W", count = 2), ChannelChoices(), listOf(x)) + val log = mutableListOf() + val step = refresh.step(RefreshProgress("t", false, 0), 50, 0, { false }, read(mapOf("Z" to listOf(z), "W" to listOf(show("W"))), log = log)) + assertEquals(listOf("Y", "Z"), log) + assertEquals(listOf(x.id, z.id), step.pool.map { it.id }) + } + + @Test fun aChosenTitleIsKeptUnlessTheChoiceGoes() { + val chosen = film("Matilda", 1996) + val choices = ChannelChoices(listOf(Suggestion(chosen.id, "Matilda", 1996, "Movie", "", ""))) + val refresh = PoolRefresh(filmChannel("A"), choices, listOf(chosen)) + // The weekly re-read: the server gave nothing for it, so it keeps its copy. + val step = refresh.step(RefreshProgress("t", true, 0), 50, 0, { false }, read(emptyMap())) + assertTrue(step.pool.any { it.id == chosen.id }) + // Unchosen: it goes. + assertTrue(PoolRefresh(filmChannel("A"), ChannelChoices(), listOf(chosen)).dropped.any { it.id == chosen.id }) + } + + @Test fun theHoursBudgetIsSharedEquallyByTheChannelsStillRefreshing() { + // A tenth of the hour is left for the rest of the round (the Drive-In, the evidence, the catalogue). + assertEquals(22, refreshShare(100, 0, 4)) + assertEquals(REFRESH_MIN_SHARE, refreshShare(100, 0, 22)) + assertEquals(25, refreshShare(100, 40, 2)) + assertEquals(REFRESH_MIN_SHARE, refreshShare(100, 100, 1)) + assertFalse(refreshPacedOut(100, 89)); assertTrue(refreshPacedOut(100, 90)) + } + + @Test fun settingsSaysHowTheListsStand() { + val h = 3_600_000L; val now = 1_000 * h + assertEquals("Not checked yet: the lists are looked at in the background, once an hour.", refreshStatusLine(emptyMap(), now)) + val fine = mapOf(101 to RefreshStatus.Line(now - 30 * h, 0, null), 102 to RefreshStatus.Line(now - 4 * 24 * h, 0, null)) + assertEquals("All 2 channel lists are up to date. Each list is read again about once a week; the longest since its last full read is Orbit Two, 4 days ago.", + refreshStatusLine(fine, now) { if (it == 102) "Orbit Two" else "Orbit One" }) + val catching = fine + (103 to RefreshStatus.Line(now - 2 * h, 12, now - 3 * h)) + assertEquals("1 of 3 channel lists are catching up, 12 titles still to read, a fair share each hour; the longest has been going since 3 hours ago. " + + "Each list is read again about once a week; the longest since its last full read is channel 102, 4 days ago.", refreshStatusLine(catching, now)) + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/RefreshSimulationTest.kt b/android/app/src/test/java/tv/orbit/classic/RefreshSimulationTest.kt new file mode 100644 index 00000000..d0435461 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/RefreshSimulationTest.kt @@ -0,0 +1,168 @@ +package tv.orbit.classic + +import org.json.JSONObject +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Test +import java.io.File + +/** + * The list refresh on two TVs (Paul, 26 November 2026): both start from the living room's 26 November snapshot, where 22 of + * the lists were stuck, and run the background round hourly for a week on the household budget (100 an hour each), with + * the TV restarted part-way. Reads are answered from the library's catalogue (audit-20261126-refresh/catalogue.tsv) at what + * each would cost on the server: a film search one request, a series search one and a page per 100 episodes of each copy. + * + * Measures what Paul asked for: requests per hour on each TV, how long until every list has caught up, whether any list waits + * round after round with nothing read (starvation), whether a restart loses anything, and that the plans (the bookings) are + * never touched. Run only with SIM_SNAP (a snapshot's no_backup/schedule), SIM_CATALOGUE and SIM_OUT. + */ +class RefreshSimulationTest { + private class Row(val id: String, val type: String, val title: String, val year: Int?, val imdb: String) + + @Test fun twoTvsRefreshEveryListWithinTheBudget() { + val snap = System.getenv("SIM_SNAP")?.let(::File) + assumeTrue(snap != null && snap.isDirectory) + val catalogue = File(System.getenv("SIM_CATALOGUE")!!).readLines().mapNotNull { line -> + val f = line.split('\t'); if (f.size < 5) null else Row(f[0], f[1], f[2], f[3].toIntOrNull(), f[4]) } + val films = catalogue.filter { it.type == "Movie" }.groupBy { seriesKey(it.title) } + val series = catalogue.filter { it.type == "Series" } + val seriesByKey = series.groupBy { seriesKey(it.title) } + val out = File(System.getenv("SIM_OUT")!!).also { it.mkdirs() } + val user = snap!!.listFiles()!!.first { it.name.startsWith("episodes-") && it.name.endsWith(".json") }.let { JSONObject(it.readText()).getString("user") } + val budget = BackgroundPacing.share(BackgroundPacing.HOURLY_BUDGET, 2) + val otherPerHour = System.getenv("SIM_OTHER")?.toInt() ?: 20 + val hours = System.getenv("SIM_HOURS")?.toInt() ?: (7 * 24) + val restartHour = 1 + val programmings = BuiltInChannels + val log = StringBuilder() + + // A list that hasn't changed, put together entry by entry from its saved pool, is the pool a whole read made. + val snapStore = ScheduleStore(snap) + val sameLists = programmings.mapNotNull { p -> + val cached = snapStore.loadPool(user, p.number) ?: return@mapNotNull null + val choices = snapStore.loadChoices(user, p.number) + if (cached.signature != "${p.signature}#${choices.tag}") return@mapNotNull null + val rebuilt = PoolRefresh(p, choices, cached.series).pool(RefreshProgress(cached.signature, false, 0)) + p.number to (rebuilt.map { it.id } == cached.series.map { it.id }) + } + val differ = sameLists.filter { !it.second }.map { it.first } + + // Each TV has its own copy of the snapshot's files, so the simulation never writes to the snapshot. + val tvs = (0..1).map { tv -> File(out, "tv$tv").also { d -> d.deleteRecursively(); snap.copyRecursively(d) } } + val plansBefore = tvs.map { d -> d.listFiles()!!.filter { it.name.startsWith("schedule-") }.associate { it.name to it.readBytes().contentHashCode() } } + + // What a read of one entry would find on the server, and its cost. + fun answer(p: ChannelProgramming, entry: RefreshEntry, cached: List, choices: ChannelChoices): Pair, Int> = when (entry.kind) { + RefreshEntry.Kind.FILM -> { + val identity = FilmIdentity.of(entry.text) + val named = films[seriesKey(identity.title)].orEmpty() + if (named.isEmpty()) emptyList() to 0 else { + val candidates = named.map { r -> FilmCandidate(r.id, r.title, r.year, r.imdb.ifEmpty { null }, + listOf(JSONObject().put("Id", "9" + r.id).put("Container", "mkv").put("RunTimeTicks", 6_000L * 10_000_000))) } + listOfNotNull(resolveFilm(identity, candidates).film) to 1 + } + } + RefreshEntry.Kind.SERIES -> { + val key = seriesKey(entry.text) + val copies = (seriesByKey[key] ?: series.filter { seriesKey(it.title).startsWith("$key ") }.sortedBy { it.year ?: 9999 }.take(1)).take(4) + if (copies.isEmpty()) emptyList() to 0 else { + val known = cached.firstOrNull { seriesKey(it.title) == seriesKey(copies[0].title) } + val episodes = known?.episodes?.size ?: 20 + val show = known ?: PoolSeries(copies[0].id, copies[0].title, (1..episodes).map { PoolEpisode(copies[0].id + "%03d".format(it), "9" + copies[0].id + "%03d".format(it), EpisodeMark(1, it), "E$it", 1_800_000) }) + listOf(show) to 1 + copies.size * (episodes / WHOLE_SERIES_PAGE + 1) + } + } + RefreshEntry.Kind.CHOSEN -> { + val a = choices.accepted.first { it.id == entry.text } + val known = cached.firstOrNull { it.id == a.id || seriesKey(it.title) == seriesKey(a.title) } + listOfNotNull(known) to if (a.type == "Movie") 1 else ((known?.episodes?.size ?: 20) / WHOLE_SERIES_PAGE + 1) + } + } + + class Tv(val dir: File) { + var store = ScheduleStore(dir) + val sent = ArrayDeque() + fun used(now: Long): Int { while (sent.isNotEmpty() && sent.first() <= now - 3_600_000L) sent.removeFirst(); return sent.size } + var lastRoutineMs = 0L + var nextRound = 0L + val hourly = ArrayList() + var maxUsed = 0 + } + val state = tvs.map(::Tv) + val start = 1_795_000_000_000L + val firstStale = HashMap, Int>(); val converged = HashMap, Int>() + val idleRounds = HashMap, Int>(); var worstIdle = 0 + val roundsToFinish = ArrayList() + + // The TVs' rounds aren't in step: the upstairs one starts 20 minutes after. Each round starts an hour after the last ended. + state.forEachIndexed { i, tv -> tv.nextRound = start + i * 20 * 60_000L } + for (hour in 0 until hours) for ((index, tv) in state.withIndex()) { + var now = tv.nextRound + if (hour == restartHour) tv.store = ScheduleStore(tv.dir) // a restart: only what's on disk survives + val store = tv.store + val sigs = programmings.associate { p -> p.number to "${p.signature}#${store.loadChoices(user, p.number).tag}" } + val pools = programmings.associate { p -> p.number to store.loadPool(user, p.number) } + // The routine weekly re-read: at most one starts a round, the most overdue first. + val waitingAtStart = programmings.filter { p -> pools[p.number]?.let { it.signature != sigs[p.number] } == true || store.loadRefresh(user, p.number) != null }.map { it.number } + val waiting = waitingAtStart.toMutableSet() + val routinePick = if (waiting.isNotEmpty()) null else programmings.filter { p -> pools[p.number]?.let { it.signature == sigs[p.number] && poolRefreshDue(it.fetchedAtMs, p.number, now) } == true && store.loadRefresh(user, p.number) == null } + .maxByOrNull { now - pools[it.number]!!.fetchedAtMs - poolJitterMs(it.number) }?.number?.takeIf { now - tv.lastRoutineMs >= POOL_ROUTINE_GAP_MS } + var refreshRequests = 0; var progressed = 0 + for (p in programmings) { + val cached = pools[p.number] ?: continue // a channel never set up here: set up when switched on, not in the round + val signature = sigs[p.number]!! + val choices = store.loadChoices(user, p.number) + val saved = store.loadRefresh(user, p.number)?.takeIf { it.target == signature } + val due = cached.signature != signature || saved != null || p.number == routinePick + val key = index to p.number + if (!due) { if (firstStale.containsKey(key)) converged.putIfAbsent(key, hour); continue } + firstStale.putIfAbsent(key, hour) + val full = saved?.full ?: (cached.signature == signature) + if (saved == null && full) tv.lastRoutineMs = now + val refresh = PoolRefresh(p, choices, cached.series) + val share = refreshShare(budget, tv.used(now), waiting.size + if (p.number in waiting) 0 else 1) + val step = refresh.step(saved ?: RefreshProgress(signature, full, now), share, now, { refreshPacedOut(budget, tv.used(now)) }, { entry -> + val (found, cost) = answer(p, entry, cached.series, choices) + repeat(cost) { if (tv.used(now) >= budget) throw PacedOut(); now += BackgroundPacing.GAP_MS; tv.sent.addLast(now) } + EmbySampleSession.PoolRead(found, cost) to cost + }, save = { store.saveRefresh(user, p.number, it) }) + waiting -= p.number + refreshRequests += step.spent + if (step.read > 0) { progressed++; idleRounds[key] = 0 } else { idleRounds[key] = (idleRounds[key] ?: 0) + 1; worstIdle = maxOf(worstIdle, idleRounds[key]!!) } + if (step.finished) { + store.savePool(user, p.number, ScheduleStore.SavedPool(step.pool, now, signature)); store.deleteRefresh(p.number) + roundsToFinish += step.progress.rounds + log.append("tv$index h$hour channel=${p.number} done full=$full entries=${refresh.entries.size} read=${step.progress.done.size} dropped=${refresh.dropped.size} requests=${step.progress.requests} rounds=${step.progress.rounds}\n") + } else { + store.savePool(user, p.number, ScheduleStore.SavedPool(step.pool, cached.fetchedAtMs, cached.signature)) + log.append("tv$index h$hour channel=${p.number} partial stop=${step.stop} read=${step.read} pending=${step.pending} share=$share spent=${step.spent}\n") + } + } + // The rest of the round's background work (the Drive-In, evidence, the catalogue) takes what it can. + var other = 0 + while (other < otherPerHour && tv.used(now) < budget) { now += BackgroundPacing.GAP_MS; tv.sent.addLast(now); other++ } + tv.maxUsed = maxOf(tv.maxUsed, tv.used(now)) + tv.nextRound = now + 3_600_000L + val stale = programmings.count { p -> store.loadPool(user, p.number)?.let { it.signature != sigs[p.number] } == true } + tv.hourly += "$hour\t$refreshRequests\t$other\t${tv.used(now)}\t$progressed\t$stale" + } + + val plansAfter = tvs.map { d -> d.listFiles()!!.filter { it.name.startsWith("schedule-") }.associate { it.name to it.readBytes().contentHashCode() } } + val summary = StringBuilder() + for ((index, tv) in state.withIndex()) { + File(out, "hourly-tv$index.tsv").writeText("hour\trefreshRequests\totherRequests\tusedLast60min\tchannelsProgressed\tlistsStillStale\n" + tv.hourly.joinToString("\n") + "\n") + val keys = firstStale.keys.filter { it.first == index && firstStale[it] == 0 } + val catchUp = keys.map { (converged[it] ?: hours) - firstStale[it]!! } + summary.append("tv$index: lists stale at the start=${keys.size} allCaughtUpByHour=${catchUp.maxOrNull()} median=${catchUp.sorted().getOrNull(catchUp.size / 2)} " + + "maxUsedIn60min=${tv.maxUsed} budget=$budget plansUnchanged=${plansBefore[index] == plansAfter[index]}\n") + } + summary.append("worst rounds in a row a refreshing list read nothing=$worstIdle; rounds a refresh took: max=${roundsToFinish.maxOrNull()} median=${roundsToFinish.sorted().getOrNull(roundsToFinish.size / 2)}\n") + summary.append("unchanged lists rebuilt from their saved pool: ${sameLists.size}, identical=${sameLists.size - differ.size}, differ=$differ\n") + File(out, "summary.txt").writeText(summary.toString()) + File(out, "log.txt").writeText(log.toString()) + println(summary) + assertTrue(state.all { it.maxUsed <= budget }) + assertTrue(plansBefore == plansAfter) + assertTrue(firstStale.keys.filter { firstStale[it] == 0 }.all { converged.containsKey(it) }) + } +} diff --git a/docs/roadmap.md b/docs/roadmap.md index 20034157..acbd9c98 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -544,3 +544,16 @@ using the hour the channels behind it need. Proposed fix, each with tests: Proof Paul asked for: a simulation from the real 26 Nov snapshot with all 22 stale channels at once, recording requests per hour, hours to converge per channel, any channel starved, an interrupted read and a restart, two TVs within the shared household budget, and existing bookings untouched. Later, separately: one TV sharing a finished read with the other. + +Built for build 81 (26 November 2026, `PoolRefresh.kt`; tests `PoolRefreshTest`, `RefreshSimulationTest`). In the background +round a list already on the TV is refreshed entry by entry: a changed list reads only the entries its saved pool lacks (films +by IMDb ID, else name and year; series by name), drops at once the titles the list no longer names, and a failed read keeps +the old copy (three in a row stops the round, signed out stops at once). Progress is saved to `refresh-N.json` after every +entry with the list's signature, and resumed next round or after a restart; a refresh for an older list is set aside. Each +channel still refreshing gets an equal share of what's left of the hour, at least 8, with a tenth kept for the Drive-In, +evidence and catalogue. The weekly re-read uses the same steps, and only starts while no list has a change to catch up on. +Settings, For the technical, has a Channel lists line. First-run setup and the Director's Chair's own reads are unchanged. +Simulation from the 26 Nov snapshot, two TVs at 100 an hour each, a restart in hour 1, a week: 21 lists stale under the +current build caught up within 3 hours on both TVs (median 1), never over 100 in any 60 minutes, no list waited more than one +round with nothing read, the 15 unchanged lists rebuild identically from their saved pools, plans untouched. +Results: `~/Documents/OrbitTV/audit-20261126-refresh/sim`.