# Yokan Sync Server — Plan (v2, reinvented sync)

Self-hosted sync backend for the Yokan KMP app. Rust + Postgres + Next.js admin panel.
Separate repo (`yokan-hub`). This revision **replaces** the app's current snapshot-exchange protocol
(`HttpSyncService.kt`) with a new one; nothing here is constrained by the old wire format.

## 0. Why the old model can't be made efficient

| Today (`HttpSyncService.kt`) | Cost |
|---|---|
| Client posts *all* manga/chapters/tracks every round, server returns *all* of them | O(library) bandwidth and JSON work per sync on both sides, regardless of what changed |
| Row-level last-writer-wins on `updatedAt` | Reading a chapter on the phone clobbers a category change made on the desktop for the same title (same row, different fields) |
| Whole `DbSettings` blob (~200 fields incl. per-title lists) is one row | Any two devices touching settings clobber each other |
| Ids are local auto-increment (`YokanDatabase.kt:377`) | Two devices with existing libraries collide; same title added on two devices becomes two rows |
| Deletions via `changed_part` tombstones + `lastSync*` cutoffs | Fragile against clock skew between devices |

The redesign: **stable content-derived ids, a coalescing per-field outbox on the client, hybrid logical clocks,
path-level LWW plus two commutative types on the server, and one round-trip that pushes and pulls a delta.**

## 1. Sync model

### 1.1 Identity — deterministic ids

Ids stay `Long` (no schema type change) but become **derived from the natural key**, so the same title on two
devices is the same row and merging is automatic. No dedupe feature needed, ever.

| Entity | Id source (FNV-1a 64 of the key string, masked positive — pure Kotlin, synchronous on every target; `database/sync/SyncIds.kt`) |
|---|---|
| manga (remote) | `"$itemType|$sourceId|$link"` |
| manga (local archive) | `LocalLibraryIdentity` string (`LocalLibraryService.kt:38`) |
| chapter | `"$mangaId|$url"` (`archivePath` for local) |
| track | `"$mangaId|$syncId"` |
| history | `"$mangaId"` (one history row per title; `chapterId` is a field) |
| update | `"$mangaId|$chapterId"` |
| category | random 63-bit (no natural key; user-created) |
| settings | fixed id, but see 1.3 — the blob is exploded |

One-time Room migration (v1→v2) rewrites ids and every FK (`chapter.mangaId`, `history.*`, `track.mangaId`,
`update.*`, `manga.categories`, and the `mangaId`/`chapterId` keys inside `DbSettings` lists).

### 1.2 Clock — HLC

Every write gets a **hybrid logical clock** value: 64-bit = 48 bits wall ms + 16-bit counter, ties broken by
device id. Client rule: `hlc = max(now_ms, last_hlc.ms) . counter++`. On every server response the client
adopts `max(own, server_hlc)`, so a device with a wrong clock is pulled forward and can't "win the future".
Server clamps incoming clocks to `server_now + 60 s`.

### 1.3 Granularity — paths

A synced entity is a JSON object. Changes are tracked per **path**, not per row:

- top-level field: `isRead`, `name`, `favorite`
- one level of map key for list-of-keyed-objects fields: `categories.<categoryId>` (value `true` / delete),
  `personalReaderModeList.<mangaId>`, `sortChapterList.<mangaId>`, `chapterPageIndexList.<chapterId>`,
  `sourcePreferences.<sourceId>:<key>`, …

Kotlin lists like `List<DbPersonalReaderMode>` are marshalled to/from maps keyed by `mangaId` at the sync
boundary; the app's domain classes don't change. The settings blob becomes entity kind `settings` with ~200
paths (+ map entries) instead of one opaque value, so two devices changing different preferences never conflict.

### 1.4 Merge — path LWW + two monotone types

Default for every path: **last-writer-wins by HLC**. Registry of exceptions, tiny and shared by client and server
(same JSON test vectors, §6):

