@pgxsinkit/client 0.2.7 → 0.5.0

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.
Files changed (153) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +81 -0
  4. package/README.md +11 -3
  5. package/dist/boot-report.d.ts +11 -8
  6. package/dist/boot-report.d.ts.map +1 -1
  7. package/dist/circuits/envelope-to-change.d.ts +39 -0
  8. package/dist/circuits/envelope-to-change.d.ts.map +1 -0
  9. package/dist/circuits/group-sync.d.ts +123 -0
  10. package/dist/circuits/group-sync.d.ts.map +1 -0
  11. package/dist/circuits/shape-group.d.ts +77 -0
  12. package/dist/circuits/shape-group.d.ts.map +1 -0
  13. package/dist/circuits/stream-inbox.d.ts +126 -0
  14. package/dist/circuits/stream-inbox.d.ts.map +1 -0
  15. package/dist/circuits/stream-source.d.ts +96 -0
  16. package/dist/circuits/stream-source.d.ts.map +1 -0
  17. package/dist/circuits/subscription-client.d.ts +143 -0
  18. package/dist/circuits/subscription-client.d.ts.map +1 -0
  19. package/dist/circuits/sync-engine.d.ts +131 -0
  20. package/dist/circuits/sync-engine.d.ts.map +1 -0
  21. package/dist/debug.d.ts +0 -10
  22. package/dist/debug.d.ts.map +1 -1
  23. package/dist/event-lane.d.ts +32 -1
  24. package/dist/event-lane.d.ts.map +1 -1
  25. package/dist/export-data.d.ts +3 -3
  26. package/dist/export-dump.d.ts +9 -9
  27. package/dist/export-dump.d.ts.map +1 -1
  28. package/dist/export-store.d.ts +13 -13
  29. package/dist/index.d.ts +237 -113
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +7037 -6665
  32. package/dist/index.js.map +46 -43
  33. package/dist/local-store.d.ts +1 -1
  34. package/dist/local-store.d.ts.map +1 -1
  35. package/dist/local-tables.d.ts +59 -1
  36. package/dist/local-tables.d.ts.map +1 -1
  37. package/dist/mutation.d.ts +2 -2
  38. package/dist/mutation.d.ts.map +1 -1
  39. package/dist/mutations-api.d.ts.map +1 -1
  40. package/dist/opfs-effects.d.ts +30 -2
  41. package/dist/opfs-effects.d.ts.map +1 -1
  42. package/dist/schema.d.ts +12 -1
  43. package/dist/schema.d.ts.map +1 -1
  44. package/dist/store-boot.d.ts +30 -2
  45. package/dist/store-boot.d.ts.map +1 -1
  46. package/dist/store-build.d.ts +19 -0
  47. package/dist/store-build.d.ts.map +1 -0
  48. package/dist/store-engine.d.ts +22 -0
  49. package/dist/store-engine.d.ts.map +1 -0
  50. package/dist/store-meta.d.ts +29 -3
  51. package/dist/store-meta.d.ts.map +1 -1
  52. package/dist/store-ownership-lock.d.ts +33 -0
  53. package/dist/store-ownership-lock.d.ts.map +1 -0
  54. package/dist/store-path.d.ts +40 -28
  55. package/dist/store-path.d.ts.map +1 -1
  56. package/dist/sync/apply.d.ts +17 -25
  57. package/dist/sync/apply.d.ts.map +1 -1
  58. package/dist/sync/copy.d.ts +84 -8
  59. package/dist/sync/copy.d.ts.map +1 -1
  60. package/dist/sync/drizzle-executor.d.ts +4 -4
  61. package/dist/sync/drizzle-executor.d.ts.map +1 -1
  62. package/dist/sync/fold.d.ts +40 -0
  63. package/dist/sync/fold.d.ts.map +1 -0
  64. package/dist/sync/metadata-tables.d.ts +25 -1
  65. package/dist/sync/metadata-tables.d.ts.map +1 -1
  66. package/dist/sync/subscription-state.d.ts +26 -7
  67. package/dist/sync/subscription-state.d.ts.map +1 -1
  68. package/dist/sync/types.d.ts +9 -129
  69. package/dist/sync/types.d.ts.map +1 -1
  70. package/dist/testing.d.ts +1 -1
  71. package/dist/testing.js +4 -3
  72. package/dist/testing.js.map +4 -4
  73. package/dist/worker/attach-sync-client.d.ts +27 -14
  74. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  75. package/dist/worker/define-sync-worker.d.ts +52 -19
  76. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  77. package/dist/worker/engine-control.d.ts +53 -0
  78. package/dist/worker/engine-control.d.ts.map +1 -1
  79. package/dist/worker/live-query-manager.d.ts +3 -3
  80. package/dist/worker/live-query-manager.d.ts.map +1 -1
  81. package/dist/worker/live-query-params-guard.d.ts +5 -5
  82. package/dist/worker/protocol.d.ts +26 -7
  83. package/dist/worker/protocol.d.ts.map +1 -1
  84. package/package.json +11 -9
  85. package/skills/core/SKILL.md +145 -63
  86. package/skills/operating/SKILL.md +221 -221
  87. package/skills/operating/references/postgres-builds.md +48 -0
  88. package/src/boot-report.ts +13 -12
  89. package/src/circuits/envelope-to-change.ts +211 -0
  90. package/src/circuits/group-sync.ts +1047 -0
  91. package/src/circuits/shape-group.ts +158 -0
  92. package/src/circuits/stream-inbox.ts +225 -0
  93. package/src/circuits/stream-source.ts +191 -0
  94. package/src/circuits/subscription-client.ts +353 -0
  95. package/src/circuits/sync-engine.ts +643 -0
  96. package/src/debug.ts +1 -85
  97. package/src/event-lane.ts +132 -14
  98. package/src/export-data.ts +4 -4
  99. package/src/export-dump.ts +24 -28
  100. package/src/export-store.ts +17 -17
  101. package/src/index.ts +797 -544
  102. package/src/lazy-guard.ts +1 -1
  103. package/src/live-rows-sql.ts +1 -1
  104. package/src/local-store.ts +2 -2
  105. package/src/local-tables.ts +76 -5
  106. package/src/mutation.ts +9 -8
  107. package/src/mutations-api.ts +2 -2
  108. package/src/opfs-effects.ts +74 -10
  109. package/src/schema.ts +126 -29
  110. package/src/store-boot.ts +71 -7
  111. package/src/store-build.ts +37 -0
  112. package/src/store-engine.ts +94 -0
  113. package/src/store-lifecycle.ts +1 -1
  114. package/src/store-meta.ts +155 -4
  115. package/src/store-ownership-lock.ts +109 -0
  116. package/src/store-path.ts +56 -40
  117. package/src/sync/apply.ts +104 -156
  118. package/src/sync/copy.ts +116 -21
  119. package/src/sync/drizzle-executor.ts +13 -14
  120. package/src/sync/fold.ts +94 -0
  121. package/src/sync/metadata-tables.ts +43 -2
  122. package/src/sync/subscription-state.ts +28 -10
  123. package/src/sync/types.ts +13 -141
  124. package/src/testing.ts +4 -4
  125. package/src/worker/attach-sync-client.ts +150 -57
  126. package/src/worker/define-sync-worker.ts +325 -87
  127. package/src/worker/engine-control.ts +89 -0
  128. package/src/worker/engine-router.ts +1 -1
  129. package/src/worker/live-query-fingerprint.ts +4 -4
  130. package/src/worker/live-query-manager.ts +12 -12
  131. package/src/worker/live-query-params-guard.ts +10 -10
  132. package/src/worker/protocol.ts +38 -7
  133. package/dist/read-stream-stall.d.ts +0 -54
  134. package/dist/read-stream-stall.d.ts.map +0 -1
  135. package/dist/shape-sync.d.ts +0 -207
  136. package/dist/shape-sync.d.ts.map +0 -1
  137. package/dist/sync/index.d.ts +0 -32
  138. package/dist/sync/index.d.ts.map +0 -1
  139. package/dist/sync/nudge.d.ts +0 -49
  140. package/dist/sync/nudge.d.ts.map +0 -1
  141. package/dist/sync/shape-inbox.d.ts +0 -215
  142. package/dist/sync/shape-inbox.d.ts.map +0 -1
  143. package/dist/sync/tags.d.ts +0 -142
  144. package/dist/sync/tags.d.ts.map +0 -1
  145. package/dist/sync-auth.d.ts +0 -53
  146. package/dist/sync-auth.d.ts.map +0 -1
  147. package/src/read-stream-stall.ts +0 -102
  148. package/src/shape-sync.ts +0 -533
  149. package/src/sync/index.ts +0 -1124
  150. package/src/sync/nudge.ts +0 -110
  151. package/src/sync/shape-inbox.ts +0 -566
  152. package/src/sync/tags.ts +0 -390
  153. package/src/sync-auth.ts +0 -117
