@pgxsinkit/client 0.1.32 → 0.1.40

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 (111) hide show
  1. package/README.md +11 -0
  2. package/dist/boot-report.d.ts +134 -0
  3. package/dist/boot-report.d.ts.map +1 -0
  4. package/dist/convergence.d.ts +76 -0
  5. package/dist/convergence.d.ts.map +1 -0
  6. package/dist/debug.d.ts +34 -0
  7. package/dist/debug.d.ts.map +1 -0
  8. package/dist/export-data.d.ts +100 -0
  9. package/dist/export-data.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts +92 -0
  11. package/dist/export-dump.d.ts.map +1 -0
  12. package/dist/export-store.d.ts +214 -0
  13. package/dist/export-store.d.ts.map +1 -0
  14. package/dist/index.d.ts +615 -8
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8083 -2286
  17. package/dist/index.js.map +81 -44
  18. package/dist/lazy-guard.d.ts +59 -0
  19. package/dist/lazy-guard.d.ts.map +1 -0
  20. package/dist/lifecycle-slot.d.ts +31 -0
  21. package/dist/lifecycle-slot.d.ts.map +1 -0
  22. package/dist/live-rows-sql.d.ts +21 -0
  23. package/dist/live-rows-sql.d.ts.map +1 -0
  24. package/dist/local-store.d.ts +56 -0
  25. package/dist/local-store.d.ts.map +1 -0
  26. package/dist/local-tables.d.ts +707 -0
  27. package/dist/local-tables.d.ts.map +1 -0
  28. package/dist/mutation-state.d.ts +69 -0
  29. package/dist/mutation-state.d.ts.map +1 -0
  30. package/dist/mutation.d.ts +129 -4
  31. package/dist/mutation.d.ts.map +1 -1
  32. package/dist/schema.d.ts +82 -0
  33. package/dist/schema.d.ts.map +1 -1
  34. package/dist/shape-sync.d.ts +190 -0
  35. package/dist/shape-sync.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +132 -0
  37. package/dist/store-path.d.ts.map +1 -0
  38. package/dist/sync/apply.d.ts +51 -0
  39. package/dist/sync/apply.d.ts.map +1 -0
  40. package/dist/sync/copy.d.ts +43 -0
  41. package/dist/sync/copy.d.ts.map +1 -0
  42. package/dist/sync/drizzle-executor.d.ts +5 -0
  43. package/dist/sync/drizzle-executor.d.ts.map +1 -0
  44. package/dist/sync/index.d.ts +32 -0
  45. package/dist/sync/index.d.ts.map +1 -0
  46. package/dist/sync/metadata-tables.d.ts +131 -0
  47. package/dist/sync/metadata-tables.d.ts.map +1 -0
  48. package/dist/sync/nudge.d.ts +49 -0
  49. package/dist/sync/nudge.d.ts.map +1 -0
  50. package/dist/sync/shape-inbox.d.ts +215 -0
  51. package/dist/sync/shape-inbox.d.ts.map +1 -0
  52. package/dist/sync/subscription-state.d.ts +39 -0
  53. package/dist/sync/subscription-state.d.ts.map +1 -0
  54. package/dist/sync/tags.d.ts +130 -0
  55. package/dist/sync/tags.d.ts.map +1 -0
  56. package/dist/sync/types.d.ts +126 -0
  57. package/dist/sync/types.d.ts.map +1 -0
  58. package/dist/sync-auth.d.ts +53 -0
  59. package/dist/sync-auth.d.ts.map +1 -0
  60. package/dist/testing.d.ts +27 -0
  61. package/dist/testing.d.ts.map +1 -0
  62. package/dist/testing.js +17 -0
  63. package/dist/testing.js.map +11 -0
  64. package/dist/worker/attach-sync-client.d.ts +96 -0
  65. package/dist/worker/attach-sync-client.d.ts.map +1 -0
  66. package/dist/worker/define-sync-worker.d.ts +76 -0
  67. package/dist/worker/define-sync-worker.d.ts.map +1 -0
  68. package/dist/worker/live-diff.d.ts +44 -0
  69. package/dist/worker/live-diff.d.ts.map +1 -0
  70. package/dist/worker/protocol.d.ts +341 -0
  71. package/dist/worker/protocol.d.ts.map +1 -0
  72. package/dist/worker/token-cache.d.ts +26 -0
  73. package/dist/worker/token-cache.d.ts.map +1 -0
  74. package/oxlint-plugin.js +143 -0
  75. package/package.json +20 -7
  76. package/skills/core/SKILL.md +210 -0
  77. package/skills/operating/SKILL.md +303 -0
  78. package/src/boot-report.ts +287 -0
  79. package/src/convergence.ts +197 -0
  80. package/src/debug.ts +151 -0
  81. package/src/export-data.ts +300 -0
  82. package/src/export-dump.ts +239 -0
  83. package/src/export-store.ts +309 -0
  84. package/src/index.ts +1652 -51
  85. package/src/lazy-guard.ts +135 -0
  86. package/src/lifecycle-slot.ts +66 -0
  87. package/src/live-rows-sql.ts +45 -0
  88. package/src/local-store.ts +193 -0
  89. package/src/local-tables.ts +546 -0
  90. package/src/mutation-state.ts +99 -0
  91. package/src/mutation.ts +1910 -562
  92. package/src/schema.ts +472 -28
  93. package/src/shape-sync.ts +498 -0
  94. package/src/store-path.ts +249 -0
  95. package/src/sync/apply.ts +530 -0
  96. package/src/sync/copy.ts +206 -0
  97. package/src/sync/drizzle-executor.ts +48 -0
  98. package/src/sync/index.ts +1087 -0
  99. package/src/sync/metadata-tables.ts +67 -0
  100. package/src/sync/nudge.ts +110 -0
  101. package/src/sync/shape-inbox.ts +566 -0
  102. package/src/sync/subscription-state.ts +135 -0
  103. package/src/sync/tags.ts +365 -0
  104. package/src/sync/types.ts +141 -0
  105. package/src/sync-auth.ts +117 -0
  106. package/src/testing.ts +53 -0
  107. package/src/worker/attach-sync-client.ts +653 -0
  108. package/src/worker/define-sync-worker.ts +762 -0
  109. package/src/worker/live-diff.ts +140 -0
  110. package/src/worker/protocol.ts +425 -0
  111. package/src/worker/token-cache.ts +84 -0
