@pgxsinkit/client 0.2.6 → 0.3.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 (94) hide show
  1. package/README.md +2 -1
  2. package/dist/boot-report.d.ts +5 -2
  3. package/dist/boot-report.d.ts.map +1 -1
  4. package/dist/circuits/envelope-to-change.d.ts +35 -0
  5. package/dist/circuits/envelope-to-change.d.ts.map +1 -0
  6. package/dist/circuits/group-sync.d.ts +123 -0
  7. package/dist/circuits/group-sync.d.ts.map +1 -0
  8. package/dist/circuits/shape-group.d.ts +77 -0
  9. package/dist/circuits/shape-group.d.ts.map +1 -0
  10. package/dist/circuits/stream-inbox.d.ts +126 -0
  11. package/dist/circuits/stream-inbox.d.ts.map +1 -0
  12. package/dist/circuits/stream-source.d.ts +90 -0
  13. package/dist/circuits/stream-source.d.ts.map +1 -0
  14. package/dist/circuits/subscription-client.d.ts +143 -0
  15. package/dist/circuits/subscription-client.d.ts.map +1 -0
  16. package/dist/circuits/sync-engine.d.ts +131 -0
  17. package/dist/circuits/sync-engine.d.ts.map +1 -0
  18. package/dist/debug.d.ts +0 -10
  19. package/dist/debug.d.ts.map +1 -1
  20. package/dist/export-dump.d.ts.map +1 -1
  21. package/dist/index.d.ts +47 -19
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +6258 -6443
  24. package/dist/index.js.map +26 -26
  25. package/dist/local-tables.d.ts +1 -1
  26. package/dist/local-tables.d.ts.map +1 -1
  27. package/dist/schema.d.ts.map +1 -1
  28. package/dist/sync/apply.d.ts +13 -21
  29. package/dist/sync/apply.d.ts.map +1 -1
  30. package/dist/sync/copy.d.ts +8 -8
  31. package/dist/sync/fold.d.ts +40 -0
  32. package/dist/sync/fold.d.ts.map +1 -0
  33. package/dist/sync/metadata-tables.d.ts +25 -1
  34. package/dist/sync/metadata-tables.d.ts.map +1 -1
  35. package/dist/sync/subscription-state.d.ts +21 -2
  36. package/dist/sync/subscription-state.d.ts.map +1 -1
  37. package/dist/sync/types.d.ts +9 -129
  38. package/dist/sync/types.d.ts.map +1 -1
  39. package/dist/testing.js +3 -3
  40. package/dist/testing.js.map +2 -2
  41. package/dist/worker/attach-sync-client.d.ts +3 -1
  42. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  43. package/dist/worker/define-sync-worker.d.ts +17 -1
  44. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  45. package/dist/worker/engine-control.d.ts +53 -0
  46. package/dist/worker/engine-control.d.ts.map +1 -1
  47. package/package.json +6 -7
  48. package/skills/core/SKILL.md +72 -55
  49. package/skills/operating/SKILL.md +120 -120
  50. package/src/boot-report.ts +4 -3
  51. package/src/circuits/envelope-to-change.ts +102 -0
  52. package/src/circuits/group-sync.ts +1047 -0
  53. package/src/circuits/shape-group.ts +158 -0
  54. package/src/circuits/stream-inbox.ts +225 -0
  55. package/src/circuits/stream-source.ts +165 -0
  56. package/src/circuits/subscription-client.ts +353 -0
  57. package/src/circuits/sync-engine.ts +641 -0
  58. package/src/debug.ts +1 -85
  59. package/src/export-dump.ts +3 -2
  60. package/src/index.ts +290 -273
  61. package/src/lazy-guard.ts +1 -1
  62. package/src/local-tables.ts +9 -2
  63. package/src/schema.ts +2 -11
  64. package/src/sync/apply.ts +72 -110
  65. package/src/sync/copy.ts +15 -15
  66. package/src/sync/fold.ts +94 -0
  67. package/src/sync/metadata-tables.ts +42 -1
  68. package/src/sync/subscription-state.ts +21 -3
  69. package/src/sync/types.ts +13 -141
  70. package/src/testing.ts +2 -2
  71. package/src/worker/attach-sync-client.ts +8 -1
  72. package/src/worker/define-sync-worker.ts +122 -13
  73. package/src/worker/engine-control.ts +89 -0
  74. package/dist/read-stream-stall.d.ts +0 -54
  75. package/dist/read-stream-stall.d.ts.map +0 -1
  76. package/dist/shape-sync.d.ts +0 -207
  77. package/dist/shape-sync.d.ts.map +0 -1
  78. package/dist/sync/index.d.ts +0 -32
  79. package/dist/sync/index.d.ts.map +0 -1
  80. package/dist/sync/nudge.d.ts +0 -49
  81. package/dist/sync/nudge.d.ts.map +0 -1
  82. package/dist/sync/shape-inbox.d.ts +0 -215
  83. package/dist/sync/shape-inbox.d.ts.map +0 -1
  84. package/dist/sync/tags.d.ts +0 -142
  85. package/dist/sync/tags.d.ts.map +0 -1
  86. package/dist/sync-auth.d.ts +0 -53
  87. package/dist/sync-auth.d.ts.map +0 -1
  88. package/src/read-stream-stall.ts +0 -102
  89. package/src/shape-sync.ts +0 -533
  90. package/src/sync/index.ts +0 -1124
  91. package/src/sync/nudge.ts +0 -110
  92. package/src/sync/shape-inbox.ts +0 -566
  93. package/src/sync/tags.ts +0 -390
  94. package/src/sync-auth.ts +0 -117