@@ -1,21 +1,21 @@
1
1
  ---
2
2
  name: operating
3
3
  description: >-
4
- Load when deploying or operating a live pgxsinkit app, when diagnosing a sync/write that "feels slow"
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 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.
4
+ Load when deploying or operating a pgxsinkit app, when a sync/write "feels slow" in a browser
5
+ but the server is fast, or when wiring backups/export/restore. Covers the runtime/deployment
6
+ properties (not toolkit bugs) deciding whether an app feels fast: convergence cadence (writes
7
+ flush on enqueue; interval is a fallback), serverless edge cold starts, the read path's cache
8
+ split (no-store control plane, cacheable edge on its own origin, token out of the cache key), the
9
+ browser HTTP/2 connection budget, the edge worker timeout vs the durable-streams long-poll hold,
10
+ globalThis.__pgxsinkitDebug + BootReport, worker mode (defineSyncWorker/attachSyncClient —
11
+ capability-driven engine placement, relocation outcomes, the forwarded rail), the store lifecycle
12
+ surface (storePath naming, durability, backend permanence, destruction, the three exports,
13
+ restoreFrom), and Event-lane observability: onOutboxStatus, onEventLaneReport verdicts incl.
14
+ deferred-on-skew, the acked ledger, and the Outbox across destroy/restore/backup.
15
15
  metadata:
16
16
  type: task
17
17
  library: "@pgxsinkit/client"
18
- library_version: "0.2.7"
18
+ library_version: "0.5.0"
19
19
  source: https://pgxsinkit.github.io/start/operating-in-production/
20
20
  ---
21
21
 
