# 21 — Synchronization and provider-specific conflict handling

Prerequisites: database change recording, backup codecs, profile leases and HTTP. [File workbook](../reference/21-files.md).

[chapter-content-start]: #
## How to write this chapter

Build synchronization as guarded, provider-specific state exchange. Stable identity, durable change recording and account ownership must work before any network round can safely publish remote changes.

The 46 assigned entries are integrated below at their implementation steps. Every text listing is complete, including imports, helpers and tests. Create the displayed paths in your new project; dependencies imported from other chapters are linked beside the file. Binary assets have direct downloads.

Read each step’s explanation, write its contracts and implementation, then trace the test assertions. The final application graph has dependencies across chapters: the ordering is a construction plan, and a step is not a promise that the whole app compiles before its referenced contracts exist.

Implementation sequence:

- Step 1: Define stable IDs, field paths, clocks, migration and local journals.
- Step 2: Capture provider/account identity and bind runs to profile leases.
- Step 3: Implement Hub login, push/pull rounds and live-event ownership.
- Step 4: Map Mangayomi identities, relationships and change/delete records.
- Step 5: Implement cloud-backup, SyncYomi and Drive state-sync protocols separately.
- Step 6: Coalesce content/lifecycle events through owned trigger policy.
- Verification: recreate the full test/fixture listings and run the relevant target tasks.
[chapter-content-end]: #


## Step 1: define identity and change tracking

Implement SyncIds, SyncClock, SyncPaths, identity migration, Mangayomi namespace and hub resync. IDs must stay stable across restart/import; remote IDs are not reused as unrelated local row IDs. Define sync-eligible fields and device-local exclusions explicitly. Private notes, credentials and feature preferences have policies different from ordinary title metadata.

Record local changes and deletions in the correct journal/outbox, in the same transaction as their data change. Remote apply suppresses local echo recording. Hub outbox identity includes kind/id/path and sequence; acknowledgements delete only the exact unchanged sequence so a new edit made during upload survives.

[chapter-content-start]: #
### Follow the code

Natural-key IDs allow two devices to refer to the same title/chapter without sharing a local insertion counter. Identity migration remaps existing relationships, not just primary rows. Field paths and clocks determine which data is eligible and which edit wins. Local mutations record their outbox/deletion change in the same coherent operation; remote application suppresses echo recording. An acknowledgement targets the exact uploaded sequence so a newer edit survives.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncIds.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncClock.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncPaths.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncIdentityMigration.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/MangayomiNamespace.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/HubResync.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncIds.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncIds.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncIds.kt).

Stable natural-key IDs use the recorded FNV-1a 64-bit calculation masked into positive nonzero 63-bit values. Entities without a natural key use independent random IDs; preserve the relationship remapping during migration.

The implementation below defines `SyncIds`, `stable`, `random`, `manga`, `chapter`, `history`, `update`, `track`, `forManga`, `forChapter` and 3 further declarations.

The source describes its contract as:

> Stable 63-bit ids derived from natural keys, so the same title added on two devices is the same row on the hub and merging is automatic. FNV-1a 64 over the key string, masked positive, never 0. Entities without a natural key (categories) get a random id instead of a local counter.

Cross-chapter imports used by this file: [`DbChapter`](../chapters/02-domain-and-settings-models.md), [`DbHistory`](../chapters/02-domain-and-settings-models.md), [`DbItemType`](../chapters/02-domain-and-settings-models.md), [`DbManga`](../chapters/02-domain-and-settings-models.md), [`DbTrack`](../chapters/02-domain-and-settings-models.md), [`DbUpdate`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.database.sync

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbUpdate
import kotlin.random.Random

/**
 * Stable 63-bit ids derived from natural keys, so the same title added on two devices is the same
 * row on the hub and merging is automatic. FNV-1a 64 over the key string, masked positive, never 0.
 * Entities without a natural key (categories) get a random id instead of a local counter.
 */
object SyncIds {
    private const val FNV_OFFSET: Long = -3750763034362895579L // 0xcbf29ce484222325
    private const val FNV_PRIME: Long = 1099511628211L

    fun stable(key: String): Long {
        var h = FNV_OFFSET
        for (b in key.encodeToByteArray()) {
            h = h xor (b.toLong() and 0xff)
            h *= FNV_PRIME
        }
        val v = h and Long.MAX_VALUE
        return if (v == 0L) 1L else v
    }

    fun random(): Long = Random.nextLong(1L, Long.MAX_VALUE)

    fun manga(itemType: DbItemType, sourceKey: String, link: String): Long = stable("manga|${itemType.name}|$sourceKey|$link")
    fun chapter(mangaId: Long, url: String): Long = stable("chapter|$mangaId|$url")
    fun history(mangaId: Long): Long = stable("history|$mangaId")
    fun update(mangaId: Long, chapterId: Long): Long = stable("update|$mangaId|$chapterId")
    fun track(mangaId: Long, syncId: Int): Long = stable("track|$mangaId|$syncId")

    /** Null when the row has no natural key yet (no link / source), in which case the caller falls back to [random]. */
    fun forManga(m: DbManga): Long? {
        val link = m.link?.takeIf { it.isNotBlank() } ?: return null
        val source = m.sourceId?.toString() ?: m.source?.takeIf { it.isNotBlank() } ?: return null
        return manga(m.itemType, source, link)
    }

    fun forChapter(c: DbChapter): Long? {
        val mangaId = c.mangaId?.takeIf { it != 0L } ?: return null
        val key = c.url.takeIf { it.isNotBlank() } ?: c.archivePath.takeIf { it.isNotBlank() } ?: return null
        return chapter(mangaId, key)
    }

    fun forHistory(h: DbHistory): Long? = h.mangaId?.takeIf { it != 0L }?.let(::history)

    fun forUpdate(u: DbUpdate): Long? {
        val mangaId = u.mangaId?.takeIf { it != 0L } ?: return null
        val chapterId = u.chapterId?.takeIf { it != 0L } ?: return null
        return update(mangaId, chapterId)
    }

    fun forTrack(t: DbTrack): Long? {
        val mangaId = t.mangaId?.takeIf { it != 0L } ?: return null
        val syncId = t.syncId ?: return null
        return track(mangaId, syncId)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncClock.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncClock.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncClock.kt).

The implementation below defines `SyncClock`, `pack`, `millisOf`, `counterOf`, `tick`, `observe`, `peek`.

The source describes its contract as:

> Hybrid logical clock shared with the hub: 48 bits of wall-clock milliseconds, 16 bits of counter, packed in one Long so it sorts numerically. Every outbox op gets a tick; every hub response is observed so this device can never fall behind clocks it has already seen.

Cross-chapter imports used by this file: [`nowMillis`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.database.sync

import eu.friedcutlet.yokan.util.nowMillis
import kotlin.concurrent.atomics.AtomicLong
import kotlin.concurrent.atomics.ExperimentalAtomicApi

/**
 * Hybrid logical clock shared with the hub: 48 bits of wall-clock milliseconds, 16 bits of counter,
 * packed in one Long so it sorts numerically. Every outbox op gets a tick; every hub response is
 * observed so this device can never fall behind clocks it has already seen.
 */
@OptIn(ExperimentalAtomicApi::class)
object SyncClock {
    private val last = AtomicLong(0L)

    fun pack(ms: Long, counter: Int): Long = (ms shl 16) or (counter.toLong() and 0xffff)
    fun millisOf(t: Long): Long = t ushr 16
    fun counterOf(t: Long): Int = (t and 0xffff).toInt()

    fun tick(): Long {
        while (true) {
            val prev = last.load()
            val now = nowMillis()
            val next = when {
                now > millisOf(prev) -> pack(now, 0)
                counterOf(prev) == 0xffff -> pack(millisOf(prev) + 1, 0)
                else -> prev + 1
            }
            if (last.compareAndSet(prev, next)) return next
        }
    }

    fun observe(remote: Long) {
        while (true) {
            val prev = last.load()
            if (remote <= prev || last.compareAndSet(prev, remote)) return
        }
    }

    fun peek(): Long = last.load()
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncPaths.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncPaths.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncPaths.kt).

The implementation below defines `SyncPaths`, `PathChange`, `excluded`, `keyedFields`, `idSetFields`, `elementKey`, `doc`, `syncContentChanged`, `localUpdatedAt`, `toDoc` and 11 further declarations.

The source describes its contract as:

> Wire shape of a synced entity and the path-level diff that feeds the outbox. The hub stores each entity as a JSON object and merges per *path*: a top-level field, or `field.key` for keyed collections. So a `List\<DbPersonalReaderMode\>` travels as `{ "\<mangaId\>": {...element...} }` and a manga's `categories: List\<Long\>` as `{ "\<id\>": true }`. `yokan-hub/src/snapshots.rs::to_backup_snapshot` performs the inverse on export.

Cross-chapter imports used by this file: [`DbCategory`](../chapters/02-domain-and-settings-models.md), [`DbChapter`](../chapters/02-domain-and-settings-models.md), [`DbHistory`](../chapters/02-domain-and-settings-models.md), [`DbManga`](../chapters/02-domain-and-settings-models.md), [`DbOutboxOp`](../chapters/02-domain-and-settings-models.md), [`DbPersonalReaderMode`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.database.sync

import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbOutboxOp
import eu.friedcutlet.yokan.database.DbPersonalReaderMode
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbUpdate
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.serialization.KSerializer
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.encodeToJsonElement
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

/**
 * Wire shape of a synced entity and the path-level diff that feeds the outbox.
 *
 * The hub stores each entity as a JSON object and merges per *path*: a top-level field, or
 * `field.key` for keyed collections. So a `List<DbPersonalReaderMode>` travels as
 * `{ "<mangaId>": {...element...} }` and a manga's `categories: List<Long>` as `{ "<id>": true }`.
 * `yokan-hub/src/snapshots.rs::to_backup_snapshot` performs the inverse on export.
 */
object SyncPaths {
    const val KIND_CATEGORY = 1
    const val KIND_MANGA = 2
    const val KIND_CHAPTER = 3
    const val KIND_TRACK = 4
    const val KIND_HISTORY = 5
    const val KIND_UPDATE = 6
    const val KIND_SETTINGS = 7
    const val SETTINGS_ID = 1L
    const val DELETED = "_deleted"

    val json: Json = Json {
        encodeDefaults = true
        explicitNulls = false
        ignoreUnknownKeys = true
    }

    /** `value == null` removes the path. */
    data class PathChange(val path: String, val value: JsonElement?)

    /**
     * The one list of device-local [DbSettings] fields: never pushed through sync and never
     * overwritten by a restored backup (see [preserveDeviceLocalSettings]). Paths, loopback
     * endpoints and credentials only make sense on the machine that set them.
     */
    private val settingsDeviceLocal = setOf(
        "id", "syncIdentityVersion",
        // device paths and processes
        "localFolders", "namedLocalFolders", "downloadLocalFolderName", "askDownloadDestination",
        "downloadLocation", "autoBackupLocation", "themeSeedImagePath", "androidProxyServer", "cloudflareBypassProxyUrl",
        "jrePath", "extensionServerPath", "btServerAddress", "btServerPort", "desktopCloseToTray", "desktopLaunchAtLogin",
        "customHubServers",
        // secrets and caches
        "cookiesList", "metadataServerToken", "updateErrors",
        // Discovery layout, installed-source references and API credentials belong to this device.
        "features",
        // debugging
        "enableLogs", "enableFileLogging", "developerMode",
        // Title-owned preferences need explicit owner remapping before hub protocol support.
        "chapterReleasePreferences",
        "automaticReaderLayout", "automaticReaderLayouts",
        "readerHoldToScroll",
        // E-ink display mode describes this device's screen.
        "einkMode", "einkPreset", "einkRefreshEveryPages", "einkOptimizeDownloads",
    )

    private val excludedByKind: Map<Int, Set<String>> = mapOf(
        KIND_MANGA to setOf("id", "customCoverImage", "privateNote"),
        // Only downloads set downloadSize; with it, archivePath is this device's download folder (see hasDownloadMark).
        KIND_CHAPTER to setOf("id", "downloadSize"),
        KIND_SETTINGS to settingsDeviceLocal,
    )

    fun excluded(kind: Int): Set<String> = excludedByKind[kind] ?: setOf("id")

    private const val SOURCE_PREF_KEY = "sourceId+key"

    private val settingsKeyed: Map<String, String> = mapOf(
        "sortChapterList" to "mangaId",
        "chapterFilterDownloadedList" to "mangaId",
        "chapterFilterUnreadList" to "mangaId",
        "chapterFilterBookmarkedList" to "mangaId",
        "chapterPageIndexList" to "chapterId",
        "personalReaderModeList" to "mangaId",
        "filterScanlatorList" to "mangaId",
        "personalPageModeList" to "mangaId",
        "autoScrollPages" to "mangaId",
        "titleMetadata" to "mangaId",
        "sourcePreferences" to SOURCE_PREF_KEY,
    )

    /** Fields stored as objects keyed by an element field, so two devices can edit different entries. */
    fun keyedFields(kind: Int): Map<String, String> = if (kind == KIND_SETTINGS) settingsKeyed else emptyMap()

    /** `List<Long>` fields stored as `{ "<id>": true }` (a set with per-element clocks). */
    fun idSetFields(kind: Int): Set<String> = if (kind == KIND_MANGA) setOf("categories") else emptySet()

    private fun elementKey(spec: String, element: JsonObject): String? = if (spec == SOURCE_PREF_KEY) {
        val s = element["sourceId"]?.jsonPrimitive?.content ?: return null
        val k = element["key"]?.jsonPrimitive?.content ?: return null
        "$s:$k"
    } else {
        element[spec]?.jsonPrimitive?.content
    }

    fun <T> doc(kind: Int, serializer: KSerializer<T>, value: T): JsonObject =
        toDoc(kind, json.encodeToJsonElement(serializer, value).jsonObject)

    /** Content equality used for local timestamps: excludes device-local fields and updatedAt itself. */
    fun <T> syncContentChanged(kind: Int, serializer: KSerializer<T>, before: T, after: T): Boolean {
        val old = doc(kind, serializer, before).filterKeys { it != "updatedAt" }
        val next = doc(kind, serializer, after).filterKeys { it != "updatedAt" }
        return old != next
    }

    fun <T> localUpdatedAt(kind: Int, serializer: KSerializer<T>, previous: T?, incoming: T, timestamp: (T) -> Long): Long {
        val incomingAt = timestamp(incoming)
        if (previous == null) return maxOf(nowMillis(), incomingAt)
        if (!syncContentChanged(kind, serializer, previous, incoming)) return timestamp(previous)
        val priorAt = timestamp(previous)
        val nextAt = if (priorAt == Long.MAX_VALUE) priorAt else priorAt + 1
        return maxOf(nowMillis(), incomingAt, nextAt)
    }

    fun toDoc(kind: Int, obj: JsonObject): JsonObject {
        val excluded = excluded(kind)
        val keyed = keyedFields(kind)
        val idSets = idSetFields(kind)
        return buildJsonObject {
            for ((k, v) in obj) {
                if (k in excluded || (kind == KIND_SETTINGS && k == "home")) continue
                if (kind == KIND_CHAPTER && k == "archivePath" && obj.hasDownloadMark()) {
                    // Local-library chapters keep syncing their (virtual) archivePath; a download's path stays here.
                    put(k, JsonPrimitive(""))
                    continue
                }
                when {
                    k in idSets && v is JsonArray -> put(k, buildJsonObject { v.forEach { put(it.jsonPrimitive.content, JsonPrimitive(true)) } })
                    k in keyed && v is JsonArray -> put(
                        k,
                        buildJsonObject {
                            val spec = keyed.getValue(k)
                            v.forEach { el ->
                                val o = el as? JsonObject ?: return@forEach
                                elementKey(spec, o)?.let { put(it, o) }
                            }
                        },
                    )
                    else -> put(k, v)
                }
            }
        }
    }

    fun fromDoc(kind: Int, doc: JsonObject): JsonObject {
        val keyed = keyedFields(kind)
        val idSets = idSetFields(kind)
        return buildJsonObject {
            for ((k, v) in doc) {
                if (k == DELETED) continue
                when {
                    k in idSets && v is JsonObject -> put(k, JsonArray(v.keys.mapNotNull { it.toLongOrNull() }.sorted().map(::JsonPrimitive)))
                    k in keyed && v is JsonObject -> put(k, JsonArray(v.values.toList()))
                    else -> put(k, v)
                }
            }
        }
    }

    /** Path-level difference between two docs; keyed and id-set fields diff one level down. */
    fun diff(kind: Int, before: JsonObject?, after: JsonObject): List<PathChange> {
        val nested = keyedFields(kind).keys + idSetFields(kind)
        val out = ArrayList<PathChange>()
        for (k in LinkedHashSet(before?.keys.orEmpty() + after.keys)) {
            val a = before?.get(k)
            val b = after[k]
            if (a == b) continue
            if (k in nested && (a == null || a is JsonObject) && (b == null || b is JsonObject)) {
                val ao = a
                val bo = b
                for (sub in LinkedHashSet(ao?.keys.orEmpty() + bo?.keys.orEmpty())) {
                    val x = ao?.get(sub)
                    val y = bo?.get(sub)
                    if (x != y) out += PathChange("$k.$sub", y)
                }
            } else {
                out += PathChange(k, b)
            }
        }
        return out
    }

    /**
     * Merge an incoming hub doc onto the local object: every synced field comes from the hub
     * (absent means removed), excluded fields keep their local value even when an older client
     * pushed them to the hub, `id` is the entity key. A chapter keeps this device's download
     * folder, and a download folder pushed from another device is dropped.
     */
    fun applyIncoming(kind: Int, local: JsonObject?, incomingDoc: JsonObject, id: Long): JsonObject {
        val excluded = excluded(kind)
        val incoming = fromDoc(kind, incomingDoc)
        return buildJsonObject {
            local?.forEach { (k, v) -> if (k in excluded && k != "id") put(k, v) }
            incoming.forEach { (k, v) -> if (k !in excluded && !(kind == KIND_SETTINGS && k == "home")) put(k, v) }
            if (kind == KIND_CHAPTER) {
                when {
                    local?.hasDownloadMark() == true -> put("archivePath", local["archivePath"] ?: JsonPrimitive(""))
                    incoming.hasDownloadMark() -> put("archivePath", JsonPrimitive(""))
                }
            }
            put("id", JsonPrimitive(id))
        }
    }

    private fun JsonObject.hasDownloadMark(): Boolean = this["downloadSize"].let { it != null && it !is JsonNull }

    /** Put this device's still-pending values for their paths back on top of an incoming doc. */
    fun overlay(doc: JsonObject, pending: List<DbOutboxOp>): JsonObject {
        if (pending.isEmpty()) return doc
        val top = LinkedHashMap<String, JsonElement>(doc)
        for (op in pending) {
            if (op.path == DELETED) continue
            val value = op.value?.let(json::parseToJsonElement)
            val dot = op.path.indexOf('.')
            if (dot < 0) {
                if (value == null || value is JsonNull) top.remove(op.path) else top[op.path] = value
            } else {
                val field = op.path.substring(0, dot)
                val sub = op.path.substring(dot + 1)
                val inner = LinkedHashMap<String, JsonElement>((top[field] as? JsonObject).orEmpty())
                if (value == null || value is JsonNull) inner.remove(sub) else inner[sub] = value
                top[field] = JsonObject(inner)
            }
        }
        return JsonObject(top)
    }

    /** Every synced entity of [s] (restricted to [kinds]) as `(kind, id, doc)`. */
    fun docs(s: YokanDatabaseSnapshot, kinds: Set<Int> = ALL_KINDS): Sequence<Triple<Int, Long, JsonObject>> {
        fun <T> List<T>.docs(kind: Int, serializer: KSerializer<T>, id: (T) -> Long) =
            if (kind in kinds) asSequence().map { Triple(kind, id(it), doc(kind, serializer, it)) } else emptySequence()
        return s.categories.docs(KIND_CATEGORY, DbCategory.serializer(), DbCategory::id) +
            s.mangas.docs(KIND_MANGA, DbManga.serializer(), DbManga::id) +
            s.chapters.docs(KIND_CHAPTER, DbChapter.serializer(), DbChapter::id) +
            s.tracks.docs(KIND_TRACK, DbTrack.serializer(), DbTrack::id) +
            s.histories.docs(KIND_HISTORY, DbHistory.serializer(), DbHistory::id) +
            s.updates.docs(KIND_UPDATE, DbUpdate.serializer(), DbUpdate::id) +
            listOf(s.settings).docs(KIND_SETTINGS, DbSettings.serializer()) { SETTINGS_ID }
    }

    val ALL_KINDS: Set<Int> = (KIND_CATEGORY..KIND_SETTINGS).toSet()

    /**
     * Epoch new outbox ops belong to: the logged-in hub's (0 until negotiated), or null while no hub
     * is active. Nothing is recorded then; the first sync seeds the hub with full local state.
     */
    fun activeHubEpoch(prefs: List<DbSyncPreference>): Int? = prefs.firstOrNull {
        it.serverProvider == SyncServerProvider.YokanHub && it.syncOn && !it.authToken.isNullOrBlank() &&
            !it.server.isNullOrBlank() && !it.server.startsWith("cloud://")
    }?.hubEpoch

    /**
     * [after]'s outbox extended with every path that differs from [before], each with a fresh clock,
     * so a wholesale replacement (backup restore) reaches the hub like ordinary edits and wins over
     * what the hub had. Entities missing from [after] are sent as deletes. Without an active hub
     * nothing is added, as for ordinary edits.
     */
    fun outboxForReplacement(before: YokanDatabaseSnapshot, after: YokanDatabaseSnapshot): List<DbOutboxOp> {
        val epoch = activeHubEpoch(after.syncPreferences) ?: return after.outbox
        val old = docs(before).associate { (kind, id, doc) -> (kind to id) to doc }.toMutableMap()
        var seq = after.outbox.maxOfOrNull { it.seq } ?: 0L
        val added = ArrayList<DbOutboxOp>()
        fun add(kind: Int, id: Long, change: PathChange) {
            added += DbOutboxOp(kind = kind, id = id, path = change.path, value = change.value?.toString(), hlc = SyncClock.tick(), seq = ++seq, epoch = epoch)
        }
        for ((kind, id, doc) in docs(after)) {
            for (change in diff(kind, old.remove(kind to id), doc)) add(kind, id, change)
        }
        for ((key, _) in old) add(key.first, key.second, PathChange(DELETED, JsonPrimitive(true)))
        if (added.isEmpty()) return after.outbox
        val replaced = added.mapTo(HashSet()) { Triple(it.kind, it.id, it.path) }
        return after.outbox.filterNot { Triple(it.kind, it.id, it.path) in replaced } + added
    }
}

/**
 * [incoming] settings (e.g. from a restored backup) with every device-local field
 * ([SyncPaths.excluded] for [SyncPaths.KIND_SETTINGS]) kept from [current].
 */
fun preserveDeviceLocalSettings(current: DbSettings, incoming: DbSettings): DbSettings {
    val json = SyncPaths.json
    val local = json.encodeToJsonElement(DbSettings.serializer(), current).jsonObject
    val merged = json.encodeToJsonElement(DbSettings.serializer(), incoming).jsonObject.toMutableMap()
    for (key in SyncPaths.excluded(SyncPaths.KIND_SETTINGS)) {
        // explicitNulls = false omits null fields; removing the key restores the null default.
        val value = local[key]
        if (value == null) merged.remove(key) else merged[key] = value
    }
    return json.decodeFromJsonElement(DbSettings.serializer(), JsonObject(merged))
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncIdentityMigration.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncIdentityMigration.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncIdentityMigration.kt).

The implementation below defines `SyncIdentityMigration`, `ensure`, `remap`, `manga`, `chapter`, `List`.

The source describes its contract as:

> One-time rewrite of local auto-increment ids to \[SyncIds\] so this device can merge with others. Runs once per install (tracked in `DbSettings.syncIdentityVersion`); every foreign key and every keyed settings list follows the rewritten ids. Duplicates that collapse onto one stable id keep the most recently updated row.

Cross-chapter imports used by this file: [`YokanDatabase`](../chapters/03-persistence-and-migrations.md), [`YokanDatabaseSnapshot`](../chapters/03-persistence-and-migrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.database.sync

import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot

/**
 * One-time rewrite of local auto-increment ids to [SyncIds] so this device can merge with others.
 * Runs once per install (tracked in `DbSettings.syncIdentityVersion`); every foreign key and every
 * keyed settings list follows the rewritten ids. Duplicates that collapse onto one stable id keep
 * the most recently updated row.
 */
object SyncIdentityMigration {
    const val VERSION = 1

    fun ensure(db: YokanDatabase) {
        val current = db.snapshot()
        if (current.settings.syncIdentityVersion >= VERSION) return
        val remapped = remap(current)
        db.replaceAll(
            remapped.copy(settings = remapped.settings.copy(syncIdentityVersion = VERSION)),
            expectedSnapshot = current,
        )
    }

    fun remap(s: YokanDatabaseSnapshot): YokanDatabaseSnapshot {
        val mangaIds = HashMap<Long, Long>()
        val mangas = s.mangas
            .map { m -> m.copy(id = SyncIds.forManga(m) ?: m.id).also { mangaIds[m.id] = it.id } }
            .dedupe { it.id to it.updatedAt }

        val categoryIds = HashMap<Long, Long>()
        val categories = s.categories.map { c -> c.copy(id = SyncIds.random()).also { categoryIds[c.id] = it.id } }
        val mangasWithCategories = mangas.map { m -> m.copy(categories = m.categories?.map { categoryIds[it] ?: it }?.distinct()) }

        val chapterIds = HashMap<Long, Long>()
        val chapters = s.chapters
            .map { c ->
                val moved = c.copy(mangaId = c.mangaId?.let { mangaIds[it] ?: it })
                moved.copy(id = SyncIds.forChapter(moved) ?: c.id).also { chapterIds[c.id] = it.id }
            }
            .dedupe { it.id to it.updatedAt }

        fun manga(id: Long?) = id?.let { mangaIds[it] ?: it }
        fun chapter(id: Long?) = id?.let { chapterIds[it] ?: it }

        val histories = s.histories
            .map { h ->
                val moved = h.copy(mangaId = manga(h.mangaId), chapterId = chapter(h.chapterId))
                moved.copy(id = SyncIds.forHistory(moved) ?: h.id)
            }
            .dedupe { it.id to it.updatedAt }
        val updates = s.updates
            .map { u ->
                val moved = u.copy(mangaId = manga(u.mangaId), chapterId = chapter(u.chapterId))
                moved.copy(id = SyncIds.forUpdate(moved) ?: u.id)
            }
            .dedupe { it.id to it.updatedAt }
        val tracks = s.tracks
            .map { t ->
                val moved = t.copy(mangaId = manga(t.mangaId))
                moved.copy(id = SyncIds.forTrack(moved) ?: t.id)
            }
            .dedupe { it.id to it.updatedAt }
        val downloads = s.downloads.map { d -> d.copy(chapterId = chapter(d.chapterId)) }
        val pageCache = s.pageCache.map { p -> p.copy(chapterId = chapter(p.chapterId)) }

        val st = s.settings
        val settings = st.copy(
            chapterReleasePreferences = st.chapterReleasePreferences.map { it.copy(mangaId = manga(it.mangaId)) },
            automaticReaderLayouts = st.automaticReaderLayouts.map { it.copy(mangaId = manga(it.mangaId) ?: it.mangaId) },
            sortChapterList = st.sortChapterList?.map { it.copy(mangaId = manga(it.mangaId)) },
            chapterFilterDownloadedList = st.chapterFilterDownloadedList?.map { it.copy(mangaId = manga(it.mangaId)) },
            chapterFilterUnreadList = st.chapterFilterUnreadList?.map { it.copy(mangaId = manga(it.mangaId)) },
            chapterFilterBookmarkedList = st.chapterFilterBookmarkedList?.map { it.copy(mangaId = manga(it.mangaId)) },
            chapterPageIndexList = st.chapterPageIndexList?.map { it.copy(chapterId = chapter(it.chapterId)) },
            personalReaderModeList = st.personalReaderModeList?.map { it.copy(mangaId = manga(it.mangaId)) },
            filterScanlatorList = st.filterScanlatorList?.map { it.copy(mangaId = manga(it.mangaId)) },
            personalPageModeList = st.personalPageModeList?.map { it.copy(mangaId = manga(it.mangaId)) },
            autoScrollPages = st.autoScrollPages?.map { it.copy(mangaId = manga(it.mangaId)) },
            titleMetadata = st.titleMetadata?.map { it.copy(mangaId = manga(it.mangaId) ?: it.mangaId) },
        )

        return s.copy(
            settings = settings,
            mangas = mangasWithCategories,
            chapters = chapters,
            categories = categories,
            histories = histories,
            updates = updates,
            tracks = tracks,
            downloads = downloads,
            pageCache = pageCache,
            changedParts = emptyList(),
            outbox = emptyList(),
        )
    }

    /** Keep one row per id: the one with the greatest secondary key (updatedAt). */
    private inline fun <T> List<T>.dedupe(key: (T) -> Pair<Long, Long>): List<T> {
        val best = LinkedHashMap<Long, T>()
        for (item in this) {
            val (id, stamp) = key(item)
            val current = best[id]
            if (current == null || key(current).second <= stamp) best[id] = item
        }
        return best.values.toList()
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/MangayomiNamespace.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/MangayomiNamespace.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/MangayomiNamespace.kt).

The implementation below defines `normalizeMangayomiServer`, `mangayomiBoundRows`, `mangayomiDeleteParts`, `RemovedRow`, `MutableList`, `deleteParts`, `DbChangedPart.mangayomiDeleteKey`.

The source describes its contract as:

> Canonical host/scheme while preserving path case; account identity is appended separately.

Cross-chapter imports used by this file: [`DbActionType`](../chapters/02-domain-and-settings-models.md), [`DbChangedPart`](../chapters/02-domain-and-settings-models.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`YokanDatabaseSnapshot`](../chapters/03-persistence-and-migrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.database.sync

import eu.friedcutlet.yokan.database.DbActionType
import eu.friedcutlet.yokan.database.DbChangedPart
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

/** Canonical host/scheme while preserving path case; account identity is appended separately. */
internal fun normalizeMangayomiServer(value: String): String? {
    val raw = value.trim().trimEnd('/')
    val match = Regex("^([A-Za-z][A-Za-z0-9+.-]*://)([^/]+)(.*)$").matchEntire(raw) ?: return null
    return match.groupValues[1].lowercase() + match.groupValues[2].lowercase() + match.groupValues[3]
}

/**
 * Namespace -> "kind|localId" rows bound in persisted Mangayomi mappings. Mappings are persisted before every
 * upload, so an unbound row never reached that server and needs no deletion record.
 */
internal fun mangayomiBoundRows(prefs: Iterable<DbSyncPreference>): Map<String, Set<String>> {
    val result = linkedMapOf<String, MutableSet<String>>()
    for (pref in prefs) {
        val raw = pref.mangayomiIdMappings ?: continue
        val namespaces = runCatching { Json.parseToJsonElement(raw).jsonObject["namespaces"] as? JsonObject }.getOrNull() ?: continue
        namespaces.forEach { (namespace, kinds) ->
            val rows = result.getOrPut(namespace) { linkedSetOf() }
            (kinds as? JsonObject)?.forEach { (kind, locals) -> (locals as? JsonObject)?.keys?.forEach { rows += "$kind|$it" } }
        }
    }
    return result
}

/**
 * Mangayomi delete records for rows present in [before] but not in [after] that a server already knows
 * (see [mangayomiBoundRows] over both snapshots' preferences). Rows already queued in [existing] are skipped,
 * and new record ids avoid the ids in [existing].
 */
internal fun mangayomiDeleteParts(
    before: YokanDatabaseSnapshot,
    after: YokanDatabaseSnapshot,
    existing: List<DbChangedPart>,
    now: Long,
): List<DbChangedPart> {
    val bound = mangayomiBoundRows(before.syncPreferences + after.syncPreferences)
    if (bound.isEmpty()) return emptyList()
    val removed = buildList {
        addRemoved(before.categories.map { it.id }, after.categories.map { it.id }, SyncPaths.KIND_CATEGORY, DbActionType.RemoveCategory)
        addRemoved(before.mangas.map { it.id }, after.mangas.map { it.id }, SyncPaths.KIND_MANGA, DbActionType.RemoveItem)
        addRemoved(before.chapters.map { it.id }, after.chapters.map { it.id }, SyncPaths.KIND_CHAPTER, DbActionType.RemoveChapter)
        addRemoved(before.tracks.map { it.id }, after.tracks.map { it.id }, SyncPaths.KIND_TRACK, DbActionType.RemoveTrack)
        addRemoved(before.histories.map { it.id }, after.histories.map { it.id }, SyncPaths.KIND_HISTORY, DbActionType.RemoveHistory)
        addRemoved(before.updates.map { it.id }, after.updates.map { it.id }, SyncPaths.KIND_UPDATE, DbActionType.RemoveUpdate)
    }
    return deleteParts(removed, bound, existing, now)
}

/** [mangayomiDeleteParts] for one row removed under [preferences]. */
internal fun mangayomiDeleteParts(
    kind: Int,
    id: Long,
    action: DbActionType,
    preferences: List<DbSyncPreference>,
    existing: List<DbChangedPart>,
    now: Long,
): List<DbChangedPart> = deleteParts(listOf(RemovedRow(kind, id, action)), mangayomiBoundRows(preferences), existing, now)

private class RemovedRow(val kind: Int, val id: Long, val action: DbActionType)

private fun MutableList<RemovedRow>.addRemoved(before: List<Long>, after: List<Long>, kind: Int, action: DbActionType) {
    val kept = after.toHashSet()
    before.forEach { id -> if (id !in kept) add(RemovedRow(kind, id, action)) }
}

private fun deleteParts(
    removed: List<RemovedRow>,
    bound: Map<String, Set<String>>,
    existing: List<DbChangedPart>,
    now: Long,
): List<DbChangedPart> {
    if (removed.isEmpty() || bound.isEmpty()) return emptyList()
    val queued = existing.mapNotNullTo(HashSet()) { it.mangayomiDeleteKey() }
    val usedIds = existing.mapTo(HashSet(), DbChangedPart::id)
    return buildList {
        for (row in removed) for ((namespace, rows) in bound) {
            if (row.id <= 0 || "${row.kind}|${row.id}" !in rows || !queued.add("$namespace|${row.kind}|${row.id}")) continue
            val data = buildJsonObject {
                put("provider", JsonPrimitive(MANGAYOMI_PROVIDER))
                put("namespace", JsonPrimitive(namespace))
                put("kind", JsonPrimitive(row.kind))
                put("localId", JsonPrimitive(row.id.toString()))
            }.toString()
            var recordId = SyncIds.random()
            while (!usedIds.add(recordId)) recordId = SyncIds.random()
            add(DbChangedPart(id = recordId, actionType = row.action, isarId = row.id, data = data, clientDate = now))
        }
    }
}

/** "namespace|kind|localId" of a queued Mangayomi delete record, or `null` for any other part. */
private fun DbChangedPart.mangayomiDeleteKey(): String? {
    val record = runCatching { Json.parseToJsonElement(data).jsonObject }.getOrNull() ?: return null
    if (record["provider"]?.jsonPrimitive?.content != MANGAYOMI_PROVIDER) return null
    val namespace = record["namespace"]?.jsonPrimitive?.content ?: return null
    val kind = record["kind"]?.jsonPrimitive?.content?.toIntOrNull() ?: return null
    val id = record["localId"]?.jsonPrimitive?.content?.toLongOrNull() ?: return null
    return "$namespace|$kind|$id"
}

private const val MANGAYOMI_PROVIDER = "mangayomi"
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/HubResync.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/HubResync.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/HubResync.kt).

The implementation below defines `DbSyncPreference.hubResync`.

The source describes its contract as:

> The preference after the hub reported \[epoch\], plus the epoch whose older outbox operations must be dropped (`null` keeps them). The first negotiation to epoch 1 is not a rollback.

Cross-chapter imports used by this file: [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.database.sync

import eu.friedcutlet.yokan.database.DbSyncPreference

/**
 * The preference after the hub reported [epoch], plus the epoch whose older outbox operations
 * must be dropped (`null` keeps them). The first negotiation to epoch 1 is not a rollback.
 */
internal fun DbSyncPreference.hubResync(epoch: Int): Pair<DbSyncPreference, Int?> {
    val initialNegotiation = hubEpoch == 0 && !hubBootstrapComplete && epoch == 1
    val rollback = !initialNegotiation && (hubEpoch > 0 || hubBootstrapComplete || epoch > 1)
    val dropBefore = epoch.takeIf { rollback && it > hubEpoch }
    val updated = copy(
        hubHead = 0,
        hubEpoch = maxOf(hubEpoch, epoch),
        hubRecoveryPending = hubRecoveryPending || dropBefore != null,
    )
    return updated to dropBefore
}
```
[chapter-file-end]: #

### Check your understanding

Edit a field again while its first version is being uploaded. Acknowledge the old sequence and confirm the second edit remains pending.
[chapter-content-end]: #


## Step 2: define provider-neutral lifecycle

Implement SyncService, login/status/results, operation monitor and HybridSyncService routing. Capture provider/server/account/credential/device ID for a run. Use ProfileSyncServices to bind calls and cancellation to the session. Recheck account identity at transfer/commit boundaries. Logging out or changing providers must prevent a stale response from committing credentials or last-success timestamps.

Implement SyncAccountLeases in the device registry. A profile can claim its configured remote account; a conflicting local profile is rejected before remote transfer. Key formats differ by provider; never store raw API tokens as lease keys. Preserve claim rollback on failed guarded credential writes and release on logout/deletion.

[chapter-content-start]: #
### Follow the code

Provider-neutral interfaces describe status/results and owned calls, not a universal wire format. Capture provider/server/account/credentials/device identity at admission and recheck it before committing state or success timestamps. Account leases prevent two local profiles from claiming conflicting remote identity. Failed guarded credential writes roll back a provisional claim. Profile wrappers cancel and join transfer/finalizer work on retirement.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncService.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncAccountLeases.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/ProfileSyncServices.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/StateSyncSupport.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HybridSyncService.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncService.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncService.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncService.kt).

The implementation below defines `SyncOperationStage`, `SyncOperationOutcome`, `SyncOperationState`, `SyncOperationMonitor`, `begin`, `progress`, `finish`, `SyncService`, `login`, `beginBrowserLogin` and 31 further declarations.

The source describes its contract as:

> 0..1 while a multi-page pull reports how far it got; null when unknown.

Cross-chapter imports used by this file: [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`BackupOptions`](../chapters/20-backup-and-restore.md), [`RestorePreview`](../chapters/20-backup-and-restore.md), [`PlatformLock`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.backup.BackupOptions
import eu.friedcutlet.yokan.services.backup.RestorePreview
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

enum class SyncOperationStage {
    Syncing,
    Uploading,
    Downloading,
}

enum class SyncOperationOutcome {
    Succeeded,
    Failed,
    Cancelled,
}

data class SyncOperationState(
    val activeCount: Int = 0,
    val stage: SyncOperationStage? = null,
    val lastOutcome: SyncOperationOutcome? = null,
    /** 0..1 while a multi-page pull reports how far it got; null when unknown. */
    val progress: Float? = null,
) {
    val isActive: Boolean get() = activeCount > 0
}

/** Shared operation tracker used by manual, scheduled, outbox, and live sync paths. */
class SyncOperationMonitor {
    private val lock = PlatformLock()
    private val active = linkedMapOf<Long, SyncOperationStage>()
    private var nextId = 0L
    private val _state = MutableStateFlow(SyncOperationState())
    val state: StateFlow<SyncOperationState> = _state.asStateFlow()

    fun begin(stage: SyncOperationStage): Long = lock.withLock {
        val id = ++nextId
        active[id] = stage
        _state.update { current ->
            current.copy(activeCount = active.size, stage = stage, progress = null)
        }
        id
    }

    fun progress(id: Long, fraction: Float) = lock.withLock {
        if (id !in active) return@withLock
        _state.update { it.copy(progress = fraction.coerceIn(0f, 1f)) }
    }

    fun finish(id: Long, outcome: SyncOperationOutcome) = lock.withLock {
        if (active.remove(id) == null) return@withLock
        _state.update { current ->
            current.copy(
                activeCount = active.size,
                stage = active.values.lastOrNull(),
                lastOutcome = outcome,
                progress = null,
            )
        }
    }
}

private val IdleSyncOperationState = MutableStateFlow(SyncOperationState())

interface SyncService {
    val operationState: StateFlow<SyncOperationState>
        get() = IdleSyncOperationState
    suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult
    fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? = null
    suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult? = null
    fun cancelBrowserLogin(attempt: BrowserLoginAttempt) = Unit
    suspend fun logout(syncId: Long)
    suspend fun sync(syncId: Long, settings: DbSettings): SyncResult
    suspend fun pushChanges(syncId: Long): SyncResult
    suspend fun pullChanges(syncId: Long): SyncResult
    fun status(syncId: Long): SyncConnectionStatus
    fun close() = Unit
    /** Wait for owned calls and their finalizers before releasing transport resources. */
    suspend fun closeAndJoin() { close() }
}

/** Immutable, service-owned identity for one browser login, including its one-use CSRF state. */
@ConsistentCopyVisibility
data class BrowserLoginAttempt internal constructor(
    val syncId: Long,
    val server: String,
    val url: String,
    val device: String,
    val state: String,
    /** Redirect target the browser must intercept rather than load (OAuth loopback); null when the flow ends on a real page. */
    val callbackUrl: String? = null,
)

interface CloudStorageProvider {
    val descriptor: CloudProviderDescriptor

    suspend fun validate(connection: CloudConnection): CloudConnectionStatus
    suspend fun putObject(
        connection: CloudConnection,
        key: String,
        bytes: ByteArray,
        contentType: String,
    ): CloudObject

    suspend fun listObjects(connection: CloudConnection, prefix: String): List<CloudObject>
    suspend fun getObject(connection: CloudConnection, objectRef: CloudObject): ByteArray
}

class CloudStorageException(message: String) : RuntimeException(message)

interface CloudBackupSyncService : SyncService {
    fun providers(): List<CloudProviderDescriptor>
    fun isCloudPreference(syncPreference: eu.friedcutlet.yokan.database.DbSyncPreference?): Boolean
    suspend fun connect(syncId: Long, providerId: String, accountLabel: String?, accessToken: String): SyncLoginResult
    suspend fun uploadBackup(syncId: Long, options: BackupOptions): CloudBackupResult
    suspend fun restoreLatestBackup(syncId: Long): CloudBackupRestoreResult
}

data class SyncResult(
    val uploadedChanges: Int,
    val downloadedChanges: Int,
    val settingsSynced: Boolean,
    val errors: List<String> = emptyList(),
)

data class SyncLoginResult(
    val success: Boolean,
    val message: String,
)

data class SyncConnectionStatus(
    val loggedIn: Boolean,
    val email: String?,
    val server: String?,
    val lastSyncMillis: Long?,
)

data class CloudProviderDescriptor(
    val id: String,
    val displayName: String,
    val description: String,
    val authInstructions: String,
)

data class CloudConnection(
    val providerId: String,
    val accountLabel: String?,
    val accessToken: String,
)

data class CloudConnectionStatus(
    val connected: Boolean,
    val accountLabel: String? = null,
    val message: String = "",
)

data class CloudObject(
    val key: String,
    val displayName: String,
    val sizeBytes: Long,
    val modifiedAtMillis: Long,
    val providerFileId: String? = null,
)

data class CloudBackupResult(
    val providerId: String,
    val fileName: String,
    val itemCount: Int,
    val bytesUploaded: Long,
    val remoteObject: CloudObject,
)

data class CloudBackupRestoreResult(
    val providerId: String,
    val fileName: String,
    val preview: RestorePreview,
)
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncAccountLeases.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncAccountLeases.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncAccountLeases.kt).

The implementation below defines `SyncAccountLeases`, `claim`, `release`, `syncLeaseKey`, `DbSyncPreference`, `SyncAccountLeases.claimFailure`, `adoptConfiguredSyncAccount`, `SyncAccountLeases.releaseQuietly`, `SyncAccountLeases.commitClaimed`.

The source describes its contract as:

> Device-wide ownership of remote sync accounts, so two profiles never sync into one library. \[claim\] throws with a user-facing message when another profile holds \[key\].

Cross-chapter imports used by this file: [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`SyncServerProvider`](../chapters/02-domain-and-settings-models.md), [`YokanDatabase`](../chapters/03-persistence-and-migrations.md), [`normalizeHubServer`](../chapters/05-http-cookies-and-webviews.md), [`AppLogger`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.sync.normalizeMangayomiServer
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.normalizeHubServer
import eu.friedcutlet.yokan.services.logging.AppLogger
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * Device-wide ownership of remote sync accounts, so two profiles never sync into one library.
 * [claim] throws with a user-facing message when another profile holds [key].
 */
interface SyncAccountLeases {
    suspend fun claim(key: String)
    suspend fun release(key: String)

    companion object {
        /** Single-profile hosts and tests: every claim succeeds. */
        val None = object : SyncAccountLeases {
            override suspend fun claim(key: String) = Unit
            override suspend fun release(key: String) = Unit
        }
    }
}

/**
 * Lease key of a configured account (signed in or not). Account names are trimmed and lowercased, so one
 * account is one key as far as the stored name allows (Mangayomi password logins store the typed email,
 * OAuth the server username: the same account reached both ways yields two keys). A blank account name
 * still leases the server, so only one profile may use an unnamed account there.
 */
internal fun syncLeaseKey(preference: DbSyncPreference?): String? {
    val server = preference?.server ?: return null
    val account = preference.email.orEmpty().trim()
    val key = when {
        // SyncYomi has no account name: the API key selects the account, so lease by its digest, never the raw key.
        preference.serverProvider == SyncServerProvider.SyncYomi -> "syncyomi|${normalizeSyncYomiHost(server) ?: return null}|${syncYomiKeyLabel(preference.authToken)}"
        // Google Drive state sync keeps the user's OAuth client id in `server`.
        preference.serverProvider == SyncServerProvider.GoogleDrive -> "gdrive|${server.trim().takeIf(String::isNotEmpty) ?: return null}|$account"
        server.startsWith(CloudServerPrefix) -> "cloud|${providerIdFromServer(server) ?: return null}|$account"
        preference.serverProvider == SyncServerProvider.Mangayomi -> "mangayomi|${normalizeMangayomiServer(server) ?: return null}|$account"
        else -> "hub|${normalizeHubServer(server) ?: return null}|$account"
    }
    return key.lowercase()
}

private fun DbSyncPreference?.signedIn() = !this?.authToken.isNullOrBlank() && syncLeaseKey(this) != null

/** Claims [preference]'s account if signed in; the failure message, or null when this profile may use it. */
internal suspend fun SyncAccountLeases.claimFailure(preference: DbSyncPreference?): String? {
    if (!preference.signedIn()) return null
    val key = syncLeaseKey(preference) ?: return null
    return try {
        claim(key); null
    } catch (cancelled: CancellationException) {
        throw cancelled
    } catch (error: Exception) {
        error.message ?: "Could not reserve this sync account for this profile."
    }
}

/**
 * Adopts the account a profile already uses (e.g. Default's pre-lease login) as soon as it opens. A conflict
 * is only logged; every sync operation re-checks the lease and reports it as its error.
 */
internal fun adoptConfiguredSyncAccount(leases: SyncAccountLeases, database: YokanDatabase, scope: CoroutineScope) {
    scope.launch {
        catchingNonCancellation { leases.claimFailure(database.syncPreferences().firstOrNull()) }
            .getOrNull()?.let { AppLogger.warn("[sync] $it") }
    }
}

/** Best effort: a failed release only keeps the account reserved for this profile until its next logout/delete. */
internal suspend fun SyncAccountLeases.releaseQuietly(preference: DbSyncPreference?) {
    val key = syncLeaseKey(preference) ?: return
    try {
        withContext(NonCancellable) { release(key) }
    } catch (_: Exception) {
    }
}

/**
 * Claims [next]'s account right before the guarded credential [commit]. A rejected commit hands the lease
 * back to [previous]'s account (or releases it). Returns null once committed, else the message to show.
 */
internal suspend fun SyncAccountLeases.commitClaimed(
    previous: DbSyncPreference?,
    next: DbSyncPreference,
    commit: suspend () -> Boolean,
): String? {
    claimFailure(next)?.let { return it }
    var committed = false
    try {
        committed = commit()
    } finally {
        if (!committed) withContext(NonCancellable) {
            if (!previous.signedIn() || claimFailure(previous) != null) releaseQuietly(next)
        }
    }
    return if (committed) null else "Sync configuration changed during login; try again."
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/ProfileSyncServices.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/ProfileSyncServices.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/ProfileSyncServices.kt).

The implementation below defines `ProfileSyncServices`, `isOpen`, `runOwned`, `retire`, `release`, `close`, `closeAndJoin`, `login`, `beginBrowserLogin`, `completeBrowserLogin` and 11 further declarations.

The source describes its contract as:

> Both public sync entry points capture one session. UI callers are joined to that owner, including direct cloud connect/upload/restore calls that bypass the hybrid router. \[delegate\] owns and closes the raw cloud service as part of its provider graph.

Cross-chapter imports used by this file: [`ProfileId`](../chapters/04-profiles-and-lifetimes.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`BackupOptions`](../chapters/20-backup-and-restore.md), [`PlatformLock`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.services.backup.BackupOptions
import eu.friedcutlet.yokan.services.runJoined
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.withContext
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

/**
 * Both public sync entry points capture one session. UI callers are joined to that owner,
 * including direct cloud connect/upload/restore calls that bypass the hybrid router.
 * [delegate] owns and closes the raw cloud service as part of its provider graph.
 */
internal class ProfileSyncServices(
    val profileId: ProfileId,
    private val delegate: SyncService,
    cloudDelegate: CloudBackupSyncService,
    ownerScope: CoroutineScope,
) {
    private val lock = PlatformLock()
    private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) { "Profile sync requires an owner job" }
    private val job = SupervisorJob(ownerJob)
    private val scope = CoroutineScope(ownerScope.coroutineContext + job)
    private var retired = false
    private var released = false
    private var joined = false
    private val retirementLock = Mutex()

    val sync: SyncService = BoundSyncService(delegate)
    val cloud: CloudBackupSyncService = BoundCloudService(cloudDelegate)

    private fun isOpen() = !retired && ownerJob.isActive && job.isActive

    private suspend fun <T> runOwned(action: suspend () -> T): T = scope.runJoined(
        admit = { lock.withLock { if (!isOpen()) throw CancellationException("Profile sync session has ended") } },
    ) { action() }

    private fun retire() {
        lock.withLock { retired = true }
        job.cancel()
    }

    private fun release() = lock.withLock {
        if (!released) {
            delegate.close()
            released = true
        }
    }

    /** Legacy immediate shutdown; orderly session retirement uses [closeAndJoin]. */
    private fun close() { retire(); release() }

    private suspend fun closeAndJoin() {
        retire()
        withContext(NonCancellable) {
            retirementLock.withLock {
                job.cancelAndJoin()
                if (!joined) {
                    delegate.closeAndJoin()
                    lock.withLock { released = true; joined = true }
                }
            }
        }
    }

    private open inner class BoundSyncService(private val service: SyncService) : SyncService {
        override val operationState = service.operationState

        override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult =
            runOwned { service.login(syncId, server, email, password) }

        override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? = lock.withLock {
            if (isOpen()) service.beginBrowserLogin(syncId, server) else null
        }

        override suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult? =
            runOwned { service.completeBrowserLogin(attempt, loadedUrl) }

        override fun cancelBrowserLogin(attempt: BrowserLoginAttempt) = lock.withLock {
            if (isOpen()) service.cancelBrowserLogin(attempt)
        }

        override suspend fun logout(syncId: Long) = runOwned { service.logout(syncId) }
        override suspend fun sync(syncId: Long, settings: DbSettings): SyncResult = runOwned { service.sync(syncId, settings) }
        override suspend fun pushChanges(syncId: Long): SyncResult = runOwned { service.pushChanges(syncId) }
        override suspend fun pullChanges(syncId: Long): SyncResult = runOwned { service.pullChanges(syncId) }

        override fun status(syncId: Long): SyncConnectionStatus = lock.withLock {
            if (isOpen()) service.status(syncId) else SyncConnectionStatus(false, null, null, null)
        }

        override fun close() = this@ProfileSyncServices.close()
        override suspend fun closeAndJoin() = this@ProfileSyncServices.closeAndJoin()
    }

    private inner class BoundCloudService(private val service: CloudBackupSyncService) :
        BoundSyncService(service), CloudBackupSyncService {
        override fun providers(): List<CloudProviderDescriptor> = lock.withLock {
            if (isOpen()) service.providers() else emptyList()
        }

        override fun isCloudPreference(syncPreference: DbSyncPreference?): Boolean = lock.withLock {
            isOpen() && service.isCloudPreference(syncPreference)
        }

        override suspend fun connect(syncId: Long, providerId: String, accountLabel: String?, accessToken: String): SyncLoginResult =
            runOwned { service.connect(syncId, providerId, accountLabel, accessToken) }

        override suspend fun uploadBackup(syncId: Long, options: BackupOptions): CloudBackupResult =
            runOwned { service.uploadBackup(syncId, options) }

        override suspend fun restoreLatestBackup(syncId: Long): CloudBackupRestoreResult =
            runOwned { service.restoreLatestBackup(syncId) }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/StateSyncSupport.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/StateSyncSupport.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/StateSyncSupport.kt).

The implementation below defines `StateSyncException`, `SyncAccountChangedException`, `sameSyncAccount`, `YokanDatabase.checkSyncAccount`, `BackupService.mergeRemoteState`, `YokanDatabase.recordStateSync`, `runStateSync`, `stateSyncFailure`, `HttpService.requestOrNull`.

The source describes its contract as:

> A user-facing failure; the message is shown as the sync error.

Cross-chapter imports used by this file: [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`SnapshotReplacementConflictException`](../chapters/03-persistence-and-migrations.md), [`YokanDatabase`](../chapters/03-persistence-and-migrations.md), [`BackupOpenResult`](../chapters/20-backup-and-restore.md), [`BackupRestoreTargetChangedException`](../chapters/20-backup-and-restore.md), [`BackupService`](../chapters/20-backup-and-restore.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.SnapshotReplacementConflictException
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.backup.BackupOpenResult
import eu.friedcutlet.yokan.services.backup.BackupRestoreTargetChangedException
import eu.friedcutlet.yokan.services.backup.BackupService
import eu.friedcutlet.yokan.services.backup.RestoreMode
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

/*
 * Shared by the whole-backup state sync providers (SyncYomi, Google Drive): each run captures the exact account,
 * merges remote data through a guarded restore, and commits its watermark only while that account is still selected.
 */

/** A user-facing failure; the message is shown as the sync error. */
internal class StateSyncException(message: String) : Exception(message)

internal const val SyncAccountChangedMessage = "Sync configuration changed during the operation."

/** The captured account was replaced mid-run; distinct from cancellation so a live caller gets a failure result. */
internal class SyncAccountChangedException : IllegalStateException(SyncAccountChangedMessage)

/** Same account as [captured]: settings toggles may change mid-run, the identity may not. */
internal fun sameSyncAccount(captured: DbSyncPreference, current: DbSyncPreference?): Boolean = current != null &&
    current.syncId == captured.syncId && current.serverProvider == captured.serverProvider && current.server == captured.server &&
    current.email == captured.email && current.authToken == captured.authToken && current.deviceId == captured.deviceId

internal fun YokanDatabase.checkSyncAccount(captured: DbSyncPreference) {
    if (!sameSyncAccount(captured, syncPreferences().firstOrNull { it.syncId == captured.syncId })) {
        throw SyncAccountChangedException()
    }
}

/**
 * Merges remote backup [bytes] into the library; the predicate runs on the snapshot the atomic commit expects.
 * Returns the merged item count, or null when [bytes] is not a readable backup (callers then overwrite it).
 */
internal suspend fun BackupService.mergeRemoteState(bytes: ByteArray, captured: DbSyncPreference, label: String): Int? =
    when (val opened = openBackup(bytes)) {
        is BackupOpenResult.Ready -> try {
            applyBackupIf(opened.plan, RestoreMode.Merge) { snapshot ->
                sameSyncAccount(captured, snapshot.syncPreferences.firstOrNull { it.syncId == captured.syncId })
            }.itemCount
        } catch (_: BackupRestoreTargetChangedException) {
            throw SyncAccountChangedException()
        }
        is BackupOpenResult.Failure -> {
            AppLogger.warn("[sync] $label remote data is not a readable backup (${opened.error})")
            null
        }
    }

/** Records a completed run, unless the account changed meanwhile. */
internal suspend fun YokanDatabase.recordStateSync(captured: DbSyncPreference) {
    currentCoroutineContext().ensureActive()
    val now = nowMillis()
    val accepted = upsertSyncPreferenceIf(
        syncId = requireNotNull(captured.syncId),
        accepts = { sameSyncAccount(captured, it) },
        transform = { requireNotNull(it).copy(lastSyncManga = now, lastSyncHistory = now, lastSyncUpdate = now) },
    )
    if (!accepted) throw SyncAccountChangedException()
}

/** One tracked, serialized run; failures become [SyncResult.errors], a cancelled caller still cancels. */
internal suspend fun runStateSync(
    monitor: SyncOperationMonitor,
    mutex: Mutex,
    stage: SyncOperationStage,
    label: String,
    block: suspend () -> SyncResult,
): SyncResult {
    val operationId = monitor.begin(stage)
    var outcome = SyncOperationOutcome.Failed
    try {
        val result = try {
            mutex.withLock { block() }
        } catch (cancelled: CancellationException) {
            outcome = SyncOperationOutcome.Cancelled
            throw cancelled
        } catch (_: SyncAccountChangedException) {
            stateSyncFailure(SyncAccountChangedMessage)
        } catch (_: SnapshotReplacementConflictException) {
            stateSyncFailure("Library changed while applying $label data; sync again.")
        } catch (error: StateSyncException) {
            stateSyncFailure(error.message ?: "$label sync failed.")
        } catch (error: Exception) {
            AppLogger.warn("[sync] $label sync failed: ${error::class.simpleName}")
            stateSyncFailure("$label sync failed.")
        }
        if (result.errors.isEmpty()) outcome = SyncOperationOutcome.Succeeded
        else AppLogger.warn("[sync] $label ${stage.name.lowercase()}: ${result.errors.joinToString("; ")}")
        return result
    } finally {
        monitor.finish(operationId, outcome)
    }
}

internal fun stateSyncFailure(message: String) = SyncResult(0, 0, false, listOf(message))

/** Null when the server is unreachable; cancellation still propagates. */
internal suspend fun HttpService.requestOrNull(request: HttpRequest): HttpResponse? =
    try { request(request) } catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { null }
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HybridSyncService.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HybridSyncService.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HybridSyncService.kt).

The implementation below defines `HybridSyncService`, `login`, `beginBrowserLogin`, `completeBrowserLogin`, `cancelBrowserLogin`, `logout`, `sync`, `pushChanges`, `pullChanges`, `status` and 9 further declarations.

The source describes its contract as:

> Routes each call by the selected provider: SyncYomi and Google Drive state sync own all of theirs; for Yokan Hub and Mangayomi, `cloud://` preferences go to cloud backup sync.

Cross-chapter imports used by this file: [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`SyncServerProvider`](../chapters/02-domain-and-settings-models.md), [`YokanDatabase`](../chapters/03-persistence-and-migrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.YokanDatabase

/**
 * Routes each call by the selected provider: SyncYomi and Google Drive state sync own all of theirs;
 * for Yokan Hub and Mangayomi, `cloud://` preferences go to cloud backup sync.
 */
class HybridSyncService(
    private val serverSync: SyncService,
    private val cloudSync: CloudBackupSyncService,
    private val database: YokanDatabase,
    private val operationMonitor: SyncOperationMonitor? = null,
    private val mangayomiSync: SyncService? = null,
    private val syncYomiSync: SyncService? = null,
    private val googleDriveSync: SyncService? = null,
) : SyncService {
    override val operationState = operationMonitor?.state ?: serverSync.operationState
    private val all get() = listOfNotNull(serverSync, cloudSync, mangayomiSync, syncYomiSync, googleDriveSync)

    override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult {
        val provider = provider(syncId)
        val service = when {
            provider.isStateSync() -> target(preference(syncId))
            server.trim().startsWith(CloudServerPrefix) -> cloudSync
            provider == SyncServerProvider.Mangayomi -> mangayomiSync
            else -> serverSync
        }
        return service?.login(syncId, server, email, password) ?: SyncLoginResult(false, unavailableMessage(provider))
    }

    // Cloud providers have no sign-in page; every other provider owns its browser flow.
    override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? =
        if (provider(syncId) == SyncServerProvider.YokanHub) serverSync.beginBrowserLogin(syncId, server)
        else dedicated(provider(syncId))?.beginBrowserLogin(syncId, server)

    override suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult? =
        if (provider(attempt.syncId) == SyncServerProvider.YokanHub) serverSync.completeBrowserLogin(attempt, loadedUrl)
        else dedicated(provider(attempt.syncId))?.completeBrowserLogin(attempt, loadedUrl)

    override fun cancelBrowserLogin(attempt: BrowserLoginAttempt) {
        serverSync.cancelBrowserLogin(attempt)
        mangayomiSync?.cancelBrowserLogin(attempt)
        syncYomiSync?.cancelBrowserLogin(attempt)
        googleDriveSync?.cancelBrowserLogin(attempt)
    }

    override suspend fun logout(syncId: Long) {
        target(preference(syncId))?.logout(syncId)
    }

    override suspend fun sync(syncId: Long, settings: DbSettings): SyncResult =
        target(preference(syncId))?.sync(syncId, settings) ?: unavailable(syncId)

    override suspend fun pushChanges(syncId: Long): SyncResult =
        target(preference(syncId))?.pushChanges(syncId) ?: unavailable(syncId)

    override suspend fun pullChanges(syncId: Long): SyncResult =
        target(preference(syncId))?.pullChanges(syncId) ?: unavailable(syncId)

    override fun status(syncId: Long): SyncConnectionStatus =
        target(preference(syncId))?.status(syncId) ?: SyncConnectionStatus(false, null, null, null)

    override fun close() {
        all.forEach { it.close() }
    }

    override suspend fun closeAndJoin() {
        all.forEach { it.closeAndJoin() }
    }

    /** The service for [preference]; null when its provider's service is not part of this build. */
    private fun target(preference: DbSyncPreference?): SyncService? {
        val provider = preference?.serverProvider ?: SyncServerProvider.YokanHub
        return when {
            provider.isStateSync() -> dedicated(provider)
            cloudSync.isCloudPreference(preference) -> cloudSync
            provider == SyncServerProvider.Mangayomi -> mangayomiSync
            else -> serverSync
        }
    }

    private fun dedicated(provider: SyncServerProvider): SyncService? = when (provider) {
        SyncServerProvider.YokanHub -> null
        SyncServerProvider.Mangayomi -> mangayomiSync
        SyncServerProvider.SyncYomi -> syncYomiSync
        SyncServerProvider.GoogleDrive -> googleDriveSync
    }

    private fun SyncServerProvider.isStateSync() = this == SyncServerProvider.SyncYomi || this == SyncServerProvider.GoogleDrive

    private fun preference(syncId: Long): DbSyncPreference? =
        database.syncPreferences().firstOrNull { it.syncId == syncId }

    private fun provider(syncId: Long): SyncServerProvider = preference(syncId)?.serverProvider ?: SyncServerProvider.YokanHub

    private fun unavailableMessage(provider: SyncServerProvider) = when (provider) {
        SyncServerProvider.GoogleDrive -> "Google Drive sync is unavailable."
        else -> "${provider.name} sync is unavailable."
    }

    private fun unavailable(syncId: Long) = SyncResult(0, 0, false, listOf(unavailableMessage(provider(syncId))))
}
```
[chapter-file-end]: #

### Check your understanding

Change provider or log out during a suspended request. Verify the response cannot publish account data, cursor or last-success state into the replacement configuration.
[chapter-content-end]: #


## Step 3: implement Hub rounds

Build HubLogin and browser-attempt identity, authenticated requests, push/pull rounds and live events. Reproduce cursor, epoch, bootstrap eligibility and recovery-pending semantics. A server history reset must not be treated as a normal incremental pull. Preserve outbox while recovering and apply the reference bootstrap/overwrite clock policy.

Serialize rounds, send bounded batches, apply validated remote operations transactionally, acknowledge only uploaded versions and update cursor/epoch/account state with guards. Implement WebSocket reconnection through the owner scope and close its engine explicitly. Use HubSyncRoundTest and Docker integration fixtures for the exact wire protocol rather than inventing a similar REST shape.

[chapter-content-start]: #
### Follow the code

Hub rounds serialize bounded push/pull work and apply validated operations transactionally. Cursor, epoch, bootstrap and recovery-pending state distinguish an incremental pull from a server history reset. Preserve the journal while recovering; a reset is not permission to discard unsent local edits. Live WebSocket events request work through the same owner rather than opening independent unguarded commits.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubServers.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubLogin.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncService.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubLiveEvents.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubServers.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubServers.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubServers.kt).

The implementation below defines `HubServerEntry`, `HubServerList`, `fetchHubServers`.

The source describes its contract as:

> The maintained list of public yokan-hub servers, published with the app's releases.

Cross-chapter imports used by this file: [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md), [`normalizeHubServer`](../chapters/05-http-cookies-and-webviews.md), [`AppLogger`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.normalizeHubServer
import eu.friedcutlet.yokan.services.logging.AppLogger
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

/** The maintained list of public yokan-hub servers, published with the app's releases. */
const val HubServerListUrl = "https://raw.githubusercontent.com/Schnitzel5/yokan/main/servers.json"

@Serializable
data class HubServerEntry(val name: String, val url: String, val description: String = "")

@Serializable
private data class HubServerList(val version: Int = 1, val servers: List<HubServerEntry> = emptyList())

private val hubServerJson = Json { ignoreUnknownKeys = true }

/** Predefined servers with normalized URLs; empty (and logged) when the list is unreachable or malformed. */
suspend fun fetchHubServers(http: HttpService, url: String = HubServerListUrl): List<HubServerEntry> {
    val response = catchingNonCancellation { http.request(HttpRequest(url)) }.getOrElse {
        AppLogger.warn("[sync] hub server list unavailable: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}")
        return emptyList()
    }
    if (response.statusCode !in 200..299) {
        AppLogger.warn("[sync] hub server list returned HTTP ${response.statusCode}")
        return emptyList()
    }
    val list = runCatching { hubServerJson.decodeFromString(HubServerList.serializer(), response.body) }.getOrElse {
        AppLogger.warn("[sync] hub server list is malformed: ${it.message?.lineSequence()?.firstOrNull()}")
        return emptyList()
    }
    return list.servers
        .mapNotNull { entry -> normalizeHubServer(entry.url)?.let { entry.copy(name = entry.name.trim().ifBlank { it }, url = it) } }
        .distinctBy { it.url }
        .take(MaxHubServers)
}

private const val MaxHubServers = 50
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubLogin.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubLogin.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubLogin.kt).

The implementation below defines `HubLogin`, `login`, `beginBrowserLogin`, `completeBrowserLogin`, `one`, `cancelBrowserLogin`, `invalidate`, `clear`, `preference`, `sameOrigin` and 9 further declarations.

The source describes its contract as:

> Password and browser login for \[HubSyncService\]; owns the pending browser attempts.

Cross-chapter imports used by this file: [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`SyncServerProvider`](../chapters/02-domain-and-settings-models.md), [`YokanDatabase`](../chapters/03-persistence-and-migrations.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md), [`HttpResponse`](../chapters/05-http-cookies-and-webviews.md), [`normalizeHubServer`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import dev.whyoleg.cryptography.DelicateCryptographyApi
import dev.whyoleg.cryptography.random.CryptographyRandom
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.sync.SyncPaths
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.normalizeHubServer
import eu.friedcutlet.yokan.util.PlatformLock
import io.ktor.http.URLBuilder
import io.ktor.http.Url
import io.ktor.http.parseQueryString
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlin.random.Random

/** Password and browser login for [HubSyncService]; owns the pending browser attempts. */
internal class HubLogin(
    private val database: YokanDatabase,
    private val http: HttpService,
    private val leases: SyncAccountLeases,
) {
    private val json = SyncPaths.json
    private val browserAttemptLock = PlatformLock()
    private val browserAttempts = mutableMapOf<Long, PendingBrowserAttempt>()

    suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult {
        invalidate(syncId)
        val capturedPreference = preference(syncId)
        if ((capturedPreference?.serverProvider ?: SyncServerProvider.YokanHub) != SyncServerProvider.YokanHub) return SyncLoginResult(false, "Yokan Hub is not the selected sync provider.")
        val base = normalizeHubServer(server) ?: return SyncLoginResult(false, "Server URL is required.")
        unsupportedHub(base)?.let { return it }
        val device = capturedPreference?.deviceId ?: newDeviceId()
        val response = catchingNonCancellation {
            http.request(
                HttpRequest(
                    url = "$base/api/v1/login",
                    method = "POST",
                    headers = mapOf("Content-Type" to "application/json", "X-Device" to device),
                    body = json.encodeToString(LoginReq.serializer(), LoginReq(email.trim(), password)),
                ),
            )
        }.getOrElse { return SyncLoginResult(false, it.message ?: "Login failed") }
        when (response.statusCode) {
            401 -> return SyncLoginResult(false, "Wrong email or password.")
            403 -> return SyncLoginResult(false, errorOf(response) ?: "Account disabled.")
            503 -> return SyncLoginResult(false, "The hub is in maintenance mode. Try again later.")
            !in 200..299 -> return SyncLoginResult(false, "Hub returned HTTP ${response.statusCode}")
        }
        val token = runCatching { json.decodeFromString(TokenResp.serializer(), response.body).token }.getOrNull()
            ?: return SyncLoginResult(false, "Hub response did not include a token.")
        browserAttemptLock.withLock { browserAttempts.remove(syncId) }
        return saveLogin(syncId, capturedPreference, base, email.trim(), token, device)
    }

    @OptIn(DelicateCryptographyApi::class)
    fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? {
        val base = normalizeHubServer(server) ?: return null
        val parsedBase = runCatching { Url(base) }.getOrNull() ?: return null
        if (parsedBase.protocol.name !in setOf("http", "https") || parsedBase.host.isBlank() ||
            parsedBase.user != null ||
            base.contains('?') || base.contains('#')
        ) return null
        val capturedPreference = preference(syncId)
        if ((capturedPreference?.serverProvider ?: SyncServerProvider.YokanHub) != SyncServerProvider.YokanHub) return null
        val device = capturedPreference?.deviceId ?: newDeviceId()
        val state = CryptographyRandom.Default.nextBytes(32).joinToString("") { byte ->
            val value = byte.toInt() and 0xff
            "0123456789abcdef"[value ushr 4].toString() + "0123456789abcdef"[value and 0x0f]
        }
        val url = URLBuilder("$base/login/").apply {
            parameters.append("app", "yokan")
            parameters.append("device", device)
            parameters.append("state", state)
        }.build().toString()
        val attempt = BrowserLoginAttempt(syncId, base, url, device, state)
        browserAttemptLock.withLock { browserAttempts[syncId] = PendingBrowserAttempt(attempt, capturedPreference) }
        return attempt
    }

    suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult? {
        if (loadedUrl.length > MAX_BROWSER_CALLBACK_LENGTH || loadedUrl.any(Char::isISOControl)) return null
        val callback = runCatching { Url(loadedUrl) }.getOrNull() ?: return null
        val configured = runCatching { Url(attempt.server) }.getOrNull() ?: return null
        val callbackPath = rawPath(attempt.server)?.trimEnd('/') + "/login/done"
        val loadedPath = rawPath(loadedUrl.substringBefore('#'))
        if (!sameOrigin(configured, callback) || loadedPath !in setOf(callbackPath, "$callbackPath/") || callback.user != null ||
            loadedUrl.substringBefore('#').contains('?')
        ) return null
        val handoff = parseQueryString(loadedUrl.substringAfter('#', ""))
        if (handoff.entries().any { (name, values) -> name.any(Char::isISOControl) || values.any { value -> value.any(Char::isISOControl) } }) {
            return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE)
        }
        fun one(name: String, maxLength: Int): String? = handoff.getAll(name)?.singleOrNull()
            ?.takeIf { it.isNotBlank() && it.length <= maxLength && it.none(Char::isISOControl) }
        val state = one("state", MAX_STATE_LENGTH)
            ?: return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE)
        val token = one("token", MAX_TOKEN_LENGTH)
            ?: return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE)
        val device = one("device", MAX_DEVICE_LENGTH)
            ?.takeIf { it.all { char -> char.isLetterOrDigit() || char == '-' || char == '_' } }
            ?: return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE)
        val emailValues = handoff.getAll("email")
        if (emailValues != null && (emailValues.size != 1 || emailValues.single().length > MAX_EMAIL_LENGTH)) {
            return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE)
        }
        val email = emailValues?.singleOrNull().orEmpty().trim()
        val pending = browserAttemptLock.withLock {
            browserAttempts[attempt.syncId]?.takeIf { it.attempt === attempt && !it.completing }?.also { it.completing = true }
        } ?: return null
        if (state != attempt.state || device != attempt.device) {
            browserAttemptLock.withLock {
                if (browserAttempts[attempt.syncId] === pending) pending.completing = false
            }
            return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE)
        }
        unsupportedHub(attempt.server)?.let { error ->
            browserAttemptLock.withLock {
                if (browserAttempts[attempt.syncId] === pending) pending.completing = false
            }
            return error
        }
        val completionContext = currentCoroutineContext()
        completionContext.ensureActive()
        val stillPending = browserAttemptLock.withLock {
            browserAttempts[attempt.syncId] === pending && pending.attempt === attempt && pending.completing
        }
        if (!stillPending) return null
        completionContext.ensureActive()
        val result = saveLogin(
            attempt.syncId, pending.capturedPreference, attempt.server, email, token, device,
        ) {
            browserAttemptLock.withLock { browserAttempts[attempt.syncId] === pending && pending.completing }
        }
        browserAttemptLock.withLock {
            if (browserAttempts[attempt.syncId] === pending) {
                if (result.success) browserAttempts.remove(attempt.syncId) else pending.completing = false
            }
        }
        return result
    }

    fun cancelBrowserLogin(attempt: BrowserLoginAttempt) {
        browserAttemptLock.withLock {
            if (browserAttempts[attempt.syncId]?.attempt === attempt) browserAttempts.remove(attempt.syncId)
        }
    }

    fun invalidate(syncId: Long) {
        browserAttemptLock.withLock { browserAttempts.remove(syncId) }
    }

    fun clear() = browserAttemptLock.withLock { browserAttempts.clear() }

    private fun preference(syncId: Long): DbSyncPreference? =
        database.syncPreferences().firstOrNull { it.syncId == syncId }

    private fun sameOrigin(first: Url, second: Url): Boolean =
        first.protocol.name.equals(second.protocol.name, ignoreCase = true) &&
            first.host.equals(second.host, ignoreCase = true) && first.port == second.port

    private fun rawPath(url: String): String? {
        val schemeEnd = url.indexOf("://")
        if (schemeEnd < 0) return null
        val pathStart = url.indexOf('/', schemeEnd + 3)
        return if (pathStart < 0) "" else url.substring(pathStart).substringBefore('?').substringBefore('#')
    }

    private class PendingBrowserAttempt(val attempt: BrowserLoginAttempt, val capturedPreference: DbSyncPreference?, var completing: Boolean = false)

    /** Null when [base] is a hub speaking [HubSyncService.PROTOCOL_VERSION]; otherwise the failure to show. */
    private suspend fun unsupportedHub(base: String): SyncLoginResult? {
        val version = catchingNonCancellation { http.request(HttpRequest(url = "$base/api/version")) }
            .getOrElse { return SyncLoginResult(false, it.message ?: "Hub is unreachable.") }
        val supported = runCatching { json.decodeFromString(VersionResp.serializer(), version.body).supported }.getOrNull()
        if (version.statusCode !in 200..299 || supported == null || HubSyncService.PROTOCOL_VERSION !in supported) {
            return SyncLoginResult(false, "$base is not a yokan-hub speaking sync protocol v${HubSyncService.PROTOCOL_VERSION}. Check the URL or update the hub.")
        }
        return null
    }

    private suspend fun saveLogin(
        syncId: Long,
        captured: DbSyncPreference?,
        base: String,
        email: String,
        token: String,
        device: String,
        extraGuard: () -> Boolean = { true },
    ): SyncLoginResult {
        currentCoroutineContext().ensureActive()
        val failure = leases.commitClaimed(captured, DbSyncPreference(server = base, email = email, authToken = token)) {
            database.upsertSyncPreferenceIf(
                syncId = syncId,
                accepts = { current ->
                    val unchanged = if (captured == null) current == null else current != null &&
                        current.serverProvider == captured.serverProvider && current.server == captured.server &&
                        current.email == captured.email && current.authToken == captured.authToken && current.deviceId == captured.deviceId
                    unchanged && (current?.serverProvider ?: SyncServerProvider.YokanHub) == SyncServerProvider.YokanHub && extraGuard()
                },
                transform = { current ->
                    (current ?: DbSyncPreference(syncId = syncId)).copy(
                    server = base,
                    email = email,
                    authToken = token,
                    syncOn = true,
                    serverProvider = SyncServerProvider.YokanHub,
                    hubHead = 0,
                    hubEpoch = 0,
                    hubRecoveryPending = false,
                    deviceId = device,
                )
                },
            )
        }
        if (failure != null) return SyncLoginResult(false, failure)
        return SyncLoginResult(true, "Logged in to $base")
    }

    private fun errorOf(response: HttpResponse): String? =
        runCatching { json.parseToJsonElement(response.body).jsonObject["error"]?.jsonPrimitive?.content }.getOrNull()

    private fun newDeviceId(): String = buildString(32) {
        repeat(16) { append(Random.nextInt(256).toString(16).padStart(2, '0')) }
    }

    @Serializable
    private data class LoginReq(val email: String, val password: String)

    @Serializable
    private data class TokenResp(val token: String)

    @Serializable
    private data class VersionResp(val supported: List<String> = emptyList())

    private companion object {
        const val MAX_BROWSER_CALLBACK_LENGTH = 16_384
        const val MAX_STATE_LENGTH = 256
        const val MAX_TOKEN_LENGTH = 4_096
        const val MAX_DEVICE_LENGTH = 64
        const val MAX_EMAIL_LENGTH = 320
        const val BROWSER_LOGIN_PROTOCOL_MESSAGE = "The hub did not securely hand over a session. Update the hub or use email/password sign-in."
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncService.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncService.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncService.kt).

The implementation below defines `HubSyncService`, `login`, `beginBrowserLogin`, `completeBrowserLogin`, `cancelBrowserLogin`, `logout`, `sync`, `pushChanges`, `pullChanges`, `status` and 24 further declarations.

The source describes its contract as:

> Sync client for yokan-hub. One `POST /api/v1/sync` pushes this device's outbox and pulls the delta since the stored cursor; `WS /api/v1/events` says when another device moved the head. Design: `docs/SYNC_SERVER_PLAN.md`. Clocks never leave the hub: everything this device pushed is already inside the docs it gets back, so the only local merge is "keep values for paths still pending in the outbox".

Cross-chapter imports used by this file: [`DbCategory`](../chapters/02-domain-and-settings-models.md), [`DbChapter`](../chapters/02-domain-and-settings-models.md), [`DbHistory`](../chapters/02-domain-and-settings-models.md), [`DbManga`](../chapters/02-domain-and-settings-models.md), [`DbOutboxOp`](../chapters/02-domain-and-settings-models.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbOutboxOp
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbUpdate
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.library.removeTitleWithDependents
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.normalizeHubServer
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.database.sync.SyncClock
import eu.friedcutlet.yokan.database.sync.SyncPaths
import eu.friedcutlet.yokan.util.nowMillis
import io.ktor.client.HttpClient
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.plugins.websocket.WebSockets
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.encodeToJsonElement
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

/**
 * Sync client for yokan-hub. One `POST /api/v1/sync` pushes this device's outbox and pulls the
 * delta since the stored cursor; `WS /api/v1/events` says when another device moved the head.
 * Design: `docs/SYNC_SERVER_PLAN.md`.
 *
 * Clocks never leave the hub: everything this device pushed is already inside the docs it gets
 * back, so the only local merge is "keep values for paths still pending in the outbox".
 */
class HubSyncService(
    private val database: YokanDatabase,
    private val http: HttpService,
    /** Engine for the live-events socket; owned by this service and closed in [close]. */
    webSocketEngine: HttpClientEngine? = null,
    private val autoSync: Boolean = true,
    scope: CoroutineScope,
    private val operationMonitor: SyncOperationMonitor = SyncOperationMonitor(),
    private val leases: SyncAccountLeases = SyncAccountLeases.None,
) : SyncService {
    private val ownerJob = requireNotNull(scope.coroutineContext[Job]) { "Hub sync requires an owner job" }
    private val lifecycleJob = SupervisorJob(ownerJob)
    private val scope = CoroutineScope(scope.coroutineContext + lifecycleJob)
    private val retirementLock = Mutex()
    private val webSocketEngine = webSocketEngine?.let { eu.friedcutlet.yokan.services.http.ProfileHttpEngine(it, lifecycleJob) }
    override val operationState = operationMonitor.state
    private val json = SyncPaths.json
    private val liveClient: HttpClient? = this.webSocketEngine?.let { engine ->
        HttpClient(engine) {
            expectSuccess = false
            install(WebSockets)
        }
    }
    private val syncMutex = Mutex()
    private val hubLogin = HubLogin(database, http, leases)
    private val live = HubLiveEvents(this.scope, liveClient, leases, ::preference) { round(it, push = true, pull = true) }

    init {
        if (autoSync) this.scope.launch { database.snapshots().collect(live::onSnapshot) }
    }

    // ── SyncService ─────────────────────────────────────────────────────────

    override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult =
        hubLogin.login(syncId, server, email, password)

    override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? = hubLogin.beginBrowserLogin(syncId, server)

    override suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult? =
        hubLogin.completeBrowserLogin(attempt, loadedUrl)

    override fun cancelBrowserLogin(attempt: BrowserLoginAttempt) = hubLogin.cancelBrowserLogin(attempt)

    override suspend fun logout(syncId: Long) {
        val pref = preference(syncId)
        val server = pref?.server?.let(::normalizeHubServer)
        // Removing the attempt first makes a racing browser completion's guard reject; never hold this lock across
        // the DB write, since saveLogin's guard takes it inside the DB lock.
        hubLogin.invalidate(syncId)
        upsertPreference(syncId) { it.copy(authToken = null, syncOn = false) }
        live.stopLive()
        leases.releaseQuietly(pref)
        // Revoking the session is best effort; an unreachable hub must not hold the local logout hostage.
        if (pref?.authToken != null && server != null) {
            scope.launch {
                catchingNonCancellation { http.request(HttpRequest(url = "$server/api/v1/logout", method = "POST", headers = authHeaders(pref))) }
                    .onFailure { AppLogger.warn("[sync] hub logout request failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }
            }
        }
    }

    override suspend fun sync(syncId: Long, settings: DbSettings): SyncResult = round(syncId, push = true, pull = true)

    override suspend fun pushChanges(syncId: Long): SyncResult = round(syncId, push = true, pull = false)

    override suspend fun pullChanges(syncId: Long): SyncResult = round(syncId, push = false, pull = true)

    override fun status(syncId: Long): SyncConnectionStatus {
        val pref = preference(syncId)
        return SyncConnectionStatus(
            loggedIn = !pref?.authToken.isNullOrBlank(),
            email = pref?.email,
            server = pref?.server,
            lastSyncMillis = pref?.lastSyncManga,
        )
    }

    override fun close() {
        hubLogin.clear()
        scope.cancel()
        liveClient?.close()
        // Ktor never closes an engine passed to HttpClient(engine); without this OkHttp/Darwin threads leak.
        webSocketEngine?.close()
    }

    override suspend fun closeAndJoin() {
        retirementLock.withLock {
            withContext(kotlinx.coroutines.NonCancellable) {
                hubLogin.clear()
                lifecycleJob.cancelAndJoin()
                val clientJob = liveClient?.coroutineContext?.get(Job)
                clientJob?.cancel()
                webSocketEngine?.closeAndJoin()
                clientJob?.join()
                liveClient?.close()
            }
        }
    }

    // ── the round trip ──────────────────────────────────────────────────────

    /**
     * How a full copy of local state is stamped when it is pushed outside the outbox.
     * The outbox only holds edits made on this device since it started recording, so data that
     * predates it (first login, restored backups) has to be sent explicitly.
     */
    private enum class Seed {
        /** Clock ≈ 0: fills gaps on the hub but never beats a value the hub already has. */
        Conservative,
        /** Fresh clocks: local state wins everywhere ("Upload only"). */
        Overwrite,
        ;

        fun clock(): Long = if (this == Overwrite) SyncClock.tick() else SEED_CLOCK
    }

    private suspend fun round(syncId: Long, push: Boolean, pull: Boolean): SyncResult {
        val stage = when {
            push && !pull -> SyncOperationStage.Uploading
            pull && !push -> SyncOperationStage.Downloading
            else -> SyncOperationStage.Syncing
        }
        val operationId = operationMonitor.begin(stage)
        return try {
            val result = performRound(syncId, push, pull) { operationMonitor.progress(operationId, it) }
            val summary = "[sync] hub ${stage.name.lowercase()}: ${result.uploadedChanges} up, ${result.downloadedChanges} down"
            if (result.errors.isEmpty()) AppLogger.info(summary) else AppLogger.warn("$summary; ${result.errors.joinToString("; ")}")
            operationMonitor.finish(
                operationId,
                if (result.errors.isEmpty()) SyncOperationOutcome.Succeeded else SyncOperationOutcome.Failed,
            )
            result
        } catch (cancelled: CancellationException) {
            operationMonitor.finish(operationId, SyncOperationOutcome.Cancelled)
            throw cancelled
        } catch (error: Throwable) {
            AppLogger.error("[sync] hub ${stage.name.lowercase()} failed: ${error.message?.lineSequence()?.firstOrNull() ?: error::class.simpleName}")
            operationMonitor.finish(operationId, SyncOperationOutcome.Failed)
            throw error
        }
    }

    private suspend fun performRound(
        syncId: Long,
        push: Boolean,
        pull: Boolean,
        onProgress: (Float) -> Unit,
    ): SyncResult = syncMutex.withLock {
        var pref = preference(syncId) ?: return@withLock SyncResult(0, 0, false, listOf("No sync configuration."))
        if (pref.serverProvider != SyncServerProvider.YokanHub) return@withLock SyncResult(0, 0, false, listOf("Yokan Hub is not the selected sync provider."))
        val server = pref.server?.let(::normalizeHubServer) ?: return@withLock SyncResult(0, 0, false, listOf("No hub configured."))
        if (pref.authToken.isNullOrBlank()) return@withLock SyncResult(0, 0, false, listOf("Not logged in."))
        leases.claimFailure(pref)?.let { return@withLock SyncResult(0, 0, false, listOf(it)) }
        val operationToken = pref.authToken

        var uploaded = 0
        var downloaded = 0
        var lost = 0
        var failedEntities = 0
        val deferredDeletes = mutableListOf<String>()
        var failure = ""
        fun done(vararg errors: String) = SyncResult(
            uploadedChanges = uploaded,
            downloadedChanges = downloaded,
            settingsSynced = pref.syncSettings && errors.isEmpty(),
            errors = errors.toList() +
                (if (lost > 0) listOf("$lost change(s) from another device took precedence.") else emptyList()) +
                (if (failedEntities > 0) listOf("$failedEntities incoming record(s) could not be applied.") else emptyList()) + deferredDeletes,
        )

        /** One POST; null ends the round with [failure] set. A single 409 resets the cursor and retries. */
        suspend fun exchange(build: (DbSyncPreference) -> SyncReq): SyncResp? {
            var resynced = false
            while (true) {
                val response = catchingNonCancellation {
                    http.request(
                        HttpRequest(
                            url = "$server/api/v1/sync",
                            method = "POST",
                            headers = authHeaders(pref) + ("Content-Type" to "application/json"),
                            body = json.encodeToString(SyncReq.serializer(), build(pref)),
                        ),
                    )
                }.getOrElse {
                    failure = "Could not reach the hub: ${it.message ?: "network error"}"
                    return null
                }
                val activePreference = preference(syncId)
                if (activePreference?.serverProvider != SyncServerProvider.YokanHub ||
                    activePreference.server?.let(::normalizeHubServer) != server || activePreference.authToken != operationToken
                ) {
                    failure = "Sync configuration changed during the operation."
                    return null
                }
                when (response.statusCode) {
                    401 -> {
                        upsertPreference(syncId) { it.copy(authToken = null) }
                        live.stopLive()
                        failure = "Session expired; log in to the hub again."
                        return null
                    }
                    503 -> {
                        failure = "The hub is in maintenance mode; changes are kept locally."
                        return null
                    }
                    409 -> {
                        if (resynced) {
                            failure = "The hub asked for a second resync; giving up for now."
                            return null
                        }
                        resynced = true
                        val epoch = runCatching { json.parseToJsonElement(response.body).jsonObject["epoch"]?.jsonPrimitive?.int }
                            .getOrNull() ?: 0
                        pref = database.resyncHub(syncId, epoch)
                        continue
                    }
                    !in 200..299 -> {
                        failure = "Hub returned HTTP ${response.statusCode}"
                        return null
                    }
                }
                val resp = runCatching { json.decodeFromString(SyncResp.serializer(), response.body) }.getOrElse {
                    failure = "Unreadable hub response."
                    return null
                }
                SyncClock.observe(resp.hlc)
                pref = upsertPreference(syncId) { it.copy(hubEpoch = resp.epoch, hubHlc = resp.hlc) }
                return resp
            }
        }

        val kinds = enabledKinds(pref)
        val seed = when {
            pref.hubRecoveryPending -> null
            !push -> null
            !pull -> Seed.Overwrite
            !pref.hubBootstrapComplete -> Seed.Conservative
            else -> null
        }
        if (seed != null) {
            val seeded = seedHub(kinds, seed, { pref.hubRecoveryPending }) { build -> exchange(build) }
            uploaded += seeded.uploaded
            lost += seeded.lost
            if (seeded.failed) return@withLock done(failure)
            if (seeded.completed && !pref.hubBootstrapComplete) {
                pref = upsertPreference(syncId) { it.copy(hubBootstrapComplete = true) }
            }
        }

        // ponytail: progress by seq range, not row count; seqs of rewritten rows leave gaps, so it can jump.
        val pullFrom = pref.hubHead
        while (true) {
            var ops = emptyList<DbOutboxOp>()
            val resp = exchange {
                // Re-read after a 409 resync: stale ops may have been
                // discarded before the retry is built.
                val eligible = eligibleOutbox(it)
                ops = if (push) {
                    eligible.filter { op ->
                        op.epoch == it.hubEpoch &&
                            (op.kind in kinds || op.kind in setOf(SyncPaths.KIND_HISTORY, SyncPaths.KIND_UPDATE) && op.path == SyncPaths.DELETED)
                    }.take(MAX_OPS)
                } else {
                    emptyList()
                }
                SyncReq(
                    since = if (pull || it.hubRecoveryPending) it.hubHead else NO_DELTA,
                    epoch = it.hubEpoch,
                    generation = 1,
                    hlc = SyncClock.tick(),
                    ops = ops.map { op -> WireOp(op.kind, op.id, op.path, op.value?.let(json::parseToJsonElement) ?: JsonNull, op.hlc) },
                )
            } ?: return@withLock done(failure)

            if (ops.isNotEmpty()) {
                database.removeOutbox(ops)
                uploaded += ops.size
                lost += resp.lost
            }
            val shouldPull = pull || pref.hubRecoveryPending
            if (shouldPull) {
                val incoming = resp.ents.filter { it.k in kinds || it.del && it.k in setOf(SyncPaths.KIND_HISTORY, SyncPaths.KIND_UPDATE) }
                val (incomingFailed, deferred) = applyEntities(incoming, pref.hubEpoch)
                failedEntities += incomingFailed
                deferredDeletes += deferred
                downloaded += incoming.size
                val recoveryComplete = pref.hubRecoveryPending && !resp.more && incomingFailed == 0
                pref = upsertPreference(syncId) {
                    it.copy(
                        hubHead = if (incomingFailed == 0) resp.head else it.hubHead,
                        lastSyncManga = nowMillis(),
                        hubRecoveryPending = if (recoveryComplete) false else it.hubRecoveryPending,
                        hubBootstrapComplete = it.hubBootstrapComplete || recoveryComplete,
                    )
                }
                if (resp.more && resp.tip > pullFrom) {
                    onProgress((resp.head - pullFrom).toFloat() / (resp.tip - pullFrom))
                }
            } else {
                pref = upsertPreference(syncId) {
                    it.copy(
                        lastSyncManga = nowMillis(),
                        hubBootstrapComplete = it.hubBootstrapComplete ||
                            (push && !it.hubBootstrapComplete && it.hubEpoch > 0),
                    )
                }
            }
            val morePush = push && ops.size == MAX_OPS
            if (!morePush && !(shouldPull && resp.more)) break
        }
        done()
    }

    private class SeedOutcome(val uploaded: Int, val lost: Int, val completed: Boolean, val failed: Boolean)

    /**
     * Pushes every local entity stamped by [seed]. NO_DELTA keeps the hub from paging its whole library back
     * on every chunk; the pull after it (or the next full sync) fetches the merged result from the stored cursor.
     * [exchange] returning null fails the seed; a recovery flagged by [recoveryPending] stops it unfinished.
     */
    private suspend fun seedHub(
        kinds: Set<Int>,
        seed: Seed,
        recoveryPending: () -> Boolean,
        exchange: suspend ((DbSyncPreference) -> SyncReq) -> SyncResp?,
    ): SeedOutcome {
        var uploaded = 0
        var lost = 0
        for (chunk in localOps(kinds, seed)) {
            val resp = exchange {
                SyncReq(
                    since = if (it.hubRecoveryPending) it.hubHead else NO_DELTA,
                    epoch = it.hubEpoch,
                    generation = 1,
                    hlc = SyncClock.tick(),
                    ops = if (it.hubRecoveryPending) emptyList() else chunk,
                )
            } ?: return SeedOutcome(uploaded, lost, completed = false, failed = true)
            if (recoveryPending()) return SeedOutcome(uploaded, lost, completed = false, failed = false)
            uploaded += chunk.size
            lost += resp.lost
        }
        return SeedOutcome(uploaded, lost, completed = true, failed = false)
    }

    /** Drop pre-generation rows before selecting a batch; never relabel them as current. */
    private fun eligibleOutbox(pref: DbSyncPreference): List<DbOutboxOp> {
        val current = database.outbox()
        if (!pref.hubBootstrapComplete) {
            return current.filter { it.epoch == 0 || it.epoch == pref.hubEpoch }
        }
        if (pref.hubEpoch == 0) return current
        val stale = current.filter { it.epoch < pref.hubEpoch }
        if (stale.isNotEmpty()) database.removeOutbox(stale)
        return database.outbox()
    }

    /** Every synced local entity as path ops, in request-sized chunks. */
    private fun localOps(kinds: Set<Int>, seed: Seed): Sequence<List<WireOp>> = sequence {
        val chunk = ArrayList<WireOp>(MAX_OPS)
        for ((kind, id, doc) in SyncPaths.docs(database.snapshot(), kinds)) {
            for (change in SyncPaths.diff(kind, null, doc)) {
                chunk += WireOp(kind, id, change.path, change.value ?: JsonNull, seed.clock())
                if (chunk.size == MAX_OPS) {
                    yield(chunk.toList())
                    chunk.clear()
                }
            }
        }
        if (chunk.isNotEmpty()) yield(chunk.toList())
    }

    /** Apply hub docs locally. Returns the failed count and actionable deferred-delete errors. */
    private fun applyEntities(ents: List<WireEnt>, epoch: Int): Pair<Int, List<String>> {
        if (ents.isEmpty()) return 0 to emptyList()
        var failed = 0
        val deferred = mutableListOf<String>()
        database.applyRemote {
            database.batch {
                // Re-read within the transaction: unsent lower-sequence edits matter too.
                val pending = database.outbox().filter { it.epoch == epoch }.groupBy { it.kind to it.id }
                for (e in ents) {
                    val result = runCatching {
                        if (e.del) {
                            if (e.k == SyncPaths.KIND_MANGA) {
                                val chapterIds = database.chapters(e.id).mapTo(HashSet()) { it.id }
                                if (database.downloads().any { it.chapterId?.let(chapterIds::contains) == true && it.isStartDownload == true && it.isDownload != true }) {
                                    error("Title ${e.id} has an active chapter download; finish or cancel it before syncing this deletion.")
                                }
                            }
                            removeEntity(e.k, e.id)
                        } else {
                            val ops = pending[e.k to e.id].orEmpty()
                            if (ops.none { it.path == SyncPaths.DELETED && it.value?.let(json::parseToJsonElement) == kotlinx.serialization.json.JsonPrimitive(true) }) {
                                e.doc?.let { applyEntity(e.k, e.id, SyncPaths.overlay(it, ops)) }
                            }
                        }
                    }
                    result.exceptionOrNull()?.let { exception ->
                        failed++
                        exception.message?.takeIf { it.startsWith("Title ") }?.let(deferred::add)
                    }
                }
            }
        }
        return failed to deferred
    }

    private fun removeEntity(kind: Int, id: Long) {
        when (kind) {
            SyncPaths.KIND_CATEGORY -> database.removeCategory(id, recordChange = false)
            SyncPaths.KIND_MANGA -> removeTitleWithDependents(database, id, recordChange = false)
            SyncPaths.KIND_CHAPTER -> database.removeChapter(id, recordChange = false)
            SyncPaths.KIND_TRACK -> database.removeTrack(id, recordChange = false)
            SyncPaths.KIND_HISTORY -> database.removeHistory(id, recordChange = false)
            SyncPaths.KIND_UPDATE -> database.removeUpdate(id, recordChange = false)
        }
    }

    private fun applyEntity(kind: Int, id: Long, doc: JsonObject) {
        when (kind) {
            SyncPaths.KIND_MANGA -> database.upsertManga(decode(kind, id, doc, DbManga.serializer()) { database.manga(id) })
            SyncPaths.KIND_CHAPTER -> database.upsertChapter(decode(kind, id, doc, DbChapter.serializer()) { database.chapter(id) })
            SyncPaths.KIND_CATEGORY -> database.upsertCategory(decode(kind, id, doc, DbCategory.serializer()) { database.categories().firstOrNull { it.id == id } })
            SyncPaths.KIND_TRACK -> database.upsertTrack(decode(kind, id, doc, DbTrack.serializer()) { database.tracks().firstOrNull { it.id == id } })
            SyncPaths.KIND_HISTORY -> database.upsertHistory(decode(kind, id, doc, DbHistory.serializer()) { database.histories().firstOrNull { it.id == id } })
            SyncPaths.KIND_UPDATE -> database.upsertUpdate(decode(kind, id, doc, DbUpdate.serializer()) { database.updates().firstOrNull { it.id == id } })
            SyncPaths.KIND_SETTINGS -> {
                val current = database.settings()
                database.updateSettings(decode(kind, id, doc, DbSettings.serializer()) { current }.copy(id = current.id))
            }
        }
    }

    /**
     * Only excluded (device-local) fields survive from the local row, so it is looked up only for
     * kinds that have some; a full-table scan per pulled row made large pulls quadratic.
     */
    private fun <T> decode(kind: Int, id: Long, doc: JsonObject, serializer: KSerializer<T>, local: () -> T?): T {
        val localObj = if (SyncPaths.excluded(kind).any { it != "id" }) {
            local()?.let { json.encodeToJsonElement(serializer, it).jsonObject }
        } else {
            null
        }
        return json.decodeFromJsonElement(serializer, SyncPaths.applyIncoming(kind, localObj, doc, id))
    }

    // ── helpers ─────────────────────────────────────────────────────────────

    private fun preference(syncId: Long): DbSyncPreference? =
        database.syncPreferences().firstOrNull { it.syncId == syncId }

    private fun upsertPreference(syncId: Long, transform: (DbSyncPreference) -> DbSyncPreference): DbSyncPreference {
        val current = preference(syncId) ?: DbSyncPreference(syncId = syncId)
        return database.upsertSyncPreference(transform(current.copy(syncId = current.syncId ?: syncId)))
    }

    private fun enabledKinds(pref: DbSyncPreference): Set<Int> = buildSet {
        add(SyncPaths.KIND_CATEGORY)
        add(SyncPaths.KIND_MANGA)
        add(SyncPaths.KIND_CHAPTER)
        add(SyncPaths.KIND_TRACK)
        if (pref.syncHistories) add(SyncPaths.KIND_HISTORY)
        if (pref.syncUpdates) add(SyncPaths.KIND_UPDATE)
        if (pref.syncSettings) add(SyncPaths.KIND_SETTINGS)
    }

    private fun authHeaders(pref: DbSyncPreference): Map<String, String> =
        mapOf("Authorization" to "Bearer ${pref.authToken}", "X-Device" to (pref.deviceId ?: "unknown"))

    @Serializable
    private data class WireOp(val k: Int, val id: Long, val p: String, val v: JsonElement = JsonNull, val t: Long)

    @Serializable
    private data class SyncReq(
        val since: Long,
        val epoch: Int,
        val generation: Int,
        val hlc: Long,
        val ops: List<WireOp>,
    )

    @Serializable
    private data class WireEnt(val k: Int, val id: Long, val doc: JsonObject? = null, val del: Boolean = false)

    @Serializable
    private data class SyncResp(
        val epoch: Int,
        val head: Long,
        val hlc: Long,
        val more: Boolean = false,
        val ents: List<WireEnt> = emptyList(),
        val lost: Int = 0,
        val applied: Int = 0,
        /** Hub's newest seq; with [head] it tells how far a multi-page pull got. 0 from older hubs. */
        val tip: Long = 0,
    )

    companion object {
        const val PUSH_DEBOUNCE_MS = 3_000L
        /** Hub-side limit per request (`MAX_OPS` in `routes/sync.rs`). */
        const val MAX_OPS = 10_000
        /** `since` beyond any seq: the hub validates the epoch but returns no delta. */
        const val NO_DELTA = Long.MAX_VALUE
        /** Smallest clock the hub accepts as a real write; loses to anything already stored. */
        val SEED_CLOCK = SyncClock.pack(1, 0)
        /** Sync protocol this client speaks; checked against the hub's `GET /api/version` at login. */
        const val PROTOCOL_VERSION = "1"
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubLiveEvents.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubLiveEvents.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubLiveEvents.kt).

The implementation below defines `HubLiveEvents`, `LiveKey`, `onSnapshot`, `stopLive`, `schedulePushLocked`, `runLive`.

The source describes its contract as:

> `WS /api/v1/events` hints plus the debounced push after local edits, for \[HubSyncService\].

Cross-chapter imports used by this file: [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`SyncServerProvider`](../chapters/02-domain-and-settings-models.md), [`YokanDatabaseSnapshot`](../chapters/03-persistence-and-migrations.md), [`hubWebSocketBase`](../chapters/05-http-cookies-and-webviews.md), [`normalizeHubServer`](../chapters/05-http-cookies-and-webviews.md), [`AppLogger`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.database.sync.SyncPaths
import eu.friedcutlet.yokan.services.http.hubWebSocketBase
import eu.friedcutlet.yokan.services.http.normalizeHubServer
import eu.friedcutlet.yokan.services.logging.AppLogger
import io.ktor.client.HttpClient
import io.ktor.client.plugins.websocket.webSocket
import io.ktor.client.request.header
import io.ktor.http.HttpHeaders
import io.ktor.websocket.Frame
import io.ktor.websocket.readText
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.long

/** `WS /api/v1/events` hints plus the debounced push after local edits, for [HubSyncService]. */
internal class HubLiveEvents(
    private val scope: CoroutineScope,
    private val liveClient: HttpClient?,
    private val leases: SyncAccountLeases,
    private val preference: (Long) -> DbSyncPreference?,
    private val round: suspend (syncId: Long) -> SyncResult,
) {
    private val json = SyncPaths.json
    private val stateMutex = Mutex()
    private var liveKey: LiveKey? = null
    private var liveJob: Job? = null
    private var pushJob: Job? = null
    private var lastOutboxSeq = -1L

    private data class LiveKey(val syncId: Long, val server: String, val token: String, val device: String)

    suspend fun onSnapshot(snapshot: YokanDatabaseSnapshot) {
        val pref = snapshot.syncPreferences.firstOrNull()
        val key = pref
            ?.takeIf { it.syncOn }
            ?.takeIf { it.serverProvider == SyncServerProvider.YokanHub }
            ?.let { p ->
                val token = p.authToken?.takeIf { it.isNotBlank() } ?: return@let null
                normalizeHubServer(p.server)?.let { LiveKey(p.syncId ?: 1L, it, token, p.deviceId ?: "unknown") }
            }
        val outboxSeq = snapshot.outbox.maxOfOrNull { it.seq } ?: 0L
        stateMutex.withLock {
            val keyChanged = key != liveKey
            if (keyChanged) {
                liveJob?.cancel()
                pushJob?.cancel()
                liveKey = key
                liveJob = if (key != null && liveClient != null) scope.launch { runLive(key) } else null
            }
            if (key != null && (outboxSeq > lastOutboxSeq || keyChanged && outboxSeq > 0)) schedulePushLocked(key.syncId)
            lastOutboxSeq = outboxSeq
        }
    }

    suspend fun stopLive() = stateMutex.withLock {
        liveJob?.cancel()
        liveJob = null
        liveKey = null
    }

    private fun schedulePushLocked(syncId: Long) {
        pushJob?.cancel()
        pushJob = scope.launch {
            delay(HubSyncService.PUSH_DEBOUNCE_MS)
            round(syncId)
        }
    }

    private suspend fun runLive(key: LiveKey) {
        val client = liveClient ?: return
        leases.claimFailure(preference(key.syncId))?.let { AppLogger.warn("[sync] hub live events not started: $it"); return }
        var backoff = 1_000L
        while (scope.isActive && stateMutex.withLock { liveKey == key }) {
            try {
                client.webSocket(
                    urlString = hubWebSocketBase(key.server) + "/api/v1/events",
                    request = {
                        header(HttpHeaders.Authorization, "Bearer ${key.token}")
                        header("X-Device", key.device)
                    },
                ) {
                    backoff = 1_000L
                    round(key.syncId)
                    for (frame in incoming) {
                        val text = (frame as? Frame.Text)?.readText() ?: continue
                        val head = runCatching { json.parseToJsonElement(text).jsonObject["head"]?.jsonPrimitive?.long }.getOrNull() ?: continue
                        if (head > (preference(key.syncId)?.hubHead ?: 0L)) round(key.syncId)
                    }
                }
            } catch (cancelled: CancellationException) {
                throw cancelled
            } catch (error: Throwable) {
                // The REST round trip stays authoritative; a socket failure only delays hints.
                // Logged once per outage: the backoff only stays at its base until the first retry.
                if (backoff == 1_000L) {
                    AppLogger.warn("[sync] hub live events disconnected: ${error.message?.lineSequence()?.firstOrNull() ?: error::class.simpleName}")
                }
            }
            if (!scope.isActive) break
            delay(backoff)
            backoff = (backoff * 2).coerceAtMost(30_000L)
        }
    }
}
```
[chapter-file-end]: #

### Check your understanding

Reset the server epoch with pending local changes, reconnect, and inspect recovery/bootstrap behavior. Verify only the uploaded unchanged sequences are acknowledged.
[chapter-content-end]: #


## Step 4: implement Mangayomi synchronization

Implement password/OAuth redirects, server normalization and JWT cookie isolation using raw HTTP. `MangayomiSyncMapper` maps external tables, IDs, relationships, changed parts/deletes, chapter/title fields and settings. Reproduce ID mappings and deletion recorder behavior before adding networking. Keep manual local filler overrides when remote source flags arrive. Preserve unsupported/device-local fields.

[chapter-content-start]: #
### Follow the code

The mapper converts external tables, fields and IDs into current database relationships. Its namespace/ID mappings are part of persistent compatibility, while unsupported/device-local values remain local. Apply source facts without removing manual filler overrides. Network/auth helpers use the intended raw transport and isolated cookie/attempt state. Write mapper fixtures before login/round orchestration so wire failures cannot hide identity bugs.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncMapper.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncService.kt`
- `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.desktop.kt`
- `composeApp/src/platformWebViewMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.platformWebView.kt`
- `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.wasm.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncMapper.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncMapper.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncMapper.kt).

The implementation below defines `MangayomiNamespace`, `MangayomiBatch`, `MangayomiPage`, `MangayomiMerge`, `MangayomiSyncMapper`, `Binding`, `mappingsJson`, `prepare`, `encode`, `decodePage` and 92 further declarations.

The source describes its contract as:

> Pure conversion between Yokan snapshots and Mangayomi's independent clientId wire protocol.

Cross-chapter imports used by this file: [`DbCategory`](../chapters/02-domain-and-settings-models.md), [`DbChangedPart`](../chapters/02-domain-and-settings-models.md), [`DbChapter`](../chapters/02-domain-and-settings-models.md), [`DbChapterPageUrls`](../chapters/02-domain-and-settings-models.md), [`DbFetchType`](../chapters/02-domain-and-settings-models.md), [`DbHistory`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbChangedPart
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbChapterPageUrls
import eu.friedcutlet.yokan.database.DbFetchType
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbStatus
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.DbUpdate
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.database.effectiveFiller
import eu.friedcutlet.yokan.database.sync.SyncIds
import eu.friedcutlet.yokan.database.sync.SyncPaths
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonObjectBuilder
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.int
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put

internal data class MangayomiNamespace(val server: String, val accountId: String)

internal data class MangayomiBatch(
    val kind: Int?,
    val localIds: List<Long>,
    val deletions: List<DbChangedPart> = emptyList(),
)

internal data class MangayomiPage(
    val data: JsonObject,
    val cursors: Map<String, String?>,
    val sessionToken: String?,
    val hasMore: Boolean,
    val syncedAt: Long?,
)

internal data class MangayomiMerge(
    val snapshot: YokanDatabaseSnapshot,
    val downloadedChanges: Int,
    val settingsChanged: Boolean,
)

/** Pure conversion between Yokan snapshots and Mangayomi's independent clientId wire protocol. */
internal class MangayomiSyncMapper(
    mappingsJson: String?,
    private val namespace: MangayomiNamespace,
) {
    private val json = Json {
        ignoreUnknownKeys = true
        explicitNulls = false
    }
    private val namespaceKey = "${normalizeServer(namespace.server)}\n${namespace.accountId}"
    private val all = linkedMapOf<String, MutableMap<String, MutableMap<String, Binding>>>()
    private val bindings = linkedMapOf<String, MutableMap<String, Binding>>()
    // Every canonical/alias id of the active namespace -> owning local key, per kind. Binding id
    // sets only grow, so entries are never removed.
    private val owners = mutableMapOf<String, MutableMap<Long, String>>()
    private val pendingAliases = mutableMapOf<String, MutableMap<Long, Long>>()
    private val pendingByCanonical = mutableMapOf<String, MutableMap<Long, MutableSet<Long>>>()

    private class Binding(
        var canonical: Long,
        val aliases: MutableSet<Long> = linkedSetOf(),
        val retired: MutableSet<Long> = linkedSetOf(),
        val deletionTargets: MutableMap<String, Long> = linkedMapOf(),
    )

    init {
        if (mappingsJson != null) {
            val root = json.parseToJsonElement(mappingsJson).jsonObject
            val version = root["version"] as? JsonPrimitive
            require(version != null && !version.isString && version.intOrNull == 1) {
                "Unsupported Mangayomi mapping version"
            }
            val namespaces = root["namespaces"]?.jsonObject ?: error("Missing mapping namespaces")
            namespaces.forEach { (key, value) ->
                require(key.isNotBlank()) { "Invalid mapping namespace" }
                val namespaceBindings = linkedMapOf<String, MutableMap<String, Binding>>()
                value.jsonObject.forEach { (kind, rows) ->
                    require(
                        kind.toIntOrNull()?.let {
                            it in SyncPaths.KIND_CATEGORY..SyncPaths.KIND_UPDATE
                        } == true
                    ) {
                        "Invalid mapping kind"
                    }
                    val entities = linkedMapOf<String, Binding>()
                    rows.jsonObject.forEach { (local, raw) ->
                        val localId = local.toLongOrNull()
                        require(localId != null && localId > 0 && local == localId.toString()) {
                            "Invalid local mapping id"
                        }
                        val obj = raw.jsonObject
                        val canonical = safeId(obj["canonical"])
                        val aliasesElement = obj["aliases"]
                        require(aliasesElement == null || aliasesElement is JsonArray) {
                            "Invalid mapping aliases"
                        }
                        val aliasList = aliasesElement.orEmpty().map(::safeId)
                        require(aliasList.size == aliasList.toSet().size) {
                            "Duplicate mapping alias"
                        }
                        val aliases = aliasList.toMutableSet()
                        val retiredElement = obj["retired"]
                        require(retiredElement == null || retiredElement is JsonArray) {
                            "Invalid retired ids"
                        }
                        val retiredList = retiredElement.orEmpty().map(::safeId)
                        require(retiredList.size == retiredList.toSet().size) {
                            "Duplicate retired id"
                        }
                        val retired = retiredList.toMutableSet()
                        require(canonical !in aliases) { "Canonical id repeated as alias" }
                        require(canonical !in retired && retired.all { it in aliases }) {
                            "Invalid retired mapping ids"
                        }
                        val targetsObj =
                            obj["deletionTargets"]?.jsonObject ?: JsonObject(emptyMap())
                        val targets = targetsObj.mapValues { safeId(it.value) }.toMutableMap()
                        require(targets.values.all { it == canonical || it in aliases }) {
                            "Invalid recreation deletion target"
                        }
                        entities[local] = Binding(canonical, aliases, retired, targets)
                    }
                    validateOwnership(entities)
                    namespaceBindings[kind] = entities
                }
                all[key] = namespaceBindings
            }
            all[namespaceKey]?.forEach { (kind, rows) ->
                bindings[kind] = rows
                rows.forEach { (local, b) ->
                    own(kind, b.canonical, local)
                    b.aliases.forEach { own(kind, it, local) }
                }
            }
        }
    }

    fun mappingsJson(): String =
        buildJsonObject {
                put("version", 1)
                put(
                    "namespaces",
                    buildJsonObject {
                        val namespaces = all.toMutableMap()
                        namespaces[namespaceKey] = bindings
                        namespaces.entries
                            .sortedBy { it.key }
                            .forEach { (ns, kinds) ->
                                put(
                                    ns,
                                    buildJsonObject {
                                        kinds.entries
                                            .sortedBy { it.key }
                                            .forEach { (kind, entries) ->
                                                put(
                                                    kind,
                                                    buildJsonObject {
                                                        entries.entries
                                                            .sortedBy { it.key }
                                                            .forEach { (local, b) ->
                                                                put(
                                                                    local,
                                                                    buildJsonObject {
                                                                        put(
                                                                            "canonical",
                                                                            b.canonical,
                                                                        )
                                                                        put(
                                                                            "aliases",
                                                                            JsonArray(
                                                                                b.aliases
                                                                                    .sorted()
                                                                                    .map(
                                                                                        ::
                                                                                            JsonPrimitive
                                                                                    )
                                                                            ),
                                                                        )
                                                                        if (b.retired.isNotEmpty())
                                                                            put(
                                                                                "retired",
                                                                                JsonArray(
                                                                                    b.retired
                                                                                        .sorted()
                                                                                        .map(
                                                                                            ::
                                                                                                JsonPrimitive
                                                                                        )
                                                                                ),
                                                                            )
                                                                        if (
                                                                            b.deletionTargets
                                                                                .isNotEmpty()
                                                                        )
                                                                            put(
                                                                                "deletionTargets",
                                                                                buildJsonObject {
                                                                                    b
                                                                                        .deletionTargets
                                                                                        .entries
                                                                                        .sortedBy {
                                                                                            it.key
                                                                                        }
                                                                                        .forEach {
                                                                                            (
                                                                                                record,
                                                                                                id)
                                                                                            ->
                                                                                            put(
                                                                                                record,
                                                                                                id,
                                                                                            )
                                                                                        }
                                                                                },
                                                                            )
                                                                    },
                                                                )
                                                            }
                                                    },
                                                )
                                            }
                                    },
                                )
                            }
                    },
                )
            }
            .toString()

    fun prepare(
        snapshot: YokanDatabaseSnapshot,
        preference: DbSyncPreference,
    ): List<MangayomiBatch> {
        val rows =
            linkedMapOf(
                SyncPaths.KIND_CATEGORY to snapshot.categories.map { it.id },
                SyncPaths.KIND_MANGA to snapshot.mangas.map { it.id },
                SyncPaths.KIND_CHAPTER to snapshot.chapters.map { it.id },
                SyncPaths.KIND_TRACK to snapshot.tracks.map { it.id },
                SyncPaths.KIND_HISTORY to
                    if (preference.syncHistories) snapshot.histories.map { it.id } else emptyList(),
                SyncPaths.KIND_UPDATE to
                    if (preference.syncUpdates) snapshot.updates.map { it.id } else emptyList(),
            )
        ensureRecreationTransitions(snapshot.changedParts, snapshot, preference)
        rows.forEach { (kind, ids) -> ids.forEach { id -> remoteId(kind, id) } }
        val rowSets = rows.mapValues { it.value.toHashSet() }
        validateUploadDependencies(snapshot, rowSets)
        val order = rows.keys.toList()
        val deleteGroups = linkedMapOf<Int, MutableList<DbChangedPart>>()
        snapshot.changedParts.forEach { part ->
            deletionRecord(part)?.let { (kind, local) ->
                if (
                    kind in order &&
                        bindings[kind.toString()]?.containsKey(local.toString()) == true &&
                        (local !in rowSets.getValue(kind) ||
                            deletionTarget(kind, local, part) != null) &&
                        (kind != SyncPaths.KIND_HISTORY || preference.syncHistories) &&
                        (kind != SyncPaths.KIND_UPDATE || preference.syncUpdates)
                )
                    deleteGroups.getOrPut(kind) { mutableListOf() } += part
            }
        }
        val batches = mutableListOf<MangayomiBatch>()
        if (deleteGroups.isNotEmpty()) {
            deleteGroups.forEach { (kind, parts) ->
                val chunks = parts.distinct().chunked(5000)
                chunks.forEachIndexed { index, chunk ->
                    val target = batches.size.also { batches += MangayomiBatch(null, emptyList()) }
                    batches[target] =
                        batches[target].copy(deletions = batches[target].deletions + chunk)
                }
            }
        }
        for (kind in order) for (chunk in rows.getValue(kind).chunked(5000)) batches +=
            MangayomiBatch(kind, chunk)
        if (batches.isEmpty()) batches += MangayomiBatch(null, emptyList())
        return batches
    }

    fun encode(captured: YokanDatabaseSnapshot, batch: MangayomiBatch): JsonObject =
        buildJsonObject {
            batch.kind?.let { kind ->
                val kindName = wireKey(kind)
                val byId = rowsById(captured, kind)
                val array =
                    batch.localIds.map { id ->
                        encodeRow(
                            kind,
                            byId[id] ?: error("Captured entity $kind/$id no longer exists"),
                        )
                    }
                put(kindName, JsonArray(array))
            }
            if (batch.deletions.isNotEmpty()) {
                val deleted = linkedMapOf<String, MutableList<Long>>()
                batch.deletions.forEach { part ->
                    val o = json.parseToJsonElement(part.data).jsonObject
                    val kind = o.getValue("kind").jsonPrimitive.int
                    val local = o.getValue("localId").jsonPrimitive.content.toLong()
                    deleted.getOrPut(wireKey(kind)) { mutableListOf() } +=
                        deletionTarget(kind, local, part) ?: mappedId(kind, local)
                }
                put(
                    "deleted",
                    buildJsonObject {
                        deleted.forEach { (k, ids) ->
                            put(k, JsonArray(ids.distinct().map(::JsonPrimitive)))
                        }
                    },
                )
            }
        }

    fun decodePage(body: String): MangayomiPage {
        val root = json.parseToJsonElement(body).jsonObject
        val data =
            root["data"]?.let { raw ->
                val nested = raw as? JsonObject ?: error("Invalid response data")
                val wireKeys =
                    (SyncPaths.KIND_CATEGORY..SyncPaths.KIND_UPDATE).map(::wireKey) +
                        listOf(
                            "tombstones",
                            "deleted",
                            "mangaClientIdRemap",
                            "chapterClientIdRemap",
                        )
                JsonObject(nested + root.filterKeys { it in wireKeys && it !in nested })
            } ?: root
        val cursorsRaw = root["cursors"] ?: data["cursors"]
        val cursorObj =
            cursorsRaw?.let { it as? JsonObject ?: error("Invalid cursors") }
                ?: JsonObject(emptyMap())
        val cursors =
            cursorObj.mapValues { (_, v) ->
                if (v is JsonNull) null
                else
                    (v as? JsonPrimitive)?.takeIf { it.isString }?.content
                        ?: error("Invalid cursor")
            }
        val moreElement = root["hasMore"] ?: data["hasMore"] ?: error("Missing hasMore")
        val hasMore = moreElement.jsonPrimitive.booleanOrNull ?: error("Invalid hasMore")
        val syncedElement = root["syncedAt"] ?: data["syncedAt"] ?: error("Missing syncedAt")
        val syncedAt =
            if (syncedElement is JsonNull && hasMore) null
            else longValue(syncedElement).also { require(it >= 0) { "Invalid syncedAt" } }
        val tokenElement = root["sessionToken"] ?: data["sessionToken"]
        val token =
            tokenElement?.let {
                if (it is JsonNull) null
                else
                    (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.content
                        ?: error("Invalid sessionToken")
            }
        return MangayomiPage(data, cursors, token, hasMore, syncedAt)
    }

    fun acceptRemaps(page: MangayomiPage) {
        validatePage(page)
        acceptRemapKind(page.data, SyncPaths.KIND_MANGA, "mangaClientIdRemap")
        acceptRemapKind(page.data, SyncPaths.KIND_CHAPTER, "chapterClientIdRemap")
    }

    fun merge(
        current: YokanDatabaseSnapshot,
        pages: List<MangayomiPage>,
        preference: DbSyncPreference,
    ): MangayomiMerge {
        pages.forEach(::validatePage)
        ensureRecreationTransitions(current.changedParts, current, preference)
        val rows = mutableMapOf<Int, MutableList<JsonObject>>()
        val tombstones = mutableMapOf<Int, MutableSet<Long>>()
        pages.forEach { page ->
            acceptRemaps(page)
            listOf(
                    SyncPaths.KIND_CATEGORY,
                    SyncPaths.KIND_MANGA,
                    SyncPaths.KIND_CHAPTER,
                    SyncPaths.KIND_TRACK,
                    SyncPaths.KIND_HISTORY,
                    SyncPaths.KIND_UPDATE,
                )
                .forEach { k ->
                    if (
                        k == SyncPaths.KIND_HISTORY && !preference.syncHistories ||
                            k == SyncPaths.KIND_UPDATE && !preference.syncUpdates
                    )
                        return@forEach
                    (page.data[wireKey(k)] as? JsonArray)?.forEach {
                        rows.getOrPut(k) { mutableListOf() } += it.jsonObject
                    }
                }
            val deleted =
                page.data["tombstones"] as? JsonObject ?: page.data["deleted"] as? JsonObject
            deleted?.forEach { (key, ids) ->
                kindForKey(key)?.let { k ->
                    if (
                        (k != SyncPaths.KIND_HISTORY || preference.syncHistories) &&
                            (k != SyncPaths.KIND_UPDATE || preference.syncUpdates)
                    )
                        (ids as JsonArray).forEach {
                            tombstones.getOrPut(k) { mutableSetOf() } += safeId(it)
                        }
                }
            }
        }
        val result = MutableSnapshot(current)
        val queuedDeleteLocals =
            current.changedParts
                .mapNotNull(::deletionRecord)
                .groupBy({ it.first }, { it.second })
                .mapValues { it.value.toSet() }
        val localByRemote = mutableMapOf<Int, MutableMap<Long, Long>>()
        val claimedNaturalLocals = mutableMapOf<Int, MutableSet<Long>>()
        // Identity is established for all rows before LWW, allowing stale rows/remaps to
        // canonicalize references.
        for (k in
            listOf(
                SyncPaths.KIND_CATEGORY,
                SyncPaths.KIND_MANGA,
                SyncPaths.KIND_CHAPTER,
                SyncPaths.KIND_TRACK,
                SyncPaths.KIND_HISTORY,
                SyncPaths.KIND_UPDATE,
            )) {
            rows[k].orEmpty().forEach { row ->
                val remote = safeId(row["clientId"])
                val local =
                    localByRemote[k]?.get(remote)
                        ?: resolveLocal(result, k, remote, row, claimedNaturalLocals[k].orEmpty())
                bind(k, local, remote)
                localByRemote.getOrPut(k) { mutableMapOf() }[remote] = local
                if (k == SyncPaths.KIND_HISTORY || k == SyncPaths.KIND_UPDATE)
                    claimedNaturalLocals.getOrPut(k) { mutableSetOf() } += local
            }
        }
        val count = intArrayOf(0)
        for (k in
            listOf(
                SyncPaths.KIND_CATEGORY,
                SyncPaths.KIND_MANGA,
                SyncPaths.KIND_CHAPTER,
                SyncPaths.KIND_TRACK,
                SyncPaths.KIND_HISTORY,
                SyncPaths.KIND_UPDATE,
            )) {
            rows[k].orEmpty().forEach { row ->
                val local = localByRemote[k]?.get(safeId(row["clientId"]))
                if (
                    local != null &&
                        local in queuedDeleteLocals[k].orEmpty() &&
                        !hasLocalEntity(result, k, local)
                )
                    return@forEach
                if (
                    k != SyncPaths.KIND_MANGA &&
                        rowParentPendingDelete(result, k, row, localByRemote, queuedDeleteLocals)
                )
                    return@forEach
                if (applyRow(result, k, row, localByRemote, queuedDeleteLocals)) count[0]++
            }
        }
        tombstones.forEach { (kind, ids) ->
            val recreationTargets =
                bindings[kind.toString()]
                    ?.values
                    ?.flatMapTo(hashSetOf()) { it.deletionTargets.values }
                    .orEmpty()
            ids.forEach { remote ->
                if (remote in recreationTargets) return@forEach
                val owner = ownerForRemote(kind, remote)
                val local = owner?.takeIf { remote == it.second.canonical }?.first?.toLong()
                if (local == null) return@forEach
                require(!unsafeDownload(result, kind, local)) {
                    "Cannot delete entity with active download"
                }
                rotate(kind, local)
                result.delete(kind, local)
            }
        }
        return MangayomiMerge(result.build(), count[0], false)
    }

    private fun encodeRow(k: Int, value: Any): JsonObject {
        val row =
            when (k) {
                SyncPaths.KIND_CATEGORY -> encodeCategory(value as DbCategory)
                SyncPaths.KIND_MANGA -> encodeManga(requireNotNull(value as? DbManga))
                SyncPaths.KIND_CHAPTER -> encodeChapter(requireNotNull(value as? DbChapter))
                SyncPaths.KIND_TRACK -> encodeTrack(value as DbTrack)
                SyncPaths.KIND_HISTORY -> encodeHistory(value as DbHistory)
                else -> encodeUpdate(value as DbUpdate)
            }
        return withinServerLimits(k, row)
    }

    private fun clientId(kind: Int, local: Long?): JsonElement =
        local?.let { JsonPrimitive(mappedId(kind, it)) } ?: JsonNull

    private fun millis(v: String?): JsonElement =
        v?.let { (it.toLongOrNull() ?: parseInstantMillis(it))?.let(::JsonPrimitive) } ?: JsonNull

    private fun encodeCategory(x: DbCategory) = buildJsonObject {
        put("clientId", clientId(SyncPaths.KIND_CATEGORY, x.id))
        put("name", x.name)
        put("forItemType", x.forItemType.name.uppercase())
        put("pos", x.position?.let(::JsonPrimitive) ?: JsonNull)
        put("hide", x.hidden ?: false)
        put("shouldUpdate", x.shouldUpdate ?: true)
        put("updatedAt", x.updatedAt)
    }

    private fun encodeManga(x: DbManga) = buildJsonObject {
        put("clientId", clientId(SyncPaths.KIND_MANGA, x.id))
        nullable("source", x.source)
        nullable("sourceId", x.sourceId)
        nullable("link", x.link)
        put("itemType", type(x.itemType))
        nullable("name", x.name)
        nullable("imageUrl", x.imageUrl)
        nullable("description", x.description)
        nullable("author", x.author)
        nullable("artist", x.artist)
        put("status", status(x.status))
        put("genre", JsonArray((x.genre ?: emptyList()).map(::JsonPrimitive)))
        nullable("lang", x.lang)
        nullable("lastUpdate", x.lastUpdate)
        put("favorite", x.favorite)
        nullable("dateAdded", x.dateAdded)
        put("lastRead", x.lastRead)
        put("isLocalArchive", x.isLocalArchive)
        nullable("customCoverFromTracker", x.customCoverFromTracker)
        nullable("smartUpdateDays", x.smartUpdateDays)
        put(
            "categoryClientIds",
            JsonArray((x.categories ?: emptyList()).map { clientId(SyncPaths.KIND_CATEGORY, it) }),
        )
        put("updatedAt", x.updatedAt)
    }

    private fun encodeChapter(x: DbChapter) = buildJsonObject {
        put("clientId", clientId(SyncPaths.KIND_CHAPTER, x.id))
        put("mangaClientId", clientId(SyncPaths.KIND_MANGA, x.mangaId))
        nullable("name", x.name)
        nullable("url", x.url)
        put("scanlator", x.scanlator)
        put("dateUpload", millis(x.dateUpload))
        put("isFiller", x.effectiveFiller)
        nullable("thumbnailUrl", x.thumbnailUrl)
        nullable("description", x.description)
        put("downloadSize", JsonNull)
        nullable("duration", x.duration?.toLongOrNull())
        put("isRead", x.isRead)
        put("isBookmarked", x.isBookmarked)
        put("lastPageRead", x.lastPageRead)
        put("updatedAt", x.updatedAt)
    }

    private fun encodeTrack(x: DbTrack) = buildJsonObject {
        put("clientId", clientId(SyncPaths.KIND_TRACK, x.id))
        put("mangaClientId", clientId(SyncPaths.KIND_MANGA, x.mangaId))
        nullable("syncId", x.syncId)
        nullable("mediaId", x.mediaId)
        nullable("libraryId", x.libraryId)
        nullable("title", x.title)
        nullable("lastChapterRead", x.lastChapterRead)
        nullable("totalChapter", x.totalChapter)
        nullable("score", x.score)
        put("status", x.status.name.replace(Regex("([a-z])([A-Z])"), "$1_$2").uppercase())
        nullable("startedReadingDate", x.startedReadingDate)
        nullable("finishedReadingDate", x.finishedReadingDate)
        nullable("trackingUrl", x.trackingUrl)
        put("itemType", type(x.itemType))
        put("updatedAt", x.updatedAt)
    }

    private fun encodeHistory(x: DbHistory) = buildJsonObject {
        put("clientId", clientId(SyncPaths.KIND_HISTORY, x.id))
        put("mangaClientId", clientId(SyncPaths.KIND_MANGA, x.mangaId))
        put("chapterClientId", clientId(SyncPaths.KIND_CHAPTER, x.chapterId))
        put("itemType", type(x.itemType))
        put("date", millis(x.date))
        nullable("readingTimeSeconds", x.readingTimeSeconds ?: 0)
        put("updatedAt", x.updatedAt)
    }

    private fun encodeUpdate(x: DbUpdate) = buildJsonObject {
        put("clientId", clientId(SyncPaths.KIND_UPDATE, x.id))
        put("mangaClientId", clientId(SyncPaths.KIND_MANGA, x.mangaId))
        nullable("chapterName", x.chapterName)
        put("date", millis(x.date))
        put("updatedAt", x.updatedAt)
    }

    /**
     * The server rejects a whole request (HTTP 400) when any field exceeds its schema, and real
     * libraries have longer descriptions/authors than it allows. Clip to its limits
     * (mangayomi-sync-server lib/validation/sync.ts): only the server's copy is shortened; local
     * rows keep full text because equal-timestamp pulls never replace them.
     */
    private fun withinServerLimits(k: Int, row: JsonObject): JsonObject {
        val limits = SERVER_STRING_LIMITS.getValue(k)
        return JsonObject(
            row.mapValues { (key, value) ->
                val max = limits[key]
                when {
                    key == "trackingUrl" &&
                        value is JsonPrimitive &&
                        value.isString &&
                        value.content.isNotEmpty() &&
                        !value.content.startsWith("http://") &&
                        !value.content.startsWith("https://") -> JsonNull
                    max != null &&
                        value is JsonPrimitive &&
                        value.isString &&
                        value.content.length > max -> JsonPrimitive(clip(value.content, max))
                    key == "genre" && value is JsonArray ->
                        JsonArray(
                            value.map { g ->
                                if (g is JsonPrimitive && g.content.length > 100)
                                    JsonPrimitive(clip(g.content, 100))
                                else g
                            }
                        )
                    key == "categoryClientIds" && value is JsonArray && value.size > 200 ->
                        JsonArray(value.take(200))
                    else -> value
                }
            }
        )
    }

    // Counts UTF-16 units like JavaScript's string length; never splits a surrogate pair.
    private fun clip(s: String, max: Int): String =
        s.take(if (s[max - 1].isHighSurrogate()) max - 1 else max)

    private fun JsonObjectBuilder.nullable(key: String, v: String?) {
        put(key, v?.let(::JsonPrimitive) ?: JsonNull)
    }

    private fun JsonObjectBuilder.nullable(key: String, v: Number?) {
        put(key, v?.let(::JsonPrimitive) ?: JsonNull)
    }

    // asReversed keeps the first row for a duplicated id, like firstOrNull did.
    private fun rowsById(s: YokanDatabaseSnapshot, k: Int): Map<Long, Any> =
        when (k) {
            SyncPaths.KIND_CATEGORY -> s.categories.asReversed().associateBy { it.id }
            SyncPaths.KIND_MANGA -> s.mangas.asReversed().associateBy { it.id }
            SyncPaths.KIND_CHAPTER -> s.chapters.asReversed().associateBy { it.id }
            SyncPaths.KIND_TRACK -> s.tracks.asReversed().associateBy { it.id }
            SyncPaths.KIND_HISTORY -> s.histories.asReversed().associateBy { it.id }
            else -> s.updates.asReversed().associateBy { it.id }
        }

    private fun own(kind: String, id: Long, local: String) {
        val owner = owners.getOrPut(kind) { mutableMapOf() }.getOrPut(id) { local }
        require(owner == local) { "Remote mapping id collision" }
    }

    private fun remoteId(k: Int, local: Long): Long {
        require(local > 0)
        val ks = k.toString()
        val map = bindings.getOrPut(ks) { linkedMapOf() }
        val key = local.toString()
        map[key]?.let {
            return it.canonical
        }
        val used = owners[ks].orEmpty()
        var candidate = hash("$namespaceKey|$k|$local")
        while (candidate in used || candidate <= 0) candidate =
            if (candidate == MAX_SAFE) 1 else candidate + 1
        map[key] = Binding(candidate)
        own(ks, candidate, key)
        return candidate
    }

    private fun mappedId(k: Int, local: Long): Long =
        bindings[k.toString()]?.get(local.toString())?.canonical
            ?: error("Missing prepared mapping for kind $k local id $local")

    private fun recordKey(part: DbChangedPart): String =
        buildJsonObject {
                put("id", part.id)
                put("actionType", part.actionType.name)
                put("isarId", part.isarId?.let(::JsonPrimitive) ?: JsonNull)
                put("clientDate", part.clientDate)
                put("data", part.data)
            }
            .toString()

    private fun deletionTarget(kind: Int, local: Long, part: DbChangedPart): Long? =
        bindings[kind.toString()]?.get(local.toString())?.deletionTargets?.get(recordKey(part))

    private fun ensureRecreationTransitions(
        parts: List<DbChangedPart>,
        snapshot: YokanDatabaseSnapshot,
        preference: DbSyncPreference,
    ) {
        val records =
            parts.mapNotNull { part ->
                deletionRecord(part)?.let { (kind, local) -> Triple(kind, local, part) }
            }
        if (records.isEmpty()) return
        val ids = entityIds(snapshot)
        val groups =
            records
                .filter { (kind, local, _) ->
                    enabled(kind, preference) && local in ids.getValue(kind)
                }
                .groupBy({ it.first to it.second }, { it.third })
        val children by lazy { Children(snapshot) }
        groups.forEach { (identity, records) ->
            val (kind, local) = identity
            val binding = bindings[kind.toString()]?.get(local.toString()) ?: return@forEach
            val known = records.mapNotNull { binding.deletionTargets[recordKey(it)] }.distinct()
            require(known.size <= 1) { "Conflicting recreation deletion targets" }
            val target =
                known.singleOrNull()
                    ?: binding.canonical.also {
                        rotate(kind, local)
                        rotateDependents(children, kind, local)
                    }
            records.forEach {
                val key = recordKey(it)
                if (key !in binding.deletionTargets) binding.deletionTargets[key] = target
            }
        }
    }

    // The server cascades a manga delete to its chapters/tracks/histories/updates and a chapter
    // delete to its histories.
    // Surviving children must leave those old IDs too, or the cascade tombstones delete them on the
    // next pull.
    private class Children(s: YokanDatabaseSnapshot) {
        val byManga =
            listOf(
                SyncPaths.KIND_CHAPTER to s.chapters.groupBy({ it.mangaId }, { it.id }),
                SyncPaths.KIND_TRACK to s.tracks.groupBy({ it.mangaId }, { it.id }),
                SyncPaths.KIND_HISTORY to s.histories.groupBy({ it.mangaId }, { it.id }),
                SyncPaths.KIND_UPDATE to s.updates.groupBy({ it.mangaId }, { it.id }),
            )
        val historiesByChapter = s.histories.groupBy({ it.chapterId }, { it.id })
    }

    private fun rotateDependents(c: Children, k: Int, id: Long) {
        when (k) {
            SyncPaths.KIND_MANGA ->
                c.byManga.forEach { (kind, byParent) ->
                    byParent[id].orEmpty().forEach { rotate(kind, it) }
                }
            SyncPaths.KIND_CHAPTER ->
                c.historiesByChapter[id].orEmpty().forEach { rotate(SyncPaths.KIND_HISTORY, it) }
        }
    }

    private fun entityIds(s: YokanDatabaseSnapshot): Map<Int, Set<Long>> =
        mapOf(
            SyncPaths.KIND_CATEGORY to s.categories.mapTo(hashSetOf()) { it.id },
            SyncPaths.KIND_MANGA to s.mangas.mapTo(hashSetOf()) { it.id },
            SyncPaths.KIND_CHAPTER to s.chapters.mapTo(hashSetOf()) { it.id },
            SyncPaths.KIND_TRACK to s.tracks.mapTo(hashSetOf()) { it.id },
            SyncPaths.KIND_HISTORY to s.histories.mapTo(hashSetOf()) { it.id },
            SyncPaths.KIND_UPDATE to s.updates.mapTo(hashSetOf()) { it.id },
        )

    private fun rotate(k: Int, local: Long) {
        val ks = k.toString()
        val key = local.toString()
        val b = bindings[ks]?.get(key) ?: return
        b.aliases += b.canonical
        b.retired += b.canonical
        var id = hash("$namespaceKey|$k|$local|${SyncIds.random()}")
        val used = owners[ks].orEmpty()
        while (id in used) id = if (id == MAX_SAFE) 1 else id + 1
        b.canonical = id
        own(ks, id, key)
    }

    private fun bind(k: Int, local: Long, remote: Long) {
        val ks = k.toString()
        val map = bindings.getOrPut(ks) { linkedMapOf() }
        val key = local.toString()
        val owner = owners[ks]?.get(remote)
        require(owner == null || owner == key) {
            "Remote id $remote already belongs to another local row"
        }
        val b = map.getOrPut(key) { Binding(remote) }
        when {
            remote == b.canonical -> Unit
            remote in b.aliases -> Unit // A retired/legacy alias never becomes canonical again.
            else -> {
                require(owner == null)
                b.aliases += b.canonical
                b.retired += b.canonical
                b.canonical = remote
                b.aliases += remote
                b.aliases.remove(remote)
                b.retired.remove(remote)
            }
        }
        own(ks, remote, key)
        pendingByCanonical[ks]?.get(remote)?.forEach { old ->
            b.aliases += old
            b.retired += old
            own(ks, old, key)
        }
    }

    private fun resolveLocal(
        s: MutableSnapshot,
        k: Int,
        remote: Long,
        r: JsonObject,
        claimed: Set<Long>,
    ): Long {
        ownerForRemote(k, remote)?.let {
            return it.first.toLong()
        }
        val matches =
            when (k) {
                SyncPaths.KIND_CATEGORY -> emptyList()
                SyncPaths.KIND_MANGA -> {
                    val link = nullableString(r, "link")
                    val source = nullableString(r, "source")
                    if (link.isNullOrBlank() || source.isNullOrBlank()) emptyList()
                    else
                        s.mangaNatural[Triple(link, source, itemType(r, "itemType"))].map {
                            s.mangas[it].id
                        }
                }
                SyncPaths.KIND_CHAPTER -> {
                    val url = nullableString(r, "url")
                    val parent = remoteLocal(SyncPaths.KIND_MANGA, long(r, "mangaClientId"))
                    if (url.isNullOrBlank() || parent == null || !s.mangas.has(parent)) emptyList()
                    else s.chapterByUrl[parent to url].map { s.chapters[it].id }
                }
                SyncPaths.KIND_TRACK -> {
                    val parent = remoteLocal(SyncPaths.KIND_MANGA, long(r, "mangaClientId"))
                    val tracker = intNullable(r, "syncId")
                    if (parent == null || tracker == null || !s.mangas.has(parent)) emptyList()
                    else s.trackBySync[parent to tracker].map { s.tracks[it].id }
                }
                SyncPaths.KIND_HISTORY ->
                    s.historyByChapter[
                            remoteLocal(SyncPaths.KIND_CHAPTER, long(r, "chapterClientId"))]
                        .map { s.histories[it].id }
                else -> {
                    val parent = remoteLocal(SyncPaths.KIND_MANGA, long(r, "mangaClientId"))
                    val name = nullableString(r, "chapterName")
                    if (parent == null || name.isNullOrBlank() || !s.mangas.has(parent)) emptyList()
                    else s.updateByName[parent to name].map { s.updates[it].id }
                }
            }
        val available =
            if (k == SyncPaths.KIND_HISTORY || k == SyncPaths.KIND_UPDATE)
                matches.filterNot { it in claimed }
            else matches
        require(available.size <= 1) { "Ambiguous Mangayomi natural identity" }
        return available.singleOrNull() ?: newLocalIdentity(s, k)
    }

    private fun applyRow(
        s: MutableSnapshot,
        k: Int,
        r: JsonObject,
        maps: Map<Int, Map<Long, Long>>,
        pendingDeletes: Map<Int, Set<Long>>,
    ): Boolean {
        val remote = safeId(r["clientId"])
        val id = maps[k]?.get(remote) ?: error("Missing mapped identity")
        val updated = long(r, "updatedAt")
        require(updated >= 0)
        return when (k) {
            SyncPaths.KIND_CATEGORY -> applyCategory(s, id, r, updated)
            SyncPaths.KIND_MANGA -> applyManga(s, id, r, updated, maps, pendingDeletes)
            SyncPaths.KIND_CHAPTER -> applyChapter(s, id, r, updated, maps)
            SyncPaths.KIND_TRACK -> applyTrack(s, id, r, updated, maps)
            SyncPaths.KIND_HISTORY -> applyHistory(s, id, r, updated, maps)
            else -> applyUpdate(s, id, r, updated, maps)
        }
    }

    private fun ref(
        s: MutableSnapshot,
        r: JsonObject,
        maps: Map<Int, Map<Long, Long>>,
        kind: Int,
        key: String,
    ): Long {
        val rid = safeId(r[key])
        return resolveReference(s, kind, rid, maps) ?: error("Unresolved $key reference")
    }

    private fun applyCategory(s: MutableSnapshot, id: Long, r: JsonObject, updated: Long): Boolean {
        val i = s.categories.indexOf(id)
        val old = s.categories.getOrNull(i)
        if (old != null && updated <= old.updatedAt) return false
        val x =
            DbCategory(
                id,
                str(r, "name"),
                itemType(r, "forItemType"),
                intNullable(r, "pos"),
                boolNullable(r, "hide"),
                boolNullable(r, "shouldUpdate"),
                updated,
            )
        if (old == null) s.categories += x else s.categories[i] = x
        return true
    }

    private fun applyManga(
        s: MutableSnapshot,
        id: Long,
        r: JsonObject,
        updated: Long,
        maps: Map<Int, Map<Long, Long>>,
        pendingDeletes: Map<Int, Set<Long>>,
    ): Boolean {
        val i = s.mangas.indexOf(id)
        val old = s.mangas.getOrNull(i)
        if (old != null && updated <= old.updatedAt) return false
        val catIds =
            r["categoryClientIds"]
                ?.jsonArray
                ?.mapNotNull { e ->
                    val remoteCat = safeId(e)
                    resolveReference(s, SyncPaths.KIND_CATEGORY, remoteCat, maps)
                        ?: run {
                            val owner =
                                ownerForRemote(SyncPaths.KIND_CATEGORY, remoteCat)?.first?.toLong()
                            if (
                                owner != null &&
                                    owner in pendingDeletes[SyncPaths.KIND_CATEGORY].orEmpty() &&
                                    !hasLocalEntity(s, SyncPaths.KIND_CATEGORY, owner)
                            ) {
                                null
                            } else {
                                error("Unresolved category membership")
                            }
                        }
                }
                ?.takeIf { r.containsKey("categoryClientIds") }
        val x =
            DbManga(
                id = id,
                name = nullableString(r, "name"),
                link = nullableString(r, "link"),
                imageUrl = nullableString(r, "imageUrl"),
                description = nullableString(r, "description"),
                author = nullableString(r, "author"),
                artist = nullableString(r, "artist"),
                status = status(r, old?.status),
                itemType = itemType(r, "itemType"),
                genre = r["genre"]?.jsonArray?.map { it.jsonPrimitive.content },
                favorite = bool(r, "favorite", false),
                source = nullableString(r, "source"),
                lang = nullableString(r, "lang"),
                dateAdded = longNullable(r, "dateAdded"),
                lastUpdate = longNullable(r, "lastUpdate"),
                lastRead = longNullable(r, "lastRead") ?: old?.lastRead ?: 0,
                categories = catIds ?: old?.categories,
                isLocalArchive = bool(r, "isLocalArchive", false),
                customCoverImage = old?.customCoverImage,
                customCoverFromTracker = nullableString(r, "customCoverFromTracker"),
                smartUpdateDays = intNullable(r, "smartUpdateDays"),
                updatedAt = updated,
                sourceId = longNullable(r, "sourceId"),
                privateNote = old?.privateNote.orEmpty(),
                cast = old?.cast.orEmpty(),
                parentId = old?.parentId,
                fetchType = old?.fetchType ?: DbFetchType.Episodes,
                seasonNumber = old?.seasonNumber,
            )
        if (old == null) s.mangas += x else s.mangas[i] = x
        return true
    }

    private fun applyChapter(
        s: MutableSnapshot,
        id: Long,
        r: JsonObject,
        updated: Long,
        maps: Map<Int, Map<Long, Long>>,
    ): Boolean {
        val manga = ref(s, r, maps, SyncPaths.KIND_MANGA, "mangaClientId")
        val i = s.chapters.indexOf(id)
        val old = s.chapters.getOrNull(i)
        if (old != null && updated <= old.updatedAt) return false
        require(s.mangas.has(manga)) { "Unresolved manga reference" }
        val x =
            DbChapter(
                id = id,
                mangaId = manga,
                name = nullableString(r, "name"),
                url = nullableString(r, "url") ?: "",
                dateUpload = longNullable(r, "dateUpload")?.toString() ?: "",
                scanlator = nullableString(r, "scanlator") ?: "",
                isBookmarked = bool(r, "isBookmarked", false),
                isRead = bool(r, "isRead", false),
                lastPageRead = nullableString(r, "lastPageRead") ?: "",
                archivePath = old?.archivePath ?: "",
                isFiller = bool(r, "isFiller", false),
                thumbnailUrl = nullableString(r, "thumbnailUrl"),
                description = nullableString(r, "description"),
                downloadSize = old?.downloadSize,
                duration = longNullable(r, "duration")?.toString(),
                updatedAt = updated,
                fetchedAt = old?.fetchedAt ?: 0,
                number = old?.number,
                season = old?.season,
                numberingName = old?.numberingName,
                fillerOverride = old?.fillerOverride,
            )
        if (old == null) s.chapters += x else s.chapters[i] = x
        return true
    }

    private fun applyTrack(
        s: MutableSnapshot,
        id: Long,
        r: JsonObject,
        updated: Long,
        maps: Map<Int, Map<Long, Long>>,
    ): Boolean {
        val manga = ref(s, r, maps, SyncPaths.KIND_MANGA, "mangaClientId")
        val i = s.tracks.indexOf(id)
        val old = s.tracks.getOrNull(i)
        if (old != null && updated <= old.updatedAt) return false
        val x =
            DbTrack(
                id = id,
                libraryId = intNullable(r, "libraryId")?.toLong(),
                mediaId = intNullable(r, "mediaId")?.toLong(),
                mangaId = manga,
                syncId = intNullable(r, "syncId"),
                title = nullableString(r, "title"),
                lastChapterRead = intNumberNullable(r, "lastChapterRead"),
                totalChapter = intNullable(r, "totalChapter"),
                score = intNumberNullable(r, "score"),
                status = trackStatus(r),
                startedReadingDate = longNullable(r, "startedReadingDate"),
                finishedReadingDate = longNullable(r, "finishedReadingDate"),
                trackingUrl = nullableString(r, "trackingUrl"),
                itemType = itemType(r, "itemType"),
                updatedAt = updated,
            )
        if (old == null) s.tracks += x else s.tracks[i] = x
        return true
    }

    private fun applyHistory(
        s: MutableSnapshot,
        id: Long,
        r: JsonObject,
        updated: Long,
        maps: Map<Int, Map<Long, Long>>,
    ): Boolean {
        val manga = ref(s, r, maps, SyncPaths.KIND_MANGA, "mangaClientId")
        val chapter = ref(s, r, maps, SyncPaths.KIND_CHAPTER, "chapterClientId")
        require(s.mangas.has(manga) && s.chapters.row(chapter)?.mangaId == manga) {
            "Unresolved history reference"
        }
        val i = s.histories.indexOf(id)
        val old = s.histories.getOrNull(i)
        if (old != null && updated <= old.updatedAt) return false
        val x =
            DbHistory(
                id = id,
                mangaId = manga,
                chapterId = chapter,
                itemType = itemType(r, "itemType"),
                date = longNullable(r, "date")?.toString(),
                updatedAt = updated,
                readingTimeSeconds = intNullable(r, "readingTimeSeconds"),
            )
        if (old == null) s.histories += x else s.histories[i] = x
        return true
    }

    private fun applyUpdate(
        s: MutableSnapshot,
        id: Long,
        r: JsonObject,
        updated: Long,
        maps: Map<Int, Map<Long, Long>>,
    ): Boolean {
        val manga = ref(s, r, maps, SyncPaths.KIND_MANGA, "mangaClientId")
        val i = s.updates.indexOf(id)
        val old = s.updates.getOrNull(i)
        if (old != null && updated <= old.updatedAt) return false
        val chapterName = nullableString(r, "chapterName")
        val kept =
            old?.chapterId?.takeIf { old.mangaId == manga && s.chapters.row(it)?.mangaId == manga }
        val chapters =
            if (chapterName == null) emptyList() else s.chapterByName[manga to chapterName]
        val x =
            DbUpdate(
                id = id,
                mangaId = manga,
                chapterId = kept ?: chapters.singleOrNull()?.let { s.chapters[it].id },
                chapterName = chapterName,
                date = longNullable(r, "date")?.toString(),
                updatedAt = updated,
            )
        if (old == null) s.updates += x else s.updates[i] = x
        return true
    }

    private fun acceptRemapKind(data: JsonObject, k: Int, key: String) {
        (data[key] as? JsonObject)?.forEach { (from, v) ->
            val old =
                from.toLongOrNull()?.also { require(it in 1..MAX_SAFE) }
                    ?: error("Invalid remap id")
            val canonical = safeId(v)
            val ks = k.toString()
            val fromOwner = owners[ks]?.get(old)
            val toOwner = owners[ks]?.get(canonical)
            // Two local rows for one server title (e.g. duplicate manga with the same source+link):
            // the server dedups
            // onto the other row's id. Stealing it would merge unrelated local identities, and
            // failing would block every
            // future sync, so keep both bindings; the duplicate's own id just stays unknown to the
            // server.
            if (fromOwner != null && toOwner != null && fromOwner != toOwner) return@forEach
            val owner = fromOwner ?: toOwner
            if (owner == null) {
                val previous = pendingAliases.getOrPut(ks) { mutableMapOf() }.put(old, canonical)
                if (previous != canonical) {
                    previous?.let { pendingByCanonical[ks]?.get(it)?.remove(old) }
                    pendingByCanonical
                        .getOrPut(ks) { mutableMapOf() }
                        .getOrPut(canonical) { linkedSetOf() } += old
                }
            } else {
                val b = bindings.getValue(ks).getValue(owner)
                if (canonical != b.canonical) {
                    b.aliases += b.canonical
                    b.retired += b.canonical
                    b.aliases.remove(canonical)
                    b.retired.remove(canonical)
                    b.canonical = canonical
                    own(ks, canonical, owner)
                }
                if (old != b.canonical) {
                    b.aliases += old
                    b.retired += old
                    own(ks, old, owner)
                }
            }
        }
    }

    private fun wireKey(k: Int) =
        when (k) {
            SyncPaths.KIND_CATEGORY -> "categories"
            SyncPaths.KIND_MANGA -> "manga"
            SyncPaths.KIND_CHAPTER -> "chapters"
            SyncPaths.KIND_TRACK -> "tracks"
            SyncPaths.KIND_HISTORY -> "histories"
            SyncPaths.KIND_UPDATE -> "updates"
            else -> error("Unsupported kind")
        }

    private fun kindForKey(s: String) =
        when (s) {
            "categories" -> SyncPaths.KIND_CATEGORY
            "manga" -> SyncPaths.KIND_MANGA
            "chapters" -> SyncPaths.KIND_CHAPTER
            "tracks" -> SyncPaths.KIND_TRACK
            "histories" -> SyncPaths.KIND_HISTORY
            "updates" -> SyncPaths.KIND_UPDATE
            else -> null
        }

    private fun type(t: DbItemType) = t.name.uppercase()

    private fun status(s: DbStatus) =
        when (s) {
            DbStatus.Ongoing -> "ONGOING"
            DbStatus.Completed -> "COMPLETED"
            DbStatus.Canceled -> "CANCELED"
            DbStatus.Unknown,
            DbStatus.Licensed,
            DbStatus.Upcoming -> "UNKNOWN"
            DbStatus.OnHiatus -> "ON_HIATUS"
            DbStatus.PublishingFinished -> "PUBLISHING_FINISHED"
        }

    private fun itemType(o: JsonObject, k: String) = enumValue<DbItemType>(str(o, k))

    private fun status(o: JsonObject, previous: DbStatus? = null): DbStatus {
        val incoming =
            when (str(o, "status")) {
                "ONGOING" -> DbStatus.Ongoing
                "COMPLETED" -> DbStatus.Completed
                "CANCELED" -> DbStatus.Canceled
                "UNKNOWN" -> DbStatus.Unknown
                "ON_HIATUS" -> DbStatus.OnHiatus
                "PUBLISHING_FINISHED" -> DbStatus.PublishingFinished
                else -> error("Invalid manga status")
            }
        // UNKNOWN is also our downgrade for statuses this server cannot represent.
        return if (
            incoming == DbStatus.Unknown &&
                (previous == DbStatus.Licensed || previous == DbStatus.Upcoming)
        )
            previous
        else incoming
    }

    private fun trackStatus(o: JsonObject) =
        when (str(o, "status")) {
            "READING" -> DbTrackStatus.Reading
            "COMPLETED" -> DbTrackStatus.Completed
            "ON_HOLD" -> DbTrackStatus.OnHold
            "DROPPED" -> DbTrackStatus.Dropped
            "PLAN_TO_READ" -> DbTrackStatus.PlanToRead
            "RE_READING" -> DbTrackStatus.ReReading
            "WATCHING" -> DbTrackStatus.Watching
            "PLAN_TO_WATCH" -> DbTrackStatus.PlanToWatch
            "RE_WATCHING" -> DbTrackStatus.ReWatching
            else -> error("Invalid track status")
        }

    private inline fun <reified T : Enum<T>> enumValue(v: String) =
        enumValues<T>().firstOrNull { it.name.uppercase() == v } ?: error("Invalid enum value")

    private fun safeId(v: JsonElement?): Long {
        val n = longValue(requireNotNull(v))
        require(n in 1..MAX_SAFE) { "Invalid clientId" }
        return n
    }

    private fun longValue(v: JsonElement): Long {
        val p = v as? JsonPrimitive ?: error("Expected number")
        require(!p.isString && p.booleanOrNull == null) { "Expected number" }
        val d = p.content.toDoubleOrNull() ?: error("Invalid number")
        require(
            d.isFinite() &&
                d % 1.0 == 0.0 &&
                d >= Long.MIN_VALUE.toDouble() &&
                d <= Long.MAX_VALUE.toDouble()
        ) {
            "Expected integral number"
        }
        return d.toLong()
    }

    private fun long(o: JsonObject, k: String, default: Long? = null) =
        o[k]?.let(::longValue) ?: default ?: error("Missing $k")

    private fun longNullable(o: JsonObject, k: String) =
        o[k]?.takeUnless { it is JsonNull }?.let(::longValue)

    private fun intNullable(o: JsonObject, k: String) =
        longNullable(o, k)?.also { require(it in Int.MIN_VALUE..Int.MAX_VALUE) }?.toInt()

    private fun bool(o: JsonObject, k: String, d: Boolean) =
        o[k]?.let { (it as? JsonPrimitive)?.booleanOrNull ?: error("Invalid $k") } ?: d

    private fun boolNullable(o: JsonObject, k: String) =
        o[k]
            ?.takeUnless { it is JsonNull }
            ?.let { (it as? JsonPrimitive)?.booleanOrNull ?: error("Invalid $k") }

    private fun str(o: JsonObject, k: String) =
        ((o[k] as? JsonPrimitive)?.takeIf { it.isString }?.content)
            ?: error("Missing or invalid $k")

    private fun nullableString(o: JsonObject, k: String) =
        o[k]
            ?.takeUnless { it is JsonNull }
            ?.let {
                (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.content ?: error("Invalid $k")
            }

    private fun hash(s: String): Long {
        var h = -3750763034362895579L
        for (b in s.encodeToByteArray()) {
            h = (h xor (b.toLong() and 255)) * 1099511628211L
        }
        return (h and MAX_SAFE).coerceAtLeast(1)
    }

    private fun unsafeDownload(s: MutableSnapshot, k: Int, id: Long): Boolean {
        fun active(chapter: Long) =
            s.downloadByChapter[chapter].any {
                s.downloads[it].let { d -> d.isStartDownload == true && d.isDownload != true }
            }
        return when (k) {
            SyncPaths.KIND_MANGA -> s.chapterByManga[id].any { active(s.chapters[it].id) }
            SyncPaths.KIND_CHAPTER -> active(id)
            else -> false
        }
    }

    private fun remoteLocal(k: Int, id: Long) = ownerForRemote(k, id)?.first?.toLong()

    private fun MutableSnapshot.delete(k: Int, id: Long) {
        val chapterRows = if (k == SyncPaths.KIND_MANGA) chapterByManga[id] else emptyList()
        val affectedChapters =
            when (k) {
                SyncPaths.KIND_MANGA -> chapterRows.mapTo(linkedSetOf()) { chapters[it].id }
                SyncPaths.KIND_CHAPTER -> setOf(id)
                else -> emptySet()
            }
        affectedChapters.forEach { c ->
            downloadByChapter[c].forEach { removedDownloads += downloads[it].id }
        }
        when (k) {
            SyncPaths.KIND_CATEGORY -> {
                categories.killId(id)
                mangas.liveIndices().forEach { i ->
                    val m = mangas[i]
                    mangas[i] = m.copy(categories = m.categories?.filterNot { it == id })
                }
            }
            SyncPaths.KIND_MANGA -> {
                val cs = affectedChapters
                cs.forEach { rotate(SyncPaths.KIND_CHAPTER, it) }
                trackByManga[id].forEach { rotate(SyncPaths.KIND_TRACK, tracks[it].id) }
                historyByManga[id].forEach { rotate(SyncPaths.KIND_HISTORY, histories[it].id) }
                updateByManga[id].forEach { rotate(SyncPaths.KIND_UPDATE, updates[it].id) }
                mangas.killId(id)
                chapterRows.forEach(chapters::kill)
                (cs.flatMap { historyByChapter[it] } + historyByManga[id]).forEach(histories::kill)
                trackByManga[id].forEach(tracks::kill)
                updateByManga[id].forEach(updates::kill)
                cs.forEach { c ->
                    downloadByChapter[c].forEach(downloads::kill)
                    pageCacheByChapter[c].forEach(pageCache::kill)
                }
                removedMangas += id
                removedChapters += cs
                settingsDirty = true
            }
            SyncPaths.KIND_CHAPTER -> {
                historyByChapter[id].forEach { rotate(SyncPaths.KIND_HISTORY, histories[it].id) }
                chapters.killId(id)
                historyByChapter[id].forEach(histories::kill)
                updateByChapter[id].forEach { i -> updates[i] = updates[i].copy(chapterId = null) }
                downloadByChapter[id].forEach(downloads::kill)
                pageCacheByChapter[id].forEach(pageCache::kill)
                removedChapters += id
                settingsDirty = true
            }
            SyncPaths.KIND_TRACK -> tracks.killId(id)
            SyncPaths.KIND_HISTORY -> histories.killId(id)
            SyncPaths.KIND_UPDATE -> updates.killId(id)
        }
    }

    private fun ownerForRemote(kind: Int, remote: Long): Pair<String, Binding>? {
        val ks = kind.toString()
        val local = owners[ks]?.get(remote) ?: return null
        return local to bindings.getValue(ks).getValue(local)
    }

    private fun validateOwnership(entries: Map<String, Binding>) {
        val owner = mutableMapOf<Long, String>()
        entries.forEach { (local, b) ->
            (listOf(b.canonical) + b.aliases).forEach { id ->
                val old = owner.put(id, local)
                require(old == null || old == local) { "Remote mapping id collision" }
            }
        }
    }

    private fun validatePage(page: MangayomiPage) {
        for (k in SyncPaths.KIND_CATEGORY..SyncPaths.KIND_UPDATE) {
            val field = wireKey(k)
            val raw = page.data[field] ?: continue
            val array = raw as? JsonArray ?: error("Invalid $field array")
            array.forEach { element ->
                val row = element as? JsonObject ?: error("Invalid $field row")
                safeId(row["clientId"])
                long(row, "updatedAt")
                fun requiredString(key: String) {
                    str(row, key)
                }
                fun requiredId(key: String) {
                    safeId(row[key])
                }
                fun nullableStringField(key: String) {
                    nullableString(row, key)
                }
                fun nullableBool(key: String) {
                    boolNullable(row, key)
                }
                fun nullableNumber(key: String) {
                    longNullable(row, key)
                }
                when (k) {
                    SyncPaths.KIND_CATEGORY -> {
                        requiredString("name")
                        itemType(row, "forItemType")
                        intNullable(row, "pos")
                        nullableBool("hide")
                        nullableBool("shouldUpdate")
                    }
                    SyncPaths.KIND_MANGA -> {
                        itemType(row, "itemType")
                        nullableStringField("source")
                        nullableStringField("link")
                        nullableStringField("name")
                        nullableStringField("imageUrl")
                        nullableStringField("description")
                        nullableStringField("author")
                        nullableStringField("artist")
                        nullableStringField("lang")
                        nullableStringField("customCoverFromTracker")
                        nullableNumber("sourceId")
                        nullableNumber("lastUpdate")
                        nullableNumber("dateAdded")
                        nullableNumber("lastRead")
                        intNullable(row, "smartUpdateDays")
                        status(row)
                        row["favorite"]?.let { bool(row, "favorite", false) }
                        row["isLocalArchive"]?.let { bool(row, "isLocalArchive", false) }
                        row["genre"]?.let { v ->
                            (v as? JsonArray ?: error("Invalid genre array")).forEach {
                                require((it as? JsonPrimitive)?.isString == true) {
                                    "Invalid genre"
                                }
                            }
                        }
                        row["categoryClientIds"]?.let { v ->
                            (v as? JsonArray ?: error("Invalid categoryClientIds")).forEach(
                                ::safeId
                            )
                        }
                    }
                    SyncPaths.KIND_CHAPTER -> {
                        requiredId("mangaClientId")
                        nullableStringField("name")
                        nullableStringField("url")
                        nullableStringField("scanlator")
                        nullableStringField("thumbnailUrl")
                        nullableStringField("description")
                        nullableStringField("lastPageRead")
                        nullableNumber("dateUpload")
                        nullableNumber("downloadSize")
                        nullableNumber("duration")
                        nullableBool("isFiller")
                        nullableBool("isRead")
                        nullableBool("isBookmarked")
                    }
                    SyncPaths.KIND_TRACK -> {
                        requiredId("mangaClientId")
                        itemType(row, "itemType")
                        trackStatus(row)
                        nullableNumber("syncId")
                        nullableNumber("mediaId")
                        nullableNumber("libraryId")
                        nullableStringField("title")
                        intNumberNullable(row, "lastChapterRead")
                        intNullable(row, "totalChapter")
                        intNumberNullable(row, "score")
                        nullableNumber("startedReadingDate")
                        nullableNumber("finishedReadingDate")
                        nullableStringField("trackingUrl")
                    }
                    SyncPaths.KIND_HISTORY -> {
                        requiredId("mangaClientId")
                        requiredId("chapterClientId")
                        itemType(row, "itemType")
                        nullableNumber("date")
                        intNullable(row, "readingTimeSeconds")
                    }
                    SyncPaths.KIND_UPDATE -> {
                        requiredId("mangaClientId")
                        nullableStringField("chapterName")
                        nullableNumber("date")
                    }
                }
            }
        }
        validateRemapFields(page.data)
        (page.data["tombstones"] ?: page.data["deleted"])?.let { raw ->
            val obj = raw as? JsonObject ?: error("Invalid tombstones")
            obj.forEach { (key, ids) ->
                require(kindForKey(key) != null)
                (ids as? JsonArray ?: error("Invalid tombstones array")).forEach(::safeId)
            }
        }
    }

    private fun intNumberNullable(o: JsonObject, k: String): Int? =
        o[k]
            ?.takeUnless { it is JsonNull }
            ?.let {
                val p = it as? JsonPrimitive ?: error("Unsupported $k value")
                require(!p.isString) { "Unsupported $k value" }
                val d = p.content.toDoubleOrNull() ?: error("Unsupported $k value")
                require(
                    d.isFinite() && d % 1.0 == 0.0 && d >= Int.MIN_VALUE && d <= Int.MAX_VALUE
                ) {
                    "Unsupported fractional/out-of-range $k"
                }
                d.toInt()
            }

    private fun resolveReference(
        s: MutableSnapshot,
        k: Int,
        remote: Long,
        maps: Map<Int, Map<Long, Long>>,
    ): Long? {
        val local =
            maps[k]?.get(remote) ?: ownerForRemote(k, remote)?.first?.toLong() ?: return null
        return if (hasLocalEntity(s, k, local)) local else null
    }

    private fun newLocalIdentity(s: MutableSnapshot, k: Int): Long {
        val table = s.table(k)
        val bound = bindings[k.toString()]
        var id = SyncIds.random()
        while (table.has(id) || bound?.containsKey(id.toString()) == true) id = SyncIds.random()
        return id
    }

    private fun hasLocalEntity(s: MutableSnapshot, k: Int, id: Long) = s.table(k).has(id)

    private fun rowParentPendingDelete(
        s: MutableSnapshot,
        k: Int,
        row: JsonObject,
        maps: Map<Int, Map<Long, Long>>,
        pending: Map<Int, Set<Long>>,
    ): Boolean {
        fun local(kind: Int, key: String): Long? {
            val remote = row[key]?.let(::safeId) ?: return null
            return maps[kind]?.get(remote) ?: ownerForRemote(kind, remote)?.first?.toLong()
        }
        val parent =
            if (k in SyncPaths.KIND_CHAPTER..SyncPaths.KIND_UPDATE)
                local(SyncPaths.KIND_MANGA, "mangaClientId")
            else null
        if (
            parent != null &&
                parent in pending[SyncPaths.KIND_MANGA].orEmpty() &&
                !hasLocalEntity(s, SyncPaths.KIND_MANGA, parent)
        ) {
            return true
        }
        val chapter =
            if (k == SyncPaths.KIND_HISTORY) local(SyncPaths.KIND_CHAPTER, "chapterClientId")
            else null
        return chapter != null &&
            chapter in pending[SyncPaths.KIND_CHAPTER].orEmpty() &&
            !hasLocalEntity(s, SyncPaths.KIND_CHAPTER, chapter)
    }

    private fun deletionRecord(part: DbChangedPart): Pair<Int, Long>? =
        runCatching {
                val o = json.parseToJsonElement(part.data).jsonObject
                if (
                    o["provider"]?.jsonPrimitive?.content != "mangayomi" ||
                        o["namespace"]?.jsonPrimitive?.content != namespaceKey
                )
                    return null
                val kind = o["kind"]?.jsonPrimitive?.int ?: return null
                val localPrimitive = o["localId"] as? JsonPrimitive ?: return null
                require(localPrimitive.isString)
                val local = localPrimitive.content.toLongOrNull() ?: return null
                if (kind !in SyncPaths.KIND_CATEGORY..SyncPaths.KIND_UPDATE || local <= 0)
                    return null
                kind to local
            }
            .getOrNull()

    private fun enabled(kind: Int, p: DbSyncPreference) =
        when (kind) {
            SyncPaths.KIND_HISTORY -> p.syncHistories
            SyncPaths.KIND_UPDATE -> p.syncUpdates
            else -> true
        }

    private fun validateUploadDependencies(s: YokanDatabaseSnapshot, rows: Map<Int, Set<Long>>) {
        val mangas = s.mangas.associateBy { it.id }
        val chapters = s.chapters.associateBy { it.id }
        val cats = s.categories.associateBy { it.id }
        s.chapters
            .filter { it.id in rows[SyncPaths.KIND_CHAPTER].orEmpty() }
            .forEach {
                require(it.mangaId != null && mangas.containsKey(it.mangaId)) {
                    "Unresolved local chapter manga"
                }
            }
        s.tracks
            .filter { it.id in rows[SyncPaths.KIND_TRACK].orEmpty() }
            .forEach {
                require(it.mangaId != null && mangas.containsKey(it.mangaId)) {
                    "Unresolved local track manga"
                }
            }
        s.histories
            .filter { it.id in rows[SyncPaths.KIND_HISTORY].orEmpty() }
            .forEach {
                require(
                    it.mangaId != null &&
                        mangas.containsKey(it.mangaId) &&
                        it.chapterId != null &&
                        chapters[it.chapterId]?.mangaId == it.mangaId
                ) {
                    "Unresolved local history reference"
                }
            }
        s.updates
            .filter { it.id in rows[SyncPaths.KIND_UPDATE].orEmpty() }
            .forEach {
                require(it.mangaId != null && mangas.containsKey(it.mangaId)) {
                    "Unresolved local update manga"
                }
            }
        s.mangas
            .filter { it.id in rows[SyncPaths.KIND_MANGA].orEmpty() }
            .flatMap { it.categories.orEmpty() }
            .forEach { require(cats.containsKey(it)) { "Unresolved local category membership" } }
    }

    private fun normalizeServer(value: String): String {
        val s = value.trim().trimEnd('/')
        val match = Regex("^([A-Za-z][A-Za-z0-9+.-]*://)([^/]+)(.*)$").matchEntire(s) ?: return s
        return match.groupValues[1].lowercase() +
            match.groupValues[2].lowercase() +
            match.groupValues[3]
    }

    private fun validateRemapFields(data: JsonObject) {
        listOf("mangaClientIdRemap", "chapterClientIdRemap").forEach { key ->
            data[key]?.let { raw ->
                (raw as? JsonObject ?: error("Invalid $key")).forEach { (from, to) ->
                    val id = from.toLongOrNull() ?: error("Invalid remap id")
                    require(id in 1..MAX_SAFE)
                    safeId(to)
                }
            }
        }
    }

    /**
     * A list with an id index and lazily built secondary indexes. Deletes are tombstoned until
     * [live], so positions stay stable.
     */
    private class Table<T>(initial: List<T>, private val idOf: (T) -> Long?) {
        private val rows = initial.toMutableList()
        private val dead = HashSet<Int>()
        private val byId =
            HashMap<Long, Int>().also { m ->
                rows.forEachIndexed { i, x -> idOf(x)?.let { m.getOrPut(it) { i } } }
            }
        private val indexes = ArrayList<Index>()

        // Buckets are a superset (a replaced row keeps its old bucket entry), so lookups re-check
        // liveness and the key.
        inner class Index(val keyOf: (T) -> Any?) {
            var buckets: HashMap<Any?, MutableList<Int>>? = null

            operator fun get(key: Any?): List<Int> {
                val b =
                    buckets
                        ?: HashMap<Any?, MutableList<Int>>().also { b ->
                            rows.indices.forEach { i ->
                                if (i !in dead) b.getOrPut(keyOf(rows[i])) { ArrayList(1) } += i
                            }
                            buckets = b
                        }
                return b[key].orEmpty().filter { it !in dead && keyOf(rows[it]) == key }.distinct()
            }

            fun note(i: Int) {
                buckets?.getOrPut(keyOf(rows[i])) { ArrayList(1) }?.add(i)
            }
        }

        fun index(keyOf: (T) -> Any?) = Index(keyOf).also { indexes += it }

        operator fun get(i: Int) = rows[i]

        fun getOrNull(i: Int) = rows.getOrNull(i)

        fun indexOf(id: Long) = byId[id] ?: -1

        fun has(id: Long) = id in byId

        fun row(id: Long) = byId[id]?.let { rows[it] }

        operator fun plusAssign(x: T) {
            rows += x
            val i = rows.lastIndex
            idOf(x)?.let { byId.getOrPut(it) { i } }
            indexes.forEach { it.note(i) }
        }

        operator fun set(i: Int, x: T) {
            val old = rows[i]
            rows[i] = x
            indexes.forEach { if (it.keyOf(old) != it.keyOf(x)) it.note(i) }
        }

        fun kill(i: Int) {
            if (dead.add(i)) idOf(rows[i])?.let { if (byId[it] == i) byId.remove(it) }
        }

        fun killId(id: Long) {
            byId[id]?.let(::kill)
        }

        fun liveIndices() = rows.indices.filter { it !in dead }

        fun live(): List<T> =
            if (dead.isEmpty()) rows else rows.filterIndexed { i, _ -> i !in dead }
    }

    private class MutableSnapshot(private val original: YokanDatabaseSnapshot) {
        val categories = Table(original.categories) { it.id }
        val mangas = Table(original.mangas) { it.id }
        val chapters = Table(original.chapters) { it.id }
        val tracks = Table(original.tracks) { it.id }
        val histories = Table(original.histories) { it.id }
        val updates = Table(original.updates) { it.id }
        val downloads = Table(original.downloads) { it.id }
        val pageCache = Table<DbChapterPageUrls>(original.pageCache) { null }
        val mangaNatural = mangas.index { Triple(it.link, it.source, it.itemType) }
        val chapterByManga = chapters.index { it.mangaId }
        val chapterByUrl = chapters.index { it.mangaId to it.url }
        val chapterByName = chapters.index { it.mangaId to it.name }
        val trackByManga = tracks.index { it.mangaId }
        val trackBySync = tracks.index { it.mangaId to it.syncId }
        val historyByManga = histories.index { it.mangaId }
        val historyByChapter = histories.index { it.chapterId }
        val updateByManga = updates.index { it.mangaId }
        val updateByChapter = updates.index { it.chapterId }
        val updateByName = updates.index { it.mangaId to it.chapterName }
        val downloadByChapter = downloads.index { it.chapterId }
        val pageCacheByChapter = pageCache.index { it.chapterId }
        // Settings cleanup only drops entries by id, so one pass over the accumulated ids in
        // build() equals a pass per delete.
        var settingsDirty = false
        val removedDownloads = HashSet<Long>()
        val removedMangas = HashSet<Long?>()
        val removedChapters = HashSet<Long?>()

        fun table(k: Int): Table<*> =
            when (k) {
                SyncPaths.KIND_CATEGORY -> categories
                SyncPaths.KIND_MANGA -> mangas
                SyncPaths.KIND_CHAPTER -> chapters
                SyncPaths.KIND_TRACK -> tracks
                SyncPaths.KIND_HISTORY -> histories
                else -> updates
            }

        fun build(): YokanDatabaseSnapshot {
            val st = original.settings
            val settings =
                if (!settingsDirty) st
                else
                    st.copy(
                        downloadQueueOrder =
                            st.downloadQueueOrder.filterNot { it in removedDownloads },
                        sortChapterList =
                            st.sortChapterList?.filterNot { it.mangaId in removedMangas },
                        chapterFilterDownloadedList =
                            st.chapterFilterDownloadedList?.filterNot {
                                it.mangaId in removedMangas
                            },
                        chapterFilterUnreadList =
                            st.chapterFilterUnreadList?.filterNot { it.mangaId in removedMangas },
                        chapterFilterBookmarkedList =
                            st.chapterFilterBookmarkedList?.filterNot {
                                it.mangaId in removedMangas
                            },
                        personalReaderModeList =
                            st.personalReaderModeList?.filterNot { it.mangaId in removedMangas },
                        personalPageModeList =
                            st.personalPageModeList?.filterNot { it.mangaId in removedMangas },
                        filterScanlatorList =
                            st.filterScanlatorList?.filterNot { it.mangaId in removedMangas },
                        autoScrollPages =
                            st.autoScrollPages?.filterNot { it.mangaId in removedMangas },
                        titleMetadata = st.titleMetadata?.filterNot { it.mangaId in removedMangas },
                        chapterPageIndexList =
                            st.chapterPageIndexList?.filterNot { it.chapterId in removedChapters },
                    )
            return original.copy(
                settings = settings,
                mangas = mangas.live(),
                chapters = chapters.live(),
                categories = categories.live(),
                histories = histories.live(),
                updates = updates.live(),
                tracks = tracks.live(),
                downloads = downloads.live(),
                pageCache = pageCache.live(),
            )
        }
    }

    companion object {
        private const val MAX_SAFE = 9_007_199_254_740_991L

        /**
         * String `.max()` limits per entity from the server's zod schemas; keep in step with
         * lib/validation/sync.ts.
         */
        private val SERVER_STRING_LIMITS: Map<Int, Map<String, Int>> =
            mapOf(
                SyncPaths.KIND_CATEGORY to mapOf("name" to 200),
                SyncPaths.KIND_MANGA to
                    mapOf(
                        "source" to 200,
                        "link" to 2000,
                        "name" to 500,
                        "imageUrl" to 2000,
                        "description" to 10_000,
                        "author" to 500,
                        "artist" to 500,
                        "lang" to 20,
                        "customCoverFromTracker" to 2000,
                    ),
                SyncPaths.KIND_CHAPTER to
                    mapOf(
                        "name" to 500,
                        "url" to 2000,
                        "scanlator" to 200,
                        "thumbnailUrl" to 2000,
                        "description" to 5000,
                        "lastPageRead" to 50,
                    ),
                SyncPaths.KIND_TRACK to mapOf("title" to 500, "trackingUrl" to 2000),
                SyncPaths.KIND_HISTORY to emptyMap(),
                SyncPaths.KIND_UPDATE to mapOf("chapterName" to 500),
            )
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.kt).

The implementation below defines `mangayomiOAuthRedirectUri`.

The source describes its contract as:

> Loopback redirect for Mangayomi OAuth; the server only accepts `mangayomi:` or http loopback redirects. Mobile WebViews intercept it before loading, so nothing listens there. JavaFX follows redirects internally without exposing them, so desktop serves a real one-page loopback listener the in-app browser loads.

```kotlin
package eu.friedcutlet.yokan.services.sync

/**
 * Loopback redirect for Mangayomi OAuth; the server only accepts `mangayomi:` or http loopback redirects.
 * Mobile WebViews intercept it before loading, so nothing listens there. JavaFX follows redirects internally
 * without exposing them, so desktop serves a real one-page loopback listener the in-app browser loads.
 */
internal expect fun mangayomiOAuthRedirectUri(): String
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncService.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncService.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncService.kt).

The implementation below defines `MangayomiSyncService`, `PendingOAuth`, `login`, `beginBrowserLogin`, `completeBrowserLogin`, `field`, `cancelBrowserLogin`, `commitLogin`, `logout`, `sync` and 21 further declarations.

The source describes its contract as:

> Mangayomi's cookie-authenticated `/api/sync/v1`; deliberately independent of yokan-hub.

Cross-chapter imports used by this file: [`DbChangedPart`](../chapters/02-domain-and-settings-models.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`SnapshotReplacementConflictException`](../chapters/03-persistence-and-migrations.md), [`SyncServerProvider`](../chapters/02-domain-and-settings-models.md), [`YokanDatabase`](../chapters/03-persistence-and-migrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbChangedPart
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.SnapshotReplacementConflictException
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.sync.normalizeMangayomiServer
import eu.friedcutlet.yokan.util.sha256
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.header
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.util.PlatformLock
import dev.whyoleg.cryptography.DelicateCryptographyApi
import dev.whyoleg.cryptography.random.CryptographyRandom
import io.ktor.http.URLBuilder
import io.ktor.http.Url
import io.ktor.http.parseQueryString
import kotlin.io.encoding.Base64
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

/** Mangayomi's cookie-authenticated `/api/sync/v1`; deliberately independent of yokan-hub. */
class MangayomiSyncService(
    private val database: YokanDatabase,
    private val http: HttpService,
    private val operationMonitor: SyncOperationMonitor = SyncOperationMonitor(),
    private val leases: SyncAccountLeases = SyncAccountLeases.None,
) : SyncService {
    override val operationState = operationMonitor.state
    private val json = Json { ignoreUnknownKeys = true; explicitNulls = false }
    private val operationMutex = Mutex()
    private var operationSessionToken: String? = null
    private val oauthLock = PlatformLock()
    private val oauthAttempts = mutableMapOf<Long, PendingOAuth>()

    private class PendingOAuth(val attempt: BrowserLoginAttempt, val verifier: String, val prior: DbSyncPreference?)

    override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult = operationMutex.withLock {
        oauthLock.withLock { oauthAttempts.remove(syncId) }
        val prior = preference(syncId)
        val base = validBase(server) ?: return@withLock SyncLoginResult(false, "Enter a valid Mangayomi server URL.")
        val response = try {
            http.request(HttpRequest("$base/api/login", "POST", mapOf("Content-Type" to "application/json"),
                json.encodeToString(JsonObject.serializer(), buildJsonObject {
                    put("email", JsonPrimitive(email.trim())); put("password", JsonPrimitive(password)); put("stayLoggedIn", JsonPrimitive(true))
                })))
        } catch (cancelled: CancellationException) { throw cancelled }
        catch (_: Exception) { return@withLock SyncLoginResult(false, "Could not reach the Mangayomi server.") }
        when (response.statusCode) {
            401, 403 -> return@withLock SyncLoginResult(false, "Invalid username or password.")
            429 -> return@withLock SyncLoginResult(false, retryMessage("Login", response.headers))
            503 -> return@withLock SyncLoginResult(false, "Mangayomi server is unavailable.")
            !in 200..299 -> return@withLock SyncLoginResult(false, "Mangayomi server returned HTTP ${response.statusCode}.")
        }
        val body = runCatching { json.parseToJsonElement(response.body).jsonObject }.getOrNull()
            ?: return@withLock SyncLoginResult(false, "Mangayomi server returned an invalid login response.")
        if (body["requiresTotp"]?.jsonPrimitive?.content == "true") {
            return@withLock SyncLoginResult(false, "This account uses two-factor authentication; sign in in the browser instead.")
        }
        if (body["ok"]?.jsonPrimitive?.content != "true") return@withLock SyncLoginResult(false, "Mangayomi login failed.")
        val token = response.setCookies.firstNotNullOfOrNull { raw ->
            raw.substringBefore(';').trim().takeIf { it.startsWith("id=") }?.substringAfter("id=")?.takeIf(String::isNotBlank)
        } ?: return@withLock SyncLoginResult(false, "Mangayomi login response did not include a session cookie.")
        commitLogin(syncId, prior, base, email.trim(), token)
    }

    /**
     * Flutter's OAuth/PKCE sign-in, run in the in-app browser: the server's own login page handles passwords and
     * two-factor codes, then redirects to the loopback [mangayomiOAuthRedirectUri], which ends the flow.
     */
    @OptIn(DelicateCryptographyApi::class)
    override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? {
        val base = validBase(server) ?: return null
        val prior = preference(syncId)
        if (prior != null && prior.serverProvider != SyncServerProvider.Mangayomi) return null
        val verifier = base64Url(CryptographyRandom.Default.nextBytes(32))
        val state = base64Url(CryptographyRandom.Default.nextBytes(24))
        val redirect = mangayomiOAuthRedirectUri()
        val url = URLBuilder("$base/api/oauth/authorize").apply {
            parameters.append("redirect_uri", redirect)
            parameters.append("code_challenge", base64Url(sha256(verifier.encodeToByteArray())))
            parameters.append("code_challenge_method", "S256")
            parameters.append("state", state)
        }.build().toString()
        val attempt = BrowserLoginAttempt(syncId, base, url, device = "", state = state, callbackUrl = redirect)
        oauthLock.withLock { oauthAttempts[syncId] = PendingOAuth(attempt, verifier, prior) }
        return attempt
    }

    override suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult? {
        if (loadedUrl.length > MAX_CALLBACK_LENGTH || loadedUrl.any(Char::isISOControl) || '#' in loadedUrl ||
            loadedUrl.substringBefore('?') != attempt.callbackUrl || '?' !in loadedUrl
        ) return null
        // One use: a replayed or late callback for this attempt is ignored.
        val pending = oauthLock.withLock {
            oauthAttempts[attempt.syncId]?.takeIf { it.attempt === attempt }?.also { oauthAttempts.remove(attempt.syncId) }
        } ?: return null
        val params = parseQueryString(loadedUrl.substringAfter('?'))
        if (params["error"] != null) return SyncLoginResult(false, "Mangayomi sign-in was not completed.")
        val code = params.getAll("code")?.singleOrNull()?.takeIf { it.isNotBlank() && it.length <= 256 }
        if (code == null || params.getAll("state")?.singleOrNull() != attempt.state) {
            return SyncLoginResult(false, "Mangayomi sign-in response did not match this attempt; try again.")
        }
        return operationMutex.withLock {
            val response = http.requestOrNull(HttpRequest("${attempt.server}/api/oauth/token", "POST", mapOf("Content-Type" to "application/json"),
                json.encodeToString(JsonObject.serializer(), buildJsonObject {
                    put("code", JsonPrimitive(code)); put("codeVerifier", JsonPrimitive(pending.verifier))
                    put("redirectUri", JsonPrimitive(attempt.callbackUrl)) // the server requires the authorize-time value verbatim
                }))) ?: return@withLock SyncLoginResult(false, "Could not reach the Mangayomi server.")
            when (response.statusCode) {
                400 -> return@withLock SyncLoginResult(false, "Mangayomi sign-in expired; try again.")
                429 -> return@withLock SyncLoginResult(false, retryMessage("Sign-in", response.headers))
                503 -> return@withLock SyncLoginResult(false, "Mangayomi server is unavailable.")
                !in 200..299 -> return@withLock SyncLoginResult(false, "Mangayomi server returned HTTP ${response.statusCode}.")
            }
            val body = runCatching { json.parseToJsonElement(response.body).jsonObject }.getOrNull()
            fun field(name: String) = (body?.get(name) as? JsonPrimitive)?.takeIf { it.isString }?.content?.trim()?.takeIf(String::isNotEmpty)
            val token = field("access_token")
            val username = field("username")
            if (token == null || username == null) return@withLock SyncLoginResult(false, "Mangayomi server returned an invalid sign-in response.")
            commitLogin(attempt.syncId, pending.prior, attempt.server, username, token)
        }
    }

    override fun cancelBrowserLogin(attempt: BrowserLoginAttempt) {
        oauthLock.withLock { if (oauthAttempts[attempt.syncId]?.attempt === attempt) oauthAttempts.remove(attempt.syncId) }
    }

    /** Commits only if the preference is still what it was when sign-in began, so a stale login can't overwrite a newer setup. */
    private suspend fun commitLogin(syncId: Long, prior: DbSyncPreference?, base: String, username: String, token: String): SyncLoginResult {
        currentCoroutineContext().ensureActive()
        val next = DbSyncPreference(server = base, email = username, authToken = token, serverProvider = SyncServerProvider.Mangayomi)
        val failure = leases.commitClaimed(prior, next) {
            database.upsertSyncPreferenceIf(
                syncId = syncId,
                accepts = { current -> current == prior && (current == null || current.serverProvider == SyncServerProvider.Mangayomi) },
                transform = { current ->
                    (current ?: DbSyncPreference(syncId = syncId)).copy(
                        server = base, email = username, authToken = token, syncOn = true,
                        serverProvider = SyncServerProvider.Mangayomi, lastSyncManga = null, lastSyncHistory = null,
                        lastSyncUpdate = null, hubHead = 0, hubEpoch = 0, hubRecoveryPending = false,
                        hubBootstrapComplete = false, hubHlc = 0,
                    )
                },
            )
        }
        if (failure != null) return SyncLoginResult(false, failure)
        return SyncLoginResult(true, "Logged in to Mangayomi server.")
    }

    override suspend fun logout(syncId: Long) = operationMutex.withLock {
        val pref = preference(syncId) ?: return@withLock
        val base = pref.server?.let(::validBase)
        val token = pref.authToken
        database.upsertSyncPreference(pref.copy(authToken = null, syncOn = false)) // Keep namespace mappings for this account.
        leases.releaseQuietly(pref)
        if (base != null && !token.isNullOrBlank()) try {
            http.request(HttpRequest("$base/api/logout", "POST", mapOf("Cookie" to "id=$token")))
        } catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { /* local logout wins */ }
    }

    override suspend fun sync(syncId: Long, settings: DbSettings) = runOperation(SyncOperationStage.Syncing, syncId, push = true, pull = true)
    override suspend fun pushChanges(syncId: Long) = runOperation(SyncOperationStage.Uploading, syncId, push = true, pull = false)
    override suspend fun pullChanges(syncId: Long) = runOperation(SyncOperationStage.Downloading, syncId, push = false, pull = true)

    override fun status(syncId: Long): SyncConnectionStatus {
        val pref = preference(syncId)
        return SyncConnectionStatus(!pref?.authToken.isNullOrBlank(), pref?.email, pref?.server, pref?.lastSyncManga)
    }

    private suspend fun runOperation(stage: SyncOperationStage, syncId: Long, push: Boolean, pull: Boolean): SyncResult {
        val operationId = operationMonitor.begin(stage)
        var outcome = SyncOperationOutcome.Failed
        try {
            val result = operationMutex.withLock { perform(syncId, push, pull) }
            outcome = if (result.errors.isEmpty()) SyncOperationOutcome.Succeeded else SyncOperationOutcome.Failed
            return result
        } catch (cancelled: CancellationException) {
            outcome = SyncOperationOutcome.Cancelled
            throw cancelled
        } catch (error: Throwable) {
            AppLogger.warn("[sync] Mangayomi sync failed: ${error::class.simpleName}")
            return SyncResult(0, 0, false, listOf("Mangayomi sync failed."))
        } finally {
            operationMonitor.finish(operationId, outcome)
        }
    }

    private suspend fun perform(syncId: Long, push: Boolean, pull: Boolean): SyncResult {
        operationSessionToken = null
        val capturedPreference = preference(syncId) ?: return failed("No sync configuration.")
        if (capturedPreference.serverProvider != SyncServerProvider.Mangayomi) return failed("Mangayomi is not the selected sync provider.")
        val base = capturedPreference.server?.let(::validBase) ?: return failed("Invalid Mangayomi server URL.")
        val token = capturedPreference.authToken?.takeIf(String::isNotBlank) ?: return failed("Not logged in.")
        leases.claimFailure(capturedPreference)?.let { return failed(it) }
        val accountId = capturedPreference.email?.trim()?.takeIf(String::isNotBlank) ?: return failed("Mangayomi account name is missing.")
        val namespace = MangayomiNamespace(base, accountId)
        checkCaptured(syncId, capturedPreference, base, token)?.let { return failed(it) }
        val version = http.requestOrNull(HttpRequest("$base/api/version")) ?: return failed("Could not reach the Mangayomi server.")
        val versions = runCatching { json.parseToJsonElement(version.body).jsonObject["supported"] as? JsonArray }.getOrNull()
        if (version.statusCode !in 200..299 || versions?.any { it.jsonPrimitive.content == "1" } != true) {
            return failed("Server does not support Mangayomi sync protocol v1.")
        }

        // ponytail: since=0 full-state pull on each run; the server's timestamp cursor can miss late uploads.
        // Upgrade to incremental only when the server exposes a revision-safe cursor.
        var current = database.snapshot()
        var pref = current.syncPreferences.firstOrNull { it.syncId == syncId } ?: capturedPreference
        var mapper = MangayomiSyncMapper(pref.mangayomiIdMappings, namespace)

        // Pull before allocating IDs so remote identities and natural-key matches are adopted first.
        val bootstrap = pullAll(syncId, capturedPreference, base, token, mapper) ?: return failed(lastRequestError)
        // Upload-only must not apply tombstones, and merging them would also rotate the tombstoned row's wire ID.
        val bootstrapPages = if (pull) bootstrap else bootstrap.map { it.copy(data = JsonObject(it.data - "tombstones" - "deleted")) }
        val preBootstrapMappings = mapper.mappingsJson()
        val bootstrapped = mapper.merge(current, bootstrapPages, pref)
        var downloadedChanges = if (pull) bootstrapped.downloadedChanges else 0
        var uploadedChanges = 0
        current = if (pull) {
            persistMerge(current, bootstrapped, bootstrap, mapper, preBootstrapMappings, namespace, syncId, capturedPreference, base, token, emptySet())
                ?: return failed("Database changed while applying Mangayomi data; retry sync.")
        } else {
            // Bootstrap discovers identities/remaps only in upload-only mode; it must not restore remote rows or tombstones.
            persistMappings(current, syncId, mapper.mappingsJson(), capturedPreference, base, token)
                ?: return failed("Database changed while preparing Mangayomi IDs; retry sync.")
        }
        pref = current.syncPreferences.first { it.syncId == syncId }
        mapper = MangayomiSyncMapper(pref.mangayomiIdMappings, namespace)

        val acknowledgedDeletes = mutableSetOf<DbChangedPart>()
        if (push) {
            val batches = mapper.prepare(current, pref)
            // Persist ID reservations before any request; each batch is encoded using canonical IDs after prior remaps.
            current = persistMappings(current, syncId, mapper.mappingsJson(), capturedPreference, base, token)
                ?: return failed("Database changed while preparing Mangayomi IDs; retry sync.")
            acknowledgedDeletes += batches.flatMap { it.deletions }
            for (batch in batches) {
                val subBatches = splitForBodyLimit(current, batch, mapper) ?: return failed(lastRequestError)
                for (subBatch in subBatches) {
                    checkCaptured(syncId, capturedPreference, base, token)?.let { return failed(it) }
                    val requestData = mapper.encode(current, subBatch)
                    val uploadPages = sendBatch(syncId, capturedPreference, base, token, requestData, mapper) ?: return failed(lastRequestError)
                    uploadedChanges += subBatch.localIds.size + subBatch.deletions.size
                    uploadPages.forEach(mapper::acceptRemaps)
                    current = persistMappings(current, syncId, mapper.mappingsJson(), capturedPreference, base, token)
                        ?: return failed("Database changed while adopting Mangayomi IDs; retry sync.")
                }
            }
            if (!pull && acknowledgedDeletes.isNotEmpty()) {
                // An upload-only request can acknowledge only captured queue entries, never concurrent deletes.
                current = ackDeletes(current, acknowledgedDeletes, syncId, capturedPreference, base, token)
                    ?: return failed("Database changed while acknowledging Mangayomi deletions; retry sync.")
            }
        }

        if (pull) {
            val pages = pullAll(syncId, capturedPreference, base, token, mapper) ?: return failed(lastRequestError)
            val prePullMappings = mapper.mappingsJson()
            val merge = mapper.merge(current, pages, current.syncPreferences.first { it.syncId == syncId })
            downloadedChanges += merge.downloadedChanges
            current = persistMerge(current, merge, pages, mapper, prePullMappings, namespace, syncId, capturedPreference, base, token, acknowledgedDeletes)
                ?: return failed("Database changed while applying Mangayomi sync; retry sync.")
            val now = pages.lastOrNull()?.syncedAt ?: return failed("Mangayomi sync did not complete.")
            val p = current.syncPreferences.first { it.syncId == syncId }
            val resultWithWatermark = current.copy(syncPreferences = current.syncPreferences.map {
                if (it.syncId == syncId) it.copy(lastSyncManga = now, lastSyncHistory = if (it.syncHistories) now else it.lastSyncHistory,
                    lastSyncUpdate = if (it.syncUpdates) now else it.lastSyncUpdate) else it
            })
            current = persistSnapshot(current, resultWithWatermark, syncId, capturedPreference, base, token)
                ?: return failed("Database changed before Mangayomi sync completed; retry sync.")
            if (p.syncSettings) AppLogger.warn("[sync] Mangayomi settings sync is not supported; local settings were preserved")
            return SyncResult(uploadedChanges, downloadedChanges, settingsSynced = false)
        }
        if (pref.syncSettings) AppLogger.warn("[sync] Mangayomi settings sync is not supported; local settings were preserved")
        return SyncResult(uploadedChanges, downloadedChanges, false)
    }

    private var lastRequestError: String = "Mangayomi request failed."

    private suspend fun pullAll(syncId: Long, captured: DbSyncPreference, base: String, token: String, mapper: MangayomiSyncMapper): List<MangayomiPage>? =
        transferPages(syncId, captured, base, token, null, mapper)

    private suspend fun sendBatch(syncId: Long, captured: DbSyncPreference, base: String, token: String, data: JsonObject, mapper: MangayomiSyncMapper): List<MangayomiPage>? =
        transferPages(syncId, captured, base, token, data, mapper, drainPages = false)

    private fun splitForBodyLimit(snapshot: eu.friedcutlet.yokan.database.YokanDatabaseSnapshot, batch: MangayomiBatch, mapper: MangayomiSyncMapper): List<MangayomiBatch>? {
        val pending = ArrayDeque<MangayomiBatch>()
        val result = mutableListOf<MangayomiBatch>()
        pending.addLast(batch)
        while (pending.isNotEmpty()) {
            val next = pending.removeFirst()
            val bytes = json.encodeToString(JsonObject.serializer(), mapper.encode(snapshot, next)).encodeToByteArray().size
            if (bytes <= MAX_BATCH_BYTES) {
                result += next
                continue
            }
            when {
                next.localIds.isNotEmpty() && next.deletions.isNotEmpty() -> {
                    pending.addFirst(next.copy(localIds = emptyList()))
                    pending.addFirst(next.copy(deletions = emptyList()))
                }
                next.localIds.size > 1 -> {
                    val mid = next.localIds.size / 2
                    pending.addFirst(next.copy(localIds = next.localIds.drop(mid), deletions = emptyList()))
                    pending.addFirst(next.copy(localIds = next.localIds.take(mid), deletions = emptyList()))
                }
                next.deletions.size > 1 -> {
                    val mid = next.deletions.size / 2
                    pending.addFirst(next.copy(localIds = emptyList(), deletions = next.deletions.drop(mid)))
                    pending.addFirst(next.copy(localIds = next.localIds, deletions = next.deletions.take(mid)))
                }
                else -> {
                    lastRequestError = "A Mangayomi sync record exceeds the server's request size limit."
                    return null
                }
            }
        }
        return result
    }

    private suspend fun transferPages(
        syncId: Long,
        captured: DbSyncPreference,
        base: String,
        token: String,
        initialData: JsonObject?,
        mapper: MangayomiSyncMapper,
        drainPages: Boolean = true,
    ): List<MangayomiPage>? {
        var cursors = emptyMap<String, String?>()
        var sessionToken: String? = operationSessionToken
        var nextData = initialData
        val pages = mutableListOf<MangayomiPage>()
        val seen = mutableSetOf<String>()
        repeat(MAX_PAGES) {
            checkCaptured(syncId, captured, base, token)?.let { lastRequestError = it; return null }
            val payload = buildJsonObject {
                put("since", JsonPrimitive(0))
                if (cursors.isNotEmpty()) put("cursors", buildJsonObject { cursors.forEach { (key, value) -> if (value != null) put(key, JsonPrimitive(value)) } })
                sessionToken?.let { put("sessionToken", JsonPrimitive(it)) }
                nextData?.forEach { (key, value) -> put(key, value) }
            }
            val response = http.requestOrNull(HttpRequest("$base/api/sync/v1", "POST", mapOf(
                "Content-Type" to "application/json", "Cookie" to "id=$token",
            ), json.encodeToString(JsonObject.serializer(), payload))) ?: run { lastRequestError = "Could not reach the Mangayomi server."; return null }
            if (response.statusCode == 401 || response.statusCode == 403) { lastRequestError = "Mangayomi session expired; log in again."; return null }
            if (response.statusCode == 429) { lastRequestError = retryMessage("Mangayomi sync", response.headers); return null }
            if (response.statusCode !in 200..299) { lastRequestError = "Mangayomi server returned HTTP ${response.statusCode}."; return null }
            val page = runCatching { mapper.decodePage(response.body) }.getOrNull()
                ?: run { lastRequestError = "Mangayomi server returned malformed sync data."; return null }
            pages += page
            sessionToken = page.sessionToken ?: sessionToken
            operationSessionToken = sessionToken
            cursors = (cursors.keys + page.cursors.keys).associateWith { key -> page.cursors[key] ?: cursors[key] }
            val fingerprint = cursors.entries.sortedBy { it.key }.joinToString("|") { "${it.key}=${it.value}" } + ":${page.hasMore}:${page.syncedAt}"
            if (page.hasMore && !seen.add(fingerprint)) { lastRequestError = "Mangayomi pagination made no progress."; return null }
            if (!drainPages) return listOf(page)
            nextData = null
            if (!page.hasMore) return deduplicatePages(pages)
        }
        lastRequestError = "Mangayomi sync exceeded the page limit."
        return null
    }

    private suspend fun persistMerge(
        expected: eu.friedcutlet.yokan.database.YokanDatabaseSnapshot,
        merge: MangayomiMerge,
        pages: List<MangayomiPage>,
        mapper: MangayomiSyncMapper,
        preMergeMappings: String,
        namespace: MangayomiNamespace,
        syncId: Long,
        captured: DbSyncPreference,
        base: String,
        token: String,
        ack: Set<DbChangedPart>,
    ): eu.friedcutlet.yokan.database.YokanDatabaseSnapshot? {
        var old = expected
        var latestMerge = merge
        var latestMapper = mapper
        repeat(3) {
            val changedParts = latestMerge.snapshot.changedParts.filterNot { it in ack }
            val candidate = latestMerge.snapshot.copy(
                changedParts = changedParts,
                syncPreferences = latestMerge.snapshot.syncPreferences.map {
                    if (it.syncId == syncId) it.copy(mangayomiIdMappings = latestMapper.mappingsJson()) else it
                },
            )
            persistSnapshot(old, candidate, syncId, captured, base, token)?.let { return it }
            old = database.snapshot()
            // merge() mutates mapper state (tombstone rotations); re-merging on the same mapper would skip tombstones.
            latestMapper = MangayomiSyncMapper(preMergeMappings, namespace)
            latestMerge = latestMapper.merge(old, pages, old.syncPreferences.firstOrNull { it.syncId == syncId } ?: captured)
        }
        return null
    }

    private suspend fun persistMappings(
        expected: eu.friedcutlet.yokan.database.YokanDatabaseSnapshot,
        syncId: Long,
        mappings: String,
        captured: DbSyncPreference,
        base: String,
        token: String,
    ): eu.friedcutlet.yokan.database.YokanDatabaseSnapshot? {
        var latest = expected
        repeat(5) {
            checkCaptured(syncId, captured, base, token)?.let { return null }
            val next = latest.copy(syncPreferences = latest.syncPreferences.map {
                if (it.syncId == syncId) it.copy(mangayomiIdMappings = mappings) else it
            })
            try {
                database.replaceAllRemoteAtomically(next, latest)
                return database.snapshot()
            } catch (_: SnapshotReplacementConflictException) {
                latest = database.snapshot()
            }
        }
        return null
    }

    private suspend fun ackDeletes(
        expected: eu.friedcutlet.yokan.database.YokanDatabaseSnapshot,
        changes: Set<DbChangedPart>, syncId: Long, captured: DbSyncPreference, base: String, token: String,
    ): eu.friedcutlet.yokan.database.YokanDatabaseSnapshot? = persistSnapshot(expected,
        expected.copy(changedParts = expected.changedParts.filterNot { it in changes }), syncId, captured, base, token)

    private suspend fun persistSnapshot(
        expected: eu.friedcutlet.yokan.database.YokanDatabaseSnapshot,
        next: eu.friedcutlet.yokan.database.YokanDatabaseSnapshot,
        syncId: Long, captured: DbSyncPreference, base: String, token: String,
    ): eu.friedcutlet.yokan.database.YokanDatabaseSnapshot? {
        checkCaptured(syncId, captured, base, token)?.let { return null }
        return try {
            database.replaceAllRemoteAtomically(next, expected)
            database.snapshot()
        } catch (_: SnapshotReplacementConflictException) { null }
    }

    private fun checkCaptured(syncId: Long, captured: DbSyncPreference, base: String, token: String): String? {
        val current = preference(syncId) ?: return "Sync configuration changed during the operation."
        return if (current.serverProvider != SyncServerProvider.Mangayomi || current.server?.let(::validBase) != base || current.authToken != token || current.email != captured.email)
            "Sync configuration changed during the operation." else null
    }

    private fun isMangayomiDelete(change: DbChangedPart, namespace: String): Boolean = runCatching {
        val data = json.parseToJsonElement(change.data).jsonObject
        data["provider"]?.jsonPrimitive?.content == "mangayomi" && data["namespace"]?.jsonPrimitive?.content == namespace
    }.getOrDefault(false)

    private fun deduplicatePages(pages: List<MangayomiPage>): List<MangayomiPage> {
        val entityKeys = setOf("categories", "manga", "chapters", "tracks", "histories", "updates")
        val seenDeletes = mutableMapOf<String, MutableSet<String>>()
        return pages.map { page ->
            val uniqueData = buildJsonObject {
                page.data.forEach { (key, value) ->
                    when {
                        key in entityKeys && value is JsonArray -> put(key, value)
                        (key == "tombstones" || key == "deleted") && value is JsonObject -> put(key, buildJsonObject {
                            value.forEach { (kind, ids) ->
                                if (ids is JsonArray) put(kind, JsonArray(ids.filter { seenDeletes.getOrPut(kind) { mutableSetOf() }.add(it.jsonPrimitive.content) }))
                                else put(kind, ids)
                            }
                        })
                        else -> put(key, value)
                    }
                }
            }
            page.copy(data = uniqueData)
        }
    }

    private fun retryMessage(action: String, headers: Map<String, String>): String {
        val seconds = headers.header("Retry-After")?.toLongOrNull()
        return if (seconds != null && seconds >= 0) "$action rate limited; retry after $seconds seconds." else "$action rate limited; try again later."
    }

    private fun preference(id: Long): DbSyncPreference? = database.syncPreferences().firstOrNull { it.syncId == id }
    private fun validBase(value: String): String? {
        val raw = normalizeMangayomiServer(value) ?: return null
        val url = runCatching { Url(raw) }.getOrNull() ?: return null
        if (url.protocol.name !in setOf("http", "https") || url.host.isBlank() || url.user != null || raw.contains('?') || raw.contains('#')) return null
        return raw
    }
    private fun failed(message: String) = SyncResult(0, 0, false, listOf(message))

    companion object {
        private const val MAX_PAGES = 10_000
        private const val MAX_BATCH_BYTES = 24 * 1024 * 1024
        private const val MAX_CALLBACK_LENGTH = 2048

        private fun base64Url(bytes: ByteArray) = Base64.UrlSafe.withPadding(Base64.PaddingOption.ABSENT).encode(bytes)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.desktop.kt
### Write `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.desktop.kt`

Create this path in your reconstruction project. Source set: **desktopMain**. [Exact file download](../reference/source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.desktop.kt).

The implementation below defines `mangayomiOAuthRedirectUri`.

The source describes its contract as:

> Serves one static "signed in" page so the JavaFX sign-in browser can finish loading the callback, which PlatformWebView then reports. The code travels in the URL the browser reports; requests here are ignored, and PKCE keeps a code seen by any other local process useless.

```kotlin
package eu.friedcutlet.yokan.services.sync

import java.net.InetAddress
import java.net.ServerSocket
import kotlin.concurrent.thread

/**
 * Serves one static "signed in" page so the JavaFX sign-in browser can finish loading the callback, which
 * PlatformWebView then reports. The code travels in the URL the browser reports; requests here are ignored,
 * and PKCE keeps a code seen by any other local process useless.
 */
private val loopbackRedirect: String by lazy {
    val server = ServerSocket(0, 16, InetAddress.getLoopbackAddress())
    thread(isDaemon = true, name = "mangayomi-oauth-loopback") {
        val page = "<!doctype html><meta charset=utf-8><title>Yokan</title><p>Signed in. Returning to Yokan…</p>".encodeToByteArray()
        while (true) {
            runCatching {
                server.accept().use { socket ->
                    socket.soTimeout = 5_000
                    val reader = socket.getInputStream().bufferedReader()
                    while (!reader.readLine().isNullOrEmpty()) {}
                    socket.getOutputStream().apply {
                        write(("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: ${page.size}\r\n" +
                            "Cache-Control: no-store\r\nConnection: close\r\n\r\n").encodeToByteArray())
                        write(page)
                        flush()
                    }
                }
            }
        }
    }
    "http://127.0.0.1:${server.localPort}/yokan/oauth-callback"
}

internal actual fun mangayomiOAuthRedirectUri(): String = loopbackRedirect
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/platformWebViewMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.platformWebView.kt
### Write `composeApp/src/platformWebViewMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.platformWebView.kt`

Create this path in your reconstruction project. Source set: **platformWebViewMain**. [Exact file download](../reference/source/composeApp/src/platformWebViewMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.platformWebView.kt).

The implementation below defines `mangayomiOAuthRedirectUri`.

```kotlin
package eu.friedcutlet.yokan.services.sync

internal actual fun mangayomiOAuthRedirectUri(): String = "http://127.0.0.1/yokan/oauth-callback"
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.wasm.kt
### Write `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.wasm.kt`

Create this path in your reconstruction project. Source set: **wasmJsMain**. [Exact file download](../reference/source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiOAuthRedirect.wasm.kt).

The implementation below defines `mangayomiOAuthRedirectUri`.

```kotlin
package eu.friedcutlet.yokan.services.sync

// Unused: the web build has no in-app browser, so browser sign-in is never offered there.
internal actual fun mangayomiOAuthRedirectUri(): String = "http://127.0.0.1/yokan/oauth-callback"
```
[chapter-file-end]: #

### Check your understanding

Apply an external chapter update to a locally renamed/manual-filler chapter. Verify imported source fields change while the specified local overrides and references survive.
[chapter-content-end]: #


## Step 5: distinguish cloud backups from state sync

CloudBackupSyncService and its GoogleDriveCloudStorageProvider transfer backup objects using backup privacy rules. GoogleDriveSyncService is a different whole-library state-sync protocol. Do not implement both buttons by calling the same upload function.

SyncYomi uses `GET /api/sync/content` with `X-API-Token`, accepts 404 as empty, requires ETag on existing data, merges Tachiyomi protobuf and PUTs raw protobuf with If-Match. On 412 restart the round, up to the source's three-pass limit. Upload-only still fetches current ETag; download-only never uploads. Remote absence/deletion does not delete local state. Novels and Yokan-only fields cannot travel in that format.

Google Drive state sync uses user-provided OAuth client configuration, authorization-code/PKCE, a single-use pasted redirect/code attempt, refresh token and transient access tokens. Recreate `yokan_sync.json.gz` in appDataFolder and a ten-minute `yokan_sync.lock` with device/expiry metadata. Settle simultaneous lock creation by the reference ordering, merge another device's file, upload via create/update and release the lock in non-cancellable cleanup. Browser uploads can be plain JSON under the same name; all readers accept supported forms. A private appDataFolder is scoped to its OAuth client, not shared with unrelated apps.

[chapter-content-start]: #
### Follow the code

Cloud backup transfers backup objects under exporter privacy rules; state sync merges a live library. SyncYomi first reads content/ETag, applies merge rules and conditionally PUTs raw protobuf; a 412 restarts the bounded round. Drive state sync owns PKCE/token attempts and its expiring lock/file protocol. Simultaneous locks need deterministic settlement, and release runs during non-cancellable cleanup. Keep provider lossiness explicit.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/CloudBackupSyncService.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/GoogleDriveCloudStorageProvider.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncYomiSyncService.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/GoogleDriveSyncService.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/CloudBackupSyncService.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/CloudBackupSyncService.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/CloudBackupSyncService.kt).

The implementation below defines `DefaultCloudBackupSyncService`, `providers`, `isCloudPreference`, `connect`, `login`, `logout`, `sync`, `pushChanges`, `pullChanges`, `status` and 21 further declarations.

The source describes its contract as:

> Sync by whole Yokan backups kept with a \[CloudStorageProvider\]; the newest remote backup wins.

Cross-chapter imports used by this file: [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`YokanDatabase`](../chapters/03-persistence-and-migrations.md), [`BackupFormat`](../chapters/20-backup-and-restore.md), [`BackupRestoreTargetChangedException`](../chapters/20-backup-and-restore.md), [`BackupOptions`](../chapters/20-backup-and-restore.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.backup.BackupFormat
import eu.friedcutlet.yokan.services.backup.BackupRestoreTargetChangedException
import eu.friedcutlet.yokan.services.backup.BackupOptions
import eu.friedcutlet.yokan.services.backup.BackupService
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive

internal const val CloudServerPrefix = "cloud://"
private const val CloudBackupPrefix = "yokan-cloud-backup-"

/** Sync by whole Yokan backups kept with a [CloudStorageProvider]; the newest remote backup wins. */
class DefaultCloudBackupSyncService(
    private val database: YokanDatabase,
    private val backup: BackupService,
    private val providers: List<CloudStorageProvider>,
    private val operationMonitor: SyncOperationMonitor = SyncOperationMonitor(),
    private val leases: SyncAccountLeases = SyncAccountLeases.None,
) : CloudBackupSyncService {
    override val operationState = operationMonitor.state
    override fun providers(): List<CloudProviderDescriptor> = providers.map { it.descriptor }

    override fun isCloudPreference(syncPreference: DbSyncPreference?): Boolean =
        syncPreference?.server?.startsWith(CloudServerPrefix) == true

    override suspend fun connect(syncId: Long, providerId: String, accountLabel: String?, accessToken: String): SyncLoginResult {
        currentCoroutineContext().ensureActive()
        val capturedPreference = database.syncPreferences().firstOrNull { it.syncId == syncId }
        val provider = provider(providerId) ?: return SyncLoginResult(false, "Unknown cloud provider: $providerId")
        if (accessToken.isBlank()) return SyncLoginResult(false, "Access token is required.")
        val connection = CloudConnection(provider.descriptor.id, accountLabel, accessToken)
        val status = provider.validate(connection)
        if (!status.connected) {
            AppLogger.warn("[sync] cloud connect to ${provider.descriptor.id} failed: ${status.message.lineSequence().firstOrNull().orEmpty()}")
            return SyncLoginResult(false, status.message.ifBlank { "Could not connect to ${provider.descriptor.displayName}." })
        }
        currentCoroutineContext().ensureActive()
        val server = cloudServerUri(provider.descriptor.id)
        val email = status.accountLabel ?: accountLabel
        val failure = leases.commitClaimed(capturedPreference, DbSyncPreference(server = server, email = email, authToken = accessToken)) {
            database.upsertSyncPreferenceIf(
                syncId = syncId,
                accepts = { it == capturedPreference },
                transform = { current -> (current ?: DbSyncPreference(syncId = syncId)).copy(
                    server = server,
                    email = email,
                    authToken = accessToken,
                    syncOn = true,
                ) },
            )
        }
        if (failure != null) return SyncLoginResult(false, failure)
        return SyncLoginResult(true, "Connected to ${provider.descriptor.displayName}")
    }

    override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult =
        connect(syncId, providerIdFromServer(server) ?: server, email.takeIf { it.isNotBlank() }, password)

    override suspend fun logout(syncId: Long) {
        val preference = preference(syncId)
        upsertPreference(syncId) { it.copy(authToken = null, syncOn = false) }
        leases.releaseQuietly(preference)
    }

    override suspend fun sync(syncId: Long, settings: DbSettings): SyncResult = trackResult(SyncOperationStage.Syncing) {
        val transfer = captureTransfer(syncId)
        val latest = latestCloudBackup(transfer)
        val preference = transfer.preference
        val lastSync = listOfNotNull(preference.lastSyncManga, preference.lastSyncHistory, preference.lastSyncUpdate).maxOrNull() ?: 0L
        if (latest != null && latest.modifiedAtMillis > lastSync) {
            val restored = restoreBackupInternal(transfer, latest)
            SyncResult(
                uploadedChanges = 0,
                downloadedChanges = restored.preview.itemCount,
                settingsSynced = true,
                errors = restored.preview.warnings,
            )
        } else {
            val uploaded = uploadBackupInternal(transfer, cloudBackupOptions(settings, preference))
            SyncResult(
                uploadedChanges = uploaded.itemCount,
                downloadedChanges = 0,
                settingsSynced = preference.syncSettings,
            )
        }
    }

    override suspend fun pushChanges(syncId: Long): SyncResult = trackResult(SyncOperationStage.Uploading) {
        val transfer = captureTransfer(syncId)
        val uploaded = uploadBackupInternal(transfer, cloudBackupOptions(database.settings(), transfer.preference))
        SyncResult(uploadedChanges = uploaded.itemCount, downloadedChanges = 0, settingsSynced = transfer.preference.syncSettings)
    }

    override suspend fun pullChanges(syncId: Long): SyncResult = trackResult(SyncOperationStage.Downloading) {
        val restored = restoreLatestBackupInternal(syncId)
        SyncResult(
            uploadedChanges = 0,
            downloadedChanges = restored.preview.itemCount,
            settingsSynced = true,
            errors = restored.preview.warnings,
        )
    }

    override fun status(syncId: Long): SyncConnectionStatus {
        val preference = preference(syncId)
        val providerName = providerIdFromServer(preference?.server)
            ?.let(::provider)
            ?.descriptor
            ?.displayName
        return SyncConnectionStatus(
            loggedIn = !preference?.authToken.isNullOrBlank(),
            email = preference?.email,
            server = providerName ?: preference?.server,
            lastSyncMillis = listOfNotNull(preference?.lastSyncManga, preference?.lastSyncHistory, preference?.lastSyncUpdate).maxOrNull(),
        )
    }

    override suspend fun uploadBackup(syncId: Long, options: BackupOptions): CloudBackupResult =
        trackAction(SyncOperationStage.Uploading) { uploadBackupInternal(captureTransfer(syncId), options) }

    private suspend fun uploadBackupInternal(transfer: CloudTransfer, options: BackupOptions): CloudBackupResult {
        checkTransfer(transfer)
        val provider = transfer.provider
        val connection = transfer.connection
        val export = backup.exportBackup(options.copy(format = BackupFormat.Yokan, includePrivateNotes = false))
        checkTransfer(transfer)
        val key = CloudBackupPrefix + export.fileName
        val remote = provider.putObject(connection, key, export.bytes, export.contentType)
        recordSuccess(transfer)
        AppLogger.info("[sync] cloud upload to ${provider.descriptor.id}: $key, ${export.itemCount} items, ${export.bytes.size} bytes")
        return CloudBackupResult(
            providerId = provider.descriptor.id,
            fileName = key,
            itemCount = export.itemCount,
            bytesUploaded = export.bytes.size.toLong(),
            remoteObject = remote,
        )
    }

    override suspend fun restoreLatestBackup(syncId: Long): CloudBackupRestoreResult =
        trackAction(SyncOperationStage.Downloading) { restoreLatestBackupInternal(syncId) }

    private suspend fun restoreLatestBackupInternal(syncId: Long): CloudBackupRestoreResult {
        val transfer = captureTransfer(syncId)
        val latest = latestCloudBackup(transfer) ?: throw CloudStorageException("No cloud backup found.")
        return restoreBackupInternal(transfer, latest)
    }

    private suspend fun restoreBackupInternal(transfer: CloudTransfer, latest: CloudObject): CloudBackupRestoreResult {
        checkTransfer(transfer)
        val bytes = transfer.provider.getObject(transfer.connection, latest)
        checkTransfer(transfer)
        // The predicate sees the same snapshot used as the atomic replacement's
        // expected value, so an account change during decoding/preparation cannot commit.
        val preview = try {
            backup.restoreIf(bytes) { snapshot ->
                transfer.matches(snapshot.syncPreferences.firstOrNull { it.syncId == transfer.preference.syncId })
            }
        } catch (_: BackupRestoreTargetChangedException) {
            throw SyncAccountChangedException()
        }
        recordSuccess(transfer)
        AppLogger.info("[sync] cloud restore from ${transfer.provider.descriptor.id}: ${latest.displayName}, ${preview.itemCount} items")
        return CloudBackupRestoreResult(transfer.provider.descriptor.id, latest.displayName, preview)
    }

    private suspend fun latestCloudBackup(transfer: CloudTransfer): CloudObject? {
        checkTransfer(transfer)
        val objects = transfer.provider.listObjects(transfer.connection, CloudBackupPrefix)
        checkTransfer(transfer)
        return objects.maxByOrNull { it.modifiedAtMillis }
    }

    private data class CloudTransfer(
        val preference: DbSyncPreference,
        val provider: CloudStorageProvider,
        val connection: CloudConnection,
    ) {
        fun matches(current: DbSyncPreference?): Boolean = current != null &&
            current.syncId == preference.syncId && current.serverProvider == preference.serverProvider &&
            current.server == preference.server && current.email == preference.email && current.authToken == preference.authToken
    }

    private suspend fun captureTransfer(syncId: Long): CloudTransfer {
        currentCoroutineContext().ensureActive()
        val preference = preference(syncId) ?: throw CloudStorageException("No cloud sync configuration.")
        leases.claimFailure(preference)?.let { throw CloudStorageException(it) }
        return CloudTransfer(preference, providerFor(preference), connectionFor(preference))
    }

    private suspend fun checkTransfer(transfer: CloudTransfer) {
        currentCoroutineContext().ensureActive()
        if (!transfer.matches(preference(requireNotNull(transfer.preference.syncId)))) throw SyncAccountChangedException()
    }

    private suspend fun recordSuccess(transfer: CloudTransfer) {
        currentCoroutineContext().ensureActive()
        val now = nowMillis()
        val accepted = database.upsertSyncPreferenceIf(
            syncId = requireNotNull(transfer.preference.syncId),
            accepts = transfer::matches,
            transform = { current -> requireNotNull(current).copy(lastSyncManga = now, lastSyncHistory = now, lastSyncUpdate = now) },
        )
        if (!accepted) throw SyncAccountChangedException()
        currentCoroutineContext().ensureActive()
    }

    private suspend fun trackResult(stage: SyncOperationStage, block: suspend () -> SyncResult): SyncResult {
        val operationId = operationMonitor.begin(stage)
        return try {
            val result = block()
            if (result.errors.isNotEmpty()) AppLogger.warn("[sync] cloud ${stage.name.lowercase()}: ${result.errors.joinToString("; ")}")
            operationMonitor.finish(
                operationId,
                if (result.errors.isEmpty()) SyncOperationOutcome.Succeeded else SyncOperationOutcome.Failed,
            )
            result
        } catch (cancelled: CancellationException) {
            operationMonitor.finish(operationId, SyncOperationOutcome.Cancelled)
            throw cancelled
        } catch (changed: SyncAccountChangedException) {
            operationMonitor.finish(operationId, SyncOperationOutcome.Cancelled)
            throw changed
        } catch (error: Throwable) {
            AppLogger.error("[sync] cloud ${stage.name.lowercase()} failed: ${error.message?.lineSequence()?.firstOrNull() ?: error::class.simpleName}")
            operationMonitor.finish(operationId, SyncOperationOutcome.Failed)
            throw error
        }
    }

    private suspend fun <T> trackAction(stage: SyncOperationStage, block: suspend () -> T): T {
        val operationId = operationMonitor.begin(stage)
        return try {
            block().also { operationMonitor.finish(operationId, SyncOperationOutcome.Succeeded) }
        } catch (cancelled: CancellationException) {
            operationMonitor.finish(operationId, SyncOperationOutcome.Cancelled)
            throw cancelled
        } catch (changed: SyncAccountChangedException) {
            operationMonitor.finish(operationId, SyncOperationOutcome.Cancelled)
            throw changed
        } catch (error: Throwable) {
            AppLogger.error("[sync] cloud ${stage.name.lowercase()} failed: ${error.message?.lineSequence()?.firstOrNull() ?: error::class.simpleName}")
            operationMonitor.finish(operationId, SyncOperationOutcome.Failed)
            throw error
        }
    }

    private fun cloudBackupOptions(settings: DbSettings, preference: DbSyncPreference?): BackupOptions {
        return BackupOptions(
            includeHistory = preference?.syncHistories ?: true,
            includeUpdates = preference?.syncUpdates ?: true,
            includeSettings = preference?.syncSettings ?: true,
            compressionLevel = settings.backupCompressionLevel ?: 6,
            format = BackupFormat.Yokan,
        )
    }

    private fun provider(id: String): CloudStorageProvider? =
        providers.firstOrNull { it.descriptor.id == id }

    private fun providerFor(preference: DbSyncPreference): CloudStorageProvider {
        val providerId = providerIdFromServer(preference.server) ?: throw CloudStorageException("Cloud provider is missing.")
        return provider(providerId) ?: throw CloudStorageException("Cloud provider is not registered: $providerId")
    }

    private fun connectionFor(preference: DbSyncPreference): CloudConnection {
        val providerId = providerIdFromServer(preference.server) ?: throw CloudStorageException("Cloud provider is missing.")
        val token = preference.authToken?.takeIf { it.isNotBlank() } ?: throw CloudStorageException("Cloud access token is missing.")
        return CloudConnection(providerId, preference.email, token)
    }

    private fun preference(syncId: Long): DbSyncPreference? =
        database.syncPreferences().firstOrNull { it.syncId == syncId }

    private suspend fun upsertPreference(syncId: Long, transform: (DbSyncPreference) -> DbSyncPreference) {
        currentCoroutineContext().ensureActive()
        database.upsertSyncPreferenceIf(
            syncId = syncId,
            accepts = { it != null },
            transform = { transform(requireNotNull(it)) },
        )
    }
}

fun cloudServerUri(providerId: String): String = "$CloudServerPrefix$providerId"

fun providerIdFromServer(server: String?): String? =
    server
        ?.takeIf { it.startsWith(CloudServerPrefix) }
        ?.removePrefix(CloudServerPrefix)
        ?.substringBefore('?')
        ?.takeIf { it.isNotBlank() }
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/GoogleDriveCloudStorageProvider.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/GoogleDriveCloudStorageProvider.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/GoogleDriveCloudStorageProvider.kt).

The implementation below defines `GoogleDriveCloudStorageProvider`, `validate`, `putObject`, `listObjects`, `getObject`, `parseFile`, `authHeaders`, `JsonObject.string`, `escapeDriveQuery`, `percentEncode` and 1 further declarations.

The source describes its contract as:

> Stores cloud backups in the Drive `appDataFolder` of the connected account.

Cross-chapter imports used by this file: [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md), [`nowMillis`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.longOrNull

/** Stores cloud backups in the Drive `appDataFolder` of the connected account. */
class GoogleDriveCloudStorageProvider(
    private val http: HttpService,
) : CloudStorageProvider {
    override val descriptor: CloudProviderDescriptor = CloudProviderDescriptor(
        id = ProviderId,
        displayName = "Google Drive",
        description = "Stores Yokan sync snapshots and backups in the app data folder of the connected Google Drive account.",
        authInstructions = "Use an OAuth access token with the https://www.googleapis.com/auth/drive.appdata scope.",
    )

    private val json = Json {
        ignoreUnknownKeys = true
        isLenient = true
    }

    override suspend fun validate(connection: CloudConnection): CloudConnectionStatus =
        catchingNonCancellation {
            listObjects(connection, "__yokan-validation__")
            CloudConnectionStatus(connected = true, accountLabel = connection.accountLabel, message = "Connected")
        }.getOrElse { error ->
            CloudConnectionStatus(connected = false, accountLabel = connection.accountLabel, message = error.message.orEmpty())
        }

    override suspend fun putObject(
        connection: CloudConnection,
        key: String,
        bytes: ByteArray,
        contentType: String,
    ): CloudObject {
        val boundary = "yokan-${nowMillis()}"
        val metadata = JsonObject(
            mapOf(
                "name" to JsonPrimitive(key),
                "parents" to JsonArray(listOf(JsonPrimitive("appDataFolder"))),
            ),
        ).toString()
        val body = multipartRelated(boundary, metadata, contentType, bytes)
        val response = http.request(
            HttpRequest(
                url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,name,size,modifiedTime",
                method = "POST",
                headers = authHeaders(connection) + mapOf("Content-Type" to "multipart/related; boundary=$boundary"),
                bodyBytes = body,
            ),
        )
        if (response.statusCode !in 200..299) {
            throw CloudStorageException("Google Drive upload failed with HTTP ${response.statusCode}: ${response.body.take(160)}")
        }
        return parseFile(response.body, fallbackKey = key, fallbackSize = bytes.size.toLong())
    }

    override suspend fun listObjects(connection: CloudConnection, prefix: String): List<CloudObject> {
        val query = "'appDataFolder' in parents and name contains '${escapeDriveQuery(prefix)}' and trashed=false"
        val url = "https://www.googleapis.com/drive/v3/files" +
            "?spaces=appDataFolder" +
            "&q=${percentEncode(query)}" +
            "&fields=${percentEncode("files(id,name,size,modifiedTime)")}"
        val response = http.request(HttpRequest(url = url, headers = authHeaders(connection)))
        if (response.statusCode !in 200..299) {
            throw CloudStorageException("Google Drive list failed with HTTP ${response.statusCode}: ${response.body.take(160)}")
        }
        val files = json.parseToJsonElement(response.body).jsonObject["files"]?.jsonArray ?: JsonArray(emptyList())
        return files.mapNotNull { element ->
            runCatching { parseFile(element.jsonObject, fallbackKey = prefix, fallbackSize = 0L) }.getOrNull()
        }
    }

    override suspend fun getObject(connection: CloudConnection, objectRef: CloudObject): ByteArray {
        val fileId = objectRef.providerFileId ?: throw CloudStorageException("Google Drive file id is missing.")
        val response = http.request(
            HttpRequest(
                url = "https://www.googleapis.com/drive/v3/files/${percentEncode(fileId)}?alt=media",
                headers = authHeaders(connection),
            ),
        )
        if (response.statusCode !in 200..299) {
            throw CloudStorageException("Google Drive download failed with HTTP ${response.statusCode}: ${response.body.take(160)}")
        }
        return response.bodyBytes
    }

    private fun parseFile(body: String, fallbackKey: String, fallbackSize: Long): CloudObject =
        parseFile(json.parseToJsonElement(body).jsonObject, fallbackKey, fallbackSize)

    private fun parseFile(file: JsonObject, fallbackKey: String, fallbackSize: Long): CloudObject {
        val id = file.string("id")
        val name = file.string("name") ?: fallbackKey
        val size = file["size"]?.jsonPrimitive?.longOrNull
            ?: file.string("size")?.toLongOrNull()
            ?: fallbackSize
        val modified = file.string("modifiedTime")?.let(::parseInstantMillis) ?: nowMillis()
        return CloudObject(
            key = name,
            displayName = name,
            sizeBytes = size,
            modifiedAtMillis = modified,
            providerFileId = id,
        )
    }

    private fun authHeaders(connection: CloudConnection): Map<String, String> =
        mapOf(
            "Authorization" to "Bearer ${connection.accessToken}",
            "Accept" to "application/json",
        )

    private fun JsonObject.string(key: String): String? =
        this[key]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() }

    private fun escapeDriveQuery(value: String): String =
        value.replace("\\", "\\\\").replace("'", "\\'")

    private fun percentEncode(value: String): String {
        val allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"
        return buildString {
            value.encodeToByteArray().forEach { byte ->
                val int = byte.toInt() and 0xff
                val char = int.toChar()
                if (char in allowed) {
                    append(char)
                } else {
                    append('%')
                    append(int.toString(16).uppercase().padStart(2, '0'))
                }
            }
        }
    }

    companion object {
        const val ProviderId = "google-drive"
    }
}

/** Drive `uploadType=multipart` body: JSON metadata part, then the media part. */
internal fun multipartRelated(boundary: String, metadata: String, contentType: String, bytes: ByteArray): ByteArray {
    val prefix = buildString {
        append("--").append(boundary).append("\r\n")
        append("Content-Type: application/json; charset=UTF-8\r\n\r\n")
        append(metadata).append("\r\n")
        append("--").append(boundary).append("\r\n")
        append("Content-Type: ").append(contentType).append("\r\n\r\n")
    }.encodeToByteArray()
    val suffix = "\r\n--$boundary--\r\n".encodeToByteArray()
    return prefix + bytes + suffix
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncYomiSyncService.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncYomiSyncService.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncYomiSyncService.kt).

Read current ETag before both merge uploads and upload-only operations. Conditional publication and the bounded 412 retry loop are necessary for multi-device safety, not optional HTTP optimizations.

The implementation below defines `normalizeSyncYomiHost`, `syncYomiKeyLabel`, `SyncYomiSyncService`, `login`, `logout`, `sync`, `pushChanges`, `pullChanges`, `status`, `run` and 4 further declarations.

The source describes its contract as:

> `https://` assumed, lowercase scheme/host, no trailing slash; null unless a plain http(s) origin/path.

Cross-chapter imports used by this file: [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`SyncServerProvider`](../chapters/02-domain-and-settings-models.md), [`YokanDatabase`](../chapters/03-persistence-and-migrations.md), [`BackupFormat`](../chapters/20-backup-and-restore.md), [`BackupOptions`](../chapters/20-backup-and-restore.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.sync.normalizeMangayomiServer
import eu.friedcutlet.yokan.services.backup.BackupFormat
import eu.friedcutlet.yokan.services.backup.BackupOptions
import eu.friedcutlet.yokan.services.backup.BackupService
import eu.friedcutlet.yokan.util.sha256
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.header
import eu.friedcutlet.yokan.services.http.normalizeHubServer
import eu.friedcutlet.yokan.services.logging.AppLogger
import io.ktor.http.Url
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

/** `https://` assumed, lowercase scheme/host, no trailing slash; null unless a plain http(s) origin/path. */
internal fun normalizeSyncYomiHost(value: String): String? {
    val raw = normalizeHubServer(value)?.let(::normalizeMangayomiServer) ?: return null
    val url = runCatching { Url(raw) }.getOrNull() ?: return null
    if (url.protocol.name !in setOf("http", "https") || url.host.isBlank() || url.user != null || '?' in raw || '#' in raw) return null
    return raw
}

/** Lease-key label for an API key: a short SHA-256 digest, so the key itself never leaves the preference. */
internal fun syncYomiKeyLabel(apiKey: String?): String =
    apiKey?.takeIf(String::isNotBlank)?.let { key ->
        sha256(key.encodeToByteArray()).copyOf(8).toHexString()
    }.orEmpty()

/**
 * SyncYomi (`/api/sync/content`): one Tachiyomi-protobuf backup per API key. A run downloads it, merges it into the
 * library, and uploads the merged library under `If-Match`; a concurrent upload (412) restarts the run a bounded
 * number of times. Local data is only merged into, never replaced.
 */
class SyncYomiSyncService(
    private val database: YokanDatabase,
    private val backup: BackupService,
    private val http: HttpService,
    private val operationMonitor: SyncOperationMonitor = SyncOperationMonitor(),
    private val leases: SyncAccountLeases = SyncAccountLeases.None,
) : SyncService {
    override val operationState = operationMonitor.state
    private val operationMutex = Mutex()

    /** [server] is the SyncYomi host, [password] the API key; [email] is unused. */
    override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult = operationMutex.withLock {
        val prior = preference(syncId)
        if (prior?.serverProvider != SyncServerProvider.SyncYomi) return@withLock SyncLoginResult(false, "SyncYomi is not the selected sync provider.")
        val host = normalizeSyncYomiHost(server) ?: return@withLock SyncLoginResult(false, "Enter a valid SyncYomi server URL.")
        val apiKey = password.trim().takeIf(String::isNotEmpty) ?: return@withLock SyncLoginResult(false, "API key is required.")
        val response = http.requestOrNull(HttpRequest(contentUrl(host), headers = mapOf(TokenHeader to apiKey)))
            ?: return@withLock SyncLoginResult(false, "Could not reach the SyncYomi server.")
        when (response.statusCode) {
            in 200..299, 404 -> Unit
            401, 403 -> return@withLock SyncLoginResult(false, "SyncYomi rejected the API key.")
            else -> return@withLock SyncLoginResult(false, "SyncYomi server returned HTTP ${response.statusCode}.")
        }
        currentCoroutineContext().ensureActive()
        val next = DbSyncPreference(server = host, authToken = apiKey, serverProvider = SyncServerProvider.SyncYomi)
        val failure = leases.commitClaimed(prior, next) {
            database.upsertSyncPreferenceIf(
                syncId = syncId,
                accepts = { it == prior },
                transform = { current ->
                    requireNotNull(current).copy(
                        server = host, email = null, authToken = apiKey, syncOn = true,
                        lastSyncManga = null, lastSyncHistory = null, lastSyncUpdate = null,
                    )
                },
            )
        }
        if (failure != null) SyncLoginResult(false, failure) else SyncLoginResult(true, "Connected to SyncYomi server.")
    }

    override suspend fun logout(syncId: Long) = operationMutex.withLock {
        val pref = preference(syncId) ?: return@withLock
        database.upsertSyncPreferenceIf(syncId, accepts = { it != null }, transform = { requireNotNull(it).copy(authToken = null, syncOn = false) })
        leases.releaseQuietly(pref)
    }

    override suspend fun sync(syncId: Long, settings: DbSettings) = run(SyncOperationStage.Syncing, syncId, push = true, pull = true)
    override suspend fun pushChanges(syncId: Long) = run(SyncOperationStage.Uploading, syncId, push = true, pull = false)
    override suspend fun pullChanges(syncId: Long) = run(SyncOperationStage.Downloading, syncId, push = false, pull = true)

    override fun status(syncId: Long): SyncConnectionStatus {
        val pref = preference(syncId)
        return SyncConnectionStatus(!pref?.authToken.isNullOrBlank(), pref?.email, pref?.server, pref?.lastSyncManga)
    }

    private suspend fun run(stage: SyncOperationStage, syncId: Long, push: Boolean, pull: Boolean): SyncResult =
        runStateSync(operationMonitor, operationMutex, stage, "SyncYomi") { perform(syncId, push, pull) }

    private suspend fun perform(syncId: Long, push: Boolean, pull: Boolean): SyncResult {
        val captured = preference(syncId) ?: return stateSyncFailure("No sync configuration.")
        if (captured.serverProvider != SyncServerProvider.SyncYomi) return stateSyncFailure("SyncYomi is not the selected sync provider.")
        val host = captured.server?.let(::normalizeSyncYomiHost) ?: return stateSyncFailure("Invalid SyncYomi server URL.")
        val apiKey = captured.authToken?.takeIf(String::isNotBlank) ?: return stateSyncFailure("Not logged in.")
        leases.claimFailure(captured)?.let { return stateSyncFailure(it) }
        var downloaded = 0
        repeat(MaxAttempts) {
            database.checkSyncAccount(captured)
            // Always a full GET: the ETag it returns is the If-Match precondition of this run's upload.
            val remote = http.requestOrNull(HttpRequest(contentUrl(host), headers = mapOf(TokenHeader to apiKey)))
                ?: throw StateSyncException("Could not reach the SyncYomi server.")
            database.checkSyncAccount(captured)
            val etag = when (remote.statusCode) {
                404 -> null
                in 200..299 -> remote.headers.header("ETag") ?: throw StateSyncException("SyncYomi server response is missing its ETag.")
                else -> throw httpFailure(remote.statusCode)
            }
            if (pull && etag != null) {
                // Unreadable remote content is overwritten below, as upstream SyncYomi clients do.
                downloaded += backup.mergeRemoteState(remote.bodyBytes, captured, "SyncYomi") ?: 0
            }
            if (!push) {
                database.recordStateSync(captured)
                return SyncResult(0, downloaded, settingsSynced = false)
            }
            val export = backup.exportBackup(
                BackupOptions(
                    includeHistory = captured.syncHistories,
                    includeUpdates = captured.syncUpdates,
                    includeSettings = false,
                    compressionLevel = 0,
                    format = BackupFormat.Tachiyomi,
                    includePrivateNotes = false,
                ),
            )
            if (export.bytes.isEmpty()) throw StateSyncException("Nothing to upload to SyncYomi.")
            database.checkSyncAccount(captured)
            val headers = buildMap {
                put(TokenHeader, apiKey)
                put("Content-Type", "application/octet-stream")
                etag?.let { put("If-Match", it) }
            }
            val upload = http.requestOrNull(HttpRequest(contentUrl(host), "PUT", headers, bodyBytes = export.bytes))
                ?: throw StateSyncException("Could not reach the SyncYomi server.")
            when (upload.statusCode) {
                in 200..299 -> {
                    database.recordStateSync(captured)
                    return SyncResult(export.itemCount, downloaded, settingsSynced = false)
                }
                412 -> AppLogger.info("[sync] SyncYomi data changed during upload; restarting sync")
                else -> throw httpFailure(upload.statusCode)
            }
        }
        return stateSyncFailure("SyncYomi data kept changing on the server during sync; try again later.")
    }

    private fun httpFailure(status: Int) = StateSyncException(
        if (status == 401 || status == 403) "SyncYomi rejected the API key; sign in again." else "SyncYomi server returned HTTP $status.",
    )

    private fun preference(id: Long): DbSyncPreference? = database.syncPreferences().firstOrNull { it.syncId == id }

    private companion object {
        const val TokenHeader = "X-API-Token"
        /** Full pull/merge/push passes before a persistent 412 is reported as a conflict. */
        const val MaxAttempts = 3

        fun contentUrl(host: String) = "$host/api/sync/content"
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/GoogleDriveSyncService.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/GoogleDriveSyncService.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/GoogleDriveSyncService.kt).

The implementation below defines `googleDriveAuthorizationUrl`, `pkceChallenge`, `base64Url`, `parseInstantMillis`, `GoogleDriveCredential`, `GoogleDriveSyncService`, `PendingAuth`, `DriveFile`, `beginBrowserLogin`, `cancelBrowserLogin` and 20 further declarations.

The source describes its contract as:

> Loopback redirect of a Google "Desktop app" OAuth client; the browser fails to load it and the user copies the URL.

Cross-chapter imports used by this file: [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`SyncServerProvider`](../chapters/02-domain-and-settings-models.md), [`YokanDatabase`](../chapters/03-persistence-and-migrations.md), [`BackupFormat`](../chapters/20-backup-and-restore.md), [`BackupOptions`](../chapters/20-backup-and-restore.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import dev.whyoleg.cryptography.DelicateCryptographyApi
import dev.whyoleg.cryptography.random.CryptographyRandom
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.backup.BackupFormat
import eu.friedcutlet.yokan.services.backup.BackupOptions
import eu.friedcutlet.yokan.services.backup.BackupService
import eu.friedcutlet.yokan.util.sha256
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.tracking.callbackParameter
import eu.friedcutlet.yokan.util.PlatformLock
import eu.friedcutlet.yokan.util.nowMillis
import io.ktor.http.URLBuilder
import io.ktor.http.formUrlEncode
import kotlin.io.encoding.Base64
import kotlin.time.Instant
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.put

/** Loopback redirect of a Google "Desktop app" OAuth client; the browser fails to load it and the user copies the URL. */
internal const val GoogleDriveRedirectUri = "http://127.0.0.1"
internal const val GoogleDriveScope = "https://www.googleapis.com/auth/drive.appdata"

/** Authorization-code + PKCE (S256) URL for the user's own OAuth client. */
internal fun googleDriveAuthorizationUrl(clientId: String, verifier: String, state: String): String =
    URLBuilder("https://accounts.google.com/o/oauth2/v2/auth").apply {
        parameters.append("client_id", clientId)
        parameters.append("redirect_uri", GoogleDriveRedirectUri)
        parameters.append("response_type", "code")
        parameters.append("scope", GoogleDriveScope)
        parameters.append("access_type", "offline")
        parameters.append("prompt", "consent")
        parameters.append("code_challenge", pkceChallenge(verifier))
        parameters.append("code_challenge_method", "S256")
        parameters.append("state", state)
    }.build().toString()

internal fun pkceChallenge(verifier: String): String = base64Url(sha256(verifier.encodeToByteArray()))

private fun base64Url(bytes: ByteArray) = Base64.UrlSafe.withPadding(Base64.PaddingOption.ABSENT).encode(bytes)

/** Epoch millis of an ISO-8601 instant, or null when [value] is not one. */
internal fun parseInstantMillis(value: String): Long? = runCatching { Instant.parse(value).toEpochMilliseconds() }.getOrNull()

/** Stored in [DbSyncPreference.authToken]; the client id lives in `server`, the account email in `email`. */
@Serializable
private data class GoogleDriveCredential(val clientSecret: String = "", val refreshToken: String)

/**
 * Application-state sync through one file in the Drive `appDataFolder` of the user's own OAuth client
 * (independent of the `cloud://google-drive` backup path). A run takes a lock file, merges the sync file
 * when another device wrote it, uploads the merged library, and always releases the lock.
 */
class GoogleDriveSyncService(
    private val database: YokanDatabase,
    private val backup: BackupService,
    private val http: HttpService,
    private val operationMonitor: SyncOperationMonitor = SyncOperationMonitor(),
    private val leases: SyncAccountLeases = SyncAccountLeases.None,
    private val clock: () -> Long = ::nowMillis,
) : SyncService {
    override val operationState = operationMonitor.state
    private val operationMutex = Mutex()
    private val json = Json { ignoreUnknownKeys = true }
    private val authLock = PlatformLock()
    private val pendingAuth = mutableMapOf<Long, PendingAuth>()

    private class PendingAuth(val clientId: String, val verifier: String, val state: String)

    private class DriveFile(val id: String, val createdMillis: Long, val modifiedMillis: Long, val properties: Map<String, String>) {
        val deviceId: String? get() = properties["deviceId"]
        val expiresAt: Long get() = properties["expiresAt"]?.toLongOrNull() ?: 0L
    }

    /** [server] is the user's OAuth client id; the returned URL is opened in the system browser. */
    @OptIn(DelicateCryptographyApi::class)
    override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? {
        val clientId = server.trim().takeIf { it.isNotEmpty() && it.length <= 256 && it.none(Char::isWhitespace) } ?: return null
        if (preference(syncId)?.serverProvider != SyncServerProvider.GoogleDrive) return null
        val verifier = base64Url(CryptographyRandom.Default.nextBytes(32))
        val state = base64Url(CryptographyRandom.Default.nextBytes(24))
        authLock.withLock { pendingAuth[syncId] = PendingAuth(clientId, verifier, state) }
        return BrowserLoginAttempt(syncId, clientId, googleDriveAuthorizationUrl(clientId, verifier, state), device = "", state = state)
    }

    override fun cancelBrowserLogin(attempt: BrowserLoginAttempt) {
        authLock.withLock { if (pendingAuth[attempt.syncId]?.state == attempt.state) pendingAuth.remove(attempt.syncId) }
    }

    /**
     * Completes the sign-in begun by [beginBrowserLogin]: [server] is the OAuth client id, [email] its client secret,
     * [password] the pasted loopback URL (or bare code) the browser ended on.
     */
    override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult = operationMutex.withLock {
        val clientId = server.trim()
        val pending = authLock.withLock { pendingAuth[syncId]?.takeIf { it.clientId == clientId }?.also { pendingAuth.remove(syncId) } }
            ?: return@withLock SyncLoginResult(false, "Open the Google sign-in page for this client ID first.")
        val prior = preference(syncId)
        if (prior == null || prior.serverProvider != SyncServerProvider.GoogleDrive) return@withLock SyncLoginResult(false, "Google Drive is not the selected sync provider.")
        val pasted = password.trim()
        if (pasted.length > 4096 || "error=" in pasted) return@withLock SyncLoginResult(false, "Google sign-in was not completed.")
        if ("state=" in pasted && callbackParameter(pasted, "state") != pending.state) {
            return@withLock SyncLoginResult(false, "This sign-in address belongs to another attempt; open the sign-in page again.")
        }
        val code = callbackParameter(pasted, "code").takeIf { it.isNotEmpty() && it.length <= 1024 && it.none(Char::isWhitespace) && "://" !in it }
            ?: return@withLock SyncLoginResult(false, "Paste the address the browser opened after sign-in, or its code.")
        val secret = email.trim()
        try {
            val token = tokenRequest(clientId, secret, listOf(
                "code" to code, "redirect_uri" to GoogleDriveRedirectUri,
                "grant_type" to "authorization_code", "code_verifier" to pending.verifier,
            ))
            val refreshToken = token.string("refresh_token")
                ?: throw StateSyncException("Google returned no refresh token; remove Yokan's access in your Google account and sign in again.")
            val accessToken = token.string("access_token") ?: throw StateSyncException("Google returned an invalid token response.")
            val user = driveJson(HttpRequest("$DriveApi/about?fields=user(emailAddress,displayName)", headers = bearer(accessToken)), "account lookup")["user"] as? JsonObject
            val account = user?.string("emailAddress") ?: user?.string("displayName")
            currentCoroutineContext().ensureActive()
            val credential = json.encodeToString(GoogleDriveCredential.serializer(), GoogleDriveCredential(secret, refreshToken))
            val deviceId = prior.deviceId?.takeIf(String::isNotBlank) ?: newDeviceId()
            val next = DbSyncPreference(server = clientId, email = account, authToken = credential, serverProvider = SyncServerProvider.GoogleDrive)
            val failure = leases.commitClaimed(prior, next) {
                database.upsertSyncPreferenceIf(
                    syncId = syncId,
                    accepts = { it == prior },
                    transform = { current ->
                        requireNotNull(current).copy(
                            server = clientId, email = account, authToken = credential, syncOn = true, deviceId = deviceId,
                            lastSyncManga = null, lastSyncHistory = null, lastSyncUpdate = null,
                        )
                    },
                )
            }
            if (failure != null) SyncLoginResult(false, failure)
            else SyncLoginResult(true, "Connected to Google Drive${account?.let { " as $it" }.orEmpty()}.")
        } catch (error: StateSyncException) {
            SyncLoginResult(false, error.message ?: "Google sign-in failed.")
        }
    }

    override suspend fun logout(syncId: Long) = operationMutex.withLock {
        val pref = preference(syncId) ?: return@withLock
        database.upsertSyncPreferenceIf(syncId, accepts = { it != null }, transform = { requireNotNull(it).copy(authToken = null, syncOn = false) })
        leases.releaseQuietly(pref)
    }

    override suspend fun sync(syncId: Long, settings: DbSettings) = run(SyncOperationStage.Syncing, syncId, push = true, pull = true)
    override suspend fun pushChanges(syncId: Long) = run(SyncOperationStage.Uploading, syncId, push = true, pull = false)
    override suspend fun pullChanges(syncId: Long) = run(SyncOperationStage.Downloading, syncId, push = false, pull = true)

    override fun status(syncId: Long): SyncConnectionStatus {
        val pref = preference(syncId)
        return SyncConnectionStatus(!pref?.authToken.isNullOrBlank(), pref?.email, "Google Drive", pref?.lastSyncManga)
    }

    private suspend fun run(stage: SyncOperationStage, syncId: Long, push: Boolean, pull: Boolean): SyncResult =
        runStateSync(operationMonitor, operationMutex, stage, "Google Drive") { perform(syncId, push, pull) }

    private suspend fun perform(syncId: Long, push: Boolean, pull: Boolean): SyncResult {
        val captured = preference(syncId) ?: return stateSyncFailure("No sync configuration.")
        if (captured.serverProvider != SyncServerProvider.GoogleDrive) return stateSyncFailure("Google Drive is not the selected sync provider.")
        val clientId = captured.server?.trim()?.takeIf(String::isNotEmpty) ?: return stateSyncFailure("Google OAuth client ID is missing.")
        val credential = captured.authToken?.let { runCatching { json.decodeFromString(GoogleDriveCredential.serializer(), it) }.getOrNull() }
            ?: return stateSyncFailure("Not signed in to Google Drive.")
        val deviceId = captured.deviceId?.takeIf(String::isNotBlank) ?: return stateSyncFailure("Sign in to Google Drive again.")
        leases.claimFailure(captured)?.let { return stateSyncFailure(it) }
        val accessToken = tokenRequest(clientId, credential.clientSecret, listOf("refresh_token" to credential.refreshToken, "grant_type" to "refresh_token"))
            .string("access_token") ?: throw StateSyncException("Google returned an invalid token response.")
        database.checkSyncAccount(captured)
        val lockId = acquireLock(accessToken, deviceId)
        try {
            database.checkSyncAccount(captured)
            val remote = listFiles(accessToken, SyncFileName).maxByOrNull { it.modifiedMillis }
            var downloaded = 0
            // Our own last upload holds nothing new; another device's file is merged in, never replacing local data.
            if (pull && remote != null && remote.deviceId != deviceId) {
                val bytes = drive(HttpRequest("$DriveApi/files/${remote.id}?alt=media", headers = bearer(accessToken)), "download").bodyBytes
                database.checkSyncAccount(captured)
                downloaded = backup.mergeRemoteState(bytes, captured, "Google Drive") ?: 0
            }
            var uploaded = 0
            if (push) {
                val export = backup.exportBackup(
                    BackupOptions(
                        includeHistory = captured.syncHistories,
                        includeUpdates = captured.syncUpdates,
                        includeSettings = captured.syncSettings,
                        compressionLevel = 6,
                        format = BackupFormat.Yokan,
                        includePrivateNotes = false,
                    ),
                )
                database.checkSyncAccount(captured)
                upload(accessToken, remote?.id, deviceId, export.bytes, export.contentType)
                uploaded = export.itemCount
            }
            database.recordStateSync(captured)
            return SyncResult(uploaded, downloaded, settingsSynced = push && captured.syncSettings)
        } finally {
            withContext(NonCancellable) {
                runCatching { deleteFile(accessToken, lockId) }
                    .onFailure { AppLogger.warn("[sync] Google Drive lock release failed; it expires on its own") }
            }
        }
    }

    /**
     * Takes the `appDataFolder` lock: expired locks are removed, a live lock of another device refuses the run,
     * and when two devices create locks at once (Drive allows duplicate names) the later one backs off.
     */
    private suspend fun acquireLock(accessToken: String, deviceId: String): String {
        val now = clock()
        val (stale, live) = listFiles(accessToken, LockFileName).partition { it.expiresAt <= now }
        stale.forEach { deleteFile(accessToken, it.id) }
        if (live.any { it.deviceId != deviceId }) throw StateSyncException(BusyMessage)
        live.forEach { deleteFile(accessToken, it.id) } // Left behind by an interrupted run on this device.
        val metadata = buildJsonObject {
            put("name", LockFileName)
            put("parents", JsonArray(listOf(JsonPrimitive("appDataFolder"))))
            put("appProperties", buildJsonObject { put("deviceId", deviceId); put("expiresAt", (now + LockTtlMillis).toString()) })
        }
        val created = driveJson(
            HttpRequest("$DriveApi/files?fields=id,createdTime", "POST", bearer(accessToken) + ("Content-Type" to "application/json"), metadata.toString()),
            "lock",
        )
        val lockId = created.string("id") ?: throw StateSyncException("Google Drive returned an invalid lock file.")
        val mine = created.string("createdTime")?.let(::parseInstantMillis) ?: now
        val rival = listFiles(accessToken, LockFileName).any {
            it.id != lockId && it.deviceId != deviceId && it.expiresAt > now &&
                (it.createdMillis < mine || (it.createdMillis == mine && it.id < lockId))
        }
        if (rival) {
            withContext(NonCancellable) { runCatching { deleteFile(accessToken, lockId) } }
            throw StateSyncException(BusyMessage)
        }
        return lockId
    }

    private suspend fun upload(accessToken: String, fileId: String?, deviceId: String, bytes: ByteArray, contentType: String) {
        val metadata = buildJsonObject {
            if (fileId == null) {
                put("name", SyncFileName)
                put("parents", JsonArray(listOf(JsonPrimitive("appDataFolder"))))
            }
            put("appProperties", buildJsonObject { put("deviceId", deviceId) })
        }
        val boundary = "yokan-sync-${clock()}"
        val url = if (fileId == null) "$DriveUpload/files?uploadType=multipart&fields=id" else "$DriveUpload/files/$fileId?uploadType=multipart&fields=id"
        drive(
            HttpRequest(
                url, if (fileId == null) "POST" else "PATCH",
                bearer(accessToken) + ("Content-Type" to "multipart/related; boundary=$boundary"),
                bodyBytes = multipartRelated(boundary, metadata.toString(), contentType, bytes),
            ),
            "upload",
        )
    }

    private suspend fun listFiles(accessToken: String, name: String): List<DriveFile> {
        val url = URLBuilder("$DriveApi/files").apply {
            parameters.append("spaces", "appDataFolder")
            parameters.append("q", "name = '$name' and trashed = false")
            parameters.append("fields", "files(id,createdTime,modifiedTime,appProperties)")
        }.build().toString()
        val files = driveJson(HttpRequest(url, headers = bearer(accessToken)), "list")["files"] as? JsonArray ?: return emptyList()
        return files.mapNotNull { element ->
            val file = element as? JsonObject ?: return@mapNotNull null
            val id = file.string("id") ?: return@mapNotNull null
            val properties = (file["appProperties"] as? JsonObject)?.mapNotNull { (key, value) ->
                (value as? JsonPrimitive)?.contentOrNull?.let { key to it }
            }?.toMap().orEmpty()
            DriveFile(id, file.string("createdTime")?.let(::parseInstantMillis) ?: 0L, file.string("modifiedTime")?.let(::parseInstantMillis) ?: 0L, properties)
        }
    }

    private suspend fun deleteFile(accessToken: String, id: String) {
        val response = http.requestOrNull(HttpRequest("$DriveApi/files/$id", "DELETE", bearer(accessToken)))
            ?: throw StateSyncException("Could not reach Google Drive.")
        if (response.statusCode != 404 && response.statusCode !in 200..299) throw driveFailure(response, "delete")
    }

    private suspend fun drive(request: HttpRequest, action: String): HttpResponse {
        val response = http.requestOrNull(request) ?: throw StateSyncException("Could not reach Google Drive.")
        if (response.statusCode !in 200..299) throw driveFailure(response, action)
        return response
    }

    private suspend fun driveJson(request: HttpRequest, action: String): JsonObject {
        val body = drive(request, action).body
        return runCatching { json.parseToJsonElement(body).jsonObject }.getOrNull()
            ?: throw StateSyncException("Google Drive returned an invalid $action response.")
    }

    private fun driveFailure(response: HttpResponse, action: String) = StateSyncException(
        if (response.statusCode == 401) "Google Drive rejected the sign-in; sign in again."
        else "Google Drive $action failed with HTTP ${response.statusCode}.",
    )

    /** Token endpoint call (code exchange or refresh); the client secret is sent when the user entered one. */
    private suspend fun tokenRequest(clientId: String, clientSecret: String, form: List<Pair<String, String>>): JsonObject {
        val fields = listOf("client_id" to clientId) + listOfNotNull(clientSecret.takeIf(String::isNotBlank)?.let { "client_secret" to it }) + form
        val response = http.requestOrNull(
            HttpRequest(TokenUrl, "POST", mapOf("Content-Type" to "application/x-www-form-urlencoded", "Accept" to "application/json"), fields.formUrlEncode()),
        ) ?: throw StateSyncException("Could not reach Google.")
        val body = runCatching { json.parseToJsonElement(response.body).jsonObject }.getOrNull()
        if (response.statusCode !in 200..299) throw StateSyncException(
            when (body?.string("error")) {
                "invalid_grant" -> "Google sign-in expired or was revoked; sign in to Google Drive again."
                "invalid_client", "unauthorized_client" -> "Google rejected the OAuth client ID or secret."
                else -> "Google token request failed with HTTP ${response.statusCode}."
            },
        )
        return body ?: throw StateSyncException("Google returned an invalid token response.")
    }

    private fun bearer(accessToken: String) = mapOf("Authorization" to "Bearer $accessToken", "Accept" to "application/json")

    private fun preference(id: Long): DbSyncPreference? = database.syncPreferences().firstOrNull { it.syncId == id }

    @OptIn(DelicateCryptographyApi::class)
    private fun newDeviceId(): String =
        CryptographyRandom.Default.nextBytes(16).toHexString()

    private fun JsonObject.string(key: String): String? =
        (this[key] as? JsonPrimitive)?.contentOrNull?.trim()?.takeIf(String::isNotEmpty)

    internal companion object {
        const val SyncFileName = "yokan_sync.json.gz"
        const val LockFileName = "yokan_sync.lock"
        const val LockTtlMillis = 10 * 60 * 1000L
        const val BusyMessage = "Sync is in progress on another device; try again in a few minutes."
        private const val DriveApi = "https://www.googleapis.com/drive/v3"
        private const val DriveUpload = "https://www.googleapis.com/upload/drive/v3"
        const val TokenUrl = "https://oauth2.googleapis.com/token"
    }
}
```
[chapter-file-end]: #

### Check your understanding

Race two SyncYomi writes and two Drive lock creations with fixtures. Confirm conflict recovery without deleting local-only state or releasing another device's live lock.
[chapter-content-end]: #


## Step 6: add automatic and manual triggers

Implement six switches: chapter read/open, episode seen/open, app start/resume. Defaults are off and device-local. The coordinator debounces content events 5 seconds and lifecycle events 1 second, keeps runs at least 60 seconds apart and coalesces pending requests. Repository hooks respect incognito and actual unread→read transitions. Manual Sync/Upload/Download and periodic scheduling all route through the correct provider.

[chapter-content-start]: #
### Follow the code

Triggers request a sync; they do not each launch an unrelated transfer. Content/lifecycle debounce windows and a minimum interval coalesce work while preserving pending requests. Defaults stay off and device-local. Repository events distinguish a real unread-to-read transition from another progress save, and incognito suppresses the applicable automatic path. Manual actions and periodic work still route through the selected provider.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncTriggerCoordinator.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncTriggerCoordinator.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncTriggerCoordinator.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncTriggerCoordinator.kt).

This coordinator is the single policy boundary for debouncing, minimum intervals and pending work. Keep its owner/cancellation behavior so stale account events cannot start later rounds.

The implementation below defines `SyncTriggerKind`, `read`, `opened`, `DbSyncTriggerPreferences.enabled`, `SyncTriggerCoordinator`, `onTrigger`, `work`.

The source describes its contract as:

> Runs \[runSync\] (the scheduler's provider-agnostic `PeriodicTaskRunner.sync()`) for enabled triggers. One worker in \[scope\]: bursts coalesce into one run after the debounce, a trigger during a run queues at most one follow-up, and runs are at least \[minIntervalMillis\] apart. Cancelling \[scope\] drops pending runs.

Cross-chapter imports used by this file: [`DbItemType`](../chapters/02-domain-and-settings-models.md), [`DbSyncTriggerPreferences`](../chapters/02-domain-and-settings-models.md), [`YokanDatabase`](../chapters/03-persistence-and-migrations.md), [`AppLogger`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSyncTriggerPreferences
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.logging.AppLogger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull

/** Animetail SyncTriggerOptions events. */
enum class SyncTriggerKind {
    ChapterRead, ChapterOpen, EpisodeSeen, EpisodeOpen, AppStart, AppResume;

    companion object {
        fun read(type: DbItemType) = if (type == DbItemType.Anime) EpisodeSeen else ChapterRead
        fun opened(type: DbItemType) = if (type == DbItemType.Anime) EpisodeOpen else ChapterOpen
    }
}

fun DbSyncTriggerPreferences.enabled(kind: SyncTriggerKind): Boolean = when (kind) {
    SyncTriggerKind.ChapterRead -> onChapterRead
    SyncTriggerKind.ChapterOpen -> onChapterOpen
    SyncTriggerKind.EpisodeSeen -> onEpisodeSeen
    SyncTriggerKind.EpisodeOpen -> onEpisodeOpen
    SyncTriggerKind.AppStart -> onAppStart
    SyncTriggerKind.AppResume -> onAppResume
}

/**
 * Runs [runSync] (the scheduler's provider-agnostic `PeriodicTaskRunner.sync()`) for enabled triggers.
 * One worker in [scope]: bursts coalesce into one run after the debounce, a trigger during a run queues at
 * most one follow-up, and runs are at least [minIntervalMillis] apart. Cancelling [scope] drops pending runs.
 */
class SyncTriggerCoordinator(
    private val database: YokanDatabase,
    private val scope: CoroutineScope,
    private val eventDebounceMillis: Long = 5_000,
    private val lifecycleDebounceMillis: Long = 1_000,
    private val minIntervalMillis: Long = 60_000,
    private val runSync: suspend () -> Unit,
) {
    /** Conflated: each element is the debounce window requested by the latest trigger. */
    private val requests = Channel<Long>(Channel.CONFLATED)

    init {
        scope.launch { work() }
    }

    /** Never throws; safe from any thread. */
    fun onTrigger(kind: SyncTriggerKind) {
        catchingNonCancellation {
            if (!database.settings().features.syncTriggers.enabled(kind)) return
            val preference = database.syncPreferences().firstOrNull()
            if (preference?.syncOn != true || preference.authToken.isNullOrBlank()) return
            requests.trySend(if (kind == SyncTriggerKind.AppStart || kind == SyncTriggerKind.AppResume) lifecycleDebounceMillis else eventDebounceMillis)
        }.onFailure { AppLogger.warn("Sync trigger $kind ignored: ${it.message.orEmpty()}") }
    }

    private suspend fun work() {
        while (true) {
            var window = requests.receive()
            // Each new trigger restarts the quiet window.
            while (true) window = withTimeoutOrNull(window) { requests.receive() } ?: break
            catchingNonCancellation { runSync() }
                .onFailure { AppLogger.warn("Triggered sync failed: ${it.message.orEmpty()}") }
            delay(minIntervalMillis)
        }
    }
}
```
[chapter-file-end]: #

### Check your understanding

Emit a burst of chapter events, then log out before the debounce expires. Verify no old-account sync starts and pending work follows the reference policy.
[chapter-content-end]: #


[chapter-content-start]: #
## Recreate the tests and verify the chapter

Recreate identity/outbox/acknowledgement, mapper, provider, account lease and trigger fixtures. Run controlled two-device simulations for edits during upload, epoch reset, SyncYomi precondition failures and Drive lock races. Live Hub/SyncYomi/Drive, OAuth and browser CORS/ETag behavior remain separate integration checks.

These are source tests to reproduce and run in your reconstruction. Their inclusion here is not a claim that application/native/device tests were executed while writing the guide.

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/DeviceLocalSettingsTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/DeviceLocalSettingsTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/DeviceLocalSettingsTest.kt).

The implementation below defines `DeviceLocalSettingsTest`, `DbSettings.fields`, `restoreKeepsEveryDeviceLocalFieldFromCurrentDevice`, `syncOutboxExcludesTheSameDeviceLocalFields`, `hubPullKeepsDeviceLocalFieldsAnOlderClientPushed`.

The source describes its contract as:

> Another device's settings with every device-local field set away from \[thisDevice\].

Read the setup, action and assertions in these cases before implementing their production paths:

- `restoreKeepsEveryDeviceLocalFieldFromCurrentDevice`
- `syncOutboxExcludesTheSameDeviceLocalFields`
- `hubPullKeepsDeviceLocalFieldsAnOlderClientPushed`

Cross-chapter imports used by this file: [`DbCookie`](../chapters/02-domain-and-settings-models.md), [`DbChapterReleasePreference`](../chapters/02-domain-and-settings-models.md), [`DbLocalFolder`](../chapters/02-domain-and-settings-models.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`DbUpdateError`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.database.sync

import eu.friedcutlet.yokan.database.DbCookie
import eu.friedcutlet.yokan.database.DbChapterReleasePreference
import eu.friedcutlet.yokan.database.DbLocalFolder
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.DbUpdateError
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonObject
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue

class DeviceLocalSettingsTest {
    private val deviceLocal = SyncPaths.excluded(SyncPaths.KIND_SETTINGS)

    private val thisDevice = DbSettings(
        id = 1,
        downloadLocation = "/storage/emulated/0/Yokan",
        jrePath = "/usr/lib/jvm",
        themeIsDark = false,
    )

    /** Another device's settings with every device-local field set away from [thisDevice]. */
    private val otherDevice = DbSettings(
        id = 2,
        syncIdentityVersion = 1,
        localFolders = listOf("/mnt/usb"),
        namedLocalFolders = listOf(DbLocalFolder(name = "USB", path = "/mnt/usb")),
        downloadLocalFolderName = "USB",
        askDownloadDestination = false,
        downloadLocation = "C:/Yokan",
        autoBackupLocation = "C:/Backups",
        themeSeedImagePath = "C:/wallpaper.png",
        androidProxyServer = "127.0.0.1:1080",
        cloudflareBypassProxyUrl = "http://127.0.0.1:8191",
        jrePath = "C:/jdk",
        extensionServerPath = "C:/server.jar",
        btServerAddress = "10.0.0.2",
        btServerPort = 8090,
        desktopCloseToTray = true,
        desktopLaunchAtLogin = true,
        cookiesList = listOf(DbCookie(host = "example.org", cookie = "session=1")),
        metadataServerToken = "secret",
        features = eu.friedcutlet.yokan.database.DbFeaturePreferences(home = eu.friedcutlet.yokan.database.DbHomePreferences(tmdbReadAccessToken = "device-secret",
            sourceFeeds = listOf(eu.friedcutlet.yokan.database.DbHomeSourceFeed(42))),
            externalDownloads = eu.friedcutlet.yokan.database.DbExternalDownloads(eu.friedcutlet.yokan.database.PreferredDownloader.Aria2, "https://aria.example.org/jsonrpc", "device-rpc-secret", "/downloads")),
        updateErrors = listOf(DbUpdateError(mangaId = 1, name = "Title", error = "Host not found")),
        enableLogs = true,
        enableFileLogging = true,
        developerMode = true,
        customHubServers = listOf("http://192.168.1.5:8080"),
        chapterReleasePreferences = listOf(DbChapterReleasePreference(scanlatorPriority = listOf("group b"), skipDuplicateReleases = true)),
        automaticReaderLayout = true,
        readerHoldToScroll = true,
        einkMode = true,
        einkPreset = eu.friedcutlet.yokan.database.DbEinkPreset.KoboSage,
        einkRefreshEveryPages = 1,
        einkOptimizeDownloads = true,
        automaticReaderLayouts = listOf(eu.friedcutlet.yokan.database.DbAutomaticReaderLayout(1)),
        themeIsDark = true,
    )

    private fun DbSettings.fields(): JsonObject =
        SyncPaths.json.encodeToJsonElement(DbSettings.serializer(), this).jsonObject

    @Test
    fun restoreKeepsEveryDeviceLocalFieldFromCurrentDevice() {
        val here = thisDevice.fields()
        val there = otherDevice.fields()
        for (key in deviceLocal) assertNotEquals(here[key], there[key], "fixture must differ on $key")

        val restored = preserveDeviceLocalSettings(current = thisDevice, incoming = otherDevice).fields()

        for (key in deviceLocal) assertEquals(here[key], restored[key], "restore overwrote device-local $key")
        assertEquals(there["themeIsDark"], restored["themeIsDark"], "shared settings still come from the backup")
    }

    @Test
    fun syncOutboxExcludesTheSameDeviceLocalFields() {
        val hub = DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubEpoch = 1)
        val db = InMemoryYokanDatabase(emptySnapshot(thisDevice).copy(syncPreferences = listOf(hub)))

        db.updateSettings(otherDevice)

        val paths = db.outbox()
            .filter { it.kind == SyncPaths.KIND_SETTINGS }
            .map { it.path.substringBefore('.') }
        assertTrue("themeIsDark" in paths, "shared settings are still recorded")
        assertTrue(paths.none { it in deviceLocal }, "device-local fields leaked into the outbox: $paths")
    }

    @Test
    fun hubPullKeepsDeviceLocalFieldsAnOlderClientPushed() {
        val here = thisDevice.fields()
        val legacyHubDoc = otherDevice.fields()

        val pulled = SyncPaths.applyIncoming(SyncPaths.KIND_SETTINGS, here, legacyHubDoc, SyncPaths.SETTINGS_ID)

        for (key in deviceLocal - "id") assertEquals(here[key], pulled[key], "hub pull overwrote device-local $key")
        assertEquals(legacyHubDoc["themeIsDark"], pulled["themeIsDark"], "shared settings still come from the hub")
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/OutboxTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/OutboxTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/OutboxTest.kt).

The implementation below defines `OutboxTest`, `loggedIn`, `nothingIsRecordedWithoutALoggedInHubAndUnsendableOpsAreDropped`, `newOutboxOpsUseTheActiveHubEpoch`, `insertsRecordEveryFieldAndUpdatesOnlyTheChangedPath`, `deleteBecomesTombstoneOpAndRemoteApplyIsSilent`, `settingsDiffIsKeyedPerTitle`, `removeOutboxOnlyDropsOpsThatWereSent`, `batchEmitsOneSnapshot`, `oneTableMutationReusesUnchangedSnapshotLists` and 2 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

- `nothingIsRecordedWithoutALoggedInHubAndUnsendableOpsAreDropped`
- `newOutboxOpsUseTheActiveHubEpoch`
- `insertsRecordEveryFieldAndUpdatesOnlyTheChangedPath`
- `deleteBecomesTombstoneOpAndRemoteApplyIsSilent`
- `settingsDiffIsKeyedPerTitle`
- `removeOutboxOnlyDropsOpsThatWereSent`
- `batchEmitsOneSnapshot`
- `oneTableMutationReusesUnchangedSnapshotLists`
- `aMangaEditIsPublishedEvenWhenNothingElseChanges`
- `concurrentMutationsKeepRowsAndOutboxSequencesConsistent`

Cross-chapter imports used by this file: [`DbCategory`](../chapters/02-domain-and-settings-models.md), [`DbItemType`](../chapters/02-domain-and-settings-models.md), [`DbManga`](../chapters/02-domain-and-settings-models.md), [`DbOutboxOp`](../chapters/02-domain-and-settings-models.md), [`DbPersonalReaderMode`](../chapters/02-domain-and-settings-models.md), [`DbReaderMode`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.database.sync

import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbOutboxOp
import eu.friedcutlet.yokan.database.DbPersonalReaderMode
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotSame
import kotlin.test.assertSame
import kotlin.test.assertTrue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest

class OutboxTest {
    private fun loggedIn() = InMemoryYokanDatabase(
        emptySnapshot().copy(
            syncPreferences = listOf(DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubEpoch = 1)),
        ),
    )

    @Test
    fun nothingIsRecordedWithoutALoggedInHubAndUnsendableOpsAreDropped() {
        val db = InMemoryYokanDatabase(
            emptySnapshot().copy(
                outbox = listOf(
                    DbOutboxOp(SyncPaths.KIND_MANGA, 1, "name", "\"never sent\"", hlc = 1, seq = 1),
                    DbOutboxOp(SyncPaths.KIND_MANGA, 2, "name", "\"pending since logout\"", hlc = 2, seq = 2, epoch = 3),
                ),
            ),
        )
        assertEquals(listOf(2L), db.outbox().map { it.id }, "epoch-0 ops are dropped, ops of a real hub epoch kept")

        val manga = db.upsertManga(DbManga(name = "T", link = "/t", sourceId = 1))
        db.updateSettings(db.settings().copy(themeIsDark = !db.settings().themeIsDark))
        db.removeManga(manga.id)
        assertEquals(listOf(2L), db.outbox().map { it.id }, "no hub: the first sync seeds full state instead")

        db.upsertSyncPreference(DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubEpoch = 3))
        val next = db.upsertManga(DbManga(name = "T2", link = "/t2", sourceId = 1))
        assertTrue(db.outbox().any { it.id == next.id && it.path == "name" && it.epoch == 3 })
    }

    @Test
    fun newOutboxOpsUseTheActiveHubEpoch() {
        val db = InMemoryYokanDatabase(
            emptySnapshot().copy(
                syncPreferences = listOf(
                    DbSyncPreference(syncId = 2, server = "https://other.test", authToken = "other", hubEpoch = 99),
                    DbSyncPreference(syncId = 3, server = "cloud://drive", authToken = "cloud", syncOn = true, hubEpoch = 88),
                    DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "hub", syncOn = true, hubEpoch = 7),
                ),
            ),
        )

        db.upsertManga(DbManga(name = "T", link = "/t", sourceId = 1))

        assertTrue(db.outbox().isNotEmpty())
        assertTrue(db.outbox().all { it.epoch == 7 })
    }

    @Test
    fun insertsRecordEveryFieldAndUpdatesOnlyTheChangedPath() {
        val db = loggedIn()
        val saved = db.upsertManga(DbManga(name = "T", link = "/t", sourceId = 1))
        assertEquals(SyncIds.forManga(saved), saved.id, "new rows get a stable id")
        val first = db.outbox()
        assertTrue(first.any { it.kind == SyncPaths.KIND_MANGA && it.id == saved.id && it.path == "name" && it.value == "\"T\"" })

        db.upsertManga(saved.copy(favorite = true))
        val delta = db.outbox().filter { it.seq > first.maxOf { o -> o.seq } }
        assertEquals(listOf("favorite"), delta.map { it.path })
        assertEquals("true", delta.single().value)

        // Coalesced: the second write to the same path replaces the first row
        db.upsertManga(saved.copy(favorite = false))
        assertEquals(1, db.outbox().count { it.path == "favorite" })
        assertEquals("false", db.outbox().single { it.path == "favorite" }.value)
        assertTrue(db.outbox().zipWithNext().all { (a, b) -> a.seq < b.seq }, "outbox is ordered by seq")
    }

    @Test
    fun deleteBecomesTombstoneOpAndRemoteApplyIsSilent() {
        val db = loggedIn()
        val cat = db.upsertCategory(DbCategory(name = "Reading", forItemType = DbItemType.Manga))
        db.removeCategory(cat.id)
        val tomb = db.outbox().last()
        assertEquals(SyncPaths.DELETED, tomb.path)
        assertEquals("true", tomb.value)

        val before = db.outbox().size
        db.applyRemote { db.upsertManga(DbManga(name = "from hub", link = "/h", sourceId = 2)) }
        assertEquals(before, db.outbox().size, "hub writes are not echoed")
    }

    @Test
    fun settingsDiffIsKeyedPerTitle() {
        val db = loggedIn()
        val s0 = db.settings()
        db.updateSettings(s0.copy(personalReaderModeList = listOf(DbPersonalReaderMode(111, DbReaderMode.Vertical))))
        db.updateSettings(db.settings().copy(personalReaderModeList = listOf(DbPersonalReaderMode(111, DbReaderMode.Vertical), DbPersonalReaderMode(222, DbReaderMode.Webtoon))))
        val paths = db.outbox().filter { it.kind == SyncPaths.KIND_SETTINGS }.map { it.path }
        assertEquals(listOf("personalReaderModeList.111", "personalReaderModeList.222"), paths)

        // device-local settings never produce ops
        db.updateSettings(db.settings().copy(jrePath = "/opt/jdk"))
        assertEquals(paths, db.outbox().filter { it.kind == SyncPaths.KIND_SETTINGS }.map { it.path })
    }

    @Test
    fun removeOutboxOnlyDropsOpsThatWereSent() {
        val db = loggedIn()
        val m = db.upsertManga(DbManga(name = "T", link = "/t", sourceId = 1))
        val sent = db.outbox()
        db.upsertManga(m.copy(name = "T2")) // rewrites the "name" path with a newer seq
        db.removeOutbox(sent)
        assertEquals(listOf("name"), db.outbox().map { it.path })
        assertEquals("\"T2\"", db.outbox().single().value)
    }

    @Test
    fun batchEmitsOneSnapshot() {
        val db = InMemoryYokanDatabase(emptySnapshot())
        var emissions = 0
        val start = db.snapshots().value
        db.batch {
            db.upsertManga(DbManga(name = "A", link = "/a", sourceId = 1))
            db.upsertManga(DbManga(name = "B", link = "/b", sourceId = 1))
            if (db.snapshots().value !== start) emissions++
        }
        assertEquals(0, emissions, "nothing emitted inside the batch")
        assertEquals(2, db.snapshots().value.mangas.size)
    }

    @Test
    fun oneTableMutationReusesUnchangedSnapshotLists() {
        val db = InMemoryYokanDatabase(emptySnapshot())
        val before = db.snapshots().value

        db.upsertManga(DbManga(name = "A", link = "/a", sourceId = 1))

        val after = db.snapshots().value
        assertNotSame(before.mangas, after.mangas)
        assertSame(before.chapters, after.chapters)
        assertSame(before.downloads, after.downloads)
    }

    @Test
    fun aMangaEditIsPublishedEvenWhenNothingElseChanges() {
        val db = InMemoryYokanDatabase(emptySnapshot())
        val manga = db.upsertManga(DbManga(name = "A", link = "/a", sourceId = 1))

        db.upsertManga(manga.copy(favorite = true))

        assertTrue(db.snapshots().value.mangas.single().favorite, "snapshot flows drop values equal to the current one")
    }

    @Test
    fun concurrentMutationsKeepRowsAndOutboxSequencesConsistent() = runTest {
        val db = loggedIn()
        coroutineScope {
            repeat(4) { worker ->
                launch(Dispatchers.Default) {
                    repeat(25) { index ->
                        val id = worker * 25L + index + 1L
                        db.upsertManga(DbManga(id = id, name = "M$id", link = "/$id", sourceId = 1))
                    }
                }
            }
        }

        assertEquals(100, db.mangas().size)
        val sequences = db.outbox().map { it.seq }
        assertEquals(sequences.size, sequences.distinct().size)
        assertEquals(sequences.sorted(), sequences)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/SyncIdentityMigrationTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/SyncIdentityMigrationTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/SyncIdentityMigrationTest.kt).

The implementation below defines `SyncIdentityMigrationTest`, `rewritesIdsAndEveryForeignKey`, `duplicatesCollapseOntoTheNewestRow`, `ensureRunsOnceAndStampsTheVersion`, `ensurePropagatesReplacementConflictAndPreservesConcurrentEdit`, `InjectingDatabase`, `replaceAll`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `rewritesIdsAndEveryForeignKey`
- `duplicatesCollapseOntoTheNewestRow`
- `ensureRunsOnceAndStampsTheVersion`
- `ensurePropagatesReplacementConflictAndPreservesConcurrentEdit`

Cross-chapter imports used by this file: [`DbCategory`](../chapters/02-domain-and-settings-models.md), [`DbChapter`](../chapters/02-domain-and-settings-models.md), [`DbChapterReleasePreference`](../chapters/02-domain-and-settings-models.md), [`DbHistory`](../chapters/02-domain-and-settings-models.md), [`DbItemType`](../chapters/02-domain-and-settings-models.md), [`DbManga`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.database.sync

import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbChapterReleasePreference
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbPersonalReaderMode
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.SnapshotReplacementConflictException
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.database.emptySnapshot
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue

class SyncIdentityMigrationTest {
    @Test
    fun rewritesIdsAndEveryForeignKey() {
        val legacy = emptySnapshot(DbSettings(personalReaderModeList = listOf(DbPersonalReaderMode(1, DbReaderMode.Webtoon)),
            chapterReleasePreferences = listOf(DbChapterReleasePreference(), DbChapterReleasePreference(1, listOf("Preferred"), true)),
            automaticReaderLayouts = listOf(eu.friedcutlet.yokan.database.DbAutomaticReaderLayout(1)))).copy(
            mangas = listOf(DbManga(id = 1, name = "T", link = "/t", sourceId = 5, categories = listOf(1), itemType = DbItemType.Manga)),
            categories = listOf(DbCategory(id = 1, name = "Reading", forItemType = DbItemType.Manga)),
            chapters = listOf(DbChapter(id = 1, mangaId = 1, url = "/t/1"), DbChapter(id = 2, mangaId = 1, url = "/t/2")),
            histories = listOf(DbHistory(id = 1, mangaId = 1, chapterId = 2, itemType = DbItemType.Manga)),
            tracks = listOf(DbTrack(id = 1, mangaId = 1, syncId = 2, status = DbTrackStatus.Reading)),
        )
        val out = SyncIdentityMigration.remap(legacy)

        val manga = out.mangas.single()
        assertEquals(SyncIds.manga(DbItemType.Manga, "5", "/t"), manga.id)
        val category = out.categories.single()
        assertNotEquals(1L, category.id)
        assertEquals(listOf(category.id), manga.categories)

        val chapters = out.chapters.sortedBy { it.url }
        assertTrue(chapters.all { it.mangaId == manga.id })
        assertEquals(SyncIds.chapter(manga.id, "/t/1"), chapters[0].id)
        assertEquals(SyncIds.chapter(manga.id, "/t/2"), chapters[1].id)

        val history = out.histories.single()
        assertEquals(manga.id, history.mangaId)
        assertEquals(chapters[1].id, history.chapterId)
        assertEquals(SyncIds.history(manga.id), history.id)

        assertEquals(SyncIds.track(manga.id, 2), out.tracks.single().id)
        assertEquals(manga.id, out.settings.personalReaderModeList!!.single().mangaId)
        assertEquals(listOf(null, manga.id), out.settings.chapterReleasePreferences.map { it.mangaId })
        assertEquals(manga.id, out.settings.automaticReaderLayouts.single().mangaId)
    }

    @Test
    fun duplicatesCollapseOntoTheNewestRow() {
        val legacy = emptySnapshot().copy(
            mangas = listOf(
                DbManga(id = 1, name = "old", link = "/t", sourceId = 5, updatedAt = 10),
                DbManga(id = 2, name = "new", link = "/t", sourceId = 5, updatedAt = 20),
            ),
        )
        val out = SyncIdentityMigration.remap(legacy)
        assertEquals("new", out.mangas.single().name)
    }

    @Test
    fun ensureRunsOnceAndStampsTheVersion() {
        val db = InMemoryYokanDatabase(emptySnapshot().copy(mangas = listOf(DbManga(id = 1, name = "T", link = "/t", sourceId = 5))))
        SyncIdentityMigration.ensure(db)
        assertEquals(SyncIdentityMigration.VERSION, db.settings().syncIdentityVersion)
        val id = db.mangas().single().id
        assertEquals(SyncIds.manga(DbItemType.Manga, "5", "/t"), id)
        assertTrue(db.outbox().isEmpty(), "a migration is not a change to sync")
        SyncIdentityMigration.ensure(db)
        assertEquals(id, db.mangas().single().id)
    }

    @Test
    fun ensurePropagatesReplacementConflictAndPreservesConcurrentEdit() {
        val manga = DbManga(id = 1, name = "T", link = "/t", sourceId = 5)
        val backing = InMemoryYokanDatabase(emptySnapshot().copy(mangas = listOf(manga)))
        val db = InjectingDatabase(backing) {
            backing.upsertManga(manga.copy(name = "Concurrent edit"))
        }

        assertFailsWith<SnapshotReplacementConflictException> {
            SyncIdentityMigration.ensure(db)
        }
        assertEquals("Concurrent edit", backing.mangas().single().name)
        assertEquals(0, backing.settings().syncIdentityVersion)
    }

    private class InjectingDatabase(
        private val delegate: InMemoryYokanDatabase,
        private val beforeReplacement: () -> Unit,
    ) : YokanDatabase by delegate {
        override fun replaceAll(
            snapshot: YokanDatabaseSnapshot,
            expectedSnapshot: YokanDatabaseSnapshot?,
        ) {
            beforeReplacement()
            delegate.replaceAll(snapshot, expectedSnapshot)
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/SyncIdsTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/SyncIdsTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/SyncIdsTest.kt).

The implementation below defines `SyncIdsTest`, `stableIdsArePositiveDeterministicAndDistinct`, `mangaIdComesFromSourceAndLink`, `chapterIdFollowsMangaAndUrlOrArchivePath`, `randomIdsAreNeverZeroOrNegative`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `stableIdsArePositiveDeterministicAndDistinct`
- `mangaIdComesFromSourceAndLink`
- `chapterIdFollowsMangaAndUrlOrArchivePath`
- `randomIdsAreNeverZeroOrNegative`

Cross-chapter imports used by this file: [`DbChapter`](../chapters/02-domain-and-settings-models.md), [`DbItemType`](../chapters/02-domain-and-settings-models.md), [`DbManga`](../chapters/02-domain-and-settings-models.md), [`Manga`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.database.sync

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.domain.Manga
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue

class SyncIdsTest {
    @Test
    fun stableIdsArePositiveDeterministicAndDistinct() {
        val a = SyncIds.stable("manga|Manga|1|/x")
        assertTrue(a > 0)
        assertEquals(a, SyncIds.stable("manga|Manga|1|/x"))
        assertNotEquals(a, SyncIds.stable("manga|Manga|1|/y"))
        assertNotEquals(a, SyncIds.stable("manga|Anime|1|/x"))
    }

    @Test
    fun mangaIdComesFromSourceAndLink() {
        val m = DbManga(name = "T", link = "/series/abc", sourceId = 42, itemType = DbItemType.Manga)
        assertEquals(SyncIds.manga(DbItemType.Manga, "42", "/series/abc"), SyncIds.forManga(m))
        assertEquals(SyncIds.forManga(m), SyncIds.forManga(m.copy(name = "renamed", favorite = true)))
        assertNull(SyncIds.forManga(DbManga(name = "no link")))
        // source name is the fallback key for rows without a sourceId
        assertEquals(SyncIds.manga(DbItemType.Manga, "MangaDex", "/s"), SyncIds.forManga(DbManga(link = "/s", source = "MangaDex")))
    }

    @Test
    fun chapterIdFollowsMangaAndUrlOrArchivePath() {
        val mangaId = SyncIds.stable("m")
        assertEquals(SyncIds.chapter(mangaId, "/c/1"), SyncIds.forChapter(DbChapter(mangaId = mangaId, url = "/c/1")))
        assertEquals(SyncIds.chapter(mangaId, "vol1.cbz"), SyncIds.forChapter(DbChapter(mangaId = mangaId, archivePath = "vol1.cbz")))
        assertNull(SyncIds.forChapter(DbChapter(mangaId = null, url = "/c/1")))
        assertNull(SyncIds.forChapter(DbChapter(mangaId = mangaId)))
    }

    @Test
    fun randomIdsAreNeverZeroOrNegative() {
        repeat(1000) { assertTrue(SyncIds.random() > 0) }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/SyncPathsTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/SyncPathsTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/database/sync/SyncPathsTest.kt).

The implementation below defines `SyncPathsTest`, `nativeHubDocumentsRetainLicensedAndUpcomingStatuses`, `releasePreferencesStayLocalThroughHubDocumentsAndIncomingSettings`, `mangaCategoriesTravelAsIdSetAndCustomCoverStaysLocal`, `keyedSettingsListsBecomeMapsOfWholeElements`, `diffIsPathLevelAndDescendsIntoKeyedFields`, `diffAgainstNothingListsEveryPresentField`, `applyIncomingKeepsLocalOnlyFieldsAndDropsAbsentSyncedOnes`, `chapterDownloadMarkStaysOnTheDeviceThatDownloaded`, `pull` and 1 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

- `nativeHubDocumentsRetainLicensedAndUpcomingStatuses`
- `releasePreferencesStayLocalThroughHubDocumentsAndIncomingSettings`
- `mangaCategoriesTravelAsIdSetAndCustomCoverStaysLocal`
- `keyedSettingsListsBecomeMapsOfWholeElements`
- `diffIsPathLevelAndDescendsIntoKeyedFields`
- `diffAgainstNothingListsEveryPresentField`
- `applyIncomingKeepsLocalOnlyFieldsAndDropsAbsentSyncedOnes`
- `chapterDownloadMarkStaysOnTheDeviceThatDownloaded`
- `overlayPutsPendingLocalValuesBack`

Cross-chapter imports used by this file: [`DbChapter`](../chapters/02-domain-and-settings-models.md), [`DbChapterReleasePreference`](../chapters/02-domain-and-settings-models.md), [`DbManga`](../chapters/02-domain-and-settings-models.md), [`DbOutboxOp`](../chapters/02-domain-and-settings-models.md), [`DbPersonalReaderMode`](../chapters/02-domain-and-settings-models.md), [`DbReaderMode`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.database.sync

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbChapterReleasePreference
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbOutboxOp
import eu.friedcutlet.yokan.database.DbPersonalReaderMode
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSourcePreference
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue

class SyncPathsTest {
    @Test
    fun nativeHubDocumentsRetainLicensedAndUpcomingStatuses() {
        for (status in listOf(eu.friedcutlet.yokan.database.DbStatus.Licensed, eu.friedcutlet.yokan.database.DbStatus.Upcoming)) {
            val manga = DbManga(id = 1, status = status)
            val doc = SyncPaths.doc(SyncPaths.KIND_MANGA, DbManga.serializer(), manga)
            assertEquals(JsonPrimitive(status.name), doc["status"])
            val restored = SyncPaths.json.decodeFromJsonElement(DbManga.serializer(), SyncPaths.fromDoc(SyncPaths.KIND_MANGA, doc))
            assertEquals(status, restored.status)
        }
    }

    @Test
    fun releasePreferencesStayLocalThroughHubDocumentsAndIncomingSettings() {
        val local = DbSettings(chapterReleasePreferences = listOf(DbChapterReleasePreference(100, listOf("Preferred"), true)))
        val doc = SyncPaths.doc(SyncPaths.KIND_SETTINGS, DbSettings.serializer(), local)
        assertNull(doc["chapterReleasePreferences"])
        val before = SyncPaths.doc(SyncPaths.KIND_SETTINGS, DbSettings.serializer(), DbSettings())
        assertTrue(SyncPaths.diff(SyncPaths.KIND_SETTINGS, before, doc).isEmpty())
        val incoming = DbSettings(chapterReleasePreferences = listOf(DbChapterReleasePreference(100, listOf("Unrelated"))))
        assertEquals(local.chapterReleasePreferences, preserveDeviceLocalSettings(local, incoming).chapterReleasePreferences)
    }

    private val json = SyncPaths.json

    @Test
    fun mangaCategoriesTravelAsIdSetAndCustomCoverStaysLocal() {
        val m = DbManga(id = 5, name = "T", categories = listOf(9, 3), customCoverImage = byteArrayOf(1, 2, 3))
        val doc = SyncPaths.doc(SyncPaths.KIND_MANGA, DbManga.serializer(), m)
        assertEquals(setOf("3", "9"), doc["categories"]!!.jsonObject.keys)
        assertNull(doc["customCoverImage"])
        assertNull(doc["id"], "the entity id is the key, not a field")

        val back = SyncPaths.fromDoc(SyncPaths.KIND_MANGA, doc)
        assertEquals("[3,9]", back["categories"].toString())
    }

    @Test
    fun keyedSettingsListsBecomeMapsOfWholeElements() {
        val s = DbSettings(
            personalReaderModeList = listOf(DbPersonalReaderMode(111, DbReaderMode.Vertical), DbPersonalReaderMode(222, DbReaderMode.Webtoon)),
            sourcePreferences = listOf(DbSourcePreference(7, "lang", "en")),
            cookiesList = null,
        )
        val doc = SyncPaths.doc(SyncPaths.KIND_SETTINGS, DbSettings.serializer(), s)
        val modes = doc["personalReaderModeList"]!!.jsonObject
        assertEquals(setOf("111", "222"), modes.keys)
        assertEquals("111", modes["111"]!!.jsonObject["mangaId"]!!.jsonPrimitive.content)
        assertEquals(setOf("7:lang"), doc["sourcePreferences"]!!.jsonObject.keys)
        assertNull(doc["cookiesList"])
        assertNull(doc["jrePath"], "device-local settings never leave the device")

        val restored = json.decodeFromJsonElement(DbSettings.serializer(), SyncPaths.fromDoc(SyncPaths.KIND_SETTINGS, doc))
        assertEquals(s.personalReaderModeList, restored.personalReaderModeList)
        assertEquals(s.sourcePreferences, restored.sourcePreferences)
    }

    @Test
    fun diffIsPathLevelAndDescendsIntoKeyedFields() {
        val before = SyncPaths.doc(SyncPaths.KIND_MANGA, DbManga.serializer(), DbManga(id = 1, name = "A", favorite = false, categories = listOf(1, 2)))
        val after = SyncPaths.doc(SyncPaths.KIND_MANGA, DbManga.serializer(), DbManga(id = 1, name = "A", favorite = true, categories = listOf(2, 3)))
        val changes = SyncPaths.diff(SyncPaths.KIND_MANGA, before, after).associate { it.path to it.value }
        assertEquals(setOf("favorite", "categories.1", "categories.3"), changes.keys)
        assertEquals(JsonPrimitive(true), changes["favorite"])
        assertNull(changes["categories.1"], "removed set member is a path delete")
        assertEquals(JsonPrimitive(true), changes["categories.3"])
    }

    @Test
    fun diffAgainstNothingListsEveryPresentField() {
        val after = SyncPaths.doc(SyncPaths.KIND_MANGA, DbManga.serializer(), DbManga(id = 1, name = "A"))
        val paths = SyncPaths.diff(SyncPaths.KIND_MANGA, null, after).map { it.path }
        assertTrue("name" in paths)
        assertTrue("favorite" in paths, "non-null defaults are explicit on the wire")
        assertFalse("link" in paths, "null fields are absent, not sent")
    }

    @Test
    fun applyIncomingKeepsLocalOnlyFieldsAndDropsAbsentSyncedOnes() {
        val local = json.encodeToJsonElement(DbManga.serializer(), DbManga(id = 1, name = "Old", author = "X", customCoverImage = byteArrayOf(9))).jsonObject
        val incoming = buildJsonObject { put("name", "New"); put("favorite", true) }
        val merged = json.decodeFromJsonElement(DbManga.serializer(), SyncPaths.applyIncoming(SyncPaths.KIND_MANGA, local, incoming, 1))
        assertEquals("New", merged.name)
        assertTrue(merged.favorite)
        assertNull(merged.author, "absent on the hub means removed")
        assertEquals(1L, merged.id)
        assertTrue(merged.customCoverImage!!.contentEquals(byteArrayOf(9)), "excluded fields stay local")
    }

    @Test
    fun chapterDownloadMarkStaysOnTheDeviceThatDownloaded() {
        val downloaded = DbChapter(id = 1, mangaId = 5, url = "/c/1", archivePath = "/data/Yokan/ch1.cbz", downloadSize = "3.1 MB")
        val doc = SyncPaths.doc(SyncPaths.KIND_CHAPTER, DbChapter.serializer(), downloaded)
        assertNull(doc["downloadSize"])
        assertEquals(JsonPrimitive(""), doc["archivePath"])
        val plain = SyncPaths.doc(SyncPaths.KIND_CHAPTER, DbChapter.serializer(), downloaded.copy(archivePath = "", downloadSize = null))
        assertTrue(SyncPaths.diff(SyncPaths.KIND_CHAPTER, plain, doc).isEmpty(), "finishing a download sends nothing")

        val localLibrary = DbChapter(id = 2, mangaId = 6, url = "Comics/T/ch.cbz", archivePath = "Comics/T/ch.cbz")
        assertEquals(JsonPrimitive("Comics/T/ch.cbz"), SyncPaths.doc(SyncPaths.KIND_CHAPTER, DbChapter.serializer(), localLibrary)["archivePath"])

        fun pull(local: DbChapter?, incoming: JsonObject) = json.decodeFromJsonElement(
            DbChapter.serializer(),
            SyncPaths.applyIncoming(SyncPaths.KIND_CHAPTER, local?.let { json.encodeToJsonElement(DbChapter.serializer(), it).jsonObject }, incoming, 1),
        )
        val read = pull(downloaded, SyncPaths.doc(SyncPaths.KIND_CHAPTER, DbChapter.serializer(), downloaded.copy(isRead = true, archivePath = "", downloadSize = null)))
        assertTrue(read.isRead)
        assertEquals("/data/Yokan/ch1.cbz" to "3.1 MB", read.archivePath to read.downloadSize, "a hub update keeps this device's download")

        val pushedByOlderClient = buildJsonObject { put("url", "/c/1"); put("archivePath", "/other/ch1"); put("downloadSize", "3.1 MB") }
        val elsewhere = pull(DbChapter(id = 1, mangaId = 5, url = "/c/1"), pushedByOlderClient)
        assertEquals("" to null, elsewhere.archivePath to elsewhere.downloadSize, "another device's download path is ignored")
        assertEquals("Comics/T/ch.cbz", pull(null, SyncPaths.doc(SyncPaths.KIND_CHAPTER, DbChapter.serializer(), localLibrary)).archivePath)
    }

    @Test
    fun overlayPutsPendingLocalValuesBack() {
        val doc = buildJsonObject { put("name", "Remote"); put("favorite", false) }
        val pending = listOf(
            DbOutboxOp(SyncPaths.KIND_MANGA, 1, "favorite", "true", 1, 1),
            DbOutboxOp(SyncPaths.KIND_MANGA, 1, "categories.7", "true", 2, 2),
        )
        val out = SyncPaths.overlay(doc, pending)
        assertEquals(JsonPrimitive(true), out["favorite"])
        assertEquals(JsonPrimitive(true), out["categories"]!!.jsonObject["7"])
        assertEquals(JsonPrimitive("Remote"), out["name"])
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/CloudBackupSyncServiceTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/CloudBackupSyncServiceTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/CloudBackupSyncServiceTest.kt).

The implementation below defines `CloudBackupSyncServiceTest`, `lateCloudCredentialsCannotCommitAfterOwnerRetirement`, `delayedCloudConnectCannotOverwriteChangedSyncConfiguration`, `overlappingConnectsKeepTheFirstCommittedAccount`, `lateCloudDownloadDoesNotStartRestoreAfterRetirement`, `lateCloudUploadDoesNotRecordSuccessAfterRetirement`, `connectStoresCloudProviderConfiguration`, `pushChangesUploadsBackupThroughProvider`, `restoreLatestBackupUsesNewestCloudObject`, `changedAccountDuringListingCannotDownloadOrRestore` and 35 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

- `lateCloudCredentialsCannotCommitAfterOwnerRetirement`
- `delayedCloudConnectCannotOverwriteChangedSyncConfiguration`
- `overlappingConnectsKeepTheFirstCommittedAccount`
- `lateCloudDownloadDoesNotStartRestoreAfterRetirement`
- `lateCloudUploadDoesNotRecordSuccessAfterRetirement`
- `connectStoresCloudProviderConfiguration`
- `pushChangesUploadsBackupThroughProvider`
- `restoreLatestBackupUsesNewestCloudObject`
- `changedAccountDuringListingCannotDownloadOrRestore`
- `changedAccountDuringExportCannotDispatchUpload`
- `accountChangesDuringDownloadCannotStartRestore`
- `cancelledCallerStillCancelsInsteadOfReportingAccountChange`
- `changedAccountInsideRestorePreparationIsRejectedBySnapshotGuard`
- `acceptedUploadCannotMarkAnotherAccountSynced`
- `unrelatedBookkeepingSurvivesAtomicSuccessUpdate`
- `missingSyncIdNeverFallsBackToAnotherAccount`
- The remaining 2 cases are included in the complete listing below.

Cross-chapter imports used by this file: [`InMemoryYokanDatabase`](../chapters/03-persistence-and-migrations.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`ProfileId`](../chapters/04-profiles-and-lifetimes.md), [`emptySnapshot`](../chapters/03-persistence-and-migrations.md), [`BackupExport`](../chapters/20-backup-and-restore.md), [`BackupFileEntry`](../chapters/20-backup-and-restore.md). Keep those contracts available as you connect this step.

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.backup.BackupExport
import eu.friedcutlet.yokan.services.backup.BackupFileEntry
import eu.friedcutlet.yokan.services.backup.BackupFormat
import eu.friedcutlet.yokan.services.backup.BackupOpenResult
import eu.friedcutlet.yokan.services.backup.BackupOptions
import eu.friedcutlet.yokan.services.backup.BackupPlan
import eu.friedcutlet.yokan.services.backup.BackupResult
import eu.friedcutlet.yokan.services.backup.BackupService
import eu.friedcutlet.yokan.services.backup.RestoreMode
import eu.friedcutlet.yokan.services.backup.RestorePreview
import eu.friedcutlet.yokan.services.backup.SafetySnapshot
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.cancel
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class CloudBackupSyncServiceTest {
    @Test
    fun lateCloudCredentialsCannotCommitAfterOwnerRetirement() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider()
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        provider.beforeValidate = { entered.complete(Unit); withContext(NonCancellable) { release.await() } }
        val raw = DefaultCloudBackupSyncService(database, StubBackupService(database), listOf(provider))
        val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
        val bound = ProfileSyncServices(ProfileId.Default, raw, raw, scope)
        val caller = launch { bound.cloud.connect(1, provider.descriptor.id, "account", "late-token") }
        entered.await(); parent.cancel(); release.complete(Unit); parent.join(); caller.join()
        assertTrue(database.syncPreferences().isEmpty())
        bound.sync.closeAndJoin()
    }

    @Test
    fun delayedCloudConnectCannotOverwriteChangedSyncConfiguration() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider()
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        provider.beforeValidate = { entered.complete(Unit); release.await() }
        val service = DefaultCloudBackupSyncService(database, StubBackupService(database), listOf(provider))
        var result: SyncLoginResult? = null
        val caller = launch { result = service.connect(1, provider.descriptor.id, "account", "old-token") }
        entered.await()
        val selected = DbSyncPreference(syncId = 1, server = "https://new-server.test", email = "new-account", authToken = "new-token")
        database.upsertSyncPreference(selected)
        release.complete(Unit); caller.join()
        assertFalse(requireNotNull(result).success)
        assertEquals(selected, database.syncPreferences().single())
    }

    @Test
    fun overlappingConnectsKeepTheFirstCommittedAccount() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider()
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        provider.beforeValidate = { connection -> if (connection.accessToken == "late-token") { entered.complete(Unit); release.await() } }
        val service = DefaultCloudBackupSyncService(database, StubBackupService(database), listOf(provider))
        var delayed: SyncLoginResult? = null
        val caller = launch { delayed = service.connect(1, provider.descriptor.id, "late-account", "late-token") }
        entered.await()
        assertTrue(service.connect(1, provider.descriptor.id, "current-account", "current-token").success)
        release.complete(Unit); caller.join()
        assertFalse(requireNotNull(delayed).success)
        assertEquals("current-token", database.syncPreferences().single().authToken)
        assertEquals("current-account", database.syncPreferences().single().email)
    }

    @Test
    fun lateCloudDownloadDoesNotStartRestoreAfterRetirement() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider(listOf(StoredObject("yokan-cloud-backup-test.json", byteArrayOf(1), 1)))
        val backup = StubBackupService(database)
        val raw = DefaultCloudBackupSyncService(database, backup, listOf(provider))
        raw.connect(1, provider.descriptor.id, "account", "token")
        val prior = database.syncPreferences().single()
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        provider.beforeGet = { entered.complete(Unit); withContext(NonCancellable) { release.await() } }
        val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
        val bound = ProfileSyncServices(ProfileId.Default, raw, raw, scope)
        val caller = launch { bound.cloud.restoreLatestBackup(1) }
        entered.await(); parent.cancel(); release.complete(Unit); parent.join(); caller.join()
        assertEquals(0, backup.restores)
        assertEquals(prior, database.syncPreferences().single())
        bound.sync.closeAndJoin()
    }

    @Test
    fun lateCloudUploadDoesNotRecordSuccessAfterRetirement() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider()
        val raw = DefaultCloudBackupSyncService(database, StubBackupService(database), listOf(provider))
        raw.connect(1, provider.descriptor.id, "account", "token")
        val prior = database.syncPreferences().single()
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        provider.afterPut = { entered.complete(Unit); withContext(NonCancellable) { release.await() } }
        val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
        val bound = ProfileSyncServices(ProfileId.Default, raw, raw, scope)
        val caller = launch { bound.cloud.uploadBackup(1, BackupOptions()) }
        entered.await(); parent.cancel(); release.complete(Unit); parent.join(); caller.join()
        assertEquals(1, provider.uploads.size) // A remote upload already accepted cannot be undone by cancellation.
        assertEquals(prior, database.syncPreferences().single())
        bound.sync.closeAndJoin()
    }

    @Test
    fun connectStoresCloudProviderConfiguration() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider()
        val service = DefaultCloudBackupSyncService(database, StubBackupService(database), listOf(provider))

        val result = service.connect(syncId = 1L, providerId = provider.descriptor.id, accountLabel = "user@example.com", accessToken = "token")

        assertTrue(result.success)
        val preference = database.syncPreferences().single()
        assertEquals(cloudServerUri(provider.descriptor.id), preference.server)
        assertEquals("user@example.com", preference.email)
        assertEquals("token", preference.authToken)
        assertTrue(preference.syncOn)
    }

    @Test
    fun pushChangesUploadsBackupThroughProvider() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider()
        val service = DefaultCloudBackupSyncService(database, StubBackupService(database), listOf(provider))
        service.connect(syncId = 1L, providerId = provider.descriptor.id, accountLabel = null, accessToken = "token")

        val result = service.pushChanges(1L)

        assertEquals(1, provider.uploads.size)
        assertTrue(provider.uploads.single().key.startsWith("yokan-cloud-backup-"))
        assertTrue(result.errors.isEmpty())
        assertTrue(database.syncPreferences().single().lastSyncManga != null)
    }

    @Test
    fun restoreLatestBackupUsesNewestCloudObject() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider(
            initialObjects = listOf(
                StoredObject("yokan-cloud-backup-old.json", "old".encodeToByteArray(), modifiedAtMillis = 100L),
                StoredObject("yokan-cloud-backup-new.json", "new".encodeToByteArray(), modifiedAtMillis = 200L),
            ),
        )
        val service = DefaultCloudBackupSyncService(database, StubBackupService(database), listOf(provider))
        service.connect(syncId = 1L, providerId = provider.descriptor.id, accountLabel = null, accessToken = "token")

        val result = service.restoreLatestBackup(1L)

        assertEquals("yokan-cloud-backup-new.json", result.fileName)
        assertEquals("yokan-cloud-backup-new.json", provider.downloadedKeys.single())
    }

    @Test
    fun changedAccountDuringListingCannotDownloadOrRestore() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider(listOf(StoredObject("yokan-cloud-backup-test.json", byteArrayOf(1), 1)))
        val backup = StubBackupService(database)
        val service = DefaultCloudBackupSyncService(database, backup, listOf(provider))
        service.connect(1, provider.descriptor.id, "old", "old-token")
        val replacement = database.syncPreferences().single().copy(email = "new", authToken = "new-token")
        provider.afterList = { database.upsertSyncPreference(replacement) }
        assertFailsWith<SyncAccountChangedException> { service.restoreLatestBackup(1) }
        assertTrue(provider.downloadedKeys.isEmpty())
        assertEquals(0, backup.restores)
        assertEquals(replacement, database.syncPreferences().single())
        assertEquals(SyncOperationOutcome.Cancelled, service.operationState.value.lastOutcome)
    }

    @Test
    fun changedAccountDuringExportCannotDispatchUpload() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider()
        val backup = StubBackupService(database)
        val service = DefaultCloudBackupSyncService(database, backup, listOf(provider))
        service.connect(1, provider.descriptor.id, "old", "old-token")
        val replacement = database.syncPreferences().single().copy(authToken = "new-token")
        backup.beforeExport = { database.upsertSyncPreference(replacement) }
        assertFailsWith<SyncAccountChangedException> { service.pushChanges(1) }
        assertEquals(SyncOperationOutcome.Cancelled, service.operationState.value.lastOutcome)
        assertTrue(provider.uploads.isEmpty())
        assertEquals(replacement, database.syncPreferences().single())
    }

    @Test
    fun accountChangesDuringDownloadCannotStartRestore() = runTest {
        val mutations: List<(DbSyncPreference) -> DbSyncPreference> = listOf(
            { it.copy(authToken = null, syncOn = false) },
            { it.copy(authToken = "new-token") },
            { it.copy(email = "new-account") },
            { it.copy(server = cloudServerUri("other")) },
            { it.copy(serverProvider = eu.friedcutlet.yokan.database.SyncServerProvider.Mangayomi) },
            { it.copy(syncId = 2) },
        )
        for (mutate in mutations) {
            val database = InMemoryYokanDatabase(emptySnapshot())
            val provider = RecordingCloudStorageProvider(listOf(StoredObject("yokan-cloud-backup-test.json", byteArrayOf(1), 1)))
            val backup = StubBackupService(database)
            val service = DefaultCloudBackupSyncService(database, backup, listOf(provider))
            service.connect(1, provider.descriptor.id, "old", "old-token")
            val replacement = mutate(database.syncPreferences().single())
            provider.beforeGet = { database.replaceAll(database.snapshot().copy(syncPreferences = listOf(replacement))) }
            assertFailsWith<SyncAccountChangedException> { service.pullChanges(1) }
            assertEquals(0, backup.restores)
            assertEquals(replacement, database.syncPreferences().single())
        }
    }

    @Test
    fun cancelledCallerStillCancelsInsteadOfReportingAccountChange() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider(listOf(StoredObject("yokan-cloud-backup-test.json", byteArrayOf(1), 1)))
        val backup = StubBackupService(database)
        val service = DefaultCloudBackupSyncService(database, backup, listOf(provider))
        service.connect(1, provider.descriptor.id, "old", "old-token")
        provider.beforeGet = { currentCoroutineContext().cancel() }
        var thrown: Throwable? = null
        val caller = launch {
            try { service.pullChanges(1) } catch (error: Throwable) { thrown = error; throw error }
        }
        caller.join()
        assertIs<CancellationException>(thrown)
        assertTrue(caller.isCancelled)
        assertEquals(0, backup.restores)
        assertEquals(SyncOperationOutcome.Cancelled, service.operationState.value.lastOutcome)
    }

    @Test
    fun changedAccountInsideRestorePreparationIsRejectedBySnapshotGuard() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider(listOf(StoredObject("yokan-cloud-backup-test.json", byteArrayOf(1), 1)))
        val backup = StubBackupService(database)
        val service = DefaultCloudBackupSyncService(database, backup, listOf(provider))
        service.connect(1, provider.descriptor.id, "old", "old-token")
        val replacement = database.syncPreferences().single().copy(authToken = "new-token")
        backup.beforeRestore = { database.upsertSyncPreference(replacement) }
        assertFailsWith<SyncAccountChangedException> { service.restoreLatestBackup(1) }
        assertEquals(0, backup.restores)
        assertEquals(replacement, database.syncPreferences().single())
    }

    @Test
    fun acceptedUploadCannotMarkAnotherAccountSynced() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider()
        val service = DefaultCloudBackupSyncService(database, StubBackupService(database), listOf(provider))
        service.connect(1, provider.descriptor.id, "old", "old-token")
        val replacement = database.syncPreferences().single().copy(authToken = "new-token")
        provider.afterPut = { database.upsertSyncPreference(replacement) }
        assertFailsWith<SyncAccountChangedException> { service.uploadBackup(1, BackupOptions()) }
        assertEquals(1, provider.uploads.size)
        assertEquals(replacement, database.syncPreferences().single())
    }

    @Test
    fun unrelatedBookkeepingSurvivesAtomicSuccessUpdate() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider()
        val service = DefaultCloudBackupSyncService(database, StubBackupService(database), listOf(provider))
        service.connect(1, provider.descriptor.id, "old", "old-token")
        provider.afterPut = {
            database.upsertSyncPreference(database.syncPreferences().single().copy(syncHistories = true, autoSyncFrequency = 17, hubHead = 32))
        }
        service.uploadBackup(1, BackupOptions())
        val current = database.syncPreferences().single()
        assertTrue(current.syncHistories)
        assertEquals(17, current.autoSyncFrequency)
        assertEquals(32L, current.hubHead)
        assertTrue(current.lastSyncManga != null)
        assertEquals(SyncOperationOutcome.Succeeded, service.operationState.value.lastOutcome)
    }

    @Test
    fun missingSyncIdNeverFallsBackToAnotherAccount() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider()
        val service = DefaultCloudBackupSyncService(database, StubBackupService(database), listOf(provider))
        service.connect(1, provider.descriptor.id, "account", "token")
        val original = database.syncPreferences().single()
        assertFalse(service.status(2).loggedIn)
        assertFailsWith<CloudStorageException> { service.uploadBackup(2, BackupOptions()) }
        assertFailsWith<CloudStorageException> { service.restoreLatestBackup(2) }
        service.logout(2)
        assertEquals(original, database.syncPreferences().single())
        assertEquals(0, provider.listCalls)
        assertTrue(provider.uploads.isEmpty())
    }

    @Test
    fun syncUsesExactlyTheObjectFromItsSingleListing() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val provider = RecordingCloudStorageProvider(listOf(StoredObject("yokan-cloud-backup-test.json", byteArrayOf(1), 1)))
        val service = DefaultCloudBackupSyncService(database, StubBackupService(database), listOf(provider))
        service.connect(1, provider.descriptor.id, "account", "token")
        service.sync(1, database.settings())
        assertEquals(1, provider.listCalls)
        assertEquals(listOf("yokan-cloud-backup-test.json"), provider.downloadedKeys)
    }

    @Test
    fun blankStoredTokenCannotDispatchProviderCalls() = runTest {
        val preference = DbSyncPreference(syncId = 1, server = cloudServerUri("recording"), authToken = " ")
        val database = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(preference)))
        val provider = RecordingCloudStorageProvider()
        val service = DefaultCloudBackupSyncService(database, StubBackupService(database), listOf(provider))
        assertFailsWith<CloudStorageException> { service.sync(1, database.settings()) }
        assertEquals(0, provider.listCalls)
        assertTrue(provider.uploads.isEmpty())
        assertEquals(preference, database.syncPreferences().single())
    }

    private data class StoredObject(
        val key: String,
        val bytes: ByteArray,
        val modifiedAtMillis: Long,
    ) {
        override fun equals(other: Any?): Boolean {
            if (this === other) return true
            if (other !is StoredObject) return false
            return key == other.key &&
                bytes.contentEquals(other.bytes) &&
                modifiedAtMillis == other.modifiedAtMillis
        }

        override fun hashCode(): Int {
            var result = key.hashCode()
            result = 31 * result + bytes.contentHashCode()
            result = 31 * result + modifiedAtMillis.hashCode()
            return result
        }
    }

    private data class Upload(val key: String, val bytes: ByteArray) {
        override fun equals(other: Any?): Boolean {
            if (this === other) return true
            if (other !is Upload) return false
            return key == other.key && bytes.contentEquals(other.bytes)
        }

        override fun hashCode(): Int = 31 * key.hashCode() + bytes.contentHashCode()
    }

    private class RecordingCloudStorageProvider(
        initialObjects: List<StoredObject> = emptyList(),
    ) : CloudStorageProvider {
        override val descriptor: CloudProviderDescriptor = CloudProviderDescriptor(
            id = "recording",
            displayName = "Recording",
            description = "Test provider",
            authInstructions = "Provide token",
        )

        private val objects = initialObjects.associateBy { it.key }.toMutableMap()
        val uploads = mutableListOf<Upload>()
        val downloadedKeys = mutableListOf<String>()
        var beforeValidate: suspend (CloudConnection) -> Unit = {}
        var beforeGet: suspend () -> Unit = {}
        var afterPut: suspend () -> Unit = {}
        var afterList: suspend () -> Unit = {}
        var listCalls = 0

        override suspend fun validate(connection: CloudConnection): CloudConnectionStatus {
            beforeValidate(connection)
            return CloudConnectionStatus(connected = connection.accessToken.isNotBlank(), accountLabel = connection.accountLabel)
        }

        override suspend fun putObject(connection: CloudConnection, key: String, bytes: ByteArray, contentType: String): CloudObject {
            uploads += Upload(key, bytes)
            val stored = StoredObject(key, bytes, modifiedAtMillis = uploads.size.toLong())
            objects[key] = stored
            afterPut()
            return stored.toCloudObject()
        }

        override suspend fun listObjects(connection: CloudConnection, prefix: String): List<CloudObject> {
            listCalls++
            val result = objects.values.filter { it.key.startsWith(prefix) }.map { it.toCloudObject() }
            afterList()
            return result
        }

        override suspend fun getObject(connection: CloudConnection, objectRef: CloudObject): ByteArray {
            beforeGet()
            downloadedKeys += objectRef.key
            return objects.getValue(objectRef.key).bytes
        }

        private fun StoredObject.toCloudObject(): CloudObject =
            CloudObject(
                key = key,
                displayName = key,
                sizeBytes = bytes.size.toLong(),
                modifiedAtMillis = modifiedAtMillis,
                providerFileId = key,
            )
    }

    private class StubBackupService(
        private val database: eu.friedcutlet.yokan.database.YokanDatabase,
    ) : BackupService {
        var restores = 0
        var beforeExport: suspend () -> Unit = {}
        var beforeRestore: suspend () -> Unit = {}
        override suspend fun exportBackup(options: BackupOptions): BackupExport {
            beforeExport()
            assertEquals(false, options.includePrivateNotes, "Cloud uploads must exclude private notes")
            val snapshot = database.snapshot()
            val itemCount = snapshot.mangas.size + snapshot.chapters.size + snapshot.categories.size +
                snapshot.sources.size + snapshot.histories.size + snapshot.updates.size + snapshot.tracks.size
            val bytes = "stub backup with $itemCount items".encodeToByteArray()
            return BackupExport(
                fileName = "yokan-backup.json",
                bytes = bytes,
                itemCount = itemCount,
                format = BackupFormat.Yokan,
                compressed = false,
                contentType = "application/json",
            )
        }

        override suspend fun createBackup(options: BackupOptions): BackupResult {
            val export = exportBackup(options)
            return BackupResult(fileName = export.fileName, bytesWritten = export.bytes.size.toLong(), itemCount = export.itemCount)
        }

        override suspend fun restore(bytes: ByteArray): RestorePreview {
            restores++
            return RestorePreview(itemCount = 0, warnings = listOf("Stub restore"))
        }

        override suspend fun restoreIf(bytes: ByteArray, accepts: (eu.friedcutlet.yokan.database.YokanDatabaseSnapshot) -> Boolean): RestorePreview {
            beforeRestore()
            if (!accepts(database.snapshot())) throw eu.friedcutlet.yokan.services.backup.BackupRestoreTargetChangedException()
            return restore(bytes)
        }

        override suspend fun listAvailableBackups(): List<BackupFileEntry> = emptyList()

        override suspend fun readBackupFile(path: String): ByteArray = ByteArray(0)

        // Cloud sync only exports and restores; the plan/safety-snapshot API is out of scope here.
        override suspend fun exportEncryptedBackup(options: BackupOptions, password: String): BackupExport = unused()
        override suspend fun openBackup(bytes: ByteArray, password: String?): BackupOpenResult = unused()
        override suspend fun previewBackup(plan: BackupPlan): RestorePreview = unused()
        override suspend fun applyBackup(plan: BackupPlan): RestorePreview = unused()
        override suspend fun applyBackup(plan: BackupPlan, mode: RestoreMode): RestorePreview = unused()
        override suspend fun listSafetySnapshots(): List<SafetySnapshot> = unused()
        override suspend fun createSafetySnapshot(description: String): SafetySnapshot = unused()
        override suspend fun rollbackSafetySnapshot(snapshot: SafetySnapshot): RestorePreview = unused()
        override suspend fun clearSafetySnapshots(): Unit = unused()

        private fun unused(): Nothing = error("Not used by cloud backup sync")
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/GoogleDriveSyncServiceTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/GoogleDriveSyncServiceTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/GoogleDriveSyncServiceTest.kt).

The implementation below defines `GoogleDriveSyncServiceTest`, `refreshesTokenThenCreatesSyncFileAndReleasesLock`, `foreignSyncFileIsMergedAndUpdatedInPlace`, `ownSyncFileIsNotMergedBack`, `liveForeignLockRefusesTheRun`, `staleLockIsDeleted`, `olderRivalLockCreatedConcurrentlyWins`, `lockIsReleasedWhenUploadFails`, `authorizationUrlUsesUsersClientAndPkceS256`, `pastedLoopbackUrlCompletesSignIn` and 12 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

- `refreshesTokenThenCreatesSyncFileAndReleasesLock`
- `foreignSyncFileIsMergedAndUpdatedInPlace`
- `ownSyncFileIsNotMergedBack`
- `liveForeignLockRefusesTheRun`
- `staleLockIsDeleted`
- `olderRivalLockCreatedConcurrentlyWins`
- `lockIsReleasedWhenUploadFails`
- `authorizationUrlUsesUsersClientAndPkceS256`
- `pastedLoopbackUrlCompletesSignIn`

Cross-chapter imports used by this file: [`DbManga`](../chapters/02-domain-and-settings-models.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`InMemoryYokanDatabase`](../chapters/03-persistence-and-migrations.md), [`SyncServerProvider`](../chapters/02-domain-and-settings-models.md), [`emptySnapshot`](../chapters/03-persistence-and-migrations.md), [`BackupOptions`](../chapters/20-backup-and-restore.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.backup.BackupOptions
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import io.ktor.http.Url
import io.ktor.http.parseQueryString
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlin.time.Instant
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put

class GoogleDriveSyncServiceTest {
    @Test
    fun refreshesTokenThenCreatesSyncFileAndReleasesLock() = runTest {
        val db = db()
        val drive = FakeDrive()
        val result = service(db, drive).sync(1, db.settings())

        assertTrue(result.errors.isEmpty(), result.errors.toString())
        val token = drive.requests.first()
        assertEquals("https://oauth2.googleapis.com/token", token.url)
        assertEquals("POST", token.method)
        assertEquals("application/x-www-form-urlencoded", token.headers["Content-Type"])
        val form = parseQueryString(assertNotNull(token.body))
        assertEquals("refresh_token", form["grant_type"])
        assertEquals("refresh-1", form["refresh_token"])
        assertEquals(ClientId, form["client_id"])
        assertEquals("secret", form["client_secret"])
        assertTrue(drive.requests.drop(1).all { it.headers["Authorization"] == "Bearer access-1" })
        val create = drive.requests.single { it.url.startsWith("https://www.googleapis.com/upload/drive/v3/files?") }
        assertEquals("POST", create.method)
        assertTrue("uploadType=multipart" in create.url)
        val sync = drive.files.single()
        assertEquals(GoogleDriveSyncService.SyncFileName, sync.name)
        assertEquals(listOf("appDataFolder"), sync.parents)
        assertEquals("device-a", sync.properties["deviceId"])
        assertTrue(drive.requests.any { it.method == "DELETE" }, "lock released")
        assertNotNull(db.syncPreferences().single().lastSyncManga)
    }

    @Test
    fun foreignSyncFileIsMergedAndUpdatedInPlace() = runTest {
        val db = db()
        val drive = FakeDrive()
        val file = drive.add(GoogleDriveSyncService.SyncFileName, mapOf("deviceId" to "device-b"), remoteBytes())
        val result = service(db, drive).sync(1, db.settings())

        assertTrue(result.errors.isEmpty(), result.errors.toString())
        assertTrue(db.mangas().any { it.name == "Remote" })
        val update = drive.requests.single { it.method == "PATCH" }
        assertTrue(update.url.startsWith("https://www.googleapis.com/upload/drive/v3/files/${file.id}?"), update.url)
        assertEquals("device-a", drive.files.single().properties["deviceId"])
    }

    @Test
    fun ownSyncFileIsNotMergedBack() = runTest {
        val db = db()
        val drive = FakeDrive()
        drive.add(GoogleDriveSyncService.SyncFileName, mapOf("deviceId" to "device-a"), remoteBytes())
        val result = service(db, drive).sync(1, db.settings())

        assertTrue(result.errors.isEmpty(), result.errors.toString())
        assertTrue(db.mangas().none { it.name == "Remote" })
        assertTrue(drive.requests.none { it.url.endsWith("alt=media") })
        assertEquals(1, drive.requests.count { it.method == "PATCH" })
    }

    @Test
    fun liveForeignLockRefusesTheRun() = runTest {
        val db = db()
        val drive = FakeDrive()
        val lock = drive.add(GoogleDriveSyncService.LockFileName, mapOf("deviceId" to "device-b", "expiresAt" to (Now + 60_000).toString()))
        val result = service(db, drive).sync(1, db.settings())

        assertEquals(listOf(GoogleDriveSyncService.BusyMessage), result.errors)
        assertEquals(listOf(lock), drive.files)
        assertTrue(drive.requests.none { it.method == "PATCH" || it.url.contains("/upload/") })
        assertNull(db.syncPreferences().single().lastSyncManga)
    }

    @Test
    fun staleLockIsDeleted() = runTest {
        val db = db()
        val drive = FakeDrive()
        val stale = drive.add(GoogleDriveSyncService.LockFileName, mapOf("deviceId" to "device-b", "expiresAt" to (Now - 1).toString()))
        val result = service(db, drive).sync(1, db.settings())

        assertTrue(result.errors.isEmpty(), result.errors.toString())
        assertTrue(drive.requests.any { it.method == "DELETE" && it.url.endsWith("/files/${stale.id}") })
        assertEquals(listOf(GoogleDriveSyncService.SyncFileName), drive.files.map { it.name })
    }

    @Test
    fun olderRivalLockCreatedConcurrentlyWins() = runTest {
        val db = db()
        val drive = FakeDrive()
        drive.onRequest = { request ->
            // Another device creates its lock just before ours reaches Drive.
            if (request.method == "POST" && request.url.startsWith("https://www.googleapis.com/drive/v3/files?") && drive.files.none { it.properties["deviceId"] == "device-b" }) {
                drive.add(GoogleDriveSyncService.LockFileName, mapOf("deviceId" to "device-b", "expiresAt" to (Now + 60_000).toString()))
            }
        }
        val result = service(db, drive).sync(1, db.settings())

        assertEquals(listOf(GoogleDriveSyncService.BusyMessage), result.errors)
        assertEquals(listOf("device-b"), drive.files.map { it.properties["deviceId"] })
        assertTrue(drive.requests.none { it.url.contains("/upload/") })
    }

    @Test
    fun lockIsReleasedWhenUploadFails() = runTest {
        val db = db()
        val drive = FakeDrive().apply { failUploads = true }
        val result = service(db, drive).sync(1, db.settings())

        assertTrue(result.errors.single().contains("HTTP 500"), result.errors.toString())
        assertTrue(drive.files.isEmpty())
        assertNull(db.syncPreferences().single().lastSyncManga)
    }

    @Test
    fun authorizationUrlUsesUsersClientAndPkceS256() {
        val url = Url(googleDriveAuthorizationUrl("my-client.apps.googleusercontent.com", "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", "st"))
        assertEquals("accounts.google.com", url.host)
        assertEquals("/o/oauth2/v2/auth", url.encodedPath)
        assertEquals("my-client.apps.googleusercontent.com", url.parameters["client_id"])
        // RFC 7636 appendix B test vector.
        assertEquals("E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", url.parameters["code_challenge"])
        assertEquals("S256", url.parameters["code_challenge_method"])
        assertEquals("http://127.0.0.1", url.parameters["redirect_uri"])
        assertEquals("https://www.googleapis.com/auth/drive.appdata", url.parameters["scope"])
        assertEquals("offline", url.parameters["access_type"])
        assertEquals("consent", url.parameters["prompt"])
        assertEquals("code", url.parameters["response_type"])
        assertEquals("st", url.parameters["state"])
    }

    @Test
    fun pastedLoopbackUrlCompletesSignIn() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(DbSyncPreference(syncId = 1, serverProvider = SyncServerProvider.GoogleDrive))))
        val drive = FakeDrive()
        val service = service(db, drive)
        val attempt = assertNotNull(service.beginBrowserLogin(1, ClientId))
        val verifier = assertNotNull(Url(attempt.url).parameters["code_challenge"])

        val forged = service.login(1, ClientId, "secret", "http://127.0.0.1/?state=forged&code=4/abc")
        assertFalse(forged.success)
        assertTrue(drive.requests.isEmpty())

        val again = assertNotNull(service.beginBrowserLogin(1, ClientId))
        val result = service.login(1, ClientId, "secret", "http://127.0.0.1/?state=${again.state}&code=4%2Fabc&scope=$GoogleDriveScope")
        assertTrue(result.success, result.message)
        val form = parseQueryString(assertNotNull(drive.requests.first().body))
        assertEquals("authorization_code", form["grant_type"])
        assertEquals("4/abc", form["code"])
        assertEquals("http://127.0.0.1", form["redirect_uri"])
        assertEquals(Url(again.url).parameters["code_challenge"], pkceChallenge(assertNotNull(form["code_verifier"])))
        assertTrue(verifier != Url(again.url).parameters["code_challenge"])
        val stored = db.syncPreferences().single()
        assertEquals(ClientId, stored.server)
        assertEquals("reader@example.com", stored.email)
        assertTrue(assertNotNull(stored.authToken).contains("refresh-1"))
        assertTrue(stored.syncOn)
        assertFalse(stored.deviceId.isNullOrBlank())
        assertEquals("gdrive|$ClientId|reader@example.com", syncLeaseKey(stored))

        // The pending attempt is single-use; a bare code needs a fresh sign-in page.
        assertFalse(service.login(1, ClientId, "secret", "4/abc").success)
        service.beginBrowserLogin(1, ClientId)
        assertTrue(service.login(1, ClientId, "secret", "4/abc").success)
    }

    private class FakeDrive : HttpService {
        data class File(val id: String, val name: String, val parents: List<String>, var properties: Map<String, String>, var bytes: ByteArray, val created: Long)

        val files = mutableListOf<File>()
        val requests = mutableListOf<HttpRequest>()
        var failUploads = false
        var onRequest: (HttpRequest) -> Unit = {}
        private var clock = 0L

        fun add(name: String, properties: Map<String, String>, bytes: ByteArray = ByteArray(0)): File =
            File("f${++clock}", name, listOf("appDataFolder"), properties, bytes, clock).also(files::add)

        override suspend fun request(request: HttpRequest): HttpResponse {
            requests += request
            onRequest(request)
            val url = Url(request.url)
            val path = url.encodedPath
            return when {
                request.url == "https://oauth2.googleapis.com/token" ->
                    HttpResponse(200, """{"access_token":"access-1","expires_in":3599,"refresh_token":"refresh-1","token_type":"Bearer"}""")
                path == "/drive/v3/about" -> HttpResponse(200, """{"user":{"emailAddress":"reader@example.com","displayName":"Reader"}}""")
                request.method == "GET" && path == "/drive/v3/files" -> {
                    val query = assertNotNull(url.parameters["q"])
                    HttpResponse(200, buildJsonObject {
                        put("files", JsonArray(files.filter { "'${it.name}'" in query }.map { it.json() }))
                    }.toString())
                }
                request.method == "GET" && url.parameters["alt"] == "media" ->
                    HttpResponse(200, bodyBytes = files.first { path.endsWith("/${it.id}") }.bytes)
                request.method == "POST" && path == "/drive/v3/files" -> {
                    val metadata = Json.parseToJsonElement(assertNotNull(request.body)).jsonObject
                    HttpResponse(200, create(metadata, ByteArray(0)).json().toString())
                }
                failUploads && path.startsWith("/upload/") -> HttpResponse(500, "boom")
                request.method == "POST" && path == "/upload/drive/v3/files" -> {
                    val (metadata, media) = multipart(request)
                    HttpResponse(200, create(metadata, media).json().toString())
                }
                request.method == "PATCH" && path.startsWith("/upload/drive/v3/files/") -> {
                    val (metadata, media) = multipart(request)
                    val file = files.first { path.endsWith("/${it.id}") }
                    file.properties = properties(metadata)
                    file.bytes = media
                    HttpResponse(200, """{"id":"${file.id}"}""")
                }
                request.method == "DELETE" -> {
                    val removed = files.removeAll { path.endsWith("/${it.id}") }
                    HttpResponse(if (removed) 204 else 404)
                }
                else -> error("Unexpected ${request.method} ${request.url}")
            }
        }

        private fun create(metadata: JsonObject, bytes: ByteArray): File {
            val parents = (metadata["parents"] as? JsonArray)?.map { it.jsonPrimitive.content }.orEmpty()
            return File("f${++clock}", metadata.getValue("name").jsonPrimitive.content, parents, properties(metadata), bytes, clock).also(files::add)
        }

        private fun properties(metadata: JsonObject) =
            (metadata["appProperties"] as? JsonObject)?.mapValues { it.value.jsonPrimitive.content }.orEmpty()

        private fun multipart(request: HttpRequest): Pair<JsonObject, ByteArray> {
            val boundary = assertNotNull(request.headers["Content-Type"]).substringAfter("boundary=")
            val parts = assertNotNull(request.bodyBytes).decodeToString().split("--$boundary")
            fun content(part: String) = part.substringAfter("\r\n\r\n").removeSuffix("\r\n")
            return Json.parseToJsonElement(content(parts[1])).jsonObject to content(parts[2]).encodeToByteArray()
        }

        private fun File.json() = buildJsonObject {
            put("id", id)
            put("createdTime", Instant.fromEpochMilliseconds(1_700_000_000_000 + created * 1000).toString())
            put("modifiedTime", Instant.fromEpochMilliseconds(1_700_000_000_000 + created * 1000).toString())
            put("appProperties", JsonObject(properties.mapValues { JsonPrimitive(it.value) }))
        }
    }

    private fun service(db: InMemoryYokanDatabase, drive: FakeDrive) = GoogleDriveSyncService(db, backup(db), drive, clock = { Now })

    private suspend fun remoteBytes(): ByteArray =
        backup(InMemoryYokanDatabase(emptySnapshot().copy(mangas = listOf(DbManga(id = 7, name = "Remote", link = "/remote", source = "src", favorite = true)))))
            .exportBackup(BackupOptions(compressionLevel = 6, includePrivateNotes = false)).bytes

    private fun db() = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(Preference)))

    private companion object {
        const val Now = 1_800_000_000_000L
        const val ClientId = "my-client.apps.googleusercontent.com"
        val Preference = DbSyncPreference(
            syncId = 1, server = ClientId, email = "reader@example.com",
            authToken = """{"clientSecret":"secret","refreshToken":"refresh-1"}""", syncOn = true,
            deviceId = "device-a", serverProvider = SyncServerProvider.GoogleDrive,
        )
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncLoginTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncLoginTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncLoginTest.kt).

The implementation below defines `HubSyncLoginTest`, `loginStoresTokenServerAndDevice`, `loginRefusesServerWithoutMatchingProtocol`, `lateHubLoginCannotOverwriteProviderSwitch`, `pendingBrowserLoginCannotOverwriteProviderSwitch`, `logoutClearsTheSessionWithoutWaitingForTheHub`, `browserLoginRequiresTheIssuedStateAndAcceptsEncodedPlus`, `browserCallbackRejectsWrongStateDeviceAndDuplicateParametersWithoutNetwork`, `oldHubCallbackWithoutStateFailsClosedWithSignInGuidance`, `supersededAttemptCannotSaveAfterSuspendedVersionRequestReturns` and 2 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

- `loginStoresTokenServerAndDevice`
- `loginRefusesServerWithoutMatchingProtocol`
- `lateHubLoginCannotOverwriteProviderSwitch`
- `pendingBrowserLoginCannotOverwriteProviderSwitch`
- `logoutClearsTheSessionWithoutWaitingForTheHub`
- `browserLoginRequiresTheIssuedStateAndAcceptsEncodedPlus`
- `browserCallbackRejectsWrongStateDeviceAndDuplicateParametersWithoutNetwork`
- `oldHubCallbackWithoutStateFailsClosedWithSignInGuidance`
- `supersededAttemptCannotSaveAfterSuspendedVersionRequestReturns`
- `cancelledAttemptCannotSaveAfterNonCancellableVersionRequestReturns`
- `concurrentDuplicateBrowserCallbackMakesOneVersionRequestAndSave`

Cross-chapter imports used by this file: [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`SyncServerProvider`](../chapters/02-domain-and-settings-models.md), [`InMemoryYokanDatabase`](../chapters/03-persistence-and-migrations.md), [`emptySnapshot`](../chapters/03-persistence-and-migrations.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md), [`HttpResponse`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.launch

class HubSyncLoginTest {
    @Test
    fun loginStoresTokenServerAndDevice() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        val hub = FakeHub()
        hub.responses += HttpResponse(200, """{"supported":["1"]}""")
        hub.responses += HttpResponse(200, """{"token":"abc","user":{"id":"u","email":"a@b"}}""")
        val result = service(db, hub).login(1, "hub.test/", "a@b", "pw")
        assertTrue(result.success, result.message)
        assertEquals("https://hub.test/api/version", hub.requests[0].url)
        val req = hub.requests[1]
        assertEquals("https://hub.test/api/v1/login", req.url)
        assertNotNull(req.headers["X-Device"])
        val pref = db.syncPreferences().single()
        assertEquals("abc", pref.authToken)
        assertEquals("https://hub.test", pref.server)
        assertEquals(req.headers["X-Device"], pref.deviceId)
        assertTrue(pref.syncOn)
    }

    @Test
    fun loginRefusesServerWithoutMatchingProtocol() = runTest {
        for (version in listOf(HttpResponse(404, "not found"), HttpResponse(200, """{"supported":["2"]}"""))) {
            val db = InMemoryYokanDatabase(emptySnapshot())
            val hub = FakeHub()
            hub.responses += version
            val result = service(db, hub).login(1, "hub.test", "a@b", "pw")
            assertFalse(result.success)
            assertEquals(1, hub.requests.size, "no credentials are sent to an incompatible server")
            assertTrue(db.syncPreferences().isEmpty())
        }
    }

    @Test
    fun lateHubLoginCannotOverwriteProviderSwitch() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        db.upsertSyncPreference(DbSyncPreference(syncId = 1, server = "https://hub.test", email = "old", serverProvider = SyncServerProvider.YokanHub))
        val hub = FakeHub()
        hub.responses += HttpResponse(200, """{"supported":["1"]}""")
        hub.responses += HttpResponse(200, """{"token":"late-token"}""")
        val requestStarted = CompletableDeferred<Unit>()
        val releaseLogin = CompletableDeferred<Unit>()
        hub.suspendOnRequest = { request ->
            if (request.url.endsWith("/api/v1/login")) {
                requestStarted.complete(Unit)
                releaseLogin.await()
            }
        }
        val service = service(db, hub)
        val login = launch { assertFalse(service.login(1, "https://hub.test", "new", "password").success) }
        requestStarted.await()
        db.upsertSyncPreference(db.syncPreferences().single().copy(
            serverProvider = SyncServerProvider.Mangayomi, server = null, email = null, authToken = null,
        ))
        releaseLogin.complete(Unit)
        login.join()
        assertEquals(SyncServerProvider.Mangayomi, db.syncPreferences().single().serverProvider)
        assertEquals(null, db.syncPreferences().single().authToken)
    }

    @Test
    fun pendingBrowserLoginCannotOverwriteProviderSwitch() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        db.upsertSyncPreference(DbSyncPreference(syncId = 1, server = "https://hub.test", serverProvider = SyncServerProvider.YokanHub))
        val hub = FakeHub()
        hub.responses += HttpResponse(200, """{"supported":["1"]}""")
        val service = service(db, hub)
        val attempt = assertNotNull(service.beginBrowserLogin(1, "https://hub.test"))
        db.upsertSyncPreference(db.syncPreferences().single().copy(serverProvider = SyncServerProvider.Mangayomi, server = null))
        val callback = "https://hub.test/login/done/#token=late&device=${attempt.device}&state=${attempt.state}"
        val result = assertNotNull(service.completeBrowserLogin(attempt, callback))
        assertFalse(result.success)
        assertEquals(SyncServerProvider.Mangayomi, db.syncPreferences().single().serverProvider)
        assertEquals(null, db.syncPreferences().single().authToken)
    }

    @Test
    fun logoutClearsTheSessionWithoutWaitingForTheHub() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        val hub = FakeHub()
        val revokeSent = kotlinx.coroutines.CompletableDeferred<HttpRequest>()
        hub.onRequest = { revokeSent.complete(it) }
        hub.suspendOnRequest = { kotlinx.coroutines.awaitCancellation() } // an unreachable hub never answers
        val service = service(db, hub)
        try {
            service.logout(1)
            assertEquals(null, db.syncPreferences().single().authToken)
            assertFalse(db.syncPreferences().single().syncOn)
            val revoke = revokeSent.await()
            assertEquals("https://hub.test/api/v1/logout", revoke.url)
            assertEquals("Bearer tok", revoke.headers["Authorization"])
        } finally {
            service.close()
        }
    }

    @Test
    fun browserLoginRequiresTheIssuedStateAndAcceptsEncodedPlus() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        val hub = FakeHub()
        val service = service(db, hub)
        val attempt = assertNotNull(service.beginBrowserLogin(1, "hub.test/"))
        assertTrue(attempt.url.startsWith("https://hub.test/login/?"), attempt.url)
        assertTrue(attempt.url.contains("state=${attempt.state}"))
        assertTrue(attempt.state.length >= 32)

        assertFalse(assertNotNull(service.completeBrowserLogin(attempt, "https://hub.test/login/done/#token=stolen&device=${attempt.device}&state=wrong")).success)
        assertEquals(null, service.completeBrowserLogin(attempt, "https://hub.test.evil/login/done/#token=stolen&device=${attempt.device}&state=${attempt.state}"))
        assertEquals(null, service.completeBrowserLogin(attempt, "https://hub.test/login/done/extra/#token=stolen&device=${attempt.device}&state=${attempt.state}"))
        assertEquals(null, service.completeBrowserLogin(attempt, "https://hub.test/login/%64one/#token=stolen&device=${attempt.device}&state=${attempt.state}"))
        assertEquals(null, service.completeBrowserLogin(attempt, "https://hub.test/login/done/?x=1#token=stolen&device=${attempt.device}&state=${attempt.state}"))
        assertEquals(null, service.completeBrowserLogin(attempt, "https://user@hub.test/login/done/#token=stolen&device=${attempt.device}&state=${attempt.state}"))
        assertTrue(hub.requests.isEmpty())

        hub.responses += HttpResponse(200, """{"supported":["1"]}""")
        val result = assertNotNull(service.completeBrowserLogin(attempt, "https://hub.test/login/done/#token=t%2B1&email=a%40b.test&device=${attempt.device}&state=${attempt.state}"))
        assertTrue(result.success, result.message)
        val pref = db.syncPreferences().single()
        assertEquals("t+1", pref.authToken)
        assertEquals("a@b.test", pref.email)
        assertEquals(attempt.device, pref.deviceId)
        assertEquals("https://hub.test", pref.server)
        assertEquals(null, service.completeBrowserLogin(attempt, "https://hub.test/login/done/#token=second&email=x&device=${attempt.device}&state=${attempt.state}"))
        assertEquals(1, hub.requests.size, "a completed attempt is single-use")
    }

    @Test
    fun browserCallbackRejectsWrongStateDeviceAndDuplicateParametersWithoutNetwork() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        val hub = FakeHub()
        val service = service(db, hub)
        val attempt = assertNotNull(service.beginBrowserLogin(1, "hub.test"))
        val valid = "token=t&email=e&device=${attempt.device}&state=${attempt.state}"
        for (fragment in listOf(
            "token=t&email=e&device=${attempt.device}&state=wrong",
            "token=t&email=e&device=other&state=${attempt.state}",
            "$valid&state=${attempt.state}",
            "token=t&token=x&email=e&device=${attempt.device}&state=${attempt.state}",
            "token=%00&email=e&device=${attempt.device}&state=${attempt.state}",
        )) {
            val result = service.completeBrowserLogin(attempt, "https://hub.test/login/done/#$fragment")
            assertNotNull(result)
            assertFalse(result.success)
        }
        assertTrue(hub.requests.isEmpty())
        assertTrue(db.syncPreferences().isEmpty())
    }

    @Test
    fun oldHubCallbackWithoutStateFailsClosedWithSignInGuidance() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        val hub = FakeHub()
        val service = service(db, hub)
        val attempt = assertNotNull(service.beginBrowserLogin(1, "hub.test"))
        val result = assertNotNull(service.completeBrowserLogin(attempt, "https://hub.test/login/done/#token=t&email=e&device=${attempt.device}"))
        assertFalse(result.success)
        assertTrue(result.message.contains("Update the hub or use email/password sign-in"))
        assertTrue(hub.requests.isEmpty())
        assertTrue(db.syncPreferences().isEmpty())
    }

    @Test
    fun supersededAttemptCannotSaveAfterSuspendedVersionRequestReturns() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        val hub = FakeHub()
        val requestStarted = CompletableDeferred<Unit>()
        val allowVersionResponse = CompletableDeferred<Unit>()
        hub.suspendOnRequest = {
            requestStarted.complete(Unit)
            kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) { allowVersionResponse.await() }
        }
        hub.responses += HttpResponse(200, """{"supported":["1"]}""")
        val service = service(db, hub)
        val old = assertNotNull(service.beginBrowserLogin(1, "hub.test"))
        val completing = launch {
            service.completeBrowserLogin(old, "https://hub.test/login/done/#token=old&email=e&device=${old.device}&state=${old.state}")
        }
        requestStarted.await()
        val newer = assertNotNull(service.beginBrowserLogin(1, "hub.test"))
        allowVersionResponse.complete(Unit)
        completing.join()

        assertTrue(db.syncPreferences().isEmpty())
        assertEquals(null, service.completeBrowserLogin(old, "https://hub.test/login/done/#token=old&email=e&device=${old.device}&state=${old.state}"))
        assertTrue(newer !== old)
        assertEquals(1, hub.requests.size)
    }

    @Test
    fun cancelledAttemptCannotSaveAfterNonCancellableVersionRequestReturns() = runTest {
        val original = DbSyncPreference(
            syncId = 1,
            server = "https://hub.test",
            email = "before@example.test",
            authToken = "existing-token",
            syncOn = false,
            deviceId = "dev1",
        )
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(original)))
        val hub = FakeHub()
        val requestStarted = CompletableDeferred<Unit>()
        val allowVersionResponse = CompletableDeferred<Unit>()
        hub.suspendOnRequest = {
            requestStarted.complete(Unit)
            kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) { allowVersionResponse.await() }
        }
        hub.responses += HttpResponse(200, """{"supported":["1"]}""")
        val service = service(db, hub)
        val attempt = assertNotNull(service.beginBrowserLogin(1, "hub.test"))
        val completing = launch {
            service.completeBrowserLogin(
                attempt,
                "https://hub.test/login/done/#token=new-token&email=after%40example.test&device=${attempt.device}&state=${attempt.state}",
            )
        }

        requestStarted.await()
        service.cancelBrowserLogin(attempt)
        allowVersionResponse.complete(Unit)
        completing.join()

        assertEquals(original, db.syncPreferences().single())
        assertEquals(1, hub.requests.size)
    }

    @Test
    fun concurrentDuplicateBrowserCallbackMakesOneVersionRequestAndSave() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        val hub = FakeHub()
        val requestStarted = CompletableDeferred<Unit>()
        val allowVersionResponse = CompletableDeferred<Unit>()
        hub.suspendOnRequest = {
            requestStarted.complete(Unit)
            kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) { allowVersionResponse.await() }
        }
        hub.responses += HttpResponse(200, """{"supported":["1"]}""")
        val service = service(db, hub)
        val attempt = assertNotNull(service.beginBrowserLogin(1, "hub.test"))
        val callback = "https://hub.test/login/done/#token=once&email=a%40b.test&device=${attempt.device}&state=${attempt.state}"
        val firstResult = CompletableDeferred<SyncLoginResult?>()
        val first = launch { firstResult.complete(service.completeBrowserLogin(attempt, callback)) }
        requestStarted.await()

        val duplicateResult = CompletableDeferred<SyncLoginResult?>()
        val duplicate = launch { duplicateResult.complete(service.completeBrowserLogin(attempt, callback)) }
        assertEquals(null, duplicateResult.await())

        allowVersionResponse.complete(Unit)
        first.join()
        duplicate.join()

        assertTrue(assertNotNull(firstResult.await()).success)
        assertEquals(1, hub.requests.size)
        assertEquals("once", db.syncPreferences().single().authToken)
        assertTrue(db.syncPreferences().single().syncOn)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncRoundTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncRoundTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncRoundTest.kt).

The implementation below defines `HubSyncRoundTest`, `roundPushesOutboxAppliesDeltaAndStoresCursor`, `dataThatPredatesTheOutboxReachesTheHub`, `conflictTriggersOneResyncFromZero`, `higherEpochResyncDropsStaleOpsButRetriesCurrentGeneration`, `conflictAtCurrentEpochDoesNotDiscardUnrelatedOutboxOps`, `completedRollbackWithEmptyHeadDoesNotReseedRestoredMonotoneState`, `firstEpochAdoptionPreservesInitialSeedUploads`, `epochZeroToTwoRollbackDropsStaleSeedWorkBeforeRetry`, `establishedSerializedPreferenceDoesNotReseedStaleLocalState` and 13 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

- `roundPushesOutboxAppliesDeltaAndStoresCursor`
- `dataThatPredatesTheOutboxReachesTheHub`
- `conflictTriggersOneResyncFromZero`
- `higherEpochResyncDropsStaleOpsButRetriesCurrentGeneration`
- `conflictAtCurrentEpochDoesNotDiscardUnrelatedOutboxOps`
- `completedRollbackWithEmptyHeadDoesNotReseedRestoredMonotoneState`
- `firstEpochAdoptionPreservesInitialSeedUploads`
- `epochZeroToTwoRollbackDropsStaleSeedWorkBeforeRetry`
- `establishedSerializedPreferenceDoesNotReseedStaleLocalState`
- `interruptedMultiChunkBootstrapRestartsFromTheBeginning`
- `interruptedRollbackRecoveryNeverSeedsExtremeDocuments`
- `capturedSeedChunkIsNotRetriedAfterGenerationChange`
- `legacyEpochRowsAreDroppedAndOnlyCurrentEpochIsSent`
- `editCreatedDuringRecoveryIsSentAfterRecoveryCompletes`
- `editsMadeDuringTheRequestWinOverTheIncomingDoc`
- `pendingTitleDeleteSuppressesAnInFlightLiveDocument`
- The remaining 6 cases are included in the complete listing below.

Cross-chapter imports used by this file: [`DbManga`](../chapters/02-domain-and-settings-models.md), [`DbChapter`](../chapters/02-domain-and-settings-models.md), [`DbDownload`](../chapters/02-domain-and-settings-models.md), [`DbHistory`](../chapters/02-domain-and-settings-models.md), [`DbUpdate`](../chapters/02-domain-and-settings-models.md), [`DbOutboxOp`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbUpdate
import eu.friedcutlet.yokan.database.DbOutboxOp
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.decodeDatabaseSnapshot
import eu.friedcutlet.yokan.database.encodeDatabaseSnapshot
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.database.sync.SyncPaths
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.long

class HubSyncRoundTest {
    @Test
    fun roundPushesOutboxAppliesDeltaAndStoresCursor() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1))
        val manga = db.upsertManga(DbManga(name = "Local", link = "/t", sourceId = 5))
        val hub = FakeHub()
        hub.responses += HttpResponse(200, """{"epoch":1,"head":40,"hlc":6,"ents":[]}""") // seed chunk
        hub.responses += HttpResponse(
            200,
            """{"epoch":1,"head":42,"hlc":7,"more":false,"lost":1,"applied":2,"ents":[
                 {"k":2,"id":${manga.id},"doc":{"name":"Remote","favorite":true,"categories":{"7":true}}},
                 {"k":1,"id":7,"doc":{"name":"Reading","forItemType":"Manga","position":0}}
               ]}""",
        )
        val result = service(db, hub).sync(1, db.settings())

        assertEquals(2, hub.requests.size, "first sync from a device seeds its full state before the outbox")
        val seed = Json.parseToJsonElement(hub.requests[0].body!!).jsonObject
        assertEquals(HubSyncService.NO_DELTA, seed["since"]!!.jsonPrimitive.long)
        val seedOp = seed["ops"]!!.jsonArray.map { it.jsonObject }.single { it["p"]!!.jsonPrimitive.content == "name" }
        assertEquals(manga.id, seedOp["id"]!!.jsonPrimitive.long)
        assertEquals(HubSyncService.SEED_CLOCK, seedOp["t"]!!.jsonPrimitive.long, "seeded values never beat what the hub already has")

        val body = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject
        assertEquals(0L, body["since"]!!.jsonPrimitive.long)
        val ops = body["ops"]!!.jsonArray
        assertTrue(ops.any { it.jsonObject["p"]!!.jsonPrimitive.content == "name" && it.jsonObject["id"]!!.jsonPrimitive.long == manga.id })
        assertEquals("Bearer tok", hub.requests[1].headers["Authorization"])

        assertTrue(db.outbox().isEmpty(), "sent ops are cleared")
        val updated = db.manga(manga.id)!!
        assertEquals("Remote", updated.name)
        assertTrue(updated.favorite)
        assertEquals(listOf(7L), updated.categories)
        assertEquals("Reading", db.categories().single { it.id == 7L }.name)
        val pref = db.syncPreferences().single()
        assertEquals(42L, pref.hubHead)
        assertEquals(1, pref.hubEpoch)
        assertEquals(seed["ops"]!!.jsonArray.size + ops.size, result.uploadedChanges)
        assertEquals(2, result.downloadedChanges)
        assertTrue(result.errors.single().contains("took precedence"))
        assertTrue(db.outbox().isEmpty(), "applying hub docs did not create new ops")
    }

    @Test
    fun dataThatPredatesTheOutboxReachesTheHub() = runTest {
        // Restored backups and pre-sync installs have entities with no outbox rows at all.
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        val manga = db.applyRemote { db.upsertManga(DbManga(name = "Old", link = "/o", sourceId = 5, favorite = true)) }
        assertTrue(db.outbox().isEmpty())
        val hub = FakeHub()
        hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":1,"ents":[]}""")
        hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":2,"ents":[]}""")
        service(db, hub).sync(1, db.settings())
        val seedOps = Json.parseToJsonElement(hub.requests[0].body!!).jsonObject["ops"]!!.jsonArray.map { it.jsonObject }
        assertTrue(seedOps.any { it["k"]!!.jsonPrimitive.content == "2" && it["id"]!!.jsonPrimitive.long == manga.id && it["p"]!!.jsonPrimitive.content == "favorite" })

        // An established device (cursor > 0) does not re-seed on a normal sync…
        hub.requests.clear()
        hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":3,"ents":[]}""")
        service(db, hub).sync(1, db.settings())
        assertEquals(1, hub.requests.size)
        assertTrue(Json.parseToJsonElement(hub.requests[0].body!!).jsonObject["ops"]!!.jsonArray.isEmpty())

        // …but "Upload only" re-sends everything with fresh clocks so local state wins.
        hub.requests.clear()
        hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":4,"ents":[]}""")
        hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":5,"ents":[]}""")
        service(db, hub).pushChanges(1)
        val overwrite = Json.parseToJsonElement(hub.requests[0].body!!).jsonObject
        assertEquals(HubSyncService.NO_DELTA, overwrite["since"]!!.jsonPrimitive.long)
        val op = overwrite["ops"]!!.jsonArray.map { it.jsonObject }.single { it["p"]!!.jsonPrimitive.content == "favorite" }
        assertTrue(op["t"]!!.jsonPrimitive.long > HubSyncService.SEED_CLOCK)
        assertEquals(1L, db.syncPreferences().single().hubHead, "upload-only leaves the pull cursor alone")
    }

    @Test
    fun conflictTriggersOneResyncFromZero() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        db.upsertSyncPreference(db.syncPreferences().single().copy(hubHead = 900, hubEpoch = 1))
        val hub = FakeHub()
        hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""")
        hub.responses += HttpResponse(200, """{"epoch":2,"head":3,"hlc":1,"ents":[]}""")
        val result = service(db, hub).pullChanges(1)
        assertTrue(result.errors.isEmpty(), result.errors.toString())
        assertEquals(2, hub.requests.size)
        val second = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject
        assertEquals(0L, second["since"]!!.jsonPrimitive.long)
        assertEquals(2, second["epoch"]!!.jsonPrimitive.content.toInt())
        assertEquals(3L, db.syncPreferences().single().hubHead)
    }

    @Test
    fun higherEpochResyncDropsStaleOpsButRetriesCurrentGeneration() = runTest {
        val db = InMemoryYokanDatabase(
            emptySnapshot().copy(
                syncPreferences = listOf(
                    DbSyncPreference(
                        syncId = 1,
                        server = "https://hub.test",
                        authToken = "tok",
                        syncOn = true,
                        hubHead = 1,
                        hubEpoch = 1,
                    ),
                ),
                outbox = listOf(
                    DbOutboxOp(SyncPaths.KIND_MANGA, 21, "name", "\"Old\"", 1, 1, epoch = 1),
                    DbOutboxOp(SyncPaths.KIND_MANGA, 22, "favorite", "true", 2, 2, epoch = 2),
                ),
            ),
        )

        val hub = FakeHub()
        hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""")
        hub.responses += HttpResponse(200, """{"epoch":2,"head":4,"hlc":1,"ents":[]}""")

        service(db, hub).sync(1, db.settings())

        assertEquals(2, hub.requests.size)
        val retried = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject["ops"]!!.jsonArray
        assertEquals(listOf("favorite"), retried.map { it.jsonObject["p"]!!.jsonPrimitive.content })
        assertEquals(2, db.syncPreferences().single().hubEpoch)
        assertTrue(db.outbox().isEmpty())
    }

    @Test
    fun conflictAtCurrentEpochDoesNotDiscardUnrelatedOutboxOps() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        db.upsertSyncPreference(db.syncPreferences().single().copy(hubHead = 1, hubEpoch = 2))
        val manga = db.upsertManga(DbManga(name = "Local", link = "/t", sourceId = 5))
        val hub = FakeHub()
        hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""")
        hub.responses += HttpResponse(200, """{"epoch":2,"head":2,"hlc":1,"ents":[]}""")

        service(db, hub).sync(1, db.settings())

        val retried = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject["ops"]!!.jsonArray
        assertTrue(retried.any { it.jsonObject["id"]!!.jsonPrimitive.long == manga.id })
    }

    @Test
    fun completedRollbackWithEmptyHeadDoesNotReseedRestoredMonotoneState() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        db.upsertSyncPreference(
            db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true),
        )
        db.applyRemote { db.upsertManga(DbManga(id = 99, name = "local", lastRead = 42)) }
        val hub = FakeHub()
        hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""")
        hub.responses += HttpResponse(
            200,
            """{"epoch":2,"head":0,"hlc":1,"ents":[{"k":2,"id":99,"doc":{"name":"restored","lastRead":7}}]}""",
        )
        service(db, hub).sync(1, db.settings())
        assertFalse(db.syncPreferences().single().hubRecoveryPending)
        assertTrue(db.syncPreferences().single().hubBootstrapComplete)
        assertEquals(7, db.manga(99)!!.lastRead)

        hub.requests.clear()
        hub.responses += HttpResponse(200, """{"epoch":2,"head":0,"hlc":2,"ents":[]}""")
        service(db, hub).sync(1, db.settings())

        val next = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject
        assertTrue(next["ops"]!!.jsonArray.isEmpty())
        assertFalse(hub.requests.single().body!!.contains("restored"))
    }

    @Test
    fun firstEpochAdoptionPreservesInitialSeedUploads() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        val manga = db.upsertManga(DbManga(name = "preexisting", link = "/local"))
        val hub = FakeHub()
        hub.responses += HttpResponse(200, """{"supported":["1"]}""")
        hub.responses += HttpResponse(200, """{"token":"abc"}""")
        hub.responses += HttpResponse(409, """{"resync":true,"epoch":1}""")
        hub.responses += HttpResponse(200, """{"epoch":1,"head":10,"hlc":1,"ents":[]}""")
        hub.responses += HttpResponse(200, """{"epoch":1,"head":10,"hlc":2,"ents":[]}""")
        val service = service(db, hub)

        assertTrue(service.login(1, "hub.test", "a@b", "pw").success)
        service.sync(1, db.settings())

        val firstSeed = Json.parseToJsonElement(hub.requests[2].body!!).jsonObject
        val adoptedSeed = Json.parseToJsonElement(hub.requests[3].body!!).jsonObject
        assertEquals(0, firstSeed["epoch"]!!.jsonPrimitive.content.toInt())
        assertEquals(1, adoptedSeed["epoch"]!!.jsonPrimitive.content.toInt())
        assertTrue(firstSeed["ops"]!!.jsonArray.any { it.jsonObject["id"]!!.jsonPrimitive.long == manga.id })
        assertTrue(adoptedSeed["ops"]!!.jsonArray.any { it.jsonObject["id"]!!.jsonPrimitive.long == manga.id })
        assertFalse(db.syncPreferences().single().hubRecoveryPending)
        assertTrue(db.syncPreferences().single().hubBootstrapComplete)
    }

    @Test
    fun epochZeroToTwoRollbackDropsStaleSeedWorkBeforeRetry() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        val manga = db.upsertManga(DbManga(name = "stale", link = "/stale"))
        val hub = FakeHub()
        hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""")
        hub.responses += HttpResponse(200, """{"epoch":2,"head":0,"hlc":1,"ents":[]}""")
        hub.responses += HttpResponse(200, """{"epoch":2,"head":0,"hlc":2,"ents":[]}""")

        service(db, hub).sync(1, db.settings())

        assertTrue(hub.requests[0].body!!.contains(manga.id.toString()))
        assertTrue(hub.requests.drop(1).all { request ->
            Json.parseToJsonElement(request.body!!).jsonObject["ops"]!!.jsonArray.isEmpty()
        })
        assertFalse(db.syncPreferences().single().hubRecoveryPending)
        assertTrue(db.syncPreferences().single().hubBootstrapComplete)
    }

    @Test
    fun establishedSerializedPreferenceDoesNotReseedStaleLocalState() = runTest {
        val legacyRaw = encodeDatabaseSnapshot(
            emptySnapshot().copy(
                syncPreferences = listOf(
                    DbSyncPreference(
                        syncId = 1,
                        server = "https://hub.test",
                        authToken = "old-token",
                        syncOn = true,
                    ),
                ),
                mangas = listOf(DbManga(id = 77, name = "stale", lastRead = 101)),
            ),
        ).replace("\"hubRecoveryPending\": false", "\"legacyRecoveryPending\": false")
            .replace("\"hubBootstrapComplete\": false", "\"legacyBootstrapComplete\": false")
        val db = InMemoryYokanDatabase(decodeDatabaseSnapshot(legacyRaw)!!)

        assertTrue(db.syncPreferences().single().hubBootstrapComplete)

        val fresh = InMemoryYokanDatabase(
            emptySnapshot().copy(
                syncPreferences = listOf(
                    DbSyncPreference(
                        syncId = 1,
                        server = "https://hub.test",
                        authToken = "new-token",
                        syncOn = true,
                    ),
                ),
            ),
        )
        assertFalse(fresh.syncPreferences().single().hubBootstrapComplete)
        val hub = FakeHub()
        hub.responses += HttpResponse(200, """{"epoch":1,"head":0,"hlc":1,"ents":[]}""")

        service(db, hub).sync(1, db.settings())

        val body = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject
        assertTrue(body["ops"]!!.jsonArray.isEmpty())
    }

    @Test
    fun interruptedMultiChunkBootstrapRestartsFromTheBeginning() = runTest {
        val db = InMemoryYokanDatabase(
            emptySnapshot().copy(
                syncPreferences = listOf(
                    DbSyncPreference(
                        syncId = 1,
                        server = "https://hub.test",
                        authToken = "tok",
                        syncOn = true,
                        hubEpoch = 1,
                    ),
                ),
                mangas = (1L..2_000L).map { id -> DbManga(id = id, name = "m$id") },
            ),
        )
        db.upsertSyncPreference(db.syncPreferences().single().copy(hubBootstrapComplete = false))
        val hub = FakeHub()
        hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":1,"ents":[]}""")
        hub.responses += HttpResponse(503, """{"error":"interrupted"}""")
        service(db, hub).sync(1, db.settings())
        assertFalse(db.syncPreferences().single().hubBootstrapComplete)

        val reopened = InMemoryYokanDatabase(db.snapshot())
        reopened.removeManga(1L, recordChange = false)
        reopened.upsertManga(DbManga(id = 3_000L, name = "added-before-retry"))
        hub.requests.clear()
        // Enough acknowledgements for every bootstrap chunk; the count depends on title document fields.
        repeat(6) { hub.responses += HttpResponse(200, """{"epoch":1,"head":2,"hlc":${it + 2},"ents":[]}""") }
        service(reopened, hub).sync(1, reopened.settings())

        val restarted = hub.requests.first().body!!
        assertTrue(Json.parseToJsonElement(restarted).jsonObject["ops"]!!.jsonArray.isNotEmpty())
        assertTrue(hub.requests.any { it.body!!.contains("3000") })
        assertTrue(hub.requests.any { it.body!!.contains("2") })
        assertTrue(reopened.syncPreferences().single().hubBootstrapComplete)
    }

    @Test
    fun interruptedRollbackRecoveryNeverSeedsExtremeDocuments() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 0))
        db.upsertManga(DbManga(id = Long.MIN_VALUE, name = "min"))
        db.upsertManga(DbManga(id = Long.MAX_VALUE, name = "max"))

        val hub = FakeHub()
        hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""")
        hub.responses += HttpResponse(503, """{"error":"interrupted"}""")
        service(db, hub).sync(1, db.settings())

        assertTrue(db.syncPreferences().single().hubRecoveryPending)
        assertTrue(hub.requests[0].body!!.contains(Long.MIN_VALUE.toString()))
        assertTrue(hub.requests[0].body!!.contains(Long.MAX_VALUE.toString()))
        val interruptedRetry = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject
        assertEquals(0L, interruptedRetry["since"]!!.jsonPrimitive.long)
        assertTrue(interruptedRetry["ops"]!!.jsonArray.isEmpty())

        hub.requests.clear()
        hub.responses += HttpResponse(200, """{"epoch":2,"head":8,"hlc":1,"ents":[]}""")
        service(db, hub).sync(1, db.settings())

        val recovered = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject
        assertEquals(0L, recovered["since"]!!.jsonPrimitive.long)
        assertTrue(recovered["ops"]!!.jsonArray.isEmpty())
        assertFalse(db.syncPreferences().single().hubRecoveryPending)
    }

    @Test
    fun capturedSeedChunkIsNotRetriedAfterGenerationChange() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 0))
        val manga = db.upsertManga(DbManga(name = "seed", link = "/seed"))
        val hub = FakeHub()
        hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""")
        hub.responses += HttpResponse(200, """{"epoch":2,"head":5,"hlc":1,"ents":[]}""")
        hub.responses += HttpResponse(200, """{"epoch":2,"head":6,"hlc":2,"ents":[]}""")

        service(db, hub).sync(1, db.settings())

        assertTrue(hub.requests[0].body!!.contains(manga.id.toString()))
        assertTrue(hub.requests.drop(1).all { request ->
            Json.parseToJsonElement(request.body!!).jsonObject["ops"]!!.jsonArray.isEmpty()
        })
    }

    @Test
    fun legacyEpochRowsAreDroppedAndOnlyCurrentEpochIsSent() = runTest {
        val db = InMemoryYokanDatabase(
            emptySnapshot().copy(
                syncPreferences = listOf(
                    DbSyncPreference(
                        syncId = 1,
                        server = "https://hub.test",
                        authToken = "tok",
                        syncOn = true,
                        hubHead = 1,
                        hubEpoch = 2,
                    ),
                ),
                outbox = listOf(
                    DbOutboxOp(SyncPaths.KIND_MANGA, 31, "name", "\"legacy\"", 1, 1),
                    DbOutboxOp(SyncPaths.KIND_MANGA, 32, "name", "\"current\"", 2, 2, epoch = 2),
                ),
            ),
        )
        val hub = FakeHub()
        hub.responses += HttpResponse(200, """{"epoch":2,"head":2,"hlc":1,"ents":[]}""")

        service(db, hub).pushChanges(1)

        val body = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject
        assertEquals(listOf(32L), body["ops"]!!.jsonArray.map { it.jsonObject["id"]!!.jsonPrimitive.long })
        assertEquals(1, body["generation"]!!.jsonPrimitive.content.toInt())
    }

    @Test
    fun editCreatedDuringRecoveryIsSentAfterRecoveryCompletes() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        db.upsertSyncPreference(
            db.syncPreferences().single().copy(hubEpoch = 2, hubHead = 0, hubRecoveryPending = true),
        )
        val hub = FakeHub()
        hub.onRequest = { if (hub.requests.size == 1) db.upsertManga(DbManga(name = "after recovery")) }
        hub.responses += HttpResponse(200, """{"epoch":2,"head":8,"hlc":1,"ents":[]}""")
        service(db, hub).sync(1, db.settings())
        assertFalse(db.outbox().isEmpty())
        assertTrue(db.outbox().all { it.epoch == 2 })
        assertFalse(db.syncPreferences().single().hubRecoveryPending)

        hub.onRequest = {}
        hub.responses += HttpResponse(200, """{"epoch":2,"head":9,"hlc":2,"ents":[]}""")
        service(db, hub).sync(1, db.settings())

        val sent = Json.parseToJsonElement(hub.requests.last().body!!).jsonObject["ops"]!!.jsonArray
        assertTrue(sent.isNotEmpty())
        assertEquals(1, Json.parseToJsonElement(hub.requests.last().body!!).jsonObject["generation"]!!.jsonPrimitive.content.toInt())
    }

    @Test
    fun editsMadeDuringTheRequestWinOverTheIncomingDoc() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        db.upsertSyncPreference(
            db.syncPreferences().single().copy(hubHead = 1, hubEpoch = 1, hubBootstrapComplete = true),
        ) // established device: no seed round
        val manga = db.upsertManga(DbManga(name = "Local", link = "/t", sourceId = 5, favorite = false))
        val hub = FakeHub()
        hub.onRequest = { db.upsertManga(db.manga(manga.id)!!.copy(favorite = true)) } // user taps while the request is in flight
        hub.responses += HttpResponse(200, """{"epoch":1,"head":2,"hlc":1,"ents":[{"k":2,"id":${manga.id},"doc":{"name":"Remote","favorite":false}}]}""")
        service(db, hub).sync(1, db.settings())
        val after = db.manga(manga.id)!!
        assertEquals("Remote", after.name)
        assertTrue(after.favorite, "the in-flight local edit is kept")
        assertEquals(listOf("favorite"), db.outbox().map { it.path }, "and still pending for the next round")
    }

    @Test
    fun pendingTitleDeleteSuppressesAnInFlightLiveDocument() = runTest {
        val id = 42L
        val db = InMemoryYokanDatabase(
            emptySnapshot().copy(
                syncPreferences = listOf(DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true)),
                outbox = listOf(DbOutboxOp(SyncPaths.KIND_MANGA, id, SyncPaths.DELETED, "true", 1, 1, epoch = 1)),
            ),
        )
        val hub = FakeHub()
        hub.responses += HttpResponse(200, """{"epoch":1,"head":2,"hlc":1,"ents":[{"k":2,"id":$id,"doc":{"name":"resurrected"}}]}""")

        service(db, hub).pullChanges(1)

        assertNull(db.manga(id))
        assertEquals("true", db.outbox().single().value)
        assertEquals(2L, db.syncPreferences().single().hubHead)
    }

    @Test
    fun remoteTitleTombstoneRemovesDependentRowsWithoutCreatingOutboxOps() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true))
        val manga = db.upsertManga(DbManga(name = "Title"))
        val chapter = db.upsertChapter(DbChapter(mangaId = manga.id, name = "Chapter"))
        db.upsertHistory(DbHistory(mangaId = manga.id, chapterId = chapter.id, itemType = eu.friedcutlet.yokan.database.DbItemType.Manga))
        db.upsertUpdate(DbUpdate(mangaId = manga.id, chapterId = chapter.id))
        val pendingOutbox = db.outbox()
        val hub = FakeHub()
        hub.responses += HttpResponse(200, """{"epoch":1,"head":2,"hlc":1,"ents":[{"k":2,"id":${manga.id},"del":true}]}""")

        service(db, hub).pullChanges(1)

        assertNull(db.manga(manga.id))
        assertTrue(db.chapters(manga.id).isEmpty())
        assertTrue(db.histories().isEmpty())
        assertTrue(db.updates().isEmpty())
        assertEquals(pendingOutbox, db.outbox(), "remote deletion creates no echo ops or discards unrelated pending ops")
        assertEquals(2L, db.syncPreferences().single().hubHead)
    }

    @Test
    fun historyAndUpdateTombstonesSyncWhileTheirContentFlagsAreOff() = runTest {
        val db = InMemoryYokanDatabase(
            emptySnapshot().copy(
                syncPreferences = listOf(DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true, syncHistories = false, syncUpdates = false)),
                outbox = listOf(
                    DbOutboxOp(SyncPaths.KIND_HISTORY, 11, SyncPaths.DELETED, "true", 1, 1, epoch = 1),
                    DbOutboxOp(SyncPaths.KIND_HISTORY, 11, "date", "\"today\"", 2, 2, epoch = 1),
                    DbOutboxOp(SyncPaths.KIND_UPDATE, 12, SyncPaths.DELETED, "true", 3, 3, epoch = 1),
                    DbOutboxOp(SyncPaths.KIND_UPDATE, 12, "chapterName", "\"Chapter\"", 4, 4, epoch = 1),
                ),
            ),
        )
        val hub = FakeHub()
        hub.responses += HttpResponse(200, """{"epoch":1,"head":2,"hlc":1,"ents":[{"k":5,"id":21,"del":true},{"k":6,"id":22,"del":true},{"k":5,"id":23,"doc":{"date":"today","itemType":"Manga"}},{"k":6,"id":24,"doc":{"chapterName":"Chapter"}}]}""")

        service(db, hub).sync(1, db.settings())

        val sent = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject["ops"]!!.jsonArray
        assertEquals(setOf(5, 6), sent.map { it.jsonObject["k"]!!.jsonPrimitive.content.toInt() }.toSet())
        assertTrue(sent.all { it.jsonObject["p"]!!.jsonPrimitive.content == SyncPaths.DELETED })
        assertEquals(setOf("date", "chapterName"), db.outbox().map { it.path }.toSet())
        assertTrue(db.histories().isEmpty())
        assertTrue(db.updates().isEmpty())
        assertEquals(2L, db.syncPreferences().single().hubHead)
    }

    @Test
    fun activeDownloadDefersRemoteTitleDeleteAndKeepsCursor() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true))
        val manga = db.upsertManga(DbManga(name = "Downloading"))
        val chapter = db.upsertChapter(DbChapter(mangaId = manga.id))
        db.upsertDownload(DbDownload(chapterId = chapter.id, isStartDownload = true, isDownload = false))
        val hub = FakeHub()
        hub.responses += HttpResponse(200, """{"epoch":1,"head":9,"hlc":1,"ents":[{"k":2,"id":${manga.id},"del":true}]}""")

        val result = service(db, hub).pullChanges(1)

        assertTrue(result.errors.any { it.contains("active chapter download") }, result.errors.toString())
        assertEquals(1L, db.syncPreferences().single().hubHead)
        assertNotNull(db.manga(manga.id))
        assertNotNull(db.chapter(chapter.id))
    }

    @Test
    fun maintenanceAndExpiredSessionAreReportedNotRetried() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        val hub = FakeHub()
        hub.responses += HttpResponse(503, """{"error":"maintenance"}""")
        assertTrue(service(db, hub).pullChanges(1).errors.single().contains("maintenance"))
        hub.responses += HttpResponse(401, "")
        assertTrue(service(db, hub).pullChanges(1).errors.single().contains("log in"))
        assertNull(db.syncPreferences().single().authToken)
    }

    @Test
    fun pagedPullReportsProgressAgainstTheHubTip() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 100, hubBootstrapComplete = true))
        val monitor = SyncOperationMonitor()
        val hub = FakeHub()
        hub.responses += HttpResponse(200, """{"epoch":1,"head":150,"tip":300,"hlc":1,"more":true}""")
        hub.responses += HttpResponse(200, """{"epoch":1,"head":300,"tip":300,"hlc":2,"more":false}""")
        val seen = mutableListOf<Float?>()
        hub.onRequest = { seen += monitor.state.value.progress }

        service(db, hub, monitor).pullChanges(1)

        assertEquals(listOf(null, 0.25f), seen)
        assertNull(monitor.state.value.progress, "finished rounds drop stale progress")
    }

    @Test
    fun cancellingHttpRoundCleansObservableOperationState() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        loggedIn(db)
        db.upsertSyncPreference(
            db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true),
        )
        val started = CompletableDeferred<Unit>()
        val hub = FakeHub().apply {
            suspendOnRequest = {
                started.complete(Unit)
                awaitCancellation()
            }
        }
        val monitor = SyncOperationMonitor()
        val service = service(db, hub, monitor)
        val job = launch { service.pullChanges(1) }
        started.await()
        assertTrue(monitor.state.value.isActive)

        job.cancelAndJoin()

        assertFalse(monitor.state.value.isActive)
        assertEquals(SyncOperationOutcome.Cancelled, monitor.state.value.lastOutcome)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncTestFixtures.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncTestFixtures.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncTestFixtures.kt).

The implementation below defines `FakeHub`, `request`, `loggedIn`, `TestScope.service`.

Cross-chapter imports used by this file: [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`InMemoryYokanDatabase`](../chapters/03-persistence-and-migrations.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md), [`HttpResponse`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlinx.coroutines.test.TestScope

internal class FakeHub : HttpService {
    val requests = mutableListOf<HttpRequest>()
    val responses = ArrayDeque<HttpResponse>()
    var onRequest: (HttpRequest) -> Unit = {}
    var suspendOnRequest: suspend (HttpRequest) -> Unit = {}

    override suspend fun request(request: HttpRequest): HttpResponse {
        requests += request
        onRequest(request)
        suspendOnRequest(request)
        return responses.removeFirstOrNull() ?: HttpResponse(500, "")
    }
}

internal fun loggedIn(db: InMemoryYokanDatabase) {
    db.upsertSyncPreference(DbSyncPreference(syncId = 1, server = "https://hub.test", email = "a@b", authToken = "tok", syncOn = true, deviceId = "dev1"))
}

internal fun TestScope.service(
    db: InMemoryYokanDatabase,
    hub: FakeHub,
    monitor: SyncOperationMonitor = SyncOperationMonitor(),
) = HubSyncService(db, hub, webSocketEngine = null, autoSync = false, scope = backgroundScope, operationMonitor = monitor)
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/HybridSyncServiceTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/HybridSyncServiceTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/HybridSyncServiceTest.kt).

The implementation below defines `HybridSyncServiceTest`, `routesEveryCallToTheSelectedProvider`, `stateSyncProvidersOwnLoginAndBrowserSignIn`, `missingStateSyncServiceReportsUnavailable`, `Recorder`, `record`, `login`, `beginBrowserLogin`, `logout`, `sync` and 9 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

- `routesEveryCallToTheSelectedProvider`
- `stateSyncProvidersOwnLoginAndBrowserSignIn`
- `missingStateSyncServiceReportsUnavailable`

Cross-chapter imports used by this file: [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`InMemoryYokanDatabase`](../chapters/03-persistence-and-migrations.md), [`SyncServerProvider`](../chapters/02-domain-and-settings-models.md), [`emptySnapshot`](../chapters/03-persistence-and-migrations.md), [`BackupOptions`](../chapters/20-backup-and-restore.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.backup.BackupOptions
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.coroutines.test.runTest

class HybridSyncServiceTest {
    @Test
    fun routesEveryCallToTheSelectedProvider() = runTest {
        val cases = listOf(
            DbSyncPreference(syncId = 1, server = "https://hub.test") to "hub",
            DbSyncPreference(syncId = 1, server = cloudServerUri("google-drive")) to "cloud",
            DbSyncPreference(syncId = 1, server = "https://m.test", serverProvider = SyncServerProvider.Mangayomi) to "mangayomi",
            DbSyncPreference(syncId = 1, server = "https://sync.test", serverProvider = SyncServerProvider.SyncYomi) to "syncyomi",
            // A state-sync provider owns its calls even if a cloud:// server string was left behind.
            DbSyncPreference(syncId = 1, server = cloudServerUri("google-drive"), serverProvider = SyncServerProvider.GoogleDrive) to "gdrive",
        )
        for ((preference, expected) in cases) {
            val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(preference)))
            val hub = Recorder("hub"); val cloud = CloudRecorder(); val mangayomi = Recorder("mangayomi")
            val syncYomi = Recorder("syncyomi"); val drive = Recorder("gdrive")
            val calls = listOf(hub, cloud, mangayomi, syncYomi, drive)
            val hybrid = HybridSyncService(hub, cloud, db, mangayomiSync = mangayomi, syncYomiSync = syncYomi, googleDriveSync = drive)

            hybrid.sync(1, DbSettings()); hybrid.pushChanges(1); hybrid.pullChanges(1); hybrid.status(1); hybrid.logout(1)
            assertEquals(List(5) { expected }, calls.flatMap { it.calls }, "routing for $expected")
        }
    }

    @Test
    fun stateSyncProvidersOwnLoginAndBrowserSignIn() = runTest {
        for ((provider, expected) in listOf(SyncServerProvider.SyncYomi to "syncyomi", SyncServerProvider.GoogleDrive to "gdrive")) {
            val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(DbSyncPreference(syncId = 1, serverProvider = provider))))
            val hub = Recorder("hub"); val cloud = CloudRecorder(); val syncYomi = Recorder("syncyomi"); val drive = Recorder("gdrive")
            val hybrid = HybridSyncService(hub, cloud, db, syncYomiSync = syncYomi, googleDriveSync = drive)
            hybrid.login(1, "cloud://google-drive", "", "secret")
            hybrid.beginBrowserLogin(1, "client")
            assertEquals(listOf(expected, expected), listOf(hub, cloud, syncYomi, drive).flatMap { it.calls })
        }
    }

    @Test
    fun missingStateSyncServiceReportsUnavailable() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(DbSyncPreference(syncId = 1, serverProvider = SyncServerProvider.GoogleDrive))))
        val hybrid = HybridSyncService(Recorder("hub"), CloudRecorder(), db)
        assertEquals(listOf("Google Drive sync is unavailable."), hybrid.sync(1, DbSettings()).errors)
    }

    private open class Recorder(private val name: String) : SyncService {
        val calls = mutableListOf<String>()
        private fun record() { calls += name }
        override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult { record(); return SyncLoginResult(true, name) }
        override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? { record(); return null }
        override suspend fun logout(syncId: Long) = record()
        override suspend fun sync(syncId: Long, settings: DbSettings): SyncResult { record(); return SyncResult(0, 0, false) }
        override suspend fun pushChanges(syncId: Long): SyncResult { record(); return SyncResult(0, 0, false) }
        override suspend fun pullChanges(syncId: Long): SyncResult { record(); return SyncResult(0, 0, false) }
        override fun status(syncId: Long): SyncConnectionStatus { record(); return SyncConnectionStatus(true, null, name, null) }
    }

    private class CloudRecorder : Recorder("cloud"), CloudBackupSyncService {
        override fun providers(): List<CloudProviderDescriptor> = emptyList()
        override fun isCloudPreference(syncPreference: DbSyncPreference?): Boolean = syncPreference?.server?.startsWith(CloudServerPrefix) == true
        override suspend fun connect(syncId: Long, providerId: String, accountLabel: String?, accessToken: String) = SyncLoginResult(true, "")
        override suspend fun uploadBackup(syncId: Long, options: BackupOptions): CloudBackupResult = error("unused")
        override suspend fun restoreLatestBackup(syncId: Long): CloudBackupRestoreResult = error("unused")
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncMapperTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncMapperTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncMapperTest.kt).

The implementation below defines `MangayomiSyncMapperTest`, `incoming`, `wireIds`, `librarySizedSync`, `remotePages`, `page`, `categoryRow`, `mangaRow`, `deletion`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `unsupportedTitleStatusesSurviveLegacyUnknownRoundTrips`
- `legacyChapterUpdatesPreserveLocalNumberingAndDiscoveryDate`
- `legacyChaptersSendTheEffectiveFillerMarkAndPullsKeepTheLocalOverride`
- `remoteUpdateKeepsLocalNoteAndOutgoingPayloadOmitsIt`
- `mappingsSurviveRestartAndAreAccountScoped`
- `remappedStaleRowKeepsLocalAndDeviceOnlyState`
- `laterPageParentResolvesChildAndTombstoneDeletesExplicitly`
- `rejectsMalformedWireIdsAndUnresolvedReferences`
- `decodeRealPageAcceptsNullSyncedAtOnlyWhileMorePagesRemain`
- `categoryNamesAreNotIdentityAndPathCaseScopesMappings`
- `remapRoundTripsAliasWithoutPromotingItAndOldTombstoneCannotDeleteCanonical`
- `explicitRemapCanPromoteHistoricalAliasAndForeignKeysFollowIt`
- `pendingDeleteIsNotResurrectedAndRecreationUsesFreshId`
- `recreationTransitionIsOneTimePersistsAndDeletesOldIdBeforeUploadingNewId`
- `recreatedMangaRotatesChildrenSoServerCascadeTombstonesCannotDeleteThem`
- `ownershipAndMalformedRowsFailBeforeStateChanges`
- The remaining 11 cases are included in the complete listing below.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.database.sync.SyncPaths
import kotlinx.serialization.json.*
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue

class MangayomiSyncMapperTest {
    private val ns = MangayomiNamespace("https://sync.example/", "account")
    private val pref = DbSyncPreference(syncHistories = true, syncUpdates = true)

    @Test fun unsupportedTitleStatusesSurviveLegacyUnknownRoundTrips() {
        for (status in listOf(DbStatus.Licensed, DbStatus.Upcoming)) {
            val cast = listOf(eu.friedcutlet.yokan.domain.TitleCredit("Actor", "Voice actor", "Hero"))
            val current = emptySnapshot().copy(mangas = listOf(DbManga(id = 10, source = "s", link = "/m", status = status, updatedAt = 20, cast = cast)))
            val mapper = MangayomiSyncMapper(null, ns)
            val batch = mapper.prepare(current, pref).first { it.kind == SyncPaths.KIND_MANGA }
            val wire = requireNotNull(mapper.encode(current, batch)["manga"]).jsonArray.single().jsonObject
            assertEquals("UNKNOWN", wire.getValue("status").jsonPrimitive.content)
            assertTrue(!wire.containsKey("cast"))
            fun incoming(at: Int, wireStatus: String) = page(
                buildJsonObject {
                    put(
                        "manga",
                        JsonArray(
                            listOf(
                                buildJsonObject {
                                    wire.forEach { (key, value) -> put(key, value) }
                                    put("updatedAt", at)
                                    put("name", "Remote title")
                                    put("status", wireStatus)
                                }
                            )
                        )
                    )
                }
            )
            val roundTrip = mapper.merge(current, listOf(incoming(21, "UNKNOWN")), pref).snapshot
            assertEquals(status, roundTrip.mangas.single().status)
            assertEquals(cast, roundTrip.mangas.single().cast)
            assertEquals("Remote title", roundTrip.mangas.single().name)
            val changed = mapper.merge(roundTrip, listOf(incoming(22, "ONGOING")), pref).snapshot
            assertEquals(DbStatus.Ongoing, changed.mangas.single().status)
        }
    }

    @Test fun legacyChapterUpdatesPreserveLocalNumberingAndDiscoveryDate() {
        val local = DbChapter(
            id = 11, mangaId = 10, url = "/episode", name = "Opening Night", updatedAt = 20,
            fetchedAt = 777, number = 12.5, season = 0, numberingName = "Episode 12.5 [English]",
        )
        val current = emptySnapshot().copy(
            mangas = listOf(DbManga(id = 10, source = "s", link = "/m", updatedAt = 20)),
            chapters = listOf(local),
        )
        val mapper = MangayomiSyncMapper(null, ns)
        val batch = mapper.prepare(current, pref).first { it.kind == SyncPaths.KIND_CHAPTER }
        val wire = requireNotNull(mapper.encode(current, batch)["chapters"]).jsonArray.single().jsonObject
        assertTrue(listOf("number", "season", "numberingName", "fetchedAt").none(wire::containsKey))
        val incoming = buildJsonObject {
            wire.forEach { (key, value) -> put(key, value) }
            put("updatedAt", 21)
            put("name", "Remote title")
        }
        val merged = mapper.merge(current, listOf(page(buildJsonObject { put("chapters", JsonArray(listOf(incoming))) })), pref)
        val chapter = merged.snapshot.chapters.single()
        assertEquals("Remote title", chapter.name)
        assertEquals(local.fetchedAt, chapter.fetchedAt)
        assertEquals(local.number, chapter.number)
        assertEquals(local.season, chapter.season)
        assertEquals(local.numberingName, chapter.numberingName)
    }

    @Test fun legacyChaptersSendTheEffectiveFillerMarkAndPullsKeepTheLocalOverride() {
        val local = DbChapter(id = 11, mangaId = 10, url = "/episode", name = "Episode 1", updatedAt = 20, isFiller = false, fillerOverride = true)
        val current = emptySnapshot().copy(
            mangas = listOf(DbManga(id = 10, source = "s", link = "/m", updatedAt = 20)),
            chapters = listOf(local),
        )
        val mapper = MangayomiSyncMapper(null, ns)
        val batch = mapper.prepare(current, pref).first { it.kind == SyncPaths.KIND_CHAPTER }
        val wire = requireNotNull(mapper.encode(current, batch)["chapters"]).jsonArray.single().jsonObject
        assertEquals(true, wire.getValue("isFiller").jsonPrimitive.boolean)
        assertTrue(!wire.containsKey("fillerOverride"))
        // Another client unmarks it; Mangayomi's value becomes the source value, the local override still wins.
        val incoming = buildJsonObject {
            wire.forEach { (key, value) -> put(key, value) }
            put("updatedAt", 21)
            put("isFiller", false)
        }
        val chapter = mapper.merge(current, listOf(page(buildJsonObject { put("chapters", JsonArray(listOf(incoming))) })), pref).snapshot.chapters.single()
        assertEquals(false, chapter.isFiller)
        assertEquals(true, chapter.fillerOverride)
        assertTrue(chapter.effectiveFiller)
    }

    @Test fun remoteUpdateKeepsLocalNoteAndOutgoingPayloadOmitsIt() {
        val current = emptySnapshot().copy(
            mangas = listOf(
                DbManga(id = 10, source = "s", link = "/m", name = "local", updatedAt = 20, privateNote = "秘密\nprivate"),
            )
        )
        val mapper = MangayomiSyncMapper(null, ns)
        val batch = mapper.prepare(current, pref).first { it.kind == SyncPaths.KIND_MANGA }
        val wire = mapper.encode(current, batch)
        assertTrue(!wire.toString().contains("private"))
        val incoming = mangaRow(900, 21, "s", "/m", "remote")
        val merged = mapper.merge(current, listOf(page(buildJsonObject { put("manga", JsonArray(listOf(incoming))) })), pref)
        assertEquals("remote", merged.snapshot.mangas.single().name)
        assertEquals("秘密\nprivate", merged.snapshot.mangas.single().privateNote)
    }

    @Test fun mappingsSurviveRestartAndAreAccountScoped() {
        val mapper = MangayomiSyncMapper(null, ns)
        val snap = emptySnapshot().copy(categories = listOf(DbCategory(id = 88, name = "Reading", forItemType = DbItemType.Manga)))
        val a = mapper.prepare(snap, pref).first { it.kind == SyncPaths.KIND_CATEGORY }
        val wireId = mapper.encode(snap, a)["categories"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long
        val restarted = MangayomiSyncMapper(mapper.mappingsJson(), ns)
        assertEquals(wireId, restarted.encode(snap, a)["categories"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long)
        val other = MangayomiSyncMapper(mapper.mappingsJson(), MangayomiNamespace(ns.server, "other"))
        val otherId = other.prepare(snap, pref).first { it.kind == SyncPaths.KIND_CATEGORY }.let { other.encode(snap, it)["categories"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long }
        assertNotEquals(wireId, otherId)
    }

    @Test fun remappedStaleRowKeepsLocalAndDeviceOnlyState() {
        val current = emptySnapshot().copy(
            mangas = listOf(DbManga(id = 10, source = "s", link = "/m", itemType = DbItemType.Manga, name = "local", updatedAt = 20, customCoverImage = byteArrayOf(1, 2))),
        )
        val mapper = MangayomiSyncMapper(null, ns)
        val manga = mangaRow(900, 19, "s", "/m", "remote")
        val page = page(
            buildJsonObject {
                put("manga", JsonArray(listOf(manga)))
                put("mangaClientIdRemap", buildJsonObject { put("700", 900) })
            }
        )
        val merged = mapper.merge(current, listOf(page), pref)
        assertEquals(10L, merged.snapshot.mangas.single().id)
        assertEquals("local", merged.snapshot.mangas.single().name)
        assertTrue(merged.snapshot.mangas.single().customCoverImage!!.contentEquals(byteArrayOf(1, 2)))
        assertTrue(mapper.mappingsJson().contains("\"10\""))
    }

    @Test fun laterPageParentResolvesChildAndTombstoneDeletesExplicitly() {
        val mapper = MangayomiSyncMapper(null, ns)
        val chapter = buildJsonObject {
            put("clientId", 22)
            put("mangaClientId", 11)
            put("name", "c1")
            put("url", "u")
            put("updatedAt", 2)
        }
        val manga = mangaRow(11, 1, "s", "l", "m")
        val merged = mapper.merge(emptySnapshot(), listOf(page(buildJsonObject { put("chapters", JsonArray(listOf(chapter))) }), page(buildJsonObject { put("manga", JsonArray(listOf(manga))) })), pref)
        assertEquals(1, merged.snapshot.chapters.size)
        val mangaRemote = mapper.mappingsJson()
        val tomb = page(buildJsonObject { put("tombstones", buildJsonObject { put("manga", JsonArray(listOf(JsonPrimitive(11)))) }) })
        val deleted = mapper.merge(merged.snapshot, listOf(tomb), pref)
        assertTrue(deleted.snapshot.mangas.isEmpty())
        assertTrue(mangaRemote.isNotEmpty())
    }

    @Test fun rejectsMalformedWireIdsAndUnresolvedReferences() {
        val mapper = MangayomiSyncMapper(null, ns)
        val invalid = buildJsonObject {
            put(
                "manga",
                JsonArray(
                    listOf(
                        buildJsonObject {
                            put("clientId", 9007199254740992.0)
                            put("updatedAt", 1)
                        }
                    )
                )
            )
        }
        assertFails { mapper.merge(emptySnapshot(), listOf(page(invalid)), pref) }
        val orphan = buildJsonObject {
            put(
                "chapters",
                JsonArray(
                    listOf(
                        buildJsonObject {
                            put("clientId", 2)
                            put("mangaClientId", 99)
                            put("updatedAt", 1)
                        }
                    )
                )
            )
        }
        assertFails { mapper.merge(emptySnapshot(), listOf(page(orphan)), pref) }
        val orphanHistory = buildJsonObject {
            put(
                "histories",
                JsonArray(
                    listOf(
                        buildJsonObject {
                            put("clientId", 3)
                            put("mangaClientId", 99)
                            put("chapterClientId", 98)
                            put("itemType", "MANGA")
                            put("updatedAt", 1)
                        }
                    )
                )
            )
        }
        assertFails { mapper.merge(emptySnapshot(), listOf(page(orphanHistory)), pref) }
        assertFails { mapper.merge(emptySnapshot(), listOf(page(buildJsonObject { put("manga", "not an array") })), pref) }
    }

    @Test fun decodeRealPageAcceptsNullSyncedAtOnlyWhileMorePagesRemain() {
        val mapper = MangayomiSyncMapper(null, ns)
        val ongoing = mapper.decodePage("""{"data":{"manga":[]},"cursors":{"manga":"next"},"hasMore":true,"syncedAt":null}""")
        assertTrue(ongoing.hasMore)
        assertEquals(null, ongoing.syncedAt)
        assertFails { mapper.decodePage("""{"data":{},"hasMore":false,"syncedAt":null}""") }
        assertEquals(4L, mapper.decodePage("""{"data":{},"hasMore":false,"syncedAt":4}""").syncedAt)
        assertFails { mapper.decodePage("""{"data":{},"syncedAt":4}""") }
    }

    @Test fun categoryNamesAreNotIdentityAndPathCaseScopesMappings() {
        val snapshot = emptySnapshot().copy(categories = listOf(DbCategory(1, "Read", DbItemType.Manga), DbCategory(2, "Read", DbItemType.Manga)))
        val mapper = MangayomiSyncMapper(null, ns)
        val batches = mapper.prepare(snapshot, pref)
        assertEquals(2, batches.first { it.kind == SyncPaths.KIND_CATEGORY }.localIds.size)
        val lower = MangayomiSyncMapper(null, MangayomiNamespace("https://sync.example/accounta", "account"))
        val a = mapper.encode(snapshot, batches.first { it.kind == SyncPaths.KIND_CATEGORY })["categories"]!!.jsonArray.map { it.jsonObject["clientId"]!!.jsonPrimitive.long }
        val bBatch = lower.prepare(snapshot, pref).first { it.kind == SyncPaths.KIND_CATEGORY }
        val b = lower.encode(snapshot, bBatch)["categories"]!!.jsonArray.map { it.jsonObject["clientId"]!!.jsonPrimitive.long }
        assertNotEquals(a, b)
        val upper = MangayomiSyncMapper(null, MangayomiNamespace("https://sync.example/AccountA", "account"))
        val upperBatch = upper.prepare(snapshot, pref).first { it.kind == SyncPaths.KIND_CATEGORY }
        assertNotEquals(b, upper.encode(snapshot, upperBatch)["categories"]!!.jsonArray.map { it.jsonObject["clientId"]!!.jsonPrimitive.long })
        val remote = page(buildJsonObject { put("categories", JsonArray(listOf(categoryRow(51, "Read"), categoryRow(52, "Read")))) })
        assertEquals(2, MangayomiSyncMapper(null, ns).merge(emptySnapshot(), listOf(remote), pref).snapshot.categories.distinctBy { it.id }.size)
    }

    @Test fun remapRoundTripsAliasWithoutPromotingItAndOldTombstoneCannotDeleteCanonical() {
        val mapper = MangayomiSyncMapper(null, ns)
        val snap = emptySnapshot().copy(mangas = listOf(DbManga(id = 5, source = "s", link = "l", itemType = DbItemType.Manga)))
        val batch = mapper.prepare(snap, pref).first { it.kind == SyncPaths.KIND_MANGA }
        val old = mapper.encode(snap, batch)["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long
        val page = page(
            buildJsonObject {
                put("mangaClientIdRemap", buildJsonObject { put(old.toString(), 777) })
                put("manga", JsonArray(listOf(mangaRow(777, 10, "s", "l", "m"))))
            }
        )
        mapper.acceptRemaps(page)
        mapper.merge(snap, listOf(page), pref)
        val persisted = mapper.mappingsJson()
        val restarted = MangayomiSyncMapper(persisted, ns)
        val newBatch = restarted.prepare(snap, pref).first { it.kind == SyncPaths.KIND_MANGA }
        assertEquals(777L, restarted.encode(snap, newBatch)["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long)
        restarted.merge(snap, listOf(page(buildJsonObject { put("manga", JsonArray(listOf(mangaRow(old, 11, "s", "l", "old alias")))) })), pref)
        val afterAlias = restarted.prepare(snap, pref).first { it.kind == SyncPaths.KIND_MANGA }
        assertEquals(777L, restarted.encode(snap, afterAlias)["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long)
        val obsolete = page(buildJsonObject { put("tombstones", buildJsonObject { put("manga", JsonArray(listOf(JsonPrimitive(old)))) }) })
        assertEquals(1, restarted.merge(snap, listOf(obsolete), pref).snapshot.mangas.size)
    }

    @Test fun explicitRemapCanPromoteHistoricalAliasAndForeignKeysFollowIt() {
        val mapper = MangayomiSyncMapper(null, ns)
        val current = emptySnapshot().copy(mangas = listOf(DbManga(id = 5, source = "s", link = "l")), chapters = listOf(DbChapter(id = 6, mangaId = 5, url = "u")))
        val initial = mapper.prepare(current, pref)
        val old = mapper.encode(current, initial.first { it.kind == SyncPaths.KIND_MANGA })["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long
        mapper.acceptRemaps(page(buildJsonObject { put("mangaClientIdRemap", buildJsonObject { put(old.toString(), 777) }) }))
        mapper.acceptRemaps(page(buildJsonObject { put("mangaClientIdRemap", buildJsonObject { put("777", old) }) }))
        val restarted = MangayomiSyncMapper(mapper.mappingsJson(), ns)
        val batches = restarted.prepare(current, pref)
        val manga = restarted.encode(current, batches.first { it.kind == SyncPaths.KIND_MANGA })["manga"]!!.jsonArray.single().jsonObject
        val chapter = restarted.encode(current, batches.first { it.kind == SyncPaths.KIND_CHAPTER })["chapters"]!!.jsonArray.single().jsonObject
        assertEquals(old, manga["clientId"]!!.jsonPrimitive.long)
        assertEquals(old, chapter["mangaClientId"]!!.jsonPrimitive.long)
        val deleted = current.copy(mangas = emptyList(), chapters = emptyList(), changedParts = listOf(deletion(SyncPaths.KIND_MANGA, 5), deletion(SyncPaths.KIND_CHAPTER, 6)))
        val deleteBatch = restarted.prepare(deleted, pref).first { it.deletions.any { part -> part.data.contains("\"kind\":2") } }
        assertEquals(old, restarted.encode(deleted, deleteBatch)["deleted"]!!.jsonObject["manga"]!!.jsonArray.single().jsonPrimitive.long)
    }

    @Test fun pendingDeleteIsNotResurrectedAndRecreationUsesFreshId() {
        val base = emptySnapshot().copy(mangas = listOf(DbManga(id = 5, source = "s", link = "l", itemType = DbItemType.Manga)))
        val mapper = MangayomiSyncMapper(null, ns)
        val initial = mapper.prepare(base, pref).first { it.kind == SyncPaths.KIND_MANGA }
        val original = mapper.encode(base, initial)["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long
        val pending = base.copy(mangas = emptyList(), changedParts = listOf(deletion(SyncPaths.KIND_MANGA, 5)))
        val resurrect = page(buildJsonObject { put("manga", JsonArray(listOf(mangaRow(original, 99, "s", "l", "remote")))) })
        assertTrue(mapper.merge(pending, listOf(resurrect), pref).snapshot.mangas.isEmpty())
        val recreated = pending.copy(mangas = listOf(DbManga(id = 5, source = "s", link = "l", itemType = DbItemType.Manga)))
        val batch = mapper.prepare(recreated, pref).first { it.kind == SyncPaths.KIND_MANGA }
        val fresh = mapper.encode(recreated, batch)["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long
        assertNotEquals(original, fresh)
        assertTrue(batch.deletions.isEmpty())
        val tomb = page(buildJsonObject { put("tombstones", buildJsonObject { put("manga", JsonArray(listOf(JsonPrimitive(original)))) }) })
        assertEquals(1, mapper.merge(recreated, listOf(tomb), pref).snapshot.mangas.size)
    }

    @Test fun recreationTransitionIsOneTimePersistsAndDeletesOldIdBeforeUploadingNewId() {
        val mapper = MangayomiSyncMapper(null, ns)
        val original = emptySnapshot().copy(mangas = listOf(DbManga(id = 5, source = "s", link = "l")))
        val originalBatch = mapper.prepare(original, pref).first { it.kind == SyncPaths.KIND_MANGA }
        val old = mapper.encode(original, originalBatch)["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long
        val record = deletion(SyncPaths.KIND_MANGA, 5)
        val recreated = original.copy(changedParts = listOf(record))
        val response = page(
            buildJsonObject {
                put("manga", JsonArray(listOf(mangaRow(old, 9, "s", "l", "server"))))
                put("tombstones", buildJsonObject { put("manga", JsonArray(listOf(JsonPrimitive(old)))) })
            }
        )
        assertEquals(1, mapper.merge(recreated, listOf(response), pref).snapshot.mangas.size)
        val batches = mapper.prepare(recreated, pref)
        assertTrue(batches.first().deletions.contains(record))
        assertEquals(old, mapper.encode(recreated, batches.first())["deleted"]!!.jsonObject["manga"]!!.jsonArray.single().jsonPrimitive.long)
        val uploaded = batches.first { it.kind == SyncPaths.KIND_MANGA }.let { mapper.encode(recreated, it)["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long }
        assertNotEquals(old, uploaded)
        assertTrue(batches.indexOfFirst { it.kind == SyncPaths.KIND_MANGA } > batches.indexOfFirst { it.deletions.isNotEmpty() })
        val restarted = MangayomiSyncMapper(mapper.mappingsJson(), ns)
        val again = restarted.prepare(recreated, pref)
        assertEquals(uploaded, restarted.encode(recreated, again.first { it.kind == SyncPaths.KIND_MANGA })["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long)
        val acknowledged = recreated.copy(changedParts = emptyList())
        val afterAck = mapper.prepare(acknowledged, pref).first { it.kind == SyncPaths.KIND_MANGA }
        assertEquals(uploaded, mapper.encode(acknowledged, afterAck)["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long)
        assertTrue(afterAck.deletions.isEmpty())
    }

    @Test fun recreatedMangaRotatesChildrenSoServerCascadeTombstonesCannotDeleteThem() {
        val mapper = MangayomiSyncMapper(null, ns)
        val live = emptySnapshot().copy(
            mangas = listOf(DbManga(id = 5, source = "s", link = "l")),
            chapters = listOf(DbChapter(id = 6, mangaId = 5, url = "u")),
            histories = listOf(DbHistory(id = 7, mangaId = 5, chapterId = 6, itemType = DbItemType.Manga))
        )
        fun wireIds(s: eu.friedcutlet.yokan.database.YokanDatabaseSnapshot, kind: Int, key: String) = mapper.prepare(s, pref).filter { it.kind == kind }
            .flatMap { mapper.encode(s, it)[key]!!.jsonArray.map { r -> r.jsonObject["clientId"]!!.jsonPrimitive.long } }
        val oldChapter = wireIds(live, SyncPaths.KIND_CHAPTER, "chapters").single()
        val oldHistory = wireIds(live, SyncPaths.KIND_HISTORY, "histories").single()
        val recreated = live.copy(changedParts = listOf(deletion(SyncPaths.KIND_MANGA, 5)))
        assertNotEquals(oldChapter, wireIds(recreated, SyncPaths.KIND_CHAPTER, "chapters").single())
        assertNotEquals(oldHistory, wireIds(recreated, SyncPaths.KIND_HISTORY, "histories").single())
        val cascade = page(
            buildJsonObject {
                put(
                    "tombstones",
                    buildJsonObject {
                        put("chapters", JsonArray(listOf(JsonPrimitive(oldChapter))))
                        put("histories", JsonArray(listOf(JsonPrimitive(oldHistory))))
                    }
                )
            }
        )
        val merged = mapper.merge(recreated, listOf(cascade), pref).snapshot
        assertEquals(1, merged.chapters.size)
        assertEquals(1, merged.histories.size)
    }

    @Test fun ownershipAndMalformedRowsFailBeforeStateChanges() {
        val colliding = """{"version":1,"namespaces":{"https://sync.example\naccount":{"2":{"10":{"canonical":5,"aliases":[]},"11":{"canonical":5,"aliases":[]}}}}}"""
        assertFails { MangayomiSyncMapper(colliding, ns) }
        val aliasCollision = """{"version":1,"namespaces":{"https://sync.example\naccount":{"2":{"10":{"canonical":5,"aliases":[7]},"11":{"canonical":8,"aliases":[7]}}}}}"""
        assertFails { MangayomiSyncMapper(aliasCollision, ns) }
        val mapper = MangayomiSyncMapper(null, ns)
        val before = mapper.mappingsJson()
        val malformed = page(buildJsonObject { put("manga", JsonArray(listOf(JsonObject(mangaRow(1, 1, "s", "l", "m") + mapOf("favorite" to JsonPrimitive("yes")))))) })
        assertFails { mapper.merge(emptySnapshot(), listOf(malformed), pref) }
        assertEquals(before, mapper.mappingsJson())
    }

    @Test fun remapOntoAnotherLocalOwnersIdIsIgnoredRatherThanStolenOrFatal() {
        val mapper = MangayomiSyncMapper(null, ns)
        val snap = emptySnapshot().copy(mangas = listOf(DbManga(id = 1, source = "s", link = "same"), DbManga(id = 2, source = "s", link = "same")))
        val batch = mapper.prepare(snap, pref).first { it.kind == SyncPaths.KIND_MANGA }
        val ids = mapper.encode(snap, batch)["manga"]!!.jsonArray.map { it.jsonObject["clientId"]!!.jsonPrimitive.long }
        // What the real server answers when two local duplicates hit one catalog entry.
        mapper.acceptRemaps(page(buildJsonObject { put("mangaClientIdRemap", buildJsonObject { put(ids[1].toString(), ids[0]) }) }))
        val restarted = MangayomiSyncMapper(mapper.mappingsJson(), ns)
        val again = restarted.prepare(snap, pref).first { it.kind == SyncPaths.KIND_MANGA }
        assertEquals(ids, restarted.encode(snap, again)["manga"]!!.jsonArray.map { it.jsonObject["clientId"]!!.jsonPrimitive.long })
    }

    @Test fun unfinishedDownloadsBlockButCompletedDownloadsAllowCascadeCleanup() {
        val mapper = MangayomiSyncMapper(null, ns)
        val current = emptySnapshot().copy(settings = DbSettings(downloadQueueOrder = listOf(3, 1), chapterPageIndexList = listOf(DbChapterPageIndex(chapterId = 2, index = 1))), mangas = listOf(DbManga(id = 1, source = "s", link = "l", itemType = DbItemType.Manga)), chapters = listOf(DbChapter(id = 2, mangaId = 1, archivePath = "archive")), downloads = listOf(DbDownload(id = 3, chapterId = 2, isDownload = false, isStartDownload = true)), pageCache = listOf(DbChapterPageUrls(chapterId = 2, urls = listOf("cached"))))
        val prepared = mapper.prepare(current, pref).first { it.kind == SyncPaths.KIND_MANGA }
        val remote = mapper.encode(current, prepared)["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long
        val tomb = page(buildJsonObject { put("tombstones", buildJsonObject { put("manga", JsonArray(listOf(JsonPrimitive(remote)))) }) })
        // Establish remote identity first, then the cascade safety check uses the canonical binding.
        val mangaPage = page(buildJsonObject { put("manga", JsonArray(listOf(mangaRow(remote, 1, "s", "l", "m")))) })
        val mapped = mapper.merge(current, listOf(mangaPage), pref).snapshot
        assertFails { mapper.merge(current.copy(syncPreferences = emptyList()), listOf(tomb), pref) }
        val done = mapper.merge(mapped.copy(downloads = listOf(DbDownload(id = 3, chapterId = 2, isDownload = true, isStartDownload = true))), listOf(tomb), pref)
        assertTrue(done.snapshot.mangas.isEmpty())
        assertTrue(done.snapshot.chapters.isEmpty())
        assertTrue(done.snapshot.downloads.isEmpty())
        assertTrue(done.snapshot.pageCache.isEmpty())
        assertEquals(listOf(1L), done.snapshot.settings.downloadQueueOrder)
        assertTrue(done.snapshot.settings.chapterPageIndexList.isNullOrEmpty())
    }

    @Test fun encodingDoesNotAllocateIdsAndDanglingLocalReferencesFailPrepare() {
        val mapper = MangayomiSyncMapper(null, ns)
        val dangling = emptySnapshot().copy(mangas = listOf(DbManga(id = 1, categories = listOf(999))))
        assertFails { mapper.prepare(dangling, pref) }
        val before = mapper.mappingsJson()
        val simple = emptySnapshot().copy(categories = listOf(DbCategory(id = 1, "c", DbItemType.Manga)))
        val b = mapper.prepare(simple, pref).first { it.kind == SyncPaths.KIND_CATEGORY }
        val prepared = mapper.mappingsJson()
        mapper.encode(simple, b)
        assertEquals(prepared, mapper.mappingsJson())
        assertNotEquals(before, prepared)
    }

    @Test fun categoryReferencesResolveFromPersistedMappingsWithoutCategoryPage() {
        val current = emptySnapshot().copy(categories = listOf(DbCategory(7, "Read", DbItemType.Manga)))
        val mapper = MangayomiSyncMapper(null, ns)
        val categoryBatch = mapper.prepare(current, pref).first { it.kind == SyncPaths.KIND_CATEGORY }
        val categoryRemote = mapper.encode(current, categoryBatch)["categories"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long
        val manga = mangaRow(101, 1, "s", "l", "m") + mapOf("categoryClientIds" to JsonArray(listOf(JsonPrimitive(categoryRemote))))
        val merged = mapper.merge(current, listOf(page(buildJsonObject { put("manga", JsonArray(listOf(JsonObject(manga)))) })), pref)
        assertEquals(listOf(7L), merged.snapshot.mangas.single().categories)
    }

    @Test fun queuedCategoryDeletionFiltersOnlyThatMembershipDuringBootstrap() {
        val mapper = MangayomiSyncMapper(null, ns)
        val existing = emptySnapshot().copy(categories = listOf(DbCategory(7, "Old", DbItemType.Manga)))
        val categoryBatch = mapper.prepare(existing, pref).first { it.kind == SyncPaths.KIND_CATEGORY }
        val old = mapper.encode(existing, categoryBatch)["categories"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long
        val deleted = existing.copy(categories = emptyList(), changedParts = listOf(deletion(SyncPaths.KIND_CATEGORY, 7)))
        val category = categoryRow(old, "Old")
        val manga = mangaRow(101, 1, "s", "l", "m") + mapOf("categoryClientIds" to JsonArray(listOf(JsonPrimitive(old))))
        val merged = mapper.merge(
            deleted,
            listOf(
                page(
                    buildJsonObject {
                        put("categories", JsonArray(listOf(category)))
                        put("manga", JsonArray(listOf(JsonObject(manga))))
                    }
                )
            ),
            pref
        )
        assertTrue(merged.snapshot.categories.isEmpty())
        assertTrue(merged.snapshot.mangas.single().categories.isNullOrEmpty())
        val deletionBatch = mapper.prepare(merged.snapshot, pref).first { it.deletions.isNotEmpty() }
        assertEquals(old, mapper.encode(merged.snapshot, deletionBatch)["deleted"]!!.jsonObject["categories"]!!.jsonArray.single().jsonPrimitive.long)
    }

    @Test fun multipleDistinctHistoriesOnOneChapterDoNotCollapse() {
        val current = emptySnapshot().copy(mangas = listOf(DbManga(id = 10, source = "s", link = "l")), chapters = listOf(DbChapter(id = 20, mangaId = 10, url = "u")), histories = listOf(DbHistory(id = 30, mangaId = 10, chapterId = 20, itemType = DbItemType.Manga, updatedAt = 1)))
        val mapper = MangayomiSyncMapper(null, ns)
        val batches = mapper.prepare(current, pref)
        val mangaId = mapper.encode(current, batches.first { it.kind == SyncPaths.KIND_MANGA })["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long
        val chapterId = mapper.encode(current, batches.first { it.kind == SyncPaths.KIND_CHAPTER })["chapters"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long
        val rows = listOf(801L, 802L).map { remote ->
            buildJsonObject {
                put("clientId", remote)
                put("mangaClientId", mangaId)
                put("chapterClientId", chapterId)
                put("itemType", "MANGA")
                put("updatedAt", 2)
            }
        }
        val merged = mapper.merge(current, listOf(page(buildJsonObject { put("histories", JsonArray(rows)) })), pref)
        assertEquals(2, merged.snapshot.histories.size)
        assertEquals(2, merged.snapshot.histories.map { it.id }.distinct().size)
    }

    @Test fun decodedChapterDurationRoundTripsAsNumberAndNull() {
        for (duration in listOf<JsonElement>(JsonPrimitive(120), JsonNull)) {
            val mapper = MangayomiSyncMapper(null, ns)
            val current = emptySnapshot().copy(mangas = listOf(DbManga(id = 1, source = "s", link = "l")))
            val mangaBatch = mapper.prepare(current, pref).first { it.kind == SyncPaths.KIND_MANGA }
            val mangaId = mapper.encode(current, mangaBatch)["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long
            val body = """{"data":{"chapters":[{"clientId":77,"mangaClientId":$mangaId,"duration":$duration,"updatedAt":2}]},"hasMore":false,"syncedAt":2}"""
            val merged = mapper.merge(current, listOf(mapper.decodePage(body)), pref)
            assertEquals(if (duration is JsonNull)null else "120", merged.snapshot.chapters.single().duration)
            val chapterBatch = mapper.prepare(merged.snapshot, pref).first { it.kind == SyncPaths.KIND_CHAPTER }
            assertEquals(duration, mapper.encode(merged.snapshot, chapterBatch)["chapters"]!!.jsonArray.single().jsonObject["duration"])
        }
    }

    @Test fun updateKeepsAnExistingConsistentChapterReferenceAfterRename() {
        val current = emptySnapshot().copy(mangas = listOf(DbManga(id = 1, source = "s", link = "l")), chapters = listOf(DbChapter(id = 2, mangaId = 1, name = "old")), updates = listOf(DbUpdate(id = 3, mangaId = 1, chapterId = 2, chapterName = "old", updatedAt = 1)))
        val mapper = MangayomiSyncMapper(null, ns)
        val batches = mapper.prepare(current, pref)
        val mangaId = mapper.encode(current, batches.first { it.kind == SyncPaths.KIND_MANGA })["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long
        val updateId = mapper.encode(current, batches.first { it.kind == SyncPaths.KIND_UPDATE })["updates"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.long
        val response = page(
            buildJsonObject {
                put(
                    "updates",
                    JsonArray(
                        listOf(
                            buildJsonObject {
                                put("clientId", updateId)
                                put("mangaClientId", mangaId)
                                put("chapterName", "renamed")
                                put("updatedAt", 2)
                            }
                        )
                    )
                )
            }
        )
        assertEquals(2L, mapper.merge(current, listOf(response), pref).snapshot.updates.single().chapterId)
    }

    @Test fun encodedRowsStayWithinServerSchemaLimitsWithoutTouchingLocalRows() {
        // Sizes from a real library that made the server reject the whole manga batch with HTTP 400.
        val description = "d".repeat(9_999) + "\uD83D\uDE00" + "tail".repeat(1_000)
        val manga = DbManga(
            id = 1,
            source = "s",
            link = "l",
            name = "n",
            description = description,
            author = "a".repeat(821),
            genre = listOf("g".repeat(150), "Romance")
        )
        val snapshot = emptySnapshot().copy(
            mangas = listOf(manga),
            tracks = listOf(DbTrack(id = 2, mangaId = 1, status = DbTrackStatus.Reading, trackingUrl = "anilist:123"))
        )
        val mapper = MangayomiSyncMapper(null, ns)
        val batches = mapper.prepare(snapshot, pref)
        val row = mapper.encode(snapshot, batches.first { it.kind == SyncPaths.KIND_MANGA })["manga"]!!.jsonArray.single().jsonObject
        val sent = row.getValue("description").jsonPrimitive.content
        assertEquals(9_999, sent.length) // the emoji straddling 10,000 is dropped whole, not split
        assertEquals(500, row.getValue("author").jsonPrimitive.content.length)
        assertEquals(listOf(100, 7), row.getValue("genre").jsonArray.map { it.jsonPrimitive.content.length })
        val track = mapper.encode(snapshot, batches.first { it.kind == SyncPaths.KIND_TRACK })["tracks"]!!.jsonArray.single().jsonObject
        assertEquals(JsonNull, track.getValue("trackingUrl"))
        assertEquals(description, snapshot.mangas.single().description)
    }

    @Test fun deletionRecordsChunkAndTrackNumbersRejectLossyFractions() {
        val parts = (1L..5001L).map { deletion(SyncPaths.KIND_MANGA, it) }
        val mapper = MangayomiSyncMapper(null, ns)
        val populated = emptySnapshot().copy(mangas = (1L..5001L).map { DbManga(id = it, source = "s", link = "l$it") })
        mapper.prepare(populated, pref)
        val snap = populated.copy(mangas = emptyList(), changedParts = parts)
        val chunks = mapper.prepare(snap, pref).filter { it.deletions.isNotEmpty() }.map { it.deletions }
        assertEquals(listOf(5000, 1), chunks.map { it.size })
        val manga = mangaRow(1, 1, "s", "l", "m")
        val track = buildJsonObject {
            put("clientId", 2)
            put("mangaClientId", 1)
            put("itemType", "MANGA")
            put("status", "READING")
            put("score", 2.5)
            put("updatedAt", 2)
        }
        val bad = page(
            buildJsonObject {
                put("manga", JsonArray(listOf(manga)))
                put("tracks", JsonArray(listOf(track)))
            }
        )
        assertFails { mapper.merge(emptySnapshot(), listOf(bad), pref) }
        val whole = track.toMutableMap().let { JsonObject(it + mapOf("score" to JsonPrimitive(2.0))) }
        val good = page(
            buildJsonObject {
                put("manga", JsonArray(listOf(manga)))
                put("tracks", JsonArray(listOf(whole)))
            }
        )
        assertEquals(2, mapper.merge(emptySnapshot(), listOf(good), pref).snapshot.tracks.single().score)
    }

    @Test fun prepareEncodeAndMergeStayNearLinearAtLibraryScale() {
        librarySizedSync(mangaCount = 600, chaptersPerManga = 70)
    }

    private fun librarySizedSync(mangaCount: Int, chaptersPerManga: Int) {
        val mangas = (1L..mangaCount).map { DbManga(id = it, source = "s", link = "/m$it", itemType = DbItemType.Manga, updatedAt = 1) }
        val chapters = mangas.flatMap { m -> (1L..chaptersPerManga).map { c -> DbChapter(id = m.id * 1000 + c, mangaId = m.id, name = "c$c", url = "/m${m.id}/$c", updatedAt = 1) } }
        val histories = mangas.map { m -> DbHistory(id = m.id, mangaId = m.id, chapterId = m.id * 1000 + 1, itemType = DbItemType.Manga, updatedAt = 1) }
        val local = emptySnapshot().copy(mangas = mangas, chapters = chapters, histories = histories)
        val mapper = MangayomiSyncMapper(null, ns)
        val encoded = mapper.prepare(local, pref).map { mapper.encode(local, it) }
        assertEquals(chapters.size, encoded.sumOf { (it["chapters"] as? JsonArray)?.size ?: 0 })
        val wireChapter = encoded.flatMap { (it["chapters"] as? JsonArray).orEmpty() }.first { it.jsonObject["name"]!!.jsonPrimitive.content == "c1" }.jsonObject
        val wireManga = encoded.flatMap { (it["manga"] as? JsonArray).orEmpty() }.first().jsonObject
        assertEquals(wireManga["clientId"], wireChapter["mangaClientId"])

        // Another device's rows: fresh clientIds that match local rows only by natural key.
        fun remotePages(base: Long, updated: Long) = listOf(
            page(buildJsonObject { put("manga", JsonArray(mangas.map { m -> mangaRow(base + m.id, updated, "s", "/m${m.id}", "remote") })) }),
            page(
                buildJsonObject {
                    put(
                        "chapters",
                        JsonArray(
                            chapters.map { c ->
                                buildJsonObject {
                                    put("clientId", base * 2 + c.id)
                                    put("mangaClientId", base + c.mangaId!!)
                                    put("name", "remote")
                                    put("url", c.url)
                                    put("updatedAt", updated)
                                }
                            }
                        )
                    )
                }
            ),
            page(
                buildJsonObject {
                    put(
                        "histories",
                        JsonArray(
                            histories.map { h ->
                                buildJsonObject {
                                    put("clientId", base * 3 + h.id)
                                    put("mangaClientId", base + h.mangaId!!)
                                    put("chapterClientId", base * 2 + h.chapterId!!)
                                    put("itemType", "MANGA")
                                    put("updatedAt", updated)
                                }
                            }
                        )
                    )
                }
            ),
        )
        val matched = mapper.merge(local, remotePages(1_000_000_000, 2), pref)
        assertEquals(mangas.size + chapters.size + histories.size, matched.downloadedChanges)
        assertEquals(mangas.map { it.id }, matched.snapshot.mangas.map { it.id })
        assertEquals(chapters.map { it.id }, matched.snapshot.chapters.map { it.id })
        assertEquals(histories.map { it.id }, matched.snapshot.histories.map { it.id })
        assertTrue(matched.snapshot.chapters.all { it.name == "remote" })
        val remapped = mapper.prepare(matched.snapshot, pref).first { it.kind == SyncPaths.KIND_MANGA }
        assertEquals(1_000_000_001L, mapper.encode(matched.snapshot, remapped)["manga"]!!.jsonArray.first().jsonObject["clientId"]!!.jsonPrimitive.long)

        // A fresh install pulls the same library, then the server tombstones every manga (cascading locally).
        val fresh = MangayomiSyncMapper(null, ns)
        val pulled = fresh.merge(emptySnapshot(), remotePages(2_000_000_000, 3), pref).snapshot
        assertEquals(chapters.size, pulled.chapters.size)
        assertEquals(histories.size, pulled.histories.size)
        val firstManga = pulled.mangas.first().id
        assertEquals(chaptersPerManga, pulled.chapters.count { it.mangaId == firstManga })
        assertEquals(pulled.chapters.first { it.mangaId == firstManga }.id, pulled.histories.first { it.mangaId == firstManga }.chapterId)
        val tombstones = page(buildJsonObject { put("tombstones", buildJsonObject { put("manga", JsonArray(mangas.map { JsonPrimitive(2_000_000_000 + it.id) })) }) })
        val cleared = fresh.merge(pulled, listOf(tombstones), pref).snapshot
        assertTrue(cleared.mangas.isEmpty() && cleared.chapters.isEmpty() && cleared.histories.isEmpty())
    }

    private fun page(data: JsonObject) = MangayomiPage(data, emptyMap(), null, false, null)
    private fun categoryRow(id: Long, name: String) = buildJsonObject {
        put("clientId", id)
        put("name", name)
        put("forItemType", "MANGA")
        put("updatedAt", 1)
    }
    private fun mangaRow(id: Long, updated: Long, source: String?, link: String?, name: String) = buildJsonObject {
        put("clientId", id)
        source?.let { put("source", it) }
        link?.let { put("link", it) }
        put("itemType", "MANGA")
        put("name", name)
        put("status", "UNKNOWN")
        put("updatedAt", updated)
    }
    private fun deletion(kind: Int, id: Long) = DbChangedPart(
        actionType = DbActionType.RemoveItem,
        data = buildJsonObject {
            put("provider", "mangayomi")
            put("namespace", "${ns.server.trimEnd('/')}\n${ns.accountId}")
            put("kind", kind)
            put("localId", id.toString())
        }.toString(),
        clientDate = 1
    )
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncServiceTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncServiceTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncServiceTest.kt).

The implementation below defines `MangayomiSyncServiceTest`, `loginRequiresRealSessionCookieAndStoresProvider`, `rejectsTotpInsteadOfClaimingAuthenticated`, `browserLoginExchangesCodeWithMatchingPkceVerifierOnceAndIgnoresOtherPages`, `browserLoginRejectsMismatchedStateWithoutExchangingTheCode`, `syncUploadsMappedRowsWithCookieAndFullPullsBeforeWatermarkCommit`, `failedUploadDoesNotAcknowledgeTombstoneOrAdvanceWatermark`, `invalidVersionPreventsSyncPostAndExactPreferenceLookupHasNoFallback`, `unevenPagesRetainOpaqueCursorAndSessionUntilComplete`, `uploadOnlyUsesBootstrapIdentityWithoutApplyingRemoteRowsOrTombstones` and 8 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

- `loginRequiresRealSessionCookieAndStoresProvider`
- `rejectsTotpInsteadOfClaimingAuthenticated`
- `browserLoginExchangesCodeWithMatchingPkceVerifierOnceAndIgnoresOtherPages`
- `browserLoginRejectsMismatchedStateWithoutExchangingTheCode`
- `syncUploadsMappedRowsWithCookieAndFullPullsBeforeWatermarkCommit`
- `failedUploadDoesNotAcknowledgeTombstoneOrAdvanceWatermark`
- `invalidVersionPreventsSyncPostAndExactPreferenceLookupHasNoFallback`
- `unevenPagesRetainOpaqueCursorAndSessionUntilComplete`
- `uploadOnlyUsesBootstrapIdentityWithoutApplyingRemoteRowsOrTombstones`
- `completionAcknowledgesOnlyCapturedDeletionRecordsNotSameIdReplacement`
- `uploadRemapPersistsBeforeContinuationFailureAndConcurrentDelete`
- `repeatedEntityAcrossPagesKeepsGreatestUpdatedAt`
- `tombstoneStillAppliesWhenLocalWriteDuringPullForcesMergeRetry`

Cross-chapter imports used by this file: [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`DbManga`](../chapters/02-domain-and-settings-models.md), [`InMemoryYokanDatabase`](../chapters/03-persistence-and-migrations.md), [`SyncServerProvider`](../chapters/02-domain-and-settings-models.md), [`emptySnapshot`](../chapters/03-persistence-and-migrations.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.RecordingHttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.test.assertNotNull
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

class MangayomiSyncServiceTest {
    @Test
    fun loginRequiresRealSessionCookieAndStoresProvider() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        val http = RecordingHttpService { HttpResponse(200, """{"ok":true}""", setCookies = listOf("id=jwt-value; Path=/; HttpOnly")) }
        val service = MangayomiSyncService(db, http)
        val result = service.login(1, "https://mangayomi.test/", "user", "secret")
        assertTrue(result.success, result.message)
        assertEquals("https://mangayomi.test/api/login", http.requests.single().url)
        assertEquals(SyncServerProvider.Mangayomi, db.syncPreferences().single().serverProvider)
        assertEquals("jwt-value", db.syncPreferences().single().authToken)

        val badDb = InMemoryYokanDatabase(emptySnapshot())
        val noCookie = MangayomiSyncService(badDb, HttpService { HttpResponse(200, """{"ok":true}""") })
        assertFalse(noCookie.login(1, "https://mangayomi.test", "user", "secret").success)
        assertTrue(badDb.syncPreferences().isEmpty())
    }

    @Test
    fun rejectsTotpInsteadOfClaimingAuthenticated() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        val service = MangayomiSyncService(db, HttpService { HttpResponse(200, """{"ok":true,"requiresTotp":true,"pendingToken":"pending"}""", setCookies = listOf("id=not-session")) })
        val result = service.login(1, "https://mangayomi.test", "user", "secret")
        assertFalse(result.success)
        assertTrue(db.syncPreferences().isEmpty())
    }

    @Test
    fun browserLoginExchangesCodeWithMatchingPkceVerifierOnceAndIgnoresOtherPages() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(
            DbSyncPreference(syncId = 1, serverProvider = SyncServerProvider.Mangayomi))))
        val http = RecordingHttpService { HttpResponse(200, """{"access_token":"jwt-oauth","token_type":"Bearer","expires_in":60,"username":"reader"}""") }
        val service = MangayomiSyncService(db, http)
        val attempt = assertNotNull(service.beginBrowserLogin(1, "https://mangayomi.test/"))
        val authorize = io.ktor.http.Url(attempt.url)
        assertEquals("/api/oauth/authorize", authorize.encodedPath)
        assertEquals("S256", authorize.parameters["code_challenge_method"])
        val redirect = assertNotNull(authorize.parameters["redirect_uri"])
        assertEquals(redirect, attempt.callbackUrl)

        // Pages of the server's own login flow are not the callback, and a forged state never reaches the server.
        assertEquals(null, service.completeBrowserLogin(attempt, "https://mangayomi.test/login?next=%2Fapi%2Foauth%2Fauthorize"))
        assertEquals(null, service.completeBrowserLogin(attempt, "$redirect/extra?code=c&state=${attempt.state}"))
        assertTrue(http.requests.isEmpty())

        val result = assertNotNull(service.completeBrowserLogin(attempt, "$redirect?code=one-use&state=${attempt.state}"))
        assertTrue(result.success, result.message)
        val exchange = Json.parseToJsonElement(http.requests.single().body!!).jsonObject
        assertEquals("https://mangayomi.test/api/oauth/token", http.requests.single().url)
        assertEquals("one-use", exchange.getValue("code").jsonPrimitive.content)
        assertEquals(redirect, exchange.getValue("redirectUri").jsonPrimitive.content)
        val verifier = exchange.getValue("codeVerifier").jsonPrimitive.content
        assertTrue(verifier.length in 43..128)
        val challenge = kotlin.io.encoding.Base64.UrlSafe.withPadding(kotlin.io.encoding.Base64.PaddingOption.ABSENT)
            .encode(eu.friedcutlet.yokan.util.sha256(verifier.encodeToByteArray()))
        assertEquals(authorize.parameters["code_challenge"], challenge)
        val pref = db.syncPreferences().single()
        assertEquals("jwt-oauth", pref.authToken)
        assertEquals("reader", pref.email) // the server's username is the account namespace
        assertEquals("https://mangayomi.test", pref.server)

        assertEquals(null, service.completeBrowserLogin(attempt, "$redirect?code=one-use&state=${attempt.state}"))
        assertEquals(1, http.requests.size)
    }

    @Test
    fun browserLoginRejectsMismatchedStateWithoutExchangingTheCode() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        val http = RecordingHttpService { HttpResponse(200, """{"access_token":"stolen","username":"attacker"}""") }
        val service = MangayomiSyncService(db, http)
        val attempt = assertNotNull(service.beginBrowserLogin(1, "https://mangayomi.test"))
        val result = assertNotNull(service.completeBrowserLogin(attempt, "${attempt.callbackUrl}?code=c&state=forged"))
        assertFalse(result.success)
        assertTrue(http.requests.isEmpty())
        assertTrue(db.syncPreferences().isEmpty())
    }

    @Test
    fun syncUploadsMappedRowsWithCookieAndFullPullsBeforeWatermarkCommit() = runTest {
        val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test/Case", email = "user", authToken = "jwt",
            syncOn = true, serverProvider = SyncServerProvider.Mangayomi)
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref), mangas = listOf(DbManga(
            id = 29, name = "Title", link = "/title", source = "source", favorite = true, updatedAt = 1_700_000_000_000,
        ))))
        val http = ScriptedSyncHttp(listOf(
            HttpResponse(200, """{"supported":["1"]}"""),
            completePage(), // mapping bootstrap pull
            completePage(), // manga upload
            completePage(), // full post-upload pull
        ))
        val result = MangayomiSyncService(db, http).sync(1, db.settings())
        assertTrue(result.errors.isEmpty(), result.errors.toString())
        val posts = http.requests.filter { it.url.endsWith("/api/sync/v1") }
        assertEquals(3, posts.size)
        assertTrue(posts.all { it.headers["Cookie"] == "id=jwt" })
        assertTrue(posts.all { it.body?.contains("\"since\":0") == true })
        val upload = posts[1].body?.let { Json.parseToJsonElement(it).jsonObject }
        val manga = assertNotNull(upload?.get("manga")).jsonArray.single().jsonObject
        val safeId = manga["clientId"]!!.jsonPrimitive.content.toLong()
        assertTrue(safeId in 1..9_007_199_254_740_991L)
        assertEquals(1_700_000_000_000L, manga["updatedAt"]!!.jsonPrimitive.content.toLong())
        assertNotNull(db.syncPreferences().single().mangayomiIdMappings)
        assertEquals(1_700_000_000_100L, db.syncPreferences().single().lastSyncManga)
    }

    @Test
    fun failedUploadDoesNotAcknowledgeTombstoneOrAdvanceWatermark() = runTest {
        val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",
            syncOn = true, serverProvider = SyncServerProvider.Mangayomi,
            mangayomiIdMappings = """{"version":1,"namespaces":{"https://mangayomi.test\nuser":{"2":{"42":{"canonical":4200,"aliases":[]}}}}}""")
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref), mangas = listOf(DbManga(
            id = 42, name = "Deleted", link = "/deleted", source = "source", updatedAt = 10,
        ))))
        db.removeManga(42)
        val http = ScriptedSyncHttp(listOf(
            HttpResponse(200, """{"supported":["1"]}"""), completePage(), HttpResponse(500, "server error"),
        ))
        val result = MangayomiSyncService(db, http).sync(1, db.settings())
        assertFalse(result.errors.isEmpty())
        assertTrue(db.changedParts().any { it.data.contains("\"provider\":\"mangayomi\"") })
        assertEquals(null, db.syncPreferences().single().lastSyncManga)
    }

    @Test
    fun invalidVersionPreventsSyncPostAndExactPreferenceLookupHasNoFallback() = runTest {
        val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",
            serverProvider = SyncServerProvider.Mangayomi)
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref)))
        val http = ScriptedSyncHttp(listOf(HttpResponse(200, """{"supported":["2"]}""")))
        val result = MangayomiSyncService(db, http).sync(1, db.settings())
        assertFalse(result.errors.isEmpty())
        assertEquals(1, http.requests.size)
        val otherDb = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref.copy(syncId = 2))))
        assertEquals(null, MangayomiSyncService(otherDb, http).status(1).server)
    }

    @Test
    fun unevenPagesRetainOpaqueCursorAndSessionUntilComplete() = runTest {
        val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",
            serverProvider = SyncServerProvider.Mangayomi)
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref)))
        val http = ScriptedSyncHttp(listOf(
            HttpResponse(200, """{"supported":["1"]}"""),
            page(hasMore = true, syncedAt = null, cursor = "boot-1", token = "st-1"),
            completePage(), // bootstrap second page
            completePage(), // empty upload batch
            page(hasMore = true, syncedAt = null, cursor = "pull-1", token = "st-2"),
            completePage(), // final pull second page
        ))
        val result = MangayomiSyncService(db, http).sync(1, db.settings())
        assertTrue(result.errors.isEmpty(), result.errors.toString())
        val posts = http.requests.filter { it.url.endsWith("/api/sync/v1") }
        val continuation = Json.parseToJsonElement(posts[1].body!!).jsonObject
        assertEquals("boot-1", continuation["cursors"]!!.jsonObject["manga"]!!.jsonPrimitive.content)
        assertEquals("st-1", continuation["sessionToken"]!!.jsonPrimitive.content)
        assertEquals(1_700_000_000_100L, db.syncPreferences().single().lastSyncManga)
    }

    @Test
    fun uploadOnlyUsesBootstrapIdentityWithoutApplyingRemoteRowsOrTombstones() = runTest {
        val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",
            serverProvider = SyncServerProvider.Mangayomi)
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref), mangas = listOf(DbManga(
            id = 29, name = "Local", link = "/title", source = "source", favorite = true, updatedAt = 100,
        ))))
        val remote = HttpResponse(200, """{"hasMore":false,"syncedAt":1700000000100,"sessionToken":"s","cursors":{},"categories":[],"manga":[{"clientId":4200,"source":"source","link":"/title","itemType":"MANGA","status":"UNKNOWN","name":"Remote newer","updatedAt":999}],"chapters":[],"tracks":[],"histories":[],"updates":[],"tombstones":{"categories":[],"manga":[4200],"chapters":[],"tracks":[],"histories":[],"updates":[]}}""")
        val http = ScriptedSyncHttp(listOf(HttpResponse(200, """{"supported":["1"]}"""), remote, completePage()))
        val result = MangayomiSyncService(db, http).pushChanges(1)
        assertTrue(result.errors.isEmpty(), result.errors.toString())
        assertEquals("Local", db.manga(29)?.name)
        assertEquals(null, db.syncPreferences().single().lastSyncManga)
        val posts = http.requests.filter { it.url.endsWith("/api/sync/v1") }
        assertEquals(2, posts.size)
        val upload = Json.parseToJsonElement(posts.last().body!!).jsonObject
        assertEquals("4200", upload["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.content)
    }

    @Test
    fun completionAcknowledgesOnlyCapturedDeletionRecordsNotSameIdReplacement() = runTest {
        val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",
            serverProvider = SyncServerProvider.Mangayomi,
            mangayomiIdMappings = """{"version":1,"namespaces":{"https://mangayomi.test\nuser":{"2":{"42":{"canonical":4200,"aliases":[]}}}}}""")
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref), mangas = listOf(DbManga(id = 42, name = "removed"))))
        db.removeManga(42)
        val captured = db.changedParts().single()
        val http = ScriptedSyncHttp(listOf(HttpResponse(200, """{"supported":["1"]}"""), completePage(), completePage(), completePage()))
        http.beforeResponse = { request ->
            if (request.url.endsWith("/api/sync/v1") && http.requests.count { it.url.endsWith("/api/sync/v1") } == 3) {
                val snapshot = db.snapshot()
                db.replaceAll(snapshot.copy(changedParts = listOf(captured.copy(
                    data = captured.data.replace("\"localId\":\"42\"", "\"localId\":\"43\""),
                    isarId = 43,
                ))), snapshot)
            }
        }
        val result = MangayomiSyncService(db, http).sync(1, db.settings())
        assertTrue(result.errors.isEmpty(), result.errors.toString())
        assertEquals(43L, Json.parseToJsonElement(db.changedParts().single().data).jsonObject["localId"]!!.jsonPrimitive.content.toLong())
    }

    @Test
    fun uploadRemapPersistsBeforeContinuationFailureAndConcurrentDelete() = runTest {
        val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",
            serverProvider = SyncServerProvider.Mangayomi)
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref),
            mangas = listOf(DbManga(id = 29, name = "M", link = "/m", source = "s")),
            chapters = listOf(eu.friedcutlet.yokan.database.DbChapter(id = 30, mangaId = 29, name = "C", url = "/c"))))
        val http = ScriptedSyncHttp(listOf(HttpResponse(200, """{"supported":["1"]}"""), completePage()))
        var canonicalWireId: Long? = null
        http.responseFor = { request ->
            if (!request.url.endsWith("/api/sync/v1")) null else {
                val payload = request.body?.let { Json.parseToJsonElement(it).jsonObject }.orEmpty()
                val manga = payload["manga"] as? kotlinx.serialization.json.JsonArray
                val chapters = payload["chapters"] as? kotlinx.serialization.json.JsonArray
                when {
                    !manga.isNullOrEmpty() -> {
                        canonicalWireId = manga.single().jsonObject["clientId"]!!.jsonPrimitive.content.toLong()
                        HttpResponse(200, """{"hasMore":true,"syncedAt":null,"sessionToken":"continued","cursors":{"manga":"opaque"},"mangaClientIdRemap":{"$canonicalWireId":9000}}""")
                    }
                    !chapters.isNullOrEmpty() -> {
                        db.removeManga(29)
                        db.removeChapter(30)
                        HttpResponse(500, "later chunk failed")
                    }
                    else -> null
                }
            }
        }
        val result = MangayomiSyncService(db, http).sync(1, db.settings())
        assertFalse(result.errors.isEmpty())
        val mappings = Json.parseToJsonElement(db.syncPreferences().single().mangayomiIdMappings!!).jsonObject
            .getValue("namespaces").jsonObject.getValue("https://mangayomi.test\nuser").jsonObject
            .getValue("2").jsonObject.getValue("29").jsonObject
        assertEquals("9000", mappings.getValue("canonical").jsonPrimitive.content)
        assertTrue(canonicalWireId != null)
        assertEquals(2, db.changedParts().size)
        val chapterRequest = http.requests.last { it.body?.contains("\"chapters\"") == true }
        assertTrue(chapterRequest.body!!.contains("\"sessionToken\":\"continued\""))
    }

    @Test
    fun repeatedEntityAcrossPagesKeepsGreatestUpdatedAt() = runTest {
        val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",
            serverProvider = SyncServerProvider.Mangayomi)
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref)))
        val row10 = """{"clientId":555,"source":"s","link":"/m","itemType":"MANGA","status":"UNKNOWN","name":"older","updatedAt":10}"""
        val row20 = """{"clientId":555,"source":"s","link":"/m","itemType":"MANGA","status":"UNKNOWN","name":"newer","updatedAt":20}"""
        val firstPage = HttpResponse(200, """{"hasMore":true,"syncedAt":null,"sessionToken":"s","cursors":{"manga":"c1"},"manga":[$row10],"categories":[],"chapters":[],"tracks":[],"histories":[],"updates":[],"tombstones":{}}""")
        val secondPage = HttpResponse(200, """{"hasMore":false,"syncedAt":1700000000100,"sessionToken":"s","cursors":{"manga":null},"manga":[$row20],"categories":[],"chapters":[],"tracks":[],"histories":[],"updates":[],"tombstones":{}}""")
        val http = ScriptedSyncHttp(listOf(HttpResponse(200, """{"supported":["1"]}"""), firstPage, secondPage, completePage(), completePage()))
        val result = MangayomiSyncService(db, http).sync(1, db.settings())
        assertTrue(result.errors.isEmpty(), result.errors.toString())
        assertEquals("newer", db.mangas().single().name)
        assertEquals(20L, db.mangas().single().updatedAt)
    }

    @Test
    fun tombstoneStillAppliesWhenLocalWriteDuringPullForcesMergeRetry() = runTest {
        val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",
            serverProvider = SyncServerProvider.Mangayomi,
            mangayomiIdMappings = """{"version":1,"namespaces":{"https://mangayomi.test\nuser":{"2":{"42":{"canonical":4200,"aliases":[]},"43":{"canonical":4300,"aliases":[]}}}}}""")
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref),
            mangas = listOf(DbManga(id = 42, name = "deleted remotely", source = "s", link = "/a"), DbManga(id = 43, name = "kept", source = "s", link = "/b"))))
        val tombstonePage = HttpResponse(200, completePage().body.replace("\"tombstones\":{\"categories\":[],\"manga\":[]", "\"tombstones\":{\"categories\":[],\"manga\":[4200]"))
        val http = ScriptedSyncHttp(listOf(HttpResponse(200, """{"supported":["1"]}"""), completePage(), completePage(), tombstonePage))
        http.beforeResponse = { request ->
            // A reader-progress style write while the final pull is in flight makes the first persist lose its CAS.
            if (http.requests.count { it.url.endsWith("/api/sync/v1") } == 3) db.upsertManga(db.manga(43)!!.copy(name = "edited"))
        }
        val result = MangayomiSyncService(db, http).sync(1, db.settings())
        assertTrue(result.errors.isEmpty(), result.errors.toString())
        assertEquals(null, db.manga(42))
        assertEquals("edited", db.manga(43)?.name)
    }

    private class ScriptedSyncHttp(responses: List<HttpResponse>) : HttpService {
        private val responses = responses.toMutableList()
        val requests = mutableListOf<HttpRequest>()
        var beforeResponse: suspend (HttpRequest) -> Unit = {}
        var responseFor: suspend (HttpRequest) -> HttpResponse? = { null }
        override suspend fun request(request: HttpRequest): HttpResponse {
            requests += request
            beforeResponse(request)
            return responseFor(request) ?: responses.removeAt(0)
        }
    }

    private fun completePage() = HttpResponse(200, """{"hasMore":false,"syncedAt":1700000000100,"sessionToken":"session","cursors":{"categories":null,"manga":null,"chapters":null,"tracks":null,"histories":null,"updates":null,"tombstones":null},"categories":[],"manga":[],"chapters":[],"tracks":[],"histories":[],"updates":[],"tombstones":{"categories":[],"manga":[],"chapters":[],"tracks":[],"histories":[],"updates":[]}}""")
    private fun page(hasMore: Boolean, syncedAt: Long?, cursor: String, token: String) = HttpResponse(200,
        """{"hasMore":$hasMore,"syncedAt":${syncedAt?.toString() ?: "null"},"sessionToken":"$token","cursors":{"categories":null,"manga":"$cursor","chapters":null,"tracks":null,"histories":null,"updates":null,"tombstones":null},"categories":[],"manga":[],"chapters":[],"tracks":[],"histories":[],"updates":[],"tombstones":{"categories":[],"manga":[],"chapters":[],"tracks":[],"histories":[],"updates":[]}}""")
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/ProfileSyncServicesTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/ProfileSyncServicesTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/ProfileSyncServicesTest.kt).

The implementation below defines `ProfileSyncServicesTest`, `close`, `closeAndJoin`, `TestScope.fixture`, `Fixture`, `finish`, `FakeSync`, `login`, `beginBrowserLogin`, `completeBrowserLogin` and 12 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

- `concurrentPublicClosesAwaitTheProviderCleanupOnce`
- `awaitedProviderCleanupIsForwardedAfterLegacyImmediateClose`
- `hybridProfileRetirementJoinsHubHandshakeWithoutCancelingParentOrSiblings`
- `publicRouterAndDirectCloudCallsRetainTheirArgumentsAndState`
- `retirementJoinsAnExternalSignInBeforeReleasingTheProviderGraph`
- `ownerCancellationJoinsCloudRestoreFinalizers`
- `callerExpiryJoinsOnlyItsCallAndPreservesOwnerAndSiblingWork`
- `alreadyExpiredCallerCannotDispatchWithAnImmediateOwner`
- `queuedCallCanceledBeforeDispatchCannotWriteCredentials`
- `staleReferencesCannotReadAccountsOrPerformAnySyncAction`
- `retiringOneOwnerDoesNotRetargetTheOtherWithTheSameSyncId`
- `failedProviderReleaseCanBeRetriedWithoutReopeningCalls`
- `lateHubCredentialResponseCannotCommitAfterOwnerRetirement`
- `lateMangayomiCredentialResponseCannotCommitAfterOwnerRetirement`
- `browserAttemptFromAnotherOwnerOrReplacementSessionIsRejected`

Cross-chapter imports used by this file: [`ProfileId`](../chapters/04-profiles-and-lifetimes.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`InMemoryYokanDatabase`](../chapters/03-persistence-and-migrations.md), [`SyncServerProvider`](../chapters/02-domain-and-settings-models.md), [`emptySnapshot`](../chapters/03-persistence-and-migrations.md). Keep those contracts available as you connect this step.

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.backup.BackupOptions
import eu.friedcutlet.yokan.services.backup.RestorePreview
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.ProfileTestEngine
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue

class ProfileSyncServicesTest {
    @Test fun concurrentPublicClosesAwaitTheProviderCleanupOnce() = runTest {
        val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>(); var joins = 0
        val router = object : FakeSync() {
            override fun close() { error("Orderly retirement must await provider cleanup") }
            override suspend fun closeAndJoin() { joins++; entered.complete(Unit); release.await() }
        }
        val bound = ProfileSyncServices(A, router, FakeCloud(), scope)
        val first = launch { bound.sync.closeAndJoin() }
        entered.await()
        val second = launch { bound.cloud.closeAndJoin() }
        testScheduler.runCurrent()
        assertFalse(first.isCompleted); assertFalse(second.isCompleted); assertEquals(1, joins)
        release.complete(Unit); first.join(); second.join()
        assertEquals(1, joins); assertTrue(parent.isActive)
        parent.cancelAndJoin()
    }

    @Test fun awaitedProviderCleanupIsForwardedAfterLegacyImmediateClose() = runTest {
        val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
        var joins = 0
        val router = object : FakeSync() { override suspend fun closeAndJoin() { joins++ } }
        val bound = ProfileSyncServices(A, router, FakeCloud(), scope)
        bound.sync.close(); assertEquals(1, router.closes)
        bound.cloud.closeAndJoin(); bound.sync.closeAndJoin()
        assertEquals(1, joins); assertEquals(1, router.closes)
        parent.cancelAndJoin()
    }

    @Test fun hybridProfileRetirementJoinsHubHandshakeWithoutCancelingParentOrSiblings() = runTest {
        val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler)
        val scope = CoroutineScope(parent + dispatcher)
        val sibling = scope.launch { awaitCancellation() }
        val database = InMemoryYokanDatabase(emptySnapshot())
        val preference = DbSyncPreference(syncId = 1, syncOn = true, server = "https://hub.test",
            authToken = "captured-token", deviceId = "captured-device")
        database.upsertSyncPreference(preference)
        val release = CompletableDeferred<Unit>(); var finalized = false
        val engine = ProfileTestEngine(dispatcher) {
            try { awaitCancellation() }
            finally { withContext(NonCancellable) { release.await(); finalized = true } }
        }
        val http = HttpService { error("Handshake is still pending") }
        val hub = HubSyncService(database, http, engine, scope = scope)
        val cloud = FakeCloud(); val mangayomi = FakeSync()
        val bound = ProfileSyncServices(A, HybridSyncService(hub, cloud, database, mangayomiSync = mangayomi), cloud, scope)
        val request = engine.requests.receive()
        assertEquals("Bearer captured-token", request.headers["Authorization"])
        assertEquals("captured-device", request.headers["X-Device"])
        assertEquals("/api/v1/events", request.url.encodedPath)
        val retiring = launch { bound.sync.closeAndJoin() }
        testScheduler.runCurrent()
        assertFalse(retiring.isCompleted); assertFalse(finalized)
        assertEquals(0, engine.closeCalls); assertEquals(0, cloud.closes); assertEquals(0, mangayomi.closes)
        assertTrue(parent.isActive); assertTrue(sibling.isActive)
        release.complete(Unit); retiring.join()
        assertTrue(finalized); assertEquals(1, engine.closeCalls)
        assertTrue(engine.coroutineContext[Job]?.isCompleted == true)
        assertEquals(1, cloud.closes); assertEquals(1, mangayomi.closes)
        bound.cloud.closeAndJoin()
        database.upsertSyncPreference(preference.copy(authToken = "replacement-token"))
        testScheduler.runCurrent()
        assertTrue(engine.requests.tryReceive().isFailure)
        assertTrue(parent.isActive); assertTrue(sibling.isActive)
        assertEquals(listOf(sibling), parent.children.toList())
        parent.cancelAndJoin()
    }

    @Test fun publicRouterAndDirectCloudCallsRetainTheirArgumentsAndState() = runTest {
        val fixture = fixture()
        val sync = fixture.bound.sync
        val cloud = fixture.bound.cloud
        assertSame(fixture.router.operationState, sync.operationState)
        assertSame(fixture.cloud.operationState, cloud.operationState)
        assertTrue(sync.login(7, "server", "email", "password").success)
        val attempt = requireNotNull(sync.beginBrowserLogin(7, "server"))
        assertTrue(requireNotNull(sync.completeBrowserLogin(attempt, "callback")).success)
        sync.cancelBrowserLogin(attempt)
        sync.logout(7); sync.sync(7, DbSettings()); sync.pushChanges(7); sync.pullChanges(7)
        assertTrue(cloud.connect(8, "cloud", "account", "token").success)
        cloud.uploadBackup(8, BackupOptions()); cloud.restoreLatestBackup(8)
        assertEquals(listOf("login:7:server:email:password", "begin:7:server", "complete:7:callback", "cancel:7",
            "logout:7", "sync:7", "push:7", "pull:7"), fixture.router.calls)
        assertEquals(listOf("connect:8:cloud:account:token", "upload:8", "restore:8"), fixture.cloud.calls)
        fixture.finish()
    }

    @Test fun retirementJoinsAnExternalSignInBeforeReleasingTheProviderGraph() = runTest {
        val fixture = fixture()
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        var finalized = false
        fixture.router.action = {
            try { entered.complete(Unit); awaitCancellation() }
            finally { withContext(NonCancellable) { release.await(); finalized = true } }
        }
        val caller = launch { fixture.bound.sync.login(1, "server", "email", "password") }
        entered.await()
        val shutdown = launch { fixture.bound.sync.closeAndJoin() }
        testScheduler.runCurrent()
        assertFalse(shutdown.isCompleted); assertFalse(caller.isCompleted)
        assertEquals(0, fixture.router.closes)
        assertNull(fixture.bound.sync.beginBrowserLogin(1, "server"))
        assertFailsWith<CancellationException> { fixture.bound.cloud.connect(1, "cloud", null, "late") }
        release.complete(Unit); shutdown.join(); caller.join()
        assertTrue(finalized); assertEquals(1, fixture.router.closes)
        fixture.bound.cloud.closeAndJoin(); assertEquals(1, fixture.router.closes)
        fixture.finish()
    }

    @Test fun ownerCancellationJoinsCloudRestoreFinalizers() = runTest {
        val fixture = fixture()
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        var finalized = false
        fixture.cloud.action = {
            try { entered.complete(Unit); awaitCancellation() }
            finally { withContext(NonCancellable) { release.await(); finalized = true } }
        }
        val caller = launch { fixture.bound.cloud.restoreLatestBackup(1) }
        entered.await()
        val retiring = launch { fixture.parent.cancelAndJoin() }
        testScheduler.runCurrent()
        assertFalse(retiring.isCompleted); assertFalse(caller.isCompleted)
        release.complete(Unit); retiring.join(); caller.join()
        assertTrue(finalized)
        fixture.bound.sync.closeAndJoin()
        assertEquals(1, fixture.router.closes)
    }

    @Test fun callerExpiryJoinsOnlyItsCallAndPreservesOwnerAndSiblingWork() = runTest {
        val fixture = fixture()
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        fixture.router.action = {
            try { entered.complete(Unit); awaitCancellation() }
            finally { withContext(NonCancellable) { release.await() } }
        }
        val sibling = fixture.scope.launch { awaitCancellation() }
        val caller = launch { fixture.bound.sync.pushChanges(1) }
        entered.await(); caller.cancel(); testScheduler.runCurrent()
        assertFalse(caller.isCompleted); assertTrue(fixture.parent.isActive); assertTrue(sibling.isActive)
        release.complete(Unit); caller.join()
        fixture.router.action = {}
        assertTrue(fixture.bound.sync.login(1, "server", "email", "password").success)
        fixture.finish()
    }

    @Test fun alreadyExpiredCallerCannotDispatchWithAnImmediateOwner() = runTest {
        val fixture = fixture(immediate = true)
        val caller = launch {
            currentCoroutineContext().cancel()
            assertFailsWith<CancellationException> { fixture.bound.cloud.connect(1, "cloud", null, "token") }
        }
        caller.join()
        assertTrue(fixture.cloud.calls.isEmpty()); assertTrue(fixture.parent.isActive)
        fixture.finish()
    }

    @Test fun queuedCallCanceledBeforeDispatchCannotWriteCredentials() = runTest {
        val fixture = fixture()
        val caller = launch(UnconfinedTestDispatcher(testScheduler)) {
            fixture.bound.sync.login(1, "server", "email", "password")
        }
        fixture.parent.cancel(); testScheduler.runCurrent(); caller.join()
        assertTrue(fixture.router.calls.isEmpty())
        fixture.finish()
    }

    @Test fun staleReferencesCannotReadAccountsOrPerformAnySyncAction() = runTest {
        val fixture = fixture()
        val attempt = requireNotNull(fixture.bound.sync.beginBrowserLogin(1, "server"))
        fixture.parent.cancelAndJoin()
        fixture.router.calls.clear(); fixture.cloud.calls.clear()
        assertNull(fixture.bound.sync.beginBrowserLogin(1, "server"))
        fixture.bound.sync.cancelBrowserLogin(attempt)
        assertEquals(SyncConnectionStatus(false, null, null, null), fixture.bound.sync.status(1))
        assertTrue(fixture.bound.cloud.providers().isEmpty())
        assertFalse(fixture.bound.cloud.isCloudPreference(DbSyncPreference(syncId = 1, server = "cloud://cloud")))
        assertFailsWith<CancellationException> { fixture.bound.sync.login(1, "server", "email", "password") }
        assertFailsWith<CancellationException> { fixture.bound.sync.completeBrowserLogin(attempt, "callback") }
        assertFailsWith<CancellationException> { fixture.bound.sync.logout(1) }
        assertFailsWith<CancellationException> { fixture.bound.sync.sync(1, DbSettings()) }
        assertFailsWith<CancellationException> { fixture.bound.sync.pushChanges(1) }
        assertFailsWith<CancellationException> { fixture.bound.sync.pullChanges(1) }
        assertFailsWith<CancellationException> { fixture.bound.cloud.connect(1, "cloud", null, "token") }
        assertFailsWith<CancellationException> { fixture.bound.cloud.uploadBackup(1, BackupOptions()) }
        assertFailsWith<CancellationException> { fixture.bound.cloud.restoreLatestBackup(1) }
        assertTrue(fixture.router.calls.isEmpty()); assertTrue(fixture.cloud.calls.isEmpty())
        fixture.finish()
    }

    @Test fun retiringOneOwnerDoesNotRetargetTheOtherWithTheSameSyncId() = runTest {
        val left = fixture(A); val right = fixture(B)
        left.bound.cloud.closeAndJoin()
        assertEquals(A, left.bound.profileId); assertEquals(B, right.bound.profileId)
        assertFailsWith<CancellationException> { left.bound.sync.login(1, "left", "a", "a-token") }
        assertTrue(right.bound.sync.login(1, "right", "b", "b-token").success)
        assertEquals(listOf("login:1:right:b:b-token"), right.router.calls)
        assertTrue(left.router.calls.isEmpty()); assertEquals(0, right.router.closes)
        left.finish(); right.finish()
    }

    @Test fun failedProviderReleaseCanBeRetriedWithoutReopeningCalls() = runTest {
        val fixture = fixture()
        fixture.router.failClose = true
        assertFailsWith<IllegalStateException> { fixture.bound.sync.closeAndJoin() }
        assertFailsWith<CancellationException> { fixture.bound.sync.logout(1) }
        fixture.router.failClose = false
        fixture.bound.sync.closeAndJoin(); fixture.bound.cloud.closeAndJoin()
        assertEquals(2, fixture.router.closes)
        fixture.finish()
    }

    @Test fun lateHubCredentialResponseCannotCommitAfterOwnerRetirement() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        val http = HttpService { request ->
            if (request.url.endsWith("/api/version")) HttpResponse(200, """{"supported":["1"]}""")
            else {
                entered.complete(Unit)
                withContext(NonCancellable) { release.await() }
                HttpResponse(200, """{"token":"late-token","user":{"id":"u","email":"a@b"}}""")
            }
        }
        val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
        val hub = HubSyncService(database, http, webSocketEngine = null, autoSync = false, scope = scope)
        val bound = ProfileSyncServices(A, hub, FakeCloud(), scope)
        val caller = launch { bound.sync.login(1, "https://hub.test", "a@b", "password") }
        entered.await(); parent.cancel(); testScheduler.runCurrent()
        release.complete(Unit); parent.join(); caller.join()
        assertTrue(database.syncPreferences().isEmpty())
        bound.sync.closeAndJoin()
    }

    @Test fun lateMangayomiCredentialResponseCannotCommitAfterOwnerRetirement() = runTest {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val prior = DbSyncPreference(syncId = 1, serverProvider = SyncServerProvider.Mangayomi)
        database.upsertSyncPreference(prior)
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        val http = HttpService {
            entered.complete(Unit)
            withContext(NonCancellable) { release.await() }
            HttpResponse(statusCode = 200, body = """{"ok":true}""", setCookies = listOf("id=late-token; Path=/"))
        }
        val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
        val mangayomi = MangayomiSyncService(database, http)
        val bound = ProfileSyncServices(A, mangayomi, FakeCloud(), scope)
        val caller = launch { bound.sync.login(1, "https://mangayomi.test", "user", "password") }
        entered.await(); parent.cancel(); testScheduler.runCurrent()
        release.complete(Unit); parent.join(); caller.join()
        assertEquals(prior, database.syncPreferences().single())
        bound.sync.closeAndJoin()
    }

    @Test fun browserAttemptFromAnotherOwnerOrReplacementSessionIsRejected() = runTest {
        val http = HttpService { HttpResponse(200, """{"supported":["1"]}""") }
        val parentA = SupervisorJob(); val parentB = SupervisorJob()
        val scopeA = CoroutineScope(parentA + StandardTestDispatcher(testScheduler))
        val scopeB = CoroutineScope(parentB + StandardTestDispatcher(testScheduler))
        val databaseA = InMemoryYokanDatabase(emptySnapshot()); val databaseB = InMemoryYokanDatabase(emptySnapshot())
        val a = ProfileSyncServices(A, HubSyncService(databaseA, http, null, autoSync = false, scope = scopeA), FakeCloud(), scopeA)
        val b = ProfileSyncServices(B, HubSyncService(databaseB, http, null, autoSync = false, scope = scopeB), FakeCloud(), scopeB)
        val attempt = requireNotNull(a.sync.beginBrowserLogin(1, "https://hub.test"))
        val callback = "https://hub.test/login/done#state=${attempt.state}&device=${attempt.device}&token=token&email=a%40b"
        assertNull(b.sync.completeBrowserLogin(attempt, callback))
        assertTrue(databaseB.syncPreferences().isEmpty())
        assertTrue(requireNotNull(a.sync.completeBrowserLogin(attempt, callback)).success)
        assertEquals("token", databaseA.syncPreferences().single().authToken)
        a.sync.closeAndJoin(); parentA.cancelAndJoin()
        val replacement = ProfileSyncServices(A, HubSyncService(databaseB, http, null, autoSync = false, scope = scopeB), FakeCloud(), scopeB)
        assertNull(replacement.sync.completeBrowserLogin(attempt, callback))
        assertTrue(databaseB.syncPreferences().isEmpty())
        b.sync.closeAndJoin(); replacement.sync.closeAndJoin(); parentB.cancelAndJoin()
    }

    private fun TestScope.fixture(id: ProfileId = A, immediate: Boolean = false): Fixture {
        val parent = SupervisorJob()
        val scope = CoroutineScope(parent + if (immediate) UnconfinedTestDispatcher(testScheduler) else StandardTestDispatcher(testScheduler))
        val router = FakeSync(); val cloud = FakeCloud()
        return Fixture(parent, scope, router, cloud, ProfileSyncServices(id, router, cloud, scope))
    }

    private class Fixture(val parent: Job, val scope: CoroutineScope, val router: FakeSync, val cloud: FakeCloud, val bound: ProfileSyncServices) {
        suspend fun finish() { parent.cancelAndJoin(); bound.sync.closeAndJoin() }
    }

    private open class FakeSync : SyncService {
        val calls = mutableListOf<String>()
        var action: suspend () -> Unit = {}
        var closes = 0
        var failClose = false
        override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult {
            calls += "login:$syncId:$server:$email:$password"; action(); return SyncLoginResult(true, "ok")
        }
        override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt {
            calls += "begin:$syncId:$server"; return BrowserLoginAttempt(syncId, server, "url", "device", "state")
        }
        override suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult {
            calls += "complete:${attempt.syncId}:$loadedUrl"; action(); return SyncLoginResult(true, "ok")
        }
        override fun cancelBrowserLogin(attempt: BrowserLoginAttempt) { calls += "cancel:${attempt.syncId}" }
        override suspend fun logout(syncId: Long) { calls += "logout:$syncId"; action() }
        override suspend fun sync(syncId: Long, settings: DbSettings): SyncResult { calls += "sync:$syncId"; action(); return SyncResult(1, 2, true) }
        override suspend fun pushChanges(syncId: Long): SyncResult { calls += "push:$syncId"; action(); return SyncResult(1, 0, false) }
        override suspend fun pullChanges(syncId: Long): SyncResult { calls += "pull:$syncId"; action(); return SyncResult(0, 1, false) }
        override fun status(syncId: Long): SyncConnectionStatus { calls += "status:$syncId"; return SyncConnectionStatus(true, "email", "server", 1) }
        override fun close() { closes++; check(!failClose) }
    }

    private class FakeCloud : FakeSync(), CloudBackupSyncService {
        override fun providers(): List<CloudProviderDescriptor> { calls += "providers"; return emptyList() }
        override fun isCloudPreference(syncPreference: DbSyncPreference?): Boolean { calls += "isCloud"; return true }
        override suspend fun connect(syncId: Long, providerId: String, accountLabel: String?, accessToken: String): SyncLoginResult {
            calls += "connect:$syncId:$providerId:$accountLabel:$accessToken"; action(); return SyncLoginResult(true, "ok")
        }
        override suspend fun uploadBackup(syncId: Long, options: BackupOptions): CloudBackupResult {
            calls += "upload:$syncId"; action(); return CloudBackupResult("cloud", "file", 1, 1, CloudObject("file", "file", 1, 1))
        }
        override suspend fun restoreLatestBackup(syncId: Long): CloudBackupRestoreResult {
            calls += "restore:$syncId"; action(); return CloudBackupRestoreResult("cloud", "file", RestorePreview(1, emptyList()))
        }
    }

    private companion object {
        val A = ProfileId("p_11111111111111111111111111111111")
        val B = ProfileId("p_22222222222222222222222222222222")
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/StateSyncSupportTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/StateSyncSupportTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/StateSyncSupportTest.kt).

The implementation below defines `StateSyncSupportTest`, `guardedRestoreRefusingChangedAccountBecomesAccountChangedFailure`, `cancellingTheCallerPropagatesInsteadOfReturningAResult`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `guardedRestoreRefusingChangedAccountBecomesAccountChangedFailure`
- `cancellingTheCallerPropagatesInsteadOfReturningAResult`

Cross-chapter imports used by this file: [`DbManga`](../chapters/02-domain-and-settings-models.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`InMemoryYokanDatabase`](../chapters/03-persistence-and-migrations.md), [`SyncServerProvider`](../chapters/02-domain-and-settings-models.md), [`emptySnapshot`](../chapters/03-persistence-and-migrations.md), [`BackupFormat`](../chapters/20-backup-and-restore.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.backup.BackupFormat
import eu.friedcutlet.yokan.services.backup.BackupOptions
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue

class StateSyncSupportTest {
    @Test
    fun guardedRestoreRefusingChangedAccountBecomesAccountChangedFailure() = runTest {
        val remote = backup(InMemoryYokanDatabase(emptySnapshot().copy(mangas = listOf(DbManga(id = 7, name = "Remote", link = "/remote", source = "src", favorite = true)))))
            .exportBackup(BackupOptions(format = BackupFormat.Tachiyomi, compressionLevel = 0)).bytes
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(Captured.copy(authToken = "key-2"))))

        val result = runStateSync(SyncOperationMonitor(), Mutex(), SyncOperationStage.Syncing, "Test") {
            backup(db).mergeRemoteState(remote, Captured, "Test")
            SyncResult(0, 0, false, emptyList())
        }

        assertEquals(listOf(SyncAccountChangedMessage), result.errors)
        assertTrue(db.mangas().none { it.name == "Remote" })
    }

    @Test
    fun cancellingTheCallerPropagatesInsteadOfReturningAResult() = runTest {
        val entered = CompletableDeferred<Unit>()
        var result: SyncResult? = null
        val caller = launch {
            result = runStateSync(SyncOperationMonitor(), Mutex(), SyncOperationStage.Syncing, "Test") {
                entered.complete(Unit)
                awaitCancellation()
            }
        }
        entered.await()
        caller.cancel()
        caller.join()

        assertTrue(caller.isCancelled)
        assertNull(result)
    }

    private companion object {
        val Captured = DbSyncPreference(
            syncId = 1, server = "https://sync.test", authToken = "key-1", syncOn = true, serverProvider = SyncServerProvider.SyncYomi,
        )
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/SyncAccountLeasesTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/SyncAccountLeasesTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/SyncAccountLeasesTest.kt).

The implementation below defines `SyncAccountLeasesTest`, `MemoryRegistry`, `read`, `compareAndSet`, `FakeHub`, `request`, `registry`, `TestScope.hub`.

The source describes its contract as:

> Answers the version probe and login; everything else is an unexpected network call.

Read the setup, action and assertions in these cases before implementing their production paths:

- `leasedAccountRejectsOtherProfilesLoginWithoutWritingCredentials`
- `conflictingExistingLoginDoesNotSync`
- `rejectedCommitReturnsTheLeaseToThePreviousAccount`

Cross-chapter imports used by this file: [`ProfileId`](../chapters/04-profiles-and-lifetimes.md), [`ProfileRegistry`](../chapters/04-profiles-and-lifetimes.md), [`ProfileRegistryPersistence`](../chapters/04-profiles-and-lifetimes.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`InMemoryYokanDatabase`](../chapters/03-persistence-and-migrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.app.profiles.ProfileRegistry
import eu.friedcutlet.yokan.app.profiles.ProfileRegistryPersistence
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue

class SyncAccountLeasesTest {
    private class MemoryRegistry : ProfileRegistryPersistence {
        var raw: String? = null
        override suspend fun read() = raw
        override suspend fun compareAndSet(expected: String?, replacement: String) = (raw == expected).also { if (it) raw = replacement }
    }

    /** Answers the version probe and login; everything else is an unexpected network call. */
    private class FakeHub : HttpService {
        val requests = mutableListOf<HttpRequest>()
        override suspend fun request(request: HttpRequest): HttpResponse {
            requests += request
            return when {
                request.url.endsWith("/api/version") -> HttpResponse(200, """{"supported":["1"]}""")
                request.url.endsWith("/api/v1/login") -> HttpResponse(200, """{"token":"tok"}""")
                else -> HttpResponse(500, "")
            }
        }
    }

    private suspend fun registry() = ProfileRegistry(MemoryRegistry()).apply {
        refresh(); beginCreate("Reader", A); markReady(A); beginCreate("Other", B); markReady(B)
    }

    private fun TestScope.hub(db: InMemoryYokanDatabase, http: HttpService, leases: SyncAccountLeases) =
        HubSyncService(db, http, webSocketEngine = null, autoSync = false, scope = backgroundScope, leases = leases)

    @Test fun leasedAccountRejectsOtherProfilesLoginWithoutWritingCredentials() = runTest {
        val registry = registry()
        val dbA = InMemoryYokanDatabase(emptySnapshot()); val dbB = InMemoryYokanDatabase(emptySnapshot())
        assertTrue(hub(dbA, FakeHub(), registry.syncLeases(A)).login(1, "hub.test", "a@b", "pw").success)

        // Server/account spelling differences still name the same remote library.
        val result = hub(dbB, FakeHub(), registry.syncLeases(B)).login(1, "https://HUB.test/", " A@B ", "pw")
        assertFalse(result.success)
        assertEquals("This sync account is already connected to profile ‘Reader’. Log out there first.", result.message)
        assertTrue(dbB.syncPreferences().isEmpty())

        hub(dbA, FakeHub(), registry.syncLeases(A)).logout(1)
        assertTrue(hub(dbB, FakeHub(), registry.syncLeases(B)).login(1, "https://HUB.test/", " A@B ", "pw").success)
        assertEquals("tok", dbB.syncPreferences().single().authToken)
    }

    @Test fun conflictingExistingLoginDoesNotSync() = runTest {
        val registry = registry()
        registry.claimSyncLease(A, "hub|https://hub.test|a@b")
        // e.g. a login restored into B from a backup of A.
        val dbB = InMemoryYokanDatabase(emptySnapshot())
        dbB.upsertSyncPreference(DbSyncPreference(syncId = 1, server = "https://hub.test", email = "a@b", authToken = "tok", syncOn = true))
        val http = FakeHub()
        val result = hub(dbB, http, registry.syncLeases(B)).sync(1, DbSettings())
        assertEquals(listOf("This sync account is already connected to profile ‘Reader’. Log out there first."), result.errors)
        assertTrue(http.requests.isEmpty())
        assertEquals("tok", dbB.syncPreferences().single().authToken, "the conflicting login is kept, not deleted")
    }

    @Test fun rejectedCommitReturnsTheLeaseToThePreviousAccount() = runTest {
        val registry = registry()
        val previous = DbSyncPreference(server = "https://hub.test", email = "old", authToken = "tok")
        registry.claimSyncLease(A, syncLeaseKey(previous)!!)
        val failure = registry.syncLeases(A).commitClaimed(previous, previous.copy(email = "new")) { false }
        assertEquals("Sync configuration changed during login; try again.", failure)
        assertEquals(listOf("hub|https://hub.test|old"), registry.refresh().syncLeases.map { it.key })
        assertNull(registry.syncLeases(A).commitClaimed(null, previous.copy(email = "new")) { true })
        assertEquals(listOf("hub|https://hub.test|new"), registry.refresh().syncLeases.map { it.key })
    }

    private companion object {
        val A = ProfileId("p_${"a".repeat(32)}")
        val B = ProfileId("p_${"b".repeat(32)}")
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/SyncOperationMonitorTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/SyncOperationMonitorTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/SyncOperationMonitorTest.kt).

The implementation below defines `SyncOperationMonitorTest`, `overlappingOperationsRemainActiveUntilTheLastOneFinishes`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `overlappingOperationsRemainActiveUntilTheLastOneFinishes`

```kotlin
package eu.friedcutlet.yokan.services.sync

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class SyncOperationMonitorTest {
    @Test
    fun overlappingOperationsRemainActiveUntilTheLastOneFinishes() {
        val monitor = SyncOperationMonitor()
        val first = monitor.begin(SyncOperationStage.Syncing)
        val second = monitor.begin(SyncOperationStage.Uploading)
        assertEquals(2, monitor.state.value.activeCount)
        assertEquals(SyncOperationStage.Uploading, monitor.state.value.stage)

        monitor.finish(second, SyncOperationOutcome.Succeeded)
        assertTrue(monitor.state.value.isActive)
        assertEquals(SyncOperationStage.Syncing, monitor.state.value.stage)
        monitor.finish(first, SyncOperationOutcome.Cancelled)
        assertEquals(SyncOperationState(lastOutcome = SyncOperationOutcome.Cancelled), monitor.state.value)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/SyncTriggerCoordinatorTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/SyncTriggerCoordinatorTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/SyncTriggerCoordinatorTest.kt).

The implementation below defines `SyncTriggerCoordinatorTest`, `FakeSync`, `sync`, `database`, `TestScope.coordinator`, `TestScope.advance`, `disabledKindsNeverSyncWhileEnabledLifecycleKindRunsQuickly`, `burstOfReadEventsSyncsOnceAfterTheDebounce`, `triggerDuringRunQueuesExactlyOneFollowUpWithoutOverlap`, `runsAreAtLeastTheMinimumIntervalApart` and 3 further declarations.

The source describes its contract as:

> Stands in for the provider sync behind `PeriodicTaskRunner.sync()`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `disabledKindsNeverSyncWhileEnabledLifecycleKindRunsQuickly`
- `burstOfReadEventsSyncsOnceAfterTheDebounce`
- `triggerDuringRunQueuesExactlyOneFollowUpWithoutOverlap`
- `runsAreAtLeastTheMinimumIntervalApart`
- `unconfiguredSyncNeverRuns`
- `failedSyncDoesNotBreakLaterTriggers`
- `retirementCancelsPendingRuns`

Cross-chapter imports used by this file: [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`DbSyncTriggerPreferences`](../chapters/02-domain-and-settings-models.md), [`InMemoryYokanDatabase`](../chapters/03-persistence-and-migrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.DbSyncTriggerPreferences
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest

@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class SyncTriggerCoordinatorTest {
    /** Stands in for the provider sync behind `PeriodicTaskRunner.sync()`. */
    private class FakeSync(var durationMillis: Long = 0) {
        var calls = 0
        var running = 0
        var maxRunning = 0
        var failNext = false

        suspend fun sync() {
            calls++
            running++
            maxRunning = maxOf(maxRunning, running)
            try {
                delay(durationMillis)
                if (failNext) {
                    failNext = false
                    error("provider down")
                }
            } finally {
                running--
            }
        }
    }

    private fun database(
        triggers: DbSyncTriggerPreferences = DbSyncTriggerPreferences(onChapterRead = true, onEpisodeSeen = true, onAppResume = true),
        configured: Boolean = true,
    ) = InMemoryYokanDatabase().apply {
        updateSettings(settings().let { it.copy(features = it.features.copy(syncTriggers = triggers)) })
        if (configured) upsertSyncPreference(DbSyncPreference(syncId = 1L, syncOn = true, authToken = "token"))
    }

    private fun TestScope.coordinator(
        sync: FakeSync,
        db: InMemoryYokanDatabase = database(),
        scope: CoroutineScope = backgroundScope,
    ) = SyncTriggerCoordinator(db, scope, eventDebounceMillis = 5_000, lifecycleDebounceMillis = 1_000, minIntervalMillis = 60_000) { sync.sync() }

    private fun TestScope.advance(millis: Long) {
        advanceTimeBy(millis)
        runCurrent()
    }

    @Test
    fun disabledKindsNeverSyncWhileEnabledLifecycleKindRunsQuickly() = runTest {
        val sync = FakeSync()
        val triggers = coordinator(sync)
        listOf(SyncTriggerKind.ChapterOpen, SyncTriggerKind.EpisodeOpen, SyncTriggerKind.AppStart).forEach(triggers::onTrigger)
        advance(600_000)
        assertEquals(0, sync.calls)
        triggers.onTrigger(SyncTriggerKind.AppResume)
        advance(1_001)
        assertEquals(1, sync.calls)
    }

    @Test
    fun burstOfReadEventsSyncsOnceAfterTheDebounce() = runTest {
        val sync = FakeSync()
        val triggers = coordinator(sync)
        repeat(10) {
            triggers.onTrigger(if (it % 2 == 0) SyncTriggerKind.ChapterRead else SyncTriggerKind.EpisodeSeen)
            advance(1_000)
        }
        assertEquals(0, sync.calls)
        advance(4_001)
        assertEquals(1, sync.calls)
        advance(600_000)
        assertEquals(1, sync.calls)
    }

    @Test
    fun triggerDuringRunQueuesExactlyOneFollowUpWithoutOverlap() = runTest {
        val sync = FakeSync(durationMillis = 30_000)
        val triggers = coordinator(sync)
        triggers.onTrigger(SyncTriggerKind.ChapterRead)
        advance(10_000) // run started at 5 s
        assertEquals(1, sync.running)
        repeat(3) { triggers.onTrigger(SyncTriggerKind.ChapterRead) }
        // Run ends at 35 s, cooldown until 95 s, then the 5 s debounce.
        advance(89_000)
        assertEquals(1, sync.calls)
        advance(2_000)
        assertEquals(2, sync.calls)
        advance(600_000)
        assertEquals(2, sync.calls)
        assertEquals(1, sync.maxRunning)
    }

    @Test
    fun runsAreAtLeastTheMinimumIntervalApart() = runTest {
        val sync = FakeSync()
        val triggers = coordinator(sync)
        triggers.onTrigger(SyncTriggerKind.ChapterRead)
        advance(5_001)
        assertEquals(1, sync.calls)
        triggers.onTrigger(SyncTriggerKind.AppResume)
        advance(60_000) // 65 s: still cooling down from the 5 s run plus 1 s debounce
        assertEquals(1, sync.calls)
        advance(1_000)
        assertEquals(2, sync.calls)
    }

    @Test
    fun unconfiguredSyncNeverRuns() = runTest {
        val sync = FakeSync()
        val triggers = coordinator(sync, database(configured = false))
        triggers.onTrigger(SyncTriggerKind.ChapterRead)
        triggers.onTrigger(SyncTriggerKind.AppResume)
        advance(600_000)
        assertEquals(0, sync.calls)
    }

    @Test
    fun failedSyncDoesNotBreakLaterTriggers() = runTest {
        val sync = FakeSync().apply { failNext = true }
        val triggers = coordinator(sync)
        triggers.onTrigger(SyncTriggerKind.ChapterRead)
        advance(5_001)
        assertEquals(1, sync.calls)
        advance(60_000)
        triggers.onTrigger(SyncTriggerKind.ChapterRead)
        advance(5_001)
        assertEquals(2, sync.calls)
    }

    @Test
    fun retirementCancelsPendingRuns() = runTest {
        val sync = FakeSync()
        val owner = CoroutineScope(StandardTestDispatcher(testScheduler) + Job())
        val triggers = coordinator(sync, scope = owner)
        triggers.onTrigger(SyncTriggerKind.ChapterRead)
        advance(1_000)
        owner.cancel()
        triggers.onTrigger(SyncTriggerKind.ChapterRead)
        advance(600_000)
        assertEquals(0, sync.calls)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/SyncYomiSyncServiceTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/SyncYomiSyncServiceTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/SyncYomiSyncServiceTest.kt).

The implementation below defines `SyncYomiSyncServiceTest`, `mergesRemoteThenUploadsMergedProtobufUnderIfMatch`, `missingRemoteUploadsWithoutIfMatch`, `preconditionFailuresRetryTheWholeRunThenReportConflict`, `remoteWithoutEtagIsAnError`, `unreadableRemoteIsOverwritten`, `accountChangeDuringRunCommitsNothing`, `leaseConflictSendsNoRequest`, `claim`, `release` and 20 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

- `mergesRemoteThenUploadsMergedProtobufUnderIfMatch`
- `missingRemoteUploadsWithoutIfMatch`
- `preconditionFailuresRetryTheWholeRunThenReportConflict`
- `remoteWithoutEtagIsAnError`
- `unreadableRemoteIsOverwritten`
- `accountChangeDuringRunCommitsNothing`
- `leaseConflictSendsNoRequest`
- `pushOnlyKeepsLocalLibraryAndPullOnlyNeverUploads`
- `loginValidatesKeyAndLeasesByDigest`

Cross-chapter imports used by this file: [`DbManga`](../chapters/02-domain-and-settings-models.md), [`NoNotifications`](../chapters/24-settings-and-integrations.md), [`DbSyncPreference`](../chapters/02-domain-and-settings-models.md), [`InMemoryYokanDatabase`](../chapters/03-persistence-and-migrations.md), [`SyncServerProvider`](../chapters/02-domain-and-settings-models.md), [`emptySnapshot`](../chapters/03-persistence-and-migrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.services.notifications.NoNotifications
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.backup.BackupCompression
import eu.friedcutlet.yokan.services.backup.BackupFormat
import eu.friedcutlet.yokan.services.backup.BackupOpenResult
import eu.friedcutlet.yokan.services.backup.BackupOptions
import eu.friedcutlet.yokan.services.backup.DefaultBackupService
import eu.friedcutlet.yokan.services.files.LocalEntry
import eu.friedcutlet.yokan.services.files.LocalFileEntry
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

class SyncYomiSyncServiceTest {
    @Test
    fun mergesRemoteThenUploadsMergedProtobufUnderIfMatch() = runTest {
        val db = db(DbManga(id = 1, name = "Local", link = "/local", source = "src", favorite = true))
        val http = ScriptedHttp(
            HttpResponse(200, headers = mapOf("ETag" to "\"v1\""), bodyBytes = remoteBytes(DbManga(id = 7, name = "Remote", link = "/remote", source = "src", favorite = true))),
            HttpResponse(200, headers = mapOf("ETag" to "\"v2\"")),
        )
        val result = SyncYomiSyncService(db, backup(db), http).sync(1, db.settings())

        assertTrue(result.errors.isEmpty(), result.errors.toString())
        assertTrue(db.mangas().any { it.name == "Remote" }, "remote title merged")
        assertTrue(db.mangas().any { it.name == "Local" }, "local title kept")
        val (get, put) = http.requests
        assertEquals("GET", get.method)
        assertEquals("https://sync.test/api/sync/content", get.url)
        assertEquals("key-1", get.headers["X-API-Token"])
        assertEquals("PUT", put.method)
        assertEquals("https://sync.test/api/sync/content", put.url)
        assertEquals("key-1", put.headers["X-API-Token"])
        assertEquals("\"v1\"", put.headers["If-Match"])
        assertEquals("application/octet-stream", put.headers["Content-Type"])
        assertIs<BackupOpenResult.Ready>(backup(InMemoryYokanDatabase(emptySnapshot())).openBackup(assertNotNull(put.bodyBytes)))
        assertNotNull(db.syncPreferences().single().lastSyncManga)
    }

    @Test
    fun missingRemoteUploadsWithoutIfMatch() = runTest {
        val db = db()
        val http = ScriptedHttp(HttpResponse(404), HttpResponse(201, headers = mapOf("ETag" to "\"v1\"")))
        val result = SyncYomiSyncService(db, backup(db), http).sync(1, db.settings())

        assertTrue(result.errors.isEmpty(), result.errors.toString())
        assertEquals("PUT", http.requests[1].method)
        assertFalse("If-Match" in http.requests[1].headers)
    }

    @Test
    fun preconditionFailuresRetryTheWholeRunThenReportConflict() = runTest {
        val db = db()
        val remote = remoteBytes()
        val responses = (0 until 3).flatMap { listOf(HttpResponse(200, headers = mapOf("ETag" to "\"v$it\""), bodyBytes = remote), HttpResponse(412)) }
        val http = ScriptedHttp(*responses.toTypedArray())
        val result = SyncYomiSyncService(db, backup(db), http).sync(1, db.settings())

        assertEquals(6, http.requests.size)
        assertEquals(listOf("GET", "PUT", "GET", "PUT", "GET", "PUT"), http.requests.map { it.method })
        assertEquals("\"v2\"", http.requests[5].headers["If-Match"])
        assertTrue(result.errors.single().contains("changing"), result.errors.toString())
        assertNull(db.syncPreferences().single().lastSyncManga)
    }

    @Test
    fun remoteWithoutEtagIsAnError() = runTest {
        val db = db()
        val http = ScriptedHttp(HttpResponse(200, bodyBytes = remoteBytes()))
        val result = SyncYomiSyncService(db, backup(db), http).sync(1, db.settings())

        assertTrue(result.errors.single().contains("ETag"), result.errors.toString())
        assertEquals(1, http.requests.size)
    }

    @Test
    fun unreadableRemoteIsOverwritten() = runTest {
        val db = db(DbManga(id = 1, name = "Local", link = "/local", source = "src", favorite = true))
        val http = ScriptedHttp(
            HttpResponse(200, "<html>not a backup</html>", headers = mapOf("ETag" to "\"v1\"")),
            HttpResponse(200, headers = mapOf("ETag" to "\"v2\"")),
        )
        val result = SyncYomiSyncService(db, backup(db), http).sync(1, db.settings())

        assertTrue(result.errors.isEmpty(), result.errors.toString())
        assertEquals("PUT", http.requests[1].method)
        assertEquals(listOf("Local"), db.mangas().map { it.name })
    }

    @Test
    fun accountChangeDuringRunCommitsNothing() = runTest {
        val db = db()
        val http = ScriptedHttp(HttpResponse(200, headers = mapOf("ETag" to "\"v1\""), bodyBytes = remoteBytes(DbManga(id = 7, name = "Remote", link = "/remote", source = "src", favorite = true))))
        http.beforeResponse = { db.upsertSyncPreference(Preference.copy(authToken = "key-2")) }
        val result = SyncYomiSyncService(db, backup(db), http).sync(1, db.settings())

        assertEquals(listOf(SyncAccountChangedMessage), result.errors)
        assertEquals(1, http.requests.size)
        assertTrue(db.mangas().none { it.name == "Remote" })
        assertNull(db.syncPreferences().single().lastSyncManga)
    }

    @Test
    fun leaseConflictSendsNoRequest() = runTest {
        val db = db()
        val http = ScriptedHttp()
        val leases = object : SyncAccountLeases {
            override suspend fun claim(key: String) = throw IllegalStateException("Held by profile B")
            override suspend fun release(key: String) = Unit
        }
        val result = SyncYomiSyncService(db, backup(db), http, leases = leases).sync(1, db.settings())

        assertEquals(listOf("Held by profile B"), result.errors)
        assertTrue(http.requests.isEmpty())
    }

    @Test
    fun pushOnlyKeepsLocalLibraryAndPullOnlyNeverUploads() = runTest {
        val db = db()
        val remote = remoteBytes(DbManga(id = 7, name = "Remote", link = "/remote", source = "src", favorite = true))
        val push = ScriptedHttp(HttpResponse(200, headers = mapOf("ETag" to "\"v1\""), bodyBytes = remote), HttpResponse(200))
        assertTrue(SyncYomiSyncService(db, backup(db), push).pushChanges(1).errors.isEmpty())
        assertEquals("\"v1\"", push.requests[1].headers["If-Match"])
        assertTrue(db.mangas().none { it.name == "Remote" })

        val pull = ScriptedHttp(HttpResponse(200, headers = mapOf("ETag" to "\"v1\""), bodyBytes = remote))
        assertTrue(SyncYomiSyncService(db, backup(db), pull).pullChanges(1).errors.isEmpty())
        assertEquals(listOf("GET"), pull.requests.map { it.method })
        assertTrue(db.mangas().any { it.name == "Remote" })
    }

    @Test
    fun loginValidatesKeyAndLeasesByDigest() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(DbSyncPreference(syncId = 1, serverProvider = SyncServerProvider.SyncYomi))))
        val rejected = ScriptedHttp(HttpResponse(401))
        assertFalse(SyncYomiSyncService(db, backup(db), rejected).login(1, "sync.test/", "", "bad").success)
        assertNull(db.syncPreferences().single().authToken)

        val http = ScriptedHttp(HttpResponse(404))
        val result = SyncYomiSyncService(db, backup(db), http).login(1, "sync.test/", "", " key-1 ")
        assertTrue(result.success, result.message)
        assertEquals("key-1", http.requests.single().headers["X-API-Token"])
        val stored = db.syncPreferences().single()
        assertEquals("https://sync.test", stored.server)
        assertEquals("key-1", stored.authToken)
        assertTrue(stored.syncOn)
        val key = assertNotNull(syncLeaseKey(stored))
        assertTrue(key.startsWith("syncyomi|https://sync.test|"), key)
        assertFalse("key-1" in key)
        assertEquals(16, key.substringAfterLast('|').length)
    }

    private class ScriptedHttp(vararg responses: HttpResponse) : HttpService {
        private val responses = responses.toMutableList()
        val requests = mutableListOf<HttpRequest>()
        var beforeResponse: suspend (HttpRequest) -> Unit = {}
        override suspend fun request(request: HttpRequest): HttpResponse {
            requests += request
            beforeResponse(request)
            return responses.removeAt(0)
        }
    }

    private suspend fun remoteBytes(vararg mangas: DbManga): ByteArray =
        backup(InMemoryYokanDatabase(emptySnapshot().copy(mangas = mangas.toList())))
            .exportBackup(BackupOptions(format = BackupFormat.Tachiyomi, compressionLevel = 0)).bytes

    private fun db(vararg mangas: DbManga) =
        InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(Preference), mangas = mangas.toList()))

    private companion object {
        val Preference = DbSyncPreference(
            syncId = 1, server = "https://sync.test", authToken = "key-1", syncOn = true, serverProvider = SyncServerProvider.SyncYomi,
        )
    }
}

internal fun backup(database: InMemoryYokanDatabase) =
    DefaultBackupService(database, MemoryBackupFiles(), PassthroughBackupCompression(), NoNotifications)

internal class MemoryBackupFiles : LocalFileService {
    override val downloadRoot: String = "/tmp/downloads"
    override val backupRoot: String = "/tmp/backups"
    override val cacheRoot: String = "/tmp/cache"
    private val files = mutableMapOf<String, ByteArray>()

    override fun writeBytes(path: String, bytes: ByteArray) { files[path] = bytes }
    override fun readBytes(path: String): ByteArray = files[path] ?: ByteArray(0)
    override fun canonicalPath(path: String): String? = path
    override fun exists(path: String): Boolean = path in files
    override fun deleteRecursively(path: String): Boolean = files.keys.removeAll { it.startsWith(path) }
    override fun directorySize(path: String): Long = 0
    override fun openLocation(path: String): Boolean = false
    override fun listLocalEntries(root: String): List<LocalEntry>? = emptyList()
    override fun listFiles(root: String): List<LocalFileEntry> = emptyList()
}

internal class PassthroughBackupCompression : BackupCompression {
    override fun compress(data: ByteArray, level: Int): ByteArray = data
    override fun decompress(data: ByteArray): ByteArray = data
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncDockerIntegrationTest.kt
### Write `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncDockerIntegrationTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncDockerIntegrationTest.kt).

The implementation below defines `HubSyncDockerIntegrationTest`, `productionClientAuthenticatesAndRoundTripsDottedSettingsPreference`, `enableSettingsSync`, `readCredentials`, `RecordingHttpService`, `request`, `stream`, `close`, `safeError`, `SyncDiagnostic` and 1 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

- `productionClientAuthenticatesAndRoundTripsDottedSettingsPreference`

Cross-chapter imports used by this file: [`DbCategory`](../chapters/02-domain-and-settings-models.md), [`DbItemType`](../chapters/02-domain-and-settings-models.md), [`DbSourcePreference`](../chapters/02-domain-and-settings-models.md), [`InMemoryYokanDatabase`](../chapters/03-persistence-and-migrations.md), [`emptySnapshot`](../chapters/03-persistence-and-migrations.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.sync

import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSourcePreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.KtorHttpService
import eu.friedcutlet.yokan.services.http.createPlatformHttpClientEngine
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class HubSyncDockerIntegrationTest {
    @Test
    fun productionClientAuthenticatesAndRoundTripsDottedSettingsPreference() = runBlocking {
        val hubUrl = System.getenv("YOKAN_TEST_HUB_URL")?.trim()?.takeIf(String::isNotEmpty)
        val envPath = System.getenv("YOKAN_TEST_HUB_ENV_FILE")?.trim()?.takeIf(String::isNotEmpty)
        assumeTrue("Set YOKAN_TEST_HUB_URL and YOKAN_TEST_HUB_ENV_FILE to enable the local-hub test", hubUrl != null && envPath != null)

        val configuredHub = requireNotNull(hubUrl)
        val credentials = readCredentials(File(requireNotNull(envPath)))
        val reproValue = "repro-value"
        val diagnostics = mutableListOf<SyncDiagnostic>()
        val productionHttp = KtorHttpService(createPlatformHttpClientEngine())
        val http = RecordingHttpService(productionHttp, diagnostics, credentials.values + reproValue)
        val owner = CoroutineScope(SupervisorJob() + Dispatchers.Default)
        val firstDb = InMemoryYokanDatabase(emptySnapshot())
        val first = HubSyncService(firstDb, http, webSocketEngine = null, autoSync = false, scope = owner)
        val secondDb = InMemoryYokanDatabase(emptySnapshot())
        val second = HubSyncService(secondDb, http, webSocketEngine = null, autoSync = false, scope = owner)
        try {
            assertTrue(first.login(1, configuredHub, credentials.getValue("ADMIN_EMAIL"), credentials.getValue("ADMIN_PASSWORD")).success, "Disposable hub admin login failed")
            enableSettingsSync(firstDb)
            firstDb.upsertCategory(DbCategory(name = "synthetic-round-trip", forItemType = DbItemType.Manga))

            val initialPush = first.sync(1, firstDb.settings())
            val initialSyncAccepted = diagnostics.any { it.status in 200..299 }
            if (!initialSyncAccepted) printDiagnostic(diagnostics.lastOrNull { it.status >= 400 }, phase = "initialSync")
            assertTrue(initialSyncAccepted, "Hub did not accept the initial full-state sync")
            assertTrue(initialPush.uploadedChanges > 0, "Initial state push sent no changes")

            assertTrue(second.login(2, configuredHub, credentials.getValue("ADMIN_EMAIL"), credentials.getValue("ADMIN_PASSWORD")).success, "Second disposable hub admin login failed")
            enableSettingsSync(secondDb)
            val pull = second.pullChanges(2)
            assertTrue(pull.errors.isEmpty(), "Second-client pull failed: ${pull.errors.size} sync error(s)")
            assertTrue(secondDb.categories().any { it.name == "synthetic-round-trip" }, "Synthetic category did not round-trip")

            firstDb.updateSettings(firstDb.settings().copy(sourcePreferences = listOf(DbSourcePreference(7, "invalid.dot-key", reproValue))))
            val keyedPush = first.pushChanges(1)
            val acceptedPreferencePush = diagnostics.lastOrNull {
                it.status in 200..299 && it.paths.any { (_, path) -> path == "sourcePreferences.7:invalid.dot-key" }
            }
            if (acceptedPreferencePush == null) {
                printDiagnostic(diagnostics.lastOrNull { it.status >= 400 }, phase = "keyedPreferencePush")
            }
            assertTrue(acceptedPreferencePush != null, "Hub did not accept dotted preference path with a 2xx response")
            assertTrue(keyedPush.uploadedChanges > 0, "Dotted preference push sent no changes")

            val keyedPull = second.pullChanges(2)
            if (keyedPull.errors.isNotEmpty()) {
                printDiagnostic(diagnostics.lastOrNull { it.status >= 400 }, phase = "keyedPreferencePull")
            }
            assertTrue(keyedPull.errors.isEmpty(), "Second-client dotted preference pull failed: ${keyedPull.errors.size} sync error(s)")
            assertEquals(
                reproValue,
                secondDb.settings().sourcePreferences.orEmpty()
                    .singleOrNull { it.sourceId == 7L && it.key == "invalid.dot-key" }?.value,
                "Dotted preference key/value did not round-trip exactly",
            )
        } finally {
            first.close()
            second.close()
            http.close()
            owner.cancel()
        }
    }

    private fun enableSettingsSync(database: InMemoryYokanDatabase) {
        val preference = database.syncPreferences().single()
        database.upsertSyncPreference(preference.copy(syncSettings = true))
    }

    private fun readCredentials(file: File): Map<String, String> {
        require(file.isFile && file.canRead()) { "Hub env file is unavailable" }
        return file.readLines()
            .filter { it.isNotBlank() && !it.trimStart().startsWith("#") }
            .mapNotNull { line ->
                val (key, value) = line.removePrefix("export ").split("=", limit = 2).takeIf { it.size == 2 } ?: return@mapNotNull null
                key.trim() to value.trim().removeSurrounding("\"").removeSurrounding("'")
            }
            .toMap()
            .also { require("ADMIN_EMAIL" in it && "ADMIN_PASSWORD" in it) { "Hub env file lacks disposable admin credentials" } }
    }

    private class RecordingHttpService(
        private val delegate: KtorHttpService,
        private val diagnostics: MutableList<SyncDiagnostic>,
        private val secrets: List<String>,
    ) : HttpService {
        override suspend fun request(request: HttpRequest): HttpResponse {
            val response = delegate.request(request)
            if (request.url.endsWith("/api/v1/sync") && request.method.equals("POST", ignoreCase = true)) {
                val req = runCatching { Json.parseToJsonElement(request.body.orEmpty()).jsonObject }.getOrNull()
                val ops = req?.get("ops")?.let { runCatching { it as kotlinx.serialization.json.JsonArray }.getOrNull() }
                val paths = ops.orEmpty().mapNotNull { op ->
                    runCatching {
                        val value = op.jsonObject
                        value["k"]?.jsonPrimitive?.content?.let { kind ->
                            value["p"]?.jsonPrimitive?.content?.let { path -> kind to path }
                        }
                    }.getOrNull()
                }
                val error = runCatching {
                    Json.parseToJsonElement(response.body).jsonObject["error"]?.jsonPrimitive?.content
                        ?: Json.parseToJsonElement(response.body).jsonObject["code"]?.jsonPrimitive?.content
                }.getOrNull()?.let { message ->
                    val authToken = request.headers.entries.firstOrNull { it.key.equals("Authorization", ignoreCase = true) }
                        ?.value?.removePrefix("Bearer ")
                    safeError(message, secrets + listOfNotNull(authToken))
                }
                diagnostics += SyncDiagnostic(response.statusCode, error, paths.size, paths)
            }
            return response
        }

        override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit) =
            delegate.stream(request, onChunk)

        fun close() = delegate.close()

        private fun safeError(message: String, secrets: List<String>): String = secrets
            .filter(String::isNotEmpty)
            .fold(message) { safe, secret -> safe.replace(secret, "<redacted>") }
            .filter { it.isLetterOrDigit() || it in " _.:/-<>" }
            .take(240)
    }

    private data class SyncDiagnostic(val status: Int, val error: String?, val opCount: Int, val paths: List<Pair<String, String>>)

    private fun printDiagnostic(diagnostic: SyncDiagnostic?, phase: String) {
        if (diagnostic == null) {
            println("Hub diagnostic: request=not-captured phase=$phase")
            return
        }
        val op = diagnostic.paths.firstOrNull { (_, path) -> path == "sourcePreferences.7:invalid.dot-key" }
            ?: diagnostic.paths.firstOrNull()
        println("Hub diagnostic: status=${diagnostic.status} error=${diagnostic.error ?: "<none>"} " +
            "opKind=${op?.first ?: "<unknown>"} opCount=${diagnostic.opCount} path=${op?.second ?: "<unknown>"} " +
            "phase=$phase")
    }
}
```
[chapter-file-end]: #

### Completion record

- [ ] Every implementation/configuration and required asset shown above is present at its displayed path.
- [ ] Cross-chapter imports resolve against the intended contracts and platform source sets.
- [ ] The tests for this chapter pass in the rebuilt app; record the command, platform and result.
- [ ] Native, device, browser and live-service checks have evidence or an explicit “not run” entry.
[chapter-content-end]: #


Gate: two simulated devices converge without losing edits made during upload; account switch/logout cancels stale commits; outbox survives acknowledgement races and hub reset; SyncYomi 412 and Drive lock races recover. Run mapper/provider/lease/trigger/lifecycle tests. Live servers, CORS/ETag exposure and real Google OAuth remain separate integration checks. External Hub/SyncYomi server implementations are not in this repository.
