0.99.13: story-aware episode grouping on Paradox (Living Network Stage A)
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 1m54s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m31s

Multi-part stories, verified from part markers and consecutive episodes only, are booked whole and back to back on
Paradox's weighted blocks; mixed decks keep each story as one card; no isolated later part is booked. Other channels
unchanged (fingerprints identical); committed bookings untouched.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-04 13:50:59 +00:00
co-authored by Claude Opus 5.5
parent a0ae85f669
commit 6343e8d254
12 changed files with 591 additions and 20 deletions
@@ -51,7 +51,7 @@ class ReplayFingerprintTest {
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, weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest) ?: break
shuffle = programming.shuffleEpisodes, mixed = programming::mixes, weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, stories = programming.storyGrouping) ?: break
current.entries.filter { e -> all.none { it.startMs == e.startMs } }.forEach { all += it }
now += 6 * 60 * 60_000L
}
@@ -0,0 +1,150 @@
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
/**
* Living Network Stage A's check: story grouping on Paradox, from copies of the box's files. Four weeks of new bookings
* after Paradox's committed plan, without grouping (0.99.12) and with it (as built), avoiding every other channel's
* programmes as the box does, and once more with a save and reload every 18 hours. Run by hand:
* ORBIT_REPLAY_DIR=<copies of the box's files> ./gradlew :app:testDebugUnitTest --tests '*StoryGroupingReplayTest*'
* Writes story-grouping-replay.txt there, and fails on any broken rule.
*/
class StoryGroupingReplayTest {
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>, programming: ChannelProgramming, stories: Boolean, avoid: ProgrammeClash = { _, _, _ -> false },
restartEvery: Int = 0, keepCommitted: Boolean = false): 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("stories").toFile()
var step = 0
while (now < end) {
if (restartEvery > 0 && ++step % restartEvery == 0) { ScheduleStore(folder).savePlan("user", programming.number, current); current = ScheduleStore(folder).loadPlan("user", programming.number)!! }
current = topUpPlan(current, current.tail, series, now, programming.filmRestMs, programming.finishTogether, programming.dayParts, zone, avoid,
shuffle = programming.shuffleEpisodes, mixed = programming::mixes, weightOf = programming.tierWeights?.let { programming::weightOf },
adaptiveRest = programming.adaptiveFilmRest, stories = stories) ?: break
current.entries.filter { e -> all.none { it.startMs == e.startMs } }.forEach { all += it }
now += 6 * hour
}
all.sortBy { it.startMs }
assertEquals("${programming.name}: committed programmes kept", committed.entries, all.take(committed.entries.size))
return if (keepCommitted) all.filter { it.startMs < end } else all.filter { it.startMs >= committed.endMs && it.startMs < end }
}
private fun pct(x: Double) = "%.0f%%".format(100 * x)
/** Parts booked, and how many aren't straight after their part before or straight before their next. */
private class StoryCount(val parts: Int, val stranded: Int, val whole: Int)
private fun storyCount(entries: List<ScheduleEntry>, series: List<PoolSeries>, only: (PoolSeries) -> Boolean = { true }): StoryCount {
val byId = series.associateBy { it.id }
val found = series.associate { it.id to storiesOf(it) }
var parts = 0; var stranded = 0; var whole = 0
entries.forEachIndexed { i, e ->
val show = byId[e.seriesId]?.takeIf(only) ?: return@forEachIndexed
val episode = show.episodes.firstOrNull { it.mark == e.mark } ?: return@forEachIndexed
val story = found.getValue(show.id).of(episode) ?: return@forEachIndexed
val k = story.parts.indexOfFirst { it.id == episode.id }
parts++
val before = entries.getOrNull(i - 1); val after = entries.getOrNull(i + 1)
val joinedBefore = k == 0 || (before != null && before.seriesId == e.seriesId && before.mark == story.parts[k - 1].mark && before.endMs == e.startMs)
// The last programme of the window can't show what follows it.
val joinedAfter = k == story.parts.size - 1 || after == null || (after.seriesId == e.seriesId && after.mark == story.parts[k + 1].mark && after.startMs == e.endMs)
if (!joinedBefore || !joinedAfter) stranded++
if (k == story.parts.size - 1 && joinedBefore && (0 until k).all { j -> entries.getOrNull(i - k + j)?.mark == story.parts[j].mark && entries[i - k + j].seriesId == e.seriesId }) whole++
}
return StoryCount(parts, stranded, whole)
}
@Test fun paradox() {
assumeTrue(dir != null && dir.isDirectory)
val programming = SmartChannels.first { it.number == 106 }
assertTrue(programming.storyGrouping)
val committed = plan(File(dir, "schedule-106.json")); val series = pool(File(dir, "episodes-106.json"))
val baseline = SmartChannels.filter { it.number != 106 && File(dir, "schedule-${it.number}.json").exists() && File(dir, "episodes-${it.number}.json").exists() }.map { p ->
replay(plan(File(dir, "schedule-${p.number}.json")), pool(File(dir, "episodes-${p.number}.json")), p, p.storyGrouping, keepCommitted = true)
}
val others = clashesWith(baseline.map { ChannelPlan(it, ScheduleCursor()) })
val out = StringBuilder("Stage A: story grouping on Paradox. Four weeks of new bookings after the committed plan (ends " +
"${java.time.Instant.ofEpochMilli(committed.endMs).atZone(zone).toLocalDateTime().withNano(0)}), avoiding every other channel's programmes.\n\n")
out.appendLine("Stories found in Paradox's pool (verified markers only):")
series.sortedBy { it.title }.forEach { s ->
val found = storiesOf(s).stories
val marked = s.episodes.count { partNumber(it.title) != null }
if (marked > 0) out.appendLine(" ${s.title}: ${s.episodes.size} episodes, $marked marked, ${found.size} stories (" +
found.groupingBy { it.parts.size }.eachCount().toSortedMap().entries.joinToString { "${it.value} of ${it.key} parts" } + "), ${marked - found.sumOf { it.parts.size }} marked but unverified, left as they are")
}
out.appendLine()
val committedCount = storyCount(committed.entries, series)
val committedWho = storyCount(committed.entries, series) { it.title.startsWith("Doctor Who") }
out.appendLine("Committed plan (unchanged): ${committedCount.parts} story parts booked, ${committedCount.stranded} stranded; Doctor Who ${committedWho.parts} parts, ${committedWho.stranded} stranded")
val before = replay(committed, series, programming, false, others)
val after = replay(committed, series, programming, true, others)
val restarted = replay(committed, series, programming, true, others, restartEvery = 3)
assertEquals("a restart changes nothing", after, restarted)
val byId = series.associateBy { it.id }
fun decks(grouped: Boolean) = series.filter { programming.mixes(it) }.associate { s -> s.id to (if (grouped) shuffledStories(s, storiesOf(s)) else shuffledEpisodes(s)).map { it.mark } }
val ordered = series.filter { !programming.mixes(it) }.associateBy { it.id }
fun block(e: ScheduleEntry) = dayPartFor(series, programming.dayParts, e.startMs, zone)
val results = mutableMapOf<String, Int>()
for ((label, entries) in listOf("0.99.12, no grouping" to before, "Stage A, grouping" to after)) {
val all = storyCount(entries, series); val who = storyCount(entries, series) { it.title.startsWith("Doctor Who") }
val minutes = entries.groupBy { block(it).second }.mapValues { (_, es) -> es.groupBy { byId.getValue(it.seriesId).title }.mapValues { (_, x) -> x.sumOf { it.media.durationMs } / 60_000.0 } }
out.appendLine("== $label: ${entries.size} programmes")
out.appendLine(" story parts booked ${all.parts}, stranded ${all.stranded}, complete stories ${all.whole}; Doctor Who parts ${who.parts}, stranded ${who.stranded}, complete stories ${who.whole}")
minutes.toSortedMap().forEach { (b, m) -> val total = m.values.sum()
out.appendLine(" $b: " + m.entries.sortedByDescending { it.value }.joinToString { "${it.key} ${pct(it.value / total)}" }) }
val sameDay = entries.groupBy { it.media.item.id }.values.sumOf { es -> es.zipWithNext().count { (a, b) -> b.startMs - a.startMs < day } }
val twice = entries.zipWithNext().count { (a, b) -> a.seriesId == b.seriesId && "story: part" !in b.why && "air elsewhere then" !in b.why && "airs elsewhere then" !in b.why }
val back = 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 decks = decks(label.startsWith("Stage A"))
val offDeck = entries.filter { it.seriesId in decks }.groupBy { it.seriesId }.entries.sumOf { (id, es) -> val d = decks.getValue(id); es.zipWithNext().count { (a, b) -> d[(d.indexOf(a.mark) + 1) % d.size] != b.mark } }
val gaps = entries.zipWithNext().count { (a, b) -> a.endMs != b.startMs }
val outside = entries.count { e -> block(e).first.none { it.id == e.seriesId } }
val clashes = entries.count { others(byId.getValue(it.seriesId), it.startMs, it.endMs) }
val never = series.filter { s -> programming.dayParts.any { p -> p.titles.any { seriesKey(it) == seriesKey(s.title) } } && entries.none { it.seriesId == s.id } }.map { it.title }
out.appendLine(" rules: same file within 24 h $sameDay; same show twice running (not a story) $twice; in-order stepping back $back; off the grouped deck $offDeck; gaps $gaps; outside its block $outside; on another channel at the same time $clashes; never aired ${never.ifEmpty { listOf("none") }.joinToString()}")
if (label.startsWith("Stage A")) results.putAll(mapOf("stranded" to all.stranded, "sameDay" to sameDay, "twice" to twice, "back" to back, "offDeck" to offDeck, "gaps" to gaps, "outside" to outside, "clashes" to clashes, "never" to never.size))
}
out.appendLine("a save and reload every 18 hours gives the identical four weeks: true")
File(dir, "story-grouping-replay.txt").writeText(out.toString())
println(out)
for (key in listOf("stranded", "sameDay", "twice", "back", "offDeck", "gaps", "outside", "clashes", "never")) assertEquals(key, 0, results[key])
}
}
@@ -0,0 +1,135 @@
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 StoryGroupingTest {
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 ep(show: String, season: Int, episode: Int, title: String, minutes: Int = 45) = PoolEpisode("$show-$season-$episode", "src", EpisodeMark(season, episode), title, minutes * 60_000L)
private fun show(title: String, vararg episodes: PoolEpisode) = PoolSeries(title, title, episodes.toList())
private fun plain(title: String, count: Int, minutes: Int = 45) = PoolSeries(title, title, (1..count).map { ep(title, 1 + (it - 1) / 10, 1 + (it - 1) % 10, "Story $it", minutes) })
/** A Doctor Who-like series: standalones, two-parters, a three-parter, a six-parter and a cliffhanger across seasons. */
private val who = show("Who",
ep("Who", 1, 1, "Rose"), ep("Who", 1, 2, "Aliens of London (1)"), ep("Who", 1, 3, "World War Three (2)"), ep("Who", 1, 4, "Dalek"),
ep("Who", 1, 5, "Utopia (1)"), ep("Who", 1, 6, "The Sound of Drums (2)"), ep("Who", 1, 7, "Last of the Time Lords (3)"), ep("Who", 1, 8, "Blink"),
ep("Who", 1, 9, "Spyfall (1)", 60), ep("Who", 1, 10, "Spyfall (2)", 60), ep("Who", 1, 11, "Midnight"), ep("Who", 1, 12, "Bad Wolf (1)"),
ep("Who", 2, 1, "The Parting of the Ways (2)"), ep("Who", 2, 2, "Boom Town"),
ep("Who", 2, 3, "Flux (1)", 50), ep("Who", 2, 4, "Flux (2)", 59), ep("Who", 2, 5, "Flux (3)", 49), ep("Who", 2, 6, "Flux (4)", 56), ep("Who", 2, 7, "Flux (5)", 50), ep("Who", 2, 8, "Flux (6)", 59),
ep("Who", 2, 9, "Gridlock"), ep("Who", 2, 10, "Fear Her"), ep("Who", 2, 11, "Love and Monsters"), ep("Who", 2, 12, "42"))
@Test fun storiesAreFoundFromVerifiedMarkersOnly() {
val found = storiesOf(who).stories.map { story -> story.parts.map { it.title } }
assertEquals(listOf(
listOf("Aliens of London (1)", "World War Three (2)"),
listOf("Utopia (1)", "The Sound of Drums (2)", "Last of the Time Lords (3)"),
listOf("Spyfall (1)", "Spyfall (2)"),
// A season's last episode into the next one's first.
listOf("Bad Wolf (1)", "The Parting of the Ways (2)"),
listOf("Flux (1)", "Flux (2)", "Flux (3)", "Flux (4)", "Flux (5)", "Flux (6)")), found)
}
@Test fun anythingUncertainIsNotAStory() {
val odd = show("Odd",
// Orphans: a part 2 with no marked part 1, and a part 1 with no part 2.
ep("Odd", 1, 1, "The Blessing Way (2)"), ep("Odd", 1, 2, "Nisei (1)"), ep("Odd", 1, 3, "731"),
// Not consecutive.
ep("Odd", 1, 4, "Gap (1)"), ep("Odd", 1, 6, "Gap (2)"),
// Both halves in one file.
ep("Odd", 1, 7, "Encounter at Farpoint (1), Encounter at Farpoint (2)"),
// A season break that isn't a season's end.
ep("Odd", 2, 3, "Early (1)"), ep("Odd", 3, 1, "Early (2)"), ep("Odd", 2, 9, "Finale"),
// Seven parts is a serial, not a story.
*(1..7).map { ep("Odd", 4, it, "Chapter Part $it") }.toTypedArray())
assertTrue(storiesOf(odd).stories.isEmpty())
// "Part One" and "Part II" count as markers.
val worded = show("Worded", ep("Worded", 1, 1, "Descent, Part One"), ep("Worded", 1, 2, "Descent, Part Two"), ep("Worded", 1, 3, "Unity Part I"), ep("Worded", 1, 4, "Unity Part II"))
assertEquals(2, storiesOf(worded).stories.size)
}
private val parts = listOf(DayPart(6, 18, listOf("Who", "Trek", "Files", "Sliders")), DayPart(18, 6, listOf("Buffy", "Fringe")))
private val pool = listOf(who, plain("Trek", 80), plain("Files", 60), plain("Sliders", 40), plain("Buffy", 60), plain("Fringe", 60))
private fun mixedWho(s: PoolSeries) = s.title in setOf("Who", "Trek", "Files", "Sliders")
private fun run(cursor: ScheduleCursor = ScheduleCursor(), from: Long = start, until: Long = start + 28 * day, stories: Boolean = true, pool: List<PoolSeries> = this.pool,
mixed: (PoolSeries) -> Boolean = ::mixedWho, avoid: ProgrammeClash = { _, _, _ -> false }) =
extendWeighted(pool, cursor, from, until, { TIER_SUPPORTING }, parts, zone, avoid, false, mixed, stories = stories)
/** Every part airs straight after the part before it, every story airs whole, and none crosses out of its block. */
private fun assertWhole(entries: List<ScheduleEntry>, show: PoolSeries) {
val stories = storiesOf(show)
entries.forEachIndexed { i, entry ->
val episode = show.episodes.firstOrNull { it.mark == entry.mark && entry.seriesId == show.id } ?: return@forEachIndexed
val story = stories.of(episode) ?: return@forEachIndexed
val part = stories.partOf(episode)
if (part > 0) {
val before = entries.getOrNull(i - 1)
assertTrue("${episode.title} at $i isn't straight after its part before", before != null && before.seriesId == show.id && before.mark == story.parts[part - 1].mark && before.endMs == entry.startMs)
}
if (part < story.parts.size - 1 && i < entries.size - 1) assertEquals("${episode.title} isn't followed by its next part", story.parts[part + 1].mark, entries[i + 1].mark)
val hour = java.time.Instant.ofEpochMilli(entry.startMs).atZone(zone).hour
assertTrue("${episode.title} starts outside its block at $hour", hour in 6 until 18)
}
}
@Test fun aMixedShowAirsEachStoryWholeAndInOrder() {
val plan = run()
assertWhole(plan.entries, who)
val aired = plan.entries.filter { it.seriesId == "Who" }.map { it.mark }.toSet()
// Every story and standalone comes round in four weeks.
assertEquals(who.episodes.map { it.mark }.toSet(), aired)
assertTrue(plan.entries.any { it.why.contains("story: part 6 of 6") })
}
@Test fun anInOrderShowCarriesStraightOnThroughItsStory() {
val plan = run(mixed = { false })
assertWhole(plan.entries, who)
// In order, its progression is untouched: each episode follows the one before in season order.
val marks = plan.entries.filter { it.seriesId == "Who" }.map { it.mark }
marks.zipWithNext().forEach { (a, b) -> assertTrue(b > a || b == who.episodes.first().mark) }
}
@Test fun aStoryThatWouldCrossItsBlockOrClashWaits() {
// Another channel shows Who all afternoon, so no story may start where any of its parts would meet it.
val busy: ProgrammeClash = { s, from, to -> s.title == "Who" && java.time.Instant.ofEpochMilli(from).atZone(zone).hour.let { it in 12..17 } ||
s.title == "Who" && java.time.Instant.ofEpochMilli(to - 1).atZone(zone).hour.let { it in 12..17 } }
val plan = run(avoid = busy)
assertWhole(plan.entries, who)
plan.entries.filter { it.seriesId == "Who" }.forEach { assertFalse(busy(who, it.startMs, it.endMs)) }
}
@Test fun aTopUpPartWayThroughAStoryCarriesOn() {
val whole = run()
// Cut the plan straight after a part 1, as a top-up would, and carry on from its cursor.
val cut = whole.entries.indexOfFirst { it.why.contains("part 1 of 6") }
val first = run(until = whole.entries[cut].endMs)
assertEquals(whole.entries.take(cut + 1), first.entries)
val second = run(cursor = first.tail, from = first.entries.last().endMs)
assertEquals(whole.entries.drop(cut + 1).take(5), second.entries.take(5))
assertTrue(second.entries.first().why.contains("story: part 2 of 6"))
}
@Test fun aStoryCutOffBeforeGroupingNeverRestartsMidWay() {
// Today's committed plans have lone first parts; the deck carries on from one without opening on its part 2.
val stranded = ScheduleCursor(lastSeriesId = "Trek", marks = mapOf("Who" to who.episodes.first { it.title == "Aliens of London (1)" }.mark))
val plan = run(cursor = stranded)
val whoEntries = plan.entries.filter { it.seriesId == "Who" }
assertFalse(whoEntries.first().mark == who.episodes.first { it.title == "World War Three (2)" }.mark)
assertWhole(plan.entries, who)
}
@Test fun withoutStoriesNothingChanges() {
// A pool with no markers plans exactly the same with grouping on or off.
val unmarked = pool.map { s -> s.copy(episodes = s.episodes.map { it.copy(title = it.title.replace(Regex("""\s*\(\d\)$"""), "")) }) }
assertEquals(run(pool = unmarked, stories = false), run(pool = unmarked, stories = true))
}
@Test fun onlyParadoxGroupsStories() {
assertEquals(listOf(106), SmartChannels.filter { it.storyGrouping }.map { it.number })
assertTrue(SmartChannels.first { it.number == 106 }.tierWeights != null)
}
}