| Path | Type | Why |
|---|---|---|
| `history.readingTimeSeconds.<device>` | **max** per device (a grow-only counter: the client stores its own running total under its device id and reads the sum of the map) | reading on two devices adds up, and re-sending the same op is a no-op — a plain delta counter would double-count on retry |
| `manga.dateAdded` | **min** | earliest add wins |
| `chapter.lastPageRead` | LWW (deliberate) | re-reading from page 0 is intent, not a conflict |
| `_deleted` | LWW path like any other | delete newer than every field → row gone; any field newer than the delete → row resurrected with its stored doc |

Properties: commutative, associative, idempotent → replaying a batch is a no-op, order of arrival doesn't
matter, retries are free. There is no manual conflict UI: every conflict has a deterministic outcome. The server
reports which client ops *lost* so the app can show "n changes from another device took precedence" (optional).

### 1.5 Client outbox

Room table `outbox(kind, id, path, value_json, hlc, seq autoinc)`, PK `(kind, id, path)`.

- Every write to a synced entity in `YokanDatabase` diffs old vs new row and **upserts one outbox row per changed
  path**. Writing the same path again overwrites value/hlc and takes a new `seq`. Page-by-page reading produces
  one row, not hundreds. Nothing is recorded while no hub is logged in: such epoch-0 ops are never accepted, and
  the first sync after login seeds the hub with full local state instead (see the phase notes below).
- Non-synced tables: `download`, `page_cache`, `track_search`, `track_preference` (OAuth), `sync_preference`.
  `manga.customCoverImage` (BLOB) syncs as base64, it's rare.
- `chapter.downloadSize`, and `chapter.archivePath` while `downloadSize` is set (a download folder on this device),
  stay device-local; local-library chapters keep syncing their virtual `archivePath` (`SyncPaths`).
- Push triggers: debounce 3 s after the last outbox write while foreground+online; on background
  (WorkManager / BGTaskScheduler / desktop timer); on a live hint (§2.3).

### 1.6 Round trip

One request does push and pull. Client-side, in order:

1. Read outbox rows with `seq ≤ N` (N = current max). Send them with `since` (last server head).
2. Server (§3) merges ops, returns changed entities with `seq > since` as **full docs** (already merged), plus new `head`.
3. Client, in one Room transaction: delete outbox rows with `seq ≤ N` (rows rewritten during flight have `seq > N`
   and survive); apply each incoming doc, **except paths that still have an outbox row** (local newer edit,
   will win next round by HLC anyway). Store `head`.

Clocks never leave the server. The client only needs its unpushed ops to merge correctly, because everything it
has pushed is already inside the docs it receives.

## 2. Wire protocol

Single endpoint plus a hint channel. JSON via kotlinx.serialization (already used), gzip both ways
(Ktor `ContentEncoding` / tower-http). Field names are one letter because a steady-state sync is dominated
by op envelopes, not values.

All API routes live under `/api/` so the admin SPA can own every other path. `GET /api/version` →
`{"supported": ["1"]}` (no auth) is checked by the client before it sends credentials.

```
POST /api/v1/sync
Authorization: Bearer <token>
X-Device: <stable device id>

{ "since": 18234, "epoch": 3, "hlc": 1756700000000_0007,
  "ops": [ {"k":3,"id":-812…,"p":"isRead","v":true,"t":1756700000000_0007},
           {"k":3,"id":-812…,"p":"lastPageRead","v":18,"t":1756700000000_0008},
           {"k":5,"id":4471…,"p":"readingTimeSeconds.<device>","v":5340,"t":…}, // per-device running total, merge = max
           {"k":2,"id":4471…,"p":"categories.77","v":null,"t":…},          // null = delete path
           {"k":2,"id":9912…,"p":"_deleted","v":true,"t":…} ] }

200 { "epoch": 3, "head": 18291, "tip": 18291, "hlc": 1756700000210_0001, "more": false,
      "ents": [ {"k":3,"id":-812…,"doc":{…full merged chapter…}},
                {"k":2,"id":9912…,"del":true} ],
      "lost": 1 }
```

- `k` = kind: 1 category, 2 manga, 3 chapter, 4 track, 5 history, 6 update, 7 settings.
- `more: true` → client repeats with `since = head` (page size 500 entities). Initial sync of a new device is
  the same loop from `since: 0`; no separate restore mode. `tip` is the user's newest seq, so
  `(head - since) / (tip - since)` is pull progress while `more` is true.