@@ -1,21 +1,21 @@
1
1
  ---
2
2
  name: operating
3
3
  description: >-
4
- Load when deploying or operating a live pgxsinkit app, when diagnosing a sync/write that "feels slow"
5
- in a browser even though the server is fast, or when wiring backups/export/restore. Covers the runtime
6
- and deployment properties (not toolkit bugs) that decide whether an app feels fast: convergence cadence
7
- (writes flush on enqueue; the interval is a fallback), serverless edge cold starts and warming,
8
- cache-control:no-store on a same-origin shape proxy, the browser HTTP/2 connection budget, the edge
9
- worker timeout vs Electric's long-poll, globalThis.__pgxsinkitDebug + the BootReport, worker mode
10
- (defineSyncWorker/attachSyncClient — capability-driven engine placement, factories, relocation outcomes,
11
- the forwarded rail), the store lifecycle surface (storePath naming, durability, backend permanence,
12
- supervised destruction, the three exports, restoreFrom), and Event-lane
13
- observability: onOutboxStatus, onEventLaneReport verdicts including deferred-on-skew, and the Outbox in
14
- destroy/restore/backup/dropReadCache.
4
+ Load when deploying or operating a pgxsinkit app, when a sync/write "feels slow" in a browser
5
+ but the server is fast, or when wiring backups/export/restore. Covers the runtime/deployment
6
+ properties (not toolkit bugs) deciding whether an app feels fast: convergence cadence (writes
7
+ flush on enqueue; the interval is a fallback), serverless edge cold starts, the read path's cache
8
+ split (no-store control plane, cacheable edge on its own origin, token out of the cache key), the
9
+ browser HTTP/2 connection budget, the edge worker timeout vs the durable-streams long-poll hold,
10
+ globalThis.__pgxsinkitDebug + the BootReport, worker mode (defineSyncWorker/attachSyncClient —
11
+ capability-driven engine placement, relocation outcomes, the forwarded rail), the store lifecycle
12
+ surface (storePath naming, durability, backend permanence, destruction, the three exports,
13
+ restoreFrom), and Event-lane observability: onOutboxStatus, onEventLaneReport verdicts including
14
+ deferred-on-skew, and the Outbox across destroy/restore/backup.
15
15
  metadata:
16
16
  type: task
17
17
  library: "@pgxsinkit/client"
18
- library_version: "0.2.6"
18
+ library_version: "0.3.0"
19
19
  source: https://pgxsinkit.github.io/start/operating-in-production/
20
20
  ---
21
21
 
@@ -36,34 +36,36 @@ retries/recovery/cross-tab.
36
36
  Therefore **keep the interval long.** A short interval is the dominant idle cost: every PGlite query is
37
37
  ~50ms of WASM work on one thread, and an unconditional reconcile each tick re-runs every live query. The
38
38
  demo uses `intervalMs: 15_000`, cutting idle CPU from ~70% of a core to ~2% with **no change to convergence
39
- latency** (latency is bounded by the Electric echo). Do **not** shorten it to "make writes faster".
39
+ latency** (latency is bounded by the read-path echo). Do **not** shorten it to "make writes faster".
40
40
 
41
41
  ## Serve the gateway over HTTP/2 (the connection budget)
42
42
 
