@pgxsinkit/client 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,129 +3,122 @@ name: operating
3
3
  description: >-
4
4
  Load when deploying or operating a live pgxsinkit app, when diagnosing a sync/write that "feels slow"
5
5
  in a browser even though the server is fast, or when wiring backups/export/restore. Covers the runtime
6
- and deployment properties (not toolkit bugs) that decide whether a live app feels fast: convergence
7
- cadence (writes flush on enqueue; the interval is only a fallback), serverless edge cold starts and
8
- warming, cache-control:no-store on a same-origin Electric shape proxy, the browser HTTP/2 connection
9
- budget, the edge worker timeout vs Electric's long-poll, globalThis.__pgxsinkitDebug + the BootReport,
10
- worker mode (defineSyncWorker/attachSyncClient — capability-driven Safari SharedWorker vs elected
11
- Chromium/Firefox engine placement, factories, relocation outcomes, diagnostics, and the forwarded rail),
12
- and the store lifecycle surface: storePath naming, backend-specific durability, backend permanence,
13
- supervised destruction, exportStore/exportDiagnostics/exportData (+ drain guard), and restoreFrom.
6
+ and deployment properties (not toolkit bugs) that decide whether an app feels fast: convergence cadence
7
+ (writes flush on enqueue; the interval is a fallback), serverless edge cold starts and warming,
8
+ cache-control:no-store on a same-origin shape proxy, the browser HTTP/2 connection budget, the edge
9
+ worker timeout vs Electric's long-poll, globalThis.__pgxsinkitDebug + the BootReport, worker mode
10
+ (defineSyncWorker/attachSyncClient — capability-driven engine placement, factories, relocation outcomes,
11
+ the forwarded rail), the store lifecycle surface (storePath naming, durability, backend permanence,
12
+ supervised destruction, the three exports, restoreFrom), and Event-lane
13
+ observability: onOutboxStatus, onEventLaneReport verdicts including deferred-on-skew, and the Outbox in
14
+ destroy/restore/backup/dropReadCache.
14
15
  metadata:
15
16
  type: task
16
17
  library: "@pgxsinkit/client"
17
- library_version: "0.2.5"
18
+ library_version: "0.2.7"
18
19
  source: https://pgxsinkit.github.io/start/operating-in-production/
19
20
  ---
20
21
 
21
22
  # Operating a pgxsinkit app in production
22
23
 
23
24
  The read/write/converge primitives are fast. When a live app feels slow it is almost always one of the
24
- properties below — none are toolkit bugs; they are how serverless edges, browser HTTP, and CDN-shaped
25
- caching behave. If writes or sync feel slow in a real browser but server benchmarks are fast, start here.
25
+ properties below — none are toolkit bugs; they are how serverless edges, browser HTTP and CDN-shaped caching
26
+ behave. If writes or sync feel slow in a real browser but server benchmarks are fast, start here.
26
27
 
27
28
  ## Convergence cadence: event-driven, interval is a fallback
28
29
 