- `epoch` mismatch or `since < min_seq` (tombstones already purged) → `409 {"resync": true}` → client sets
  `since = 0` and keeps its outbox. Only two failure shapes exist.
- Idempotent: same ops re-sent after a network failure lose LWW to themselves (strict `>`) — no idempotency keys.
- Steady state: reading one chapter costs ~150 bytes up, ~400 bytes down. `ops: []` with `since == head`
  returns ~60 bytes.

### 2.3 Live hint

`WS /api/v1/events` (WebSockets are already wired on all five targets in the app). Server sends `{"head": 18291}`
whenever the user's head advances by a *different* device. Client does a round trip. Nothing else travels over
the socket. Reconnect with jittered backoff; the socket is a latency optimisation, never a correctness requirement.

## 3. Server

### 3.1 Data model

```sql
create table entities (
  user_id  uuid not null references users on delete cascade,
  kind     smallint not null,
  id       bigint not null,
  doc      jsonb not null,               -- merged current value (kept on tombstones for resurrection)
  clocks   jsonb not null,               -- {"path": hlc, ...} incl. "_deleted"
  deleted  bool not null default false,
  seq      bigint not null,              -- per-user dense sequence
  primary key (user_id, kind, id)
);
create index entities_delta on entities (user_id, seq);

alter table users add column head bigint not null default 0,      -- last assigned seq
                  add column min_seq bigint not null default 0,   -- oldest seq still fully represented
                  add column epoch int not null default 1;        -- bump only when history is rewritten
```

No oplog table. The materialised row *is* the log entry: `seq` says "changed after X", the merged doc says what
it is now. Storage stays O(entities), never grows with activity. Tombstones are purged after 30 days (`min_seq`
advances; a device gone longer than that resyncs from zero).

### 3.2 Request handling (one transaction)

```
pg_advisory_xact_lock(hash(user_id))                 -- serialise devices of the same user
select … from entities where (kind,id) in unnest(touched) for update
merge in Rust: per op, compare t with clocks[path]; apply lww / counter / min; note losers
head += 1 per changed entity; upsert via unnest (doc, clocks, deleted, seq)
select … where user_id = $1 and seq > $2 order by seq limit 500
update users set head = …
notify live hub (in-process broadcast channel keyed by user_id; single-node server, no Redis)
```

Cost per request is O(ops + delta rows). A 50k-chapter library that nobody touched costs one index probe.
Merge lives in one pure Rust module (`merge.rs`: `fn apply(doc, clocks, op) -> Outcome`) with no SQL in it.

### 3.3 Snapshots, backups, rollback

- **Infra**: `pg_dump` cron sidecar in `compose.yaml`. Not built into the binary.
- **Per-user snapshots** (`snapshots(user_id, reason, seq_at, blob zstd, created_at)`): nightly, before every
  rollback, on demand. Export renders as a Yokan `BackupSnapshot` (`schemaVersion 1`) so the app's existing
  importer reads it.
- **Rollback** to a snapshot: `pre_rollback` snapshot first; then in one transaction every live entity not in the
  snapshot is tombstoned and every snapshot entity is written with `clocks = {all paths: now_hlc}` and a fresh
  `seq`. That's the whole trick: rolled-back values carry the newest clocks, so **pending ops on offline devices
  lose by ordinary LWW** and every device converges through the normal delta pull. No generation counter, no
  special client state. `epoch` is bumped only when a Postgres restore moves `head` backwards.
- The panel shows a diff-count preview (`+n / −n` per kind) before confirming.

### 3.4 Stack

| | |
|---|---|
| HTTP/WS | `axum`, `tokio`, `tower-http` (compression, request-decompression, trace, `ServeDir`) |
| DB | `sqlx` postgres, compile-time checked, `sqlx migrate` |
| Auth | `argon2`, random 32-byte tokens hashed with SHA-256 in `sessions`; `subtle` compare |
| JSON | `serde_json` with `RawValue` for op values (never re-serialised) |
| Blobs | `zstd` |
| Admin UI | Next.js 15 App Router + Tailwind + **shadcn/ui**, `output: 'export'`, served by axum → no Node in prod |
| Deploy | `compose.yaml`: `postgres:17`, `yokan-hub` (distroless), `pg_dump` cron. TLS from the user's proxy |
| Config | env vars only. `tracing` JSON logs, `GET /healthz` |

