Server move guarantees: unmatched titles remembered, no duplicates, ambiguous ones wait for you (build 66)

Paul, 18 November 2026: three permanent guarantees. A title nothing matched is kept in the new server's workspace
(moved-pending-0.json) and comes back by itself when the library has it (recheck, from what the TV knows; no scan). A
title with more than one possible match waits for your choice, and only one of its possible matches is accepted.
Running the move again adds nothing: approvals by title, your channels by name, decisions, viewing and the pending
list are all checked first. Rollback forgets what the move remembered. adb: move-pending, move-resolve, move-recheck.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 14:46:43 +00:00
co-authored by Claude Opus 5.5
parent 97b0947257
commit 788ea9268a
4 changed files with 160 additions and 10 deletions
+1 -1
View File
@@ -3,7 +3,7 @@ plugins {
id("org.jetbrains.kotlin.plugin.compose")
}
/** The release's build number: versionCode is this x 10 plus the edition's channel. */
val ORBIT_BUILD = 65
val ORBIT_BUILD = 66
android {
namespace = "tv.orbit.classic"
compileSdk = 36
@@ -126,7 +126,25 @@ internal object InstallSnapshot {
val target = Workspaces.current(context)
if (target.original) return "refused: the server in use is the original one"
val from = File(data, "no_backup/schedule"); val to = target.scheduleDir
if (action != "move-preview" && OrbitScreen.open) return "refused: Orbit is open; force-stop it first"
if (action !in setOf("move-preview", "move-pending") && OrbitScreen.open) return "refused: Orbit is open; force-stop it first"
if (action == "move-pending") {
val out = File(context.getExternalFilesDir(null), "install-snapshot").apply { mkdirs() }
val pending = PendingTitle.load(to)
File(out, "move-pending.json").writeText(org.json.JSONArray(pending.map { it.toJson() }).toString(1))
return "pending ${pending.size} (${pending.count { it.ambiguous }} waiting for your choice)"
}
if (action == "move-resolve") {
// --es signature "<channel>:<old id>=<candidate id>": your choice for one ambiguous title.
val (key, pick) = (signature ?: return "refused: no choice").split('=').takeIf { it.size == 2 } ?: return "refused: give key=candidate"
return PendingTitle.resolve(to, ServerMove.userOf(to) ?: return "refused: no saved schedules", key, pick)
}
if (action == "move-recheck") {
val pending = PendingTitle.load(to).filter { !it.ambiguous }
if (pending.isEmpty()) return "nothing to recheck"
val titles = pending.map { moveTitleKey(it.title) }.toSet(); val refs = pending.flatMap { p -> p.refs.map { (s, v) -> "$s|${v.lowercase()}" } }.toSet()
val cat = MemoryMoveCatalogue.of(target.catalogueFile) { i -> moveTitleKey(i.title) in titles || i.refs.any { (s, v) -> "$s|${v.lowercase()}" in refs } }
return "back ${PendingTitle.recheck(to, ServerMove.userOf(to) ?: return "refused: no saved schedules", cat)}"
}
if (action == "move-rollback") {
val folder = File(target.root, receipt ?: return "refused: no receipt").takeIf { Regex("server-move-\\d+").matches(it.name) && it.isDirectory } ?: return "refused: no such receipt"
return "rolled back ${ServerMove.rollback(to, folder)} files"
@@ -97,10 +97,10 @@ internal enum class MoveHow(val label: String) {
internal class MoveMatch(val oldId: String, val title: String, val type: String, val year: Int?, val newId: String?, val how: MoveHow,
/** For an ambiguous match, the titles it could be. */
val candidates: List<String> = emptyList()) {
val candidates: List<MoveItem> = emptyList()) {
val matched get() = newId != null
fun toJson(): JSONObject = JSONObject().put("old", oldId).put("t", title).put("k", type).put("y", year ?: JSONObject.NULL).put("new", newId ?: JSONObject.NULL)
.put("how", how.name).put("cands", JSONArray(candidates))
.put("how", how.name).put("cands", JSONArray(candidates.map { "${it.title} (${it.year ?: "?"})" }))
}
/**
@@ -125,7 +125,7 @@ internal class MoveMatcher(private val old: MoveCatalogue, private val new: Move
// Each candidate shares an ID with the old title; one that contradicts another of its IDs is a different work.
val agreed = byRef.filter { c -> MOVE_SOURCES.none { s -> was.refs[s] != null && c.refs[s] != null && !c.refs[s].equals(was.refs[s], true) } }
return@getOrPut if (agreed.isNotEmpty()) MoveMatch(oldId, name, type, y, pick(agreed).id, MoveHow.Provider)
else MoveMatch(oldId, name, type, y, null, MoveHow.Ambiguous, byRef.map { "${it.title} (${it.year ?: "?"})" }.distinct().take(5))
else MoveMatch(oldId, name, type, y, null, MoveHow.Ambiguous, byRef.distinctBy { "${it.title}|${it.year}" }.take(5))
}
// By title: never a title whose own IDs say it's a different work (a remake), and the year must agree when both have one.
val sameName = new.byTitle(type, moveTitleKey(name)).filter { c -> MOVE_SOURCES.none { s -> was.refs[s] != null && c.refs[s] != null && !c.refs[s].equals(was.refs[s], true) } }
@@ -133,13 +133,86 @@ internal class MoveMatcher(private val old: MoveCatalogue, private val new: Move
val works = fits.groupBy(::work)
when {
works.size == 1 -> MoveMatch(oldId, name, type, y, pick(fits).id, if (y != null && fits.any { it.year == y }) MoveHow.TitleYear else MoveHow.Title)
works.size > 1 -> MoveMatch(oldId, name, type, y, null, MoveHow.Ambiguous, fits.map { "${it.title} (${it.year ?: "?"})" }.distinct().take(5))
sameName.isNotEmpty() -> MoveMatch(oldId, name, type, y, null, MoveHow.Ambiguous, sameName.map { "${it.title} (${it.year ?: "?"})" }.distinct().take(5))
works.size > 1 -> MoveMatch(oldId, name, type, y, null, MoveHow.Ambiguous, fits.distinctBy { "${it.title}|${it.year}" }.take(5))
sameName.isNotEmpty() -> MoveMatch(oldId, name, type, y, null, MoveHow.Ambiguous, sameName.distinctBy { "${it.title}|${it.year}" }.take(5))
else -> MoveMatch(oldId, name, type, y, null, MoveHow.Missing)
}
}
}
/**
* A title a move couldn't place by itself (Paul's guarantees, 18 November 2026): one with more than one possible match waits
* for you to choose; one nothing matched, with no ID to look it up by, is remembered so it can come back when the library
* has it. Kept in the new server's workspace (moved-pending-0.json), whatever happens to the old one.
*/
internal class PendingTitle(val channel: Int, val group: String, val oldId: String, val title: String, val year: Int?, val type: String, val reason: String,
val refs: Map<String, String>, val ambiguous: Boolean, val candidates: List<MoveItem>, val atMs: Long) {
val key get() = "$channel:$oldId"
fun toJson(): JSONObject = JSONObject().put("c", channel).put("g", group).put("i", oldId).put("t", title).put("y", year ?: JSONObject.NULL).put("k", type).put("r", reason)
.put("refs", JSONObject(refs)).put("amb", ambiguous).put("at", atMs)
.put("cands", JSONArray(candidates.map { JSONObject().put("i", it.id).put("t", it.title).put("y", it.year ?: JSONObject.NULL).put("refs", JSONObject(it.refs)) }))
companion object {
private fun refs(o: JSONObject?) = o?.keys()?.asSequence()?.filter { it in MOVE_SOURCES }?.associateWith { o.getString(it) }.orEmpty()
fun of(o: JSONObject) = PendingTitle(o.getInt("c"), o.optString("g"), o.getString("i"), o.getString("t"), if (o.isNull("y")) null else o.optInt("y"), o.getString("k"),
o.optString("r"), refs(o.optJSONObject("refs")), o.optBoolean("amb"),
o.optJSONArray("cands")?.let { a -> (0 until a.length()).map { a.getJSONObject(it) }.map { c -> MoveItem(c.getString("i"), o.getString("k"), c.getString("t"), if (c.isNull("y")) null else c.optInt("y"), refs(c.optJSONObject("refs"))) } }.orEmpty(),
o.optLong("at"))
fun file(dir: File) = File(dir, "moved-pending-0.json")
fun load(dir: File): List<PendingTitle> = runCatching { JSONArray(file(dir).readText()).let { a -> (0 until a.length()).mapNotNull { runCatching { of(a.getJSONObject(it)) }.getOrNull() } } }.getOrDefault(emptyList())
fun save(dir: File, all: List<PendingTitle>) = writeSafely(file(dir), JSONArray(all.distinctBy { it.key }.map { it.toJson() }).toString())
/**
* Looks again for remembered titles nothing matched, in the library as the TV knows it now: one that's arrived joins
* its channel (by its provider ID where it has one); one that could now be more than one title waits for your choice.
* Nothing is asked of the server. Returns how many came back.
*/
fun recheck(dir: File, user: String, catalogue: MoveCatalogue, nowMs: Long = System.currentTimeMillis()): Int {
val all = load(dir); var back = 0
val oldCat = MemoryMoveCatalogue(all.asSequence().map { MoveItem(it.oldId, it.type, it.title, it.year, it.refs) })
val matcher = MoveMatcher(oldCat, catalogue)
val kept = all.map { p ->
if (p.ambiguous) return@map p
val m = matcher.match(p.oldId, p.title, p.type, p.year)
when {
m.matched -> { val store = ScheduleStore(dir); val now = store.loadChoices(user, p.channel)
if (now.accepted.none { moveTitleKey(it.title) == moveTitleKey(p.title) && it.type == p.type }) {
val item = catalogue.item(m.newId!!)
val order = if (p.type == "Series") listOf("tvdb", "imdb", "tmdb") else listOf("imdb", "tmdb")
val ref = order.firstNotNullOfOrNull { s -> item?.refs?.get(s)?.takeIf { it.matches(Regex("[A-Za-z0-9_-]{1,40}")) }?.let { "$s.$it" } }.orEmpty()
store.saveChoices(user, p.channel, ChannelChoices(now.accepted + Suggestion(if (ref.isNotEmpty()) MOVED_PREFIX + p.oldId else m.newId, p.title, p.year, p.type, p.group,
"Approved on your previous server; back in the library", ref = ref), now.rejected))
}
back++; null }
m.how == MoveHow.Ambiguous -> PendingTitle(p.channel, p.group, p.oldId, p.title, p.year, p.type, p.reason, p.refs, true, m.candidates, nowMs)
else -> p
}
}.filterNotNull()
if (back > 0 || kept.any { it.ambiguous } != all.any { it.ambiguous }) save(dir, kept)
return back
}
/**
* Your choice for a title with more than one possible match: [candidateId] must be one of its candidates. It joins the
* channel's approvals (by its provider ID where it has one, so it heals like any other) and leaves the pending list.
*/
fun resolve(dir: File, user: String, key: String, candidateId: String): String {
val all = load(dir)
val p = all.firstOrNull { it.key == key } ?: return "refused: nothing pending as $key"
val pick = p.candidates.firstOrNull { it.id == candidateId } ?: return "refused: $candidateId isn't one of its possible matches"
val store = ScheduleStore(dir)
val now = store.loadChoices(user, p.channel)
if (now.accepted.none { moveTitleKey(it.title) == moveTitleKey(pick.title) && it.type == p.type }) {
val order = if (p.type == "Series") listOf("tvdb", "imdb", "tmdb") else listOf("imdb", "tmdb")
val ref = order.firstNotNullOfOrNull { s -> pick.refs[s]?.takeIf { it.matches(Regex("[A-Za-z0-9_-]{1,40}")) }?.let { "$s.$it" } }.orEmpty()
val id = if (ref.isNotEmpty()) MOVED_PREFIX + p.oldId else pick.id
store.saveChoices(user, p.channel, ChannelChoices(now.accepted + Suggestion(id, pick.title, pick.year, p.type, p.group, "Chosen by you after a server move", ref = ref), now.rejected))
}
save(dir, all.filter { it.key != key })
return "added ${pick.title} to channel ${p.channel}"
}
}
}
/** One channel's approvals and rejections, matched. */
internal class ChannelMove(val number: Int, val name: String, val matches: List<Pair<MoveMatch, String>>, val alreadyThere: Int, val add: List<Suggestion>,
val rejectedMatched: Set<String>, val rejectedTotal: Int)
@@ -148,7 +221,9 @@ internal class ChannelMove(val number: Int, val name: String, val matches: List<
internal class YourChannelMove(val from: Int, val channel: CustomChannel, val enabled: Boolean)
internal class MovePlan(val channels: List<ChannelMove>, val yours: List<YourChannelMove>, val decisions: List<ChairDecision>, val decisionsTotal: Int,
val taste: Map<String, List<TasteEvent>>, val tasteTotal: Int, val copyLearning: Boolean, val dismissed: Set<String>, val refresh: List<Int>) {
val taste: Map<String, List<TasteEvent>>, val tasteTotal: Int, val copyLearning: Boolean, val dismissed: Set<String>, val refresh: List<Int>,
/** Titles to remember: ambiguous ones waiting for your choice, and ones nothing matched. */
val pending: List<PendingTitle> = emptyList()) {
val all get() = channels.flatMap { c -> c.matches.map { it.first } }
val missing get() = all.filter { it.how == MoveHow.Missing }.distinctBy { it.oldId }
val ambiguous get() = all.filter { it.how == MoveHow.Ambiguous }.distinctBy { it.oldId }
@@ -161,7 +236,7 @@ internal class MovePlan(val channels: List<ChannelMove>, val yours: List<YourCha
/** What apply will do, as a fingerprint: apply refuses unless the preview it's given still matches. */
val signature: String get() {
val text = channels.joinToString("\n") { c -> "${c.number}:" + c.add.joinToString(",") { "${it.id}/${it.group}" } + "|" + c.rejectedMatched.sorted().joinToString(",") } +
yours.joinToString("\n") { "y${it.from}>${it.channel.number}" } + "d${decisions.size}t${taste.values.sumOf { it.size }}l$copyLearning" + dismissed.sorted().joinToString(",") + refresh.joinToString(",")
yours.joinToString("\n") { "y${it.from}>${it.channel.number}" } + "d${decisions.size}t${taste.values.sumOf { it.size }}l$copyLearning" + dismissed.sorted().joinToString(",") + refresh.joinToString(",") + pending.joinToString(",") { it.key }
return MessageDigest.getInstance("SHA-256").digest(text.toByteArray()).take(8).joinToString("") { "%02x".format(it) }
}
@@ -174,6 +249,8 @@ internal class MovePlan(val channels: List<ChannelMove>, val yours: List<YourCha
.put("yours", JSONArray(yours.map { JSONObject().put("from", it.from).put("to", it.channel.number).put("name", it.channel.name).put("enabled", it.enabled) }))
.put("decisions", "${decisions.size}/$decisionsTotal").put("taste", "${taste.values.sumOf { it.size }}/$tasteTotal").put("learning", copyLearning)
.put("dismissed", dismissed.size).put("refresh", JSONArray(refresh))
.put("pending", JSONArray(pending.map { JSONObject().put("key", it.key).put("t", it.title).put("y", it.year ?: JSONObject.NULL).put("ambiguous", it.ambiguous)
.put("choices", JSONArray(it.candidates.map { c -> JSONObject().put("id", c.id).put("t", c.title).put("y", c.year ?: JSONObject.NULL) })) }))
}
/**
@@ -242,7 +319,11 @@ internal class ServerMove(private val from: File, private val fromUser: String,
old.itemType(id)?.let { (t, k, y) -> matcher.match(id, t, k, y).newId }?.let { "$kind:${renumber[n] ?: n}:$group:$it" } } }.toSet() - loadDismissedKeys(to)
val copyLearning = oldStore.learningFile().exists() && !newStore.learningFile().exists()
val refresh = refreshChannels.filter { newStore.loadPool(toUser, it) != null }.sorted()
return MovePlan(channels, yours, decisions, oldDecisions.size, taste.first, taste.second, copyLearning, dismissed, refresh)
val already = PendingTitle.load(to).map { it.key }.toSet()
val pending = channels.flatMap { c -> c.matches.filter { (m, _) -> m.how == MoveHow.Ambiguous || (m.how == MoveHow.Missing && c.add.none { it.id == MOVED_PREFIX + m.oldId }) }
.map { (m, group) -> PendingTitle(c.number, group, m.oldId, m.title, m.year, m.type, "Approved on your previous server", old.item(m.oldId)?.refs.orEmpty(),
m.how == MoveHow.Ambiguous, m.candidates, nowMs) } }.filter { it.key !in already }.distinctBy { it.key }
return MovePlan(channels, yours, decisions, oldDecisions.size, taste.first, taste.second, copyLearning, dismissed, refresh, pending)
}
/** The approval's provider ID, from the new library's row (or the old one's), so it can be found again if the ID moves. */
@@ -326,6 +407,7 @@ internal class ServerMove(private val from: File, private val fromUser: String,
keep(File(to, "episodes-$n.json")); keep(File(to, "episodes-$n.json.prev"))
newStore.savePool(toUser, n, ScheduleStore.SavedPool(pool.series, 0L, pool.signature))
}
if (plan.pending.isNotEmpty()) { keep(PendingTitle.file(to)); PendingTitle.save(to, PendingTitle.load(to) + plan.pending) }
writeSafely(File(receipt, "plan.json"), plan.toJson().toString(1))
return receipt
}
@@ -179,6 +179,56 @@ class ServerMoveTest {
assertTrue(move(r).preview().channels.single { it.number == 305 }.add.none { it.title == "Tremors" })
}
// --- Paul's three guarantees (18 November 2026) ---
@Test fun runningTheMoveTwiceNeverDuplicatesAnything() {
val r = rig()
move(r).let { it.apply(it.preview().signature) }
val choices = File(r.to, "choices-305.json").readText(); val yours = File(r.to, "yours.json").readText()
val again = move(r, emptySet()); val plan = again.preview()
assertEquals(0, plan.adds); assertTrue(plan.yours.isEmpty()); assertTrue(plan.decisions.isEmpty()); assertTrue(plan.pending.isEmpty())
again.apply(plan.signature)
assertEquals(choices, File(r.to, "choices-305.json").readText())
assertEquals(yours, File(r.to, "yours.json").readText())
assertEquals(1, loadDecisions(ScheduleStore(r.to).decisionsFile()).size)
assertEquals(1, TasteStore(File(r.to, "taste")).events("grown").size)
assertEquals(2, PendingTitle.load(r.to).size) // Robin Redbreast and Cosmos, once each
}
@Test fun anAmbiguousTitleWaitsForYourChoiceAndOnlyAPossibleMatchIsAccepted() {
val r = rig()
move(r).let { it.apply(it.preview().signature) }
val cosmos = PendingTitle.load(r.to).single { it.ambiguous }
assertEquals("Cosmos", cosmos.title)
assertTrue(ScheduleStore(r.to).loadChoices(newUser, 305).accepted.none { it.title == "Cosmos" }) // never guessed
assertTrue(PendingTitle.resolve(r.to, newUser, cosmos.key, "9500").startsWith("refused")) // not one of its matches
PendingTitle.resolve(r.to, newUser, cosmos.key, "9004")
val added = ScheduleStore(r.to).loadChoices(newUser, 305).accepted.single { it.title == "Cosmos" }
assertEquals("tvdb.2", added.ref)
assertTrue(PendingTitle.load(r.to).none { it.ambiguous })
assertTrue(PendingTitle.resolve(r.to, newUser, cosmos.key, "9004").startsWith("refused")) // once only
}
@Test fun anUnmatchedTitleIsRememberedAndComesBackWhenTheLibraryHasIt() {
val r = rig()
move(r).let { it.apply(it.preview().signature) }
assertEquals("Robin Redbreast", PendingTitle.load(r.to).single { !it.ambiguous }.title)
assertEquals(0, PendingTitle.recheck(r.to, newUser, newCat)) // still not there
val arrived = MemoryMoveCatalogue(sequenceOf(film("9900", "Robin Redbreast", 1970, "imdb" to "tt0066303")))
assertEquals(1, PendingTitle.recheck(r.to, newUser, arrived))
val back = ScheduleStore(r.to).loadChoices(newUser, 305).accepted.single { it.title == "Robin Redbreast" }
assertEquals("imdb.tt0066303", back.ref); assertEquals("late", back.group)
assertTrue(PendingTitle.load(r.to).none { it.title == "Robin Redbreast" })
assertEquals(0, PendingTitle.recheck(r.to, newUser, arrived)) // and only once
}
@Test fun rollbackAlsoForgetsWhatTheMoveRemembered() {
val r = rig(); val m = move(r)
val receipt = m.apply(m.preview().signature)
ServerMove.rollback(r.to, receipt)
assertTrue(PendingTitle.load(r.to).isEmpty())
}
private fun snapshot(dir: File): Map<String, String> =
dir.walk().filter { it.isFile && !it.name.endsWith(".prev") && !it.name.endsWith(".tmp") }.associate { it.relativeTo(dir).path to it.readText() }