43
- Electric's client holds **one live long-poll connection open per synced shape**, and browsers cap
44
- **HTTP/1.1 at ~6 connections per origin** — so over plain HTTP six shapes' long-polls consume every slot and
45
- the same-origin **write** request is **Stalled in the browser's connection queue** for a whole long-poll
46
- cycle before it is even dispatched. This presents as multi-second writes invisible to `curl`/Node (no
47
- per-host cap); only a real browser shows it (DevTools → Network → a stuck `write` with a long **Stalled**
48
- time). Fix: serve the gateway over **HTTP/2** (or HTTP/3), which multiplexes every request over one
49
- connection. Any production ingress already does; it only bites a local stack on plain `http://` (browsers
50
- only negotiate HTTP/2 over TLS).
43
+ `@durable-streams/client` holds **one live long-poll connection open per subscribed stream** (a subject in K
44
+ scopes of a shared shape holds K streams), and browsers cap **HTTP/1.1 at ~6 connections per origin** — so over
45
+ plain HTTP six streams' long-polls consume every slot and the same-origin **write** request is **Stalled in the
46
+ browser's connection queue** for a whole long-poll cycle before it is 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).
51
51
 
52
52
  ## Serverless edge cold starts
53
53
 
54
- On a serverless edge a worker is suspended when idle and evicted after longer idle, so the **first write
55
- after a quiet period** pays a cold start while steady-state writes are instant (measured: ~20ms warm, ~0.45s
56
- after ~15s idle, ~5.8s on a cold module cache). That is the deployment target, not pgxsinkit — a long-lived
57
- Bun/Deno process or a managed warm pool has none. Mitigate: keep the worker warm with a periodic cheap
58
- request (an empty `{"mutations":[]}` POST, rejected at validation before any DB work), and set the worker
59
- wall-clock timeout **above** Electric's ~25s long-poll so a live subscription is not recycled mid-cycle.
60
-
61
- Region-pin **only the DB-bound write function**, not read proxies. Pinning it to the database's region
62
- (Supabase `x-region`) keeps its chatty function→DB protocol on a ~1ms loop; a read proxy's upstream is
63
- Electric Cloud's global CDN, so pinning reads away from a distant caller instead **adds** intercontinental
64
- hops per catch-up (~1.2s vs ~300ms). `createSyncClient` splits this: `requestHeaders` is the shared base
65
- (reads AND writes — e.g. a gateway `apikey`), `writeRequestHeaders` is merged over it on the write path
66
- only. Put the region header in `writeRequestHeaders`, never in the shared `requestHeaders`.
54
+ On a serverless edge a worker is suspended when idle and evicted after longer idle, so the **first write after a
55
+ quiet period** pays a cold start while steady-state writes are instant (measured: ~20ms warm, ~0.45s after ~15s
56
+ idle, ~5.8s on a cold module cache). That is the deployment target, not pgxsinkit — a long-lived Bun/Deno
57
+ process or a managed warm pool has none. Mitigate: keep the worker warm with a periodic cheap request (an empty
58
+ `{"mutations":[]}` POST, rejected at validation before any DB work), and set the worker wall-clock timeout
59
+ **above** the durable-streams long-poll hold so a live subscription is not recycled mid-cycle (the board gives
60
+ its read functions `EDGE_WORKER_TIMEOUT_MS: "600000"`, not the stock 60s).
61
+
62
+ Region-pin **only the DB-bound write function**, never the two read functions. Pinning it to the database's
63
+ region (Supabase `x-region`) keeps its chatty function→DB protocol on a ~1ms loop; the read halves are not
64
+ DB-bound at all — the control plane's upstream is the Circuits engine, the edge's is durable-streams — and the
65
+ edge wants to sit near the CALLER, so catch-up bytes take the short hop. `createSyncClient` splits this:
66
+ `requestHeaders` is the shared base (reads AND writes — e.g. a gateway `apikey`), `writeRequestHeaders` is
67
+ merged over it on the write path only. Put the region header in `writeRequestHeaders`, never in the shared
68
+ `requestHeaders`.
67
69
 
68
70
  ## Pre-warming PGlite's boot assets
69
71
 
@@ -121,9 +123,10 @@ its class) and carries the refused `storePath`; a no-grant `provision` declines
121
123
  reason rather than pre-minting the sibling.
122
124
 
123
125
  **Two-file pattern.** One worker entry, bundled for both SharedWorker and dedicated Worker, calls
124
- `defineSyncWorker({ registry, electricUrl, batchWriteUrl, … })` at module top level — no placement or
125
- durability option (both are runtime/registry concerns); the registry is CODE, _imported_ by the worker
126
- file, never cloned/serialized in. Give each store a stable SharedWorker name and always pass
126
+ `defineSyncWorker({ registry, controlPlaneUrl, streamBaseUrl, batchWriteUrl, … })` at module top level (read
127
+ URLs both-or-neither, as on `createSyncClient`) — no placement or durability option (both are
128
+ runtime/registry concerns); the registry is CODE, _imported_ by the worker file, never cloned/serialized
129
+ in. Give each store a stable SharedWorker name and always pass
127
130
  `extendedLifetime: true` (Chromium 148+ grace period; ignore-safe elsewhere). The tab calls
