@pgxsinkit/client 0.3.0 → 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 (107) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +81 -0
  4. package/README.md +10 -3
  5. package/dist/boot-report.d.ts +6 -6
  6. package/dist/circuits/envelope-to-change.d.ts +9 -5
  7. package/dist/circuits/envelope-to-change.d.ts.map +1 -1
  8. package/dist/circuits/group-sync.d.ts +2 -2
  9. package/dist/circuits/group-sync.d.ts.map +1 -1
  10. package/dist/circuits/stream-source.d.ts +6 -0
  11. package/dist/circuits/stream-source.d.ts.map +1 -1
  12. package/dist/circuits/sync-engine.d.ts +2 -2
  13. package/dist/circuits/sync-engine.d.ts.map +1 -1
  14. package/dist/event-lane.d.ts +32 -1
  15. package/dist/event-lane.d.ts.map +1 -1
  16. package/dist/export-data.d.ts +3 -3
  17. package/dist/export-dump.d.ts +9 -9
  18. package/dist/export-dump.d.ts.map +1 -1
  19. package/dist/export-store.d.ts +13 -13
  20. package/dist/index.d.ts +191 -95
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +989 -432
  23. package/dist/index.js.map +39 -36
  24. package/dist/local-store.d.ts +1 -1
  25. package/dist/local-store.d.ts.map +1 -1
  26. package/dist/local-tables.d.ts +58 -0
  27. package/dist/local-tables.d.ts.map +1 -1
  28. package/dist/mutation.d.ts +2 -2
  29. package/dist/mutation.d.ts.map +1 -1
  30. package/dist/mutations-api.d.ts.map +1 -1
  31. package/dist/opfs-effects.d.ts +30 -2
  32. package/dist/opfs-effects.d.ts.map +1 -1
  33. package/dist/schema.d.ts +12 -1
  34. package/dist/schema.d.ts.map +1 -1
  35. package/dist/store-boot.d.ts +30 -2
  36. package/dist/store-boot.d.ts.map +1 -1
  37. package/dist/store-build.d.ts +19 -0
  38. package/dist/store-build.d.ts.map +1 -0
  39. package/dist/store-engine.d.ts +22 -0
  40. package/dist/store-engine.d.ts.map +1 -0
  41. package/dist/store-meta.d.ts +29 -3
  42. package/dist/store-meta.d.ts.map +1 -1
  43. package/dist/store-ownership-lock.d.ts +33 -0
  44. package/dist/store-ownership-lock.d.ts.map +1 -0
  45. package/dist/store-path.d.ts +40 -28
  46. package/dist/store-path.d.ts.map +1 -1
  47. package/dist/sync/apply.d.ts +5 -5
  48. package/dist/sync/apply.d.ts.map +1 -1
  49. package/dist/sync/copy.d.ts +82 -6
  50. package/dist/sync/copy.d.ts.map +1 -1
  51. package/dist/sync/drizzle-executor.d.ts +4 -4
  52. package/dist/sync/drizzle-executor.d.ts.map +1 -1
  53. package/dist/sync/subscription-state.d.ts +5 -5
  54. package/dist/sync/subscription-state.d.ts.map +1 -1
  55. package/dist/testing.d.ts +1 -1
  56. package/dist/testing.js +2 -1
  57. package/dist/testing.js.map +4 -4
  58. package/dist/worker/attach-sync-client.d.ts +24 -13
  59. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  60. package/dist/worker/define-sync-worker.d.ts +35 -18
  61. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  62. package/dist/worker/live-query-manager.d.ts +3 -3
  63. package/dist/worker/live-query-manager.d.ts.map +1 -1
  64. package/dist/worker/live-query-params-guard.d.ts +5 -5
  65. package/dist/worker/protocol.d.ts +26 -7
  66. package/dist/worker/protocol.d.ts.map +1 -1
  67. package/package.json +11 -8
  68. package/skills/core/SKILL.md +80 -15
  69. package/skills/operating/SKILL.md +129 -129
  70. package/skills/operating/references/postgres-builds.md +48 -0
  71. package/src/boot-report.ts +9 -9
  72. package/src/circuits/envelope-to-change.ts +121 -12
  73. package/src/circuits/group-sync.ts +2 -2
  74. package/src/circuits/stream-source.ts +35 -9
  75. package/src/circuits/sync-engine.ts +6 -4
  76. package/src/event-lane.ts +132 -14
  77. package/src/export-data.ts +4 -4
  78. package/src/export-dump.ts +21 -26
  79. package/src/export-store.ts +17 -17
  80. package/src/index.ts +520 -284
  81. package/src/live-rows-sql.ts +1 -1
  82. package/src/local-store.ts +2 -2
  83. package/src/local-tables.ts +70 -6
  84. package/src/mutation.ts +9 -8
  85. package/src/mutations-api.ts +2 -2
  86. package/src/opfs-effects.ts +74 -10
  87. package/src/schema.ts +124 -18
  88. package/src/store-boot.ts +71 -7
  89. package/src/store-build.ts +37 -0
  90. package/src/store-engine.ts +94 -0
  91. package/src/store-lifecycle.ts +1 -1
  92. package/src/store-meta.ts +155 -4
  93. package/src/store-ownership-lock.ts +109 -0
  94. package/src/store-path.ts +56 -40
  95. package/src/sync/apply.ts +32 -46
  96. package/src/sync/copy.ts +108 -13
  97. package/src/sync/drizzle-executor.ts +13 -14
  98. package/src/sync/metadata-tables.ts +1 -1
  99. package/src/sync/subscription-state.ts +7 -7
  100. package/src/testing.ts +3 -3
  101. package/src/worker/attach-sync-client.ts +142 -56
  102. package/src/worker/define-sync-worker.ts +204 -75
  103. package/src/worker/engine-router.ts +1 -1
  104. package/src/worker/live-query-fingerprint.ts +4 -4
  105. package/src/worker/live-query-manager.ts +12 -12
  106. package/src/worker/live-query-params-guard.ts +10 -10
  107. package/src/worker/protocol.ts +38 -7
