Provider contract step 3: catalogue import through the contract behind a switch (off), read-only shadow comparison (0.110.6)

- ProviderSwitches.catalogue, off by default, set only from adb; today's import stays the fallback and is unchanged
  when the switch is off. The import loop gains a fetch parameter whose default is today's reader.
- CatalogueItem carries every field today's import stores, and Page a cursor (rows read, including skipped ones), so
  the contract path writes byte-identical catalogue records, positions and totals.
- CatalogueShadow: reads the same pages both ways, compares ids, every field, paging and totals, records time, heap
  and errors, never writes the catalogue; keeps sanitised copies of the first raw pages as fixtures.
- MainActivity reads adb requests in onNewIntent too, since Orbit is singleTask.

772 tests (one PhoneLink port flake on a first run, passed on re-run), lint clean, replay tests unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 21:47:40 +00:00
co-authored by Claude Opus 5.5
parent 3da2159429
commit ae62a0750f
14 changed files with 277 additions and 21 deletions
@@ -0,0 +1,79 @@
package tv.orbit.classic
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
/** Step 3 (8 November 2026): the catalogue import through the contract writes exactly what today's import writes. */
class CatalogueViaProviderTest {
/** A library with the awkward rows real servers have: an episode in the list, a row with no title, a bad id. */
private class Awkward : EmbyTransport {
val rows = (1..37).map { i -> JSONObject().put("Id", "item$i").put("Type", if (i % 5 == 0) "Series" else "Movie").put("Name", "Fictional $i")
.put("ProductionYear", 1980 + i).put("RunTimeTicks", (40L + i) * 60_000 * 10_000).put("OfficialRating", if (i % 3 == 0) "" else "15")
.put("Genres", JSONArray().put("Drama")).put("Studios", JSONArray().put(JSONObject().put("Name", "Studio $i")))
.put("ProviderIds", JSONObject().put("Imdb", "tt00$i").put("Tmdb", "$i")).put("PremiereDate", "${1980 + i}-01-01T00:00:00Z")
.put("OriginalTitle", if (i % 7 == 0) "Original $i" else "").put("Tags", JSONArray().put("tag$i")) } +
listOf(JSONObject().put("Id", "ep1").put("Type", "Episode").put("Name", "An episode"), JSONObject().put("Id", "untitled").put("Type", "Movie"),
JSONObject().put("Id", "../bad").put("Type", "Movie").put("Name", "Bad id"))
override fun execute(request: EmbyRequest): EmbyReply {
val q = { k: String -> Regex("[?&]$k=([^&]*)").find(request.path)!!.groupValues[1] }
val start = q("StartIndex").toInt(); val limit = q("Limit").toInt()
return EmbyReply(200, JSONObject().put("Items", JSONArray(rows.drop(start).take(limit))).put("TotalRecordCount", if (request.path.contains("EnableTotalRecordCount=false")) 0 else rows.size).toString())
}
}
private class Capture : CatalogueSink {
var pos = 0L; val writes = mutableListOf<List<Any?>>()
override fun position(userId: String) = pos
override fun write(userId: String, records: List<CatalogueRecord>, nextStart: Long, total: Long?, finished: Boolean) { writes += listOf(records, nextStart, total, finished); pos = nextStart }
}
private fun provider(t: EmbyTransport) = EmbyProvider(EmbySampleSession(t, "fixture-token-private", "fixtureuser", EmbySample(emptyList(), 0)), t, "fixtureuser",
{ "fixture-token-private" }, ProviderKind.Emby, "fixtureserver1", images = { null })
@Test fun importThroughTheContractWritesTheSameRecordsPositionsAndTotals() {
for (pageSize in listOf(5, 200)) {
val t = Awkward(); val today = Capture(); val via = Capture(); val p = provider(t)
importCatalogue(t, "fixtureuser", { "fixture-token-private" }, today, maxPages = 50, fetch = { s, _, w -> fetchCataloguePage(t, "fixtureuser", { "x" }, s, pageSize, w) })
importCatalogue(t, "fixtureuser", { "fixture-token-private" }, via, maxPages = 50, fetch = { s, _, w -> cataloguePageVia(p, s, pageSize, w) })
assertEquals(today.writes, via.writes)
assertEquals(37, today.writes.sumOf { (it[0] as List<*>).size })
}
}
@Test fun theShadowComparisonFindsThemIdenticalAndNeverWrites() {
val t = Awkward(); val p = provider(t)
val r = CatalogueShadow.compare({ s, n, w -> fetchCataloguePage(t, "fixtureuser", { "x" }, s, n, w) }, { s, n, w -> cataloguePageVia(p, s, n, w) }, 50)
assertTrue(r.getBoolean("identical")); assertEquals(37, r.getInt("records")); assertEquals(40L, r.getLong("positionReached"))
assertFalse(r.getBoolean("wroteCatalogue"))
assertTrue(r.has("todayMs") && r.has("providerMs") && r.has("heapPeakKb"))
}
@Test fun theShadowComparisonReportsADifferenceByIdOnly() {
val t = Awkward(); val p = provider(t)
val r = CatalogueShadow.compare({ s, n, w -> fetchCataloguePage(t, "fixtureuser", { "x" }, s, n, w) },
{ s, n, w -> cataloguePageVia(p, s, n, w).let { pg -> CataloguePage(pg.records.map { if (it.id == "item3") it.copy(year = 1900) else it }, pg.rawCount, pg.total) } }, 50)
assertFalse(r.getBoolean("identical")); assertEquals(1, r.getInt("mismatches"))
assertEquals("item3", r.getJSONArray("firstMismatches").getJSONObject(0).getJSONArray("ids").getString(0))
assertFalse(r.toString().contains("Fictional")) // no titles in the report
}
@Test fun theShadowComparisonRecordsAnErrorInsteadOfFailing() {
val t = Awkward()
val r = CatalogueShadow.compare({ s, n, w -> fetchCataloguePage(t, "fixtureuser", { "x" }, s, n, w) }, { _, _, _ -> throw EmbyCheckException("down", retryable = true) }, 5)
assertFalse(r.getBoolean("identical")); assertTrue(r.getString("error").startsWith("EmbyCheckException"))
}
@Test fun sanitisingKeepsStructureAndRemovesTitles() {
val raw = JSONObject().put("Items", JSONArray(Awkward().rows)).put("TotalRecordCount", 40).toString()
val clean = sanitiseCataloguePage(raw)
assertEquals(40, clean.getJSONArray("Items").length()); assertEquals(40, clean.getInt("TotalRecordCount"))
assertFalse(clean.toString().contains("Fictional"))
val before = fetchCataloguePage(EmbyTransport { EmbyReply(200, raw) }, "fixtureuser", { "x" }, 0, 200)
val after = fetchCataloguePage(EmbyTransport { EmbyReply(200, clean.toString()) }, "fixtureuser", { "x" }, 0, 200)
assertEquals(before.records.map { Triple(it.id, it.type, it.runtimeMs) }, after.records.map { Triple(it.id, it.type, it.runtimeMs) })
assertEquals(before.rawCount, after.rawCount)
assertEquals("tt777", after.records.first { it.id == "item7" }.providerIds["Imdb"]) // "tt007": same length, digits replaced
}
@Test fun theSwitchStartsOff() { assertFalse(ProviderSwitches.catalogue) }
}
@@ -34,7 +34,7 @@ internal object ProviderContractChecks {
private fun check(ok: Boolean, what: () -> String) { if (!ok) throw AssertionError(what()) }
private fun everything(p: MediaProvider, pageSize: Int = 7): List<CatalogueItem> = runBlocking {
val out = ArrayList<CatalogueItem>(); var start = 0
while (true) { val page = p.catalogue(PageRequest(start, pageSize)); out += page.items; start += page.items.size; if (page.items.isEmpty() || start >= page.total) break }
while (true) { val page = p.catalogue(PageRequest(start, pageSize)); out += page.items; start = if (page.next >= 0) page.next else start + page.items.size; if (page.items.isEmpty() || start >= page.total) break }
out
}
@@ -37,7 +37,7 @@ internal class ReferenceProvider(private val flaw: Flaw = Flaw.None, private val
fail(); reads++
val list = if (flaw == Flaw.UnstableIds && reads % 2 == 0) items.map { it.copy(id = ItemId(it.id.value + "x")) } else items
val from = if (flaw == Flaw.PagingRepeats) maxOf(0, page.start - 1) else page.start
return Page(list.drop(from).take(page.limit), list.size)
return Page(list.drop(from).take(page.limit), list.size, from + minOf(page.limit, maxOf(0, list.size - from)))
}
override suspend fun episodes(seriesId: ItemId, includeSpecials: Boolean): List<Episode> {
fail()