Stage 4: read-only schedule audit replay (ScheduleAuditTest) and its first results
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Stage 4's read-only audit, run by hand on copies of the box's files (never the box itself):
|
||||
* ORBIT_REPLAY_DIR=<folder with schedule-, episodes- and progress-NNN.json> ./gradlew :app:testDebugUnitTest --tests '*ScheduleAuditTest*'
|
||||
* Plays each smart channel forward four weeks from its committed plan with today's rules, and writes schedule-audit.md
|
||||
* there: what each channel's list finds, how its blocks are followed, rotation, repeats, rest, gaps and what never airs.
|
||||
*/
|
||||
class ScheduleAuditTest {
|
||||
private val dir = System.getenv("ORBIT_REPLAY_DIR")?.let(::File)
|
||||
private val zone = java.time.ZoneId.of("Europe/London")
|
||||
private val hour = 60 * 60_000L
|
||||
private val day = 24 * hour
|
||||
|
||||
private fun plan(file: File): ChannelPlan {
|
||||
val root = JSONObject(file.readText())
|
||||
val rows = root.getJSONArray("entries")
|
||||
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 t = root.getJSONObject("tail"); val marks = t.getJSONObject("marks")
|
||||
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 pct(a: Int, b: Int) = if (b == 0) "-" else "${(100.0 * a / b).toInt()}%"
|
||||
private fun hours(ms: Long) = "%.0f h".format(ms / 3_600_000.0)
|
||||
|
||||
@Test fun auditFourWeeks() {
|
||||
assumeTrue(dir != null && dir.isDirectory)
|
||||
val md = StringBuilder("# Schedule audit replay (read-only)\n\nFour weeks from each channel's committed plan, with today's rules, on copies of the box's real pools. " +
|
||||
"\"Committed\" is the plan on the box now; \"New\" is what today's rules book after it.\n")
|
||||
val allPlans = mutableMapOf<Int, List<ScheduleEntry>>()
|
||||
for (programming in SmartChannels) {
|
||||
val number = programming.number
|
||||
val pf = File(dir, "schedule-$number.json"); val sf = File(dir, "episodes-$number.json")
|
||||
if (!pf.exists() || !sf.exists()) { md.append("\n## $number ${programming.name}\n\nNo plan or pool on the box.\n"); continue }
|
||||
val committed = plan(pf); val series = pool(sf)
|
||||
val all = committed.entries.toMutableList()
|
||||
var current = committed
|
||||
var now = committed.entries.first().startMs + SCHEDULE_KEEP_PAST_MS
|
||||
val end = now + 28 * day
|
||||
while (now < end) {
|
||||
current = topUpPlan(current, current.tail, series, now, programming.filmRestMs, programming.finishTogether, programming.dayParts, zone,
|
||||
shuffle = programming.shuffleEpisodes, mixed = programming::mixes) ?: break
|
||||
val known = all.map { it.startMs }.toHashSet()
|
||||
current.entries.filter { it.startMs !in known }.forEach { all += it }
|
||||
now += 6 * hour
|
||||
}
|
||||
all.sortBy { it.startMs }
|
||||
allPlans[number] = all
|
||||
val committedEnd = committed.endMs
|
||||
val fresh = all.filter { it.startMs >= committedEnd }
|
||||
// The steady state: three weeks of new bookings.
|
||||
val steady = fresh.filter { it.startMs < committedEnd + 21 * day }
|
||||
val listed = programming.searches.map(::seriesKey).toSet()
|
||||
val found = series.map { seriesKey(it.title) }.toSet()
|
||||
val filmChannel = programming.filmRestMs != null
|
||||
md.append("\n## $number ${programming.name}\n\n")
|
||||
md.append("- **Pool:** ${series.size} ${if (filmChannel) "films" else "shows"}, ${series.sumOf { it.episodes.size }} files. List names ${programming.searches.size}; ")
|
||||
val missing = programming.searches.filter { name -> seriesKey(name) !in found && seriesKey(FilmIdentity.of(name).title) !in found }
|
||||
md.append("not in the pool: ${missing.size}" + if (missing.isNotEmpty()) " (${missing.take(12).joinToString()}${if (missing.size > 12) ", +${missing.size - 12}" else ""})" else "")
|
||||
val extras = series.filter { seriesKey(it.title) !in listed && programming.searches.none { n -> seriesKey(FilmIdentity.of(n).title) == seriesKey(it.title) } }
|
||||
if (extras.isNotEmpty()) md.append("; in the pool but not on the list: ${extras.size} (${extras.take(8).joinToString { it.title }})")
|
||||
md.append(".\n")
|
||||
md.append("- **Committed plan:** ${committed.entries.size} programmes to ${java.time.Instant.ofEpochMilli(committedEnd).atZone(zone).toLocalDate()}; reasons recorded on ${committed.entries.count { it.why.isNotEmpty() }}; " +
|
||||
"booked from today's blocks: ${committed.entries.count { e -> val r = e.why.substringBefore(';'); r.isNotEmpty() && programming.dayParts.any { p -> r == (if (p.days.isNotEmpty()) "event " else "block ") + p.group.ifEmpty { "${p.fromHour}-${p.toHour}" } } }}.\n")
|
||||
// Blocks: of the new bookings in each block's hours, how many come from its own titles.
|
||||
if (programming.dayParts.isNotEmpty() && steady.isNotEmpty()) {
|
||||
md.append("- **Blocks (new bookings, 3 weeks):** ")
|
||||
md.append(programming.dayParts.joinToString("; ") { part ->
|
||||
val keys = part.titles.map(::seriesKey).toSet() + part.titles.map { seriesKey(FilmIdentity.of(it).title) }
|
||||
val inHours = steady.filter { e -> val l = java.time.Instant.ofEpochMilli(e.startMs).atZone(zone); part.covers(l.hour, l.dayOfWeek) }
|
||||
val own = inHours.count { e -> seriesKey(guideTitleParts(e.media.item.title).first) in keys || seriesKey(e.media.item.title) in keys || (part.group.isNotEmpty()) }
|
||||
val label = (if (part.key.isNotEmpty()) part.key else "${part.fromHour}-${part.toHour}") + if (part.days.isNotEmpty()) " ${part.days.joinToString("") { it.name.take(2) }}" else ""
|
||||
"$label ${pct(own, inHours.size)} of ${inHours.size}"
|
||||
})
|
||||
md.append(".\n")
|
||||
}
|
||||
// Fallbacks and deferrals the planner recorded.
|
||||
val fallbacks = steady.count { "fallback" in it.why }; val noBlock = steady.count { it.why.startsWith("no block") }
|
||||
if (fallbacks + noBlock > 0) md.append("- **Planner fallbacks (3 weeks):** $fallbacks fallback, $noBlock outside any block.\n")
|
||||
// Airtime and waits, by show.
|
||||
val airtime = steady.groupBy { it.seriesId }.mapValues { (_, es) -> es.sumOf { it.media.durationMs } }
|
||||
val total = airtime.values.sum().coerceAtLeast(1)
|
||||
val never = series.filter { it.id !in airtime }
|
||||
val top = airtime.entries.sortedByDescending { it.value }.take(5).map { (id, ms) -> "${series.firstOrNull { it.id == id }?.title ?: id} ${(100 * ms / total)}%" }
|
||||
md.append("- **Airtime (3 weeks):** ${airtime.size} of ${series.size} aired; biggest shares: ${top.joinToString()}.")
|
||||
if (never.isNotEmpty()) md.append(" Never aired: ${never.size} (${never.take(10).joinToString { it.title }}${if (never.size > 10) ", +${never.size - 10}" else ""}).")
|
||||
md.append("\n")
|
||||
// Repeats: the same file twice within 24 hours or 7 days, and films inside their rest.
|
||||
val byFile = steady.groupBy { it.media.item.id }
|
||||
val within = { gap: Long -> byFile.values.sumOf { es -> es.sortedBy { it.startMs }.zipWithNext().count { (a, b) -> b.startMs - a.startMs < gap } } }
|
||||
md.append("- **Repeats (3 weeks):** same file again within 24 h: ${within(day)}; within 7 days: ${within(7 * day)}")
|
||||
programming.filmRestMs?.let { md.append(" (rest is ${hours(it)})") }
|
||||
md.append(".\n")
|
||||
// Progression: an in-order show should never step backwards except to start again.
|
||||
val backwards = steady.filter { !programming.mixes(series.firstOrNull { s -> s.id == it.seriesId } ?: return@filter false) && !programming.shuffleEpisodes }
|
||||
.groupBy { it.seriesId }.values.sumOf { es -> es.zipWithNext().count { (a, b) -> b.mark < a.mark && b.mark != EpisodeMark(series.first { it.id == a.seriesId }.episodes.first().mark.season, series.first { it.id == a.seriesId }.episodes.first().mark.episode) } }
|
||||
if (!filmChannel) md.append("- **Progression:** in-order steps backwards (other than starting again): $backwards.\n")
|
||||
// Gaps and overlaps across the whole four weeks.
|
||||
val gaps = all.zipWithNext().filter { (a, b) -> b.startMs - a.endMs > 60_000 }
|
||||
val overlaps = all.zipWithNext().count { (a, b) -> b.startMs < a.endMs }
|
||||
md.append("- **Coverage (4 weeks):** gaps over a minute: ${gaps.size}" + (if (gaps.isNotEmpty()) " (largest ${hours(gaps.maxOf { (a, b) -> b.startMs - a.endMs })})" else "") + "; overlaps: $overlaps.\n")
|
||||
// Events: when each keyed event starts, week by week.
|
||||
programming.dayParts.filter { it.key.isNotEmpty() && it.days.isNotEmpty() }.forEach { part ->
|
||||
val starts = fresh.filter { it.presentation == part.key }.groupBy { java.time.Instant.ofEpochMilli(it.startMs).atZone(zone).let { l -> if (l.hour < part.toHour && part.fromHour > part.toHour) l.toLocalDate().minusDays(1) else l.toLocalDate() } }
|
||||
md.append(" - Event ${part.key}: ${starts.size} nights; first starts ${starts.entries.take(4).joinToString { (d, es) -> "$d ${java.time.Instant.ofEpochMilli(es.first().startMs).atZone(zone).toLocalTime().withNano(0)}" }}.\n")
|
||||
}
|
||||
}
|
||||
// The same file on two channels at once, in the committed plans and the replay.
|
||||
val clashes = mutableListOf<String>()
|
||||
val flat = allPlans.flatMap { (n, es) -> es.map { n to it } }.groupBy { it.second.media.item.id }
|
||||
flat.values.forEach { es -> es.sortedBy { it.second.startMs }.zipWithNext().forEach { (a, b) -> if (a.first != b.first && b.second.startMs < a.second.endMs) clashes += "${a.second.media.item.title.take(40)} on ${a.first} and ${b.first} at ${java.time.Instant.ofEpochMilli(b.second.startMs).atZone(zone).toLocalDateTime()}" } }
|
||||
md.append("\n## Across channels\n\nThe same file on two channels at once (replay ignores the live clash check, so new bookings may show some): ${clashes.size}${if (clashes.isNotEmpty()) "\n\n" + clashes.take(20).joinToString("\n") { "- $it" } else ""}\n")
|
||||
File(dir, "schedule-audit.md").writeText(md.toString())
|
||||
println("audit written: ${File(dir, "schedule-audit.md")}")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user