128
131
  `attachSyncClient({ worker, registry, getToken })`. Prefer the **factory** form (`worker: () => SharedWorker`)
129
132
  over a bare instance or a raw `port` — a SharedWorker cannot be reconstructed from itself, so **in elected
@@ -173,25 +176,25 @@ disposes live queries before closing that client's engine and store.
173
176
  expiry (any tab answers via `getToken`, first wins). The worker NEVER refreshes — exactly one refresher, so
174
177
  GoTrue refresh-token reuse detection can't be tripped by a second client.
175
178
 
176
- **Boot: spare-as-worker + internal prefetch overlap.** The spare store (see above) becomes a pre-spawned
177
- schemaless worker at the login screen (create + initdb off every thread that matters); the userId→storeId
178
- registry stays tab-side in localStorage so binding resolves before attach (SharedWorker naming needs it).
179
- Call `provisionSyncWorker` with the same `worker` input as attach (the factory form, so elected-mode recovery
180
- is armed for provisioning too); an elected pre-open shares the tab's one election coordinator and derives the
181
- engine from the SharedWorker's own script URL. `provisionExpiryMs` (default 60000) is ONE deadline: it
182
- retires the abandoned elected claim AND settles the returned promise with the typed `ProvisionExpiredError`
183
- in both modes, so a provision behind a dead SharedWorker connection fails loudly rather than hanging. It
184
- bounds YOUR promise; the worker-side create attempt follows the placement. SW-direct: the attempt is left
185
- running — a later attach adopts it if it completed and waits on it if it is stuck, and a retried provision
186
- re-acks the same attempt rather than opening a second. Elected: the deadline also releases the provision
187
- claim, and a LAST-claim release retires and terminates the engine with that attempt inside it, so the next
188
- attach elects a fresh one (an attach that adopted the coordinator earlier keeps its claim, and that engine).
189
- Fire-and-forget callers should `.catch()` it like any un-awaited promise. Claim = bind id, attach, push
190
- config + token. On a PROVABLY-fresh claimed store pass `attachSyncClient({ freshStore: true })` (never for a
191
- mapped/returning store) and the worker overlaps the shape catch-up with schema/journal/store-version
192
- recovery — far-user boot bounded by `max(create+schema, catch-up)`, not their sum. Boot-rail stamps: `boot
193
- spare store ensured`, `boot mapped store prewarm`, `boot store claimed`, `boot shape prefetch start`,
194
- `boot commits opened`.
179
+ **Boot: spare-as-worker.** The spare store (see above) becomes a pre-spawned schemaless worker at the login
180
+ screen (create + initdb off every thread that matters); the userId→storeId registry stays tab-side in
181
+ localStorage so binding resolves before attach (SharedWorker naming needs it). Call `provisionSyncWorker` with
182
+ the same `worker` input as attach (the factory form, so elected-mode recovery is armed for provisioning too); an
183
+ elected pre-open shares the tab's one election coordinator and derives the engine from the SharedWorker's own
184
+ script URL. `provisionExpiryMs` (default 60000) is ONE deadline: it retires the abandoned elected claim AND
185
+ settles the returned promise with the typed `ProvisionExpiredError` in both modes, so a provision behind a dead
186
+ SharedWorker connection fails loudly rather than hanging. It bounds YOUR promise; the worker-side create attempt
187
+ follows the placement. SW-direct: the attempt is left running — a later attach adopts it if it completed and
188
+ waits on it if it is stuck, and a retried provision re-acks the same attempt rather than opening a second.
189
+ Elected: the deadline also releases the provision claim, and a LAST-claim release retires and terminates the
190
+ engine with that attempt inside it, so the next attach elects a fresh one (an attach that adopted the
191
+ coordinator earlier keeps its claim, and that engine). Fire-and-forget callers should `.catch()` it like any
192
+ un-awaited promise. Claim = bind id, attach, push config + token. On a PROVABLY-fresh claimed store pass
193
+ `attachSyncClient({ freshStore: true })` (never for a mapped/returning store): it asserts freshness, so streams
194
+ start from the beginning and the subscription-state read is skipped — a wrong `true` on a warm store
195
+ re-snapshots instead of resuming. It buys no catch-up/schema OVERLAP (that needed a commit gate the native read
196
+ path has no equivalent of, so boot is strictly sequential); what the spare removes is the store create itself.
197
+ Board boot-rail stamps: `boot spare store ensured`, `boot mapped store prewarm`, `boot store claimed`.
195
198
 
196
199
  **`ready` unchanged; per-group readiness exposed.** `client.ready` still gates on every eager group; for