## 4. Users, permissions, invites

Unchanged in spirit from the first draft, restated for completeness.

- `users(id, email citext, password_hash, role 'admin'|'user', permissions text[], quota jsonb, disabled, …)`
- `sessions(token_hash, user_id, device_id, label, created_at, last_seen, expires_at)` — 30-day sliding; users
  revoke their own devices, admins anyone's. Bearer token for app and panel alike.
- `invites(code, grants jsonb {role, permissions, quota}, max_uses, uses, expires_at, revoked, created_by)`.
  `POST /api/v1/register {email,password,code?}`. Invite link `PUBLIC_URL/join/<code>` served by the SPA.
  The app only ever logs in (`POST /api/v1/login` → `{token}`).
- **Access mode** (`server_settings.access_mode`, toggled by admins in the panel, default `invite_only`):

  | Mode | `register` | `login` / `sync` |
  |---|---|---|
  | `open` | no code needed (an optional code still applies its grants) | normal |
  | `invite_only` | valid code required | normal |
  | `maintenance` | `503` | `503` for role `user`; admins still log in and use the panel |

  `503` responses carry `Retry-After` and `{"error":"maintenance"}`; the app shows the message and keeps its outbox.
- Permissions checked by an axum extractor:
  `sync:read:{library|progress|settings}`, `sync:write:{…}` (library = kinds 1,2,3,4; progress = 5,6; settings = 7),
  `backup:export`, `backup:restore`, `rollback:self`, `invite:create`, `devices:manage`,
  `admin:{users,invites,backups,audit,settings}`.
- Quota: `max_bytes` (sum of `pg_column_size(doc)`), `max_devices`, `snapshot_keep`. Enforced in the sync transaction.
- `audit_log(at, actor, action, target, meta)`; `server_settings` single jsonb row.
- `tower_governor` rate limit on `/login` and `/register` only.

## 5. Admin panel (Next.js + shadcn/ui)

| Route | Contents |
|---|---|
| `/login`, `/join/<code>` | sign in; redeem invite |
| `/` | tiles: users, live devices, entities, storage, syncs/24 h, ops lost to conflicts/24 h, last backup |
| `/users` | data-table; row sheet: permissions checklist, quota, devices (revoke), disable, reset password, **snapshot timeline + rollback** |
| `/invites` | create from template → grants, copy link, uses/expiry, revoke |
| `/backups` | per-user snapshots, create now, export, rollback-to (with diff preview); pg_dump status |
| `/audit` | filterable log |
| `/settings` | **access mode switch** (open / invite only / maintenance), snapshot schedule/retention, tombstone retention, session TTL |
| `/me` | own password, devices, snapshots, export, rollback (if permitted) |

## 6. Testing the merge (the part that must not be wrong)

- `merge.rs` gets a `proptest`: for random op sets, every permutation and every duplication yields the same doc.
- The same rules exist once in Kotlin (`SyncMerge.kt`, used for the "skip paths with pending outbox rows" step and
  for unit tests). **Shared JSON vectors** in `yokan-hub/test-vectors/*.json` (`ops → expected doc`) are run by
  `cargo test` and by `:composeApp:desktopTest` so the two implementations can't drift.
- `#[sqlx::test]` per handler; one integration test drives two simulated devices through offline edits, a
  delete/edit race, and a rollback, asserting convergence.

## 7. Client work (this repo)

| # | Change | Where |
|---|---|---|
| 1 | Deterministic ids + Room v2 migration rewriting ids/FKs/settings keys | `YokanDatabase.kt`, `YokanRoomDatabase.kt`, new `SyncIdentity.kt` |
| 2 | `outbox` table + path diff on every synced write | `YokanDatabase.kt` upsert/remove paths, `RowAdapters.kt` |
| 3 | List↔map marshalling for keyed list fields (`categories`, settings `*List`) | new `SyncPaths.kt` |
| 4 | New `HttpSyncService` (round trip, HLC, apply-with-outbox-mask, WS hint) replacing the current file | `services/HttpSyncService.kt` |
| 5 | `sync_preference`: replace `lastSync{Manga,History,Update}` with `head`, `epoch`, `hlc` | `DatabaseEntities.kt`, Room migration |
| 6 | Sync screen: server URL, login, devices link, "n changes from another device" note | `settings/sync/SyncSettingsScreen.kt` |
| 7 | Delete `changed_part` writes and `HybridSyncService`'s `cloud://` branch if cloud-backup sync is retired (decide; it's orthogonal) | `HybridSyncService.kt` |