@@ -33,63 +33,68 @@ interval (`createBrowserConvergenceTrigger({ intervalMs })`, default 1.5s; in wo
33
33
  `defineSyncWorker`'s `convergenceIntervalMs`, default 15s), which is only a fallback for
34
34
  retries/recovery/cross-tab.
35
35
 
36
- Therefore **keep the interval long.** A short interval is the dominant idle cost: every PGlite query is
36
+ Therefore **keep the interval long.** A short interval is the dominant idle cost: every local-store query is
37
37
  ~50ms of WASM work on one thread, and an unconditional reconcile each tick re-runs every live query. The
38
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".
39
+ latency** (latency is bounded by the read-path 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**, 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).
43
+ `@durable-streams/client` holds **one live long-poll connection open per subscribed stream** (a subject in K
44
+ scopes of a shared shape holds K streams), and browsers cap **HTTP/1.1 at ~6 connections per origin** — so over
45
+ plain HTTP six streams' long-polls consume every slot and the same-origin **write** request is **Stalled in the
46
+ browser's connection queue** for a whole long-poll cycle before it is dispatched. This presents as multi-second
47
+ writes invisible to `curl`/Node (no per-host cap); only a real browser shows it (DevTools → Network → a stuck
48
+ `write` with a long **Stalled** time). Fix: serve the gateway over **HTTP/2** (or HTTP/3), which multiplexes
49
+ every request over one connection — any production ingress already does, so it only bites a local stack on
50
+ plain `http://` (browsers negotiate HTTP/2 only over TLS).
51
51
 
52
- ## Serverless edge cold starts
53
-
54
- On a serverless edge a worker is suspended when idle and evicted after longer idle, so the **first write
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.
52
+ **Bun has the same budget elsewhere:** a Bun process caps concurrent `fetch` at **256**
53
+ (`BUN_CONFIG_MAX_HTTP_REQUESTS`, ignored by `bun test` on 1.4.2), so a test running the sync edge **in-process** with many clients starves its own long-polls — run the edge as a separate process.
60
54
 
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`.
67
-
68
- ## Pre-warming PGlite's boot assets
55
+ ## Serverless edge cold starts
69
56
 
70
- A cold `PGlite.create` spends ~2.5s fetching + compiling the Postgres WASM (plus the initdb WASM and the
57
+ On a serverless edge a worker is suspended when idle and evicted after longer idle, so the **first write after a
58
+ quiet period** pays a cold start while steady-state writes are instant (measured: ~20ms warm, ~0.45s after ~15s
59
+ idle, ~5.8s on a cold module cache). That is the deployment target, not pgxsinkit — a long-lived Bun/Deno
60
+ process or a managed warm pool has none. Mitigate: keep the worker warm with a periodic cheap request (an empty
61
+ `{"mutations":[]}` POST, rejected at validation before any DB work), and set the worker wall-clock timeout
62
+ **above** the durable-streams long-poll hold so a live subscription is not recycled mid-cycle (the board gives
63
+ its read functions `EDGE_WORKER_TIMEOUT_MS: "600000"`, not the stock 60s).
64
+
65
+ Region-pin **only the DB-bound write function**, never the two read functions. Pinning it to the database's
66
+ region (Supabase `x-region`) keeps its chatty function→DB protocol on a ~1ms loop; the read halves are not
67
+ DB-bound at all — the control plane's upstream is the Circuits engine, the edge's is durable-streams — and the
68
+ edge wants to sit near the CALLER, so catch-up bytes take the short hop. `createSyncClient` splits this:
69
+ `requestHeaders` is the shared base (reads AND writes — e.g. a gateway `apikey`), `writeRequestHeaders` is
70
+ merged over it on the write path only. Put the region header in `writeRequestHeaders`, never in the shared
71
+ `requestHeaders`.
72
+
73
+ ## Pre-warming the Postgres build
74
+
75
+ A cold store create spends ~2.5s fetching + compiling the Postgres WASM (plus the initdb WASM and the
71
76
  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.)
78
-
79
- **In worker mode the engine loads PGlite's OWN assets — deliberately; do not pre-supply them.** The tab's
80
- warm still serves the engine by priming the same-origin HTTP cache the worker fetches from. Handing the
81
- engine a pre-compiled `WebAssembly.Module` benched NET-NEGATIVE: it forces compile-to-completion before
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.
84
-
85
- Pre-warming only hides the WASM fetch+compile; `PGlite.create` still spends ~1.9s on `initdb` + store open,
77
+ `createSyncClient` takes a `build` option (the Postgres build, `cBuild` from `@pgxsinkit/pgwasm-c` by
78
+ default); pass `createCBuild({ assets })` with a promise of the already-fetched/compiled `CBuildAssets`
79
+ (`{ postgresWasmModule, initdbWasmModule, fsBundle }`, URLs in `cBuildArtefacts`) and the build skips its own
80
+ lazy load. Start the fetch+compile on an **earlier screen** and hand the pending promise in — the WASM cost
81
+ then hides behind user think-time. Best-effort: a rejected warm falls back to the build's own load. The
82
+ client awaits an unfinished warm BEFORE the `boot pgwasm.create` stamp, so `pgwasmCreateMs` is the create
83
+ alone; a host may time its warm as `boot pgwasm build warm`. (Board demo: `apps/board/src/board/pgwasm-warm.ts`.)
84
+ The build must match `storage.build` (else `StorageBuildMismatchError`); a store refuses any build but its own.
85
+ **Read [references/postgres-builds.md](references/postgres-builds.md) before supplying a build or handling a refusal.**
86
+
87
+ **In worker mode the engine loads the build's OWN assets — deliberately; do not pre-supply them** (the tab's
88
+ warm still primes the same-origin HTTP cache the worker fetches from; a pre-compiled module benched NET-NEGATIVE).
89
+
90
+ Pre-warming only hides the WASM fetch+compile; the create still spends ~1.9s on `initdb` + store open,
86
91
  which can't start until the store id is known (usually the signed-in user). To hide that too, create the
87
- store EAGERLY under a generated id on the first screen and BIND it at auth. `createClientPGlite(storePath,
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
92
+ store EAGERLY under a generated id on the first screen and BIND it at auth. `createPgwasmClient(storePath,
93
+ { build })` runs the exact same create the client does internally and returns a schemaless `PgwasmClient`;
94
+ hand the still-pending promise to `createSyncClient`'s `precreatedPgwasm`. Unlike `pgwasmInstance` (caller
95
+ owns schema), `precreatedPgwasm` lets the client still run schema exec, prepare hooks, journal recovery and
91
96
  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
97
+ post-auth. A rejected `precreatedPgwasm` falls back to the `storePath` create path, so it is a pure
93
98
  accelerator, never a boot dependency. Bind eager stores to users with a small localStorage registry
94
99
  (userId→storeId plus one unbound "spare"): create a spare on the login screen, claim it at sign-in, GC any
95
100
  store that is neither mapped nor the spare. On a signed-in RELOAD there is no login screen to create ahead of,
@@ -98,7 +103,7 @@ later open adopts it. (Board demo: `store-registry.ts`, `store-prewarm.ts`.)
98
103
 
99
104
  ## Worker mode: capability-placed off-thread engine (browser apps)
100
105
 
101
- In a browser, prefer worker mode so PGlite, shape streams, journal machinery, and convergence leave the main
106
+ In a browser, prefer worker mode so the pgwasm store, shape streams, journal machinery, and convergence leave the main
102
107
  thread. The SharedWorker is always the communication centre. There is no placement option: where the engine
103
108
  runs is a runtime capability decision. Under the default `storage.backend: "opfs"`, an unconditional real
104
109
  synchronous-handle open at boot chooses the engine home — real macOS/iOS Safari runs the OPFS-repacked engine
@@ -121,9 +126,10 @@ its class) and carries the refused `storePath`; a no-grant `provision` declines
121
126
  reason rather than pre-minting the sibling.