197
200
  progressive paint use `await client.groupReady(tableKey)` or read `status.groups`.
@@ -201,19 +204,20 @@ progressive paint use `await client.groupReady(tableKey)` or read `status.groups
201
204
  clock and re-printed as `[pgxsinkit·w <ms>ms] …`, gated by that tab's own `globalThis.__pgxsinkitDebug`. The
202
205
  front half of boot runs on the FIRST attach before any tab is listening, so the worker buffers those
203
206
  pre-attach lines in a bounded ring (last 500) and replays them `[replay]`-marked to the first attaching tab.
204
- The worker's NETWORK traffic is invisible the same way: shape requests never appear in the page's Network
205
- panel — "rail shows `shape request start`, Network tab shows nothing" is worker mode working as designed.
206
- Inspect the worker itself (`chrome://inspect/#workers`) for the real requests, status codes, and errors (CORS
207
- rejections surface only there). Full model: <https://pgxsinkit.github.io/concepts/worker-mode/>.
208
-
209
- **Placement and relocation diagnostics.** Pull `client.bootReport()` and inspect `storageBackend`
210
- (`opfs-repacked`/`idbfs`/`filesystem`/`memory`), `engineHome` (`shared-worker`/`elected-worker`/
211
- `in-process`) and `storageFallbackReason`; never user-agent-sniff the backend. During elected-engine handoff
212
- `EngineRelocatedError("not-dispatched")` is safe to retry, while `"unknown"` means a dispatched mutation may
213
- already be journaled — inspect/reconcile, never retry blindly. The opt-in `executionLimit` is disabled by
214
- default (no finite worst-case query duration exists, and the limit converts slow to terminated by policy);
215
- it is elected-only and must match between the worker entry and every tab
216
- (`ExecutionLimitMismatchError`), and SW-direct Safari rejects it as unsupported.
207
+ The worker's NETWORK traffic is invisible the same way: the subscribe calls and the streams' long-polls never
208
+ appear in the page's Network panel — "the app is syncing but the Network tab shows nothing" is worker mode
209
+ working as designed. Inspect the worker itself (`chrome://inspect/#workers`) for the real requests and errors
210
+ (CORS rejections surface only there, a missing `Access-Control-Expose-Headers` on the edge included). Full
211
+ model: <https://pgxsinkit.github.io/concepts/worker-mode/>.
212
+
213
+ **Placement and relocation diagnostics.** Pull `client.bootReport()`: `storageBackend`, `engineHome`
214
+ (`shared-worker`/`elected-worker`/`in-process`), `storageFallbackReason`; never user-agent-sniff the backend. On
215
+ elected-engine handoff `EngineRelocatedError("not-dispatched")` is safe to retry; `"unknown"` means a dispatched
216
+ mutation may already be journaled — inspect/reconcile, never retry. The opt-in `executionLimit` is disabled by
217
+ default (no finite worst-case query duration exists; slow becomes terminated by policy), is elected-only, must
218
+ match across the worker entry and every tab (`ExecutionLimitMismatchError`); SW-direct rejects it. An attach
219
+ waits for an in-flight spare provision only within `provisionAdoptionBudgetMs` (default 20s from provision
220
+ start), then raises `ProvisionStalledError` — rebind to a fresh store; it bounds the accelerator, not liveness.
217
221
 
218
222
  ## Live-query manager: dedup + keep-alive (ADR-0040)
219
223
 