29
- When you pass an `autoSync` trigger to `createSyncClient`, the client drives `flush → reconcile`. The
30
- pass is **event-driven**: the client calls `requestPass()` the moment a mutation is enqueued, so a local
31
- write flushes to the server immediately — it does **not** wait for the interval. The interval
32
- (`createBrowserConvergenceTrigger({ intervalMs })`, default 1.5s; in worker mode `defineSyncWorker`'s
33
- `convergenceIntervalMs`, default 15s) is only a fallback for retries/recovery/cross-tab.
30
+ With an `autoSync` trigger, the client drives `flush → reconcile` **event-driven**: it calls `requestPass()`
31
+ the moment a mutation is enqueued, so a local write flushes immediately and does **not** wait for the
32
+ interval (`createBrowserConvergenceTrigger({ intervalMs })`, default 1.5s; in worker mode
33
+ `defineSyncWorker`'s `convergenceIntervalMs`, default 15s), which is only a fallback for
34
+ retries/recovery/cross-tab.
34
35
 
35
36
  Therefore **keep the interval long.** A short interval is the dominant idle cost: every PGlite query is
36
37
  ~50ms of WASM work on one thread, and an unconditional reconcile each tick re-runs every live query. The
37
- demo uses `intervalMs: 15_000`, cutting idle CPU from ~70% of a core to ~2% with **no change to
38
- convergence latency** (latency is bounded by the Electric echo, not the interval). Do **not** shorten
39
- the interval to "make writes faster" — it does nothing and burns CPU.
38
+ demo uses `intervalMs: 15_000`, cutting idle CPU from ~70% of a core to ~2% with **no change to convergence
39
+ latency** (latency is bounded by the Electric echo). Do **not** shorten it to "make writes faster".
40
40
 
41
41
  ## Serve the gateway over HTTP/2 (the connection budget)
42
42
 
43
- Electric's client holds **one live long-poll connection open per synced shape**. A client subscribing to
44
- six shapes keeps six connections busy, and browsers cap **HTTP/1.1 at ~6 connections per origin** — so
45
- over plain HTTP those long-polls consume every slot and the **write** request (same origin) is
46
- **Stalled in the browser's connection queue** for a whole long-poll cycle before it is even dispatched.
47
- This presents as multi-second writes that are invisible to `curl`/Node (which have no per-host cap) —
48
- only a real browser shows it (DevTools → Network → a stuck `write` with a long **Stalled** time).
49
-
50
- Fix: serve the gateway over **HTTP/2** (or HTTP/3), which multiplexes every request over one connection.
51
- Any production ingress already does (Cloud Supabase, Electric Cloud, istio/Envoy, a TLS reverse proxy);
52
- it only bites a local stack on plain `http://` (browsers only negotiate HTTP/2 over TLS).
43
+ Electric's client holds **one live long-poll connection open per synced shape**, and browsers cap
44
+ **HTTP/1.1 at ~6 connections per origin** — so over plain HTTP six shapes' long-polls consume every slot and
45
+ the same-origin **write** request is **Stalled in the browser's connection queue** for a whole long-poll
46
+ cycle before it is even dispatched. This presents as multi-second writes invisible to `curl`/Node (no
47
+ per-host cap); only a real browser shows it (DevTools → Network → a stuck `write` with a long **Stalled**
48
+ time). Fix: serve the gateway over **HTTP/2** (or HTTP/3), which multiplexes every request over one
49
+ connection. Any production ingress already does; it only bites a local stack on plain `http://` (browsers
50
+ only negotiate HTTP/2 over TLS).
53
51
 
54
52
  ## Serverless edge cold starts
55
53
 
56
54
  On a serverless edge a worker is suspended when idle and evicted after longer idle, so the **first write
57
- after a quiet period** pays a cold start while steady-state writes are instant (measured: ~20ms warm,
58
- ~0.45s after ~15s idle, ~5.8s on a cold module cache). This is a property of the deployment target, not
59
- pgxsinkit — a long-lived Bun/Deno process or a managed warm pool has none. Mitigate: keep the worker warm
60
- with a periodic cheap request (an empty `{"mutations":[]}` POST, rejected at validation before any DB
61
- work), and set the worker wall-clock timeout **above** Electric's ~25s long-poll so a live subscription
62
- is not recycled mid-cycle.
63
-
64
- Region-pin **only the DB-bound write function**, not read proxies. Pinning the write function's execution
65
- to the database's region (Supabase `x-region`) keeps its chatty function→DB protocol on a ~1ms loop; a
66
- read proxy's upstream is Electric Cloud's global CDN, so pinning reads away from a distant caller instead
67
- **adds** intercontinental hops per catch-up (~1.2s vs ~300ms). `createSyncClient` splits this cleanly:
68
- `requestHeaders` is the shared base (sent on reads AND writes — e.g. a gateway `apikey`), and
69
- `writeRequestHeaders` is merged over it on the write path only. Put the region header in
70
- `writeRequestHeaders`; never in the shared `requestHeaders`, which reads also send.
55
+ after a quiet period** pays a cold start while steady-state writes are instant (measured: ~20ms warm, ~0.45s
56
+ after ~15s idle, ~5.8s on a cold module cache). That is the deployment target, not pgxsinkit — a long-lived
57
+ Bun/Deno process or a managed warm pool has none. Mitigate: keep the worker warm with a periodic cheap
58
+ request (an empty `{"mutations":[]}` POST, rejected at validation before any DB work), and set the worker
59
+ wall-clock timeout **above** Electric's ~25s long-poll so a live subscription is not recycled mid-cycle.
60
+
61
+ Region-pin **only the DB-bound write function**, not read proxies. Pinning it to the database's region
62
+ (Supabase `x-region`) keeps its chatty function→DB protocol on a ~1ms loop; a read proxy's upstream is
63
+ Electric Cloud's global CDN, so pinning reads away from a distant caller instead **adds** intercontinental
64
+ hops per catch-up (~1.2s vs ~300ms). `createSyncClient` splits this: `requestHeaders` is the shared base
65
+ (reads AND writes — e.g. a gateway `apikey`), `writeRequestHeaders` is merged over it on the write path
66
+ only. Put the region header in `writeRequestHeaders`, never in the shared `requestHeaders`.
71
67
 
72
68
  ## Pre-warming PGlite's boot assets
73
69
 
74
70
  A cold `PGlite.create` spends ~2.5s fetching + compiling the Postgres WASM (plus the initdb WASM and the
75
- filesystem bundle) before it can open a store — otherwise paid **after** sign-in, on the path to first
76
- paint. `createSyncClient` takes a `pgliteBootAssets` option: a promise of the already-fetched/compiled
77
- assets (`{ pgliteWasmModule?, initdbWasmModule?, fsBundle? }`), awaited and passed straight into
78
- `PGlite.create` so it skips its own lazy load. Start the fetch+compile on an **earlier screen** (a login /
79
- identity picker) and hand the pending promise in — the WASM cost then hides behind user think-time. It is
80
- best-effort: a rejected warm is caught to `undefined` and PGlite loads its own assets, so the warm never
81
- fails the boot. The `boot pglite assets warm` rail stamp times it. (Board demo: `apps/board/src/board/
82
- pglite-warm.ts` shows the Vite `?url` asset-URL pattern PGlite's `exports` field otherwise blocks.)
71
+ filesystem bundle) before it can open a store — otherwise paid **after** sign-in, on the path to first paint.
72
+ `createSyncClient` takes a `pgliteBootAssets` option: a promise of the already-fetched/compiled assets
73
+ (`{ pgliteWasmModule?, initdbWasmModule?, fsBundle? }`), awaited and passed straight into `PGlite.create` so
74
+ it skips its own lazy load. Start the fetch+compile on an **earlier screen** and hand the pending promise in
75
+ — the WASM cost then hides behind user think-time. It is best-effort: a rejected warm is caught to
76
+ `undefined` and PGlite loads its own assets. The `boot pglite assets warm` rail stamp times it. (Board demo:
77
+ `apps/board/src/board/pglite-warm.ts` shows the Vite `?url` pattern PGlite's `exports` field otherwise blocks.)
83
78
 
84
79
  **In worker mode the engine loads PGlite's OWN assets — deliberately; do not pre-supply them.** The tab's
85
- warm still serves the engine, by priming the same-origin HTTP cache the worker fetches from. Handing the
80
+ warm still serves the engine by priming the same-origin HTTP cache the worker fetches from. Handing the
86
81
  engine a pre-compiled `WebAssembly.Module` benched NET-NEGATIVE: it forces compile-to-completion before
87
- instantiate (forfeiting the pipelining PGlite gets from its own streaming load) and the engine realm has no
88
- overlap window longer than the placement/handshake gap, so the compile only competes for CPU at spawn.
82
+ instantiate (forfeiting PGlite's streaming-load pipelining), and the engine realm's only overlap window is
83
+ the placement/handshake gap, so the compile just competes for CPU at spawn.
89
84
 
90
85
  Pre-warming only hides the WASM fetch+compile; `PGlite.create` still spends ~1.9s on `initdb` + store open,
91
- and that can't start until the store id is known (usually the signed-in user). To hide it too, create the
86
+ which can't start until the store id is known (usually the signed-in user). To hide that too, create the
92
87
  store EAGERLY under a generated id on the first screen and BIND it at auth. `createClientPGlite(storePath,
93
- { bootAssets })` runs the exact same create the client does internally (electric + live extensions, warm
94
- consumption, the `boot pglite.create` stamp) and returns a schemaless instance; hand the still-pending
95
- promise to `createSyncClient`'s `precreatedPglite` option. Unlike `pgliteInstance` (caller owns schema),
96
- `precreatedPglite` lets the client still run schema exec, prepare hooks, journal recovery and store-version
97
- reconcile — so the eager create buys only `initdb`, and the role/registry-derived schema stays post-auth. A
98
- rejected `precreatedPglite` is caught and falls back to the `storePath` create path (which also consumes
99
- `pgliteBootAssets`), so it is a pure accelerator, never a boot dependency. Bind eager stores to users with a
100
- small localStorage registry (userId→storeId plus one unbound "spare"): create a spare on the login screen,
101
- claim it at sign-in, and GC any store that is neither mapped nor the spare. On a signed-in RELOAD there is
102
- no login screen to create ahead of, so START the mapped-store open at app bootstrap (before React render),
103
- memoised per userId so the provider's later open adopts it rather than opening a second instance. (Board
104
- demo: `apps/board/src/board/store-registry.ts`, `store-prewarm.ts`.)
88
+ { bootAssets })` runs the exact same create the client does internally and returns a schemaless instance;
89
+ hand the still-pending promise to `createSyncClient`'s `precreatedPglite`. Unlike `pgliteInstance` (caller
90
+ owns schema), `precreatedPglite` lets the client still run schema exec, prepare hooks, journal recovery and
91
+ store-version reconcile — so the eager create buys only `initdb`, and the role/registry-derived schema stays
92
+ post-auth. A rejected `precreatedPglite` falls back to the `storePath` create path, so it is a pure
93
+ accelerator, never a boot dependency. Bind eager stores to users with a small localStorage registry
94
+ (userId→storeId plus one unbound "spare"): create a spare on the login screen, claim it at sign-in, GC any
95
+ store that is neither mapped nor the spare. On a signed-in RELOAD there is no login screen to create ahead of,
96
+ so START the mapped-store open at app bootstrap (before React render), memoised per userId so the provider's
97
+ later open adopts it. (Board demo: `store-registry.ts`, `store-prewarm.ts`.)
105
98
 
106
99
  ## Worker mode: capability-placed off-thread engine (browser apps)
107
100
 
108
- In a browser, prefer worker mode so PGlite, shape streams, journal machinery, and convergence leave the
109
- main thread. The SharedWorker is always the communication centre. There is no placement option: where the
110
- engine runs is a runtime capability decision. Under the default `storage.backend: "opfs"`, an
111
- unconditional real synchronous-handle open at boot chooses the engine home: real macOS/iOS Safari
112
- runs the OPFS-repacked engine directly in the SharedWorker; Chromium/Firefox elect one tab-spawned
113
- dedicated engine worker through Web Locks. Playwright WebKitGTK denies the handle in both worker kinds and
114
- exercises the capability fallback to idb (declared durability kept, `storageBackend: "idbfs"` +
115
- `storageFallbackReason` on the BootReport). The one opt-out is `storage.backend: "idbfs"` on the registry:
116
- no probe, no election, the engine boots in the SharedWorker on idb. `createSyncClient` remains the bun/Node
117
- mode and the main-thread idb fallback where SharedWorker is missing.
101
+ In a browser, prefer worker mode so PGlite, shape streams, journal machinery, and convergence leave the main
102
+ thread. The SharedWorker is always the communication centre. There is no placement option: where the engine
103
+ runs is a runtime capability decision. Under the default `storage.backend: "opfs"`, an unconditional real
104
+ synchronous-handle open at boot chooses the engine home — real macOS/iOS Safari runs the OPFS-repacked engine
105
+ directly in the SharedWorker, Chromium/Firefox elect one tab-spawned dedicated engine worker through Web
106
+ Locks, and Playwright WebKitGTK denies the handle in both worker kinds, exercising the capability fallback to
107
+ idb (declared durability kept, `storageBackend: "idbfs"` + `storageFallbackReason` on the BootReport). The
108
+ one opt-out is `storage.backend: "idbfs"` on the registry: no probe, no election, the engine boots in the
109
+ SharedWorker on idb. `createSyncClient` remains the bun/Node mode and the main-thread idb fallback where
110
+ SharedWorker is missing.
118
111
 
119
112
  **A home with NO grant refuses a store already committed to OPFS.** A boot whose home holds no sync-access
120
113
  grant (a tab realm, the in-process fallback) over a store whose meta record says `opfs-committed` fails
121
- CLOSED with `CommittedStoreUnreachableError` — it cannot open that store, and `idb://<storePath>` would be an
122
- EMPTY sibling (app looks wiped, offline writes fork into a store no worker-mode boot opens). No override
123
- flag; the message names both exits — boot from a granted home, or destroy first with
124
- `destroyStoreArtifacts(storePath)`, the path-addressed destroy (the failed boot leaves you no client to call
125
- `destroy()` on) that deletes both backends plus the sentinel and the meta record and needs no grant; quiesce
126
- any live worker for the path first (`quiesceStoreWorker`). The error is `instanceof`-branchable on the tab
127
- side in worker mode too (it crosses the bridge as its class) and carries the refused `storePath`. A no-grant
128
- `provision` declines that store for the same reason rather than pre-minting the sibling.
114
+ CLOSED with `CommittedStoreUnreachableError`, because `idb://<storePath>` would be an EMPTY sibling (app
115
+ looks wiped, offline writes fork into a store no worker-mode boot opens). No override flag; the message names
116
+ both exits — boot from a granted home, or destroy first with `destroyStoreArtifacts(storePath)`, the
117
+ path-addressed destroy (a failed boot leaves you no client to call `destroy()` on) that deletes both backends
118
+ plus the sentinel and the meta record and needs no grant, quiescing any live worker for the path first
119
+ (`quiesceStoreWorker`). The error is `instanceof`-branchable on the tab side too (it crosses the bridge as
120
+ its class) and carries the refused `storePath`; a no-grant `provision` declines that store for the same
121
+ reason rather than pre-minting the sibling.
129
122
 
130
123
  **Two-file pattern.** One worker entry, bundled for both SharedWorker and dedicated Worker, calls
131
124
  `defineSyncWorker({ registry, electricUrl, batchWriteUrl, … })` at module top level — no placement or
@@ -133,172 +126,155 @@ durability option (both are runtime/registry concerns); the registry is CODE, _i
133
126
  file, never cloned/serialized in. Give each store a stable SharedWorker name and always pass
134
127
  `extendedLifetime: true` (Chromium 148+ grace period; ignore-safe elsewhere). The tab calls
135
128
  `attachSyncClient({ worker, registry, getToken })`. Prefer the **factory** form (`worker: () => SharedWorker`)
136
- over a bare instance or a raw `port` (`SharedWorker.port`) — a SharedWorker cannot be reconstructed from
137
- itself, so **in elected placement** (Chromium/Firefox) the factory is what arms SharedWorker(router)-death
138
- recovery: the election coordinator's keepalive reconstructs the router through it. A `port`/instance input
139
- stays fully functional — provision, attach, and the provision→attach handoff all work (the handoff is keyed
140
- by `storePath`, not the transport) — but **forfeits that reconstruction** (the coordinator detects the death
141
- and can only stop). In SW-direct placement (Safari/idbfs) the engine lives in the SharedWorker and there is
142
- no keepalive; neither form auto-recovers a dead SharedWorker (opt into `bridgeSilenceMs` + a factory for a
143
- bridge-silence reconnect there). The elected engine worker needs no
144
- consumer wiring: the SharedWorker reports its own script URL and the winning tab constructs the engine as
145
- `new Worker(reportedUrl, { type: "module" })`. Supply `createEngineWorker` ONLY as an override for entries
146
- that cannot be reconstructed from their URL as a module worker (classic-script workers, `blob:`/`data:`
147
- URLs, CSP); with no override and no derivable URL, attach fails with a typed error — never a silent
148
- no-engine attach. The attached facade returns the same
149
- client shape as `createSyncClient` (write API, one-shot Drizzle reads, live rows,
150
- `ready`/`status`/`stop`) plus `notifyAuthChanged` and `setOnline`, proxied to the shared engine. One-shot
151
- reads (`query`/`queryRow`/`queryRaw`/`queryRawRow`) compile on the tab and cross the bridge as ONE guarded
152
- round trip — the worker runs the read gate + lazy-group guard, then Drizzle's own mapping runs back on the
153
- tab, so results match the in-process client exactly. A bare awaited `client.drizzle` builder is ALSO
154
- guarded here (the in-process unguarded escape hatch has no attach equivalent), and
155
- `client.drizzle.transaction()` throws (no tab-local store). `ensureSynced` is proxied (additive,
156
- idempotent); `isSynced` throws — it is a SYNCHRONOUS activation-started peek the tab's cached catch-up
157
- readiness cannot answer (use `groupReady` for catch-up, `ensureSynced` to activate). Local
158
- `pglite` and `dropReadCache` are NOT proxied — there is no tab-local store and a cache rebuild is
159
- engine-wide. `destroy()` IS proxied through a tab-side supervisor: it refuses peers with
160
- `StoreDestroyRefusedError`, refuses owed journal rows unless `{ force: true }`, retires/closes the engine,
161
- then runs a resumable deletion. The lazy lifecycle methods ARE proxied, but the engine is SHARED:
162
- `desync(tableKey)` from one tab reverts the consistency group for EVERY attached tab (desync's group-wide
163
- revert is engine-wide here — the footgun). For an ephemeral delivery window use `discardEphemeral(tableKey)`
164
- instead — the scoped, multi-tab-safe finalize (drops the ephemeral rows, reverts to dormant, refuses a
165
- group with any persistent member); safe under a shared engine because an ephemeral window is
166
- per-delivery-session and single-consumer. The exception is the INSPECTION surface `rawQuery(sql, params)` /
167
- `rawExec(sql)` (debug pages, REPLs, ad-hoc counts): identical on both clients (executed in the worker on the
168
- attach client), it runs raw against the local store — bypasses the journal/overlay, any write stays local
169
- and never converges — so it is not an app-data read path. `replAdapter(client)` shapes it into the
170
- `{ query, exec }` duck `@electric-sql/pglite-repl` needs (`client.pglite` stays unavailable). A worker file can bake multiple role variants and pick per attach via
171
- `resolveRegistry(role)` + the tab's `role` (the board's admin/member registries; the spare needs it). The
172
- worker entry can also pass the app-level schema prepare hooks `prepareLocalDbBeforeSchema` / `prepareLocalDbAfterSchema`
173
- (app migrations, indexes, views) — same semantics as in-process, run in the worker around the registry schema
174
- exec; they are worker-entry (not attach) options because a hook is a function and cannot cross the bridge.
175
-
176
- **Identity switches do not wait for worker retirement.** Scope each worker identity by `storePath`; use a distinct,
177
- stable SharedWorker name for each store. Multiple stores may remain alive concurrently. Detach/stop the old
178
- client and immediately attach the new identity's worker/store — never wait for the old SharedWorker, elected
179
- engine, provision expiry, or `extendedLifetime` grace period. In worker mode `stop()` detaches only this tab;
180
- in-process mode it disposes live queries before closing that client's engine and store. The board's
181
- `userId → storeId` registry and real-browser identity-switch lane demonstrate this guarantee.
129
+ over a bare instance or a raw `port` — a SharedWorker cannot be reconstructed from itself, so **in elected
130
+ placement** (Chromium/Firefox) the factory is what arms SharedWorker(router)-death recovery via the election
131
+ coordinator's keepalive. A `port`/instance input stays fully functional (provision, attach, and the
132
+ `storePath`-keyed handoff all work) but **forfeits that reconstruction** — the coordinator detects the death
133
+ and can only stop. In SW-direct placement (Safari/idbfs) the engine lives in the SharedWorker and there is no
134
+ keepalive; neither form auto-recovers a dead SharedWorker (opt into `bridgeSilenceMs` + a factory for a
135
+ bridge-silence reconnect there). The elected engine worker needs no consumer wiring: the SharedWorker reports
136
+ its own script URL and the winning tab constructs `new Worker(reportedUrl, { type: "module" })`. Supply
137
+ `createEngineWorker` ONLY for entries that cannot be reconstructed from their URL as a module worker
138
+ (classic-script workers, `blob:`/`data:` URLs, CSP); with no override and no derivable URL, attach fails with
139
+ a typed error — never a silent no-engine attach.
140
+
141
+ The attached facade returns the same client shape as `createSyncClient` (write API, one-shot Drizzle reads,
142
+ live rows, `ready`/`status`/`stop`) plus `notifyAuthChanged` and `setOnline`, proxied to the shared engine.
143
+ One-shot reads (`query`/`queryRow`/`queryRaw`/`queryRawRow`) compile on the tab and cross the bridge as ONE
144
+ guarded round trip — the worker runs the read gate + lazy-group guard, then Drizzle's own mapping runs back
145
+ on the tab, so results match the in-process client exactly. A bare awaited `client.drizzle` builder is ALSO
146
+ guarded here, and `client.drizzle.transaction()` throws (no tab-local store). `ensureSynced` is proxied
147
+ (additive, idempotent); `isSynced` throws — it is a SYNCHRONOUS activation-started peek the tab's cached
148
+ catch-up readiness cannot answer (use `groupReady` for catch-up, `ensureSynced` to activate). Local `pglite`
149
+ and `dropReadCache` are NOT proxied (no tab-local store; a cache rebuild is engine-wide). `destroy()` IS
150
+ proxied through a tab-side supervisor: it refuses peers with `StoreDestroyRefusedError`, refuses owed journal
151
+ rows unless `{ force: true }`, retires/closes the engine, then runs a resumable deletion. The lazy lifecycle
152
+ methods ARE proxied, but the engine is SHARED: `desync(tableKey)` from one tab reverts the consistency group
153
+ for EVERY attached tab (the footgun). For an ephemeral delivery window use `discardEphemeral(tableKey)`
154
+ instead — the scoped, multi-tab-safe finalize (drops the ephemeral rows, reverts to dormant, refuses a group
155
+ with any persistent member), safe under a shared engine because an ephemeral window is per-delivery-session
156
+ and single-consumer. The exception is the INSPECTION surface `rawQuery(sql, params)` / `rawExec(sql)` (debug
157
+ pages, REPLs, ad-hoc counts): identical on both clients (executed in the worker on the attach client), it
158
+ runs raw against the local store — bypassing the journal/overlay, any write staying local and never
159
+ converging — so it is not an app-data read path. `replAdapter(client)` shapes it into the `{ query, exec }`
160
+ duck `@electric-sql/pglite-repl` needs. A worker file can bake multiple role variants and pick per attach via
161
+ `resolveRegistry(role)` + the tab's `role`, and can pass the schema prepare hooks
162
+ `prepareLocalDbBeforeSchema` / `prepareLocalDbAfterSchema` (app migrations, indexes, views) — worker-entry,
163
+ not attach, options, because a hook is a function and cannot cross the bridge.
164
+
165
+ **Identity switches do not wait for worker retirement.** Scope each worker identity by `storePath` with a
166
+ distinct, stable SharedWorker name; multiple stores may remain alive concurrently. Detach/stop the old client
167
+ and immediately attach the new identity's worker/store — never wait for the old SharedWorker, elected engine,
168
+ provision expiry, or `extendedLifetime` grace. In worker mode `stop()` detaches only this tab; in-process it
169
+ disposes live queries before closing that client's engine and store.
182
170
 
