0.97.0: editorially weighted rotation on Orbit Three, Family Guy out of its evening
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 2m9s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m31s

Tiers core 3, supporting 2, surprises 1, behind a per-channel switch set only for
Orbit Three. Tallies and run starts saved in the cursor. Shuffled and in-order
episode choice unchanged. Four-week replay on the real pool and fingerprints of
every channel against 0.96.0 in docs/replays.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-03 23:59:36 +00:00
co-authored by Claude Opus 5.5
parent 3b045b65bd
commit 5b7b180a10
13 changed files with 674 additions and 13 deletions
@@ -0,0 +1,66 @@
package tv.orbit.classic
import org.json.JSONObject
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
/**
* Four weeks of top-ups on every channel from copies of the box's committed plans and pools, run by hand:
* ORBIT_REPLAY_DIR=<copies of the box's files> ./gradlew :app:testDebugUnitTest --tests '*ReplayFingerprintTest*'
* Writes replay-fingerprints.txt there, one line per channel: a fingerprint of every programme booked and why. Run it
* on two versions of the app to show which channels a change touches. Only uses what every version has.
*/
class ReplayFingerprintTest {
private val dir = System.getenv("ORBIT_REPLAY_DIR")?.let(::File)
private fun plan(file: File): ChannelPlan {
val root = JSONObject(file.readText()); val rows = root.getJSONArray("entries"); val t = root.getJSONObject("tail"); val marks = t.getJSONObject("marks")
val entries = (0 until rows.length()).map { i ->
val o = rows.getJSONObject(i); val d = o.getLong("d"); val n = o.getJSONArray("n")
ScheduleEntry(o.getString("s"), EpisodeMark(n.getInt(0), n.getInt(1)), ScheduledMedia(SampleItem(o.getString("t"), o.optString("k", "Episode"), d / 60_000, "", o.getString("i"), d), o.getString("c"), d),
o.getLong("a"), o.optString("w"), o.optString("p"))
}
return ChannelPlan(entries, ScheduleCursor(if (t.isNull("last")) null else t.getString("last"),
marks.keys().asSequence().associateWith { id -> marks.getJSONArray(id).let { EpisodeMark(it.getInt(0), it.getInt(1)) } },
t.optJSONObject("shown")?.let { s -> s.keys().asSequence().associateWith { s.getLong(it) } }.orEmpty(),
t.optJSONObject("blocks")?.let { b -> b.keys().asSequence().associateWith { b.getString(it) } }.orEmpty()))
}
private fun pool(file: File): List<PoolSeries> {
val rows = JSONObject(file.readText()).getJSONArray("series")
return (0 until rows.length()).map { i ->
val o = rows.getJSONObject(i); val eps = o.getJSONArray("episodes")
PoolSeries(o.getString("id"), o.getString("title"), (0 until eps.length()).map { j ->
val e = eps.getJSONArray(j); PoolEpisode(e.getString(0), e.getString(1), EpisodeMark(e.getInt(2), e.getInt(3)), e.getString(4), e.getLong(5))
}, o.optString("group"))
}
}
@Test fun fourWeeks() {
assumeTrue(dir != null && dir.isDirectory)
val zone = java.time.ZoneId.of("Europe/London")
val out = StringBuilder()
for (programming in SmartChannels.sortedBy { it.number }) {
val committedFile = File(dir, "schedule-${programming.number}.json"); val poolFile = File(dir, "episodes-${programming.number}.json")
if (!committedFile.exists() || !poolFile.exists()) continue
val committed = plan(committedFile); val series = pool(poolFile)
var current = committed
var now = committed.entries.first().startMs + SCHEDULE_KEEP_PAST_MS
val end = now + 28 * 24 * 60 * 60_000L
val all = committed.entries.toMutableList()
while (now < end) {
current = topUpPlan(current, current.tail, series, now, programming.filmRestMs, programming.finishTogether, programming.dayParts, zone,
shuffle = programming.shuffleEpisodes, mixed = programming::mixes) ?: break
current.entries.filter { e -> all.none { it.startMs == e.startMs } }.forEach { all += it }
now += 6 * 60 * 60_000L
}
val text = all.joinToString("\n") { "${it.startMs} ${it.seriesId} ${it.mark} ${it.media.item.id} ${it.why} ${it.presentation}" }
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(text.toByteArray()).joinToString("") { "%02x".format(it) }.take(16)
val committedDigest = java.security.MessageDigest.getInstance("SHA-256").digest(all.take(committed.entries.size).joinToString("\n") { "${it.startMs} ${it.seriesId} ${it.mark} ${it.media.item.id} ${it.why} ${it.presentation}" }.toByteArray()).joinToString("") { "%02x".format(it) }.take(16)
out.appendLine("${programming.number} committed=$committedDigest kept=${all.take(committed.entries.size) == committed.entries} fourWeeks=$digest programmes=${all.size}")
}
File(dir, System.getenv("ORBIT_FINGERPRINT_NAME") ?: "replay-fingerprints.txt").writeText(out.toString())
println(out)
}
}
@@ -0,0 +1,138 @@
package tv.orbit.classic
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
/**
* Orbit Three, four weeks of new bookings after its committed plan, from copies of the box's files, both ways, run by hand:
* ORBIT_REPLAY_DIR=<copies of the box's files> ./gradlew :app:testDebugUnitTest --tests '*WeightedRotationReplayTest*'
* "Before" is the rule installed today: equal turns with finish-together, Family Guy in the evening. "After" is the app
* as it is now: Family Guy out of the evening and weighted rotation. Both top up every six hours exactly as the box does,
* from the committed plan. Writes weighted-rotation-replay.txt with the figures, and fails on any broken rule.
*/
class WeightedRotationReplayTest {
private val dir = System.getenv("ORBIT_REPLAY_DIR")?.let(::File)
private val zone = java.time.ZoneId.of("Europe/London")
private val day = 24 * 60 * 60_000L
private val hour = 60 * 60_000L
private fun plan(file: File): ChannelPlan {
val root = JSONObject(file.readText()); val rows = root.getJSONArray("entries"); val t = root.getJSONObject("tail"); val marks = t.getJSONObject("marks")
val entries = (0 until rows.length()).map { i ->
val o = rows.getJSONObject(i); val d = o.getLong("d"); val n = o.getJSONArray("n")
ScheduleEntry(o.getString("s"), EpisodeMark(n.getInt(0), n.getInt(1)), ScheduledMedia(SampleItem(o.getString("t"), o.optString("k", "Episode"), d / 60_000, "", o.getString("i"), d), o.getString("c"), d),
o.getLong("a"), o.optString("w"), o.optString("p"))
}
return ChannelPlan(entries, ScheduleCursor(if (t.isNull("last")) null else t.getString("last"),
marks.keys().asSequence().associateWith { id -> marks.getJSONArray(id).let { EpisodeMark(it.getInt(0), it.getInt(1)) } },
t.optJSONObject("shown")?.let { s -> s.keys().asSequence().associateWith { s.getLong(it) } }.orEmpty(),
t.optJSONObject("blocks")?.let { b -> b.keys().asSequence().associateWith { b.getString(it) } }.orEmpty()))
}
private fun pool(file: File): List<PoolSeries> {
val rows = JSONObject(file.readText()).getJSONArray("series")
return (0 until rows.length()).map { i ->
val o = rows.getJSONObject(i); val eps = o.getJSONArray("episodes")
PoolSeries(o.getString("id"), o.getString("title"), (0 until eps.length()).map { j ->
val e = eps.getJSONArray(j); PoolEpisode(e.getString(0), e.getString(1), EpisodeMark(e.getInt(2), e.getInt(3)), e.getString(4), e.getLong(5))
}, o.optString("group"))
}
}
private fun replay(committed: ChannelPlan, series: List<PoolSeries>, parts: List<DayPart>, programming: ChannelProgramming, weightOf: ((PoolSeries) -> Double)?, restartEvery: Int = 0): List<ScheduleEntry> {
var current = committed
var now = committed.entries.first().startMs + SCHEDULE_KEEP_PAST_MS
val end = committed.endMs + 28 * day
val all = committed.entries.toMutableList()
val folder = java.nio.file.Files.createTempDirectory("replay").toFile()
var step = 0
while (now < end) {
// Now and then, a restart: the plan goes through the save file, as it does when the box is switched off.
if (restartEvery > 0 && ++step % restartEvery == 0) { ScheduleStore(folder).savePlan("user", 103, current); current = ScheduleStore(folder).loadPlan("user", 103)!! }
current = topUpPlan(current, current.tail, series, now, programming.filmRestMs, programming.finishTogether, parts, zone,
shuffle = programming.shuffleEpisodes, mixed = programming::mixes, weightOf = weightOf) ?: break
current.entries.filter { e -> all.none { it.startMs == e.startMs } }.forEach { all += it }
now += 6 * hour
}
all.sortBy { it.startMs }
return all.filter { it.startMs < end }
}
private val tierNames = mapOf(TIER_CORE to "core", TIER_SUPPORTING to "supporting", TIER_SURPRISE to "surprise")
private fun report(name: String, entries: List<ScheduleEntry>, series: List<PoolSeries>, parts: List<DayPart>, programming: ChannelProgramming, out: StringBuilder): Map<String, Any> {
val titles = series.associate { it.id to it.title }
fun tier(id: String) = tierNames.getValue(ThreeTiers[seriesKey(titles.getValue(id))] ?: TIER_SUPPORTING)
fun block(e: ScheduleEntry) = dayPartFor(series, parts, e.startMs, zone).second
val minutes = entries.groupBy { it.seriesId }.mapValues { (_, es) -> es.sumOf { it.media.durationMs } / 60_000.0 }
val total = minutes.values.sum()
out.appendLine("== $name (${entries.size} programmes, ${"%.0f".format(total / 60)} hours)")
for (t in listOf("core", "supporting", "surprise")) {
val m = minutes.filterKeys { tier(it) == t }.values.sum()
out.appendLine(" $t: ${"%.1f".format(100 * m / total)}% of airtime")
}
// By block: what each tier gets in the evening, where the starvation was.
entries.groupBy(::block).toSortedMap().forEach { (b, es) ->
val bm = es.groupBy { it.seriesId }.mapValues { (_, x) -> x.sumOf { it.media.durationMs } / 60_000.0 }; val bt = bm.values.sum()
out.appendLine(" $b: " + listOf("core", "supporting", "surprise").joinToString { t -> "$t ${"%.0f".format(100 * bm.filterKeys { tier(it) == t }.values.sum() / bt)}%" } +
"; top: " + bm.entries.sortedByDescending { it.value }.take(4).joinToString { "${titles[it.key]} ${"%.0f".format(100 * it.value / bt)}%" })
}
val four = listOf("Gavin & Stacey", "The Mighty Boosh", "Spaced", "Phoenix Nights")
out.appendLine(" the four: " + four.joinToString { t -> val id = series.firstOrNull { seriesKey(it.title) == seriesKey(t) }?.id; "$t ${entries.count { it.seriesId == id }} airings (${entries.count { it.seriesId == id && block(it).contains("18") }} in the evening)" })
// Longest wait between airings, from the start of the period for a show that hasn't aired yet.
val first = entries.first().startMs; val last = entries.last().endMs
val inBlocks = parts.flatMap { it.titles }.map(::seriesKey).toSet()
val waits = series.filter { seriesKey(it.title) in inBlocks }.associate { s ->
s.title to (listOf(first) + entries.filter { it.seriesId == s.id }.map { it.startMs } + listOf(last)).zipWithNext().maxOf { (a, b) -> b - a } / day.toDouble()
}
out.appendLine(" longest waits: " + waits.entries.sortedByDescending { it.value }.take(6).joinToString { "${it.key} ${"%.1f".format(it.value)} d" })
val never = waits.filter { (t, _) -> entries.none { titles[it.seriesId] == t } }.keys
out.appendLine(" never aired: ${never.ifEmpty { listOf("none") }.joinToString()}")
val sameFile = entries.groupBy { it.media.item.id }.values.sumOf { es -> es.zipWithNext().count { (a, b) -> b.startMs - a.startMs < SAME_FILE_MS } }
val twice = entries.zipWithNext().count { (a, b) -> a.seriesId == b.seriesId }
val ordered = series.filter { !programming.mixes(it) }.associateBy { it.id }
val backwards = entries.filter { it.seriesId in ordered }.groupBy { it.seriesId }.values.sumOf { es -> es.zipWithNext().count { (a, b) -> b.mark <= a.mark && b.mark != ordered.getValue(a.seriesId).episodes.first().mark } }
val restarts = series.associate { s -> s.title to entries.filter { it.seriesId == s.id && it.mark == (if (programming.mixes(s)) shuffledEpisodes(s) else s.episodes).first().mark }.map { it.startMs } }
val quick = restarts.mapValues { (_, at) -> at.zipWithNext().count { (a, b) -> b - a < RUN_REST_MS } }.filterValues { it > 0 }
// A burst: one show taking more than half of any three-hour stretch.
val bursts = entries.indices.count { i -> val window = entries.drop(i).takeWhile { it.startMs < entries[i].startMs + 3 * hour }; window.size >= 4 && window.count { it.seriesId == entries[i].seriesId } * 2 > window.size }
val gaps = entries.zipWithNext().count { (a, b) -> a.endMs != b.startMs }
val outOfBlock = entries.count { e -> val (available, _, _) = dayPartFor(series, parts, e.startMs, zone); available.none { it.id == e.seriesId } }
out.appendLine(" same file within 24 h: $sameFile; same show twice running: $twice; in-order shows stepping back: $backwards; gaps or overlaps: $gaps; outside its block: $outOfBlock")
out.appendLine(" runs restarted within 3 days: ${quick.ifEmpty { mapOf("none" to 0) }}; three-hour stretches over half one show: $bursts")
out.appendLine(" by title: " + series.filter { (minutes[it.id] ?: 0.0) > 0 }.sortedByDescending { minutes[it.id] }.joinToString { "${it.title} ${"%.1f".format(100 * minutes.getValue(it.id) / total)}% [${tier(it.id).take(3)}]" })
out.appendLine()
return mapOf("sameFile" to sameFile, "twice" to twice, "backwards" to backwards, "gaps" to gaps, "outOfBlock" to outOfBlock, "never" to never, "maxWait" to waits.values.max())
}
@Test fun orbitThreeFourWeeks() {
assumeTrue(dir != null && File(dir, "episodes-103.json").exists())
val programming = SmartChannels.first { it.number == 103 }
val committed = plan(File(dir, "schedule-103.json")); val series = pool(File(dir, "episodes-103.json"))
val before = programming.dayParts.map { if (it.fromHour == 18 && it.toHour == 22) it.copy(titles = it.titles + "Family Guy") else it }
val old = replay(committed, series, before, programming, null)
val new = replay(committed, series, programming.dayParts, programming, programming::weightOf)
val restarted = replay(committed, series, programming.dayParts, programming, programming::weightOf, restartEvery = 3)
assertEquals(committed.entries, old.take(committed.entries.size)); assertEquals(committed.entries, new.take(committed.entries.size))
assertEquals("a restart changes nothing", new, restarted)
val start = committed.endMs
val out = StringBuilder("Orbit Three: four weeks of new bookings after the committed plan (which ends ${java.time.Instant.ofEpochMilli(start).atZone(zone).toLocalDateTime()}),\n" +
"both rules topping up every six hours from the box's real committed plan and pool. Committed programmes are identical in both.\n\n")
report("Before: equal turns, finish together, Family Guy in the evening", old.filter { it.startMs >= start }, series, before, programming, out)
val after = report("After: weighted 3 / 2 / 1, Family Guy out of the evening", new.filter { it.startMs >= start }, series, programming.dayParts, programming, out)
// Scottish Comedy Night: every programme Friday and Saturday 21:00 to midnight is a Scottish show, presented as one.
val scottish = new.filter { it.startMs >= start }.filter { val l = java.time.Instant.ofEpochMilli(it.startMs).atZone(zone); l.dayOfWeek in setOf(java.time.DayOfWeek.FRIDAY, java.time.DayOfWeek.SATURDAY) && l.hour >= 21 }
out.appendLine("Scottish Comedy Night: ${scottish.size} programmes, all presented as three.scottish: ${scottish.all { it.presentation == "three.scottish" }}")
out.appendLine("Family Guy in the evening after: ${new.filter { it.startMs >= start }.count { e -> series.first { it.id == e.seriesId }.title == "Family Guy" }} airings")
out.appendLine("A save and reload every 18 hours gives the identical four weeks: true")
File(dir, "weighted-rotation-replay.txt").writeText(out.toString())
println(out)
assertTrue(scottish.isNotEmpty() && scottish.all { it.presentation == "three.scottish" })
assertEquals(0, after["sameFile"]); assertEquals(0, after["twice"]); assertEquals(0, after["backwards"]); assertEquals(0, after["gaps"]); assertEquals(0, after["outOfBlock"])
assertEquals(emptySet<String>(), after["never"])
}
}
@@ -0,0 +1,162 @@
package tv.orbit.classic
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.time.ZoneOffset
class WeightedRotationTest {
private val zone = ZoneOffset.UTC
private val day = 24 * 60 * 60_000L
private val start = java.time.LocalDate.of(2026, 11, 10).atStartOfDay(zone).toInstant().toEpochMilli()
private fun show(title: String, episodes: Int, minutes: Int = 25) =
PoolSeries(title, title, (1..episodes).map { PoolEpisode("$title-$it", "src", EpisodeMark(1 + (it - 1) / 10, 1 + (it - 1) % 10), "E$it", minutes * 60_000L) })
private fun weights(vararg pairs: Pair<String, Double>) = pairs.associate { seriesKey(it.first) to it.second }.let { w -> { s: PoolSeries -> w[seriesKey(s.title)] ?: TIER_SUPPORTING } }
private fun run(pool: List<PoolSeries>, weightOf: (PoolSeries) -> Double, days: Int = 28, parts: List<DayPart> = emptyList(), mixed: (PoolSeries) -> Boolean = { false }, cursor: ScheduleCursor = ScheduleCursor()) =
extendWeighted(pool, cursor, start, start + days * day, weightOf, parts, zone, { _, _, _ -> false }, false, mixed)
private fun minutes(plan: ChannelPlan) = plan.entries.groupBy { it.seriesId }.mapValues { (_, es) -> es.sumOf { it.media.durationMs } / 60_000.0 }
@Test fun airtimeFollowsTheTiersNotTheEpisodeCounts() {
val pool = listOf(show("Core", 300), show("Huge surprise", 457), show("Supporting", 400))
val m = minutes(run(pool, weights("Core" to TIER_CORE, "Huge surprise" to TIER_SURPRISE)))
// 3 : 1 : 2, whatever the episode counts.
assertEquals(3.0, m.getValue("Core") / m.getValue("Huge surprise"), 0.15)
assertEquals(1.5, m.getValue("Core") / m.getValue("Supporting"), 0.1)
}
@Test fun longEpisodesDontBuyExtraAirtime() {
val pool = listOf(show("Hour long", 200, 56), show("Half hour", 200, 25)) + (1..4).map { show("Other $it", 200) }
val m = minutes(run(pool, weights()))
assertEquals(1.0, m.getValue("Hour long") / m.getValue("Half hour"), 0.1)
}
@Test fun aLongSeriesCantHoldAShortOneHostageAndNothingStarves() {
// Three's old trap: the short shows have reached the end of their runs, a 457-episode show hasn't.
val pool = listOf(show("Gavin", 19), show("Spaced", 14), show("Huge", 457))
val atEnd = ScheduleCursor(marks = mapOf("Gavin" to pool[0].episodes.last().mark, "Spaced" to pool[1].episodes.last().mark))
val plan = run(pool, weights("Gavin" to TIER_CORE, "Spaced" to TIER_CORE, "Huge" to TIER_SURPRISE), cursor = atEnd)
for (title in listOf("Gavin", "Spaced", "Huge")) {
val times = listOf(start) + plan.entries.filter { it.seriesId == title }.map { it.startMs } + listOf(plan.entries.last().endMs)
val longest = times.zipWithNext().maxOf { (a, b) -> b - a }
assertTrue("$title waits ${longest / day.toDouble()} days", longest <= 4 * day)
}
}
@Test fun aShortSeriesDoesntRestartTooOftenAndComesBackWithoutABurst() {
val pool = listOf(show("Six parter", 6), show("Long A", 200), show("Long B", 200))
val plan = run(pool, weights("Six parter" to TIER_CORE))
val six = plan.entries.filter { it.seriesId == "Six parter" }
val starts = six.filter { it.mark == pool[0].episodes.first().mark }.map { it.startMs }
assertTrue(starts.size >= 5)
starts.zipWithNext().forEach { (a, b) -> assertTrue(b - a >= RUN_REST_MS) }
// Back from its rest it takes its turn with the others, never more than every other slot.
plan.entries.zipWithNext().forEach { (a, b) -> assertFalse(a.seriesId == b.seriesId) }
starts.drop(1).forEach { at -> val next = plan.entries.filter { it.startMs >= at }.take(6); assertTrue(next.count { it.seriesId == "Six parter" } <= 3) }
}
@Test fun aLongCoreSeriesCarriesStraightOnIntoItsNextRun() {
// Spaced's 14 episodes take more than three days at its share, so nothing holds it back at the end of a run.
val pool = listOf(show("Spaced", 14)) + (1..30).map { show("Other $it", 100) }
val plan = run(pool, weights("Spaced" to TIER_CORE))
val spaced = plan.entries.filter { it.seriesId == "Spaced" }
val waits = spaced.zipWithNext().map { (a, b) -> b.startMs - a.startMs }
val usual = waits.sorted()[waits.size / 2]
assertTrue(waits.map { it / 3_600_000.0 }.toString() + " usual ${usual / 3_600_000.0}", waits.max() <= 2 * usual)
}
@Test fun inOrderShowsStayInOrderAndShuffledShowsKeepTheirDeck() {
val story = show("Story", 18); val sketch = show("Sketch", 16)
val pool = listOf(story, sketch, show("Other", 30))
val mixed = { s: PoolSeries -> s.title == "Sketch" }
val plan = run(pool, weights("Story" to TIER_CORE), mixed = mixed)
val storyMarks = plan.entries.filter { it.seriesId == "Story" }.map { it.mark }
storyMarks.zipWithNext().forEach { (a, b) -> assertTrue(b > a || b == story.episodes.first().mark) }
// The sketch show plays its fixed shuffled deck in order, every episode before any repeat.
val deck = shuffledEpisodes(sketch).map { it.mark }
val sketchMarks = plan.entries.filter { it.seriesId == "Sketch" }.map { it.mark }
sketchMarks.forEachIndexed { i, mark -> assertEquals(deck[i % deck.size], mark) }
}
@Test fun aTopUpCarriesOnExactlyAsOneLongPlanWould() {
val pool = listOf(show("Story", 18), show("Sketch", 16), show("Long", 120), show("Odd", 6))
val w = weights("Story" to TIER_CORE, "Odd" to TIER_SURPRISE)
val mixed = { s: PoolSeries -> s.title == "Sketch" }
val whole = run(pool, w, days = 14, mixed = mixed)
val first = extendWeighted(pool, ScheduleCursor(), start, start + 7 * day, w, emptyList(), zone, { _, _, _ -> false }, false, mixed)
val recent = first.entries.filter { it.startMs >= first.endMs - SAME_FILE_MS }.associate { it.media.item.id to it.startMs }
val second = extendWeighted(pool, first.tail, first.endMs, start + 14 * day, w, emptyList(), zone, { _, _, _ -> false }, false, mixed, recent)
assertEquals(whole.entries.map { it.seriesId to it.mark }, (first.entries + second.entries).map { it.seriesId to it.mark })
}
@Test fun noShowTwiceRunningAndNoFileAgainWithin24Hours() {
val pool = listOf(show("A", 3), show("B", 40), show("C", 40))
val plan = run(pool, weights("A" to TIER_CORE))
plan.entries.zipWithNext().forEach { (a, b) -> assertFalse(a.seriesId == b.seriesId) }
plan.entries.groupBy { it.media.item.id }.values.forEach { es -> es.zipWithNext().forEach { (a, b) -> assertTrue(b.startMs - a.startMs >= SAME_FILE_MS) } }
}
@Test fun aShowJoiningLaterDoesntFloodTheBlock() {
val pool = listOf(show("A", 100), show("B", 100))
val week = run(pool, weights(), days = 7)
val joined = extendWeighted(pool + show("New", 100), week.tail, week.endMs, week.endMs + 7 * day, weights(), emptyList(), zone, { _, _, _ -> false }, false, { false })
// The newcomer takes its share, about a third, not every slot until it has caught up.
val share = joined.entries.count { it.seriesId == "New" }.toDouble() / joined.entries.size
assertEquals(1.0 / 3, share, 0.05)
}
@Test fun blocksAndEventsAreKept() {
val pool = listOf(show("Still Game", 50), show("Day show", 50), show("Late show", 50))
val parts = listOf(DayPart(21, 0, listOf("Still Game"), days = setOf(java.time.DayOfWeek.FRIDAY), key = "three.scottish"),
DayPart(6, 21, listOf("Day show", "Still Game")), DayPart(21, 6, listOf("Late show")))
val plan = run(pool, weights("Still Game" to TIER_CORE), parts = parts)
plan.entries.forEach { e ->
val l = java.time.Instant.ofEpochMilli(e.startMs).atZone(zone)
val expected = parts.first { it.covers(l.hour, l.dayOfWeek) }.titles
assertTrue("${e.seriesId} at $l", e.seriesId in expected)
if (l.dayOfWeek == java.time.DayOfWeek.FRIDAY && l.hour >= 21) assertEquals("three.scottish", e.presentation)
}
}
@Test fun aRestartBetweenTopUpsChangesNothingAndCommittedProgrammesStay() {
val pool = listOf(show("Story", 18), show("Sketch", 16), show("Long", 120), show("Odd", 6))
val w = weights("Story" to TIER_CORE, "Odd" to TIER_SURPRISE)
val mixed = { s: PoolSeries -> s.title == "Sketch" }
// A plan committed before the switch, by today's equal turns: it must come through untouched.
val committed = extendSchedule(pool, ScheduleCursor(), start, start + 7 * day, mixed = mixed, zone = zone)
val folder = java.nio.file.Files.createTempDirectory("weighted").toFile()
var straight: ChannelPlan = committed; var restarted: ChannelPlan = committed
val all = committed.entries.toMutableList(); val allRestarted = committed.entries.toMutableList()
var now = start + day
while (now < start + 28 * day) {
straight = topUpPlan(straight, straight.tail, pool, now, zone = zone, mixed = mixed, weightOf = w)!!
ScheduleStore(folder).savePlan("user", 103, restarted)
restarted = topUpPlan(ScheduleStore(folder).loadPlan("user", 103), ScheduleCursor(), pool, now, zone = zone, mixed = mixed, weightOf = w)!!
straight.entries.filter { e -> all.none { it.startMs == e.startMs } }.forEach { all += it }
restarted.entries.filter { e -> allRestarted.none { it.startMs == e.startMs } }.forEach { allRestarted += it }
now += 6 * 60 * 60_000L
}
assertEquals(all, allRestarted)
assertEquals(committed.entries, all.take(committed.entries.size))
assertTrue(all.size > 2 * committed.entries.size)
all.zipWithNext().forEach { (a, b) -> assertEquals(a.endMs, b.startMs) }
// The tallies and run starts came through the save as they went in.
assertEquals(straight.tail, ScheduleStore(folder).also { it.savePlan("user", 103, straight) }.loadPlan("user", 103)!!.tail)
// Story keeps its order across every top-up and restart; Sketch keeps its deck.
val story = all.filter { it.seriesId == "Story" }.map { it.mark }
story.zipWithNext().forEach { (a, b) -> assertTrue(b > a || b == pool[0].episodes.first().mark) }
val deck = shuffledEpisodes(pool[1]).map { it.mark }
val sketch = all.filter { it.seriesId == "Sketch" }.map { it.mark }
val at = deck.indexOf(sketch.first())
sketch.forEachIndexed { i, mark -> assertEquals(deck[(at + i) % deck.size], mark) }
}
@Test fun onlyOrbitThreeIsWeighted() {
assertEquals(listOf(103), SmartChannels.filter { it.tierWeights != null }.map { it.number })
val three = SmartChannels.first { it.number == 103 }
assertTrue(three.searches.none { seriesKey(it) == seriesKey("Family Guy") })
assertEquals(TIER_CORE, three.weightOf(show("Gavin & Stacey", 1)), 0.0)
assertEquals(TIER_SURPRISE, three.weightOf(show("Brass Eye", 1)), 0.0)
assertEquals(TIER_SUPPORTING, three.weightOf(show("Peep Show", 1)), 0.0)
}
}