@pgxsinkit/client 0.2.7 → 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 +4 -5
  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
package/src/sync/types.ts CHANGED
@@ -1,153 +1,25 @@
1
1
  // Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).
2
2
  // Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
3
- import type { ChangeMessage, FetchError, Row, ShapeStreamInterface, ShapeStreamOptions } from "@electric-sql/client";
4
- import type { PgliteDatabase } from "drizzle-orm/pglite";
3
+ //
4
+ // What remains here is only what the NATIVE path uses. The shape-stream option and message types this
5
+ // file used to re-export were `@electric-sql/client`'s, and nothing reads them any more: the transport
6
+ // is `@durable-streams/client` and the change contract is `@pgxsinkit/contracts`' `SyncChange`.
5
7
 
6
- import type { SyncTableRegistry } from "@pgxsinkit/contracts";
7
-
8
- import type { GroupBootStamp } from "../boot-report";
9
-
10
- // Re-exported so in-repo tests (e.g. tests/unit/sync-engine.test.ts) can name these Electric types
11
- // via this engine module — they resolve here, inside @pgxsinkit/client's dependency scope, without
12
- // the root workspace needing a direct dependency on the Electric client packages.
13
- export type { Row, ShapeStreamOptions } from "@electric-sql/client";
14
- export type { MultiShapeMessages } from "@electric-sql/experimental";
8
+ import type { SyncChange } from "@pgxsinkit/contracts";
15
9
 
16
10
  export type Lsn = bigint;
17
11
 
18
12
  export type SubscriptionKey = string;
19
13
  export type InitialInsertMethod = "insert" | "copy" | "json";
20
14
 
21
- /** Default hard cap on commit-transaction attempts before the engine goes degraded (ADR-0009). */
22
- export const DEFAULT_MAX_COMMIT_RETRIES = 5;
23
-
24
15
  /**
25
- * Per-shape options for the group form (ADR-0029 D1). Every table-scoped fact — local table identity,
26
- * projection, primary keys, apply strategy, column types — is derived by the engine from the
27
- * group-level `registry` and this shape's `tableKey`; none is passed here. Only the Electric shape
28
- * stream, an optional per-shape backfill override, and the must-refetch hook remain.
16
+ * A change the fold has established is the net UPSERT of a complete row.
17
+ *
18
+ * The narrowing is what the bulk paths rely on: `value` carries every projected column, so the rows
19
+ * can go out as one multi-row statement (or a COPY) with no per-row branch on which columns are
20
+ * present. Guaranteed by the engine, not merely hoped for — `row_to_json_cols` emits every column of
21
+ * the shape's `out_cols` on every upsert.
29
22
  */
