@pgxsinkit/client 0.2.7 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +81 -0
  4. package/README.md +11 -3
  5. package/dist/boot-report.d.ts +11 -8
  6. package/dist/boot-report.d.ts.map +1 -1
  7. package/dist/circuits/envelope-to-change.d.ts +39 -0
  8. package/dist/circuits/envelope-to-change.d.ts.map +1 -0
  9. package/dist/circuits/group-sync.d.ts +123 -0
  10. package/dist/circuits/group-sync.d.ts.map +1 -0
  11. package/dist/circuits/shape-group.d.ts +77 -0
  12. package/dist/circuits/shape-group.d.ts.map +1 -0
  13. package/dist/circuits/stream-inbox.d.ts +126 -0
  14. package/dist/circuits/stream-inbox.d.ts.map +1 -0
  15. package/dist/circuits/stream-source.d.ts +96 -0
  16. package/dist/circuits/stream-source.d.ts.map +1 -0
  17. package/dist/circuits/subscription-client.d.ts +143 -0
  18. package/dist/circuits/subscription-client.d.ts.map +1 -0
  19. package/dist/circuits/sync-engine.d.ts +131 -0
  20. package/dist/circuits/sync-engine.d.ts.map +1 -0
  21. package/dist/debug.d.ts +0 -10
  22. package/dist/debug.d.ts.map +1 -1
  23. package/dist/event-lane.d.ts +32 -1
  24. package/dist/event-lane.d.ts.map +1 -1
  25. package/dist/export-data.d.ts +3 -3
  26. package/dist/export-dump.d.ts +9 -9
  27. package/dist/export-dump.d.ts.map +1 -1
  28. package/dist/export-store.d.ts +13 -13
  29. package/dist/index.d.ts +237 -113
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +7037 -6665
  32. package/dist/index.js.map +46 -43
  33. package/dist/local-store.d.ts +1 -1
  34. package/dist/local-store.d.ts.map +1 -1
  35. package/dist/local-tables.d.ts +59 -1
  36. package/dist/local-tables.d.ts.map +1 -1
  37. package/dist/mutation.d.ts +2 -2
  38. package/dist/mutation.d.ts.map +1 -1
  39. package/dist/mutations-api.d.ts.map +1 -1
  40. package/dist/opfs-effects.d.ts +30 -2
  41. package/dist/opfs-effects.d.ts.map +1 -1
  42. package/dist/schema.d.ts +12 -1
  43. package/dist/schema.d.ts.map +1 -1
  44. package/dist/store-boot.d.ts +30 -2
  45. package/dist/store-boot.d.ts.map +1 -1
  46. package/dist/store-build.d.ts +19 -0
  47. package/dist/store-build.d.ts.map +1 -0
  48. package/dist/store-engine.d.ts +22 -0
  49. package/dist/store-engine.d.ts.map +1 -0
  50. package/dist/store-meta.d.ts +29 -3
  51. package/dist/store-meta.d.ts.map +1 -1
  52. package/dist/store-ownership-lock.d.ts +33 -0
  53. package/dist/store-ownership-lock.d.ts.map +1 -0
  54. package/dist/store-path.d.ts +40 -28
  55. package/dist/store-path.d.ts.map +1 -1
  56. package/dist/sync/apply.d.ts +17 -25
  57. package/dist/sync/apply.d.ts.map +1 -1
  58. package/dist/sync/copy.d.ts +84 -8
  59. package/dist/sync/copy.d.ts.map +1 -1
  60. package/dist/sync/drizzle-executor.d.ts +4 -4
  61. package/dist/sync/drizzle-executor.d.ts.map +1 -1
  62. package/dist/sync/fold.d.ts +40 -0
  63. package/dist/sync/fold.d.ts.map +1 -0
  64. package/dist/sync/metadata-tables.d.ts +25 -1
  65. package/dist/sync/metadata-tables.d.ts.map +1 -1
  66. package/dist/sync/subscription-state.d.ts +26 -7
  67. package/dist/sync/subscription-state.d.ts.map +1 -1
  68. package/dist/sync/types.d.ts +9 -129
  69. package/dist/sync/types.d.ts.map +1 -1
  70. package/dist/testing.d.ts +1 -1
  71. package/dist/testing.js +4 -3
  72. package/dist/testing.js.map +4 -4
  73. package/dist/worker/attach-sync-client.d.ts +27 -14
  74. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  75. package/dist/worker/define-sync-worker.d.ts +52 -19
  76. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  77. package/dist/worker/engine-control.d.ts +53 -0
  78. package/dist/worker/engine-control.d.ts.map +1 -1
  79. package/dist/worker/live-query-manager.d.ts +3 -3
  80. package/dist/worker/live-query-manager.d.ts.map +1 -1
  81. package/dist/worker/live-query-params-guard.d.ts +5 -5
  82. package/dist/worker/protocol.d.ts +26 -7
  83. package/dist/worker/protocol.d.ts.map +1 -1
  84. package/package.json +11 -9
  85. package/skills/core/SKILL.md +145 -63
  86. package/skills/operating/SKILL.md +221 -221
  87. package/skills/operating/references/postgres-builds.md +48 -0
  88. package/src/boot-report.ts +13 -12
  89. package/src/circuits/envelope-to-change.ts +211 -0
  90. package/src/circuits/group-sync.ts +1047 -0
  91. package/src/circuits/shape-group.ts +158 -0
  92. package/src/circuits/stream-inbox.ts +225 -0
  93. package/src/circuits/stream-source.ts +191 -0
  94. package/src/circuits/subscription-client.ts +353 -0
  95. package/src/circuits/sync-engine.ts +643 -0
  96. package/src/debug.ts +1 -85
  97. package/src/event-lane.ts +132 -14
  98. package/src/export-data.ts +4 -4
  99. package/src/export-dump.ts +24 -28
  100. package/src/export-store.ts +17 -17
  101. package/src/index.ts +797 -544
  102. package/src/lazy-guard.ts +1 -1
  103. package/src/live-rows-sql.ts +1 -1
  104. package/src/local-store.ts +2 -2
  105. package/src/local-tables.ts +76 -5
  106. package/src/mutation.ts +9 -8
  107. package/src/mutations-api.ts +2 -2
  108. package/src/opfs-effects.ts +74 -10
  109. package/src/schema.ts +126 -29
  110. package/src/store-boot.ts +71 -7
  111. package/src/store-build.ts +37 -0
  112. package/src/store-engine.ts +94 -0
  113. package/src/store-lifecycle.ts +1 -1
  114. package/src/store-meta.ts +155 -4
  115. package/src/store-ownership-lock.ts +109 -0
  116. package/src/store-path.ts +56 -40
  117. package/src/sync/apply.ts +104 -156
  118. package/src/sync/copy.ts +116 -21
  119. package/src/sync/drizzle-executor.ts +13 -14
  120. package/src/sync/fold.ts +94 -0
  121. package/src/sync/metadata-tables.ts +43 -2
  122. package/src/sync/subscription-state.ts +28 -10
  123. package/src/sync/types.ts +13 -141
  124. package/src/testing.ts +4 -4
  125. package/src/worker/attach-sync-client.ts +150 -57
  126. package/src/worker/define-sync-worker.ts +325 -87
  127. package/src/worker/engine-control.ts +89 -0
  128. package/src/worker/engine-router.ts +1 -1
  129. package/src/worker/live-query-fingerprint.ts +4 -4
  130. package/src/worker/live-query-manager.ts +12 -12
  131. package/src/worker/live-query-params-guard.ts +10 -10
  132. package/src/worker/protocol.ts +38 -7
  133. package/dist/read-stream-stall.d.ts +0 -54
  134. package/dist/read-stream-stall.d.ts.map +0 -1
  135. package/dist/shape-sync.d.ts +0 -207
  136. package/dist/shape-sync.d.ts.map +0 -1
  137. package/dist/sync/index.d.ts +0 -32
  138. package/dist/sync/index.d.ts.map +0 -1
  139. package/dist/sync/nudge.d.ts +0 -49
  140. package/dist/sync/nudge.d.ts.map +0 -1
  141. package/dist/sync/shape-inbox.d.ts +0 -215
  142. package/dist/sync/shape-inbox.d.ts.map +0 -1
  143. package/dist/sync/tags.d.ts +0 -142
  144. package/dist/sync/tags.d.ts.map +0 -1
  145. package/dist/sync-auth.d.ts +0 -53
  146. package/dist/sync-auth.d.ts.map +0 -1
  147. package/src/read-stream-stall.ts +0 -102
  148. package/src/shape-sync.ts +0 -533
  149. package/src/sync/index.ts +0 -1124
  150. package/src/sync/nudge.ts +0 -110
  151. package/src/sync/shape-inbox.ts +0 -566
  152. package/src/sync/tags.ts +0 -390
  153. package/src/sync-auth.ts +0 -117