122
127
 
123
128
  **Two-file pattern.** One worker entry, bundled for both SharedWorker and dedicated Worker, calls
124
- `defineSyncWorker({ registry, electricUrl, batchWriteUrl, … })` at module top level — no placement or
125
- durability option (both are runtime/registry concerns); the registry is CODE, _imported_ by the worker
126
- file, never cloned/serialized in. Give each store a stable SharedWorker name and always pass
129
+ `defineSyncWorker({ registry, controlPlaneUrl, streamBaseUrl, batchWriteUrl, … })` at module top level (read
130
+ URLs both-or-neither, as on `createSyncClient`) — no placement or durability option (both are
131
+ runtime/registry concerns); the registry is CODE, _imported_ by the worker file, never cloned/serialized
132
+ in. Give each store a stable SharedWorker name and always pass
127
133
  `extendedLifetime: true` (Chromium 148+ grace period; ignore-safe elsewhere). The tab calls
128
134
  `attachSyncClient({ worker, registry, getToken })`. Prefer the **factory** form (`worker: () => SharedWorker`)
129
135
  over a bare instance or a raw `port` — a SharedWorker cannot be reconstructed from itself, so **in elected
@@ -144,23 +150,23 @@ One-shot reads (`query`/`queryRow`/`queryRaw`/`queryRawRow`) compile on the tab
144
150
  guarded round trip — the worker runs the read gate + lazy-group guard, then Drizzle's own mapping runs back
145
151
  on the tab, so results match the in-process client exactly. A bare awaited `client.drizzle` builder is ALSO
146
152
  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
153
+ (additive, idempotent); `isSynced` — SYNCHRONOUS, so never an RPC — reads a snapshot the WORKER computes by calling its OWN `isSynced` per
154
+ registry key, ack-folded and re-broadcast on change: identical to the in-process answer (promoted lazy groups and sync-disabled included),
155
+ `false` before the first one, never catch-up completion (`groupReady`). Local `pgwasm` and `dropReadCache` are NOT proxied (no tab-local
156
+ store; a cache rebuild is engine-wide). `destroy()` IS proxied through a tab-side supervisor: it refuses peers with `StoreDestroyRefusedError`, refuses owed journal
151
157
  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.
158
+ methods ARE proxied, but the engine is SHARED: `desync(tableKey)` from one tab reverts the consistency group for
159
+ EVERY attached tab (the footgun). For an ephemeral delivery window use `discardEphemeral(tableKey)` instead —
160
+ the scoped, multi-tab-safe finalize (drops the ephemeral rows, reverts to dormant, refuses a group with any
161
+ persistent member), safe under a shared engine because an ephemeral window is per-delivery-session and
162
+ single-consumer. The exception is the INSPECTION surface `rawQuery` / `rawExec` / `rawTransaction` (debug pages,
163
+ REPLs, ad-hoc counts, and your own LOCAL-ONLY tables): identical on both clients (executed in the worker on the
164
+ attach client), it runs raw against the local store — bypassing the journal/overlay, any write staying local and
165
+ never converging — so it is not an app-data read path. `replAdapter(client)` shapes it into the
166
+ `{ query, exec }` duck `@pgxsinkit/pgwasm-repl` needs. A worker file can bake multiple role variants and pick
167
+ per attach via `resolveRegistry(role)` + the tab's `role`, and can pass the schema prepare hooks
168
+ `prepareLocalDbBeforeSchema` / `prepareLocalDbAfterSchema` (app migrations, indexes, views) — worker-entry, not
169
+ attach, options, because a hook is a function and cannot cross the bridge.
164
170
 
165
171
  **Identity switches do not wait for worker retirement.** Scope each worker identity by `storePath` with a
166
172
  distinct, stable SharedWorker name; multiple stores may remain alive concurrently. Detach/stop the old client
