Final 31-channel network audit (read-only): all hard rules pass; findings for decision
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 1m42s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m36s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-04 10:21:42 +00:00
co-authored by Claude Opus 5.5
parent 036b82b78a
commit e7493b9c51
3 changed files with 268 additions and 0 deletions
@@ -0,0 +1,145 @@
package tv.orbit.classic
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
/**
* The final network audit (4 November 2026), read-only, from copies of the box's files:
* ORBIT_REPLAY_DIR=<copies of the box's files> ./gradlew :app:testDebugUnitTest --tests '*FinalNetworkAuditTest*'
* Every channel tops up every six hours for four weeks, in turn, each avoiding the others' plans as they stand, exactly
* as the app is configured. Checks every channel's pool, scheduler, tiers, blocks and events, episode order, clashes,
* film rest, fairness and presentation keys over the new bookings after its committed plan, and writes
* final-network-audit.md. Fails on any broken rule.
*/
class FinalNetworkAuditTest {
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"))
}
val tallies = t.optJSONObject("tallies")?.let { all -> all.keys().asSequence().associateWith { b -> all.getJSONObject(b).let { r -> r.keys().asSequence().associateWith { r.getDouble(it) } } } }.orEmpty()
val runs = t.optJSONObject("runs")?.let { r -> r.keys().asSequence().associateWith { r.getLong(it) } }.orEmpty()
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(), tallies, runs))
}
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 local(ms: Long) = java.time.Instant.ofEpochMilli(ms).atZone(zone)
private fun pct(x: Double) = "%.0f%%".format(100 * x)
@Test fun network() {
assumeTrue(dir != null && dir.isDirectory)
val channels = SmartChannels.filter { File(dir, "schedule-${it.number}.json").exists() && File(dir, "episodes-${it.number}.json").exists() }.sortedBy { it.number }
val pools = channels.associate { it.number to pool(File(dir, "episodes-${it.number}.json")) }
val committed = channels.associate { it.number to plan(File(dir, "schedule-${it.number}.json")) }
val driveIn = File(dir, "schedule-$DRIVE_IN_NUMBER.json").takeIf { it.exists() }?.let(::plan)
val current = HashMap<Int, ChannelPlan>(committed)
val all = committed.mapValues { it.value.entries.toMutableList() }
val start = committed.values.minOf { it.entries.first().startMs } + SCHEDULE_KEEP_PAST_MS
var now = start
while (now < start + 35 * day) {
for (p in channels) {
val others = clashesWith(current.filterKeys { it != p.number }.values.toList() + listOfNotNull(driveIn))
val before = current.getValue(p.number)
current[p.number] = topUpPlan(before, before.tail, pools.getValue(p.number), now, p.filmRestMs, p.finishTogether, p.dayParts, zone, others,
shuffle = p.shuffleEpisodes, mixed = p::mixes, weightOf = p.tierWeights?.let { p::weightOf }, adaptiveRest = p.adaptiveFilmRest) ?: before
current.getValue(p.number).entries.filter { e -> all.getValue(p.number).none { it.startMs == e.startMs } }.forEach { all.getValue(p.number) += it }
}
now += 6 * hour
}
val md = StringBuilder("# Final network audit\n\nRead-only, from copies of the box's files. Every channel booked four weeks beyond its committed plan, all channels together, each avoiding the others as the box does, with the app exactly as configured.\n\n")
md.appendLine("| Ch | Channel | Scheduler | Pool | List unmatched | Core / supp / surprise airtime | Never aired | Longest wait | Same file <24 h / <7 d | Twice running | Back / off deck | Gaps / outside block | Clashes | Keyed blocks booked |")
md.appendLine("|---|---|---|---|---|---|---|---|---|---|---|---|---|---|")
val notes = StringBuilder()
var hardFailures = 0
// Clashes across the whole network, new bookings only.
val newOnly = all.mapValues { (n, es) -> es.filter { it.startMs >= committed.getValue(n).endMs && it.startMs < committed.getValue(n).endMs + 28 * day } }
val byTitle = newOnly.flatMap { (n, es) -> es.map { n to it } }.groupBy { seriesKey(it.second.media.item.title.substringBefore(" / ")) }
val clashCount = HashMap<Int, Int>()
byTitle.values.forEach { list -> list.forEachIndexed { i, a -> list.drop(i + 1).forEach { b ->
if (a.first != b.first && a.second.startMs < b.second.endMs && b.second.startMs < a.second.endMs) { clashCount.merge(a.first, 1, Int::plus); clashCount.merge(b.first, 1, Int::plus) }
} } }
for (p in channels) {
val series = pools.getValue(p.number); val byId = series.associateBy { it.id }
val entries = newOnly.getValue(p.number).sortedBy { it.startMs }
if (entries.isEmpty()) { md.appendLine("| ${p.number} | ${p.name} | | | | | | | | | | | | no new bookings |"); continue }
val scheduler = when {
p.filmRestMs != null -> "films, rest " + (if (p.adaptiveFilmRest) "adaptive" else "${p.filmRestMs / day} d")
p.tierWeights == null -> "equal turns"
p.catalogueScaleHours != null -> "weighted + hybrid"
p.dayParts.any { !it.weighted } -> "weighted (part)"
else -> "weighted"
}
val keys = series.map { seriesKey(it.title) }.toSet() + series.map { seriesKey(FilmIdentity.of(it.title).title) }
val unmatched = p.searches.count { seriesKey(it) !in keys && seriesKey(FilmIdentity.of(it).title) !in keys }
fun weightedAt(e: ScheduleEntry) = p.tierWeights != null && dayPartFor(series, p.dayParts, e.startMs, zone).third?.weighted != false
fun choice(e: ScheduleEntry) = dayPartFor(series, p.dayParts, e.startMs, zone).first.size > 1
val tierOf = { id: String -> when (p.tierWeights?.get(seriesKey(byId[id]?.title ?: "")) ?: TIER_SUPPORTING) { TIER_CORE -> 0; TIER_SURPRISE -> 2; else -> 1 } }
val minutes = entries.groupBy { it.seriesId }.mapValues { (_, x) -> x.sumOf { it.media.durationMs } / 60_000.0 }; val total = minutes.values.sum()
val tiers = (0..2).map { t -> minutes.filterKeys { tierOf(it) == t }.values.sum() / total }
val inBlocks = series.filter { s -> p.dayParts.isEmpty() || p.dayParts.any { part -> dayPartFor(series, listOf(part), part.let { java.time.LocalDate.of(2026, 11, 16).atTime(it.fromHour, 30).atZone(zone).toInstant().toEpochMilli() }, zone).first.any { it.id == s.id } } }
val first = entries.first().startMs; val last = entries.last().endMs
val isFilmChannel = p.filmRestMs != null
val never = if (isFilmChannel) emptyList() else inBlocks.filter { s -> !s.isFilm && entries.none { it.seriesId == s.id } }.map { it.title }
val waits = if (isFilmChannel) emptyMap() else inBlocks.filter { !it.isFilm }.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() }
val fileGaps = entries.groupBy { it.media.item.id }.values.flatMap { es -> es.zipWithNext().map { (a, b) -> b.startMs - a.startMs to b } }
val sameDay = fileGaps.count { (g, b) -> g < day && (weightedAt(b) || isFilmChannel) }
val sameWeek = fileGaps.count { it.first < 7 * day }
val twice = if (isFilmChannel) 0 else entries.zipWithNext().count { (a, b) -> a.seriesId == b.seriesId && weightedAt(b) && choice(b) && "elsewhere then" !in b.why }
val ordered = series.filter { !(p.shuffleEpisodes || p.mixes(it)) && !it.isFilm }.associateBy { it.id }
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 = series.filter { (p.shuffleEpisodes || p.mixes(it)) && !it.isFilm }.associate { s -> s.id to shuffledEpisodes(s).map { it.mark } }
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 -> dayPartFor(series, p.dayParts, e.startMs, zone).first.none { it.id == e.seriesId } && "fallback" !in e.why && !(isFilmChannel) }
val keyed = p.dayParts.filter { it.key.isNotEmpty() }
val keyedBooked = keyed.map { part -> part.key to entries.count { it.presentation == part.key } }
md.appendLine("| ${p.number} | ${p.name} | $scheduler | ${series.size} | $unmatched | ${if (p.tierWeights != null) tiers.joinToString(" / ") { pct(it) } else "n/a"} | ${never.size} | ${if (waits.isEmpty()) "n/a" else "%.1f d".format(waits.values.max())} | $sameDay / $sameWeek | $twice | $back / $offDeck | $gaps / $outside | ${clashCount[p.number] ?: 0} | ${keyedBooked.joinToString(", ") { "${it.first.substringAfter('.')} ${it.second}" }.ifEmpty { "none" }} |")
if (never.isNotEmpty()) notes.appendLine("- ${p.name}: never aired in four weeks: ${never.joinToString()}")
keyedBooked.filter { it.second == 0 }.forEach { notes.appendLine("- ${p.name}: no booking carried the ${it.first} key in four weeks") }
if (isFilmChannel) {
val films = entries.filter { it.media.item.type == "Movie" }
val g = films.groupBy { it.media.item.id }.values.flatMap { es -> es.zipWithNext().map { (a, b) -> (b.startMs - a.startMs) / day.toDouble() } }.sorted()
notes.appendLine("- ${p.name}: ${films.map { it.media.item.id }.distinct().size} different films of ${series.count { it.isFilm }}; repeat gap median ${"%.1f".format(g.getOrElse(g.size / 2) { 0.0 })} d, shortest ${"%.1f".format(g.firstOrNull() ?: 0.0)} d; fixed-order fallbacks ${films.count { "no film past its rest" in it.why }}")
}
// Recurring events and appointments: how late each starts.
p.dayParts.filter { it.days.isNotEmpty() || it.onTime }.forEach { part ->
val nights = entries.filter { e -> dayPartFor(series, listOf(part), e.startMs, zone).third == part && (part.key.isEmpty() || e.presentation == part.key) }
.groupBy { local(it.startMs).toLocalDate().let { d -> if (local(it.startMs).hour < part.fromHour && part.fromHour > part.toHour) d.minusDays(1) else d } }
val lates = nights.map { (date, es) -> (es.minOf { it.startMs } - date.atTime(part.fromHour, 0).atZone(zone).toInstant().toEpochMilli()) / 60_000 }
if (lates.isNotEmpty()) notes.appendLine("- ${p.name} ${part.key.ifEmpty { "event ${part.fromHour}-${part.toHour}" }}${if (part.onTime) " (appointment)" else ""}: ${lates.size} occurrences, first programme starts ${lates.min()} to ${lates.max()} min after ${part.fromHour}:00, median ${lates.sorted()[lates.size / 2]}")
else notes.appendLine("- ${p.name} ${part.key.ifEmpty { "event ${part.fromHour}-${part.toHour}" }}: no occurrence booked in four weeks")
}
// Hard rules.
val kept = all.getValue(p.number).sortedBy { it.startMs }.take(committed.getValue(p.number).entries.size) == committed.getValue(p.number).entries
val failures = listOf("committed kept" to (if (kept) 0 else 1), "gaps" to gaps, "in-order stepping back" to back, "off deck" to offDeck, "same file within 24 h (weighted)" to sameDay.takeIf { p.tierWeights != null }.let { it ?: 0 },
"twice running with a choice (weighted)" to twice, "clashes" to (clashCount[p.number] ?: 0)).filter { it.second > 0 }
failures.forEach { (what, n) -> notes.appendLine("- **${p.name}: $what $n**"); hardFailures++ }
}
md.appendLine().appendLine("## Notes").appendLine().append(notes)
File(dir, "final-network-audit.md").writeText(md.toString())
println(md)
assertEquals("hard-rule failures (see final-network-audit.md)", 0, hardFailures)
}
}