@@ -0,0 +1,210 @@
1
+ ---
2
+ name: core
3
+ description: >-
4
+ Load when writing or reviewing code that uses @pgxsinkit/* (client, server, contracts, react) — the
5
+ offline-first sync toolkit for the Postgres -> ElectricSQL -> PGlite read path and the client -> write
6
+ API -> Postgres write path. Teaches the mental model the source does not make obvious: the two paths
7
+ are separate and asymmetric, there is exactly one write path (an in-database apply function, not
8
+ per-table CRUD), the Electric subquery flag is mandatory and fails closed, local PGlite schema is not
9
+ full DDL parity, and writable tables must declare a conflict policy plus managed fields. Load this
10
+ before wiring sync, defining a registry, or debugging "writes don't appear" / "no rows stream" / "a
11
+ removed member still sees rows".
12
+ metadata:
13
+ type: core
14
+ library: "@pgxsinkit/client"
15
+ library_version: "0.1.40"
16
+ source: https://pgxsinkit.github.io/llms-full.txt
17
+ ---
18
+
19
+ # Using pgxsinkit correctly
20
+
21
+ pgxsinkit is a **toolkit**, not a database, a framework, or the demo app. The `@pgxsinkit/*` packages
22
+ are the product: `contracts` (the registry + shared types), `server` (the write API + Electric shape
23
+ proxy), `client` (local PGlite store + mutation runtime + convergence), and `react` (hooks). A consumer
24
+ installs these and wires them; they do not "run pgxsinkit".
25
+
26
+ ## The one idea everything else follows from: two separate, asymmetric paths
27
+
28
+ - **Read path:** Postgres → ElectricSQL → a server-side shape **proxy** (ownership-filtered) → local
29
+ **PGlite**. Reads are served from PGlite.
30
+ - **Write path:** client stages an optimistic local write → flushes a batch to the **write API** → one
31
+ **in-database apply function** (`pgxsinkit_apply_mutations`) applies it under RLS → Postgres.
32
+
33
+ **Writes do not travel back to the writer through Electric.** The loop closes through Postgres: your
34
+ write lands in Postgres, then streams back to _every_ subscriber (including you) as a normal Electric
35
+ change, which clears the optimistic overlay. Do not look for a write to "come back" on the write
36
+ channel, and do not try to write through Electric — Electric is read-only here.
37
+
38
+ ## There is exactly one write path
39
+
40
+ There is no per-table CRUD API and no selectable backend. Every mutation — create, update, delete —
41
+ goes through `POST /api/mutations` and is applied by the single in-database function. You provision that
42
+ function once from your registry with the `pgxsinkit-generate` CLI (a drizzle-kit migration). Do not
43
+ invent REST endpoints per table; do not write to Postgres tables directly from the client.
44
+
45
+ **Blind update — writing a row your read shape excludes.** A pessimistic write unit
46
+ (`client.transaction({ mode: "pessimistic" }, (tx) => …)`) flush-routes to the authoritative endpoint and
47
+ resolves with each member's `acked` / `conflicted` / `rejected` outcome. Alongside `create`/`update`/`delete`
48
+ its handles carry **`updateBlind(entityKey, patch)`**: an update-by-key for a target your own read shape
49
+ excludes (a write-only flow, or an anonymity-scoped moderation write whose row streams only to a different
50
+ projection). Ordinary `update` requires the entity in the local read model (to seed the overlay + capture the
51
+ base version); `updateBlind` skips that — it plans a **journal row only**, writes **no overlay**, and the
52
+ acked row **retires without a synced echo** (nothing local ever converges for it). It is **pessimistic-only**
53
+ and throws at enqueue on an optimistic route. Never seed a phantom base row to satisfy `update` for an
54
+ invisible target — that row + its overlay would linger forever behind the echo barrier; use `updateBlind`.
55
+
56
+ ## Reading the local store: base table vs overlay view
57
+
58
+ Reads run against local PGlite through the client, not hand-written SQL. For a **pure-Drizzle** read, pass
59
+ the builder callback directly to `client.query((c) => …)` (the guarded read): pgxsinkit scans the compiled
60
+ SQL and activates + awaits every `lazy` relation the query touches (FROM, JOIN, subquery, WHERE) before it
61
+ runs — nothing to declare. `client.query` resolves to the **rows array directly** (not `{ rows }`). Inside
62
+ the callback, reach relations through a directly-imported synced table/view object, `c.drizzle`, or
63
+ `c.views`. Only when the builder embeds a raw ``sql`…` `` fragment (which the scan can miss) use
64
+ `client.queryRaw({ use, build })` and name those relations in `use`. `queryRow` / `queryRawRow` are the
65
+ first-row-or-null variants. (Reactive equivalents: `useLiveDrizzleRows` for pure reads,
66
+ `useLiveQueryRaw({ use, build })` for raw fragments.)
67
+
68
+ **Lint the split.** `@pgxsinkit/client` ships an oxlint rule via its `./oxlint` subpath export. Enable it
69
+ in the consuming repo's `.oxlintrc.jsonc` — `"jsPlugins": ["@pgxsinkit/client/oxlint"]` +
70
+ `"pgxsinkit/guarded-query-purity": "error"` — to catch a raw ``sql`…` `` fragment on the pure path and a
71
+ redundant `use` (autofixable), the two things the types can't. (oxlint `jsPlugins` is alpha.)
72
+
73
+ **The non-obvious rule — which relation to select FROM:**
74
+
75
+ - A **readonly** entry syncs only its **base table**. Read it from the entry's **`.table`**
76
+ (`registry.<name>.table`). There is no overlay.
77
+ - A **readwrite** entry also generates a `_read_model` **overlay view** that merges your own optimistic
78
+ (not-yet-synced) writes on top of the synced base rows. Read it from the entry's **`.view`**
79
+ (`registry.<name>.view`) — **not** its `.table`. Selecting the base `.table` of a readwrite entry
80
+ silently omits the writer's own pending writes, so a just-issued create/edit/delete will not appear
81
+ locally until it round-trips through Postgres and streams back via Electric.
82
+
83
+ ```ts
84
+ // readonly entry → base table
85
+ client.query((c) => c.drizzle.select({ id: catalogResource.table.id }).from(catalogResource.table));
86
+
87
+ // readwrite entry → overlay view, so your own optimistic writes are included
88
+ const reportView = registry.report.view!; // `.view` is populated only for readwrite entries
89
+ client.query((c) => c.drizzle.select({ id: reportView.id, status: reportView.status }).from(reportView));
90
+ ```
91
+
92
+ This is the read-side twin of "writes return through Electric": your optimistic write is visible
93
+ immediately **only because you read the overlay view**; the base table catches up when Postgres streams the
94
+ committed row back. (`c.views.<name>` is the client's accessor for the same overlay views; the entry's
95
+ `.view` object is the direct handle. Type note: `.view` is typed as optional on a `SyncTableEntry`, so a
96
+ non-null assertion — `registry.<name>.view!` — is expected at the read site.)
97
+
98
+ **Reaching the generated relations directly (factories).** For **diagnostics, tests, and tooling** — not
99
+ app code — `@pgxsinkit/client` exports a typed factory per generated relation so you author Drizzle instead
100
+ of hand-written SQL against `<t>_overlay` / `<t>_mutations` / `<t>_sync_state` / `<t>_read_model`:
101
+ `getSyncedLocalTable`, `getOverlayTable`, `getJournalTable`, `getSyncStateView`, `getReadModelView`,
102
+ `getLocalMetaTable` (all `(registry, tableKey)`; overlay/journal/sync-state/read-model are writable-only).
103
+
104
+ ```ts
105
+ import { getOverlayTable, getSyncStateView } from "@pgxsinkit/client";
106
+ const overlay = getOverlayTable(registry, "report"); // typed by property key: overlay.id, overlay.overlayKind
107
+ db.select({ pending: getSyncStateView(registry, "report").pendingCount }).from(getSyncStateView(registry, "report"));
108
+ ```
109
+
110
+ Why the factories (vs the entry handles): `entry.table` / `entry.localTable` are already schema-qualified
111
+ (built with the registry's schema, enforced to match it), so for the synced cache the factory only tracks
112
+ a `clientProjection.syncedTable` rename. But `entry.view` (the `_read_model` view) is built **unqualified**
113
+ — a non-public local schema _must_ read it via `getReadModelView` — and `_overlay` / `_mutations` /
114
+ `_sync_state` have **no entry handle at all**. All factory objects carry the registry's local schema and
115
+ memoize per `(registry, tableKey)` (`getLocalMetaTable` per local schema). Typing follows the registry — a
116
+ concretely-typed registry gives real per-column types (`overlay.col`, `$inferInsert`, `.values()` all
117
+ typecheck), a bare `SyncTableRegistry` degrades to bracket access (`overlay["col"]`). `getJournalTable` /
118
+ `getSyncStateView` are **always** conservatively indexed for entity/PK columns, but key them differently:
119
+ the journal by **DB column name** (`journal["author_id"]`), the sync-state view by the entry's **property
120
+ key** (`syncState["authorId"]`); the fixed runtime/state columns stay typed on both.
121
+ **In app code prefer the guarded `client.query`** — the factories are for reading the generated relations
122
+ directly (a test, a perf harness, a diagnostic), not a replacement for it.
123
+
124
+ ## Non-negotiables (each fails closed or throws)
125
+
126
+ 1. **The Electric subquery flag is mandatory.** Run Electric with
127
+ `ELECTRIC_FEATURE_FLAGS=allow_subqueries,tagged_subqueries`. Without it, sync **fails closed** — no
128
+ rows stream — which looks like a bug but is a missing flag. On **managed Electric Cloud** the flag is
129
+ activated per source by Electric staff on request (no self-serve toggle yet; default-on intended) —
130
+ ask Electric to enable subqueries for your source, or self-host Electric with the flag.
131
+ 2. **Writable tables have two hard requirements.** `defineSyncRegistry` throws unless every `readwrite`
132
+ table declares **both** a server-version managed field (a `nowMicroseconds`-on-update column,
133
+ conventionally `updated_at_us`, that optimistic convergence keys on) **and** a `conflictPolicy`
134
+ (`reject-if-stale` | `last-write-wins`). There is no silent default — a silent last-write-wins is the
135
+ exact data loss the choice exists to surface.
136
+ 3. **Managed fields are server-assigned.** Fields stamped by `authClaim` (a verified claim at a JSON path —
137
+ `["sub"]` is the old `auth.uid()` owner idiom) / `nowMicroseconds` are set by the apply function; the
138
+ write API **rejects** a client payload that includes them. Never send them.
139
+ 4. **Enum columns in a shape `where` must be cast to `text`** — `"role"::text = 'manager'`, not
140
+ `"role" = 'manager'`. The column stays an enum everywhere else. This is because **Electric**, not
141
+ Postgres, evaluates the shape filter.
142
+
143
+ ## Authorization runs in two engines — derive both from one predicate
144
+
145
+ A row must never be readable-but-unwritable (or the reverse). The two paths enforce auth in different
146
+ engines, so the subject is referenced two ways:
147
+
148
+ - **Write path — RLS in Postgres:** policies use `auth.uid()` / `current_setting('request.jwt.claims')`;
149
+ the applier sets the claims before applying a batch.
150
+ - **Read path — the shape `rowFilter`:** the proxy builds the Electric `where` and **Electric** runs it, so
151
+ a `customWhere` returns a Drizzle `SQL` fragment — reference columns through `c()` (bare, as Electric
152
+ needs) and bind `claims.sub` as a `$n` param (no hand-escaping); enum cast to `text`; `DENY_ALL` blocks
153
+ all rows.
154
+
155
+ Use `buildSupabaseOwnerOrAdminNativePolicies` / `buildSupabaseMembershipNativePolicies` for the common
156
+ owner/membership shapes — they take **Drizzle columns**, so call them in `defineSyncTable`'s `extras`
157
+ callback; compose your own from `pgPolicy` + Drizzle operators for anything beyond them (e.g. collaborative
158
+ any-member writes). Build the read filter and the RLS policy from the same Drizzle columns so they cannot
159
+ drift.
160
+
161
+ ## Membership changes converge the local store — both ways, even offline
162
+
163
+ A subquery (membership) read filter is reactive in **both** directions, against a running client with no
164
+ re-subscribe: granting a membership **materialises** the container's rows in the member's local PGlite;
165
+ revoking one **evicts** them (a row reachable through a second membership survives until its last grant is
166
+ gone). This holds **live and across an offline gap** — a client disconnected when the membership changed
167
+ converges on reconnect (the resume replays it), so a revoked member's read access never lingers offline.
168
+ Observe it on the live subscription or a normal resume, not by re-probing a shape at `offset=-1`.
169
+
170
+ ## Local PGlite schema is not full DDL parity
171
+
172
+ The local store generates enums, tables, the overlay, the journal, and convergence triggers — **not**
173
+ RLS, arbitrary triggers/functions, or managed-field defaults, and it does not enforce CHECK / FK /
174
+ UNIQUE the way Postgres does. Treat Postgres as the source of truth for integrity; do not assume a
175
+ constraint that holds server-side also holds in PGlite.
176
+
177
+ ## Common mistakes
178
+
179
+ - Expecting an optimistic write to echo back on the write channel — it returns through Electric.
180
+ - Forgetting the Electric subquery flag, then debugging "no rows" as a code bug.
181
+ - Omitting `conflictPolicy` (throws) or sending a managed field in a write payload (rejected).
182
+ - Comparing an enum without `::text` in a shape filter.
183
+ - Writing directly to Postgres tables / building per-table CRUD instead of using the one write path.
184
+ - Reading a **readwrite** entry from its base `.table` instead of its `.view` overlay, so your own
185
+ optimistic writes do not appear locally until they round-trip through Postgres.
186
+ - Assuming PGlite enforces every Postgres constraint.
187
+ - Assuming a revoked member keeps their synced rows offline — membership changes converge both ways,
188
+ live and on resume.
189
+ - Passing a PGlite storage URL (`idb://…`, `memory://…`) as `storePath` — the contract is a plain
190
+ name and schemes throw; the backend is derived (ADR-0036).
191
+
192
+ ## Naming the local store
193
+
194
+ `createSyncClient`/`createClientPGlite` take a **plain `storePath`** (e.g. `"my-app-store"`), never a
195
+ storage URL — the backend is derived (browser/worker → IndexedDB, bun/Node → filesystem), and anything
196
+ containing `://` throws `InvalidStorePathError`. Memory-backed stores are deliberately not expressible in
197
+ the production API (pgxsinkit's retention + journal durability assume a persisted store): in TESTS, spread
198
+ `memoryStoreForTests("name")` from `@pgxsinkit/client/testing` into the options; a caller-owned
199
+ `pgliteInstance` that is provably non-persistent (a bare `new PGlite()`, or `memory://`) is refused with
200
+ `NonPersistentStoreError` unless a testing acknowledgment is spread alongside. Backups, the SQL exports,
201
+ and `restoreFrom` are the `operating` skill's territory.
202
+
203
+ ## Where to look
204
+
205
+ - Concepts: the two paths, read path, write path, Electric subqueries, local-schema DDL parity, and
206
+ timestamps (microsecond BIGINT, decimal strings across the boundary).
207
+ - For deployment and runtime/operational behavior (cold starts, convergence cadence, the HTTP/2
208
+ connection budget, the `globalThis.__pgxsinkitDebug` latency instrumentation), load the `operating`
209
+ skill.
210
+ - Full prose: <https://pgxsinkit.github.io/llms-full.txt>.
@@ -0,0 +1,303 @@
1
+ ---
2
+ name: operating
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 a live app feels fast: convergence
7
+ cadence (writes flush on enqueue; the interval is only a fallback), serverless edge cold starts and
8
+ warming, cache-control:no-store on a same-origin Electric shape proxy, the browser HTTP/2 connection
9
+ budget, the edge worker timeout vs Electric's long-poll, globalThis.__pgxsinkitDebug + the BootReport,
10
+ worker mode (defineSyncWorker/attachSyncClient — the whole engine in a SharedWorker, spare-as-worker
11
+ boot, per-group readiness, the rail forwarded as [pgxsinkit·w]), and the store lifecycle surface:
12
+ storePath naming, exportStore/exportDiagnostics/exportData (+ drain guard), and restoreFrom.
13
+ metadata:
14
+ type: task
15
+ library: "@pgxsinkit/client"
16
+ library_version: "0.1.40"
17
+ source: https://pgxsinkit.github.io/start/operating-in-production/
18
+ ---
19
+
20
+ # Operating a pgxsinkit app in production
21
+
22
+ The read/write/converge primitives are fast. When a live app feels slow it is almost always one of the
23
+ properties below — none are toolkit bugs; they are how serverless edges, browser HTTP, and CDN-shaped
24
+ caching behave. If writes or sync feel slow in a real browser but server benchmarks are fast, start here.
25
+
26
+ ## Convergence cadence: event-driven, interval is a fallback
27
+
28
+ When you pass an `autoSync` trigger to `createSyncClient`, the client drives `flush → reconcile`. The
29
+ pass is **event-driven**: the client calls `requestPass()` the moment a mutation is enqueued, so a local
30
+ write flushes to the server immediately — it does **not** wait for the interval. The interval
31
+ (`createBrowserConvergenceTrigger({ intervalMs })`, default 1.5s; in worker mode `defineSyncWorker`'s
32
+ `convergenceIntervalMs`, default 15s) is only a fallback for retries/recovery/cross-tab.
33
+
34
+ Therefore **keep the interval long.** A short interval is the dominant idle cost: every PGlite query is
35
+ ~50ms of WASM work on one thread, and an unconditional reconcile each tick re-runs every live query. The
36
+ demo uses `intervalMs: 15_000`, cutting idle CPU from ~70% of a core to ~2% with **no change to
37
+ convergence latency** (latency is bounded by the Electric echo, not the interval). Do **not** shorten
38
+ the interval to "make writes faster" — it does nothing and burns CPU.
39
+
40
+ ## Serve the gateway over HTTP/2 (the connection budget)
41
+
42
+ Electric's client holds **one live long-poll connection open per synced shape**. A client subscribing to
43
+ six shapes keeps six connections busy, and browsers cap **HTTP/1.1 at ~6 connections per origin** — so
44
+ over plain HTTP those long-polls consume every slot and the **write** request (same origin) is
45
+ **Stalled in the browser's connection queue** for a whole long-poll cycle before it is even dispatched.
46
+ This presents as multi-second writes that are invisible to `curl`/Node (which have no per-host cap) —
47
+ only a real browser shows it (DevTools → Network → a stuck `write` with a long **Stalled** time).
48
+
49
+ Fix: serve the gateway over **HTTP/2** (or HTTP/3), which multiplexes every request over one connection.
50
+ Any production ingress already does (Cloud Supabase, Electric Cloud, istio/Envoy, a TLS reverse proxy);
51
+ it only bites a local stack on plain `http://` (browsers only negotiate HTTP/2 over TLS).
52
+
53
+ ## Serverless edge cold starts
54
+
55
+ On a serverless edge a worker is suspended when idle and evicted after longer idle, so the **first write
56
+ after a quiet period** pays a cold start while steady-state writes are instant (measured: ~20ms warm,
57
+ ~0.45s after ~15s idle, ~5.8s on a cold module cache). This is a property of the deployment target, not
58
+ pgxsinkit — a long-lived Bun/Deno process or a managed warm pool has none. Mitigate: keep the worker warm
59
+ with a periodic cheap request (an empty `{"mutations":[]}` POST, rejected at validation before any DB
60
+ work), and set the worker wall-clock timeout **above** Electric's ~25s long-poll so a live subscription
61
+ is not recycled mid-cycle.
62
+
63
+ Region-pin **only the DB-bound write function**, not read proxies. Pinning the write function's execution
64
+ to the database's region (Supabase `x-region`) keeps its chatty function→DB protocol on a ~1ms loop; a
65
+ read proxy's upstream is Electric Cloud's global CDN, so pinning reads away from a distant caller instead
66
+ **adds** intercontinental hops per catch-up (~1.2s vs ~300ms). `createSyncClient` splits this cleanly:
67
+ `requestHeaders` is the shared base (sent on reads AND writes — e.g. a gateway `apikey`), and
68
+ `writeRequestHeaders` is merged over it on the write path only. Put the region header in
69
+ `writeRequestHeaders`; never in the shared `requestHeaders`, which reads also send.
70
+
71
+ ## Pre-warming PGlite's boot assets
72
+
73
+ A cold `PGlite.create` spends ~2.5s fetching + compiling the Postgres WASM (plus the initdb WASM and the
74
+ filesystem bundle) before it can open a store — otherwise paid **after** sign-in, on the path to first
75
+ paint. `createSyncClient` takes a `pgliteBootAssets` option: a promise of the already-fetched/compiled
76
+ assets (`{ pgliteWasmModule?, initdbWasmModule?, fsBundle? }`), awaited and passed straight into
77
+ `PGlite.create` so it skips its own lazy load. Start the fetch+compile on an **earlier screen** (a login /
78
+ identity picker) and hand the pending promise in — the WASM cost then hides behind user think-time. It is
79
+ best-effort: a rejected warm is caught to `undefined` and PGlite loads its own assets, so the warm never
80
+ fails the boot. The `boot pglite assets warm` rail stamp times it. (Board demo: `apps/board/src/board/
81
+ pglite-warm.ts` shows the Vite `?url` asset-URL pattern PGlite's `exports` field otherwise blocks.)
82
+
83
+ Pre-warming only hides the WASM fetch+compile; `PGlite.create` still spends ~1.9s on `initdb` + store open,
84
+ and that can't start until the store id is known (usually the signed-in user). To hide it too, create the
85
+ store EAGERLY under a generated id on the first screen and BIND it at auth. `createClientPGlite(storePath,
86
+ { bootAssets })` runs the exact same create the client does internally (electric + live extensions, warm
87
+ consumption, the `boot pglite.create` stamp) and returns a schemaless instance; hand the still-pending
88
+ promise to `createSyncClient`'s `precreatedPglite` option. Unlike `pgliteInstance` (caller owns schema),
89
+ `precreatedPglite` lets the client still run schema exec, prepare hooks, journal recovery and store-version
90
+ reconcile — so the eager create buys only `initdb`, and the role/registry-derived schema stays post-auth. A
91
+ rejected `precreatedPglite` is caught and falls back to the `storePath` create path (which also consumes
92
+ `pgliteBootAssets`), so it is a pure accelerator, never a boot dependency. Bind eager stores to users with a
93
+ small localStorage registry (userId→storeId plus one unbound "spare"): create a spare on the login screen,
94
+ claim it at sign-in, and GC any store that is neither mapped nor the spare. On a signed-in RELOAD there is
95
+ no login screen to create ahead of, so START the mapped-store open at app bootstrap (before React render),
96
+ memoised per userId so the provider's later open adopts it rather than opening a second instance. (Board
97
+ demo: `apps/board/src/board/store-registry.ts`, `store-prewarm.ts`.)
98
+
99
+ ## Worker mode: the engine in a SharedWorker (browser apps)
100
+
101
+ In a browser, prefer running the whole engine in a **SharedWorker** instead of on the calling thread: PGlite,
102
+ the shape streams, the journal machinery, and the convergence loop all leave the main thread, and N tabs
103
+ dedupe onto ONE engine/store/Electric-connection-set (the worker is named by its store id — which also
104
+ removes the two-tabs-one-store hazard structurally, no leader election). `createSyncClient` stays the
105
+ in-process mode for bun/Node and as the **fallback where `SharedWorker` is missing** (correct, just
106
+ main-thread) — so worker mode is never a hard dependency.
107
+
108
+ **Two-file pattern.** A worker entry (bundled as a worker) calls `defineSyncWorker({ registry, electricUrl,
109
+ writeUrl, … })` at module top level — the registry is CODE, _imported_ by the worker file, never cloned/
110
+ serialized in. The tab calls `attachSyncClient({ worker, registry, getToken })`, which returns the same
111
+ client shape as `createSyncClient` (write API, Drizzle read BUILDING on the tab, live rows,
112
+ `ready`/`status`/`stop`) plus `notifyAuthChanged` and `setOnline`, proxied to the shared engine. One-shot
113
+ `query`/`queryRaw` and local `pglite`/`ensureSynced`/`destroy` are NOT proxied (they throw) — reactive live
114
+ rows are the read path in worker mode. The lazy lifecycle methods ARE proxied, but the engine is SHARED:
115
+ `desync(tableKey)` from one tab reverts the consistency group for EVERY attached tab (desync's group-wide
116
+ revert is engine-wide here — the footgun). For an ephemeral delivery window use `discardEphemeral(tableKey)`
117
+ instead — the scoped, multi-tab-safe finalize (drops the ephemeral rows, reverts to dormant, refuses a
118
+ group with any persistent member); safe under a shared engine because an ephemeral window is
119
+ per-delivery-session and single-consumer. The exception is the INSPECTION surface `rawQuery(sql, params)` /
120
+ `rawExec(sql)` (debug pages, REPLs, ad-hoc counts): identical on both clients (executed in the worker on the
121
+ attach client), it runs raw against the local store — bypasses the journal/overlay, any write stays local
122
+ and never converges — so it is not an app-data read path. `replAdapter(client)` shapes it into the
123
+ `{ query, exec }` duck `@electric-sql/pglite-repl` needs (`client.pglite` stays unavailable). A worker file can bake multiple role variants and pick per attach via
124
+ `resolveRegistry(role)` + the tab's `role` (the board's admin/member registries; the spare needs it).
125
+
126
+ **Auth stays tab-owned (ADR-0013).** The tab pushes `{accessToken, expiresAt}` at attach and on
127
+ `notifyAuthChanged`; the worker uses the cached token and sends a pull-request only when a request finds it
128
+ near expiry (any tab answers via `getToken`, first wins). The worker NEVER refreshes — exactly one refresher,
129
+ so GoTrue refresh-token reuse detection can't be tripped by a second client.
130
+
131
+ **Boot: spare-as-worker + internal prefetch overlap.** The spare store (see above) becomes a pre-spawned
132
+ schemaless worker at the login screen (create + initdb off every thread that matters); the userId→storeId
133
+ registry stays tab-side in localStorage so binding resolves before attach (SharedWorker naming needs it).
134
+ Claim = bind id, attach, push config + token. On a PROVABLY-fresh claimed store, pass
135
+ `attachSyncClient({ freshStore: true })` (never for a mapped/returning store) and the worker overlaps the
136
+ shape catch-up with schema/journal/store-version recovery — far-user boot bounded by `max(create+schema,
137
+ catch-up)`, not their sum. New boot-rail stamps: `boot spare store ensured`, `boot mapped store prewarm`,
138
+ `boot store claimed`, `boot shape prefetch start`, `boot commits opened`.
139
+
140
+ **`ready` unchanged; per-group readiness exposed.** `client.ready` still gates on every eager group; for
141
+ progressive paint use `await client.groupReady(tableKey)` or read `status.groups` — no contract change.
142
+
143
+ **Debug rail is forwarded and origin-tagged.** A SharedWorker's own console is invisible to the page (only
144
+ `chrome://inspect`), so the worker forwards every rail line to each tab, stamped with the WORKER's monotonic
145
+ clock and re-printed as `[pgxsinkit·w <ms>ms] …`, gated by that tab's own `globalThis.__pgxsinkitDebug`. Set
146
+ the flag on the TAB as usual; the write/read/boot phases below read the same, just origin-tagged. The front
147
+ half of boot runs on the FIRST attach before any tab is listening, so the worker buffers those pre-attach
148
+ rail lines in a bounded ring (last 500) and replays them `[replay]`-marked to the first attaching tab (so
149
+ the boot's opening phases reach it too, ADR-0034). Full model:
150
+ <https://pgxsinkit.github.io/concepts/worker-mode/>.
151
+
152
+ ## Store naming, backups, and restore (ADR-0035/0036)
153
+
154
+ **Stores are named by a plain `storePath`, never a storage URL.** The backend is derived (browser/worker →
155
+ IndexedDB, bun/Node → filesystem); anything containing `://` throws `InvalidStorePathError` — do not "fix"
156
+ that by re-adding a scheme, drop it. Memory-backed stores are deliberately unreachable from the production
157
+ API (durability semantics assume a persisted store): tests spread `memoryStoreForTests("name")` from
158
+ `@pgxsinkit/client/testing`, and a caller-owned `pgliteInstance`/`precreatedPglite` that is provably
159
+ non-persistent (`dataDir` undefined — a bare `new PGlite()` — or `memory://`) is refused with
160
+ `NonPersistentStoreError` unless `testStoreAcknowledgment()` is spread alongside. For browser store GC, get
161
+ the IndexedDB name from `storeIndexedDbDatabaseName(storePath)` — never assemble `/pglite/…` yourself.
162
+
163
+ **Three exports, named by purpose, all returning `{ file, report }`** (report = phase timings + a
164
+ `MutationDiagnostics` snapshot, BootReport-style). They work identically on the in-process client and the
165
+ attach client (the artefact crosses the bridge as a transferred buffer):
166
+
167
+ - `exportStore()` — the **store backup**: a live, checkpointed `dumpDataDir` tarball of the WHOLE store,
168
+ journal and overlay included. Never blocks, works offline with unflushed writes; restorable ONLY into
169
+ PGlite via restore below. This is the backup/migration format.
170
+ - `exportDiagnostics()` — everything as SQL (synced + overlay + journal + views/functions + the `pgxsinkit`
171
+ schema) for support evidence. Never blocks; not for restoring.
172
+ - `exportData({ drainJournal? })` — the **portable** SQL (synced tables + their enum types, nothing of
173
+ pgxsinkit's machinery; loads into vanilla Postgres). The ONE blocking variant: it requires a fully
174
+ drained journal (an `acked` write whose echo has not landed is NOT yet in the synced tables), so it
175
+ flushes and awaits convergence up to `drainJournal.timeoutMs` (default 15s), failing fast with
176
+ `DataExportDrainError` (+ diagnostics) on `failed`/`quarantined`/`conflicted` rows. `drainJournal: false`
177
+ exports synced state as-is and flags it in the report.
178
+
179
+ The pg_dump variants run against a **throwaway clone** booted from the backup — the live engine is never
180
+ suspended and tabs never pause. Exports, `destroy()`, `discardEphemeral()`, and `dropReadCache()` all
181
+ serialise through one lifecycle slot: a concurrent call rejects immediately with `LifecycleBusyError`
182
+ (no queueing — retry after the holder settles). Ephemeral (`pg_temp`) content is never in any artefact.
183
+
184
+ **Restore** = `createSyncClient({ restoreFrom: backupFile, … })` (or `attachSyncClient` — the tarball rides
185
+ the boot attach), ONLY into a store path that does not exist yet (`RestoreTargetExistsError` otherwise; the
186
+ overwrite path is a deliberate `destroy()` first). A restored engine ALWAYS boots offline — no shape
187
+ streams, no flush, whatever options say — and every journal row recovered from the backup is parked in the
188
+ terminal `quarantined` state (the write path has no mutation dedupe, so replaying recovered writes is
189
+ unsafe). Inspect `diagnostics()`, resolve rows via `discardQuarantined` (+ re-author if wanted), then go
190
+ online by REBOOTING the now-persisted store normally. Consumer docs:
191
+ <https://pgxsinkit.github.io/concepts/export-and-restore/>.
192
+
193
+ ## Proxying Electric: force `cache-control: no-store`
194
+
195
+ Electric tags shape responses with a CDN-oriented `cache-control` (`max-age`, `stale-while-revalidate`).
196
+ Behind a **same-origin proxy with no CDN**, the browser cache serves them **stale** the moment a shape
197
+ handle rotates (re-seed, re-login, restart), and the client loops on "expired shape handle" **409s**
198
+ until it self-heals. Force `cache-control: no-store` on the proxied response:
199
+
200
+ ```ts
201
+ const response = await proxyElectricShapeRequest(request, claims, { registry, electricUrl });
202
+ const headers = new Headers(response.headers);
203
+ headers.set("cache-control", "no-store");
204
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
205
+ ```
206
+
207
+ Resumption stays cheap because Electric's offset/handle bookkeeping (in the local store) makes it cheap,
208
+ not the HTTP cache.
209
+
210
+ Upstream direction, hosted Electric behind a CDN: live long-polls can be answered by a layer blind to
211
+ fresh commits (consecutive full-hold `up-to-date` responses at an unmoved offset → ~40–90s cross-client
212
+ propagation). The proxy appends a unique `cache-buster` to every `live=true` upstream request by default
213
+ (`bustLiveUpstreamCache`; catch-up stays unbusted for CDN cold-fanout sharing). TEMPORARY
214
+ upstream-defect mitigation — it defeats Electric's sanctioned live-poll coalescing (per-client origin
215
+ fan-out at scale); flip off once Electric Cloud wakes coalesced polls reliably. Distinct from the
216
+ ADR-0033 sibling nudge, which is permanent protocol behavior. Running your own CDN in front of
217
+ self-hosted Electric: key on the FULL query string (every param is load-bearing), respect origin
218
+ cache-control, keep SWR windows modest, let coalesced live polls complete immediately on origin
219
+ response, read-timeouts 60s+, then VERIFY with bust off — cross-client render ≲3s = healthy, ~a full
220
+ hold cycle = live path served blind (full checklist: operating-in-production docs page). Harmless
221
+ self-hosted;
222
+ set `false` to restore untouched forwarding.
223
+
224
+ ## Debugging latency: `globalThis.__pgxsinkitDebug`
225
+
226
+ `@pgxsinkit/client` ships opt-in, off-by-default, timestamped instrumentation that traces a write through
227
+ every phase. Enable it from the console or before boot:
228
+
229
+ ```js
230
+ globalThis.__pgxsinkitDebug = true; // reproduce, then filter the console to "pgxsinkit" + enable Verbose
231
+ ```
232
+
233
+ Read the **gaps** between phases: `mutation staged {mutationId, table}` (the write's origin — correlate
234
+ by id with the later sent/acked lines); `convergence pass requested` → `flush` / `reconcile`
235
+ (durations); `board-write auth token resolved {ms}` (a stalling per-request token fetch shows here);
236
+ `board-write responded {status, ms}` (a cold worker, or a browser connection stall, shows here);
237
+ `sync received change batch` → `sync applied {ms}` (truthful: fires only when the batch committed — a
238
+ batch gated behind a quiet sibling's watermark logs `sync change batch held by group frontier` +
239
+ `live-tail sibling nudge {shape}` instead, ADR-0033); `live query updated → re-render`. The read path has
240
+ its own pair: `shape request start {shape, offset, live}` → `shape request done {shape, status, ms,
241
+ upToDate?}` for EVERY Electric HTTP cycle (catch-up and long-poll), plus `must-refetch received {shape}`
242
+ when the server rotates a shape (the truncate + re-snapshot recovery trigger — the thing to look for
243
+ when a table unexpectedly re-syncs). Server-side, `createSyncServer({ logTimings: true })` emits the
244
+ matching per-request `[pgxsinkit-timing]` lines (see the `deploying` skill, `@pgxsinkit/server`);
245
+ client-observed minus server `totalMs` isolates routing + network. Boot is stamped too — the `boot
246
+ pglite.create` → `boot client ready` phases (local store open, schema apply, journal recovery,
247
+ store-version reconcile, sync start) let you attribute a slow first paint to a specific boot phase, and
248
+ `boot pglite assets warm` times the optional boot-asset pre-warm (see below).
249
+
250
+ **Structured boot numbers — the `BootReport`.** The rail lines are for a human reading a console; for
251
+ machine-keepable numbers (dashboards, CI budget gates) every boot ALSO builds a versioned `BootReport`,
252
+ independently of the rail so it exists whether or not the flag is on (ADR-0034). Read it by push
253
+ (`onBootReport?: (report) => void` client option, fires once at boot completion) or pull
254
+ (`await client.bootReport()` → the most recent completed boot, `null` before the first sync; in worker mode
255
+ it round-trips to the worker's stored report, so a late tab reads a boot that predates it). It carries
256
+ `totalMs`, decomposed `phases`, and a per-group `groups[]`. Two reading caveats: groups catch up
257
+ CONCURRENTLY on one WASM thread, so a group's `fetchMs` is an UPPER BOUND on network wait (it absorbs other
258
+ groups' applies + main-thread work between deliveries), and concurrent `applyMs` can overlap — never sum
259
+ them into a `totalMs` partition; and a non-null `provision` block is a spare's off-thread `initdb` made
260
+ visible (then `phases.pgliteCreateMs` is `null`).
261
+
262
+ A `catch-up watermark aligned {floor}` line marks the one moment the group finished its initial catch-up
263
+ and aligned its commit floors (ADR-0031). Electric's catch-up responses are CDN-cacheable and carry the
264
+ `up-to-date` watermark inside the cached body, so a quiet shape's stale cached watermark would otherwise
265
+ hold a busy shape's fresh changes until the quiet shape's first live long-poll (~41s on Electric Cloud —
266
+ the "stale board that rearranges itself" symptom). The client aligns once to the freshest asserted head
267
+ instead; the trade is a sub-second torn view of a multi-table transaction at load, self-healing in one
268
+ round trip, rather than a consistent-but-seconds-stale one. The same hold recurs on the **live tail**
269
+ (a quiet sibling's parked long-poll returns only at hold expiry), where the engine **nudges** the
270
+ laggards instead of waiting — `sync change batch held by group frontier` → `live-tail sibling nudge
271
+ {shape, target, round}` → commit on the refreshed watermarks; `live-tail nudge exhausted` means a
272
+ sibling never advanced and the engine degraded to waiting out its poll (ADR-0033). Full prose:
273
+ <https://pgxsinkit.github.io/start/operating-in-production/>.
274
+
275
+ **Measure at the network boundary, not by polling PGlite.** Each PGlite query is ~50ms on one thread, so
276
+ a tight `setInterval` reading PGlite to "watch" a value inflates the very latency it reports. Trust the
277
+ instrumentation's network timings and a server-side `curl` over a poll loop.
278
+
279
+ **Inspecting a stuck or failed write.** To see _why_ a write is not converging — its journal status,
280
+ attempt/retry counts, last error, or a table's pending/conflict/quarantine state — read the generated
281
+ journal and sync-state relations with the typed factories `getJournalTable(registry, tableKey)` /
282
+ `getSyncStateView(registry, tableKey)` from `@pgxsinkit/client` (typed Drizzle, no hand-written SQL against
283
+ `<t>_mutations`). One-shot diagnostic reads only — don't poll them in a loop.
284
+
285
+ **Rolling back a terminal write.** Both terminal dispositions keep the optimistic overlay and now have a
286
+ symmetric discard. A stale-write `conflicted` row (fired via `onConflict`) rolls back with
287
+ `client.discardConflict(table, entityKey)`; a structurally-rejected `quarantined` row (fired via
288
+ `onQuarantine` — a validation failure or a permanent policy denial such as an RLS `42501`) rolls back
289
+ with `client.discardQuarantined(table, entityKey)`. Each clears the entity's terminal journal rows +
290
+ kept overlay, so the read model falls back to the synced value and the entity accepts new mutations
291
+ again (a lingering terminal row otherwise blocks a re-create and chains a later update onto a dead head).
292
+ Because quarantine has a real rollback now, route a permanent policy denial to `quarantined` — don't
293
+ mis-route it to `conflicted` to borrow a discard.
294
+
295
+ ## Common mistakes
296
+
297
+ - Shortening the convergence interval to chase write latency (no effect; wastes CPU).
298
+ - Serving many-shape sync over plain HTTP/1.1 and blaming the server for stalled writes.
299
+ - Omitting `cache-control: no-store` on a same-origin shape proxy → intermittent 409 loops.
300
+ - Treating an edge cold start as a toolkit/sync-rail problem.
301
+ - Measuring latency by polling PGlite in a loop instead of at the network boundary.
302
+
303
+ Full prose: <https://pgxsinkit.github.io/start/operating-in-production/>.