From 7a5cf8da4fc879ad01816c55119718dcd843a607 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 20 Jul 2026 22:00:05 +0000 Subject: [PATCH] Revamp 4.3: Postgres persistence loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add the ydoc persistence loop (ROADMAP §4.3, D6): Realtime is latency, Postgres is truth. - 0007_compaction.sql: claim_compaction RPC (SECURITY DEFINER, membership-checked) — optimistically installs a fresh compacted ydoc_state snapshot guarded by the seq generation and prunes the subsumed ydoc_updates rows, so the append log stays bounded. - ydocPersistence.ts: catch-up on open (fetch snapshot + log, apply as ORIGIN_REMOTE, push local-ahead diff), debounced attributed appends with offline retry, and optimistic compaction past 200 rows. - syncManager: start/stop the loop for signed-in cloud projects alongside the realtime transport; strictly additive, dynamic import. - Tests: catch-up convergence, append coalescing, offline-A/online-B convergence (DoD), compaction fold+prune + stale-claim race. - Docs: cloud.md migration list + §10 manual matrix; STATUS 4.2 -> done, 4.3 -> in-review. Green: 636 unit (+7) / typecheck / build. Flag-off bundle has zero Supabase/persistence code; flag-on keeps both in lazy chunks out of the entry. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_015AEnTYBecWG64R3iP8GBiE --- docs/cloud.md | 34 +++ docs/revamp/STATUS.md | 5 +- src/storage/cloud/ydocPersistence.ts | 292 +++++++++++++++++++++++ src/storage/sync/syncManager.ts | 20 +- supabase/migrations/0007_compaction.sql | 69 ++++++ tests/unit/cloud.ydocPersistence.test.ts | 276 +++++++++++++++++++++ 6 files changed, 693 insertions(+), 3 deletions(-) create mode 100644 src/storage/cloud/ydocPersistence.ts create mode 100644 supabase/migrations/0007_compaction.sql create mode 100644 tests/unit/cloud.ydocPersistence.test.ts diff --git a/docs/cloud.md b/docs/cloud.md index e326a17..75b54db 100644 --- a/docs/cloud.md +++ b/docs/cloud.md @@ -104,6 +104,16 @@ and safe to re-run: - `0006_projects_helpers_private.sql` — moves the `is_project_member` / `has_project_role` RLS helpers into a non-API `private` schema so they are not reachable as PostgREST RPCs (clears the database linter). Apply after `0005`. +- `0007_compaction.sql` — the `claim_compaction(project_id, expected_seq, state, + up_to_id)` RPC (SECURITY DEFINER, membership-checked): optimistically installs + a fresh compacted `ydoc_state` snapshot (guarded by the `seq` generation) and + prunes the subsumed `ydoc_updates` rows, so the append log stays bounded. Backs + Phase 4.3. Apply after `0006`. *(Numbering note: ROADMAP §4.3 sketched + `0005_compaction.sql`, but `0005`/`0006` were taken by the 4.1 project + migrations, so it ships as `0007`; and the RPC signature is widened from the + sketch's `(project_id, expected_seq)` to also carry the new snapshot + the + pruned-through id, so the whole compaction is one atomic, RLS-safe + transaction.)* > Note: the linter's "Leaked Password Protection Disabled" warning is unrelated > to these migrations — it's an optional **Authentication → Policies** toggle @@ -224,3 +234,27 @@ LWW and tombstones. Apply `0004_personal_resources.sql` first. **not** appear in `personal_tm`, and uninstalling on A doesn't touch B. - [ ] **Local-only unaffected**: signed out, glossary/TM work exactly as before and no `personal_glossary`/`personal_tm` request is made (no tombstones written). + +## 10. Manual verification (Phase 4.3 — Postgres persistence loop) + +The persistence loop (`src/storage/cloud/ydocPersistence.ts`) makes Postgres the +source of truth for a cloud project's Yjs doc: catch-up on open, debounced +appends of local edits to `ydoc_updates`, and optimistic compaction into +`ydoc_state` via `claim_compaction`. Realtime (§4.2) is only the low-latency +channel. Apply `0007_compaction.sql` first. Two signed-in members, each having +opened the same published cloud project: + +- [ ] **Catch-up on open**: member B opens the project → the doc arrives from + Postgres (`ydoc_state` + `ydoc_updates`) even with Realtime idle. +- [ ] **Append**: member A edits → within ~½s a new `ydoc_updates` row appears, + `author_id = A`. B (reopened, or after a reconnect) sees the edit. +- [ ] **Offline convergence**: take B offline, edit on both A (online) and B + (offline), bring B back and reopen → both docs converge, no edit lost + (Yjs replay is idempotent). +- [ ] **Compaction bounds the log**: drive `ydoc_updates` past ~200 rows → a + client folds them into a new `ydoc_state` snapshot (its `seq` increments) + and the log shrinks. With two clients compacting at once, only one wins + (the `seq` guard) and the other no-ops — no lost updates. +- [ ] **Local-only unaffected**: a project with no `cloud` link makes no + `ydoc_state`/`ydoc_updates` request; the BroadcastChannel/LAN path is + unchanged. diff --git a/docs/revamp/STATUS.md b/docs/revamp/STATUS.md index def5444..828885c 100644 --- a/docs/revamp/STATUS.md +++ b/docs/revamp/STATUS.md @@ -29,8 +29,8 @@ Rules for autonomous sessions: | 3.3.1 | Sidebar layout sync (deferred from 3.3) | S | 3.3 | done (PR #53) | | 3.4 | Personal term bank + TM sync | M | 3.3 | done (PR #52) | | 4.1 | Cloud project schema + RLS + publish/join | M | 3.1 | done (PR #55) | -| 4.2 | SupabaseRealtimeTransport + chunking | M | 4.1 | in-review (PR #56) | -| 4.3 | Postgres persistence loop (catch-up, append, compaction) | M | 4.2 | pending | +| 4.2 | SupabaseRealtimeTransport + chunking | M | 4.1 | done (PR #56) | +| 4.3 | Postgres persistence loop (catch-up, append, compaction) | M | 4.2 | in-review (PR #57) | | 4.4 | Live collab UX: cursors, leases, attribution | M | 4.3, 1.6 | pending | | 5.1 | Members & roles management | M | 4.1 | pending | | 5.2 | Role-gated editing workflow | M | 5.1, 1.6 | pending | @@ -71,3 +71,4 @@ Rules for autonomous sessions: - 2026-07-20 — Phase 3.4 merged in PR #52 (**Milestone 3 complete**). Phase 3.3.1 built: sidebar layout sync (the layout deferred from 3.3). `useSidebarPanelStore` gains a persisted LWW `updatedAt` stamped on every layout/collapsed mutation (`setTab`/`setLayout`/`showPanel`/`togglePanel`/`toggleCollapsed`/`movePanel`/`resetLayout`; transient open/active-tab never bump it) + `partialize`/`merge` carry it; `defaultLayout` exported for rehydration backfill. New `features/editor/layoutSync.ts` syncs the layout through the same `user_settings` cloud table under the `sidebar.layout` key with the same client-supplied LWW: `syncLayout(client, userId)` (pull-newer applies to the live store via `setState` — rehydrating machine B without a reload, backfilling any stage a stale remote misses — else push local-newer), plus `startLayoutSync()`/`stopLayoutSync()` wiring (reconcile once per new sign-in; debounced push on store change, guarded by an `applyingRemote` flag so a pull's `setState` never echoes back as a push). `main.tsx` starts it via a guarded **dynamic** import only when `isCloudConfigured()`. Deviation (noted in ROADMAP §4): the 3.3 `settingsSync` engine is bound to Dexie `settingsRepo` keys (not a source-agnostic adapter engine as the 3.3.1 note optimistically implied), so the layout — a zustand/localStorage store — syncs as a small **sibling** reconciler reusing `user_settings` + LWW rather than a settingsSync "adapter". No 3.3 code refactored (keeps that phase's tests untouched). `settingsSync` never sees the `sidebar.layout` row (its `.in()` query is scoped to `SYNCED_SETTINGS_KEYS`). Verified: flag-OFF `dist` has **zero** `GoTrueClient`/`syncLayout`/`user_settings` (layoutSync tree-shaken; the only `sidebar.layout` substring is the store's `verbalis.sidebar.layout` localStorage key — local code); flag-ON keeps `GoTrueClient` out of the entry and puts `layoutSync` in its own lazy chunk. Built on the designated session branch, not `claude/revamp-phase-3-3-1`. `docs/cloud.md` §8.1 verification. Tests: `layoutSync` (LWW: apply-newer-remote rehydrates the store, push-local-newer, push-when-no-remote-row, equal-noop), `layoutSync.wiring` (sign-in applies the cloud layout live; debounced push on a local layout change). Green: 608 unit (+6) / 27 e2e / build (flag-off layout-sync-free, flag-on lazy). - 2026-07-20 — Phase 3.3.1 merged in PR #53. Phase 4.1 built: cloud project schema + RLS + publish/open (start of **Milestone 4**, real-time collaboration). Migrations applied to the live project via the Supabase MCP (advisor clean bar the unrelated leaked-password Auth toggle): `0005_projects.sql` — `projects`, `project_members(role project_role enum: project_manager|translator|revisor)`, `ydoc_state(state bytea, seq)`, append-only `ydoc_updates(update bytea, author_id default auth.uid())` (tamper-evident attribution, D8), member-scoped RLS via `is_project_member`/`has_project_role` helpers, a private `project-files` storage bucket. `0006_projects_helpers_private.sql` — moves the two SECURITY DEFINER membership helpers into a non-API `private` schema (repoints every 0005 policy) so they stop being RPC-exposed while RLS keeps calling them, clearing the linter's 0029 lints. Numbering deviation: ROADMAP §4.1 sketched `0004_projects.sql`, but `0003`/`0004` were taken by the 3.3/3.4 migrations, so this shipped as `0005` + a `0006` hardening follow-up. `src/core/types`: `ProjectRole` + additive `Project.cloud?: {id, role}` (unindexed; local-only projects never carry it). `src/storage/cloud/bytea.ts`: pure hex-literal encode/decode for bytea-over-PostgREST (base64 decode fallback). `src/storage/cloud/projectCloud.ts`: pure client-injected data layer (`insertCloudProject` seeds the project row + owner `project_manager` membership + `ydoc_state` snapshot; `listCloudProjects`; `fetchCloudProject` → summary+role; `fetchYdocState` → decoded bytes) + orchestration (`publishProject` encodes the project's live Yjs doc via `acquireProjectDoc`+`Y.encodeStateAsUpdate`, inserts, stamps `project.cloud`; `openCloudProject` fetches metadata+snapshot, hydrates a fresh local Dexie project + its segments via `readAllSegments`, reusing an existing local copy rather than duplicating). Strictly additive — `getSupabase()` dynamic, gated on `isCloudConfigured()`. UI (self-gating, cloud logic dynamically imported so the projects route stays lean): `features/projects/cloud/CloudControls.tsx` (`CloudBadge`, owner `PublishCloudButton` on a card, `OpenFromCloudButton` header action — all render null unless configured + signed-in) + `OpenCloudProjectDialog.tsx` (lists member projects, opens → navigates to the local copy); wired into `ProjectCard` + projects `index.tsx`. Verified: flag-OFF `dist` has **zero** `GoTrueClient`; flag-ON keeps Supabase in a lazy chunk out of the entry. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-4-1`; the two-account publish→open→RLS-deny round-trip is the manual DoD (needs two real sessions; vitest uses an injected mock client). Tests: `cloud.bytea` (hex round-trip incl. all 256 byte values + empty + base64 fallback), `cloud.projectCloud` (insert creates all three rows with the owner as project_manager and a decodable snapshot; list camelCase mapping; fetch summary+role incl. translator default + null-when-absent; error propagation — all via an in-memory client mirroring the PostgREST chains). Green: 618 unit (+10) / 27 e2e twice / build (flag-off Supabase-free, flag-on lazy); no new e2e (ROADMAP §4 asks none for 4.1). - 2026-07-20 — Phase 4.1 merged in PR #55. Phase 4.2 built: `SupabaseRealtimeTransport` + chunking (pure client, no schema change). `src/storage/sync/transport/chunking.ts` — the protocol core: base64 wire encoding (`bytesToBase64`/`base64ToBytes`), `encodeMessage(SyncMessage, limit=60000)` frames a message into `WireChunk`s (Realtime is JSON + ~250KB/msg, so binary payloads are base64 +33% and split), and an order-independent `ChunkReassembler` that yields a `SyncMessage` once all chunks of a message id arrive (single-chunk pass-through; payloadless kinds `hello`/`bye`/`state-request` carry `d:''`). `src/storage/sync/transport/supabaseRealtime.ts` — `SupabaseRealtimeTransport implements SyncTransport` over a private Realtime broadcast channel `project:{cloudId}` (`broadcast:{self:false}`, so no self-echo, matching BroadcastChannel); `getSupabase()` is dynamic so no eager supabase-js. Outbound `update`s are coalesced by `OutboundUpdateBatcher` (debounce 300ms → `Y.mergeUpdates` → one broadcast); other kinds send immediately; sends before `SUBSCRIBED` buffer in an outbox flushed on subscribe. The channel is injectable (`channelProvider`) as a test seam. `createTransport(projectId, {cloudId?})` gains a cloud branch (Supabase when `cloudId` set; **BroadcastChannel/Tauri paths byte-identical otherwise**); `syncManager.startProjectSync` computes `cloudId` from `project.cloud` when signed-in + `isCloudConfigured()`, else `undefined`. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-4-2`; the transport is complete + unit-covered now, but the end-to-end **two-browser live edit** DoD needs the Postgres initial-state loop (4.3) + the auto-start-on-open UI (4.4) — the transport is selectable but not yet auto-wired for cloud projects (that's 4.4), stated honestly. No migration (4.2 is transport-only). Tests: `sync.chunking` (base64 all-bytes/empty round-trip; single + multi-chunk encode/reassemble; out-of-order arrival; two interleaved messages stay separate; payloadless pass-through), `sync.realtimeTransport` (`OutboundUpdateBatcher` merges a burst into one flush that replays both edits via fake timers + no-fire-after-destroy; transport delivers a 50KB multi-chunk `state` to the *other* peer only via a linked in-memory channel pair — caught + fixed a real ordering bug where the outbox flushed before `this.channel` was assigned; pre-subscribe sends buffer then flush). Green: 629 unit (+11) / 27 e2e twice / build (flag-off has zero `GoTrueClient`; flag-on keeps Supabase a lazy chunk out of the entry). +- 2026-07-20 — Phase 4.2 merged in PR #56 (STATUS was stale — recorded here). Phase 4.3 built: the Postgres persistence loop (Realtime is latency, Postgres is truth). `supabase/migrations/0007_compaction.sql` — the `claim_compaction(project_id, expected_seq, state, up_to_id)` RPC (SECURITY DEFINER, membership-checked): atomically bumps the `ydoc_state.seq` generation **only while it still matches** `expected_seq`, installs the new compacted snapshot, and prunes `ydoc_updates` with `id <= up_to_id`. Numbering deviation: ROADMAP §4.3 sketched `0005_compaction.sql`, but `0005`/`0006` were taken by the 4.1 project migrations, so it ships as `0007`; and the RPC signature is **widened** from the sketch's `(project_id, expected_seq)` to also carry the new snapshot + pruned-through id, so the whole compaction is one atomic RLS-safe transaction (the append log has no DELETE policy by design — D8 tamper-evidence — so pruning goes through this controlled definer path, membership re-checked inside). `src/storage/cloud/ydocPersistence.ts` — pure client-injected data layer (`fetchSnapshot`/`fetchUpdates`/`appendUpdate`/`countUpdates`/`claimCompaction`, hex-bytea via 4.1's `bytea.ts`) + the `createYdocPersistence({cloudId, doc, client})` loop: **catch-up** fetches `ydoc_state` + the whole `ydoc_updates` log, merges (`Y.mergeUpdates`) and applies as `ORIGIN_REMOTE` (so neither the transport nor this loop re-broadcasts/re-appends it), then pushes anything the local doc holds that the cloud lacks (offline edits / pre-publish history) by diffing state vectors (`Y.encodeStateAsUpdate(doc, remoteSV)` when `localAheadOf`); **append** buffers local `doc.on('update')` deltas (ignoring `ORIGIN_REMOTE`), debounce-merges them (500ms) into one attributed `ydoc_updates` row, and re-buffers/retries on a failed (offline) append; **compaction** triggers once the log passes 200 rows — it re-reads the *authoritative* snapshot+updates from Postgres (never the possibly-lagging local doc) to build the new snapshot, so it subsumes exactly the rows it prunes, then optimistically `claim_compaction`s (loser gets `null` and no-ops — the log is already bounded). Catch-up is re-runnable (idempotent Yjs replay), which is what converges an offline member on reconnect. Wiring: `syncManager.startProjectSync` starts the loop (dynamic `startYdocPersistence`, only when `cloudId` set + signed-in + `isCloudConfigured()`) alongside the realtime transport, kicks off a non-blocking `catchUp()`, stores the handle on the ref-counted session, and destroys it in `stopProjectSync`; local-only projects never touch it. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-4-3`; the RPC signature widening above; live **reconnect re-sync** (re-`hello`/re-`catchUp` when Realtime drops-then-resubscribes) is left to 4.4, which owns the transport/auto-start UX — 4.3 converges on **reopen** (each open runs catch-up), the DoD proven at the persistence layer. `docs/cloud.md` (§3 migration list + §10 manual verification). Tests: `cloud.ydocPersistence` (catch-up converges a fresh doc from snapshot+log; append coalesces a burst into one row; applied-remote is never re-appended; **offline-A/online-B converge through Postgres with no edit lost** — the DoD, on a shared in-memory server; compaction folds+prunes past the threshold and bumps seq, and a stale optimistic claim returns `null`; `fetchSnapshot`/`fetchUpdates` bytea round-trips). Green: 636 unit (+7) / build (flag-off: **zero** `GoTrueClient`/`claim_compaction` — the loop tree-shakes out entirely when the cloud is unconfigured; flag-on: `GoTrueClient` and the persistence loop each in their own lazy chunk, out of the entry). No new e2e (ROADMAP §4 asks none for 4.3; the two-member live DoD needs a real backend, per the §10 manual matrix). diff --git a/src/storage/cloud/ydocPersistence.ts b/src/storage/cloud/ydocPersistence.ts new file mode 100644 index 0000000..9245c9d --- /dev/null +++ b/src/storage/cloud/ydocPersistence.ts @@ -0,0 +1,292 @@ +import type { SupabaseClient } from '@supabase/supabase-js' +import * as Y from 'yjs' +import { ORIGIN_REMOTE } from '@/storage/sync/segmentCrdt' +import { isCloudConfigured, getSupabase } from './supabaseClient' +import { encodeBytea, decodeBytea } from './bytea' + +/** + * Postgres persistence loop for a cloud project's Yjs doc (ROADMAP §4.3, D6). + * + * Realtime (§4.2) is the low-latency channel; Postgres is the source of truth. + * This loop keeps the two honest: + * + * - **Catch-up on open** — fetch the compacted `ydoc_state` snapshot plus the + * whole `ydoc_updates` log, apply the merge as `ORIGIN_REMOTE` (so neither the + * transport nor this loop re-broadcasts / re-appends it), and push anything the + * local doc holds that the cloud lacks (offline edits) back up. Yjs updates are + * idempotent, so re-running catch-up on reconnect converges by replay. + * - **Debounced append** — local edits are coalesced with `Y.mergeUpdates` and + * appended as one `ydoc_updates` row (attributed server-side via + * `author_id = auth.uid()`). A failed append re-buffers and retries. + * - **Optimistic compaction** — once the log grows past a threshold, re-read the + * authoritative snapshot + updates, fold them into a fresh snapshot, and + * install it via the `claim_compaction` RPC. The RPC's `seq` guard means only + * one racing compactor wins; the loser simply drops its attempt. + * + * Strictly additive (D6): no `@supabase/supabase-js` loads until a signed-in user + * opens a cloud project (`getSupabase()` is dynamic); the pure data functions + * take an injected client so vitest never touches a real backend. + */ + +/** Default debounce before a burst of local edits is appended as one row. */ +const APPEND_DEBOUNCE_MS = 500 +/** Compact once the update log exceeds this many rows (ROADMAP §4.3: >200). */ +const COMPACT_THRESHOLD = 200 + +// --------------------------------------------------------------------------- +// Pure data layer (client injected) +// --------------------------------------------------------------------------- + +/** The compacted snapshot bytes + its compaction generation (`seq`). */ +export interface SnapshotRow { + state: Uint8Array | null + seq: number +} + +/** Fetch the current snapshot + seq for a project (nulls when unseeded). */ +export async function fetchSnapshot( + client: SupabaseClient, + cloudId: string, +): Promise { + const { data, error } = await client + .from('ydoc_state') + .select('state,seq') + .eq('project_id', cloudId) + .maybeSingle() + if (error) throw new Error(error.message) + const row = data as { state: string | null; seq: number | string } | null + if (!row) return { state: null, seq: 0 } + return { state: row.state ? decodeBytea(row.state) : null, seq: Number(row.seq) } +} + +/** One decoded append-log row. */ +export interface UpdateRow { + id: number + bytes: Uint8Array +} + +/** Fetch the whole append log for a project, ordered oldest-first. */ +export async function fetchUpdates( + client: SupabaseClient, + cloudId: string, +): Promise { + const { data, error } = await client + .from('ydoc_updates') + .select('id,update') + .eq('project_id', cloudId) + .order('id', { ascending: true }) + if (error) throw new Error(error.message) + return ((data as { id: number | string; update: string }[] | null) ?? []).map((r) => ({ + id: Number(r.id), + bytes: decodeBytea(r.update), + })) +} + +/** Append one (already-merged) Yjs update to the log; author is server-stamped. */ +export async function appendUpdate( + client: SupabaseClient, + cloudId: string, + bytes: Uint8Array, +): Promise { + const { error } = await client + .from('ydoc_updates') + .insert({ project_id: cloudId, update: encodeBytea(bytes) }) + if (error) throw new Error(error.message) +} + +/** How many rows the append log currently holds (head-only count query). */ +export async function countUpdates(client: SupabaseClient, cloudId: string): Promise { + const { count, error } = await client + .from('ydoc_updates') + .select('id', { count: 'exact', head: true }) + .eq('project_id', cloudId) + if (error) throw new Error(error.message) + return count ?? 0 +} + +/** + * Optimistically install a compacted snapshot: bumps `seq` from `expectedSeq`, + * writes `state`, and prunes updates with `id <= upToId` — all atomically in the + * RPC. Returns the new seq, or null when another compactor won the race. + */ +export async function claimCompaction( + client: SupabaseClient, + cloudId: string, + expectedSeq: number, + state: Uint8Array, + upToId: number, +): Promise { + const { data, error } = await client.rpc('claim_compaction', { + p_project_id: cloudId, + p_expected_seq: expectedSeq, + p_state: encodeBytea(state), + p_up_to_id: upToId, + }) + if (error) throw new Error(error.message) + return data === null || data === undefined ? null : Number(data) +} + +// --------------------------------------------------------------------------- +// Pure Yjs helpers +// --------------------------------------------------------------------------- + +/** Merge a snapshot + ordered updates into one update, or null when empty. */ +function mergeRemote(snapshot: Uint8Array | null, updates: UpdateRow[]): Uint8Array | null { + const parts: Uint8Array[] = [] + if (snapshot) parts.push(snapshot) + for (const u of updates) parts.push(u.bytes) + if (parts.length === 0) return null + return parts.length === 1 ? parts[0] : Y.mergeUpdates(parts) +} + +/** True when the local doc holds structs the remote state vector is missing. */ +function localAheadOf(doc: Y.Doc, remoteSV: Uint8Array): boolean { + const local = Y.decodeStateVector(Y.encodeStateVector(doc)) + const remote = Y.decodeStateVector(remoteSV) + for (const [client, clock] of local) { + if ((remote.get(client) ?? 0) < clock) return true + } + return false +} + +const EMPTY_STATE_VECTOR = Y.encodeStateVector(new Y.Doc()) + +// --------------------------------------------------------------------------- +// The loop +// --------------------------------------------------------------------------- + +export interface YdocPersistenceHandle { + /** Reconcile the local doc with Postgres (safe to re-run on reconnect). */ + catchUp(): Promise + /** Force-flush any pending appended edits now (used by tests). */ + flush(): Promise + /** Detach the doc listener and stop the loop. */ + destroy(): void +} + +export interface YdocPersistenceOptions { + cloudId: string + doc: Y.Doc + client: SupabaseClient + debounceMs?: number + compactThreshold?: number +} + +/** + * Create the persistence loop for a doc with an injected client (the unit-test + * seam). Attaches the local-update listener immediately; callers drive the first + * {@link YdocPersistenceHandle.catchUp}. + */ +export function createYdocPersistence(opts: YdocPersistenceOptions): YdocPersistenceHandle { + const { doc, client, cloudId } = opts + const debounceMs = opts.debounceMs ?? APPEND_DEBOUNCE_MS + const compactThreshold = opts.compactThreshold ?? COMPACT_THRESHOLD + + let buffer: Uint8Array[] = [] + let timer: ReturnType | null = null + let destroyed = false + + const scheduleFlush = () => { + if (destroyed || timer !== null) return + timer = setTimeout(() => { + timer = null + void flush() + }, debounceMs) + } + + const flush = async (): Promise => { + if (destroyed || buffer.length === 0) return + const merged = buffer.length === 1 ? buffer[0] : Y.mergeUpdates(buffer) + buffer = [] + try { + await appendUpdate(client, cloudId, merged) + await maybeCompact() + } catch { + // Offline / transient: re-buffer and retry on the next tick. Postgres is + // truth, so nothing is lost — the edit is still in the local doc + Dexie. + if (!destroyed) { + buffer.unshift(merged) + scheduleFlush() + } + } + } + + const maybeCompact = async (): Promise => { + if (destroyed) return + if ((await countUpdates(client, cloudId)) <= compactThreshold) return + // Re-read the authoritative state so the new snapshot subsumes exactly the + // rows we prune — never trust the local doc, which may lag a peer's append. + const snap = await fetchSnapshot(client, cloudId) + const updates = await fetchUpdates(client, cloudId) + if (updates.length <= compactThreshold) return // a peer compacted meanwhile + const merged = mergeRemote(snap.state, updates) + if (!merged) return + const cdoc = new Y.Doc({ gc: true }) + Y.applyUpdate(cdoc, merged) + const newState = Y.encodeStateAsUpdate(cdoc) + cdoc.destroy() + // A null result means a peer compacted first — the log is already bounded, + // so there is nothing to retry. + await claimCompaction(client, cloudId, snap.seq, newState, updates[updates.length - 1].id) + } + + const onLocalUpdate = (update: Uint8Array, origin: unknown) => { + if (destroyed || origin === ORIGIN_REMOTE) return + buffer.push(update) + scheduleFlush() + } + doc.on('update', onLocalUpdate) + + const catchUp = async (): Promise => { + if (destroyed) return + const snap = await fetchSnapshot(client, cloudId) + const updates = await fetchUpdates(client, cloudId) + const merged = mergeRemote(snap.state, updates) + + let remoteSV = EMPTY_STATE_VECTOR + if (merged) { + remoteSV = Y.encodeStateVectorFromUpdate(merged) + Y.applyUpdate(doc, merged, ORIGIN_REMOTE) + } + + // Anything the local doc has that the cloud lacks (offline edits, or the + // pre-publish history) is pushed up so every member converges through + // Postgres. Empty when the cloud is already ahead-or-equal. + if (localAheadOf(doc, remoteSV)) { + await appendUpdate(client, cloudId, Y.encodeStateAsUpdate(doc, remoteSV)) + } + } + + return { + catchUp, + flush, + destroy() { + if (destroyed) return + destroyed = true + doc.off('update', onLocalUpdate) + if (timer !== null) { + clearTimeout(timer) + timer = null + } + buffer = [] + }, + } +} + +// --------------------------------------------------------------------------- +// Wiring: resolve the real client and start the loop for a cloud project. +// --------------------------------------------------------------------------- + +/** + * Start the persistence loop for a signed-in cloud project. Loads the Supabase + * client dynamically (so local-only builds never pull it) and returns null when + * the cloud is unconfigured. The caller drives the first `catchUp`. + */ +export async function startYdocPersistence( + cloudId: string, + doc: Y.Doc, +): Promise { + if (!isCloudConfigured()) return null + const client = await getSupabase() + return createYdocPersistence({ cloudId, doc, client }) +} diff --git a/src/storage/sync/syncManager.ts b/src/storage/sync/syncManager.ts index 3bd1c4e..62be277 100644 --- a/src/storage/sync/syncManager.ts +++ b/src/storage/sync/syncManager.ts @@ -6,6 +6,7 @@ import { getProfileSettings } from '@/storage/repositories/settingsRepo' import { shareRepo } from '@/storage/repositories/shareRepo' import { projectRepo } from '@/storage/repositories/projectRepo' import { isCloudConfigured } from '@/storage/cloud/supabaseClient' +import { startYdocPersistence, type YdocPersistenceHandle } from '@/storage/cloud/ydocPersistence' import { useAuthStore } from '@/features/account/useAuthStore' /** @@ -20,6 +21,8 @@ import { useAuthStore } from '@/features/account/useAuthStore' interface ActiveSync { handle: SyncSessionHandle + /** Postgres persistence loop, present only for a signed-in cloud project. */ + persistence: YdocPersistenceHandle | null refs: number } @@ -60,7 +63,21 @@ export async function startProjectSync(projectId: string): Promise { + // Non-fatal: Dexie + the local Yjs doc stay authoritative; a later + // catch-up (reopen / reconnect, §4.4) reconciles via replay. + }) + } + + active.set(projectId, { handle, persistence, refs: 1 }) return handle } @@ -70,6 +87,7 @@ export function stopProjectSync(projectId: string): void { if (!entry) return entry.refs -= 1 if (entry.refs > 0) return + entry.persistence?.destroy() entry.handle.destroy() releaseProjectDoc(projectId) active.delete(projectId) diff --git a/supabase/migrations/0007_compaction.sql b/supabase/migrations/0007_compaction.sql new file mode 100644 index 0000000..60c176e --- /dev/null +++ b/supabase/migrations/0007_compaction.sql @@ -0,0 +1,69 @@ +-- Verbalis cloud — 0007 optimistic Yjs update-log compaction (ROADMAP §4.3, D6) +-- +-- The append-only `ydoc_updates` log (0005) grows one row per edit burst. Left +-- unbounded it bloats the DB and slows every catch-up. Compaction folds the log +-- back into the `ydoc_state` snapshot: a client that sees the log cross a +-- threshold re-reads the snapshot + all updates, merges them locally into a new +-- Yjs state, and calls `claim_compaction` to install it — atomically, and only +-- if no other client compacted first. +-- +-- Concurrency is optimistic. `ydoc_state.seq` is a compaction generation counter. +-- A caller passes the `seq` it based its merge on (`p_expected_seq`); the update +-- succeeds only while `seq` still matches, so two racing compactors can't both +-- win — the loser gets NULL back and simply drops its attempt (the log is +-- already bounded by the winner). `p_up_to_id` is the highest update id the new +-- snapshot subsumes; only those rows are pruned, so updates appended *during* +-- the merge (id > p_up_to_id) survive and replay on top of the fresh snapshot. +-- +-- SECURITY DEFINER because pruning `ydoc_updates` has no DELETE policy by design +-- (the log is append-only over the API to keep attribution tamper-evident, D8); +-- membership is enforced explicitly here instead. Idempotent; apply after 0006. + +create or replace function public.claim_compaction( + p_project_id uuid, + p_expected_seq bigint, + p_state bytea, + p_up_to_id bigint +) +returns bigint +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_new_seq bigint; +begin + -- Only a project member may compact (RLS is bypassed under SECURITY DEFINER). + if not private.is_project_member(p_project_id) then + raise exception 'not a project member'; + end if; + + -- Optimistic claim: bump the generation + install the snapshot only while the + -- expected generation still holds. A concurrent compactor that already bumped + -- seq leaves 0 rows matched → v_new_seq stays NULL. + update public.ydoc_state + set state = p_state, + seq = p_expected_seq + 1, + updated_at = now() + where project_id = p_project_id + and seq = p_expected_seq + returning seq into v_new_seq; + + if v_new_seq is null then + return null; + end if; + + -- Prune only the updates the new snapshot subsumes; newer appends replay. + delete from public.ydoc_updates + where project_id = p_project_id + and id <= p_up_to_id; + + return v_new_seq; +end; +$$; + +revoke execute on function public.claim_compaction(uuid, bigint, bytea, bigint) from anon, public; +grant execute on function public.claim_compaction(uuid, bigint, bytea, bigint) to authenticated; + +comment on function public.claim_compaction(uuid, bigint, bytea, bigint) is + 'Optimistically install a compacted ydoc_state snapshot (seq guard) and prune subsumed ydoc_updates. Returns the new seq, or NULL if another compactor won (ROADMAP §4.3).'; diff --git a/tests/unit/cloud.ydocPersistence.test.ts b/tests/unit/cloud.ydocPersistence.test.ts new file mode 100644 index 0000000..a801955 --- /dev/null +++ b/tests/unit/cloud.ydocPersistence.test.ts @@ -0,0 +1,276 @@ +import { describe, expect, it } from 'vitest' +import type { SupabaseClient } from '@supabase/supabase-js' +import * as Y from 'yjs' +import { + createYdocPersistence, + fetchSnapshot, + fetchUpdates, + claimCompaction, +} from '@/storage/cloud/ydocPersistence' +import { encodeBytea, decodeBytea } from '@/storage/cloud/bytea' + +/** + * In-memory stand-in for `ydoc_state` (one row per project) + the append-only + * `ydoc_updates` log + the `claim_compaction` RPC, mirroring the exact PostgREST + * chains the persistence loop uses, so catch-up / append / compaction are + * exercised end-to-end without a real backend. + */ +function makeServer() { + const state = new Map() + const updates: { id: number; project_id: string; update: string }[] = [] + let idSeq = 1 + + function ydocStateChain() { + const filters: Record = {} + const b = { + select() { + return b + }, + eq(col: string, val: unknown) { + filters[col] = val + return b + }, + maybeSingle() { + const row = state.get(filters.project_id as string) ?? null + return Promise.resolve({ data: row, error: null }) + }, + } + return b + } + + function ydocUpdatesChain() { + const filters: Record = {} + let countMode = false + const rows = () => updates.filter((u) => u.project_id === filters.project_id) + const b = { + select(_cols: string, opts?: { count?: string; head?: boolean }) { + countMode = !!opts?.head + return b + }, + insert(row: { project_id: string; update: string }) { + return { + then(onF: (v: { error: null }) => unknown, onR?: () => unknown) { + updates.push({ id: idSeq++, project_id: row.project_id, update: row.update }) + return Promise.resolve({ error: null }).then(onF, onR) + }, + } + }, + eq(col: string, val: unknown) { + filters[col] = val + return b + }, + order() { + const data = rows() + .slice() + .sort((a, z) => a.id - z.id) + .map((u) => ({ id: u.id, update: u.update })) + return Promise.resolve({ data, error: null }) + }, + then(onF: (v: { count: number; error: null }) => unknown, onR?: () => unknown) { + // Terminal only for the head:true count query. + const value = countMode + ? { count: rows().length, error: null as null } + : { count: 0, error: null as null } + return Promise.resolve(value).then(onF, onR) + }, + } + return b + } + + const client = { + from(table: string) { + if (table === 'ydoc_state') return ydocStateChain() + if (table === 'ydoc_updates') return ydocUpdatesChain() + throw new Error(`unexpected table ${table}`) + }, + rpc(name: string, args: Record) { + if (name !== 'claim_compaction') throw new Error(`unexpected rpc ${name}`) + const pid = args.p_project_id as string + const row = state.get(pid) + if (!row || row.seq !== args.p_expected_seq) { + return Promise.resolve({ data: null, error: null }) + } + row.state = args.p_state as string + row.seq = (args.p_expected_seq as number) + 1 + const upTo = args.p_up_to_id as number + for (let i = updates.length - 1; i >= 0; i--) { + if (updates[i].project_id === pid && updates[i].id <= upTo) updates.splice(i, 1) + } + return Promise.resolve({ data: row.seq, error: null }) + }, + } + + return { + client: client as unknown as SupabaseClient, + updates, + seed(projectId: string, bytes: Uint8Array | null, seq = 0) { + state.set(projectId, { state: bytes ? encodeBytea(bytes) : null, seq }) + }, + snapshotBytes(projectId: string) { + const s = state.get(projectId)?.state + return s ? decodeBytea(s) : null + }, + snapshotSeq(projectId: string) { + return state.get(projectId)?.seq ?? 0 + }, + } +} + +const PID = 'cloud-1' + +/** A doc seeded from a snapshot, with a text key for content assertions. */ +function docFrom(snapshot: Uint8Array | null): Y.Doc { + const doc = new Y.Doc({ gc: true }) + if (snapshot) Y.applyUpdate(doc, snapshot) + return doc +} +const text = (doc: Y.Doc) => doc.getText('t') + +describe('catch-up', () => { + it('converges a fresh doc from the cloud snapshot + append log', async () => { + const server = makeServer() + // Base snapshot: "Hello". + const base = new Y.Doc() + base.getText('t').insert(0, 'Hello') + const snapshot = Y.encodeStateAsUpdate(base) + server.seed(PID, snapshot) + // Two further edits recorded only in the append log. + let u1: Uint8Array | null = null + base.on('update', (u) => (u1 = u)) + base.getText('t').insert(5, ' world') + server.updates.push({ id: 1, project_id: PID, update: encodeBytea(u1!) }) + + const doc = new Y.Doc({ gc: true }) + const p = createYdocPersistence({ client: server.client, cloudId: PID, doc }) + await p.catchUp() + expect(text(doc).toString()).toBe('Hello world') + p.destroy() + }) +}) + +describe('append', () => { + it('coalesces a burst of local edits into one appended row', async () => { + const server = makeServer() + server.seed(PID, null) + const doc = new Y.Doc({ gc: true }) + const p = createYdocPersistence({ client: server.client, cloudId: PID, doc }) + + text(doc).insert(0, 'foo') + text(doc).insert(3, 'bar') + await p.flush() + + expect(server.updates).toHaveLength(1) + const rebuilt = new Y.Doc() + Y.applyUpdate(rebuilt, decodeBytea(server.updates[0].update)) + expect(text(rebuilt).toString()).toBe('foobar') + p.destroy() + }) + + it('applied remote updates are never re-appended (ORIGIN_REMOTE)', async () => { + const server = makeServer() + const base = new Y.Doc() + base.getText('t').insert(0, 'seed') + server.seed(PID, Y.encodeStateAsUpdate(base)) + + const doc = new Y.Doc({ gc: true }) + const p = createYdocPersistence({ client: server.client, cloudId: PID, doc }) + await p.catchUp() // applies the snapshot as ORIGIN_REMOTE + await p.flush() + expect(server.updates).toHaveLength(0) // nothing local to push + p.destroy() + }) +}) + +describe('offline-A / online-B convergence (DoD)', () => { + it('converges through Postgres on reconnect and never loses an edit', async () => { + const server = makeServer() + const base = new Y.Doc() + base.getText('t').insert(0, 'X') + const snapshot = Y.encodeStateAsUpdate(base) + server.seed(PID, snapshot) + + const docA = docFrom(snapshot) + const docB = docFrom(snapshot) + const pA = createYdocPersistence({ client: server.client, cloudId: PID, doc: docA }) + const pB = createYdocPersistence({ client: server.client, cloudId: PID, doc: docB }) + await pA.catchUp() + await pB.catchUp() + + // A edits while B is offline; A appends to Postgres. + text(docA).insert(1, 'A1') + await pA.flush() + // B edits offline too (buffered, not yet flushed to the shared server). + text(docB).insert(1, 'B1') + + // B reconnects: catch-up pulls A's edit and pushes B's offline edit. + await pB.flush() + await pB.catchUp() + // A reconnects and catches up. + await pA.catchUp() + + expect(text(docA).toString()).toBe(text(docB).toString()) + // Both edits survived (order is CRDT-deterministic but content is present). + for (const s of ['A1', 'B1', 'X']) expect(text(docA).toString()).toContain(s) + pA.destroy() + pB.destroy() + }) +}) + +describe('compaction', () => { + it('folds the log into a fresh snapshot and prunes it past the threshold', async () => { + const server = makeServer() + server.seed(PID, null) + const doc = new Y.Doc({ gc: true }) + const p = createYdocPersistence({ + client: server.client, + cloudId: PID, + doc, + compactThreshold: 2, + }) + + // Three flushed edits → three log rows; the third crosses the threshold and + // triggers compaction, which folds them into the snapshot and prunes. + text(doc).insert(0, 'a') + await p.flush() + text(doc).insert(1, 'b') + await p.flush() + text(doc).insert(2, 'c') + await p.flush() + + expect(server.updates.length).toBeLessThanOrEqual(2) + expect(server.snapshotSeq(PID)).toBe(1) + // The compacted snapshot reproduces the full content. + const fresh = docFrom(server.snapshotBytes(PID)) + // Replay any surviving updates on top. + for (const u of server.updates) Y.applyUpdate(fresh, decodeBytea(u.update)) + expect(text(fresh).toString()).toBe('abc') + p.destroy() + }) + + it('a stale optimistic claim loses the race (returns null)', async () => { + const server = makeServer() + server.seed(PID, new Uint8Array([0, 0]), 5) + // A concurrent compactor already advanced seq to 6. + const won = await claimCompaction(server.client, PID, 5, new Uint8Array([1]), 0) + expect(won).toBe(6) + // Our stale claim (still expecting 5) is rejected. + const lost = await claimCompaction(server.client, PID, 5, new Uint8Array([2]), 0) + expect(lost).toBeNull() + }) +}) + +describe('data helpers', () => { + it('fetchSnapshot / fetchUpdates decode bytea round-trips', async () => { + const server = makeServer() + const bytes = new Uint8Array([1, 2, 250, 0, 42]) + server.seed(PID, bytes, 3) + server.updates.push({ id: 7, project_id: PID, update: encodeBytea(new Uint8Array([9, 8])) }) + + const snap = await fetchSnapshot(server.client, PID) + expect(snap.seq).toBe(3) + expect(snap.state).toEqual(bytes) + + const ups = await fetchUpdates(server.client, PID) + expect(ups).toEqual([{ id: 7, bytes: new Uint8Array([9, 8]) }]) + }) +})