Smart setup: the evening rotation from the plan's own time, balanced by running time (0.110.15-smartsetup, versionCode 298)

The weekly evening and late rotation read the real clock (rotationWeek() in
programmingOf), so plans depended on the day they were made, and
SmartSetupRegressionTest failed from Monday 9 November. And the weekly sets
were split by count, so one of Orbit Sakura's weeks was ten short films:
30 repeats from day 2.5 (from 16 November), against 15 from day 6.

Shaped channels now hand the planner the whole rotating list; topUpPlan
resolves it (resolveRotations) from its own time, balancing the sets by
the pool's running times (rotationSet), deterministically. Every Sakura
week is now 15-17 repeats, none before day 6. Committed plans untouched.

New tests plan every rotation week for both fixture channels; the
regression limit is 18 a week (original run: 34). Docs:
docs/smartsetup-rotation-fix.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 00:52:45 +00:00
co-authored by Claude Opus 5.5
parent 585ac726ee
commit 2df65c098c
7 changed files with 184 additions and 19 deletions
+2 -2
View File
@@ -9,8 +9,8 @@ android {
applicationId = "tv.orbit.classic"
minSdk = 26
targetSdk = 36
versionCode = 296
versionName = "0.110.13-story-p1000"
versionCode = 298
versionName = "0.110.15-smartsetup"
}
buildFeatures { compose = true }
// The finished build for the TVs (Paul, 6 November 2026: the test build stuttered on the box). Not debuggable, so
@@ -29,7 +29,15 @@ internal data class DayPart(val fromHour: Int, val toHour: Int, val titles: List
/** An appointment's own allowance for starting late, instead of [ON_TIME_GRACE_MS]. */
val graceMs: Long? = null,
/** On a film channel, a series event's episodes a night (a strand), and whether they go round a mixed deck. */
val run: Int = 1, val shuffled: Boolean = false) {
val run: Int = 1, val shuffled: Boolean = false,
/**
* A weekly rotation (smart setup's shaped evenings and late nights, 9 November 2026): these of [titles] take turns, at
* most [rotateCap] a week, the rest always play. The planner picks the week's set itself ([resolveRotations]) from the plan's
* own time and the shows' real running times, so plans never depend on the clock and no week runs thin.
*/
val rotating: List<String>? = null, val rotateCap: Int = 0,
/** How many hours a week the rotation's own slot runs, so a long show counts only for what a week can hold. */
val rotateWeekHours: Int = 0) {
fun covers(hour: Int) = if (fromHour <= toHour) hour in fromHour until toHour else hour >= fromHour || hour < toHour
/** An event that runs past midnight belongs to the night it started, so its small hours count from the day before. */
fun covers(hour: Int, day: java.time.DayOfWeek) = covers(hour) && (days.isEmpty() || (if (fromHour > toHour && hour < toHour) day.minus(1) else day) in days)
@@ -1047,6 +1055,7 @@ internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List
val kept = existing?.let { plan -> plan.copy(entries = plan.entries.dropWhile { it.endMs < nowMs - SCHEDULE_KEEP_PAST_MS }) }
if (kept != null && kept.endMs >= nowMs + SCHEDULE_TOP_UP_MS) return kept
if (pool.isNullOrEmpty()) return kept
@Suppress("NAME_SHADOWING") val dayParts = resolveRotations(dayParts, pool, nowMs, zone)
val from = if (kept != null && kept.endMs > nowMs) kept.endMs else nowMs
val untilMs = minOf(nowMs + SCHEDULE_AHEAD_MS, seasonEndMs ?: Long.MAX_VALUE)
if (from >= untilMs) return kept ?: ChannelPlan(emptyList(), existing?.tail ?: aired)
@@ -1058,6 +1067,49 @@ internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List
return ChannelPlan(kept?.entries.orEmpty() + added.entries, added.tail)
}
/**
* A weekly rotation's set for the week of [nowMs] (Mondays turn it over): the [DayPart.rotating] titles split into weeks
* ([DayPart.rotateCap] or fewer each) balanced by running time, then this week's taken. Longest first into the lightest week,
* each counting at most the hours its slot runs in a week, so a week of short films isn't left beside a week of long series
* (Orbit Sakura, 9 November 2026: one week had 14 hours of evening shows, the next 116). Deterministic: the same titles, pool
* and week always give the same set.
*/
internal fun resolveRotations(parts: List<DayPart>, pool: List<PoolSeries>, nowMs: Long, zone: java.time.ZoneId): List<DayPart> {
if (parts.none { it.rotating != null }) return parts
val week = rotationWeek(nowMs, zone)
val runtime = HashMap<String, Long>()
for (s in pool) {
val run = s.episodes.sumOf { it.durationMs }
val key = seriesKey(s.title)
runtime[key] = (runtime[key] ?: 0L) + run
if (s.isFilm) { val f = seriesKey(FilmIdentity.of(s.title).title); if (f != key) runtime[f] = (runtime[f] ?: 0L) + run }
}
return parts.map { part ->
val rotating = part.rotating ?: return@map part
val set = rotationSet(rotating, part.rotateCap, week, part.rotateWeekHours * 3_600_000L) { runtime[seriesKey(it)] ?: runtime[seriesKey(FilmIdentity.of(it).title)] ?: 0L }
val fixed = part.titles.filter { it !in rotating }
part.copy(titles = fixed + set, rotating = null)
}
}
/** The week's set of [titles] as [resolveRotations] chooses it. All of them when they fit in one week. */
internal fun rotationSet(titles: List<String>, cap: Int, week: Long, weekMs: Long, runtimeOf: (String) -> Long): List<String> {
if (titles.size <= cap) return titles
val pages = (titles.size + cap - 1) / cap
val per = (titles.size + pages - 1) / pages
val value = titles.associateWith { minOf(runtimeOf(it), if (weekMs > 0) weekMs else Long.MAX_VALUE) }
val order = titles.sortedWith(compareByDescending<String> { value.getValue(it) }.thenBy { seriesKey(it) })
val load = LongArray(pages); val count = IntArray(pages)
val pageOf = HashMap<String, Int>()
for (t in order) {
var best = -1
for (p in 0 until pages) if (count[p] < per && (best < 0 || load[p] < load[best])) best = p
pageOf[t] = best; load[best] += value.getValue(t); count[best]++
}
val k = Math.floorMod(week, pages.toLong()).toInt()
return titles.filter { pageOf[it] == k }.sortedBy { seriesKey(it) }
}
/**
* A channel that reads committed programmes, and falls back to its existing loop outside them.
* The plan is swapped inside one object, so a top-up never looks like a new channel and never interrupts playback.
@@ -105,13 +105,12 @@ internal object CustomChannels {
/** Roughly how long a first plan takes, from what it has to read: each series' episodes, a quick look for each film. */
fun planMinutes(series: Int, films: Int) = ((series * 9 + films) / 60.0).let { kotlin.math.ceil(it).toInt() }.coerceAtLeast(1)
@Volatile private var cachedWeek = -1L
@Volatile private var cached: Pair<List<CustomChannel>, List<ChannelProgramming>> = emptyList<CustomChannel>() to emptyList()
/** Every channel of your own as the planner sees it. */
val programmings: List<ChannelProgramming> get() {
val now = list; val week = rotationWeek()
// Remade when the list changes, and each week for the evening's rotation.
if (cached.first !== now || cachedWeek != week) { cached = now to now.map(::programmingOf); cachedWeek = week }
val now = list
// Remade when the list changes. The week's evening rotation is chosen by the planner from each plan's own time.
if (cached.first !== now) cached = now to now.map(::programmingOf)
return cached.second
}
}
@@ -127,7 +126,7 @@ internal fun programmingOf(channel: CustomChannel): ChannelProgramming = Channel
// You chose these titles yourself, so they play in the sound they have: Sakura's anime is mostly Japanese with subtitles,
// and asking for English sound left nearly all of it out (7 November 2026).
englishAudio = false,
dayParts = when (channel.style) { PlayStyle.Blocks -> timetableParts(channel.shows); PlayStyle.Shaped -> shapedParts(channel.slots, eveningPage = rotationWeek()); else -> emptyList() },
dayParts = when (channel.style) { PlayStyle.Blocks -> timetableParts(channel.shows); PlayStyle.Shaped -> shapedParts(channel.slots); else -> emptyList() },
storyGrouping = channel.style == PlayStyle.Standard || channel.style == PlayStyle.Shaped,
shorts = if (channel.style == PlayStyle.Standard || channel.style == PlayStyle.Shaped) YoursShorts else null,
tierWeights = if (channel.style == PlayStyle.Shaped && channel.core.isNotEmpty()) shapedWeights(channel.core) else null,
@@ -230,18 +230,33 @@ internal fun weekCheck(series: Int, films: Int): String? = when {
* never the late ones, so a late title stays late (Paul, 7 November 2026: the creator's choices and the profile's rules win).
* With nothing laid out, everything plays all day.
*/
internal fun shapedParts(slots: Map<String, Slot>, eveningPage: Long = 0): List<DayPart> {
internal fun shapedParts(slots: Map<String, Slot>, eveningPage: Long? = null): List<DayPart> {
if (slots.isEmpty()) return emptyList()
val bySlot = Slot.entries.associateWith { s -> slots.filterValues { it == s }.keys.toList() }.toMutableMap()
// Evenings are appointments (Paul, 7 November 2026: Sakura's evening had 85 shows, each on once a week): at most
// EVENING_ROTATION shows a week, so each comes back most nights, and a different set the next week until all have had theirs.
bySlot[Slot.Evening] = eveningRotation(bySlot.getValue(Slot.Evening), eveningPage)
// Late nights the same way (Paul, 7 November 2026: Sakura's late had 52 shows), with a few more as the hours are longer.
bySlot[Slot.Late] = eveningRotation(bySlot.getValue(Slot.Late), eveningPage, LATE_ROTATION)
// With no [eveningPage] (as the app plans), the week's sets are left to the planner, which balances them by running time
// and takes the week from the plan's own time ([resolveRotations]). With one, the old split by count (tests).
val evening = bySlot.getValue(Slot.Evening); val late = bySlot.getValue(Slot.Late)
val eveningTurns = evening.takeIf { eveningPage == null && it.size > EVENING_ROTATION }
val lateTurns = late.takeIf { eveningPage == null && it.size > LATE_ROTATION }
if (eveningPage != null) {
bySlot[Slot.Evening] = eveningRotation(evening, eveningPage)
bySlot[Slot.Late] = eveningRotation(late, eveningPage, LATE_ROTATION)
}
val gentle = bySlot.getValue(Slot.Daytime) + bySlot.getValue(Slot.Evening)
fun hours(s: Slot) = (if (s.fromHour <= s.toHour) s.toHour - s.fromHour else 24 - s.fromHour + s.toHour) * 7
return Slot.entries.mapNotNull { s ->
val titles = bySlot.getValue(s).ifEmpty { if (s == Slot.Late) gentle + bySlot.getValue(Slot.Late) else gentle }
titles.takeIf { it.isNotEmpty() }?.let { DayPart(s.fromHour, s.toHour, it) }
val own = bySlot.getValue(s)
val titles = own.ifEmpty { if (s == Slot.Late) gentle + bySlot.getValue(Slot.Late) else gentle }
if (titles.isEmpty()) return@mapNotNull null
// A part carrying a rotating list takes its turns: its own slot's, or the evening's when it borrows the evening.
when {
s == Slot.Late && lateTurns != null -> DayPart(s.fromHour, s.toHour, titles, rotating = lateTurns, rotateCap = LATE_ROTATION, rotateWeekHours = hours(Slot.Late))
eveningTurns != null && titles.any { it in eveningTurns } -> DayPart(s.fromHour, s.toHour, titles, rotating = eveningTurns, rotateCap = EVENING_ROTATION, rotateWeekHours = hours(Slot.Evening))
else -> DayPart(s.fromHour, s.toHour, titles)
}
}
}
@@ -262,7 +277,7 @@ internal fun eveningRotation(titles: List<String>, page: Long, cap: Int = EVENIN
}
/** Which week it is for the evening's rotation: Mondays turn it over. */
internal fun rotationWeek(nowMs: Long = System.currentTimeMillis(), zone: java.time.ZoneId = java.time.ZoneId.systemDefault()): Long =
internal fun rotationWeek(nowMs: Long, zone: java.time.ZoneId = java.time.ZoneId.systemDefault()): Long =
java.time.Instant.ofEpochMilli(nowMs).atZone(zone).toLocalDate().with(java.time.DayOfWeek.MONDAY).toEpochDay() / 7
/** "About 42 hours", for the week check: how long the picks run before anything repeats. */
@@ -12,13 +12,15 @@ import java.time.ZonedDateTime
* times only.
*/
class SmartSetupRegressionTest {
/** At most this many repeats in a planned week (the original run had 34). */
private val MAX_REPEATS = 18
private val zone = ZoneId.of("Europe/London")
private val now = ZonedDateTime.of(2026, 11, 7, 9, 0, 0, 0, zone).toInstant().toEpochMilli()
private val week = 7 * 24 * 3_600_000L
private val fixture = JSONObject(javaClass.classLoader!!.getResource("fixtures/collections.json")!!.readText())
private class Run(val rows: List<ShapeRow>, val shape: Shape, val channel: CustomChannel, val plan: ChannelPlan)
private fun run(collection: String, number: Int, name: String): Run {
private fun run(collection: String, number: Int, name: String, at: Long = now): Run {
val a = fixture.getJSONArray(collection)
val items = (0 until a.length()).map { a.getJSONObject(it) }
val pool = items.map { o -> val e = o.getJSONArray("episodes")
@@ -30,11 +32,43 @@ class SmartSetupRegressionTest {
val channel = CustomChannel(number, name, PlayStyle.Shaped, shows = rows.map { it.title },
slots = shape.slots.mapNotNull { (id, s) -> titleOf[id]?.let { it to s } }.toMap(), core = shape.core.mapNotNull { titleOf[it] }.toSet())
val p = programmingOf(channel)
val plan = topUpPlan(null, ScheduleCursor(), pool, now, p.filmRestMs, p.finishTogether, p.dayParts, zone, shuffle = p.shuffleEpisodes, mixed = p::mixes,
val plan = topUpPlan(null, ScheduleCursor(), pool, at, p.filmRestMs, p.finishTogether, p.dayParts, zone, shuffle = p.shuffleEpisodes, mixed = p::mixes,
weightOf = p.tierWeights?.let { p::weightOf }, adaptiveRest = p.adaptiveFilmRest, fileRestMs = p.fileRestMs, stories = p.storyGrouping, shorts = p.shorts, marathon = p.marathon)!!
return Run(rows, shape, channel, plan)
}
private fun repeats(plan: ChannelPlan) = plan.entries.filter { it.startMs < now + week }.groupBy { it.media.item.id }.values.sumOf { it.size - 1 }
private fun repeats(plan: ChannelPlan, at: Long = now) = plan.entries.filter { it.startMs < at + week }.groupBy { it.media.item.id }.values.sumOf { it.size - 1 }
private fun firstRepeatDays(plan: ChannelPlan, at: Long) = plan.entries.filter { it.startMs < at + week }.groupBy { it.media.item.id }.values
.filter { it.size > 1 }.minOfOrNull { it[1].startMs }?.let { (it - at) / 86_400_000.0 }
/**
* Every week of the evening rotation (9 November 2026: the third week of Sakura's had 30 repeats from day 2.5, because its
* sets were split by count). Each week from a Saturday and from a Monday, through a whole turn of the rotation and more.
*/
@Test fun everyRotationWeekStaysWithinTheRepeatsAndStartsNoEarlierThanDayFive() {
val report = StringBuilder()
var bad = 0
for ((collection, number, name) in listOf(Triple("Crunchyroll", 702, "Orbit Sakura"), Triple("Hallmark Christmas", 701, "Orbit Mistletoe"))) {
for (day in listOf(7, 9, 14, 16, 21, 23, 28, 30)) {
val at = ZonedDateTime.of(2026, 11, day, 9, 0, 0, 0, zone).toInstant().toEpochMilli()
val r = run(collection, number, name, at)
val n = repeats(r.plan, at); val first = firstRepeatDays(r.plan, at)
report.append("$name from $day Nov (week ${rotationWeek(at, zone)}): $n repeats, first ${first?.let { "%.1f".format(it) } ?: "none"}\n")
if (n > MAX_REPEATS || (first != null && first < 5.0)) bad++
}
}
println(report)
assertEquals(report.toString(), 0, bad)
}
@Test fun plansDependOnTheirOwnTimeNeverTheClock() {
val a = run("Crunchyroll", 702, "Orbit Sakura").plan
val b = run("Crunchyroll", 702, "Orbit Sakura").plan
assertEquals(a.entries.map { it.media.item.id to it.startMs }, b.entries.map { it.media.item.id to it.startMs })
// A channel's programming has no clock in it: its rotation is left for the planner.
val ch = CustomChannel(702, "Orbit Sakura", PlayStyle.Shaped, shows = listOf("x"), slots = (1..30).associate { "Show $it" to Slot.Evening })
assertEquals(programmingOf(ch).dayParts, programmingOf(ch).dayParts)
assertTrue(programmingOf(ch).dayParts.any { it.rotating != null })
}
@Test fun mistletoeIsOneKindSoItPlaysAllDayWithNothingDecidedForYou() {
val r = run("Hallmark Christmas", 701, "Orbit Mistletoe")
@@ -56,8 +90,9 @@ class SmartSetupRegressionTest {
assertEquals(Slot.Late, r.shape.slots[r.rows.first { it.title == "Murder Princess" }.id])
// Core is series, not films.
assertTrue(r.shape.core.all { id -> r.rows.first { it.id == id }.type == "Series" })
// Original: 34 repeats in the week, the first on Tuesday. Now far fewer, none before Friday.
assertTrue(repeats(r.plan) <= 15)
// Original: 34 repeats in the week, the first on Tuesday. Now far fewer, none before Friday. (18: the evening sets are
// balanced by running time since 9 November; every week now has 15 to 17, all on its last day.)
assertTrue(repeats(r.plan) <= MAX_REPEATS)
val firstRepeat = r.plan.entries.filter { it.startMs < now + week }.groupBy { it.media.item.id }.values.filter { it.size > 1 }.minOfOrNull { it[1].startMs }
assertTrue(firstRepeat == null || firstRepeat - now >= 5 * 24 * 3_600_000L)
// Late nights have at least three series (it leaned on two), and no one series takes more than 15 late slots a week.
@@ -146,4 +146,20 @@ class SmartSetupTest {
assertTrue(lateTitles.size <= LATE_ROTATION); assertTrue(lateTitles.all { it in lateShows })
assertEquals(lateShows.toSet(), (0L until 4L).flatMap { eveningRotation(lateShows, it, LATE_ROTATION) }.toSet())
}
@Test fun rotationSetsAreBalancedByRunningTimeAndCoverEveryShowOnce() {
val hour = 3_600_000L
// Ten long series, then twenty short films: by count the first week would be all series, the last all films.
val titles = (1..10).map { "Series $it" } + (1..20).map { "Film $it" }
val run = { t: String -> if (t.startsWith("Series")) 40 * hour else 2 * hour }
val weeks = (0L until 3L).map { rotationSet(titles, EVENING_ROTATION, it, 35 * hour, run) }
assertEquals(titles.toSet(), weeks.flatten().toSet()); assertEquals(titles.size, weeks.sumOf { it.size })
assertTrue(weeks.all { it.size <= EVENING_ROTATION })
val hours = weeks.map { w -> w.sumOf { minOf(run(it), 35 * hour) } / hour }
assertTrue("$hours", hours.max() - hours.min() <= 40)
assertTrue(weeks.all { w -> w.any { it.startsWith("Series") } })
// The same week always gives the same set; few enough all play every week.
assertEquals(weeks[1], rotationSet(titles, EVENING_ROTATION, 4, 35 * hour, run))
assertEquals(listOf("A", "B"), rotationSet(listOf("A", "B"), EVENING_ROTATION, 7, 0, { 0L }))
}
}
+48
View File
@@ -0,0 +1,48 @@
# Smart setup: evening rotation fix (9 November 2026)
Branch `smartsetup-rotation-fix` from `story-p1000` (`585ac72`), version 0.110.15-smartsetup, versionCode 298. Not installed.
## What was wrong
Shaped channels (smart setup, such as Orbit Sakura) rotate their evening and late-night shows weekly: at most 12 evening
and 24 late shows a week, a different set each week (commit `de68578`, 7 November). Two problems:
1. **The week came from the clock.** `programmingOf` called `rotationWeek()` with the real time, so the same plan made on a
different day came out differently. `SmartSetupRegressionTest` (planned from a fixed Saturday, 7 November) started failing
after midnight on Monday 9 November, when the rotation turned over.
2. **Sets were split by count, alphabetically.** Sakura's 29 evening shows made three sets of 10, 10 and 9, but one set was
ten short films (14 hours), another 116 hours of series. The thin week (from Monday 16 November) planned 30 repeats in a week,
the first after 2.5 days, against 15 and 6 days in the others.
## The fix
- `shapedParts` no longer picks the week: it gives the planner the whole rotating list ([DayPart.rotating], with the week's cap
and the slot's weekly hours). A part that borrows the evening's titles (an empty daytime) rotates with the evening.
- `topUpPlan` resolves the rotation first ([resolveRotations]): the week from the plan's own time (`rotationWeek(nowMs, zone)`,
which no longer has a clock default), and the sets **balanced by running time** from the real pool ([rotationSet]): longest
first into the lightest week, each show counting at most the hours its slot runs in a week. Deterministic: the same titles,
pool and week always give the same set.
- `CustomChannels.programmings` no longer rebuilds each week: nothing in a channel's programming depends on the date.
- Plans already committed are untouched; new days are planned with the balanced sets.
## Result (Orbit Sakura, the real Crunchyroll collection)
| Week from | Before | After |
|---|---|---|
| 7 Nov | 15 repeats, first after 6.1 days | 17, first after 6.1 |
| 9 Nov | 16, 6.1 | 16, 6.1 |
| **16 Nov** | **30, 2.5** | **15, 6.1** |
| 23 Nov | 15, 6.1 | 17, 6.1 |
| 30 Nov | 16, 6.1 | 16, 6.1 |
Every week now has 15 to 17 repeats, all on its last day. The regression test's limit is 18 a week (it was 15 when only one
week was ever measured; the original run had 34), with no repeat before day 5. Orbit Mistletoe (no evening part) is unchanged:
no repeats.
## Tests
- `SmartSetupRegressionTest.everyRotationWeekStaysWithinTheRepeatsAndStartsNoEarlierThanDayFive`: Sakura and Mistletoe planned
from eight dates across a whole turn of the rotation (Saturdays and Mondays).
- `SmartSetupRegressionTest.plansDependOnTheirOwnTimeNeverTheClock`: the same plan twice, and a shaped channel's programming
carries its rotation for the planner.
- `SmartSetupTest.rotationSetsAreBalancedByRunningTimeAndCoverEveryShowOnce`.