@@ -2,12 +2,12 @@
2
2
  name: core
3
3
  description: >-
4
4
  Load when writing or reviewing code that uses @pgxsinkit/* — the offline-first sync toolkit for the
5
- Postgres -> Circuits engine -> durable-streams -> PGlite read path and the client -> write API ->
5
+ Postgres -> Circuits engine -> durable-streams -> pgwasm read path and the client -> write API ->
6
6
  Postgres write path. Teaches the model the source does not make obvious: the two sync paths are
7
7
  separate and asymmetric, exactly one write path (an in-database apply function, not per-table CRUD), a
8
8
  non-sync Event lane carries append-only facts, a client asks the control plane for its streams
9
9
  (controlPlaneUrl + streamBaseUrl, both or neither) and reads fail closed twice — 401 control plane, 403
10
- edge — local PGlite schema is not full DDL parity, writable tables must declare a conflict policy plus
10
+ edge — local pgwasm schema is not full DDL parity, writable tables must declare a conflict policy plus
11
11
  managed fields, ordinary writes self-activate their lazy group, and authenticated groups must not
12
12
  activate before claims exist. Load before wiring sync, defining a registry, adding an Event stream, or
13
13
  debugging "writes don't appear" / "an acked write stays pending" / "no rows stream" / "a removed
@@ -15,7 +15,7 @@ description: >-
15
15
  metadata:
16
16
  type: core
17
17
  library: "@pgxsinkit/client"
18
- library_version: "0.3.0"
18
+ library_version: "0.5.0"
19
19
  source: https://pgxsinkit.github.io/llms-full.txt
20
20
  ---
21
21
 
@@ -23,16 +23,16 @@ metadata:
23
23
 
24
24
  pgxsinkit is a **toolkit**, not a database, a framework, or the demo app. The `@pgxsinkit/*` packages
25
25
  are the product: `contracts` (the registry + shared types), `server` (the write API, the read path's
26
- **control plane**, and the **stream edge**), `client` (local PGlite store + mutation runtime +
26
+ **control plane**, and the **stream edge**), `client` (local pgwasm store + mutation runtime +
27
27
  convergence), and `react` (hooks). A consumer installs these and wires them; they do not "run pgxsinkit".
28
28
 
29
29
  ## The one idea everything else follows from: two separate, asymmetric sync paths
30
30
 
31
31
  - **Read path:** Postgres → the **Circuits engine** (ingests logical replication and maintains the shapes
32
- the control plane creates) → **durable-streams** → the **edge** (token-gated) → local **PGlite**. The
32
+ the control plane creates) → **durable-streams** → the **edge** (token-gated) → local **pgwasm**. The
33
33
  client does not
34
34
  construct a stream URL: it subscribes through the **control plane**, which decides which streams that
35
- subject may read and hands back their paths. Reads are served from PGlite.
35
+ subject may read and hands back their paths. Reads are served from the local pgwasm store.
36
36
  - **Write path:** client stages an optimistic local write → flushes a batch to the **write API** → one
37
37
  **in-database apply function** (`pgxsinkit_apply_mutations`) applies it under RLS → Postgres.
38
38
 
@@ -63,6 +63,48 @@ acked row **retires without a synced echo** (nothing local ever converges for it
63
63
  and throws at enqueue on an optimistic route. Never seed a phantom base row to satisfy `update` for an
64
64
  invisible target — that row + its overlay would linger forever behind the echo barrier; use `updateBlind`.
65
65
 
66
+ **Tables pgxsinkit does not manage are the one exception — and they never converge.** If your app owns a
67
+ LOCAL-ONLY relation the registry knows nothing about (a definition cache, a personal dictionary, a scratch
68
+ index), the write path above does not apply to it: there is no journal row, no overlay and no server to ack
69
+ it. Write it through the inspection surface — `rawExec(sql)` for a one-off, and `rawTransaction(statements)`
70
+ when several statements must land together:
71
+
72
+ ```ts
73
+ // Atomic replace of a local-only cache entry. One local transaction, all-or-nothing, one Results per
74
+ // statement; a throw rolls the whole list back, and `[]` resolves without opening a transaction at all.
75
+ const [, inserted] = await client.rawTransaction([
76
+ { sql: "delete from my_local_cache where key = $1", params: [key] },
77
+ { sql: "insert into my_local_cache (key, body) values ($1, $2) returning key", params: [key, body] },
78
+ ]);
79
+ ```
80
+
81
+ **Bulk-load a chunk with COPY, not an INSERT per row.** A statement may carry the COPY TEXT bytes of a
82
+ `COPY … FROM '/dev/blob'` — the same loader the sync applier uses on synced tables. Build the pair with
83
+ `buildCopyFromBlobStatement` (it renders the statement from the REAL Drizzle table object and serializes the
84
+ rows from ONE column list, so they cannot drift); `json`/`jsonb` values go in **parsed**, with the column's
85
+ `udt_name` in `udtNames`:
86
+
87
+ ```ts
88
+ // 1000 fetched rows → ONE statement, atomically replacing the chunk. `rawQuery(sql, [], { blob })` is the
89
+ // same load with no transaction around it.
90
+ const copy = buildCopyFromBlobStatement({
91
+ table: definitionCache, // a real drizzle pgTable your app owns — never a hand-written name
92
+ columns: ["id", "headword", "entry"],
93
+ rows: chunk, // keyed by DB column name; `entry` is a parsed object, not JSON text
94
+ udtNames: { entry: "jsonb" },
95
+ });
96
+ await client.rawTransaction([{ sql: "delete from definition_cache where id = any($1)", params: [ids] }, copy]);
97
+ // On a worker-attached client `copy.blob` is now DETACHED (transferred, not copied) — serialize a fresh
98
+ // chunk per call; never reuse the buffer.
99
+ ```
100
+
101
+ It is identical on the in-process and worker-attached client — the whole list crosses the bridge in ONE RPC
102
+ and the transaction opens and closes inside the worker — so a tab with no local store of its own gets the same
103
+ atomicity, rather than atomicity depending on where the engine happens to live. What it writes stays local
104
+ and will NEVER converge, so it is never a shortcut for a synced table: those still go through
105
+ `mutate` / `tables.*`. (Create such tables in `prepareLocalDbBeforeSchema` / `prepareLocalDbAfterSchema`, and
106
+ remember a `destroy()` or a backend change takes them with it.)
107
+
66
108
  ## The third lane: Event streams are NOT the write path
67
109
 
68
110
  High-volume, append-only client facts — "viewed this", interaction logs, review grades — are never edited,
@@ -90,10 +132,16 @@ appendEvent() → Outbox (durable, local-only) → flush → POST /api/events
90
132
  - The client-side surfaces are `onOutboxStatus` (drain signal) and `onEventLaneReport` (per-pass verdicts:
91
133
  `acked` / `refused` / `rejected` / `deferred`, of which only `deferred` is non-terminal). Flush cadence
92
134
  and batch caps are client config (`events`), never registry.
135
+ - **Composing a best-guess view? Pending is `acked_at_us IS NULL`, not "the row exists".** `acked` means
136
+ ENQUEUED, not folded — the consumer has not handled it and its result has not synced back down — so a
137
+ composition that drops the event at the ack dips for that whole window. `events.ackedRetentionMs > 0`
138
+ (default `0` = delete on ack) keeps an acked row, stamped, as a grace ledger you count until your own
139
+ synced aggregate accounts for it. A retained row is NOT pending anywhere: not on the drain signal, not
140
+ re-sent, not on `diagnostics()`, not blocking `destroy()`.
93
141
 
94
142
  ## Reading the local store: base table vs overlay view
95
143
 
96
- Reads run against local PGlite through the client, not hand-written SQL. For a **pure-Drizzle** read, pass
144
+ Reads run against the local pgwasm store through the client, not hand-written SQL. For a **pure-Drizzle** read, pass
97
145
  the builder callback directly to `client.query((c) => …)` (the guarded read): pgxsinkit scans the compiled
98
146
  SQL and activates + awaits every `lazy` relation the query touches (FROM, JOIN, subquery, WHERE) before it
99
147
  runs — nothing to declare. `client.query` resolves to the **rows array directly** (not `{ rows }`). Inside
@@ -225,7 +273,7 @@ RLS policy from the same Drizzle columns and they cannot drift.
225
273
 
226
274
  A subquery (membership) read filter — `p.in(col, p.subquery(…))` — is reactive in **both** directions,
227
275
  against a running client with no re-subscribe: granting a membership **materialises** the container's rows
228
- in the member's local PGlite; revoking one **evicts** them (a row reachable through a second membership
276
+ in the member's local store; revoking one **evicts** them (a row reachable through a second membership
229
277
  survives until its last grant is gone). The engine **states** each side rather than implying it: the wire
230
278
  carries `upsert | delete`, so a row leaving your shape arrives as an explicit `delete` envelope. This holds
231
279
  **live and across an offline gap** — a client disconnected when the membership changed converges on
@@ -233,12 +281,29 @@ reconnect (it resumes from its per-stream offset and replays what it missed), so
233
281
  access never lingers offline. Observe it on the live subscription or a normal resume, not by re-reading a
234
282
  stream from the start.
235
283
 
236
- ## Local PGlite schema is not full DDL parity
284
+ ## The local pgwasm schema is not full DDL parity
237
285
 
238
286
  The local store generates enums, tables, the overlay, the journal, and convergence triggers — **not**
239
287
  RLS, arbitrary triggers/functions, or managed-field defaults, and it does not enforce CHECK / FK /
240
288
  UNIQUE the way Postgres does. Treat Postgres as the source of truth for integrity; do not assume a
241
- constraint that holds server-side also holds in PGlite.
289
+ constraint that holds server-side also holds in the local store.
290
+
291
+ **Indexes are opt-in too.** A synced table gets its primary key's index and nothing else — the server's
292
+ indexes are deliberately not mirrored (they serve server loads and often cover projected-away columns).
293
+ A client read that needs an index declares it on the entry as
294
+ `clientProjection.localIndexes: [{ name, columns, unique? }]` (plain btree over projected columns,
295
+ validated at registry-build time). Index what the app actually scans — a due-window over a large synced
296
+ table is the usual first case — and nothing else; every index costs write time on each applied batch.
297
+
298
+ ## What a synced value looks like on the way in
299
+
300
+ The wire carries every non-int/float/bool cell as **Postgres output text** (json, arrays, timestamps,
301
+ uuid, numeric, bytea). The client parses exactly one family of it, once, at the wire boundary: a scalar
302
+ `json`/`jsonb` column becomes a JS value before any apply tier sees it, so the local column holds the
303
+ document — `jsonb_typeof` = `object`, not `string`. Array columns (json arrays included) stay in
304
+ Postgres's array literal and are handed straight back to Postgres. You read objects back out of the local store
305
+ either way; if you ever see a JSON **string** in a `jsonb` column, that is a double-encode bug, not the
306
+ shape of the data.
242
307
 
243
308
  ## Common mistakes
244
309
 
@@ -254,22 +319,22 @@ constraint that holds server-side also holds in PGlite.
254
319
  - Activating an authenticated lazy group before auth resolves — reading OR writing while claims are
255
320
  unresolved subscribes against anonymous claims (now flagged by a console warning), and the control plane
256
321
  grants nothing, so the group stays empty until it is desynced and referenced again.
257
- - Assuming PGlite enforces every Postgres constraint.
322
+ - Assuming the local store enforces every Postgres constraint.
258
323
  - Assuming a revoked member keeps their synced rows offline — membership changes converge both ways,
259
324
  live and on resume.
260
- - Passing a PGlite storage URL (`idb://…`, `memory://…`) as `storePath` — the contract is a plain
325
+ - Passing a storage URL (`idb://…`, `memory://…`) as `storePath` — the contract is a plain
261
326
  name and schemes throw; the backend is derived (ADR-0036).
262
327
 
263
328
  ## Naming the local store
264
329
 
265
- `createSyncClient`/`createClientPGlite` take a **plain `storePath`** (e.g. `"my-app-store"`), never a
330
+ `createSyncClient`/`createPgwasmClient` take a **plain `storePath`** (e.g. `"my-app-store"`), never a
266
331
  storage URL — the backend is derived, not named: a capability-proven browser engine home uses the
267
332
  constant-handle OPFS-repacked backend, fixed worker mode and browser fallbacks use IndexedDB, and bun/Node
268
333
  uses the filesystem; anything containing `://` throws `InvalidStorePathError`. Memory-backed stores are
269
334
  deliberately not expressible in the production API (pgxsinkit's retention + journal durability assume a
270
335
  persisted store): in TESTS, spread `memoryStoreForTests("name")` from `@pgxsinkit/client/testing` into the
271
- options; a caller-owned `pgliteInstance` that is provably non-persistent (a bare `new PGlite()`, or
272
- `memory://`) is refused with `NonPersistentStoreError` unless a testing acknowledgment is spread alongside.
336
+ options; a caller-owned `pgwasmInstance` that is provably non-persistent (a memory store, or a filesystem that
337
+ declares `persistent: false`; a custom filesystem that declares nothing is accepted) is refused with `NonPersistentStoreError` unless a testing acknowledgment is spread alongside.
273
338
  Separately from persistence, the store's flush **timing** is `durability`, declared once on the registry
274
339
  (`storage.durability`, default `"relaxed"`) — never a per-open, per-tab, or minting-surface option. Its
275
340
  physical behavior is backend-specific: idb detaches its whole-snapshot flush, while OPFS-repacked keeps the
@@ -4,18 +4,18 @@ description: >-
4
4
  Load when deploying or operating a pgxsinkit app, when a sync/write "feels slow" in a browser
5
5
  but the server is fast, or when wiring backups/export/restore. Covers the runtime/deployment
6
6
  properties (not toolkit bugs) deciding whether an app feels fast: convergence cadence (writes
7
- flush on enqueue; the interval is a fallback), serverless edge cold starts, the read path's cache
7
+ flush on enqueue; interval is a fallback), serverless edge cold starts, the read path's cache
8
8
  split (no-store control plane, cacheable edge on its own origin, token out of the cache key), the
9
9
  browser HTTP/2 connection budget, the edge worker timeout vs the durable-streams long-poll hold,
10
- globalThis.__pgxsinkitDebug + the BootReport, worker mode (defineSyncWorker/attachSyncClient —
10
+ globalThis.__pgxsinkitDebug + BootReport, worker mode (defineSyncWorker/attachSyncClient —
11
11
  capability-driven engine placement, relocation outcomes, the forwarded rail), the store lifecycle
12
12
  surface (storePath naming, durability, backend permanence, destruction, the three exports,
13
- restoreFrom), and Event-lane observability: onOutboxStatus, onEventLaneReport verdicts including
14
- deferred-on-skew, and the Outbox across destroy/restore/backup.
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.3.0"
18
+ library_version: "0.5.0"
19
19
  source: https://pgxsinkit.github.io/start/operating-in-production/
20
20
  ---
21
21
 
@@ -33,7 +33,7 @@ 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
39
  latency** (latency is bounded by the read-path echo). Do **not** shorten it to "make writes faster".
@@ -43,11 +43,14 @@ latency** (latency is bounded by the read-path echo). Do **not** shorten it to "
43
43
  `@durable-streams/client` holds **one live long-poll connection open per subscribed stream** (a subject in K
44
44
  scopes of a shared shape holds K streams), and browsers cap **HTTP/1.1 at ~6 connections per origin** — so over
45
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 even dispatched. This presents as
47
- multi-second writes invisible to `curl`/Node (no per-host cap); only a real browser shows it (DevTools → Network
48
- → a stuck `write` with a long **Stalled** time). Fix: serve the gateway over **HTTP/2** (or HTTP/3), which
49
- multiplexes every request over one connection. Any production ingress already does; it only bites a local stack
50
- on plain `http://` (browsers only negotiate HTTP/2 over TLS).
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
+
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.
51
54
 
52
55
  ## Serverless edge cold starts
53
56
 
@@ -67,31 +70,31 @@ edge wants to sit near the CALLER, so catch-up bytes take the short hop. `create
67
70
  merged over it on the write path only. Put the region header in `writeRequestHeaders`, never in the shared
68
71
  `requestHeaders`.
69
72
 
70
- ## Pre-warming PGlite's boot assets
73
+ ## Pre-warming the Postgres build
71
74
 
72
- A cold `PGlite.create` spends ~2.5s fetching + compiling the Postgres WASM (plus the initdb WASM and the
75
+ A cold store create spends ~2.5s fetching + compiling the Postgres WASM (plus the initdb WASM and the
73
76
  filesystem bundle) before it can open a store — otherwise paid **after** sign-in, on the path to first paint.
74
- `createSyncClient` takes a `pgliteBootAssets` option: a promise of the already-fetched/compiled assets
75
- (`{ pgliteWasmModule?, initdbWasmModule?, fsBundle? }`), awaited and passed straight into `PGlite.create` so
76
- it skips its own lazy load. Start the fetch+compile on an **earlier screen** and hand the pending promise in
77
- — the WASM cost then hides behind user think-time. It is best-effort: a rejected warm is caught to
78
- `undefined` and PGlite loads its own assets. The `boot pglite assets warm` rail stamp times it. (Board demo:
79
- `apps/board/src/board/pglite-warm.ts` shows the Vite `?url` pattern PGlite's `exports` field otherwise blocks.)
80
-
81
- **In worker mode the engine loads PGlite's OWN assets — deliberately; do not pre-supply them.** The tab's
82
- warm still serves the engine by priming the same-origin HTTP cache the worker fetches from. Handing the
83
- engine a pre-compiled `WebAssembly.Module` benched NET-NEGATIVE: it forces compile-to-completion before
84
- instantiate (forfeiting PGlite's streaming-load pipelining), and the engine realm's only overlap window is
85
- the placement/handshake gap, so the compile just competes for CPU at spawn.
86
-
87
- 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,
88
91
  which can't start until the store id is known (usually the signed-in user). To hide that too, create the
89
- store EAGERLY under a generated id on the first screen and BIND it at auth. `createClientPGlite(storePath,
90
- { bootAssets })` runs the exact same create the client does internally and returns a schemaless instance;
91
- hand the still-pending promise to `createSyncClient`'s `precreatedPglite`. Unlike `pgliteInstance` (caller
92
- 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
93
96
  store-version reconcile — so the eager create buys only `initdb`, and the role/registry-derived schema stays
94
- 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
95
98
  accelerator, never a boot dependency. Bind eager stores to users with a small localStorage registry
96
99
  (userId→storeId plus one unbound "spare"): create a spare on the login screen, claim it at sign-in, GC any
97
100
  store that is neither mapped nor the spare. On a signed-in RELOAD there is no login screen to create ahead of,
@@ -100,7 +103,7 @@ later open adopts it. (Board demo: `store-registry.ts`, `store-prewarm.ts`.)
100
103
 
101
104
  ## Worker mode: capability-placed off-thread engine (browser apps)
102
105
 
103
- 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
104
107
  thread. The SharedWorker is always the communication centre. There is no placement option: where the engine
105
108
  runs is a runtime capability decision. Under the default `storage.backend: "opfs"`, an unconditional real
106
109
  synchronous-handle open at boot chooses the engine home — real macOS/iOS Safari runs the OPFS-repacked engine
@@ -147,23 +150,23 @@ One-shot reads (`query`/`queryRow`/`queryRaw`/`queryRawRow`) compile on the tab
147
150
  guarded round trip — the worker runs the read gate + lazy-group guard, then Drizzle's own mapping runs back
148
151
  on the tab, so results match the in-process client exactly. A bare awaited `client.drizzle` builder is ALSO
149
152
  guarded here, and `client.drizzle.transaction()` throws (no tab-local store). `ensureSynced` is proxied
150
- (additive, idempotent); `isSynced` throws — it is a SYNCHRONOUS activation-started peek the tab's cached
151
- catch-up readiness cannot answer (use `groupReady` for catch-up, `ensureSynced` to activate). Local `pglite`
152
- and `dropReadCache` are NOT proxied (no tab-local store; a cache rebuild is engine-wide). `destroy()` IS
153
- 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
154
157
  rows unless `{ force: true }`, retires/closes the engine, then runs a resumable deletion. The lazy lifecycle
155
- methods ARE proxied, but the engine is SHARED: `desync(tableKey)` from one tab reverts the consistency group
156
- for EVERY attached tab (the footgun). For an ephemeral delivery window use `discardEphemeral(tableKey)`
157
- instead — the scoped, multi-tab-safe finalize (drops the ephemeral rows, reverts to dormant, refuses a group
158
- with any persistent member), safe under a shared engine because an ephemeral window is per-delivery-session
159
- and single-consumer. The exception is the INSPECTION surface `rawQuery(sql, params)` / `rawExec(sql)` (debug
160
- pages, REPLs, ad-hoc counts): identical on both clients (executed in the worker on the attach client), it
161
- runs raw against the local store — bypassing the journal/overlay, any write staying local and never
162
- converging — so it is not an app-data read path. `replAdapter(client)` shapes it into the `{ query, exec }`
163
- duck `@electric-sql/pglite-repl` needs. A worker file can bake multiple role variants and pick per attach via
164
- `resolveRegistry(role)` + the tab's `role`, and can pass the schema prepare hooks
165
- `prepareLocalDbBeforeSchema` / `prepareLocalDbAfterSchema` (app migrations, indexes, views) — worker-entry,
166
- 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.
167
170
 
168
171
  **Identity switches do not wait for worker retirement.** Scope each worker identity by `storePath` with a
169
172
  distinct, stable SharedWorker name; multiple stores may remain alive concurrently. Detach/stop the old client
@@ -222,7 +225,7 @@ start), then raises `ProvisionStalledError` — rebind to a fresh store; it boun
222
225
  ## Live-query manager: dedup + keep-alive (ADR-0040)
223
226
 
224
227
  Every reactive read (`useLiveDrizzleRows`/`useLiveQueryRaw`/`subscribeLiveRows`) is a **local SQL live
225
- 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
226
229
  is a real cost (~a few hundred ms for a heavy aggregate) and is **automatically deduplicated** — identical
227
230
  queries (keyed on executed SQL + bound params, NOT `use`) share ONE registration and ONE re-run + diff per
228
231
  write, fanned to every subscriber, so N components (or N tabs on the shared worker) cost one materialisation.
@@ -236,7 +239,7 @@ exists on `createSyncClient`). The effective keep-alive is `max(default, subscri
236
239
  budgets outrank any hint and LRU-evict zero-subscriber entries; active entries are never evicted.
237
240
 
238
241
  **Keep the default 0 unless you have a specific hot query.** A retained zero-subscriber query is NOT paused
239
- (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
240
243
  held: retention wins only for a frequently-re-mounted, write-COLD query. For a fixed hot set the endorsed
241
244
  "permanent" pattern is a **mounted subscriber** (a root-provider hook that never unmounts) — one live
242
245
  registration for the app's life, every route dedups onto it; there is deliberately no retain-forever knob.
@@ -253,9 +256,9 @@ main-thread fallback use IndexedDB; bun/Node uses the filesystem. Anything conta
253
256
  `InvalidStorePathError` — drop the scheme, don't re-add it. Memory-backed stores are deliberately unreachable
254
257
  from the production API (durability semantics assume a persisted store): tests spread
255
258
  `memoryStoreForTests("name")` from `@pgxsinkit/client/testing`, and a caller-owned
256
- `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
257
260
  refused with `NonPersistentStoreError` unless `testStoreAcknowledgment()` is spread alongside. For browser
258
- 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/…`.
259
262
 
260
263
  **Relaxed durability is the default**, declared once on the registry
261
264
  (`SyncRegistryDefinition.storage.durability`) — never on a minting surface, worker entry or attach site,
@@ -265,7 +268,7 @@ snapshot flush and schedules it asynchronously while strict pays that synchronou
265
268
  optimistic mutation); on OPFS-repacked the host still awaits every sync, with relaxed asserting VFS health
266
269
  and running any due deferred repack without an ordinary physical flush while strict flushes arena data
267
270
  before metadata (initialization, repack activation and open-state close use strict ordering either way).
268
- 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.
269
272
 
270
273
  **The idb loss window.** On idb the store is an in-memory FS with debounced whole-snapshot writes, so
271
274
  `relaxed`'s window is every write since the last COMPLETED snapshot. The risk lands only on a crash before
@@ -281,8 +284,8 @@ browser-failure model — do not generalize it to power loss, media failure, or
281
284
  as a transferred buffer):
282
285
 
283
286
  - `exportStore()` — the **store backup**: a live, checkpointed `dumpDataDir` tarball of the WHOLE store,
284
- journal and overlay included. Never blocks, works offline with unflushed writes; restorable ONLY into
285
- 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.
286
289
  - `exportDiagnostics()` — everything as SQL (synced + overlay + journal + views/functions + the `pgxsinkit`
287
290
  schema) for support evidence. Never blocks; not for restoring.
288
291
  - `exportData({ drainJournal? })` — the **portable** SQL (synced tables + their enum types, nothing of
@@ -353,47 +356,46 @@ retry wins. Dynamic declarations travel as the wire `storage` option on
353
356
  `attachSyncClient`/`provisionSyncWorker`; a registry-attached static declaration stays authoritative.
354
357
  Consumer docs: <https://pgxsinkit.github.io/concepts/local-store-lifecycle/>.
355
358
 
356
- ## Event lane: observing the Outbox (ADR-0053)
357
-
358
- If your registry declares `streams`, `client.appendEvent(stream, payload)` stages a fire-and-forget fact in
359
- the **Outbox** — a durable, local-only table, never synced, overlaid or conflict-resolved. It resolves on
360
- **durable local enqueue, not on delivery**, so it never blocks on the network and an append made offline
361
- survives a reload. Two observation surfaces, identical on both client forms:
362
-
363
- - **`onOutboxStatus(cb)` — the drain signal.** `{ empty }`, fired on the empty ↔ non-empty **transitions**,
364
- current state delivered on subscribe (`await client.outboxStatus()` is the one-shot pull twin). It is the
365
- invalidation hook for a best-guess view composing pending events with down-synced aggregates: when the
366
- Outbox drains, the aggregate is authoritative again. It carries **no count** deliberately (one updated only
367
- on transitions is stale by construction) — query `getOutboxTable(registry)` when you need one.
368
- - **`onEventLaneReport(cb)` — the verdicts.** Per flush pass: terminal non-`acked` verdicts, `deferred` ones,
369
- and batch-level backoff transitions. `acked` is never reported (a high-volume lane would drown you), and it
370
- is **EPHEMERAL** — with **nothing subscribed the library warn-logs each report**. Subscribe for the app's
371
- lifetime: once a row is deleted the Outbox cannot answer for it.
372
-
373
- **Read the verdicts correctly — one of the four is not a failure.** `acked` is enqueued server-side. `refused`
374
- (your `eventGate` said no) and `rejected` are **terminal**: the row is deleted, and `refused` is expected, not
375
- an error. `rejected` has THREE causes on a KNOWN stream — a payload the schema refuses (or a parse output JSON
376
- cannot carry), an oversized payload, and an **identity claim the stream declares that the verified claims
377
- cannot resolve** (absent/null/object/array/empty — fail-closed, no partial stamp). The first two mean a
378
- non-library caller or a broken deployment (the library validates at append) — a **bug**; the third means the
379
- ISSUER stopped minting that claim, or moved its path. `deferred` is **NOT terminal**: the server does not
380
- (yet) know that stream — rollout skew — so the rows stay, retry with backoff, and drain once the deploy lands.
381
- A burst after a release is deploy order; one that never clears means the registry LACKS it.
382
-
383
- **There is no attempt cap and no client-side quarantine, by design.** Retry has two classes: retryable
384
- (network, 5xx, 408/425/429 — jittered backoff with a ceiling, honouring `Retry-After`, paused offline) and
385
- auth (refresh once, then retryable). A row leaves the Outbox **only** on a server-issued per-event verdict,
386
- so a stuck lane is a growing Outbox with backoff transitions on the report, never silent loss. A persistent
387
- **503 / batch backoff** is the OTHER diagnosis — the server KNOWS the stream but could not enqueue the whole
388
- batch: check the `--events` migration is applied (no queue, no enqueue), then DB reachability. Cadence/batch
389
- caps are client config (`events`, validated at construction — a bad `batchSize` throws instead of wedging a
390
- stream), clamped by the contracts limits; `flushEvents()` is the manual hatch without `autoSync`.
391
-
392
- **The Outbox on every lifecycle surface** (durable owned state): `destroy()` **refuses** while it is
393
- non-empty, exactly as on owed mutations — the refusal names which of the two blocked it, and `{ force: true }`
394
- is the escape hatch. `dropReadCache()` never touches it (not read cache). `exportStore()` and
395
- `exportDiagnostics()` include it; `exportData()` (synced tables only) excludes it. And **restore does NOT
396
- 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
397
399
  normally, because event delivery is idempotent end-to-end (`eventId` dedupe), which mutation replay is not.
398
400
 
399
401
  ## The read path's cache split: uncacheable control plane, cacheable edge
@@ -415,9 +417,9 @@ entitlement-propagation latency.
415
417
  **Every `createStreamGate` mount must set `Access-Control-Expose-Headers` from the exported
416
418
  `STREAM_READ_EXPOSED_HEADERS`.** CORS lets script read only a short safelist, and every header durable-streams
417
419
  answers with is outside it, so a cross-origin browser gets a response whose stream headers are simply not there:
418
- `@durable-streams/client` steers its read loop off them, never learns an offset, and re-requests from the
419
- start in a hot loop, with no error raised on either side. It presents as "sync does nothing, and the console
420
- is clean". Mount details: the `deploying` skill.
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
 
@@ -433,39 +435,37 @@ sent/acked lines); `convergence pass requested (event-driven, …)` → `converg
433
435
  reconcile`; `flushBatch sending to board-write`; `board-write auth token resolved {ms}` (a stalling token
434
436
  fetch); `board-write responded {status, ms}` (a cold worker or a connection stall); `board-write acks`; and
435
437
  `live-query register|dedup-hit|retained|evicted|teardown-complete` (digests only). **The read path emits no rail
436
- lines** — its cost is routing latency rather than phases, so read it off the `BootReport`'s per-group rows
437
- (below) and off `status` / `status.lastError` (`degraded`/stream = subscribe failing or the stream silent;
438
- `auth-needed` = the control plane refused this credential), and inspect the real requests in the worker's own
439
- DevTools. Server-side, `createSyncServer({ logTimings: true })` emits matching `[pgxsinkit-timing]` lines (the
440
- `deploying` skill); client-observed minus server `totalMs` isolates routing + network. Boot too: `boot
441
- pglite.create` → `boot client ready` (store open, schema apply, journal recovery, store-version reconcile, sync
442
- start) attributes a slow first paint to a phase; `boot pglite assets warm` times the optional pre-warm.
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.
443
444
 
444
445
  **Structured boot numbers — the `BootReport`.** The rail is for a human reading a console; for
445
446
  machine-keepable numbers (dashboards, CI budget gates) every boot ALSO builds a versioned `BootReport`,
446
447
  independently of the rail so it exists whether or not the flag is on (ADR-0034). Read it by push
447
448
  (`onBootReport?: (report) => void`, fires once at boot completion) or pull (`await client.bootReport()` → the
448
- most recent completed boot, `null` before the first sync; in worker mode it round-trips to the worker's
449
- stored report, so a late tab reads a boot that predates it). It carries `totalMs`, decomposed `phases`, and a
450
- 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
451
452
  `fetchMs` is an UPPER BOUND on network wait and concurrent `applyMs` can overlap — never sum them into a
452
453
  `totalMs` partition; and a non-null `provision` block is a spare's off-thread `initdb` made visible (then
453
- `phases.pgliteCreateMs` is `null`).
454
-
455
- **How a group decides to commit (ADR-0056), and the one state that is terminal.** There is **no commit floor**
456
- and no cross-shape position comparison — offsets are per-stream and comparable only within one — so a group
457
- commits when **every** one of its shapes' most recent responses asserted up-to-date (a quiet shape re-asserts
458
- freshness on every `204` long-poll timeout). Atomic at boot/catch-up alignment; LIVE deliveries commit per
459
- response, so two halves of one transaction can land milliseconds apart (backlog 0014). The **first**
460
- commit of each alignment generation (boot, and after any must-refetch) also reads the engine's convergence
461
- barrier through the control plane's `/sync/v1/barrier`, aligning only with `pendingFlips` at zero — no computed
462
- membership revocation still undelivered. A barrier the client cannot READ is a delay: the group stays on the
463
- pre-alignment gate and retries. `flipFailures > 0` is **terminal**: the engine abandoned membership-flip
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
464
  batches, those effects are lost, and the client refuses to align and goes `degraded` rather than waiting —
465
465
  restart the engine and re-subscribe. Full prose: <https://pgxsinkit.github.io/start/operating-in-production/>.
466
466
 
467
- **Measure at the network boundary, not by polling PGlite.** Each PGlite query is ~50ms on one thread, so
468
- a tight `setInterval` reading PGlite to "watch" a value inflates the very latency it reports. Trust the
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
469
469
  instrumentation's network timings and a server-side `curl` over a poll loop.
470
470
 
471
471
  **Inspecting a stuck or failed write.** To see _why_ a write is not converging — journal status,
@@ -487,12 +487,12 @@ a real rollback, route a permanent policy denial to `quarantined` — never mis-
487
487
 
488
488
  - Shortening the convergence interval to chase write latency (no effect; wastes CPU).
489
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
491
- omitting `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/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.
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