@@ -173,25 +179,25 @@ disposes live queries before closing that client's engine and store.
173
179
  expiry (any tab answers via `getToken`, first wins). The worker NEVER refreshes — exactly one refresher, so
174
180
  GoTrue refresh-token reuse detection can't be tripped by a second client.
175
181
 
176
- **Boot: spare-as-worker + internal prefetch overlap.** The spare store (see above) becomes a pre-spawned
177
- schemaless worker at the login screen (create + initdb off every thread that matters); the userId→storeId
178
- registry stays tab-side in localStorage so binding resolves before attach (SharedWorker naming needs it).
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`.
182
+ **Boot: spare-as-worker.** The spare store (see above) becomes a pre-spawned schemaless worker at the login
183
+ screen (create + initdb off every thread that matters); the userId→storeId registry stays tab-side in
184
+ localStorage so binding resolves before attach (SharedWorker naming needs it). Call `provisionSyncWorker` with
185
+ the same `worker` input as attach (the factory form, so elected-mode recovery is armed for provisioning too); an
186
+ elected pre-open shares the tab's one election coordinator and derives the engine from the SharedWorker's own
187
+ script URL. `provisionExpiryMs` (default 60000) is ONE deadline: it retires the abandoned elected claim AND
188
+ settles the returned promise with the typed `ProvisionExpiredError` in both modes, so a provision behind a dead
189
+ SharedWorker connection fails loudly rather than hanging. It bounds YOUR promise; the worker-side create attempt
190
+ follows the placement. SW-direct: the attempt is left running — a later attach adopts it if it completed and
191
+ waits on it if it is stuck, and a retried provision re-acks the same attempt rather than opening a second.
192
+ Elected: the deadline also releases the provision claim, and a LAST-claim release retires and terminates the
193
+ engine with that attempt inside it, so the next attach elects a fresh one (an attach that adopted the
194
+ coordinator earlier keeps its claim, and that engine). Fire-and-forget callers should `.catch()` it like any
195
+ un-awaited promise. Claim = bind id, attach, push config + token. On a PROVABLY-fresh claimed store pass
196
+ `attachSyncClient({ freshStore: true })` (never for a mapped/returning store): it asserts freshness, so streams
197
+ start from the beginning and the subscription-state read is skipped — a wrong `true` on a warm store
198
+ re-snapshots instead of resuming. It buys no catch-up/schema OVERLAP (that needed a commit gate the native read
199
+ path has no equivalent of, so boot is strictly sequential); what the spare removes is the store create itself.
200
+ Board boot-rail stamps: `boot spare store ensured`, `boot mapped store prewarm`, `boot store claimed`.
195
201
 
196
202
  **`ready` unchanged; per-group readiness exposed.** `client.ready` still gates on every eager group; for
197
203
  progressive paint use `await client.groupReady(tableKey)` or read `status.groups`.
@@ -201,24 +207,25 @@ progressive paint use `await client.groupReady(tableKey)` or read `status.groups
201
207
  clock and re-printed as `[pgxsinkit·w <ms>ms] …`, gated by that tab's own `globalThis.__pgxsinkitDebug`. The
202
208
  front half of boot runs on the FIRST attach before any tab is listening, so the worker buffers those
203
209
  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/>.
208
-
209
- **Placement and relocation diagnostics.** Pull `client.bootReport()` and inspect `storageBackend`
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.
210
+ The worker's NETWORK traffic is invisible the same way: the subscribe calls and the streams' long-polls never
211
+ appear in the page's Network panel — "the app is syncing but the Network tab shows nothing" is worker mode
212
+ working as designed. Inspect the worker itself (`chrome://inspect/#workers`) for the real requests and errors
213
+ (CORS rejections surface only there, a missing `Access-Control-Expose-Headers` on the edge included). Full
214
+ model: <https://pgxsinkit.github.io/concepts/worker-mode/>.
215
+
216
+ **Placement and relocation diagnostics.** Pull `client.bootReport()`: `storageBackend`, `engineHome`
217
+ (`shared-worker`/`elected-worker`/`in-process`), `storageFallbackReason`; never user-agent-sniff the backend. On
218
+ elected-engine handoff `EngineRelocatedError("not-dispatched")` is safe to retry; `"unknown"` means a dispatched
219
+ mutation may already be journaled — inspect/reconcile, never retry. The opt-in `executionLimit` is disabled by
220
+ default (no finite worst-case query duration exists; slow becomes terminated by policy), is elected-only, must
221
+ match across the worker entry and every tab (`ExecutionLimitMismatchError`); SW-direct rejects it. An attach
222
+ waits for an in-flight spare provision only within `provisionAdoptionBudgetMs` (default 20s from provision
223
+ start), then raises `ProvisionStalledError` — rebind to a fresh store; it bounds the accelerator, not liveness.
217
224
 
218
225
  ## Live-query manager: dedup + keep-alive (ADR-0040)
219
226
 
220
227
  Every reactive read (`useLiveDrizzleRows`/`useLiveQueryRaw`/`subscribeLiveRows`) is a **local SQL live
221
- query**: PGlite materialises it once, then re-runs + diffs it on every write to its tables. That registration
228
+ query**: pgwasm materialises it once, then re-runs + diffs it on every write to its tables. That registration
222
229
  is a real cost (~a few hundred ms for a heavy aggregate) and is **automatically deduplicated** — identical
223
230
  queries (keyed on executed SQL + bound params, NOT `use`) share ONE registration and ONE re-run + diff per