@@ -392,32 +396,28 @@ is the escape hatch. `dropReadCache()` never touches it (not read cache). `expor
392
396
  quarantine restored Outbox rows** — the deliberate asymmetry with the mutation journal: they resume flushing
393
397
  normally, because event delivery is idempotent end-to-end (`eventId` dedupe), which mutation replay is not.
394
398
 
395
- ## Proxying Electric: force `cache-control: no-store`
396
-
397
- Electric tags shape responses with a CDN-oriented `cache-control` (`max-age`, `stale-while-revalidate`), so
398
- behind a **same-origin proxy with no CDN** the browser cache serves them **stale** the moment a shape handle
399
- rotates (re-seed, re-login, restart) and the client loops on "expired shape handle" **409s** until it
400
- self-heals. Force `cache-control: no-store` on the proxied response:
401
-
402
- ```ts
403
- const response = await proxyElectricShapeRequest(request, claims, { registry, electricUrl });
404
- const headers = new Headers(response.headers);
405
- headers.set("cache-control", "no-store");
406
- return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
407
- ```
408
-
409
- Resumption stays cheap because Electric's offset/handle bookkeeping (in the local store) makes it cheap, not
410
- the HTTP cache. Upstream direction, hosted Electric behind a CDN: live long-polls can be answered by a layer blind to fresh
411
- commits (consecutive full-hold `up-to-date` responses at an unmoved offset → ~40–90s cross-client
412
- propagation). The proxy appends a unique `cache-buster` to every `live=true` upstream request by default
413
- (`bustLiveUpstreamCache`; catch-up stays unbusted for CDN cold-fanout sharing). TEMPORARY upstream-defect
414
- mitigation — it defeats Electric's sanctioned live-poll coalescing (per-client origin fan-out at scale), so
415
- flip it off once Electric Cloud wakes coalesced polls reliably; distinct from the ADR-0033 sibling nudge,
416
- which is permanent protocol behavior. Running your own CDN in front of self-hosted Electric: key on the FULL
417
- query string (every param is load-bearing), respect origin cache-control, keep SWR windows modest, let
418
- coalesced live polls complete immediately on origin response, read-timeouts 60s+, then VERIFY with bust off
419
- — cross-client render ≲3s = healthy, ~a full hold cycle = live path served blind (full checklist:
420
- operating-in-production docs page). Harmless self-hosted; set `false` to restore untouched forwarding.
399
+ ## The read path's cache split: uncacheable control plane, cacheable edge
400
+
401
+ The two read halves have opposite caching postures. The **control plane** (`/sync/v1/subscribe`, `/refresh`,
402
+ `/barrier`) answers per-subject questions and mints stream tokens, so force `cache-control: no-store` on it. The
403
+ **edge** (`createStreamGate` at `/v1/stream`) is the only surface a CDN may share, and durable-streams already
404
+ labels its responses for one — a catch-up read returns `cache-control: public, max-age=60,
405
+ stale-while-revalidate=300` and an `etag`, exactly where the bytes are. Sharing is a **shared-tier** property
406
+ only: a `rowFilter` fuses the subject into the predicate, so those bytes are shareable with nobody.
407
+
408
+ **Put the edge on its own origin, and keep the stream token out of the cache key.** The cache key is the URL, so
409
+ a same-origin mount makes the cacheable and uncacheable surfaces share one key and forecloses ever fronting the
410
+ shared tier; the token rides in `Authorization` (never a query parameter) for the same reason, and the cache
411
+ must not vary on that header. Revocation latency then follows the deployment: behind a hit-serving CDN it is
412
+ bounded by the token TTL (5 minutes by default), behind a cache sitting _behind_ the edge's verifier it is
413
+ entitlement-propagation latency.
414
+
415
+ **Every `createStreamGate` mount must set `Access-Control-Expose-Headers` from the exported
416
+ `STREAM_READ_EXPOSED_HEADERS`.** CORS lets script read only a short safelist, and every header durable-streams
417
+ 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.
421
421
 
422
422
  ## Debugging latency: `globalThis.__pgxsinkitDebug`
423
423
 
@@ -429,18 +429,17 @@ globalThis.__pgxsinkitDebug = true; // reproduce, then filter the console to "pg
429
429
  ```
430
430
 
431
431
  Read the **gaps** between phases: `mutation staged {mutationId, table}` (correlate by id with the later
432
- sent/acked lines); `convergence pass requested` → `flush` / `reconcile`; `board-write auth token resolved
433
- {ms}` (a stalling token fetch); `board-write responded {status, ms}` (a cold worker or a connection stall);
434
- `sync received change batch` → `sync applied {ms}` (fires only when the batch committed; a batch gated behind
435
- a quiet sibling's watermark instead logs `sync change batch held by group frontier` and `live-tail sibling
436
- nudge {shape}`, ADR-0033); `live query updated → re-render`. The read path has its own pair: `shape request
437
- start` → `shape request done {shape, status, ms, upToDate?}` for EVERY Electric HTTP cycle, plus `must-refetch
438
- received {shape}` when the server rotates a shape (the truncate + re-snapshot trigger — what to look for when
439
- a table unexpectedly re-syncs). Server-side, `createSyncServer({ logTimings: true })` emits matching
440
- `[pgxsinkit-timing]` lines (the `deploying` skill); client-observed minus server `totalMs` isolates routing +
441
- network. Boot too: `boot pglite.create` → `boot client ready` (store open, schema apply, journal recovery,
442
- store-version reconcile, sync start) attributes a slow first paint to a phase; `boot pglite assets warm` times
443
- the optional pre-warm.
432
+ sent/acked lines); `convergence pass requested (event-driven, …)` → `convergence flush` / `convergence
433
+ reconcile`; `flushBatch sending to board-write`; `board-write auth token resolved {ms}` (a stalling token
434
+ fetch); `board-write responded {status, ms}` (a cold worker or a connection stall); `board-write acks`; and
435
+ `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.
444
443
 
445
444
  **Structured boot numbers — the `BootReport`.** The rail is for a human reading a console; for
446
445
  machine-keepable numbers (dashboards, CI budget gates) every boot ALSO builds a versioned `BootReport`,
@@ -453,17 +452,17 @@ per-group `groups[]`. Two reading caveats: groups catch up CONCURRENTLY on one W
453
452
  `totalMs` partition; and a non-null `provision` block is a spare's off-thread `initdb` made visible (then
454
453
  `phases.pgliteCreateMs` is `null`).
