Server IDs are temporary references: repairs kept, failures cooled down, lookups shared, nothing substituted (build 66)

Paul, 18 November 2026: IMDb, TMDB and TVDB IDs identify the content; a server's ID only says where it is today. Every
provider-ID repair goes through IdRepairs: a repair that worked is kept per workspace (id-repairs-0.json) and never asked
twice; a lookup that found nothing cools down (6 hours, doubling, at most a week), playback's refiles included; two
lookups for one title at once become one; every lookup is an ordinary paced request within the household budget; only
what's needed when it's needed. pickByProvider never substitutes: rows that could be two different titles repair
nothing, and a different film by name and year is refused. A kept repair that has gone stale is looked up afresh once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 15:00:53 +00:00
co-authored by Claude Opus 5.5
parent 788ea9268a
commit 224b10499a
5 changed files with 226 additions and 15 deletions
@@ -385,7 +385,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
// catching up, for whoever's watching; Catch Up offers it back once it has aired.
LaunchedEffect(workspace, Profiles.current?.id) { withContext(Dispatchers.IO) { ContinueWatching.load(workspace.scheduleDir, Profiles.current?.id) } }
// Taste, Stage 1: signals per profile, recorded only (Profile-Aware Director's Chair doc).
LaunchedEffect(workspace) { withContext(Dispatchers.IO) { runCatching { Taste.attach(workspace.scheduleDir) } } }
LaunchedEffect(workspace) { withContext(Dispatchers.IO) { runCatching { Taste.attach(workspace.scheduleDir) }; runCatching { IdRepairs.attach(workspace.scheduleDir) } } }
LaunchedEffect(session) {
while (true) {
delay(30_000)
@@ -477,10 +477,18 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
else { requests++; playableFilm(accepted.id, programming.englishAudio, accepted.title) }
// Gone (renumbered, or moved from another server): found again by its provider ID, one request (18 November 2026).
if (found == null && accepted.ref.isNotEmpty()) {
requests++
val row = runCatching { byProvider("Movie", accepted.ref, "&Fields=MediaSources") }.getOrDefault(emptyList()).firstOrNull()
found = row?.let { playableSource(it, BoxDecoders::canDecode, programming.englishAudio) }
if (found != null) { refound[accepted.id] = row!!.optString("Id"); accepted = accepted.copy(id = row.optString("Id"), sourceId = null, durationMs = null) }
// A repair kept from before is tried first; a stale one is dropped and looked up afresh, once.
for (attempt in 0..1) {
val id = IdRepairs.lookup("Movie", accepted.ref) {
requests++
pickByProvider(runCatching { byProvider("Movie", accepted.ref, "&Fields=ProductionYear") }.getOrDefault(emptyList()), accepted.title, accepted.year)?.optString("Id")
} ?: break
if (id == accepted.id) break
requests++
found = playableFilm(id, programming.englishAudio, accepted.title)
if (found != null) { refound[accepted.id] = id; accepted = accepted.copy(id = id, sourceId = null, durationMs = null); break }
IdRepairs.forget("Movie", accepted.ref)
}
}
val (source, duration) = found ?: continue
pool += PoolSeries(accepted.id, accepted.title, listOf(PoolEpisode(accepted.id, source, EpisodeMark(1, 1), accepted.title, duration)), accepted.group, year = accepted.year)
@@ -490,9 +498,12 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
// one request, only when reading it by its saved ID fails or finds nothing (18 November 2026).
fun refind(): PoolSeries? {
if (accepted.ref.isEmpty()) return null
requests++
val id = runCatching { byProvider("Series", accepted.ref) }.getOrDefault(emptyList()).firstOrNull()?.optString("Id")?.takeIf { it != accepted.id } ?: return null
val id = IdRepairs.lookup("Series", accepted.ref) {
requests++
pickByProvider(runCatching { byProvider("Series", accepted.ref, "&Fields=ProductionYear") }.getOrDefault(emptyList()), accepted.title, accepted.year)?.optString("Id")
}?.takeIf { it != accepted.id } ?: return null
return runCatching { read(id) }.getOrNull()?.takeIf { it.episodes.isNotEmpty() }?.also { refound[accepted.id] = id; accepted = accepted.copy(id = id) }
?: run { IdRepairs.forget("Series", accepted.ref); null }
}
val whole = try { (if (accepted.id.startsWith(MOVED_PREFIX)) null else read(accepted.id).takeIf { it.episodes.isNotEmpty() && sameFilmName(it.title, accepted.title) }) ?: refind() ?: continue }
catch (failure: Exception) {
@@ -572,7 +583,7 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
val rows = byProvider("Movie", item.ref, "&Fields=MediaSources,ProviderIds,ProductionYear")
val candidates = rows.mapNotNull(::filmCandidate)
val imdb = item.ref.takeIf { it.startsWith("imdb.") }?.removePrefix("imdb.")
candidates.firstOrNull()?.let { first -> resolveFilm(FilmIdentity(first.name, item.year, imdb), candidates, BoxDecoders::canDecode).film?.let { return it } }
candidates.firstOrNull()?.let { first -> resolveFilm(FilmIdentity(first.name, item.year, imdb), candidates, BoxDecoders::canDecode).film?.let { IdRepairs.found("Movie", item.ref, it.id); return it } }
}
val entry = item.year?.let { "${item.title} ($it)" } ?: channelNumber?.let { listedFilmEntry(it, item.title) } ?: item.title
return findFilm(transport, userId, ::currentToken, entry, BoxDecoders::canDecode).film
@@ -586,6 +597,14 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
}
private fun byProvider(type: String, ref: String, fields: String = ""): List<org.json.JSONObject> {
// Every provider lookup, playback's refiles included, keeps to the same cooldown after finding nothing (IdRepairs).
if (IdRepairs.coolingDown(type, ref)) return emptyList()
val rows = byProviderOnce(type, ref, fields)
if (rows.isEmpty()) IdRepairs.found(type, ref, null)
return rows
}
private fun byProviderOnce(type: String, ref: String, fields: String): List<org.json.JSONObject> {
val reply = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&Recursive=true&IncludeItemTypes=$type&AnyProviderIdEquals=${java.net.URLEncoder.encode(ref, "UTF-8")}" +
"&StartIndex=0&Limit=10$fields&EnableImages=false&EnableUserData=false", token = currentToken()))
EmbyClient.expectSuccess(reply.status, false)
@@ -0,0 +1,108 @@
package tv.orbit.classic
import org.json.JSONObject
import java.io.File
import java.util.concurrent.ConcurrentHashMap
/*
* Server IDs are temporary references, never content identities (Paul, 18 November 2026, after the VPS renumbered about 40%
* of its items). IMDb, TMDB and TVDB IDs identify the content; a server's ID only says where it is today; Orbit remembers the
* content apart from its location.
*
* When Orbit has to find something again by its provider ID, it goes through here:
* - a repair that worked is kept on the TV (id-repairs-0.json in the server's own workspace), so it's never asked twice;
* - a lookup that found nothing waits before it's tried again: 6 hours, doubling each time, at most a week;
* - two lookups for the same title at once become one;
* - every lookup is an ordinary request, so it's paced and counted within the household budget like any other;
* - only what Orbit needs, when it needs it: a programme about to play, an approval its channel is reading. Never a sweep.
* Ambiguity is the caller's to refuse (see [pickByProvider]): a lookup that could be two different titles repairs nothing.
*/
internal object IdRepairs {
const val FIRST_COOLDOWN_MS = 6 * 60 * 60_000L
const val LONGEST_COOLDOWN_MS = 7 * 24 * 60 * 60_000L
private const val MAX_KEPT = 5_000
private class Entry(val id: String?, val atMs: Long, val fails: Int)
@Volatile private var file: File? = null
private val entries = HashMap<String, Entry>()
private val locks = ConcurrentHashMap<String, Any>()
/** The workspace in use: its repairs are its own, as its schedules are. */
@Synchronized fun attach(dir: File?) {
file = dir?.let { File(it, "id-repairs-0.json") }
entries.clear()
val f = file ?: return
runCatching { JSONObject(f.readText()) }.getOrNull()?.let { o -> o.keys().forEach { k ->
o.optJSONObject(k)?.let { e -> entries[k] = Entry(e.optString("id").takeIf { EmbyClient.validId(it) }, e.optLong("at"), e.optInt("fails")) } } }
}
private fun key(type: String, ref: String) = "$type|$ref"
fun cooldownMs(fails: Int): Long = if (fails <= 0) 0L else minOf(LONGEST_COOLDOWN_MS, FIRST_COOLDOWN_MS shl minOf(fails - 1, 20))
/** The item [ref] was last found at, if a repair worked. */
@Synchronized fun known(type: String, ref: String): String? = entries[key(type, ref)]?.id
/** True while a lookup that found nothing is still cooling down. */
@Synchronized fun coolingDown(type: String, ref: String, nowMs: Long = System.currentTimeMillis()): Boolean =
entries[key(type, ref)]?.let { it.id == null && nowMs - it.atMs < cooldownMs(it.fails) } == true
/**
* The item for [ref]: the kept repair, or [fetch] (one lookup, never two at once for the same title, never during a
* cooldown). A fetch that finds nothing starts or lengthens the cooldown.
*/
fun lookup(type: String, ref: String, nowMs: Long = System.currentTimeMillis(), fetch: () -> String?): String? {
if (ref.isEmpty()) return null
val k = key(type, ref)
synchronized(locks.getOrPut(k) { Any() }) {
known(type, ref)?.let { return it }
if (coolingDown(type, ref, nowMs)) return null
val id = runCatching(fetch).getOrNull()?.takeIf { EmbyClient.validId(it) }
record(k, id, nowMs)
return id
}
}
/** Lookups made elsewhere (a programme refiled for playback) count towards the same cooldowns. */
fun found(type: String, ref: String, id: String?, nowMs: Long = System.currentTimeMillis()) { if (ref.isNotEmpty()) record(key(type, ref), id?.takeIf { EmbyClient.validId(it) }, nowMs) }
/** A kept repair that's gone stale (the server renumbered again): looked up afresh next time. */
@Synchronized fun forget(type: String, ref: String) { if (entries.remove(key(type, ref)) != null) save() }
@Synchronized private fun record(k: String, id: String?, nowMs: Long) {
val before = entries[k]
entries[k] = if (id != null) Entry(id, nowMs, 0) else Entry(null, nowMs, (before?.fails ?: 0) + 1)
if (entries.size > MAX_KEPT) entries.entries.sortedBy { it.value.atMs }.take(entries.size - MAX_KEPT).forEach { entries.remove(it.key) }
save()
}
private fun save() {
val f = file ?: return
val o = JSONObject(); entries.forEach { (k, e) -> o.put(k, JSONObject().put("id", e.id ?: "").put("at", e.atMs).put("fails", e.fails)) }
runCatching { writeSafely(f, o.toString()) }
}
internal fun resetForTest() { synchronized(this) { file = null; entries.clear() }; locks.clear() }
}
/**
* The one item a provider-ID lookup found for [title] (and [year], when known), or null when the rows could be two different
* titles, or none of them is it. Copies of one film are one answer; a different film is never substituted.
*/
internal fun pickByProvider(rows: List<JSONObject>, title: String, year: Int?): JSONObject? {
if (rows.isEmpty()) return null
val works = rows.groupBy { moveTitleKey(it.optString("Name")) + "|" + it.optInt("ProductionYear", 0).takeIf { y -> y > 0 } }
if (works.size > 1) {
// Different names or years under one ID: only the one that is plainly this title, if exactly one is.
val fitting = works.values.filter { group -> group.first().let { r -> nameFits(r.optString("Name"), title) && (year == null || r.optInt("ProductionYear", 0).let { it == 0 || it == year }) } }
return fitting.singleOrNull()?.first()
}
val r = rows.first()
val yearOk = year == null || r.optInt("ProductionYear", 0).let { it == 0 || kotlin.math.abs(it - year) <= 1 }
// The ID is the content's own; a renamed title is still it, unless its year says otherwise.
return r.takeIf { yearOk || nameFits(it.optString("Name"), title) }
}
private fun nameFits(a: String, b: String): Boolean {
val x = moveTitleKey(a); val y = moveTitleKey(b)
return x.isNotEmpty() && y.isNotEmpty() && (x == y || x.contains(y) || y.contains(x))
}
@@ -0,0 +1,68 @@
package tv.orbit.classic
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
import java.nio.file.Files
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicInteger
/** Server IDs are temporary references (Paul, 18 November 2026): repairs kept, failures cooled down, lookups shared, nothing substituted. */
class IdRepairsTest {
@org.junit.Before fun clean() = IdRepairs.resetForTest()
@org.junit.After fun after() = IdRepairs.resetForTest()
@Test fun aRepairIsKeptAndNeverAskedTwiceEvenAfterARestart() {
val dir = Files.createTempDirectory("repairs").toFile()
IdRepairs.attach(dir)
val asked = AtomicInteger()
assertEquals("new1", IdRepairs.lookup("Movie", "imdb.tt1", 0L) { asked.incrementAndGet(); "new1" })
assertEquals("new1", IdRepairs.lookup("Movie", "imdb.tt1", 1L) { asked.incrementAndGet(); "other" })
IdRepairs.attach(dir) // as after Orbit restarts
assertEquals("new1", IdRepairs.lookup("Movie", "imdb.tt1", 2L) { asked.incrementAndGet(); "other" })
assertEquals(1, asked.get())
dir.deleteRecursively()
}
@Test fun aFailedLookupCoolsDownAndBacksOff() {
val asked = AtomicInteger()
val h = 60 * 60_000L
assertNull(IdRepairs.lookup("Movie", "imdb.tt2", 0L) { asked.incrementAndGet(); null })
assertNull(IdRepairs.lookup("Movie", "imdb.tt2", 5 * h) { asked.incrementAndGet(); null }) // within 6 hours: not asked
assertEquals(1, asked.get())
assertNull(IdRepairs.lookup("Movie", "imdb.tt2", 7 * h) { asked.incrementAndGet(); null }) // after 6 hours: asked once more
assertNull(IdRepairs.lookup("Movie", "imdb.tt2", 18 * h) { asked.incrementAndGet(); null }) // now 12 hours
assertEquals(2, asked.get())
assertEquals(IdRepairs.LONGEST_COOLDOWN_MS, IdRepairs.cooldownMs(30)) // never longer than a week
}
@Test fun simultaneousLookupsForOneTitleBecomeOne() {
val asked = AtomicInteger(); val start = CountDownLatch(1)
val threads = (1..8).map { Thread { start.await(); IdRepairs.lookup("Series", "tvdb.9", 0L) { asked.incrementAndGet(); Thread.sleep(50); "show9" } } }
threads.forEach { it.start() }; start.countDown(); threads.forEach { it.join() }
assertEquals(1, asked.get())
}
@Test fun aStaleRepairIsForgottenAndLookedUpAfresh() {
IdRepairs.lookup("Movie", "imdb.tt3", 0L) { "old" }
IdRepairs.forget("Movie", "imdb.tt3")
assertEquals("fresh", IdRepairs.lookup("Movie", "imdb.tt3", 1L) { "fresh" })
}
private fun row(id: String, name: String, year: Int? = null) = JSONObject().put("Id", id).put("Name", name).apply { year?.let { put("ProductionYear", it) } }
@Test fun copiesOfOneFilmAreOneAnswer() =
assertEquals("a", pickByProvider(listOf(row("a", "Tremors", 1990), row("b", "Tremors", 1990)), "Tremors", 1990)?.optString("Id"))
@Test fun twoDifferentFilmsUnderOneIdAreNeverSubstituted() {
val rows = listOf(row("a", "Halloween", 1978), row("b", "Halloween", 2018))
assertNull(pickByProvider(rows, "Halloween", null))
assertEquals("a", pickByProvider(rows, "Halloween", 1978)?.optString("Id")) // the year settles it
}
@Test fun aRenamedFilmWithItsYearIsStillIt() =
assertEquals("a", pickByProvider(listOf(row("a", "John Carpenter's Halloween", 1978)), "Halloween", 1978)?.optString("Id"))
@Test fun aDifferentFilmWithAnotherNameAndYearIsRefused() =
assertNull(pickByProvider(listOf(row("a", "Krull", 1983)), "Tremors", 1990))
}
@@ -7,7 +7,7 @@ import org.junit.Test
/** 12 to 13 November 2026: the first scan re-files titles under new numbers; Orbit finds a booked one again, once. */
class RefiledTest {
@org.junit.Before fun server() { EmbyServer.origin = "https://emby.example.com" }
@org.junit.Before fun server() { EmbyServer.origin = "https://emby.example.com"; IdRepairs.resetForTest() }
@org.junit.After fun noServer() { EmbyServer.origin = "" }
private val gone = SampleItem("Fixture Show / S2 E3 / The Third", "Episode", 22, "", "oldep1", 22 * 60_000L)
private fun source(id: String) = JSONArray().put(JSONObject().put("Id", id).put("Container", "mkv").put("RunTimeTicks", 22 * 60_000L * 10_000))
@@ -99,7 +99,7 @@ class CopyChoiceTest {
/** 13 November 2026: a film already booked as a heavy copy swaps to a lighter one when tuned, searched for once. */
class LighterCopyTest {
@org.junit.Before fun server() { EmbyServer.origin = "https://emby.example.com" }
@org.junit.Before fun server() { EmbyServer.origin = "https://emby.example.com"; IdRepairs.resetForTest() }
@org.junit.After fun noServer() { EmbyServer.origin = "" }
private val booked = SampleItem("Fixture Werewolf", "Movie", 97, "", "heavy1", 97 * 60_000L)
private fun source(id: String, width: Int, bitrate: Long) = JSONObject().put("Id", id).put("Container", "mkv").put("Bitrate", bitrate)
@@ -127,7 +127,7 @@ class LighterCopyTest {
/** 15 November 2026: one renumbered programme means a rescan; the rest of the channel's schedule is checked in one go. */
class RecheckAfterRescanTest {
@org.junit.Before fun server() { EmbyServer.origin = "https://emby.example.com" }
@org.junit.Before fun server() { EmbyServer.origin = "https://emby.example.com"; IdRepairs.resetForTest() }
@org.junit.After fun noServer() { EmbyServer.origin = "" }
private val min = 60_000L
private fun ep(id: String, n: Int, start: Long) = ScheduleEntry("show", EpisodeMark(1, n),
@@ -185,7 +185,7 @@ class RefiledPlaysTest {
* provider ID and year), so it's found again after a rescan even when its name is shared or has changed.
*/
class RenumberingTest {
@org.junit.Before fun server() { EmbyServer.origin = "https://emby.example.com" }
@org.junit.Before fun server() { EmbyServer.origin = "https://emby.example.com"; IdRepairs.resetForTest() }
@org.junit.After fun noServer() { EmbyServer.origin = "" }
private fun source(id: String, minutes: Long = 91) = JSONArray().put(JSONObject().put("Id", id).put("Container", "mkv").put("RunTimeTicks", minutes * 60_000L * 10_000))
private fun film(id: String, name: String, year: Int, imdb: String) = JSONObject().put("Id", id).put("Name", name).put("Type", "Movie").put("ProductionYear", year)
@@ -250,7 +250,7 @@ class RenumberingTest {
/** 18 November 2026: an approval whose item has gone (the server renumbered, or it came from another server) is found again. */
class SelfHealingApprovalTest {
@org.junit.Before fun server() { EmbyServer.origin = "https://emby.example.com" }
@org.junit.Before fun server() { EmbyServer.origin = "https://emby.example.com"; IdRepairs.resetForTest() }
@org.junit.After fun noServer() { EmbyServer.origin = "" }
private fun source(id: String, minutes: Long = 90) = JSONArray().put(JSONObject().put("Id", id).put("Container", "mkv").put("RunTimeTicks", minutes * 60_000L * 10_000))
private fun film(id: String, name: String) = JSONObject().put("Id", id).put("Name", name).put("Type", "Movie").put("MediaSources", source("src$id"))
@@ -260,8 +260,11 @@ class SelfHealingApprovalTest {
val asked = mutableListOf<String>()
val transport = EmbyTransport { r ->
asked += r.path
if ("AnyProviderIdEquals=imdb.tt0100814" in r.path) EmbyReply(200, JSONObject().put("Items", JSONArray().put(film("new1", "Tremors"))).toString())
else EmbyReply(200, JSONObject().put("Items", JSONArray()).toString()) // the old ID: nothing there
when {
"AnyProviderIdEquals=imdb.tt0100814" in r.path -> EmbyReply(200, JSONObject().put("Items", JSONArray().put(film("new1", "Tremors"))).toString())
"Ids=new1" in r.path -> EmbyReply(200, JSONObject().put("Items", JSONArray().put(film("new1", "Tremors"))).toString())
else -> EmbyReply(200, JSONObject().put("Items", JSONArray()).toString()) // the old ID: nothing there
}
}
val s = EmbySampleSession(transport, "fixture-token-private", "fixture-user", EmbySample(emptyList(), 0))
val read = s.readChannelPool(channel, null, ChannelChoices(listOf(Suggestion("old1", "Tremors", 1990, "Movie", "day", "", ref = "imdb.tt0100814"))))
@@ -269,6 +272,19 @@ class SelfHealingApprovalTest {
assertEquals("day", read.series.single().group)
assertEquals(mapOf("old1" to "new1"), read.refound)
assertEquals(1, asked.count { "AnyProviderIdEquals" in it })
// The repair is kept: the next read asks for the film by its new ID, with no lookup.
s.readChannelPool(channel, null, ChannelChoices(listOf(Suggestion("old1", "Tremors", 1990, "Movie", "day", "", ref = "imdb.tt0100814"))))
assertEquals(1, asked.count { "AnyProviderIdEquals" in it })
}
@Test fun aLookupThatFindsNothingIsntRepeatedDuringItsCooldown() {
val asked = mutableListOf<String>()
val transport = EmbyTransport { r -> asked += r.path; EmbyReply(200, JSONObject().put("Items", JSONArray()).toString()) }
val s = EmbySampleSession(transport, "fixture-token-private", "fixture-user", EmbySample(emptyList(), 0))
val choices = ChannelChoices(listOf(Suggestion("moved-1", "Lost Film", 1970, "Movie", "", "", ref = "imdb.tt7")))
repeat(3) { s.readChannelPool(channel, null, choices) }
assertEquals(1, asked.count { "AnyProviderIdEquals" in it })
assertTrue(asked.none { "Ids=moved-1" in it }) // a placeholder is never asked for
}
@Test fun anApprovalWithoutAnIdIsLeftAsItWas() {