30
- export interface ShapeToTableOptions {
31
- shape: ShapeStreamOptions<Row<unknown>>;
32
- /** The registry table key this shape applies into — the engine's sole per-table spec (ADR-0029 D1). */
33
- tableKey: string;
34
- /**
35
- * Must-refetch override: replaces the default `TRUNCATE` cache wipe (ADR-0029 D4). Receives a Drizzle
36
- * handle bound to the commit transaction (`drizzleOverPg(tx)`), so a scoped clear authors tier-①
37
- * (`db.delete(table).where(…)`).
38
- */
39
- onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;
40
- /**
41
- * Per-shape initial-backfill apply strategy override (ADR-0009 decisions 2 + 3). In a consistency
42
- * group each shape resolves its own apply path, so one shape's backfill never forces the rest onto
43
- * plain `INSERT`. When set it wins over the registry-classified strategy; otherwise the strategy is
44
- * derived from the entry and mapped, else the group-level default applies.
45
- */
46
- initialInsertMethod?: InitialInsertMethod | undefined;
47
- }
48
-
49
- export interface SyncShapesToTablesOptions {
50
- key: string | null;
51
- /** The engine's per-table spec source (ADR-0029 D1): every shape's `tableKey` resolves against it. */
52
- registry: SyncTableRegistry;
53
- shapes: Record<string, ShapeToTableOptions>;
54
- /**
55
- * ADR-0042: this group's sync bookkeeping (subscription cursor + tagged-subquery reason sets) is
56
- * SESSION-scoped — stored in the engine's `pg_temp` metadata relations that die with the engine, not the
57
- * durable ones. Set for an `ephemeral`-retention group, whose whole cluster is already TEMP: the cursor
58
- * and tags then die with the rows they index, so a returning engine re-streams the shape from scratch
59
- * instead of resuming a stale durable cursor over a recreated-empty TEMP cluster. Default `false` — a
60
- * persistent group's storage is identical whether the bit is `false` or unset; it only scopes an
61
- * ephemeral group's bookkeeping. One storage-scope bit; the engine never learns the retention model.
62
- */
63
- sessionScoped?: boolean | undefined;
64
- initialInsertMethod?: InitialInsertMethod | undefined;
65
- onInitialSync?: (() => void) | undefined;
66
- /**
67
- * Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003). When present, the group is on a
68
- * PROVABLY-FRESH store (a claimed schemaless spare — the caller's `freshStore` hint), so the engine
69
- * starts the shape streams and BUFFERS their catch-up into the memory inbox immediately — WITHOUT the
70
- * two DB touches the sequential path takes first (`initMetadataTables`, `getSubscriptionState`) — and
71
- * gates every commit (the first write to PGlite) until this promise resolves. The owner resolves it
72
- * once the local store is ready (schema exec + journal recovery + store-version reconcile complete), so
73
- * the network catch-up overlaps those local phases instead of running strictly after them. Absent → the
74
- * exact sequential path (warm stores, and every non-overlap caller). Because a fresh store has no prior
75
- * subscription state, the overlap treats the group as a new subscription (`subState === null`), which the
76
- * `freshStore` gate guarantees.
77
- */
78
- dbReady?: Promise<void> | undefined;
79
- /** Stream-level (network / fetch) error from Electric, forwarded to `MultiShapeStream.subscribe`. */
80
- onError?: ((error: FetchError | Error) => void) | undefined;
81
- /**
82
- * Commit-level error surfacing (ADR-0009 decision 5). Fired when a sync commit transaction
83
- * still fails after `maxCommitRetries` jittered-backoff attempts. The engine then holds its
84
- * buffer and committed frontier (never advancing `isUpToDate` on an unapplied commit) so the
85
- * read cache cannot silently diverge; recovery is a later commit or a restart/refetch.
86
- */
87
- onSyncError?: ((error: Error) => void) | undefined;
88
- /**
89
- * Fired whenever the stream delivers a batch — i.e. a fetch just succeeded (ADR-0013 Phase 3).
90
- * The runtime uses this as the read path's "alive again" signal to clear an `auth-needed` status
91
- * once sync resumes after re-authentication.
92
- */
93
- onSyncActivity?: (() => void) | undefined;
94
- /** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */
95
- maxCommitRetries?: number | undefined;
96
- /**
97
- * Backoff before re-attempting a failed commit, as a function of the attempt number. Defaults to
98
- * the runtime's jittered backoff (`computeRetryDelayMs`). A test seam — pass `() => 0` for an
99
- * immediate retry instead of sleeping the real backoff.
100
- */
101
- commitRetryDelayMs?: ((attempt: number) => number) | undefined;
102
- /**
103
- * Boot observability (ADR-0034): a per-group accumulator, stamped as this group's stream chain delivers
104
- * batches (`onBatchDelivered`), applies commits into PGlite (`onApply`), and reaches initial sync
105
- * (`markReady`). Present only for eager + promoted BOOT groups; absent for on-demand lazy starts and any
106
- * boot without report instrumentation.
107
- */
108
- bootStamp?: GroupBootStamp | undefined;
109
- }
110
-
111
- export interface SyncShapesToTablesResult {
112
- unsubscribe: () => void;
113
- readonly isUpToDate: boolean;
114
- streams: Record<string, ShapeStreamInterface<Row<unknown>>>;
115
- }
116
-
117
- /**
118
- * Single-shape options (ADR-0029 D6): thin sugar over the group form, taking the same entry-based
119
- * fields plus a `shapeKey`. Every table-scoped fact is derived from `(registry, tableKey)`.
120
- */
121
- export interface SyncShapeToTableOptions {
122
- shape: ShapeStreamOptions<Row<unknown>>;
123
- registry: SyncTableRegistry;
124
- tableKey: string;
125
- shapeKey: string | null;
126
- /** ADR-0042: SESSION-scope this shape's cursor + tags (ephemeral retention); see {@link SyncShapesToTablesOptions.sessionScoped}. */
127
- sessionScoped?: boolean | undefined;
128
- initialInsertMethod?: InitialInsertMethod | undefined;
129
- onInitialSync?: (() => void) | undefined;
130
- onError?: ((error: FetchError | Error) => void) | undefined;
131
- /** Commit-level error surfacing (ADR-0009 decision 5); see {@link SyncShapesToTablesOptions.onSyncError}. */
132
- onSyncError?: ((error: Error) => void) | undefined;
133
- /** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */
134
- maxCommitRetries?: number | undefined;
135
- /** Backoff before re-attempting a failed commit; see {@link SyncShapesToTablesOptions.commitRetryDelayMs}. */
136
- commitRetryDelayMs?: ((attempt: number) => number) | undefined;
137
- onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;
138
- }
139
-
140
- export interface SyncShapeToTableResult {
141
- unsubscribe: () => void;
142
- readonly isUpToDate: boolean;
143
- stream: ShapeStreamInterface<Row<unknown>>;
144
- }
145
-
146
- export interface ElectricSyncOptions {
147
- debug?: boolean;
148
- metadataSchema?: string;
149
- }
150
-
151
- export type InsertChangeMessage = ChangeMessage<Row<unknown>> & {
152
- headers: { operation: "insert" };
23
+ export type UpsertChangeMessage = SyncChange & {
24
+ headers: { operation: "upsert" };
153
25
  };
package/src/testing.ts CHANGED
@@ -11,8 +11,8 @@
11
11
  // The helpers mint plain options objects that ALSO carry the module-internal {@link TEST_STORE_BACKEND}
12
12
  // marker at runtime — invisible in the public return type. Consumers SPREAD them into the client options:
13
13
  //
14
- // createSyncClient({ ...memoryStoreForTests("my-test"), registry, electricUrl, batchWriteUrl })
15
- // createSyncClient({ ...testStoreAcknowledgment(), pgliteInstance, registry, electricUrl, batchWriteUrl })
14
+ // createSyncClient({ ...memoryStoreForTests("my-test"), registry, controlPlaneUrl, streamBaseUrl, batchWriteUrl })
15
+ // createSyncClient({ ...testStoreAcknowledgment(), pgliteInstance, registry, controlPlaneUrl, streamBaseUrl, batchWriteUrl })
16
16
 
17
17
  import { TEST_STORE_BACKEND } from "./store-path";
18
18
 
@@ -78,6 +78,7 @@ import {
78
78
  executionLimitMismatchFromWire,
79
79
  type ExecutionLimitConfig,
80
80
  isStaleIdentity,
81
+ provisionStalledFromWire,
81
82
  readControlEnvelope,
82
83
  wrapControlEnvelope,
83
84
  } from "./engine-control";
@@ -228,7 +229,9 @@ export class ElectedEngineUnconstructibleError extends Error {
228
229
  *
229
230
  * - **SW-direct.** The attempt lives in the SharedWorker and is left running (an in-flight store open cannot be
230
231
  * safely abandoned — a second open against the same store is an ownership conflict). A later
231
- * {@link attachSyncClient} ADOPTS it if it completed and WAITS on it if it is genuinely stuck; a retried
232
+ * {@link attachSyncClient} ADOPTS it if it completed, and waits on a genuinely stuck one only within the
233
+ * engine's spare-store adoption budget (`provisionAdoptionBudgetMs`, default 20000 from the attempt's start),
234
+ * past which that attach is refused with {@link ProvisionStalledError} instead of hanging; a retried
232
235
  * provision re-acks against the SAME attempt, so a second open never starts. A stuck storage open blocks that
233
236
  * store whether or not it was ever provisioned, and expiring this promise neither causes nor cures that.
234
237
  * - **Elected.** This deadline is ALSO the provision claim's expiry, so the claim releases here too. When it is
@@ -2842,6 +2845,10 @@ function rebuildError(error: RpcResultPayload["error"]): Error {
2842
2845
  if (error && "detail" in error) {
2843
2846
  const mismatch = executionLimitMismatchFromWire(error.detail);
2844
2847
  if (mismatch !== undefined) return mismatch;
2848
+ // An attach refused because the engine's in-flight spare provision outran the adoption budget: the host
2849
+ // branches on the TYPE to rebind to a fresh store, so it must cross the bridge as the class.
2850
+ const stalled = provisionStalledFromWire(error.detail);
2851
+ if (stalled !== undefined) return stalled;
2845
2852
  // A no-grant engine home refusing an `opfs-committed` store: the consumer branches on the TYPE to offer
2846
2853
  // the destroy-then-rebuild exit, so it must cross the bridge as the class, not a name-tagged plain Error.
2847
2854
  const unreachable = committedStoreUnreachableFromWire(error.detail);
@@ -55,6 +55,8 @@ import {
55
55
  ExecutionLimitMismatchError,
56
56
  executionLimitMismatchToWire,
57
57
  type ExecutionLimitConfig,
58
+ ProvisionStalledError,
59
+ provisionStalledToWire,
58
60
  readControlEnvelope,
59
61
  shouldApplyControlMessage,
60
62
  wrapControlEnvelope as controlEnvelope,
@@ -112,6 +114,13 @@ const DRIZZLE_PGLITE_IDENTITY_PARSERS: ParserOptions = {
112
114
  1182: identityParser,
113
115
  };
114
116
 
117
+ /**
118
+ * Cadence (ms) of the "worker store provision still pending" heartbeat rail line, emitted from the moment a
119
+ * spare provision attempt starts until it settles. Diagnosability only — no policy hangs off it (the bound is
120
+ * `provisionAdoptionBudgetMs`): it is what turns a silent stall into a visible one on the rail.
121
+ */
122
+ const PROVISION_PENDING_HEARTBEAT_MS = 5_000;
123
+
115
124
  export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
116
125
  /**
117
126
  * The sync registry — imported as CODE by the worker file, never cloned into it (ADR-0032 decision 4).
@@ -134,7 +143,10 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
134
143
  * Takes a plain store PATH (ADR-0036); the internal `backendOverride` is the test lane's memory selection.
135
144
  */
136
145
  createPglite?: (storePath: string, backendOverride?: "memory") => Promise<ClientPGlite>;
137
- electricUrl: string;
146
+ /** The pgxsinkit control plane — subscribe, token re-mint, convergence barrier (ADR-0055). */
147
+ controlPlaneUrl: string;
148
+ /** The edge that serves durable-streams reads. */
149
+ streamBaseUrl: string;
138
150
  batchWriteUrl: string;
139
151
  /** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */
140
152
  requestHeaders?: Record<string, string>;
@@ -176,6 +188,19 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
176
188
  * channel to probe, so an enabled value is rejected as unsupported before engine boot.
177
189
  */
178
190
  executionLimit?: ExecutionLimitConfig;
191
+ /**
192
+ * How long an attach may wait for the engine's IN-FLIGHT spare provision (ADR-0032 decision 5) before it
193
+ * fails typed with {@link ProvisionStalledError} instead of waiting. Measured from the provision attempt's
194
+ * START, not from the attach — a tab attaching late inherits however much of the budget the spare has
195
+ * already burned. The stalled attempt is LEFT RUNNING (an in-flight OPFS/IDB store open cannot be safely
196
+ * abandoned — a second open against the same store is an ownership conflict), so a later attach still
197
+ * ADOPTS it if it completes; refusing costs at most one extra initdb, never data (the spare is schemaless
198
+ * and holds no writes). Default 20000. `Number.POSITIVE_INFINITY` restores the unbounded wait (NOT
199
+ * recommended: a stalled spare then hangs every attach forever). Must be > 0 — anything else throws at
200
+ * construction. This bounds the ACCELERATOR only; nothing is inferred from it about engine liveness
201
+ * (ADR-0049 D5's refusal of timing-based engine-death detection is unchanged).
202
+ */
203
+ provisionAdoptionBudgetMs?: number;
179
204
  /** Injected transport binder. Defaults to auto-detecting the SharedWorker/dedicated-worker global scope. */
180
205
  installGlobal?: boolean;
181
206
  /** Injected codec (ADR-0032 S2 §1). Defaults to the v1 identity codec. */
@@ -264,6 +289,17 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
264
289
  const codec = options.codec ?? identityCodec;
265
290
  const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30_000;
266
291
  const convergenceIntervalMs = options.convergenceIntervalMs ?? 15_000;
292
+ // The spare-store adoption budget (see the option's doc): the bound on how long an attach waits for an
293
+ // in-flight provision. Validated here — a non-positive/NaN budget would refuse every attach that met a
294
+ // pending spare, so it fails at construction rather than at the first sign-in.
295
+ const provisionAdoptionBudgetMs = options.provisionAdoptionBudgetMs ?? 20_000;
296
+ if (!(provisionAdoptionBudgetMs > 0)) {
297
+ throw new Error(
298
+ `[pgxsinkit] provisionAdoptionBudgetMs must be > 0 (got ${String(options.provisionAdoptionBudgetMs)}); it ` +
299
+ "bounds how long an attach waits for an in-flight spare provision. Use Number.POSITIVE_INFINITY for the " +
300
+ "unbounded wait.",
301
+ );
302
+ }
267
303
  // ADR-0049 D1: the placement probe's OPFS grant for THIS SharedWorker lifetime. Set true only by a GRANTED
268
304
  // `shared-worker` (SW-direct) probe, so both the provision-mint (default `createPglite` factory) and the boot
269
305
  // create (below) resolve the OPFS-repacked backend. False is the honest capability-absence invariant — the
@@ -376,7 +412,18 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
376
412
  // A provision request performs a bounded authority read before it may mint. An attach that arrives during
377
413
  // that read waits for the attempt to settle, then either adopts the minted store or runs the ordinary boot
378
414
  // path. This keeps provision a pure accelerator without racing a replacement underneath live deletion.
415
+ // That wait is BOUNDED by `provisionAdoptionBudgetMs` (see `boot`), so a spare whose create never settles
416
+ // refuses the attach typed instead of hanging it — hence the start stamp, the settlement flag, and the
417
+ // attempt's store path tracked alongside the promise.
379
418
  let provisionAttempt: Promise<void> | null = null;
419
+ /** `nowStamp()` at which the current {@link provisionAttempt} was created — the budget's origin. */
420
+ let provisionAttemptStartedAt = 0;
421
+ /** Whether {@link provisionAttempt} is still in flight (settlement is observed, never inferred from timing). */
422
+ let provisionAttemptPending = false;
423
+ /** The store path the current attempt is minting — what a refusal reports, resolved before any boot runs. */
424
+ let provisionAttemptStorePath = "";
425
+ /** The "still pending" heartbeat's handle; cleared the moment the attempt settles (never outlives it). */
426
+ let provisionHeartbeat: ReturnType<typeof setInterval> | null = null;
380
427
 
381
428
  // ─── Outbound-convergence gate — the tab's Offline toggle over the bridge (ADR-0032 S3) ───────────
382
429
  // The worker owns convergence; the tab forwards its Offline flag as `set-online`. When suppressed the
@@ -510,9 +557,46 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
510
557
 
511
558
  const boot = async (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {
512
559
  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);
560
+ // Provision owns no recovery policy, and it is a pure ACCELERATOR — so this attach waits for an in-flight
561
+ // attempt only within `provisionAdoptionBudgetMs`, counted from the ATTEMPT's start (a late attach inherits
562
+ // the burned budget). A declined/settled attempt leaves `provisioned` null and this attach continues through
563
+ // createSyncClient's full phase machine; a spare whose create never settles instead REFUSES this attach typed
564
+ // (`ProvisionStalledError`), so the host can rebind to a fresh store rather than wait forever. The stalled
565
+ // attempt is deliberately left running — an in-flight store open cannot be safely abandoned (a second open is
566
+ // an ownership conflict) — and a later attach still adopts it if it completes. Nothing here infers engine
567
+ // death from elapsed time (ADR-0049 D5 unchanged); it bounds the accelerator only.
568
+ const pendingAttempt = provisionAttempt;
569
+ if (pendingAttempt !== null) {
570
+ const startedAt = provisionAttemptStartedAt;
571
+ const remainingMs = Math.max(0, provisionAdoptionBudgetMs - (nowStamp() - startedAt));
572
+ if (Number.isFinite(remainingMs)) {
573
+ // A real timer: the worker has no injected clock, so tests drive this with a small budget.
574
+ let budgetTimer: ReturnType<typeof setTimeout> | undefined;
575
+ await Promise.race([
576
+ pendingAttempt.catch(() => undefined),
577
+ new Promise<void>((resolve) => {
578
+ budgetTimer = setTimeout(resolve, remainingMs);
579
+ }),
580
+ ]);
581
+ if (budgetTimer !== undefined) clearTimeout(budgetTimer);
582
+ } else {
583
+ // `Number.POSITIVE_INFINITY` — the opted-in unbounded wait.
584
+ await pendingAttempt.catch(() => undefined);
585
+ }
586
+ if (provisionAttemptPending) {
587
+ const elapsedMs = Math.round(nowStamp() - startedAt);
588
+ syncDebug("worker provision adoption stalled — attach refused", {
589
+ storePath: provisionAttemptStorePath,
590
+ elapsedMs,
591
+ budgetMs: provisionAdoptionBudgetMs,
592
+ });
593
+ throw new ProvisionStalledError({
594
+ storePath: provisionAttemptStorePath,
595
+ elapsedMs,
596
+ budgetMs: provisionAdoptionBudgetMs,
597
+ });
598
+ }
599
+ }
516
600
  const attachLimit = attach.executionLimit?.maxDispatchMs;
517
601
  if (placementEngineHome === "shared-worker" && attachLimit !== undefined) {
518
602
  throw new Error(
@@ -581,7 +665,8 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
581
665
  // elected dedicated engine boots the OPFS-repacked backend it actually holds instead of racing to `idbfs`.
582
666
  bootPromise = createSyncClient<TRegistry>({
583
667
  registry,
584
- electricUrl: options.electricUrl,
668
+ controlPlaneUrl: options.controlPlaneUrl,
669
+ streamBaseUrl: options.streamBaseUrl,
585
670
  batchWriteUrl: options.batchWriteUrl,
586
671
  storePath,
587
672
  // Re-stamp the internal testing marker (ADR-0036) so `createSyncClient`'s option handling selects the
@@ -1106,14 +1191,29 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
1106
1191
  await pglite;
1107
1192
  });
1108
1193
  provisionAttempt = attempt;
1109
- void attempt.then(
1110
- () => {
1111
- if (provisionAttempt === attempt) provisionAttempt = null;
1112
- },
1113
- () => {
1114
- if (provisionAttempt === attempt) provisionAttempt = null;
1115
- },
1116
- );
1194
+ const attemptStartedAt = nowStamp();
1195
+ provisionAttemptStartedAt = attemptStartedAt;
1196
+ provisionAttemptStorePath = storePath;
1197
+ provisionAttemptPending = true;
1198
+ // Heartbeat the pending attempt onto the rail so a stalled create is VISIBLE (the failure that
1199
+ // motivated the budget showed `boot pglite.create start` and then nothing at all). Cleared on
1200
+ // settlement below, so it never outlives the attempt it reports on.
1201
+ const heartbeat = setInterval(() => {
1202
+ syncDebug("worker store provision still pending", {
1203
+ storePath,
1204
+ elapsedMs: Math.round(nowStamp() - attemptStartedAt),
1205
+ });
1206
+ }, PROVISION_PENDING_HEARTBEAT_MS);
1207
+ provisionHeartbeat = heartbeat;
1208
+ const settled = (): void => {
1209
+ clearInterval(heartbeat);
1210
+ if (provisionHeartbeat === heartbeat) provisionHeartbeat = null;
1211
+ if (provisionAttempt === attempt) {
1212
+ provisionAttempt = null;
1213
+ provisionAttemptPending = false;
1214
+ }
1215
+ };
1216
+ void attempt.then(settled, settled);
1117
1217
  void attempt.then(
1118
1218
  () =>
1119
1219
  postBridgeMessage(port, codec, "provision-ack", {
@@ -1416,6 +1516,12 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
1416
1516
  throw error;
1417
1517
  } finally {
1418
1518
  ports.clear();
1519
+ // A torn-down host reports on nothing: stop the pending-provision heartbeat even when the attempt it
1520
+ // watches is the stalled one that never settles.
1521
+ if (provisionHeartbeat !== null) {
1522
+ clearInterval(provisionHeartbeat);
1523
+ provisionHeartbeat = null;
1524
+ }
1419
1525
  setSyncDebugSink(undefined);
1420
1526
  }
1421
1527
  };
@@ -1476,6 +1582,9 @@ function serializeError(error: unknown): BridgeErrorWire {
1476
1582
  if (error instanceof ExecutionLimitMismatchError) {
1477
1583
  return { message: error.message, detail: executionLimitMismatchToWire(error) };
1478
1584
  }
1585
+ if (error instanceof ProvisionStalledError) {
1586
+ return { message: error.message, detail: provisionStalledToWire(error) };
1587
+ }
1479
1588
  if (error instanceof Error) {
1480
1589
  const detail = (error as Error & { detail?: unknown }).detail;
1481
1590
  return {
@@ -389,3 +389,92 @@ export function engineRelocatedFromWire(detail: unknown): EngineRelocatedError |
389
389
  if (candidate.outcome !== "not-dispatched" && candidate.outcome !== "unknown") return undefined;
390
390
  return new EngineRelocatedError(candidate.outcome);
391
391
  }
392
+
393
+ // ─── E. ProvisionStalledError (the spare-store adoption budget) ───────────────────
394
+
395
+ /** The stable clone-safe discriminator a stalled spare adoption carries on the wire. Branch on this, never prose. */
396
+ export const PROVISION_STALLED_CODE = "provision-stalled";
397
+
398
+ /**
399
+ * The clone-safe wire form of a stalled spare adoption. Like the execution-limit and relocation errors it
400
+ * travels inside the EXISTING bridge error `detail` field (the `{ message, detail }` shape `serializeError`
401
+ * produces), so no new protocol field is needed; the attach side calls {@link provisionStalledFromWire} on
402
+ * every bridge error `detail` and rebuilds the CLASS.
403
+ */
404
+ export interface ProvisionStalledWire {
405
+ code: typeof PROVISION_STALLED_CODE;
406
+ storePath: string;
407
+ elapsedMs: number;
408
+ budgetMs: number;
409
+ }
410
+
411
+ /**
412
+ * Thrown at attach when the engine's IN-FLIGHT spare provision (the pre-spawned schemaless store of ADR-0032
413
+ * decision 5) has not settled within the engine's `provisionAdoptionBudgetMs` — measured from the provision
414
+ * attempt's START, not from this attach. The spare is a pure ACCELERATOR, never a boot dependency, so an
415
+ * attach must never hang behind one: past the budget the attach is REFUSED typed, and the host can rebind to
416
+ * a fresh store (or retry) instead of sitting on "starting local database…" forever.
417
+ *
418
+ * What this is NOT: engine-death detection. Nothing is inferred about the engine's liveness from the elapsed
419
+ * time (ADR-0049 D5 refuses timing-based death inference, unchanged). The stalled attempt is deliberately LEFT
420
+ * RUNNING — an in-flight OPFS/IDB store open cannot be safely abandoned, a second open against the same store
421
+ * being an ownership conflict — so a later attach still ADOPTS it if it completes. Abandoning a slow spare
422
+ * costs at most one extra initdb, never data: the spare is schemaless and holds no writes.
423
+ *
424
+ * Survives the worker bridge AS THIS CLASS via the tagged {@link ProvisionStalledWire} `detail` (the same
425
+ * tagged-detail pair the execution-limit and relocation errors use), so a consumer can `instanceof`-branch it.
426
+ */
427
+ export class ProvisionStalledError extends Error {
428
+ readonly code = PROVISION_STALLED_CODE;
429
+ /** The store whose in-flight spare provision has not settled. */
430
+ readonly storePath: string;
431
+ /** How long that provision attempt has been running, in ms (measured from ITS start). */
432
+ readonly elapsedMs: number;
433
+ /** The budget it outran, in ms (the engine's effective `provisionAdoptionBudgetMs`). */
434
+ readonly budgetMs: number;
435
+
436
+ constructor(init: { storePath: string; elapsedMs: number; budgetMs: number }) {
437
+ super(
438
+ `[pgxsinkit] attach refused for ${JSON.stringify(init.storePath)}: the spare store's create has not ` +
439
+ `settled within ${init.budgetMs}ms (${init.elapsedMs}ms elapsed since the provision started). The ` +
440
+ "spare is a pure ACCELERATOR, never a boot dependency, so the attach is refused instead of waiting " +
441
+ 'forever — rebind to a fresh store (or retry the attach) rather than showing an endless "starting ' +
442
+ 'local database". The stalled attempt is LEFT RUNNING (an in-flight store open cannot be safely ' +
443
+ "abandoned), so a later attach adopts it if it completes. Nothing is inferred here about the engine " +
444
+ "being alive or dead. Tune or disable the bound with `defineSyncWorker`'s `provisionAdoptionBudgetMs`.",
445
+ );
446
+ this.name = "ProvisionStalledError";
447
+ this.storePath = init.storePath;
448
+ this.elapsedMs = init.elapsedMs;
449
+ this.budgetMs = init.budgetMs;
450
+ }
451
+ }
452
+
453
+ /** Encode a {@link ProvisionStalledError} to its clone-safe wire form for the bridge error `detail` field. */
454
+ export function provisionStalledToWire(error: ProvisionStalledError): ProvisionStalledWire {
455
+ return {
456
+ code: PROVISION_STALLED_CODE,
457
+ storePath: error.storePath,
458
+ elapsedMs: error.elapsedMs,
459
+ budgetMs: error.budgetMs,
460
+ };
461
+ }
462
+
463
+ /**
464
+ * Reconstruct a typed {@link ProvisionStalledError} from a bridge error's `detail`. STRICT shape check:
465
+ * returns `undefined` for anything that is not exactly the `{ code: "provision-stalled", storePath,
466
+ * elapsedMs, budgetMs }` wire form (a foreign/absent detail, a wrong code, a missing/mistyped field, a
467
+ * non-object), so an unrelated failure is never misclassified as a stalled spare.
468
+ */
469
+ export function provisionStalledFromWire(detail: unknown): ProvisionStalledError | undefined {
470
+ if (typeof detail !== "object" || detail === null) return undefined;
471
+ const candidate = detail as { code?: unknown; storePath?: unknown; elapsedMs?: unknown; budgetMs?: unknown };
472
+ if (candidate.code !== PROVISION_STALLED_CODE) return undefined;
473
+ if (typeof candidate.storePath !== "string") return undefined;
474
+ if (typeof candidate.elapsedMs !== "number" || typeof candidate.budgetMs !== "number") return undefined;
475
+ return new ProvisionStalledError({
476
+ storePath: candidate.storePath,
477
+ elapsedMs: candidate.elapsedMs,
478
+ budgetMs: candidate.budgetMs,
479
+ });
480
+ }
@@ -1,54 +0,0 @@
1
- import { type BackoffOptions } from "@electric-sql/client";
2
- /**
3
- * The read path's OUTAGE seam (board ADR-0010 "offline return").
4
- *
5
- * Every shape fetch runs inside Electric's `createFetchWithBackoff`, which retries a failed attempt
6
- * **forever** (`maxRetries: Infinity` — "clients may go offline and come back") and only re-throws a
7
- * non-retryable 4xx. A network-level failure therefore never escapes that wrapper: `ShapeStream.onError`
8
- * is never called, so neither is `onReadStreamError`, and a runtime keying off those alone reports
9
- * `syncing` for as long as the machine stays offline. `backoffOptions.onFailedAttempt` is the ONLY signal
10
- * Electric surfaces from inside the loop, and it is what this probe turns into a runtime status change.
11
- *
12
- * The two seams PARTITION the failures, they do not overlap:
13
- *
14
- * - **Retried inside the wrapper** (a rejected request — the offline case, with no HTTP status at all — a
15
- * 5xx, or a 429) → nobody else will ever hear about it. This probe's `onStalled`.
16
- * - **Escapes the wrapper** (any other 4xx: 401/403 auth, 404/409/… structural) → `ShapeStream.onError`,
17
- * i.e. `createShapeErrorHandler` → `onAuthError` / `onReadStreamError`, which own it and carry a real
18
- * error message. Deliberately NOT reported here, so a rejected token still surfaces as the more
19
- * actionable `auth-needed` and an expired handle's 409 stays the recovery it is.
20
- * - **A deliberate abort** — a stream teardown, a hidden tab (`PAUSE_STREAM`), a live-request timeout, a
21
- * system wake, and the live-tail nudge's `forceDisconnectAndRefresh` all abort the in-flight request,
22
- * and Electric calls `onFailedAttempt` for the resulting `AbortError` like any other. None is an
23
- * outage; counting them would report "connection needed" for backgrounding a tab.
24
- *
25
- * `onFailedAttempt` carries no arguments, so the classification is made one layer down, in the
26
- * `fetchClient` this probe supplies: it records how the attempt that just settled would be treated by the
27
- * very next lines of Electric's own catch block. Recovery needs nothing here — the runtime clears a
28
- * stream-degraded status on the next delivered batch (`onSyncActivity`), which a resumed stream produces
29
- * on its first successful poll.
30
- */
31
- export interface ReadStreamStallProbe {
32
- /** Pass as `ShapeStreamOptions.backoffOptions` — Electric's defaults plus the failed-attempt hook. */
33
- backoffOptions: BackoffOptions;
34
- /** Pass as `ShapeStreamOptions.fetchClient` — the innermost transport, wrapped to classify each attempt. */
35
- fetchClient: typeof fetch;
36
- }
37
- /**
38
- * The CALL signature of `fetch`, without the runtime-specific statics (Bun's global carries `preconnect`).
39
- * A ShapeStream only ever invokes its `fetchClient` as a plain call, so this is the honest contract for a
40
- * transport being wrapped — and it is what lets a test inject a failing one.
41
- */
42
- type FetchLike = (request: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => Promise<Response>;
43
- export declare function createReadStreamStallProbe(input: {
44
- /**
45
- * Notified per failed attempt that Electric will retry internally, never for an escaping 4xx and never
46
- * for a deliberate abort. Fires repeatedly while an outage lasts — Electric retries forever — so the
47
- * consumer owns the transition/dedup, not this probe.
48
- */
49
- onStalled: () => void;
50
- /** The transport to wrap. Defaults to the global `fetch`; a test injects the failure here. */
51
- fetchClient?: FetchLike;
52
- }): ReadStreamStallProbe;
53
- export {};
54
- //# sourceMappingURL=read-stream-stall.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"read-stream-stall.d.ts","sourceRoot":"","sources":["../src/read-stream-stall.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,KAAK,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE5E;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,WAAW,oBAAoB;IACnC,sGAAsG;IACtG,cAAc,EAAE,cAAc,CAAC;IAC/B,4GAA4G;IAC5G,WAAW,EAAE,OAAO,KAAK,CAAC;CAC3B;AAED;;;;GAIG;AACH,KAAK,SAAS,GAAG,CAAC,OAAO,EAAE,UAAU,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,UAAU,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAWjH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE;IAChD;;;;OAIG;IACH,SAAS,EAAE,MAAM,IAAI,CAAC;IACtB,8FAA8F;IAC9F,WAAW,CAAC,EAAE,SAAS,CAAC;CACzB,GAAG,oBAAoB,CAsCvB"}