455
454
 
456
- A `catch-up watermark aligned {floor}` line marks the one moment a group finished its initial catch-up and
457
- aligned its commit floors (ADR-0031). Electric's catch-up responses are CDN-cacheable and carry the
458
- `up-to-date` watermark inside the cached body, so a quiet shape's stale cached watermark would otherwise hold
459
- a busy shape's fresh changes until the quiet shape's first live long-poll (~41s on Electric Cloud — the
460
- "stale board that rearranges itself" symptom). The client aligns once to the freshest asserted head instead;
461
- the trade is a sub-second torn view of a multi-table transaction at load, self-healing in one round trip.
462
- The same hold recurs on the **live tail**, where the engine **nudges** the laggards instead of waiting —
463
- `sync change batch held by group frontier` → `live-tail sibling nudge {shape, target, round}` → commit on
464
- the refreshed watermarks; `live-tail nudge exhausted` means a sibling never advanced and the engine degraded
465
- to waiting out its poll (ADR-0033). Full prose:
466
- <https://pgxsinkit.github.io/start/operating-in-production/>.
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
464
+ batches, those effects are lost, and the client refuses to align and goes `degraded` rather than waiting —
465
+ restart the engine and re-subscribe. Full prose: <https://pgxsinkit.github.io/start/operating-in-production/>.
467
466
 
468
467
  **Measure at the network boundary, not by polling PGlite.** Each PGlite query is ~50ms on one thread, so
469
468
  a tight `setInterval` reading PGlite to "watch" a value inflates the very latency it reports. Trust the
@@ -487,8 +486,9 @@ a real rollback, route a permanent policy denial to `quarantined` — never mis-
487
486
  ## Common mistakes
488
487
 
489
488
  - Shortening the convergence interval to chase write latency (no effect; wastes CPU).
490
- - Serving many-shape sync over plain HTTP/1.1 and blaming the server for stalled writes.
491
- - Omitting `cache-control: no-store` on a same-origin shape proxy → intermittent 409 loops.
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
492
  - Treating an edge cold start as a toolkit/sync-rail problem.
493
493
  - Measuring latency by polling PGlite in a loop instead of at the network boundary.
494
494
  - Treating `deferred` as a failure and "cleaning up" the Outbox — it is rollout skew, and those rows drain
@@ -11,7 +11,8 @@
11
11
  import { syncDebug } from "./debug";
12
12
 
13
13
  /** Monotonic clock (ms) — `performance.now()` where available, else `Date.now()`. */
14
- const nowMs = (): number => (typeof performance !== "undefined" ? performance.now() : Date.now());
14
+ /** The monotonic clock every boot offset and duration in this module is measured on. */
15
+ export const nowMs = (): number => (typeof performance !== "undefined" ? performance.now() : Date.now());
15
16
 
16
17
  /**
17
18
  * A structured, versioned record of one client boot (ADR-0034). `reportVersion` is a contract number:
@@ -95,7 +96,7 @@ export interface BootReport {
95
96
  journalRecoveryMs: number;
96
97
  storeVersionReconcileMs: number;
97
98
  /**
98
- * `startConfiguredSync`: stream/group construction wall. On an overlap boot (ADR-0032 S4,
99
+ * `startCircuitsSync`: stream/group construction wall. On an overlap boot (ADR-0032 S4,
99
100
  * {@link BootReport.overlapPrefetch}) the early-started segment runs concurrently with schema, journal
100
101
  * recovery, and registry reconciliation, so this includes that shared wall. Structurally 0 when the boot
101
102
  * is ready inside the
@@ -179,7 +180,7 @@ export interface GroupBootStamp {
179
180
  markReady: () => void;
180
181
  }
181
182
 
182
- /** The seam `startConfiguredSync` uses to open a boot group's accumulator (implemented by the builder). */
183
+ /** The seam `startCircuitsSync` uses to open a boot group's accumulator (implemented by the builder). */
183
184
  export interface BootStampCollector {
184
185
  beginGroup: (groupKey: string, tables: number) => GroupBootStamp;
185
186
  }