183
171
  **Auth stays tab-owned (ADR-0013).** The tab pushes `{accessToken, expiresAt}` at attach and on
184
- `notifyAuthChanged`; the worker uses the cached token and sends a pull-request only when a request finds it
185
- near expiry (any tab answers via `getToken`, first wins). The worker NEVER refreshes — exactly one refresher,
186
- so GoTrue refresh-token reuse detection can't be tripped by a second client.
172
+ `notifyAuthChanged`; the worker uses the cached token and pull-requests one only when a request finds it near
173
+ expiry (any tab answers via `getToken`, first wins). The worker NEVER refreshes — exactly one refresher, so
174
+ GoTrue refresh-token reuse detection can't be tripped by a second client.
187
175
 
188
176
  **Boot: spare-as-worker + internal prefetch overlap.** The spare store (see above) becomes a pre-spawned
189
177
  schemaless worker at the login screen (create + initdb off every thread that matters); the userId→storeId
190
178
  registry stays tab-side in localStorage so binding resolves before attach (SharedWorker naming needs it).
191
- Call `provisionSyncWorker` with the same `worker` input as attach (the factory form, so elected-mode recovery is armed for provisioning too); an elected
192
- Chromium/Firefox pre-open shares the tab's one election coordinator and auto-derives the engine from the
193
- SharedWorker's own script URL (override with `createEngineWorker` only for non-module/underivable entries).
194
- `provisionExpiryMs` (default 60000) is ONE deadline: it retires the abandoned elected claim AND settles the
195
- returned promise with the typed `ProvisionExpiredError` in both modes, so a provision behind a dead
196
- SharedWorker connection fails loudly rather than hanging. It bounds YOUR promise; the worker-side create
197
- attempt follows the placement. SW-direct: the attempt is left running — a later attach adopts that create if it
198
- completed and waits on it if it is stuck, and a retried provision re-acks the same attempt rather than starting
199
- a second open. Elected: the deadline also releases the provision claim, and a LAST-claim release retires and
200
- terminates the engine with that attempt inside it, so the next attach elects a fresh engine (an attach that
201
- adopted the coordinator earlier keeps its claim, and with it that engine).
202
- Fire-and-forget callers should `.catch()` it like any un-awaited promise.
203
- Claim = bind id, attach, push config + token. On a PROVABLY-fresh claimed store, pass
204
- `attachSyncClient({ freshStore: true })` (never for a mapped/returning store) and the worker overlaps the
205
- shape catch-up with schema/journal/store-version recovery — far-user boot bounded by `max(create+schema,
206
- catch-up)`, not their sum. New boot-rail stamps: `boot spare store ensured`, `boot mapped store prewarm`,
207
- `boot store claimed`, `boot shape prefetch start`, `boot commits opened`.
179
+ Call `provisionSyncWorker` with the same `worker` input as attach (the factory form, so elected-mode recovery
180
+ is armed for provisioning too); an elected pre-open shares the tab's one election coordinator and derives the
181
+ engine from the SharedWorker's own script URL. `provisionExpiryMs` (default 60000) is ONE deadline: it
182
+ retires the abandoned elected claim AND settles the returned promise with the typed `ProvisionExpiredError`
183
+ in both modes, so a provision behind a dead SharedWorker connection fails loudly rather than hanging. It
184
+ bounds YOUR promise; the worker-side create attempt follows the placement. SW-direct: the attempt is left
185
+ running — a later attach adopts it if it completed and waits on it if it is stuck, and a retried provision
186
+ re-acks the same attempt rather than opening a second. Elected: the deadline also releases the provision
187
+ claim, and a LAST-claim release retires and terminates the engine with that attempt inside it, so the next
188
+ attach elects a fresh one (an attach that adopted the coordinator earlier keeps its claim, and that engine).
189
+ Fire-and-forget callers should `.catch()` it like any un-awaited promise. Claim = bind id, attach, push
190
+ config + token. On a PROVABLY-fresh claimed store pass `attachSyncClient({ freshStore: true })` (never for a
191
+ mapped/returning store) and the worker overlaps the shape catch-up with schema/journal/store-version
192
+ recovery — far-user boot bounded by `max(create+schema, catch-up)`, not their sum. Boot-rail stamps: `boot
193
+ spare store ensured`, `boot mapped store prewarm`, `boot store claimed`, `boot shape prefetch start`,
194
+ `boot commits opened`.
208
195
 