Web (wasm) target: no Room; the outbox lives in the same `localStorage` snapshot. Same protocol, no special case.

## 8. Phases

> **Status (2026-09-02):** server side complete in `../yokan-hub` (phases 1, 2, 4, 5). Client side
> (phase 3) implemented in this repo: `database/sync/SyncIds.kt` (stable ids), `database/sync/SyncClock.kt` (HLC),
> `database/sync/SyncPaths.kt` (wire docs, list↔map, path diff, masking), `database/sync/SyncIdentityMigration.kt`
> (one-time id rewrite, `DbSettings.syncIdentityVersion`), outbox in `InMemoryYokanDatabase` +
> Room v2 (`outbox` table, `sync_preference.hub*` columns, `MIGRATION_1_2`),
> `services/HubSyncService.kt` replacing `HttpSyncService`. Tests in `commonTest/.../database/sync/*` and
> `HubSyncServiceTest`. Deviation from the plan: no Kotlin `SyncMerge.kt` — the client never merges
> (the hub does; the client only masks pending paths), so the shared vectors stay a hub-only test and
> the client tests cover the list↔map conventions instead. Remaining: web (wasm) has no Room, so its
> outbox lives in the localStorage snapshot (already covered by the snapshot field); sync screen
> shows pending-change count. Full-state upload (2026-09-03): the outbox only covers edits made
> since it started recording, so `HubSyncService` also streams every synced entity as path ops, in
> `MAX_OPS` chunks with `since = NO_DELTA`, (a) on the first push from a device (`hubHead == 0`,
> i.e. after login) with clock `SEED_CLOCK` so the hub's existing values win and only gaps are
> filled, and (b) on "Upload only" with fresh clocks so local state wins. A backup restore records
> every path it changed (and every entity it removed) as ordinary outbox ops with fresh clocks, so
> restored values win on the hub instead of being undone by the next pull; it also resets `hubHead`
> to 0 so the next round re-pulls everything else.

| Phase | Scope | Rough size |
|---|---|---|
| 1 | `merge.rs` + proptest + test vectors; Kotlin `SyncMerge`/`SyncPaths` against the same vectors | 3 days |
| 2 | Server: schema, auth/register/invites, `/v1/sync`, `/v1/events`, compose, first-boot admin | 1 week |
| 3 | Client: deterministic ids + migration, outbox, new `HttpSyncService`, sync screen | 1.5 weeks |
| 4 | Snapshots, export, rollback; permissions/quotas; audit | 4 days |
| 5 | Admin SPA | 1 week |

Phase 1 is deliberately first: if the merge rules are right, everything else is plumbing.

## 9. Deliberately skipped (and when to add)

- **Manual conflict resolution UI.** Path LWW + counter/min gives a deterministic answer for every case in this
  data model. Add only if users report a specific field where "last write" is the wrong answer; that becomes a
  new merge type in the registry, not a UI.
- **Binary encoding (CBOR/protobuf).** Gzip'd single-letter JSON is within ~30 % of it. Add when a profile shows
  serialisation on the client's hot path.
- **Snapshot-served initial sync.** `since: 0` paging is the same code; serve the zstd snapshot blob instead when
  first sync of a huge library is measurably slow.
- **Multi-node server / Redis pub-sub.** In-process broadcast; personal-scale server.
- **Per-path clocks compaction.** `clocks` jsonb per row is small; collapse to a single row clock when all paths
  share it if storage ever matters.
- **End-to-end encryption.** Server must read paths and clocks to merge; values could be opaque later without a
  schema change, but not now.
- **OAuth/SSO, TOTP, Prometheus.** Invite-gated personal server; `tracing` + `/healthz` first.