@@ -7,8 +7,6 @@
7
7
  // port) behind {@link SyncWorkerHost.connect} — the same entry a test drives with a plain `MessageChannel`
8
8
  // port, so no real Worker is needed to exercise the whole protocol.
9
9
 
10
- import { type ParserOptions, type QueryOptions, types } from "@electric-sql/pglite";
11
-
12
10
  import type {
13
11
  ResolvedStorageDeclaration,
14
12
  SyncRuntimeStatus,
@@ -21,24 +19,29 @@ import {
21
19
  assertStorageDeclarationCompatible,
22
20
  getSyncRegistryStorage,
23
21
  isStorageBackend,
22
+ isStorageBuild,
24
23
  isStorageDurability,
24
+ isStorageEngineDeclaration,
25
25
  resolveStorageDeclaration,
26
26
  StorageDeclarationRefusedError,
27
27
  } from "@pgxsinkit/contracts";
28
+ import type { PostgresBuild, QueryOptions } from "@pgxsinkit/pgwasm";
29
+ import { drizzleParsers } from "@pgxsinkit/pgwasm/drizzle";
28
30
 
29
31
  import { type ConvergenceTrigger, createIntervalConvergenceTrigger } from "../convergence";
30
32
  import { setSyncDebugSink, syncDebug } from "../debug";
31
33
  import { describeErrorChain } from "../error-chain";
32
34
  import type { EventLaneOptions } from "../event-lane";
33
35
  import {
34
- type ClientPGlite,
35
- createClientPGlite,
36
+ type PgwasmClient,
37
+ createPgwasmClient,
36
38
  type CreateSyncClientOptions,
37
39
  createSyncClient,
38
40
  type DataExportOptions,
39
41
  type DiagnosticExportOptions,
40
42
  type MutationBatchItem,
41
43
  type RawQueryOptions,
44
+ type RawStatement,
42
45
  type StoreExportOptions,
43
46
  type SyncClient,
44
47
  } from "../index";
@@ -46,6 +49,8 @@ import { wrapLiveQueryForMaterialization } from "../live-rows-sql";
46
49
  import type { LocalStoreVersionEvent } from "../local-store";
47
50
  import { createOpfsEffects } from "../opfs-effects";
48
51
  import { type PlacementProbeResult, probeOpfsSyncAccess } from "../placement-probe";
52
+ import { assertStoreBuild } from "../store-build";
53
+ import { createStoreEngineResolver, type StoreEngineFactory, type StoreEngineModuleLoader } from "../store-engine";
49
54
  import { idbStoreExists, META_STORE_UNAVAILABLE, readStoreMetaRecord, writeStoreMetaRecord } from "../store-meta";
50
55
  import { readTestStoreMarker, TEST_STORE_BACKEND, type TestStoreMarker } from "../store-path";
51
56
  import {
@@ -55,6 +60,8 @@ import {
55
60
  ExecutionLimitMismatchError,
56
61
  executionLimitMismatchToWire,
57
62
  type ExecutionLimitConfig,
63
+ ProvisionStalledError,
64
+ provisionStalledToWire,
58
65
  readControlEnvelope,
59
66
  shouldApplyControlMessage,
60
67
  wrapControlEnvelope as controlEnvelope,
@@ -74,6 +81,7 @@ import {
74
81
  type BridgeEvent,
75
82
  type BridgeErrorWire,
76
83
  type BridgePort,
84
+ type BridgeTransferable,
77
85
  type ExportArtefactWire,
78
86
  type GuardedQueryWireArgs,
79
87
  identityCodec,
@@ -82,6 +90,7 @@ import {
82
90
  type ProvisionPayload,
83
91
  type RpcOp,
84
92
  type RpcPayload,
93
+ type RpcResultPayload,
85
94
  type SetOnlinePayload,
86
95
  type SubscribePayload,
87
96
  type TokenResponsePayload,
@@ -89,28 +98,18 @@ import {
89
98
  import { decideSwPlacement, type SwPlacementResult } from "./sw-placement";
90
99
  import { createWorkerTokenCache } from "./token-cache";
91
100
 
92
- // The identity-parser map a guarded bridge read re-applies before executing (ADR-0032 decision 4). It
93
- // MIRRORS the fixed `parsers` constant in `drizzle-orm/pglite`'s session VERBATIM (pinned to
94
- // drizzle-orm@1.0.0-rc.4, `drizzle-orm/pglite/session.js`): identity parsers so the listed OIDs come back as
95
- // raw STRINGS — exactly what the in-process drizzle session receives, because it passes this same map into
96
- // `pglite.query`. The members are: the scalar OIDs `types.TIMESTAMP` / `TIMESTAMPTZ` / `INTERVAL` / `DATE`,
97
- // and the array OIDs 1115 = `timestamp[]`, 1185 = `timestamptz[]`, 1187 = `interval[]`, 1182 = `date[]`, and
98
- // 1231 = `numeric[]` (NOT temporal — drizzle's list is mirrored verbatim, whatever its members). Over the
99
- // bridge the map is FUNCTIONS (non-serializable), so the attach side strips the options down to `rowMode`
100
- // and this worker re-applies the identical map. We do NOT import drizzle's private constant — this is a
101
- // deliberate, version-pinned mirror.
102
- const identityParser = (value: string): string => value;
103
- const DRIZZLE_PGLITE_IDENTITY_PARSERS: ParserOptions = {
104
- [types.TIMESTAMP]: identityParser,
105
- [types.TIMESTAMPTZ]: identityParser,
106
- [types.INTERVAL]: identityParser,
107
- [types.DATE]: identityParser,
108
- 1231: identityParser,
109
- 1115: identityParser,
110
- 1185: identityParser,
111
- 1187: identityParser,
112
- 1182: identityParser,
113
- };
101
+ // The identity-parser map a guarded bridge read re-applies before executing (ADR-0032 decision 4) is
102
+ // `drizzleParsers` from `@pgxsinkit/pgwasm/drizzle`: the SAME map the in-process drizzle session passes into
103
+ // `pg.query`, so the listed OIDs (the temporal scalars and arrays, and `numeric[]`) come back as raw STRINGS
104
+ // exactly as they do in process. Over the bridge the map is FUNCTIONS (non-serializable), so the attach side
105
+ // strips the options down to `rowMode` and this worker re-applies the identical map.
106
+
107
+ /**
108
+ * Cadence (ms) of the "worker store provision still pending" heartbeat rail line, emitted from the moment a
109
+ * spare provision attempt starts until it settles. Diagnosability only — no policy hangs off it (the bound is
110
+ * `provisionAdoptionBudgetMs`): it is what turns a silent stall into a visible one on the rail.
111
+ */
112
+ const PROVISION_PENDING_HEARTBEAT_MS = 5_000;
114
113
 
115
114
  export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
116
115
  /**
@@ -128,13 +127,30 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
128
127
  */
129
128
  resolveRegistry?: (role: string | undefined) => TRegistry | undefined;
130
129
  /**
131
- * How the worker creates its raw PGlite store (provision + fresh-attach paths). Defaults to
132
- * {@link createClientPGlite}, which loads PGlite's own boot assets — in a browser worker those hit the
130
+ * How the worker creates its raw pgwasm store (provision + fresh-attach paths). Defaults to
131
+ * {@link createPgwasmClient}, which loads pgwasm's own boot assets — in a browser worker those hit the
133
132
  * same-origin HTTP cache the tab's login-screen warm already primed (ADR-0032 S3). Injected in tests.
134
133
  * Takes a plain store PATH (ADR-0036); the internal `backendOverride` is the test lane's memory selection.
135
134
  */
136
- createPglite?: (storePath: string, backendOverride?: "memory") => Promise<ClientPGlite>;
137
- electricUrl: string;
135
+ createStore?: (storePath: string, backendOverride?: "memory") => Promise<PgwasmClient>;
136
+ /**
137
+ * The Postgres build this worker's stores run on: the boot's own mint, the provision mint and every spare
138
+ * mint (never on the wire — code cannot cross it). Defaults to `cBuild`. Pass `createCBuild({ assets })` to
139
+ * boot over assets warmed in the worker. It must be the registry's declared `storage.build` (default
140
+ * `"c"`, ADR-0063): a mismatch throws `StorageBuildMismatchError` before any store is touched. A store a
141
+ * {@link createStore} factory returns is checked against its own `pg.build` the same way.
142
+ */
143
+ build?: PostgresBuild;
144
+ /**
145
+ * How this scope imports a DECLARED store-engine module (ADR-0050 addendum 2026-09-08). Defaults to the
146
+ * scope's own dynamic `import()`; injected by a unit test that has no module to load. It is consulted
147
+ * only when the store's bound declaration carries `storage.engine`, and never for the built-in store.
148
+ */
149
+ loadStoreEngineModule?: StoreEngineModuleLoader;
150
+ /** The pgxsinkit control plane — subscribe, token re-mint, convergence barrier (ADR-0055). */
151
+ controlPlaneUrl: string;
152
+ /** The edge that serves durable-streams reads. */
153
+ streamBaseUrl: string;
138
154
  batchWriteUrl: string;
139
155
  /** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */
140
156
  requestHeaders?: Record<string, string>;
@@ -150,9 +166,10 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
150
166
  */
151
167
  batchEventUrl?: string;
152
168
  /**
153
- * The Event lane's client-level flush policy (ADR-0053): batch caps, the fallback interval, backoff, and
154
- * per-Event-stream overrides. A worker-ENTRY option, never an attach option — flush cadence is one
155
- * engine-wide policy, and the Outbox it drains is shared by every attached tab.
169
+ * The Event lane's client-level flush policy (ADR-0053): batch caps, the fallback interval, backoff, the
170
+ * acked ledger's retention (ADR-0060), and per-Event-stream overrides. A worker-ENTRY option, never an
171
+ * attach option — flush cadence is one engine-wide policy, and the Outbox it drains is shared by every
172
+ * attached tab.
156
173
  */
157
174
  events?: EventLaneOptions;
158
175
  /**
@@ -176,19 +193,32 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
176
193
  * channel to probe, so an enabled value is rejected as unsupported before engine boot.
177
194
  */
178
195
  executionLimit?: ExecutionLimitConfig;
196
+ /**
197
+ * How long an attach may wait for the engine's IN-FLIGHT spare provision (ADR-0032 decision 5) before it
198
+ * fails typed with {@link ProvisionStalledError} instead of waiting. Measured from the provision attempt's
199
+ * START, not from the attach — a tab attaching late inherits however much of the budget the spare has
200
+ * already burned. The stalled attempt is LEFT RUNNING (an in-flight OPFS/IDB store open cannot be safely
201
+ * abandoned — a second open against the same store is an ownership conflict), so a later attach still
202
+ * ADOPTS it if it completes; refusing costs at most one extra initdb, never data (the spare is schemaless
203
+ * and holds no writes). Default 20000. `Number.POSITIVE_INFINITY` restores the unbounded wait (NOT
204
+ * recommended: a stalled spare then hangs every attach forever). Must be > 0 — anything else throws at
205
+ * construction. This bounds the ACCELERATOR only; nothing is inferred from it about engine liveness
206
+ * (ADR-0049 D5's refusal of timing-based engine-death detection is unchanged).
207
+ */
208
+ provisionAdoptionBudgetMs?: number;
179
209
  /** Injected transport binder. Defaults to auto-detecting the SharedWorker/dedicated-worker global scope. */
180
210
  installGlobal?: boolean;
181
211
  /** Injected codec (ADR-0032 S2 §1). Defaults to the v1 identity codec. */
182
212
  codec?: BridgeCodec;
183
213
  /**
184
- * A raw PGlite the worker uses instead of creating its own (forwarded to `createSyncClient`'s
185
- * {@link CreateSyncClientOptions.precreatedPglite}) — the client still applies schema/reconcile. In a
214
+ * A raw pgwasm the worker uses instead of creating its own (forwarded to `createSyncClient`'s
215
+ * {@link CreateSyncClientOptions.precreatedPgwasm}) — the client still applies schema/reconcile. In a
186
216
  * browser worker the store is minted internally (`storePath`); this is the seam for a prepopulated store in
187
217
  * tests, and the future spare-worker claim (ADR-0032 decision 5).
188
218
  */
189
- precreatedPglite?: CreateSyncClientOptions<TRegistry>["precreatedPglite"];
190
- /** A fully-provisioned PGlite (forwarded to {@link CreateSyncClientOptions.pgliteInstance}; caller owns schema). */
191
- pgliteInstance?: CreateSyncClientOptions<TRegistry>["pgliteInstance"];
219
+ precreatedPgwasm?: CreateSyncClientOptions<TRegistry>["precreatedPgwasm"];
220
+ /** A fully-provisioned pgwasm (forwarded to {@link CreateSyncClientOptions.pgwasmInstance}; caller owns schema). */
221
+ pgwasmInstance?: CreateSyncClientOptions<TRegistry>["pgwasmInstance"];
192
222
  /**
193
223
  * App-level schema prep run IN THE WORKER, against the engine's own local store, BEFORE the registry
194
224
  * schema exec — forwarded verbatim to {@link CreateSyncClientOptions.prepareLocalDbBeforeSchema}, same
@@ -198,8 +228,8 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
198
228
  * a bespoke schema search_path). On a fresh store the registry-derived local tables do NOT yet exist when
199
229
  * this runs (that ordering is what distinguishes it from {@link prepareLocalDbAfterSchema}).
200
230
  *
201
- * Runs on the storePath, {@link precreatedPglite}, and restore boots; SKIPPED entirely on the
202
- * {@link pgliteInstance} path (the caller owns schema/prepare/reconcile there). On a restore boot it still
231
+ * Runs on the storePath, {@link precreatedPgwasm}, and restore boots; SKIPPED entirely on the
232
+ * {@link pgwasmInstance} path (the caller owns schema/prepare/reconcile there). On a restore boot it still
203
233
  * runs, but the store already carries the registry tables from the backup's datadir, so the "tables absent"
204
234
  * invariant does not hold there.
205
235
  */
@@ -211,17 +241,17 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
211
241
  * tab never sees it — functions cannot cross the bridge). Use it for app-level indexes, views, or migrations
212
242
  * that depend on the registry's local tables, which DO exist by the time this runs.
213
243
  *
214
- * Runs on the storePath, {@link precreatedPglite}, and restore boots; SKIPPED entirely on the
215
- * {@link pgliteInstance} path (the caller owns schema/prepare/reconcile there).
244
+ * Runs on the storePath, {@link precreatedPgwasm}, and restore boots; SKIPPED entirely on the
245
+ * {@link pgwasmInstance} path (the caller owns schema/prepare/reconcile there).
216
246
  */
217
247
  prepareLocalDbAfterSchema?: CreateSyncClientOptions<TRegistry>["prepareLocalDbAfterSchema"];
218
248
  /**
219
249
  * Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4). When an entry's last
220
- * subscriber leaves, a nonzero effective keep-alive retains its PGlite registration + diff state for a grace
250
+ * subscriber leaves, a nonzero effective keep-alive retains its pgwasm registration + diff state for a grace
221
251
  * period so a matching resubscribe (e.g. a re-mounted route across tabs) reuses it verbatim — no ~400 ms
222
252
  * re-materialization. Bounded by explicit budgets; DEFAULTS OFF (`defaultKeepAliveMs: 0` → tear a query
223
253
  * down the instant its last consumer leaves). The 0 default is justified: a retained entry STILL pays a
224
- * full SQL rerun + diff on every dependent write — PGlite live queries cannot be paused — so retention
254
+ * full SQL rerun + diff on every dependent write — pgwasm live queries cannot be paused — so retention
225
255
  * only pays off for a genuinely hot, re-mounted query, and the default keeps worker memory bounded with
226
256
  * no surprise standing SQL reruns.
227
257
  */
@@ -264,8 +294,19 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
264
294
  const codec = options.codec ?? identityCodec;
265
295
  const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30_000;
266
296
  const convergenceIntervalMs = options.convergenceIntervalMs ?? 15_000;
297
+ // The spare-store adoption budget (see the option's doc): the bound on how long an attach waits for an
298
+ // in-flight provision. Validated here — a non-positive/NaN budget would refuse every attach that met a
299
+ // pending spare, so it fails at construction rather than at the first sign-in.
300
+ const provisionAdoptionBudgetMs = options.provisionAdoptionBudgetMs ?? 20_000;
301
+ if (!(provisionAdoptionBudgetMs > 0)) {
302
+ throw new Error(
303
+ `[pgxsinkit] provisionAdoptionBudgetMs must be > 0 (got ${String(options.provisionAdoptionBudgetMs)}); it ` +
304
+ "bounds how long an attach waits for an in-flight spare provision. Use Number.POSITIVE_INFINITY for the " +
305
+ "unbounded wait.",
306
+ );
307
+ }
267
308
  // ADR-0049 D1: the placement probe's OPFS grant for THIS SharedWorker lifetime. Set true only by a GRANTED
268
- // `shared-worker` (SW-direct) probe, so both the provision-mint (default `createPglite` factory) and the boot
309
+ // `shared-worker` (SW-direct) probe, so both the provision-mint (default `createStore` factory) and the boot
269
310
  // create (below) resolve the OPFS-repacked backend. False is the honest capability-absence invariant — the
270
311
  // engine home in this scope opens IDBFS: the registry-declared `backend: "idbfs"` mode (no probe ran), or a
271
312
  // capability-absence fallback (every home's probe denied / the OPFS API absent). Read at CALL time — every mint
@@ -310,31 +351,67 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
310
351
  // provision payload bound the declaration (a construction-time constant could never see a wire declaration).
311
352
  const currentDurability = () =>
312
353
  engineStorage?.durability ?? getSyncRegistryStorage(options.registry)?.durability ?? "relaxed";
313
- const createPglite =
314
- options.createPglite ??
354
+ // The declared build (ADR-0063), read at mint time for the same reason as durability.
355
+ const currentBuild = () => engineStorage?.build ?? getSyncRegistryStorage(options.registry)?.build ?? "c";
356
+ const builtInCreatePglite: StoreEngineFactory =
357
+ options.createStore ??
315
358
  ((storePath: string, backendOverride?: "memory") =>
316
- createClientPGlite(storePath, {
359
+ createPgwasmClient(storePath, {
317
360
  ...(backendOverride ? { backendOverride } : {}),
361
+ // The worker's build, checked against the declaration before the mint touches a store.
362
+ ...(options.build ? { build: options.build } : {}),
363
+ declaredBuild: currentBuild(),
364
+ buildCheckSite: "defineSyncWorker",
318
365
  durability: currentDurability(),
319
366
  // SW-direct placement grant (ADR-0049 D1): a spare minted in-scope opens OPFS-repacked, matching the boot.
320
367
  ...(placementOpfsAccess ? { hasOpfsSyncAccess: true } : {}),
321
368
  }));
369
+ // The DECLARED store engine (ADR-0050 addendum 2026-09-08). A store whose bound declaration carries
370
+ // `storage.engine` is minted by THAT module, not by the built-in factory — generically: the toolkit
371
+ // imports a module URL and calls its `createStore`, and knows nothing else about the engine behind it.
372
+ // Resolved per module URL and memoized (rejections included) for this scope's lifetime.
373
+ const resolveStoreEngine = createStoreEngineResolver(options.loadStoreEngineModule);
374
+ // Read at MINT time, never at construction: the declaration arrives on the first provision/attach payload,
375
+ // long after this closure is built, and it is immutable once bound — so every mint of this store resolves
376
+ // the same engine. A declared module that will not load or exports no factory throws LOUDLY here; it never
377
+ // degrades to the built-in store, which would report a healthy engine for one that never ran.
378
+ // Every store this factory returns is checked against the declared build (ADR-0063) on its own `pg.build`:
379
+ // a caller's `createStore` or a declared engine module may run any build, whatever `options.build` says.
380
+ const createStore: StoreEngineFactory = async (storePath, backendOverride) => {
381
+ const declaredEngine = engineStorage?.engine?.module;
382
+ let store: PgwasmClient;
383
+ if (declaredEngine === undefined) {
384
+ store = await builtInCreatePglite(storePath, backendOverride);
385
+ } else {
386
+ const factory = await resolveStoreEngine(declaredEngine);
387
+ syncDebug("worker store engine declared", { storePath, module: declaredEngine });
388
+ store = await factory(storePath, backendOverride);
389
+ }
390
+ try {
391
+ assertStoreBuild(currentBuild(), store.build, "createStore");
392
+ } catch (error) {
393
+ // Refused before any use: release the store's handles (an OPFS store holds exclusive ones) and propagate.
394
+ await store.close().catch(() => undefined);
395
+ throw error;
396
+ }
397
+ return store;
398
+ };
322
399
  // A testing acknowledgment (ADR-0036) spread into THIS worker's options — needed when a test injects a
323
- // non-persistent BYO store (`precreatedPglite` / `pgliteInstance` / a memory-returning `createPglite`),
400
+ // non-persistent BYO store (`precreatedPgwasm` / `pgwasmInstance` / a memory-returning `createStore`),
324
401
  // which `createSyncClient` would otherwise refuse. Forwarded to the boot below. A browser worker never
325
402
  // sets it; a memory selection carried on the attach wire wins over it.
326
403
  const workerTestMarker = readTestStoreMarker(options);
327
404
 
328
405
  const ports = new Set<BridgePort>();
329
406
  const liveSubs = new Map<string, LiveSub>();
330
- // The live-query lifecycle (PGlite registration, diff listener, and the ADR-0040 decision-1 awaited-teardown
407
+ // The live-query lifecycle (pgwasm registration, diff listener, and the ADR-0040 decision-1 awaited-teardown
331
408
  // set) lives in a single manager owned per engine. Created lazily on first subscribe because it needs the
332
409
  // booted client's `live` namespace (`active.pglite.live`); the worker never restarts its engine in place
333
410
  // (ADR-0040 decision 7), so one manager serves the host's whole lifetime. `close()` disposes it.
334
411
  let liveManager: LiveQueryManager | null = null;
335
412
  const ensureLiveManager = (active: SyncClient<TRegistry>): LiveQueryManager =>
336
413
  (liveManager ??= createLiveQueryManager({
337
- live: active.pglite.live,
414
+ live: active.pgwasm.live,
338
415
  ...(options.liveQueries ? { policy: options.liveQueries } : {}),
339
416
  }));
340
417
  // Subscribes that have entered `handleSubscribe` but not yet reached `liveSubs.set` (they are mid-await on
@@ -363,20 +440,31 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
363
440
  };
364
441
 
365
442
  // ─── Pre-spawned (schemaless) store — the spare flow (ADR-0032 decision 5) ────────────────────────
366
- // A `provision` mints the raw PGlite (initdb only) and holds it idle here; the first real `attach`
367
- // adopts it as `precreatedPglite` (the client still runs schema/journal recovery/reconcile). Provision
443
+ // A `provision` mints the raw pgwasm (initdb only) and holds it idle here; the first real `attach`
444
+ // adopts it as `precreatedPgwasm` (the client still runs schema/journal recovery/reconcile). Provision
368
445
  // is role-agnostic — the registry is chosen at attach — so the same warmed store serves either role.
369
446
  // `stamp` carries the spare's create timing (ADR-0034): a boot adopting this store reports the initdb cost
370
- // as `BootReport.provision` (with `phases.pgliteCreateMs = null`) instead of timing a create it never ran.
447
+ // as `BootReport.provision` (with `phases.pgwasmCreateMs = null`) instead of timing a create it never ran.
371
448
  let provisioned: {
372
449
  storePath: string;
373
- pglite: Promise<ClientPGlite>;
450
+ pglite: Promise<PgwasmClient>;
374
451
  stamp: Promise<{ initdbMs: number; provisionReadyAt: number }>;
375
452
  } | null = null;
376
453
  // A provision request performs a bounded authority read before it may mint. An attach that arrives during
377
454
  // that read waits for the attempt to settle, then either adopts the minted store or runs the ordinary boot
378
455
  // path. This keeps provision a pure accelerator without racing a replacement underneath live deletion.
456
+ // That wait is BOUNDED by `provisionAdoptionBudgetMs` (see `boot`), so a spare whose create never settles
457
+ // refuses the attach typed instead of hanging it — hence the start stamp, the settlement flag, and the
458
+ // attempt's store path tracked alongside the promise.
379
459
  let provisionAttempt: Promise<void> | null = null;
460
+ /** `nowStamp()` at which the current {@link provisionAttempt} was created — the budget's origin. */
461
+ let provisionAttemptStartedAt = 0;
462
+ /** Whether {@link provisionAttempt} is still in flight (settlement is observed, never inferred from timing). */
463
+ let provisionAttemptPending = false;
464
+ /** The store path the current attempt is minting — what a refusal reports, resolved before any boot runs. */
465
+ let provisionAttemptStorePath = "";
466
+ /** The "still pending" heartbeat's handle; cleared the moment the attempt settles (never outlives it). */
467
+ let provisionHeartbeat: ReturnType<typeof setInterval> | null = null;
380
468
 
381
469
  // ─── Outbound-convergence gate — the tab's Offline toggle over the bridge (ADR-0032 S3) ───────────
382
470
  // The worker owns convergence; the tab forwards its Offline flag as `set-online`. When suppressed the
@@ -450,6 +538,38 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
450
538
  }
451
539
  };
452
540
 
541
+ // ─── The started-state snapshot (ADR-0059) ───────────────────────────────────────────────────────
542
+ // `client.isSynced` is a SYNCHRONOUS peek, so a tab cannot RPC for it. The worker therefore asks ITS OWN
543
+ // CLIENT — `isSynced(key)` for every key of the booted registry — and pushes the result; the tab answers
544
+ // out of that cache, so its answer is whatever the in-process client would have said. Faithful by
545
+ // construction: the promoted-group case (started from boot while its subscribe still retries), the
546
+ // sync-pending window and ADR-0021's sync-disabled clause all come along for free, and none of it is
547
+ // re-derived from the strictly weaker per-group catch-up readiness. Keyed by TABLE, so the tab needs no
548
+ // table→group mapping. `lastSyncedSnapshot` dedupes the broadcast — a recompute is cheap (the registry is
549
+ // small), an event for an unchanged answer is not.
550
+ let lastSyncedSnapshot: Record<string, boolean> | null = null;
551
+ const computeSyncedSnapshot = (active: SyncClient<TRegistry>): Record<string, boolean> => {
552
+ const snapshot: Record<string, boolean> = {};
553
+ for (const key of Object.keys(bootedRegistry ?? options.registry)) {
554
+ snapshot[key] = active.isSynced(key as SyncTableName<TRegistry>);
555
+ }
556
+ return snapshot;
557
+ };
558
+ const sameSnapshot = (a: Record<string, boolean>, b: Record<string, boolean>): boolean => {
559
+ const keys = Object.keys(a);
560
+ if (keys.length !== Object.keys(b).length) return false;
561
+ return keys.every((key) => a[key] === b[key]);
562
+ };
563
+ /** Recompute and broadcast the snapshot when (and only when) the answer changed. A no-op before boot. */
564
+ const publishSyncedIfChanged = (): void => {
565
+ const active = client;
566
+ if (active == null) return;
567
+ const snapshot = computeSyncedSnapshot(active);
568
+ if (lastSyncedSnapshot != null && sameSnapshot(lastSyncedSnapshot, snapshot)) return;
569
+ lastSyncedSnapshot = snapshot;
570
+ broadcastEvent({ kind: "synced", tables: snapshot });
571
+ };
572
+
453
573
  const emitStatus = (status: SyncRuntimeStatus) => {
454
574
  broadcastEvent({ kind: "status", status });
455
575
  // Derive a per-group `groupReady` event for each group that newly reached ready, so a tab gets both the
@@ -460,6 +580,9 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
460
580
  broadcastEvent({ kind: "groupReady", groupKey });
461
581
  }
462
582
  }
583
+ // A status transition accompanies every group-readiness edge and the sync-pending→wired crossing, so the
584
+ // started state can have moved (ADR-0059). Deduped, so a status change that moved nothing posts nothing.
585
+ publishSyncedIfChanged();
463
586
  };
464
587
 
465
588
  // ─── Engine boot — reuse createSyncClient verbatim (ADR-0032 decision 1/4) ────────────────────────
@@ -468,6 +591,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
468
591
  // The role the engine actually booted with (from the FIRST attach's config). Later attaches compare
469
592
  // their requested role against this and get a warning on mismatch (ADR-0032 FIX 5) — never a reject.
470
593
  let bootedRole: string | undefined;
594
+ // The registry the engine actually booted with — `options.registry`, or the role variant `resolveRegistry`
595
+ // picked (ADR-0032 S3). The started-state snapshot (ADR-0059) enumerates THIS registry's keys, so a
596
+ // role-selected variant reports its own relations rather than the default's.
597
+ let bootedRegistry: TRegistry | null = null;
471
598
  // The engine's `ready` is monotonic: once its initial sync lands it stays resolved even if the phase
472
599
  // later degrades. A tab attaching AFTER that moment must still get a resolved `ready`, so track whether
473
600
  // it has fired and tell the ack (ADR-0032 FIX 3).
@@ -493,6 +620,11 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
493
620
  if (milestones[stage]) return;
494
621
  milestones[stage] = true;
495
622
  broadcastEvent({ kind: "milestone", stage });
623
+ // `bootSettled` is the background tail's completion — sync START done, so a promoted lazy-persistent
624
+ // group is now started and every buffered activation has been replayed (ADR-0041/ADR-0021). That is a
625
+ // started-state edge no status transition is guaranteed to carry, so publish here too (ADR-0059).
626
+ // `failMilestone` needs no counterpart: a tail that failed never wired sync, so nothing started.
627
+ publishSyncedIfChanged();
496
628
  };
497
629
  const failMilestone = (stage: BootMilestone, error: unknown) => {
498
630
  if (stageErrors[stage]) return;
@@ -510,9 +642,46 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
510
642
 
511
643
  const boot = async (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {
512
644
  await placementGate;
513
- // Provision owns no recovery policy. Wait only for its bounded pre-mint check/create attempt; a declined
514
- // attempt leaves `provisioned` null and this attach continues through createSyncClient's full phase machine.
515
- await provisionAttempt?.catch(() => undefined);
645
+ // Provision owns no recovery policy, and it is a pure ACCELERATOR — so this attach waits for an in-flight
646
+ // attempt only within `provisionAdoptionBudgetMs`, counted from the ATTEMPT's start (a late attach inherits
647
+ // the burned budget). A declined/settled attempt leaves `provisioned` null and this attach continues through
648
+ // createSyncClient's full phase machine; a spare whose create never settles instead REFUSES this attach typed
649
+ // (`ProvisionStalledError`), so the host can rebind to a fresh store rather than wait forever. The stalled
650
+ // attempt is deliberately left running — an in-flight store open cannot be safely abandoned (a second open is
651
+ // an ownership conflict) — and a later attach still adopts it if it completes. Nothing here infers engine
652
+ // death from elapsed time (ADR-0049 D5 unchanged); it bounds the accelerator only.
653
+ const pendingAttempt = provisionAttempt;
654
+ if (pendingAttempt !== null) {
655
+ const startedAt = provisionAttemptStartedAt;
656
+ const remainingMs = Math.max(0, provisionAdoptionBudgetMs - (nowStamp() - startedAt));
657
+ if (Number.isFinite(remainingMs)) {
658
+ // A real timer: the worker has no injected clock, so tests drive this with a small budget.
659
+ let budgetTimer: ReturnType<typeof setTimeout> | undefined;
660
+ await Promise.race([
661
+ pendingAttempt.catch(() => undefined),
662
+ new Promise<void>((resolve) => {
663
+ budgetTimer = setTimeout(resolve, remainingMs);
664
+ }),
665
+ ]);
666
+ if (budgetTimer !== undefined) clearTimeout(budgetTimer);
667
+ } else {
668
+ // `Number.POSITIVE_INFINITY` — the opted-in unbounded wait.
669
+ await pendingAttempt.catch(() => undefined);
670
+ }
671
+ if (provisionAttemptPending) {
672
+ const elapsedMs = Math.round(nowStamp() - startedAt);
673
+ syncDebug("worker provision adoption stalled — attach refused", {
674
+ storePath: provisionAttemptStorePath,
675
+ elapsedMs,
676
+ budgetMs: provisionAdoptionBudgetMs,
677
+ });
678
+ throw new ProvisionStalledError({
679
+ storePath: provisionAttemptStorePath,
680
+ elapsedMs,
681
+ budgetMs: provisionAdoptionBudgetMs,
682
+ });
683
+ }
684
+ }
516
685
  const attachLimit = attach.executionLimit?.maxDispatchMs;
517
686
  if (placementEngineHome === "shared-worker" && attachLimit !== undefined) {
518
687
  throw new Error(
@@ -530,6 +699,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
530
699
  // Resolve the registry from the attach's role (ADR-0032 S3): a single worker file bakes both variants
531
700
  // and the claim/attach settles which one boots — the spare was provisioned before the role was known.
532
701
  const registry = options.resolveRegistry?.(attach.config?.role) ?? options.registry;
702
+ bootedRegistry = registry;
533
703
  // ADR-0050: placement and engine binding were resolved against `options.registry`'s static declaration —
534
704
  // the spare was placed before any role existed, so a role-selected registry cannot re-home the store. A
535
705
  // role registry whose static declaration EXPLICITLY conflicts with that bound resolution is refused typed
@@ -543,7 +713,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
543
713
  }
544
714
  // storePath-first, matching the `provision` handler's resolution (below): the board sends BOTH a bare
545
715
  // `storeId` (SharedWorker naming, tab-side) AND the real `storePath` (`pgxsinkit-board-<id>`), and the
546
- // PGlite store lives at `storePath` — so the provisioned store's path must be what we adopt on.
716
+ // pgwasm store lives at `storePath` — so the provisioned store's path must be what we adopt on.
547
717
  // `storeId` is only a last-ditch fallback for a caller that passes it as the store path.
548
718
  const storePath = attach.storePath ?? attach.storeId ?? options.storePath ?? "pgxsinkit-overlay-v1";
549
719
  // The testing memory-backend override rides as an explicit wire field (a symbol does not survive
@@ -559,15 +729,15 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
559
729
  const restoreFrom = attach.restore
560
730
  ? new Blob([attach.restore.buffer], { type: attach.restore.mimeType })
561
731
  : undefined;
562
- // Adopt a matching pre-provisioned store (its initdb already ran off-thread) as `precreatedPglite`;
732
+ // Adopt a matching pre-provisioned store (its initdb already ran off-thread) as `precreatedPgwasm`;
563
733
  // createSyncClient falls back to a fresh `storePath` create if that promise rejects — a pure accelerator.
564
734
  // Never adopt when restoring (restore boots a brand-new store from the backup, not the provisioned one).
565
735
  const adoptingProvisioned = restoreFrom == null && provisioned != null && provisioned.storePath === storePath;
566
- const precreatedPglite = adoptingProvisioned
736
+ const precreatedPgwasm = adoptingProvisioned
567
737
  ? provisioned!.pglite
568
738
  : restoreFrom
569
739
  ? undefined
570
- : options.precreatedPglite;
740
+ : options.precreatedPgwasm;
571
741
  // The adopted spare's create timing feeds `BootReport.provision` (ADR-0034); absent otherwise.
572
742
  const provisionStamp = adoptingProvisioned ? provisioned!.stamp : undefined;
573
743
  if (adoptingProvisioned) {
@@ -581,7 +751,8 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
581
751
  // elected dedicated engine boots the OPFS-repacked backend it actually holds instead of racing to `idbfs`.
582
752
  bootPromise = createSyncClient<TRegistry>({
583
753
  registry,
584
- electricUrl: options.electricUrl,
754
+ controlPlaneUrl: options.controlPlaneUrl,
755
+ streamBaseUrl: options.streamBaseUrl,
585
756
  batchWriteUrl: options.batchWriteUrl,
586
757
  storePath,
587
758
  // Re-stamp the internal testing marker (ADR-0036) so `createSyncClient`'s option handling selects the
@@ -599,8 +770,11 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
599
770
  // omitted only for a plain test/Node scope with no browser placement.
600
771
  ...(placementEngineHome ? { engineHome: placementEngineHome } : {}),
601
772
  ...(provisionStamp ? { provisionStamp } : {}),
602
- ...(precreatedPglite ? { precreatedPglite } : {}),
603
- ...(options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {}),
773
+ ...(precreatedPgwasm ? { precreatedPgwasm } : {}),
774
+ ...(options.pgwasmInstance && restoreFrom == null ? { pgwasmInstance: options.pgwasmInstance } : {}),
775
+ // The worker's build (ADR-0063) for the boot's own mint; `createSyncClient` checks it against the bound
776
+ // declaration before any store is touched.
777
+ ...(options.build ? { build: options.build } : {}),
604
778
  // App-level schema prep runs IN THE WORKER around the registry schema exec (before/after), exactly as
605
779
  // the in-process client. Worker-entry options, not attach options: functions cannot cross the bridge.
606
780
  ...(options.prepareLocalDbBeforeSchema ? { prepareLocalDbBeforeSchema: options.prepareLocalDbBeforeSchema } : {}),
@@ -613,7 +787,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
613
787
  // SW-direct placement grant (ADR-0049 D1): thread a GRANTED probe's grant into the boot create so the engine
614
788
  // home in this SharedWorker scope opens the OPFS-repacked backend. Absent (false) is the honest IDBFS home —
615
789
  // the declared `backend: "idbfs"` mode or a capability-absence fallback. `createSyncClient` forwards it to
616
- // its `createClientPGlite` boot create.
790
+ // its `createPgwasmClient` boot create.
617
791
  ...(placementOpfsAccess ? { hasOpfsSyncAccess: true } : {}),
618
792
  // ADR-0049 D1/D12: on a capability-absence fallback (OPFS was capable but no home could hold handles) the
619
793
  // engine boots IDBFS and stamps this verbatim reason into the BootReport's `storageFallbackReason`. Absent
@@ -671,7 +845,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
671
845
  booted.onOutboxStatus((status) => broadcastEvent({ kind: "outbox-status", status }));
672
846
  booted.onEventLaneReport((report) => broadcastEvent({ kind: "event-lane-report", report }));
673
847
  } catch (error) {
674
- // A client with no Event lane (a non-canonical write URL, or a caller-owned PGlite) refuses these
848
+ // A client with no Event lane (a non-canonical write URL, or a caller-owned pgwasm) refuses these
675
849
  // subscriptions. Nothing to bridge then — the RPCs refuse identically, so the tab still gets the
676
850
  // honest error at its own call site.
677
851
  syncDebug("worker: no Event lane to bridge", { error });
@@ -684,7 +858,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
684
858
  // Drizzle-over-bridge arrives as the {@link GuardedQueryWireArgs} tuple `[sql, params?, { rowMode? }, use?]`:
685
859
  // the `parsers` map drizzle's pglite session normally passes could not cross the bridge (it is FUNCTIONS,
686
860
  // not clonable), so the tab stripped it and we re-apply the identical map here before executing. Without it
687
- // PGlite's default parsers would turn the identity-parsed OIDs (temporal OIDs + `numeric[]`) into `Date`s
861
+ // pgwasm's default parsers would turn the identity-parsed OIDs (temporal OIDs + `numeric[]`) into `Date`s
688
862
  // and numbers, whereas the in-process drizzle session sees them as raw STRINGS — so a guarded read would
689
863
  // diverge from its in-process twin exactly on those columns. Typed against `GuardedQueryWireArgs` so the
690
864
  // decode here shares the wire contract with the tab-side encoders (attach-sync-client).
@@ -692,7 +866,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
692
866
  const [sql, params, options, use] = args as unknown as GuardedQueryWireArgs;
693
867
  const queryOptions: QueryOptions = {
694
868
  ...(options?.rowMode ? { rowMode: options.rowMode } : {}),
695
- parsers: DRIZZLE_PGLITE_IDENTITY_PARSERS,
869
+ parsers: drizzleParsers,
696
870
  };
697
871
  return active.guardedRawQuery(sql, params, queryOptions, use as readonly SyncTableName<TRegistry>[] | undefined);
698
872
  };
@@ -766,10 +940,22 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
766
940
  // Inspection read (ADR-0032 S2): run straight against the worker's own store — `active.pglite`
767
941
  // exists worker-side (it's the in-process client). `Results` rows/fields structured-clone across
768
942
  // the wire (Dates survive postMessage), so the tab receives the same shape it would in-process.
769
- // The options arg is the clonable RawQueryOptions subset (rowMode) — the REPL's array mode.
943
+ // The options arg is the clonable RawQueryOptions subset (rowMode, plus the ADR-0061 COPY `blob`).
770
944
  return active.rawQuery(args[0] as string, args[1] as unknown[] | undefined, args[2] as RawQueryOptions);
771
945
  case "rawExec":
772
946
  return active.rawExec(args[0] as string, args[1] as RawQueryOptions);
947
+ case "rawTransaction":
948
+ // The atomic raw seam: the whole statement list crossed in ONE dispatch, so the transaction begins
949
+ // and ends inside this call on the worker's own store — the tab can never hold one open. Statements
950
+ // are `{ sql, params, blob? }` plain objects (structured-clone safe), and the `Results[]` returns
951
+ // the same way `rawExec`'s does.
952
+ //
953
+ // NOTHING is rebuilt here for a COPY statement's `blob` (ADR-0061). The tab listed each body's
954
+ // `ArrayBuffer` on the dispatch's transfer list, and a `Uint8Array` survives structured clone AS a
955
+ // `Uint8Array` view over the transferred (zero-copy) buffer — so `args[0]` is already exactly the
956
+ // `RawStatement[]` the in-process client takes, and the single `Uint8Array → Blob` wrap lives where
957
+ // it does in-process: inside that client, at the pgwasm call. The tab's buffers are now detached.
958
+ return active.rawTransaction(args[0] as readonly RawStatement[], args[1] as RawQueryOptions);
773
959
  case "guardedQuery":
774
960
  // Guarded one-shot Drizzle read (ADR-0032 decision 4): the ADR-0041 read gate + the ADR-0021
775
961
  // lazy-group guard run worker-side inside the engine's `guardedRawQuery`, so a read referencing a
@@ -871,6 +1057,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
871
1057
  // state / sync disabled) → no `hydrated` gating at all; otherwise it drives both the `live-initial`
872
1058
  // `hydratingTables` field (the tab's `hydrating` source) and the `live-hydrated` block below.
873
1059
  const hydratingTables = active.hydratingTablesFor({ sql, ...(use ? { use: use as string[] } : {}) });
1060
+ // The guard above starts any lazy relation this subscription reads, exactly as a one-shot read's does —
1061
+ // so publish the new started state (ADR-0059) BEFORE the initial snapshot is posted below, keeping the
1062
+ // same ordering the RPC path has: when the tab's `subscribeLiveRows` resolves, `isSynced` already agrees.
1063
+ publishSyncedIfChanged();
874
1064
 
875
1065
  // Render the query safe to materialise: a JOIN with same-named columns fails BOTH live APIs' temp-view
876
1066
  // creation (`column "title" specified more than once`) unless every output column has a unique alias.
@@ -973,7 +1163,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
973
1163
  const provision = payload as ProvisionPayload;
974
1164
  const storePath = provision.storePath ?? provision.storeId ?? options.storePath ?? "pgxsinkit-overlay-v1";
975
1165
  // The testing memory-backend override rides as an explicit wire field (ADR-0036) — a symbol does not
976
- // survive structured clone, so the store's backend selection travels here and is passed to createPglite.
1166
+ // survive structured clone, so the store's backend selection travels here and is passed to createStore.
977
1167
  const backendOverride = provision.testStoreBackend;
978
1168
  // ADR-0050: bind (or confirm) the store's storage declaration BEFORE the mint — the mint's durability
979
1169
  // comes from it. An explicit disagreement with the bound declaration refuses THIS provision typed.
@@ -1093,7 +1283,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
1093
1283
  }
1094
1284
 
1095
1285
  const provisionStartedAt = nowStamp();
1096
- const pglite = Promise.resolve().then(() => createPglite(storePath, backendOverride));
1286
+ const pglite = Promise.resolve().then(() => createStore(storePath, backendOverride));
1097
1287
  const stamp = pglite.then(() => {
1098
1288
  const readyAt = nowStamp();
1099
1289
  return { initdbMs: readyAt - provisionStartedAt, provisionReadyAt: readyAt };
@@ -1106,14 +1296,29 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
1106
1296
  await pglite;
1107
1297
  });
1108
1298
  provisionAttempt = attempt;
1109
- void attempt.then(
1110
- () => {
1111
- if (provisionAttempt === attempt) provisionAttempt = null;
1112
- },
1113
- () => {
1114
- if (provisionAttempt === attempt) provisionAttempt = null;
1115
- },
1116
- );
1299
+ const attemptStartedAt = nowStamp();
1300
+ provisionAttemptStartedAt = attemptStartedAt;
1301
+ provisionAttemptStorePath = storePath;
1302
+ provisionAttemptPending = true;
1303
+ // Heartbeat the pending attempt onto the rail so a stalled create is VISIBLE (the failure that
1304
+ // motivated the budget showed `boot pgwasm.create start` and then nothing at all). Cleared on
1305
+ // settlement below, so it never outlives the attempt it reports on.
1306
+ const heartbeat = setInterval(() => {
1307
+ syncDebug("worker store provision still pending", {
1308
+ storePath,
1309
+ elapsedMs: Math.round(nowStamp() - attemptStartedAt),
1310
+ });
1311
+ }, PROVISION_PENDING_HEARTBEAT_MS);
1312
+ provisionHeartbeat = heartbeat;
1313
+ const settled = (): void => {
1314
+ clearInterval(heartbeat);
1315
+ if (provisionHeartbeat === heartbeat) provisionHeartbeat = null;
1316
+ if (provisionAttempt === attempt) {
1317
+ provisionAttempt = null;
1318
+ provisionAttemptPending = false;
1319
+ }
1320
+ };
1321
+ void attempt.then(settled, settled);
1117
1322
  void attempt.then(
1118
1323
  () =>
1119
1324
  postBridgeMessage(port, codec, "provision-ack", {
@@ -1229,13 +1434,17 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
1229
1434
  alreadyBooted,
1230
1435
  ...(engineReadyFired ? { engineReady: true } : {}),
1231
1436
  ...milestoneAckFields(),
1437
+ // The started-state snapshot (ADR-0059). `attachSyncClient` resolves at THIS ack, and the
1438
+ // `status` event below is posted after it — so without this field the first synchronous
1439
+ // `isSynced` after attach (a microtask later) would answer from an empty cache.
1440
+ synced: computeSyncedSnapshot(booted),
1232
1441
  });
1233
1442
  postBridgeMessage(port, codec, "event", { kind: "status", status: booted.status });
1234
1443
  },
1235
1444
  (error: unknown) => {
1236
1445
  // The engine boot rejected: tell THIS attaching tab so it rejects `attachSyncClient` instead of
1237
1446
  // hanging on the ack (ADR-0032 FIX 1), and clear `bootPromise` so a later attach retries the
1238
- // boot. Do NOT clear `provisioned`: a resolved provisioned PGlite holds the only open handle on
1447
+ // boot. Do NOT clear `provisioned`: a resolved provisioned pgwasm holds the only open handle on
1239
1448
  // that store, so a retry must adopt it (createSyncClient falls back internally if it rejected).
1240
1449
  if (!alreadyBooted) bootPromise = null;
1241
1450
  postBridgeMessage(port, codec, "attach-ack", {
@@ -1261,21 +1470,32 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
1261
1470
  const { op, args } = payload as RpcPayload;
1262
1471
  const id = envelope.id;
1263
1472
  void (async () => {
1473
+ let result: RpcResultPayload;
1474
+ // An export artefact (backup tarball or diagnostic SQL) crosses zero-copy: transfer its
1475
+ // `ArrayBuffer` (rebuilt into a `File` tab-side, ADR-0035). Every other op's value
1476
+ // structured-clones in place with no transfer list.
1477
+ let transfer: BridgeTransferable[] | undefined;
1264
1478
  try {
1265
1479
  const active = client ?? (await bootPromise);
1266
1480
  if (!active) throw new Error("rpc before attach");
1267
1481
  const value = await dispatchRpc(active, op, args);
1268
- // An export artefact (backup tarball or diagnostic SQL) crosses zero-copy: transfer its
1269
- // `ArrayBuffer` (rebuilt into a `File` tab-side, ADR-0035). Every other op's value
1270
- // structured-clones in place with no transfer list.
1271
- const transfer =
1482
+ transfer =
1272
1483
  op === "exportStore" || op === "exportDiagnostics" || op === "exportData"
1273
1484
  ? [(value as ExportArtefactWire).buffer]
1274
1485
  : undefined;
1275
- postBridgeMessage(port, codec, "rpc-result", { ok: true, value }, id, transfer);
1486
+ result = { ok: true, value };
1276
1487
  } catch (error) {
1277
- postBridgeMessage(port, codec, "rpc-result", { ok: false, error: serializeError(error) }, id);
1488
+ result = { ok: false, error: serializeError(error) };
1278
1489
  }
1490
+ // ADR-0059's ordering guarantee, for EVERY op rather than a curated list: several ops move the
1491
+ // started state (`ensureSynced`/`desync`/`discardEphemeral` explicitly, a `guardedQuery` or an
1492
+ // ordinary write implicitly, through the guard) and a rejected one may have moved it before it
1493
+ // failed — so publish here, after the dispatch settled either way and BEFORE the result is posted.
1494
+ // Events and results share one port and `MessagePort` delivery is FIFO, so on the tab
1495
+ // `await client.ensureSynced(["x"]); client.isSynced("x")` is already true. Deduped: an op that
1496
+ // changed nothing posts no event.
1497
+ publishSyncedIfChanged();
1498
+ postBridgeMessage(port, codec, "rpc-result", result, id, transfer);
1279
1499
  })();
1280
1500
  break;
1281
1501
  }
@@ -1416,6 +1636,12 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
1416
1636
  throw error;
1417
1637
  } finally {
1418
1638
  ports.clear();
1639
+ // A torn-down host reports on nothing: stop the pending-provision heartbeat even when the attempt it
1640
+ // watches is the stalled one that never settles.
1641
+ if (provisionHeartbeat !== null) {
1642
+ clearInterval(provisionHeartbeat);
1643
+ provisionHeartbeat = null;
1644
+ }
1419
1645
  setSyncDebugSink(undefined);
1420
1646
  }
1421
1647
  };
@@ -1476,6 +1702,9 @@ function serializeError(error: unknown): BridgeErrorWire {
1476
1702
  if (error instanceof ExecutionLimitMismatchError) {
1477
1703
  return { message: error.message, detail: executionLimitMismatchToWire(error) };
1478
1704
  }
1705
+ if (error instanceof ProvisionStalledError) {
1706
+ return { message: error.message, detail: provisionStalledToWire(error) };
1707
+ }
1479
1708
  if (error instanceof Error) {
1480
1709
  const detail = (error as Error & { detail?: unknown }).detail;
1481
1710
  return {
@@ -1821,6 +2050,15 @@ function invalidDeclarationField(declaration: SyncStorageDeclaration): string |
1821
2050
  if (declaration.durability !== undefined && !isStorageDurability(declaration.durability)) {
1822
2051
  return `durability "${String(declaration.durability)}"`;
1823
2052
  }
2053
+ if (declaration.build !== undefined && !isStorageBuild(declaration.build)) {
2054
+ return `build "${String(declaration.build)}"`;
2055
+ }
2056
+ // ADR-0050 addendum 2026-09-08: a declared engine must be `{ module }` naming an absolute or
2057
+ // origin-relative module URL. A malformed one is refused here rather than at the first mint, so a
2058
+ // typo surfaces at the handshake instead of halfway through a boot.
2059
+ if (declaration.engine !== undefined && !isStorageEngineDeclaration(declaration.engine)) {
2060
+ return `engine ${JSON.stringify(declaration.engine)}`;
2061
+ }
1824
2062
  return undefined;
1825
2063
  }
1826
2064