209
196
  **`ready` unchanged; per-group readiness exposed.** `client.ready` still gates on every eager group; for
210
- progressive paint use `await client.groupReady(tableKey)` or read `status.groups` — no contract change.
197
+ progressive paint use `await client.groupReady(tableKey)` or read `status.groups`.
211
198
 
212
- **Debug rail is forwarded and origin-tagged.** A SharedWorker's own console is invisible to the page (only
199
+ **Debug rail is forwarded and origin-tagged.** A SharedWorker's console is invisible to the page (only
213
200
  `chrome://inspect`), so the worker forwards every rail line to each tab, stamped with the WORKER's monotonic
214
- clock and re-printed as `[pgxsinkit·w <ms>ms] …`, gated by that tab's own `globalThis.__pgxsinkitDebug`. Set
215
- the flag on the TAB as usual; the write/read/boot phases below read the same, just origin-tagged. The front
216
- half of boot runs on the FIRST attach before any tab is listening, so the worker buffers those pre-attach
217
- rail lines in a bounded ring (last 500) and replays them `[replay]`-marked to the first attaching tab (so
218
- the boot's opening phases reach it too, ADR-0034). The worker's NETWORK traffic is invisible the same way:
219
- shape requests never appear in the page's Network panel — "rail shows `shape request start`, Network tab
220
- shows nothing" is worker mode working as designed, not an absence of requests. Inspect the worker itself
221
- (`chrome://inspect/#workers` → inspect) for the real requests, status codes, and errors (e.g. CORS
222
- rejections surface only there). Full model:
223
- <https://pgxsinkit.github.io/concepts/worker-mode/>.
201
+ clock and re-printed as `[pgxsinkit·w <ms>ms] …`, gated by that tab's own `globalThis.__pgxsinkitDebug`. The
202
+ front half of boot runs on the FIRST attach before any tab is listening, so the worker buffers those
203
+ pre-attach lines in a bounded ring (last 500) and replays them `[replay]`-marked to the first attaching tab.
204
+ The worker's NETWORK traffic is invisible the same way: shape requests never appear in the page's Network
205
+ panel — "rail shows `shape request start`, Network tab shows nothing" is worker mode working as designed.
206
+ Inspect the worker itself (`chrome://inspect/#workers`) for the real requests, status codes, and errors (CORS
207
+ rejections surface only there). Full model: <https://pgxsinkit.github.io/concepts/worker-mode/>.
224
208
 
225
209
  **Placement and relocation diagnostics.** Pull `client.bootReport()` and inspect `storageBackend`
226
- (`opfs-repacked`/`idbfs`/`filesystem`/`memory`), `engineHome`
227
- (`shared-worker`/`elected-worker`/`in-process`), and `storageFallbackReason`; never user-agent-sniff the
228
- backend. During elected-engine handoff, `EngineRelocatedError("not-dispatched")` is safe to retry, while
229
- `"unknown"` means a dispatched mutation may already be journaled — inspect/reconcile, never retry blindly.
230
- The opt-in `executionLimit` is disabled by default — no finite worst-case query duration exists and the
231
- limit converts slow to terminated by policy, so enabling it must be a deliberate choice. It is
232
- elected-only, and must match between the worker entry and every tab (`ExecutionLimitMismatchError`
233
- otherwise); SW-direct Safari rejects it as unsupported.
210
+ (`opfs-repacked`/`idbfs`/`filesystem`/`memory`), `engineHome` (`shared-worker`/`elected-worker`/
211
+ `in-process`) and `storageFallbackReason`; never user-agent-sniff the backend. During elected-engine handoff
212
+ `EngineRelocatedError("not-dispatched")` is safe to retry, while `"unknown"` means a dispatched mutation may
213
+ already be journaled — inspect/reconcile, never retry blindly. The opt-in `executionLimit` is disabled by
214
+ default (no finite worst-case query duration exists, and the limit converts slow to terminated by policy);
215
+ it is elected-only and must match between the worker entry and every tab
216
+ (`ExecutionLimitMismatchError`), and SW-direct Safari rejects it as unsupported.
234
217
 
235
218
  ## Live-query manager: dedup + keep-alive (ADR-0040)
236
219
 
237
220
  Every reactive read (`useLiveDrizzleRows`/`useLiveQueryRaw`/`subscribeLiveRows`) is a **local SQL live
238
221
  query**: PGlite materialises it once, then re-runs + diffs it on every write to its tables. That registration
239
- is a real cost — ~a few hundred ms to materialise a heavy aggregate — and is **automatically deduplicated**:
240
- identical queries (keyed on executed SQL + bound params, NOT `use`) share ONE registration and ONE re-run +
241
- diff per write, fanned to every subscriber. So N components — or N tabs on the shared worker — on the same
242
- query cost one materialisation, not N. You do nothing to get this.
222
+ is a real cost (~a few hundred ms for a heavy aggregate) and is **automatically deduplicated** — identical
223
+ queries (keyed on executed SQL + bound params, NOT `use`) share ONE registration and ONE re-run + diff per
224
+ write, fanned to every subscriber, so N components (or N tabs on the shared worker) cost one materialisation.
243
225
 
244
226
  Default lifetime is route-scoped: a live query is torn down the instant its last consumer unmounts, so a
245
227
  navigate-away-and-back RE-materialises it. Opt a genuinely hot query into a grace period with a per-hook hint
246
- `useLiveDrizzleRows(build, deps, { keepAliveMs: 30_000 })` (or the raw-hook / `subscribeLiveRows` field), or
247
- set a worker/client-wide policy `defineSyncWorker({ …, liveQueries: { defaultKeepAliveMs, maxRetainedQueries,
248
- maxRetainedRows } })` (defaults `0` / `16` / `50_000`; same block on `createSyncClient`). The effective
249
- keep-alive is `max(default, subscribers' hints)`; the count/row budgets are authoritative over any hint and
250
- LRU-evict zero-subscriber entries past them; active (still-subscribed) entries are never evicted.
251
-
252
- **Keep the default 0 unless you have a specific hot query.** A retained zero-subscriber query is NOT paused —
253
- PGlite live queries can't be — so it still pays a full re-run + diff on every write to its tables for as long
254
- as it's held. Retention wins only for a frequently-re-mounted, write-COLD query; for a write-hot one it costs
255
- more idle than the one re-materialisation it saves. For a fixed hot set, the endorsed "permanent" pattern is a
256
- **mounted subscriber** (a root-provider hook that never unmounts) — one live registration for the app's life,
257
- every route dedups onto it — not a retention setting; there is deliberately no retain-forever knob.
228
+ `useLiveDrizzleRows(build, deps, { keepAliveMs: 30_000 })` (same field on the raw hook and
229
+ `subscribeLiveRows`), or a worker/client-wide policy `defineSyncWorker({ …, liveQueries: {
230
+ defaultKeepAliveMs, maxRetainedQueries, maxRetainedRows } })` (defaults `0` / `16` / `50_000`; the same block
231
+ exists on `createSyncClient`). The effective keep-alive is `max(default, subscribers' hints)`; the count/row
232
+ budgets outrank any hint and LRU-evict zero-subscriber entries; active entries are never evicted.
233
+
234
+ **Keep the default 0 unless you have a specific hot query.** A retained zero-subscriber query is NOT paused
235
+ (PGlite live queries can't be), so it still pays a full re-run + diff on every write to its tables while
236
+ held: retention wins only for a frequently-re-mounted, write-COLD query. For a fixed hot set the endorsed
237
+ "permanent" pattern is a **mounted subscriber** (a root-provider hook that never unmounts) — one live
238
+ registration for the app's life, every route dedups onto it; there is deliberately no retain-forever knob.
258
239
 
259
240
  `client.liveQueryDiagnostics()` returns a per-entry snapshot — fingerprint DIGEST (never SQL/params/rows),
260
- subscriber + row counts, setup/refresh timings, retention state — safe to log. The manager also emits
261
- `live-query register|dedup-hit|retained|evicted|teardown-complete` lines on the debug rail (digests only).
241
+ subscriber + row counts, timings, retention state — safe to log. The manager also emits
242
+ `live-query register|dedup-hit|retained|evicted|teardown-complete` rail lines (digests only).
262
243
 
263
244
  ## Store naming, backups, and restore (ADR-0035/0036)
264
245
 
265
246
  **Stores are named by a plain `storePath`, never a storage URL.** The backend is derived, not named — a
266
- capability-proven browser engine home uses OPFS-repacked; fixed worker mode, a denied engine home, and the
267
- main-thread browser fallback use IndexedDB; bun/Node uses the filesystem. Anything containing `://` throws
268
- `InvalidStorePathError` — do not "fix" that by re-adding a scheme, drop it. Memory-backed stores are
269
- deliberately unreachable from the production API (durability semantics assume a persisted store): tests spread
247
+ capability-proven browser engine home uses OPFS-repacked; fixed worker mode, a denied engine home and the
248
+ main-thread fallback use IndexedDB; bun/Node uses the filesystem. Anything containing `://` throws
249
+ `InvalidStorePathError` — drop the scheme, don't re-add it. Memory-backed stores are deliberately unreachable
250
+ from the production API (durability semantics assume a persisted store): tests spread
270
251
  `memoryStoreForTests("name")` from `@pgxsinkit/client/testing`, and a caller-owned
271
- `pgliteInstance`/`precreatedPglite` that is provably non-persistent (`dataDir` undefined — a bare
272
- `new PGlite()` — or `memory://`) is refused with `NonPersistentStoreError` unless `testStoreAcknowledgment()`
273
- is spread alongside. For browser store GC, get the IndexedDB name from
274
- `storeIndexedDbDatabaseName(storePath)` — never assemble `/pglite/…` yourself.
275
-
276
- **Relaxed durability is the default.** It is declared once, on the registry
277
- (`SyncRegistryDefinition.storage.durability`, `"relaxed" | "strict"`) — never on a minting surface,
278
- worker entry, or attach site, because durability follows the data, and one declaration binds every open
279
- of every store minted from that registry. Its physical behavior is
280
- backend-specific. On idb, relaxed returns before the whole-datadir snapshot flush and schedules it
281
- asynchronously; strict pays that synchronous snapshot (~100–200ms per optimistic mutation). On
282
- OPFS-repacked the host still awaits every sync: relaxed asserts VFS health and runs any due deferred repack
283
- without an ordinary physical flush, while strict flushes arena data before metadata. Initialization,
284
- repack activation, and open-state close use strict ordering in either OPFS mode. The resolved value is
285
- stamped on the `boot pglite.create` rail line.
286
-
287
- **The idb loss window.** On the idb backend the store is an in-memory FS with debounced whole-snapshot writes to
288
- IndexedDB, so `relaxed`'s window is every write since the last COMPLETED snapshot (a whole-FS debounce). The
289
- risk lands only on a crash before BOTH the journal rows reach the write API (~hundreds of ms after enqueue)
290
- AND the scheduled snapshot lands — and synced tables are server-recoverable by construction, so only consumer
291
- **local-only** tables carry real risk. `storage: { durability: "strict" }` on the registry is the escape
292
- hatch if you keep unrecoverable local-only data and cannot accept that window; on idb it costs
293
- ~100–200ms/write (allowed and documented, not forbidden).
294
-
295
- On OPFS-repacked, browser/worker termination recovers the longest valid stable metadata-log prefix; an
296
- unflushed suffix may be absent. A returned strict boundary is stable under that browser-failure model. Do
297
- not generalize this to power loss, media failure, or external store edits.
252
+ `pgliteInstance`/`precreatedPglite` that is provably non-persistent (`dataDir` undefined, or `memory://`) is
253
+ refused with `NonPersistentStoreError` unless `testStoreAcknowledgment()` is spread alongside. For browser
254
+ store GC, get the IndexedDB name from `storeIndexedDbDatabaseName(storePath)`, never assemble `/pglite/…`.
255
+
256
+ **Relaxed durability is the default**, declared once on the registry
257
+ (`SyncRegistryDefinition.storage.durability`) — never on a minting surface, worker entry or attach site,
258
+ because durability follows the data and one declaration binds every open of every store minted from that
259
+ registry. Its physical behavior is backend-specific: on idb, relaxed returns before the whole-datadir
260
+ snapshot flush and schedules it asynchronously while strict pays that synchronous snapshot (~100–200ms per
261
+ optimistic mutation); on OPFS-repacked the host still awaits every sync, with relaxed asserting VFS health
262
+ and running any due deferred repack without an ordinary physical flush while strict flushes arena data
263
+ before metadata (initialization, repack activation and open-state close use strict ordering either way).
264
+ The resolved value is stamped on the `boot pglite.create` rail line.
265
+
266
+ **The idb loss window.** On idb the store is an in-memory FS with debounced whole-snapshot writes, so
267
+ `relaxed`'s window is every write since the last COMPLETED snapshot. The risk lands only on a crash before
268
+ BOTH the journal rows reach the write API (~hundreds of ms after enqueue) AND the scheduled snapshot lands —
269
+ and synced tables are server-recoverable by construction, so only consumer **local-only** tables carry real
270
+ risk. `durability: "strict"` is the escape hatch if you keep unrecoverable local-only data; on idb it costs
271
+ ~100–200ms/write. On OPFS-repacked, browser/worker termination recovers the longest valid stable
272
+ metadata-log prefix and an unflushed suffix may be absent; a returned strict boundary is stable under that
273
+ browser-failure model — do not generalize it to power loss, media failure, or external store edits.
298
274
 
299
275
  **Three exports, named by purpose, all returning `{ file, report }`** (report = phase timings + a
300
- `MutationDiagnostics` snapshot, BootReport-style). They work identically on the in-process client and the
301
- attach client (the artefact crosses the bridge as a transferred buffer):
276
+ `MutationDiagnostics` snapshot). They work identically on both client forms (the artefact crosses the bridge
277
+ as a transferred buffer):
302
278
 
303
279
  - `exportStore()` — the **store backup**: a live, checkpointed `dumpDataDir` tarball of the WHOLE store,
304
280
  journal and overlay included. Never blocks, works offline with unflushed writes; restorable ONLY into
@@ -306,85 +282,122 @@ attach client (the artefact crosses the bridge as a transferred buffer):
306
282
  - `exportDiagnostics()` — everything as SQL (synced + overlay + journal + views/functions + the `pgxsinkit`
307
283
  schema) for support evidence. Never blocks; not for restoring.
308
284
  - `exportData({ drainJournal? })` — the **portable** SQL (synced tables + their enum types, nothing of
309
- pgxsinkit's machinery; loads into vanilla Postgres). The ONE blocking variant: it requires a fully
310
- drained journal (an `acked` write whose echo has not landed is NOT yet in the synced tables), so it
311
- flushes and awaits convergence up to `drainJournal.timeoutMs` (default 15s), failing fast with
312
- `DataExportDrainError` (+ diagnostics) on `failed`/`quarantined`/`conflicted` rows. `drainJournal: false`
313
- exports synced state as-is and flags it in the report.
285
+ pgxsinkit's machinery; loads into vanilla Postgres). The ONE blocking variant: it requires a fully drained
286
+ journal (an `acked` write whose echo has not landed is NOT yet in the synced tables), so it flushes and
287
+ awaits convergence up to `drainJournal.timeoutMs` (default 15s), failing fast with `DataExportDrainError`
288
+ (which carries diagnostics) on `failed`/`quarantined`/`conflicted` rows. `drainJournal: false` exports
289
+ as-is and flags it.
314
290
 
315
291
  The pg_dump variants run against a **throwaway clone** booted from the backup — the live engine is never
316
- suspended and tabs never pause. Exports, `destroy()`, `discardEphemeral()`, and `dropReadCache()` all
317
- serialise through one lifecycle slot: a concurrent call rejects immediately with `LifecycleBusyError`
318
- (no queueing — retry after the holder settles). Ephemeral (`pg_temp`) content is never in any artefact.
292
+ suspended and tabs never pause. Exports, `destroy()`, `discardEphemeral()` and `dropReadCache()` serialise
293
+ through one lifecycle slot: a concurrent call rejects immediately with `LifecycleBusyError` (no queueing —
294
+ retry after the holder settles). Ephemeral (`pg_temp`) content is never in any artefact.
319
295
 
320
296
  **Restore** = `createSyncClient({ restoreFrom: backupFile, … })` (or `attachSyncClient` — the tarball rides
321
297
  the boot attach), ONLY into a store path that does not exist in EITHER idb or OPFS
322
298
  (`RestoreTargetExistsError` otherwise; the overwrite path is a deliberate `destroy()` first). Recovered
323
- journal rows are quarantined because the write path has no mutation dedupe. A dirty-journal restore stays
324
- offline for inspection; a clean-journal restore may honor the normal online options immediately. Inspect
325
- `diagnostics()`, resolve quarantined rows via `discardQuarantined` (+ re-author if wanted), then reboot the
326
- persisted store normally. Consumer docs:
327
- <https://pgxsinkit.github.io/concepts/export-and-restore/>.
328
-
329
- **Backend permanence.** A store's storage backend is FIXED at its first mint, for the store's whole
330
- life. An existing idb store is opened IN PLACE by a newly capable OPFS home — no candidate, no
331
- sentinel, nothing copied, nothing deleted (`storageBackend: "idbfs"` + a `storageFallbackReason` on the
332
- report); a no-grant home refuses a committed OPFS store instead (above). The ONE route to another
333
- backend is a deliberate destroy — `client.destroy()`, or `destroyStoreArtifacts(storePath)` for a store
334
- nobody holds — then a fresh boot that re-syncs from the server and mints on the then-best backend.
335
- Budget a full cold bootstrap, and expect local-only state (anything written via `rawExec`, un-flushed
336
- journal rows dropped by `force`) to be gone: the replacement is a NEW store, not a converted one. There
337
- is no migration API and no in-place conversion. For a storage-PREFERENCE change, mint under a FRESH path
338
- and destroy the obsolete one in the background — never delete-and-recreate the same path while a
339
- predecessor worker may still hold it.
340
-
341
- **Resetting and deleting stores (ADR-0050).** Three non-interchangeable levers — pick by what you keep
342
- and whether the store is running:
299
+ journal rows are quarantined because the write path has no mutation dedupe; a dirty-journal restore stays
300
+ offline for inspection, a clean-journal one may honor the normal online options immediately. Inspect
301
+ `diagnostics()`, resolve quarantined rows via `discardQuarantined`, then reboot the persisted store normally
302
+ (<https://pgxsinkit.github.io/concepts/export-and-restore/>).
303
+
304
+ **Backend permanence.** A store's backend is FIXED at its first mint, for the store's whole life. An
305
+ existing idb store is opened IN PLACE by a newly capable OPFS home — nothing copied, nothing deleted
306
+ (`storageBackend: "idbfs"` + a `storageFallbackReason` on the report); a no-grant home refuses a committed
307
+ OPFS store instead (above). The ONE route to another backend is a deliberate destroy — `client.destroy()`,
308
+ or `destroyStoreArtifacts(storePath)` for a store nobody holds — then a fresh boot that re-syncs and mints
309
+ on the then-best backend. Budget a full cold bootstrap, and expect local-only state (anything written via
310
+ `rawExec`, un-flushed journal rows dropped by `force`) to be gone: the replacement is a NEW store, not a
311
+ converted one. There is no migration API and no in-place conversion. For a storage-PREFERENCE change, mint
312
+ under a FRESH path and destroy the obsolete one in the background — never delete-and-recreate a live path.
313
+
314
+ **Resetting and deleting stores (ADR-0050).** Four non-interchangeable levers, picked by what you keep and
315
+ whether the store is running:
343
316
 
344
317
  - `client.dropReadCache()` — keep the store, drop synced rows, resync in place (overlay + journal survive).
345
318
  - `client.destroy()` — delete a RUNNING store from an attached client: peer-count checked
346
- (`StoreDestroyRefusedError` while peers hold it), owed-journal checked (refused unless `force`),
347
- teardown-acknowledged before deletion.
319
+ (`StoreDestroyRefusedError`), owed-journal checked (refused unless `force`), teardown-acked before deletion.
348
320
  - `destroyStoreArtifacts(storePath)` — delete a NOT-running store by path: OPFS directory + commitment
349
321
  sentinel + meta record + idb database, backend-agnostic, bounded ownership-lag retry. Documented
350
322
  precondition, no liveness probe: on a still-held path it throws the ownership error — loud and safely
351
- re-runnable (idempotent, phase-recorded; a `deleting`-marked store is refused for boot). Keep failed
352
- paths on a retry list for the next boot. An idb-only sweep is NOT a substitute — it leaks the OPFS arena.
353
- - `quiesceStoreWorker(worker, opts?)` (ADR-0050) — the by-path TEARDOWN companion that MAKES a store
354
- not-running before `destroyStoreArtifacts`. Give it a worker factory of the same shape `attachSyncClient`
355
- takes (`() => new SharedWorker(url, { name: storePath })`) — but the factory MUST construct the worker with
356
- **byte-identical options to the LIVE store worker**, `extendedLifetime: true` included. A named SharedWorker
357
- dedups onto one instance, and Chromium (148+) FAILS a second `new SharedWorker(name, …)` whose options
358
- disagree with the live one (an `error` event, no `onconnect`) — the teardown port then exchanges zero
359
- messages and only times out. Omitting `extendedLifetime` on the teardown worker does not shorten its life
360
- (`closeHost` + `scope.close()` end it); it only breaks the dedup and defeats the primitive. It reaches the
361
- worker by name, posts the
362
- declaration, queries placement, and for an SW-direct home (idbfs, real-Safari opfs) sends `engine-teardown`
363
- and AWAITS the reserved ack (engine stopped, backend connection released → `{ toreDown: true }`); an elected
364
- home is a no-op (`{ toreDown: false }` — the elected engine dies with its tab). Compose best-effort:
323
+ re-runnable (a `deleting`-marked store is refused for boot). Keep failed paths on a retry list for the next
324
+ boot. An idb-only sweep is NOT a substitute — it leaks the OPFS arena.
325
+ - `quiesceStoreWorker(worker, opts?)` — the by-path TEARDOWN companion that MAKES a store not-running before
326
+ `destroyStoreArtifacts`. Give it a worker factory of the shape `attachSyncClient` takes
327
+ (`() => new SharedWorker(url, { name: storePath })`) that constructs the worker with **byte-identical
328
+ options to the LIVE store worker**, `extendedLifetime: true` included: a named SharedWorker dedups onto one
329
+ instance, and Chromium (148+) FAILS a second `new SharedWorker(name, …)` whose options disagree (an `error`
330
+ event, no `onconnect`), so the teardown port exchanges zero messages and only times out. Omitting
331
+ `extendedLifetime` does not shorten the teardown worker's life (`closeHost` + `scope.close()` end it) — it
332
+ only breaks the dedup and defeats the primitive. It reaches the worker by name, posts the declaration,
333
+ queries placement, and for an SW-direct home sends `engine-teardown` and AWAITS the reserved ack (engine
334
+ stopped, backend connection released → `{ toreDown: true }`); an elected home is a no-op
335
+ (`{ toreDown: false }` — the elected engine dies with its tab). Compose best-effort:
365
336
  `await quiesceStoreWorker(f).catch(() => {}); await destroyStoreArtifacts(path)`. A timeout REJECTS (not
366
- proof of teardown, default 6s) and must not abort the destroy; omit `storage` (no opinion) so a worker on
367
- an older declaration is never refused; idempotent + safe on an already-dead store.
368
-
369
- **Storage-preference changes.** A store's storage declaration (backend/durability) is IMMUTABLE — bound at
370
- first contact, conflicts refused typed (`StorageDeclarationRefusedError`). Never re-home or
371
- delete-and-recreate a live path (an `extendedLifetime` predecessor may still hold it). The pattern:
372
- atomically drop bindings + record the old exact paths on an obsolete list FIRST, then write the new
373
- preference and reload; fresh stores mint under fresh paths, and each boot walks the obsolete list in
374
- the background (never awaited on sign-in), per path QUIESCING the worker (`quiesceStoreWorker`) BEFORE
375
- `destroyStoreArtifacts`. The quiesce is what makes idbfs converge: an `extendedLifetime` idbfs
376
- predecessor holds its IndexedDB connection across the reload, so a bare destroy would block forever
377
- (opfs releases on idle; idbfs does not) — tearing the host down releases the connection so the first
337
+ proof of teardown, default 6s) and must not abort the destroy; omit `storage` so a worker on an older
338
+ declaration is never refused; idempotent + safe on an already-dead store.
339
+
340
+ **Storage-preference changes.** A store's storage declaration is IMMUTABLE — bound at first contact,
341
+ conflicts refused typed (`StorageDeclarationRefusedError`). Never re-home or delete-and-recreate a live path
342
+ (an `extendedLifetime` predecessor may still hold it). The pattern: atomically drop bindings + record the old
343
+ exact paths on an obsolete list FIRST, then write the new preference and reload; fresh stores mint under
344
+ fresh paths, and each boot walks the obsolete list in the background (never awaited on sign-in), per path
345
+ QUIESCING the worker BEFORE `destroyStoreArtifacts`. The quiesce is what makes idbfs converge: an
346
+ `extendedLifetime` idbfs predecessor holds its IndexedDB connection across the reload, so a bare destroy
347
+ would block forever (opfs releases on idle; idbfs does not) — tearing the host down releases it so the first
378
348
  retry wins. Dynamic declarations travel as the wire `storage` option on
379
- `attachSyncClient`/`provisionSyncWorker`; a registry-attached static declaration stays authoritative. Consumer docs:
380
- <https://pgxsinkit.github.io/concepts/local-store-lifecycle/>.
349
+ `attachSyncClient`/`provisionSyncWorker`; a registry-attached static declaration stays authoritative.
350
+ Consumer docs: <https://pgxsinkit.github.io/concepts/local-store-lifecycle/>.
351
+
352
+ ## Event lane: observing the Outbox (ADR-0053)
353
+
354
+ If your registry declares `streams`, `client.appendEvent(stream, payload)` stages a fire-and-forget fact in
355
+ the **Outbox** — a durable, local-only table, never synced, overlaid or conflict-resolved. It resolves on
356
+ **durable local enqueue, not on delivery**, so it never blocks on the network and an append made offline
357
+ survives a reload. Two observation surfaces, identical on both client forms:
358
+
359
+ - **`onOutboxStatus(cb)` — the drain signal.** `{ empty }`, fired on the empty ↔ non-empty **transitions**,
360
+ current state delivered on subscribe (`await client.outboxStatus()` is the one-shot pull twin). It is the
361
+ invalidation hook for a best-guess view composing pending events with down-synced aggregates: when the
362
+ Outbox drains, the aggregate is authoritative again. It carries **no count** deliberately (one updated only
363
+ on transitions is stale by construction) — query `getOutboxTable(registry)` when you need one.
364
+ - **`onEventLaneReport(cb)` — the verdicts.** Per flush pass: terminal non-`acked` verdicts, `deferred` ones,
365
+ and batch-level backoff transitions. `acked` is never reported (a high-volume lane would drown you), and it
366
+ is **EPHEMERAL** — with **nothing subscribed the library warn-logs each report**. Subscribe for the app's
367
+ lifetime: once a row is deleted the Outbox cannot answer for it.
368
+
369
+ **Read the verdicts correctly — one of the four is not a failure.** `acked` is enqueued server-side. `refused`
370
+ (your `eventGate` said no) and `rejected` are **terminal**: the row is deleted, and `refused` is expected, not
371
+ an error. `rejected` has THREE causes on a KNOWN stream — a payload the schema refuses (or a parse output JSON
372
+ cannot carry), an oversized payload, and an **identity claim the stream declares that the verified claims
373
+ cannot resolve** (absent/null/object/array/empty — fail-closed, no partial stamp). The first two mean a
374
+ non-library caller or a broken deployment (the library validates at append) — a **bug**; the third means the
375
+ ISSUER stopped minting that claim, or moved its path. `deferred` is **NOT terminal**: the server does not
376
+ (yet) know that stream — rollout skew — so the rows stay, retry with backoff, and drain once the deploy lands.
377
+ A burst after a release is deploy order; one that never clears means the registry LACKS it.
378
+
379
+ **There is no attempt cap and no client-side quarantine, by design.** Retry has two classes: retryable
380
+ (network, 5xx, 408/425/429 — jittered backoff with a ceiling, honouring `Retry-After`, paused offline) and
381
+ auth (refresh once, then retryable). A row leaves the Outbox **only** on a server-issued per-event verdict,
382
+ so a stuck lane is a growing Outbox with backoff transitions on the report, never silent loss. A persistent
383
+ **503 / batch backoff** is the OTHER diagnosis — the server KNOWS the stream but could not enqueue the whole
384
+ batch: check the `--events` migration is applied (no queue, no enqueue), then DB reachability. Cadence/batch
385
+ caps are client config (`events`, validated at construction — a bad `batchSize` throws instead of wedging a
386
+ stream), clamped by the contracts limits; `flushEvents()` is the manual hatch without `autoSync`.
387
+
388
+ **The Outbox on every lifecycle surface** (durable owned state): `destroy()` **refuses** while it is
389
+ non-empty, exactly as on owed mutations — the refusal names which of the two blocked it, and `{ force: true }`
390
+ is the escape hatch. `dropReadCache()` never touches it (not read cache). `exportStore()` and
391
+ `exportDiagnostics()` include it; `exportData()` (synced tables only) excludes it. And **restore does NOT
392
+ quarantine restored Outbox rows** — the deliberate asymmetry with the mutation journal: they resume flushing
393
+ normally, because event delivery is idempotent end-to-end (`eventId` dedupe), which mutation replay is not.
381
394
 
382
395
  ## Proxying Electric: force `cache-control: no-store`
383
396
 
384
- Electric tags shape responses with a CDN-oriented `cache-control` (`max-age`, `stale-while-revalidate`).
385
- Behind a **same-origin proxy with no CDN**, the browser cache serves them **stale** the moment a shape
386
- handle rotates (re-seed, re-login, restart), and the client loops on "expired shape handle" **409s**
387
- until it self-heals. Force `cache-control: no-store` on the proxied response:
397
+ Electric tags shape responses with a CDN-oriented `cache-control` (`max-age`, `stale-while-revalidate`), so
398
+ behind a **same-origin proxy with no CDN** the browser cache serves them **stale** the moment a shape handle
399
+ rotates (re-seed, re-login, restart) and the client loops on "expired shape handle" **409s** until it
400
+ self-heals. Force `cache-control: no-store` on the proxied response:
388
401
 
389
402
  ```ts
390
403
  const response = await proxyElectricShapeRequest(request, claims, { registry, electricUrl });
@@ -393,22 +406,18 @@ headers.set("cache-control", "no-store");
393
406
  return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
394
407
  ```
395
408
 
396
- Resumption stays cheap because Electric's offset/handle bookkeeping (in the local store) makes it cheap,
397
- not the HTTP cache.
398
-
399
- Upstream direction, hosted Electric behind a CDN: live long-polls can be answered by a layer blind to
400
- fresh commits (consecutive full-hold `up-to-date` responses at an unmoved offset → ~40–90s cross-client
409
+ Resumption stays cheap because Electric's offset/handle bookkeeping (in the local store) makes it cheap, not
410
+ the HTTP cache. Upstream direction, hosted Electric behind a CDN: live long-polls can be answered by a layer blind to fresh
411
+ commits (consecutive full-hold `up-to-date` responses at an unmoved offset → ~40–90s cross-client
401
412
  propagation). The proxy appends a unique `cache-buster` to every `live=true` upstream request by default
402
- (`bustLiveUpstreamCache`; catch-up stays unbusted for CDN cold-fanout sharing). TEMPORARY
403
- upstream-defect mitigation — it defeats Electric's sanctioned live-poll coalescing (per-client origin
404
- fan-out at scale); flip off once Electric Cloud wakes coalesced polls reliably. Distinct from the
405
- ADR-0033 sibling nudge, which is permanent protocol behavior. Running your own CDN in front of
406
- self-hosted Electric: key on the FULL query string (every param is load-bearing), respect origin
407
- cache-control, keep SWR windows modest, let coalesced live polls complete immediately on origin
408
- response, read-timeouts 60s+, then VERIFY with bust off — cross-client render ≲3s = healthy, ~a full
409
- hold cycle = live path served blind (full checklist: operating-in-production docs page). Harmless
410
- self-hosted;
411
- set `false` to restore untouched forwarding.
413
+ (`bustLiveUpstreamCache`; catch-up stays unbusted for CDN cold-fanout sharing). TEMPORARY upstream-defect
414
+ mitigation — it defeats Electric's sanctioned live-poll coalescing (per-client origin fan-out at scale), so
415
+ flip it off once Electric Cloud wakes coalesced polls reliably; distinct from the ADR-0033 sibling nudge,
416
+ which is permanent protocol behavior. Running your own CDN in front of self-hosted Electric: key on the FULL
417
+ query string (every param is load-bearing), respect origin cache-control, keep SWR windows modest, let
418
+ coalesced live polls complete immediately on origin response, read-timeouts 60s+, then VERIFY with bust off
419
+ — cross-client render ≲3s = healthy, ~a full hold cycle = live path served blind (full checklist:
420
+ operating-in-production docs page). Harmless self-hosted; set `false` to restore untouched forwarding.
412
421
 
413
422
  ## Debugging latency: `globalThis.__pgxsinkitDebug`
414
423
 
@@ -419,67 +428,61 @@ every phase. Enable it from the console or before boot:
419
428
  globalThis.__pgxsinkitDebug = true; // reproduce, then filter the console to "pgxsinkit" + enable Verbose
420
429
  ```
421
430
 
422
- Read the **gaps** between phases: `mutation staged {mutationId, table}` (the write's origin — correlate
423
- by id with the later sent/acked lines); `convergence pass requested` → `flush` / `reconcile`
424
- (durations); `board-write auth token resolved {ms}` (a stalling per-request token fetch shows here);
425
- `board-write responded {status, ms}` (a cold worker, or a browser connection stall, shows here);
426
- `sync received change batch` → `sync applied {ms}` (truthful: fires only when the batch committed — a
427
- batch gated behind a quiet sibling's watermark logs `sync change batch held by group frontier` +
428
- `live-tail sibling nudge {shape}` instead, ADR-0033); `live query updated → re-render`. The read path has
429
- its own pair: `shape request start {shape, offset, live}` → `shape request done {shape, status, ms,
430
- upToDate?}` for EVERY Electric HTTP cycle (catch-up and long-poll), plus `must-refetch received {shape}`
431
- when the server rotates a shape (the truncate + re-snapshot recovery trigger — the thing to look for
432
- when a table unexpectedly re-syncs). Server-side, `createSyncServer({ logTimings: true })` emits the
433
- matching per-request `[pgxsinkit-timing]` lines (see the `deploying` skill, `@pgxsinkit/server`);
434
- client-observed minus server `totalMs` isolates routing + network. Boot is stamped too — the `boot
435
- pglite.create` → `boot client ready` phases (local store open, schema apply, journal recovery,
436
- store-version reconcile, sync start) let you attribute a slow first paint to a specific boot phase, and
437
- `boot pglite assets warm` times the optional boot-asset pre-warm (see below).
438
-
439
- **Structured boot numbers — the `BootReport`.** The rail lines are for a human reading a console; for
431
+ Read the **gaps** between phases: `mutation staged {mutationId, table}` (correlate by id with the later
432
+ sent/acked lines); `convergence pass requested` → `flush` / `reconcile`; `board-write auth token resolved
433
+ {ms}` (a stalling token fetch); `board-write responded {status, ms}` (a cold worker or a connection stall);
434
+ `sync received change batch` → `sync applied {ms}` (fires only when the batch committed; a batch gated behind
435
+ a quiet sibling's watermark instead logs `sync change batch held by group frontier` and `live-tail sibling
436
+ nudge {shape}`, ADR-0033); `live query updated → re-render`. The read path has its own pair: `shape request
437
+ start` → `shape request done {shape, status, ms, upToDate?}` for EVERY Electric HTTP cycle, plus `must-refetch
438
+ received {shape}` when the server rotates a shape (the truncate + re-snapshot trigger — what to look for when
439
+ a table unexpectedly re-syncs). Server-side, `createSyncServer({ logTimings: true })` emits matching
440
+ `[pgxsinkit-timing]` lines (the `deploying` skill); client-observed minus server `totalMs` isolates routing +
441
+ network. Boot too: `boot pglite.create` → `boot client ready` (store open, schema apply, journal recovery,
442
+ store-version reconcile, sync start) attributes a slow first paint to a phase; `boot pglite assets warm` times
443
+ the optional pre-warm.
444
+
445
+ **Structured boot numbers — the `BootReport`.** The rail is for a human reading a console; for
440
446
  machine-keepable numbers (dashboards, CI budget gates) every boot ALSO builds a versioned `BootReport`,
441
447
  independently of the rail so it exists whether or not the flag is on (ADR-0034). Read it by push
442
- (`onBootReport?: (report) => void` client option, fires once at boot completion) or pull
443
- (`await client.bootReport()` → the most recent completed boot, `null` before the first sync; in worker mode
444
- it round-trips to the worker's stored report, so a late tab reads a boot that predates it). It carries
445
- `totalMs`, decomposed `phases`, and a per-group `groups[]`. Two reading caveats: groups catch up
446
- CONCURRENTLY on one WASM thread, so a group's `fetchMs` is an UPPER BOUND on network wait (it absorbs other
447
- groups' applies + main-thread work between deliveries), and concurrent `applyMs` can overlap — never sum
448
- them into a `totalMs` partition; and a non-null `provision` block is a spare's off-thread `initdb` made
449
- visible (then `phases.pgliteCreateMs` is `null`).
450
-
451
- A `catch-up watermark aligned {floor}` line marks the one moment the group finished its initial catch-up
452
- and aligned its commit floors (ADR-0031). Electric's catch-up responses are CDN-cacheable and carry the
453
- `up-to-date` watermark inside the cached body, so a quiet shape's stale cached watermark would otherwise
454
- hold a busy shape's fresh changes until the quiet shape's first live long-poll (~41s on Electric Cloud —
455
- the "stale board that rearranges itself" symptom). The client aligns once to the freshest asserted head
456
- instead; the trade is a sub-second torn view of a multi-table transaction at load, self-healing in one
457
- round trip, rather than a consistent-but-seconds-stale one. The same hold recurs on the **live tail**
458
- (a quiet sibling's parked long-poll returns only at hold expiry), where the engine **nudges** the
459
- laggards instead of waiting — `sync change batch held by group frontier` → `live-tail sibling nudge
460
- {shape, target, round}` → commit on the refreshed watermarks; `live-tail nudge exhausted` means a
461
- sibling never advanced and the engine degraded to waiting out its poll (ADR-0033). Full prose:
448
+ (`onBootReport?: (report) => void`, fires once at boot completion) or pull (`await client.bootReport()` → the
449
+ most recent completed boot, `null` before the first sync; in worker mode it round-trips to the worker's
450
+ stored report, so a late tab reads a boot that predates it). It carries `totalMs`, decomposed `phases`, and a
451
+ per-group `groups[]`. Two reading caveats: groups catch up CONCURRENTLY on one WASM thread, so a group's
452
+ `fetchMs` is an UPPER BOUND on network wait and concurrent `applyMs` can overlap — never sum them into a
453
+ `totalMs` partition; and a non-null `provision` block is a spare's off-thread `initdb` made visible (then
454
+ `phases.pgliteCreateMs` is `null`).
455
+
456
+ A `catch-up watermark aligned {floor}` line marks the one moment a group finished its initial catch-up and
457
+ aligned its commit floors (ADR-0031). Electric's catch-up responses are CDN-cacheable and carry the
458
+ `up-to-date` watermark inside the cached body, so a quiet shape's stale cached watermark would otherwise hold
459
+ a busy shape's fresh changes until the quiet shape's first live long-poll (~41s on Electric Cloud — the
460
+ "stale board that rearranges itself" symptom). The client aligns once to the freshest asserted head instead;
461
+ the trade is a sub-second torn view of a multi-table transaction at load, self-healing in one round trip.
462
+ The same hold recurs on the **live tail**, where the engine **nudges** the laggards instead of waiting —
463
+ `sync change batch held by group frontier` → `live-tail sibling nudge {shape, target, round}` → commit on
464
+ the refreshed watermarks; `live-tail nudge exhausted` means a sibling never advanced and the engine degraded
465
+ to waiting out its poll (ADR-0033). Full prose:
462
466
  <https://pgxsinkit.github.io/start/operating-in-production/>.
463
467
 
464
468
  **Measure at the network boundary, not by polling PGlite.** Each PGlite query is ~50ms on one thread, so
465
469
  a tight `setInterval` reading PGlite to "watch" a value inflates the very latency it reports. Trust the
466
470
  instrumentation's network timings and a server-side `curl` over a poll loop.
467
471
 
468
- **Inspecting a stuck or failed write.** To see _why_ a write is not converging — its journal status,
469
- attempt/retry counts, last error, or a table's pending/conflict/quarantine state — read the generated
470
- journal and sync-state relations with the typed factories `getJournalTable(registry, tableKey)` /
471
- `getSyncStateView(registry, tableKey)` from `@pgxsinkit/client` (typed Drizzle, no hand-written SQL against
472
- `<t>_mutations`). One-shot diagnostic reads only — don't poll them in a loop.
473
-
474
- **Rolling back a terminal write.** Both terminal dispositions keep the optimistic overlay and now have a
475
- symmetric discard. A stale-write `conflicted` row (fired via `onConflict`) rolls back with
476
- `client.discardConflict(table, entityKey)`; a structurally-rejected `quarantined` row (fired via
477
- `onQuarantine` — a validation failure or a permanent policy denial such as an RLS `42501`) rolls back
478
- with `client.discardQuarantined(table, entityKey)`. Each clears the entity's terminal journal rows +
479
- kept overlay, so the read model falls back to the synced value and the entity accepts new mutations
480
- again (a lingering terminal row otherwise blocks a re-create and chains a later update onto a dead head).
481
- Because quarantine has a real rollback now, route a permanent policy denial to `quarantined` — don't
482
- mis-route it to `conflicted` to borrow a discard.
472
+ **Inspecting a stuck or failed write.** To see _why_ a write is not converging — journal status,
473
+ attempt/retry counts, last error, a table's pending/conflict/quarantine state — read the generated journal
474
+ and sync-state relations with the typed factories `getJournalTable(registry, tableKey)` /
475
+ `getSyncStateView(registry, tableKey)` (typed Drizzle, no hand-written SQL against `<t>_mutations`). One-shot
476
+ diagnostic reads only — don't poll them in a loop.
477
+
478
+ **Rolling back a terminal write.** Both terminal dispositions keep the optimistic overlay and have a
479
+ symmetric discard: a stale-write `conflicted` row (via `onConflict`) rolls back with
480
+ `client.discardConflict(table, entityKey)`, a structurally-rejected `quarantined` row (via `onQuarantine` —
481
+ a validation failure or a permanent policy denial such as an RLS `42501`) with
482
+ `client.discardQuarantined(table, entityKey)`. Each clears the entity's terminal journal rows + kept overlay,
483
+ so the read model falls back to the synced value and the entity accepts new mutations again (a lingering
484
+ terminal row otherwise blocks a re-create and chains a later update onto a dead head). Because quarantine has
485
+ a real rollback, route a permanent policy denial to `quarantined` — never mis-route it to `conflicted`.
483
486
 
484
487
  ## Common mistakes
485
488
 
@@ -488,5 +491,9 @@ mis-route it to `conflicted` to borrow a discard.
488
491
  - Omitting `cache-control: no-store` on a same-origin shape proxy → intermittent 409 loops.
489
492
  - Treating an edge cold start as a toolkit/sync-rail problem.
490
493
  - Measuring latency by polling PGlite in a loop instead of at the network boundary.
494
+ - Treating `deferred` as a failure and "cleaning up" the Outbox — it is rollout skew, and those rows drain
495
+ themselves once the server deploy lands.
496
+ - Subscribing to `onEventLaneReport` per-screen (verdicts are ephemeral), or expecting `acked` on it.
497
+ - Assuming `appendEvent` resolving means delivered — it means durably staged locally; delivery is the flush.
491
498
 
492
499
  Full prose: <https://pgxsinkit.github.io/start/operating-in-production/>.