224
231
  write, fanned to every subscriber, so N components (or N tabs on the shared worker) cost one materialisation.
@@ -232,7 +239,7 @@ exists on `createSyncClient`). The effective keep-alive is `max(default, subscri
232
239
  budgets outrank any hint and LRU-evict zero-subscriber entries; active entries are never evicted.
233
240
 
234
241
  **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
242
+ (pgwasm live queries can't be), so it still pays a full re-run + diff on every write to its tables while
236
243
  held: retention wins only for a frequently-re-mounted, write-COLD query. For a fixed hot set the endorsed
237
244
  "permanent" pattern is a **mounted subscriber** (a root-provider hook that never unmounts) — one live
238
245
  registration for the app's life, every route dedups onto it; there is deliberately no retain-forever knob.
@@ -249,9 +256,9 @@ main-thread fallback use IndexedDB; bun/Node uses the filesystem. Anything conta
249
256
  `InvalidStorePathError` — drop the scheme, don't re-add it. Memory-backed stores are deliberately unreachable
250
257
  from the production API (durability semantics assume a persisted store): tests spread
251
258
  `memoryStoreForTests("name")` from `@pgxsinkit/client/testing`, and a caller-owned
252
- `pgliteInstance`/`precreatedPglite` that is provably non-persistent (`dataDir` undefined, or `memory://`) is
259
+ `pgwasmInstance`/`precreatedPgwasm` that is provably non-persistent (memory, or a filesystem declaring `persistent: false`) is
253
260
  refused with `NonPersistentStoreError` unless `testStoreAcknowledgment()` is spread alongside. For browser
254
- store GC, get the IndexedDB name from `storeIndexedDbDatabaseName(storePath)`, never assemble `/pglite/…`.
261
+ store GC, get the IndexedDB name from `storeIndexedDbDatabaseName(storePath)`, never assemble `/pgwasm/…`.
255
262
 
256
263
  **Relaxed durability is the default**, declared once on the registry
257
264
  (`SyncRegistryDefinition.storage.durability`) — never on a minting surface, worker entry or attach site,
@@ -261,7 +268,7 @@ snapshot flush and schedules it asynchronously while strict pays that synchronou
261
268
  optimistic mutation); on OPFS-repacked the host still awaits every sync, with relaxed asserting VFS health
262
269
  and running any due deferred repack without an ordinary physical flush while strict flushes arena data
263
270
  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.
271
+ The resolved value is stamped on the `boot pgwasm.create` rail line.
265
272
 
266
273
  **The idb loss window.** On idb the store is an in-memory FS with debounced whole-snapshot writes, so
267
274
  `relaxed`'s window is every write since the last COMPLETED snapshot. The risk lands only on a crash before
@@ -277,8 +284,8 @@ browser-failure model — do not generalize it to power loss, media failure, or
277
284
  as a transferred buffer):
278
285
 
279
286
  - `exportStore()` — the **store backup**: a live, checkpointed `dumpDataDir` tarball of the WHOLE store,
280
- journal and overlay included. Never blocks, works offline with unflushed writes; restorable ONLY into
281
- PGlite via restore below. This is the backup/migration format.
287
+ journal and overlay included. Never blocks, works offline with unflushed writes; restorable ONLY via
288
+ restore below, into the build that made it. This is the backup/migration format.
282
289
  - `exportDiagnostics()` — everything as SQL (synced + overlay + journal + views/functions + the `pgxsinkit`
283
290
  schema) for support evidence. Never blocks; not for restoring.