@@ -0,0 +1,102 @@
1
+ import type { StreamEnvelope, StreamValue, SyncOperation } from "@pgxsinkit/contracts";
2
+
3
+ import type { ApplyTarget } from "../local-tables";
4
+
5
+ /**
6
+ * Separator the engine joins composite primary-key values with (`schema.rs`, `PK_"\u001f"`).
7
+ *
8
+ * ASCII Unit Separator, chosen upstream so it cannot collide with real id text. Restated here rather
9
+ * than derived: getting it wrong does not fail loudly, it produces deletes that match no row.
10
+ */
11
+ const PK_SEPARATOR = "\u001f";
12
+
13
+ /** The applier's message shape, once an envelope has been resolved against its table. */
14
+ export interface ChangeLike {
15
+ key: string;
16
+ value: Record<string, unknown>;
17
+ headers: { operation: SyncOperation };
18
+ }
19
+
20
+ /**
21
+ * Coerce one primary-key value out of its key-string rendering.
22
+ *
23
+ * The engine writes keys through `Value::to_key_string`, which erases type: `Int(42)` becomes
24
+ * `"42"`, `Bool(true)` becomes `"true"`. A delete carries **only** that key, so the pk has to be
25
+ * re-typed here or the `WHERE` binds text against a non-text column.
26
+ *
27
+ * `bigint` and `numeric` stay strings deliberately — routing them through `Number` would lose
28
+ * precision above 2^53, and a silently-wrong id is worse than a driver-level coercion.
29
+ */
30
+ function coercePrimaryKeyValue(sqlType: string, raw: string): StreamValue {
31
+ switch (sqlType) {
32
+ case "integer":
33
+ case "smallint":
34
+ case "serial":
35
+ case "smallserial":
36
+ return Number(raw);
37
+ case "boolean":
38
+ return raw === "true";
39
+ default:
40
+ return raw;
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Rebuild the primary-key columns of a row from the stream key.
46
+ *
47
+ * Composite keys are joined in **primary-key declaration order**, which is the order `ApplyTarget`
48
+ * already holds — so the two must agree. A count mismatch is thrown rather than tolerated: a
49
+ * silently short split would produce a `WHERE` over only part of the key, and a delete matching more
50
+ * rows than it should is data loss, not a stale row.
51
+ */
52
+ export function primaryKeyFromStreamKey(target: ApplyTarget, key: string): Record<string, unknown> {
53
+ const parts = target.primaryKey.length === 1 ? [key] : key.split(PK_SEPARATOR);
54
+ if (parts.length !== target.primaryKey.length) {
55
+ throw new Error(
56
+ `[pgxsinkit] stream key "${key}" splits into ${parts.length} part(s) but the target has a ` +
57
+ `${target.primaryKey.length}-column primary key (${target.primaryKey.join(", ")})`,
58
+ );
59
+ }
60
+
61
+ const row: Record<string, unknown> = {};
62
+ target.primaryKey.forEach((column, index) => {
63
+ const sqlType = target.columnTypes.find((type) => type.name === column)?.sqlType ?? "text";
64
+ row[column] = coercePrimaryKeyValue(sqlType, parts[index]!);
65
+ });
66
+ return row;
67
+ }
68
+
69
+ /**
70
+ * Translate a Circuits envelope into the message the applier consumes.
71
+ *
72
+ * There is no operation mapping to do — {@link SyncOperation} is the wire's own vocabulary. What
73
+ * this function carries is the one structural difference: **a delete has no row body**, only its
74
+ * key, so the pk columns are reconstructed here. That is a privacy improvement (an eviction
75
+ * discloses the key and nothing else) and an implementation hazard in the same change, which is why
76
+ * the reconstruction is a named, tested function rather than an inline split.
77
+ *
78
+ * An `upsert` carries the **complete projected row** every time — the engine's `row_to_json_cols`
79
+ * emits every column of the shape's `out_cols`, never a changed-column subset — which is what lets
80
+ * the apply path refresh every non-pk column from `excluded` without knowing whether the row already
81
+ * existed locally.
82
+ */
83
+ export function envelopeToChange(target: ApplyTarget, envelope: StreamEnvelope): ChangeLike {
84
+ const operation = envelope.headers.operation;
85
+
86
+ if (operation === "delete") {
87
+ return {
88
+ key: envelope.key,
89
+ value: primaryKeyFromStreamKey(target, envelope.key),
90
+ headers: { operation: "delete" },
91
+ };
92
+ }
93
+
94
+ if (envelope.value === undefined) {
95
+ throw new Error(
96
+ `[pgxsinkit] ${operation} envelope for key "${envelope.key}" carries no row body — only a ` +
97
+ `delete may omit one`,
98
+ );
99
+ }
100
+
101
+ return { key: envelope.key, value: envelope.value, headers: { operation: "upsert" } };
102
+ }