284
291
  - `exportData({ drainJournal? })` — the **portable** SQL (synced tables + their enum types, nothing of
@@ -349,75 +356,70 @@ retry wins. Dynamic declarations travel as the wire `storage` option on
349
356
  `attachSyncClient`/`provisionSyncWorker`; a registry-attached static declaration stays authoritative.
350
357
  Consumer docs: <https://pgxsinkit.github.io/concepts/local-store-lifecycle/>.
351
358
 
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
359
+ ## Event lane: observing the Outbox (ADR-0053, ADR-0060)
360
+
361
+ If your registry declares `streams`, `client.appendEvent(stream, payload)` stages a fire-and-forget fact in the **Outbox** — a durable, local-only
362
+ table, never synced, overlaid or conflict-resolved. It resolves on **durable local enqueue, not on delivery**, so it never blocks on the network and
363
+ an append made offline survives a reload. Two observation surfaces, identical on both client forms:
364
+
365
+ - **`onOutboxStatus(cb)` — the drain signal.** `{ empty }`, fired on the empty ↔ non-empty **transitions**, current state delivered on subscribe
366
+ (`await client.outboxStatus()` is the one-shot pull twin). "Empty" is **nothing awaiting a server VERDICT** — the invalidation hook for a best-guess
367
+ view composing pending events with down-synced aggregates. **No count**, deliberately (one updated only on transitions is stale by construction) —
368
+ query `getOutboxTable(registry)` when you need one.
369
+ - **`onEventLaneReport(cb)` — the verdicts.** Per flush pass: terminal non-`acked` verdicts, `deferred` ones, and batch-level backoff transitions.
370
+ `acked` is never reported (a high-volume lane would drown you), and it is **EPHEMERAL** — with **nothing subscribed the library warn-logs each
371
+ report**. Subscribe for the app's lifetime: once a row is deleted the Outbox cannot answer for it.
372
+
373
+ **`acked` means ENQUEUED, not folded** — the consumer has not handled the event and its result has not synced back down, so a best-guess view that
374
+ drops the row at the ack **dips** for that window, online and on a healthy deployment. `events.ackedRetentionMs > 0` (default `0` = delete on ack, the
375
+ pre-ledger behaviour) keeps the acked row STAMPED with `acked_at_us` for that long, then sweeps it. **Pending is `acked_at_us IS NULL`**, never "a row
376
+ exists": a retained row never keeps the drain signal non-empty, is never re-sent, is absent from `diagnostics().outbox`, and never blocks `destroy()`.
377
+ Count it until your own synced aggregate accounts for it — the retention is the backstop, sized to ack→fold→sync latency plus margin (the Outbox is a
378
+ queue, not an archive). The library cannot retire it on the FOLD: it knows the envelope was accepted and nothing about your consumer's data model.
379
+
380
+ **Read the verdicts correctly — one of the four is not a failure.** `acked` is enqueued server-side. `refused` (your `eventGate` said no) and
381
+ `rejected` are **terminal**: the row is deleted, and `refused` is expected, not an error. `rejected` has THREE causes on a KNOWN stream — a payload
382
+ the schema refuses (or a parse output JSON cannot carry), an oversized payload, and an **identity claim the stream declares that the verified claims
383
+ cannot resolve** (absent/null/object/array/empty — fail-closed, no partial stamp). The first two mean a non-library caller or a broken deployment (the
384
+ library validates at append) — a **bug**; the third means the ISSUER stopped minting that claim, or moved its path. `deferred` is **NOT terminal**:
385
+ the server does not (yet) know that stream — rollout skew — so the rows stay, retry with backoff, and drain once the deploy lands. A burst after a
386
+ release is deploy order; one that never clears means the registry LACKS it.
387
+
388
+ **There is no attempt cap and no client-side quarantine, by design.** Retry has two classes: retryable (network, 5xx, 408/425/429 — jittered backoff
389
+ with a ceiling, honouring `Retry-After`, paused offline) and auth (refresh once, then retryable). A row leaves the Outbox **only** on a server-issued
390
+ per-event verdict, so a stuck lane is a growing Outbox with backoff transitions on the report, never silent loss. A persistent **503 / batch backoff**
391
+ is the OTHER diagnosis — the server KNOWS the stream but could not enqueue the whole batch: check the `--events` migration is applied (no queue, no
392
+ enqueue), then DB reachability. Cadence/batch caps are client config (`events`, validated at construction — a bad `batchSize` throws instead of
393
+ wedging a stream), clamped by the contracts limits; `flushEvents()` is the manual hatch without `autoSync`.
394
+
395
+ **The Outbox on every lifecycle surface** (durable owned state): `destroy()` **refuses** while a row still awaits a verdict (a ledger-retained one
396
+ does not count), exactly as on owed mutations — the refusal names which of the two blocked it, and `{ force: true }` is the escape hatch.
397
+ `dropReadCache()` never touches it (not read cache). `exportStore()` and `exportDiagnostics()` include it; `exportData()` (synced tables only)
398
+ excludes it. And **restore does NOT quarantine restored Outbox rows** — the deliberate asymmetry with the mutation journal: they resume flushing
393
399
  normally, because event delivery is idempotent end-to-end (`eventId` dedupe), which mutation replay is not.
394
400
 
395
- ## Proxying Electric: force `cache-control: no-store`
396
-
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:
401
-
402
- ```ts
403
- const response = await proxyElectricShapeRequest(request, claims, { registry, electricUrl });
404
- const headers = new Headers(response.headers);
405
- headers.set("cache-control", "no-store");
406
- return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
407
- ```
408
-
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
412
- propagation). The proxy appends a unique `cache-buster` to every `live=true` upstream request by default
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.
401
+ ## The read path's cache split: uncacheable control plane, cacheable edge
402
+
403
+ The two read halves have opposite caching postures. The **control plane** (`/sync/v1/subscribe`, `/refresh`,
404
+ `/barrier`) answers per-subject questions and mints stream tokens, so force `cache-control: no-store` on it. The
405
+ **edge** (`createStreamGate` at `/v1/stream`) is the only surface a CDN may share, and durable-streams already
406
+ labels its responses for one — a catch-up read returns `cache-control: public, max-age=60,
407
+ stale-while-revalidate=300` and an `etag`, exactly where the bytes are. Sharing is a **shared-tier** property
408
+ only: a `rowFilter` fuses the subject into the predicate, so those bytes are shareable with nobody.
409
+
410
+ **Put the edge on its own origin, and keep the stream token out of the cache key.** The cache key is the URL, so
411
+ a same-origin mount makes the cacheable and uncacheable surfaces share one key and forecloses ever fronting the
412
+ shared tier; the token rides in `Authorization` (never a query parameter) for the same reason, and the cache
413
+ must not vary on that header. Revocation latency then follows the deployment: behind a hit-serving CDN it is
414
+ bounded by the token TTL (5 minutes by default), behind a cache sitting _behind_ the edge's verifier it is
415
+ entitlement-propagation latency.
416
+
417
+ **Every `createStreamGate` mount must set `Access-Control-Expose-Headers` from the exported
418
+ `STREAM_READ_EXPOSED_HEADERS`.** CORS lets script read only a short safelist, and every header durable-streams
419
+ answers with is outside it, so a cross-origin browser gets a response whose stream headers are simply not there:
420
+ `@durable-streams/client` steers its read loop off them, never learns an offset, and re-requests from the start
421
+ in a hot loop, with no error raised on either side. It presents as "sync does nothing, and the console is clean".
422
+ Mount details: the `deploying` skill.
421
423
 
422
424
  ## Debugging latency: `globalThis.__pgxsinkitDebug`
423
425
 
@@ -429,44 +431,41 @@ globalThis.__pgxsinkitDebug = true; // reproduce, then filter the console to "pg
429
431
  ```
430
432
 
431
433
  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.
434
+ sent/acked lines); `convergence pass requested (event-driven, …)` → `convergence flush` / `convergence
435
+ reconcile`; `flushBatch sending to board-write`; `board-write auth token resolved {ms}` (a stalling token
436
+ fetch); `board-write responded {status, ms}` (a cold worker or a connection stall); `board-write acks`; and
437
+ `live-query register|dedup-hit|retained|evicted|teardown-complete` (digests only). **The read path emits no rail
438
+ lines** — its cost is routing latency rather than phases, so read it off the `BootReport`'s per-group rows (below)
439
+ and off `status` / `status.lastError` (`degraded`/stream = subscribe failing or the stream silent; `auth-needed` =
440
+ the control plane refused this credential), and inspect the real requests in the worker's own DevTools. Server-side, `createSyncServer({ logTimings: true })` emits matching `[pgxsinkit-timing]` lines (the
441
+ `deploying` skill); client-observed minus server `totalMs` isolates routing + network. Boot too: `boot pgwasm.create` → `boot client
442
+ ready` (store open, schema apply, journal recovery, store-version reconcile, sync start) attributes a slow first
443
+ paint to a phase; `boot pgwasm build warm` times the optional pre-warm.
444
444
 
445
445
  **Structured boot numbers — the `BootReport`.** The rail is for a human reading a console; for
446
446
  machine-keepable numbers (dashboards, CI budget gates) every boot ALSO builds a versioned `BootReport`,
447
447
  independently of the rail so it exists whether or not the flag is on (ADR-0034). Read it by push
448
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
449
+ most recent completed boot, `null` before the first sync; in worker mode it round-trips to the worker's stored
450
+ report, so a late tab reads a boot that predates it). It carries `totalMs`, decomposed `phases`, and a per-group
451
+ `groups[]`. Two reading caveats: groups catch up CONCURRENTLY on one WASM thread, so a group's
452
452
  `fetchMs` is an UPPER BOUND on network wait and concurrent `applyMs` can overlap — never sum them into a
453
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:
466
- <https://pgxsinkit.github.io/start/operating-in-production/>.
467
-
468
- **Measure at the network boundary, not by polling PGlite.** Each PGlite query is ~50ms on one thread, so
469
- a tight `setInterval` reading PGlite to "watch" a value inflates the very latency it reports. Trust the
454
+ `phases.pgwasmCreateMs` is `null`).
455
+
456
+ **How a group decides to commit (ADR-0056), and the one state that is terminal.** There is **no commit floor** and
457
+ no cross-shape position comparison — offsets are per-stream and comparable only within one — so a group commits
458
+ when **every** one of its shapes' most recent responses asserted up-to-date (a quiet shape re-asserts freshness on
459
+ every `204` long-poll timeout). Atomic at boot/catch-up alignment; LIVE deliveries commit per response, so two
460
+ halves of one transaction can land milliseconds apart (backlog 0014). The **first** commit of each alignment
461
+ generation (boot, and after any must-refetch) also reads the engine's convergence barrier through the control
462
+ plane's `/sync/v1/barrier`, aligning only with `pendingFlips` at zero — no computed membership revocation still
463
+ undelivered. A barrier the client cannot READ is a delay: the group stays on the pre-alignment gate and retries. `flipFailures > 0` is **terminal**: the engine abandoned membership-flip
464
+ batches, those effects are lost, and the client refuses to align and goes `degraded` rather than waiting —
465
+ restart the engine and re-subscribe. Full prose: <https://pgxsinkit.github.io/start/operating-in-production/>.
466
+
467
+ **Measure at the network boundary, not by polling the local store.** Each local query is ~50ms on one thread, so
468
+ a tight `setInterval` reading the store to "watch" a value inflates the very latency it reports. Trust the
470
469
  instrumentation's network timings and a server-side `curl` over a poll loop.
471
470
 
472
471
  **Inspecting a stuck or failed write.** To see _why_ a write is not converging — journal status,
@@ -487,12 +486,13 @@ a real rollback, route a permanent policy denial to `quarantined` — never mis-
487
486
  ## Common mistakes
488
487
 
489
488
  - Shortening the convergence interval to chase write latency (no effect; wastes CPU).
490
- - Serving many-shape sync over plain HTTP/1.1 and blaming the server for stalled writes.
491
- - Omitting `cache-control: no-store` on a same-origin shape proxy → intermittent 409 loops.
492
- - Treating an edge cold start as a toolkit/sync-rail problem.
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.
489
+ - Serving many-stream sync over plain HTTP/1.1 and blaming the server for stalled writes.
490
+ - Mounting the stream edge on the control plane's origin (one cache key for both read surfaces), or omitting
491
+ `Access-Control-Expose-Headers` on it — that one hot-loops the client, silently on both sides.
492
+ - Treating an edge cold start as a toolkit problem, or measuring latency by polling the local store in a loop
493
+ instead of at the network boundary.
494
+ - Treating `deferred` as a failure and "cleaning up" the Outbox — it is rollout skew; those rows self-drain.
495
+ - Composing a best-guess view on row PRESENCE instead of `acked_at_us IS NULL` (with a retention configured, that counts rows the server already took).
496
496
  - Subscribing to `onEventLaneReport` per-screen (verdicts are ephemeral), or expecting `acked` on it.
497
497
  - Assuming `appendEvent` resolving means delivered — it means durably staged locally; delivery is the flush.
498
498