@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
@@ -0,0 +1,1047 @@
1
+ import type { PGliteInterface } from "@electric-sql/pglite";
2
+ import { and, eq, getTableName, isNull, sql, type SQL } from "drizzle-orm";
3
+
4
+ import type { PredicateValue, SyncTableEntry, SyncTableRegistry } from "@pgxsinkit/contracts";
5
+
6
+ import type { BootStampCollector, GroupBootStamp } from "../boot-report";
7
+ import { resolveApplyTarget, type ApplyTarget } from "../local-tables";
8
+ import { drizzleOverPg } from "../sync/drizzle-executor";
9
+ import {
10
+ deleteSubscriptionState,
11
+ getSubscriptionState,
12
+ updateSubscriptionState,
13
+ type ShapeSubscriptionState,
14
+ } from "../sync/subscription-state";
15
+ import {
16
+ ControlPlaneError,
17
+ openSubscriptionSession,
18
+ type GrantedStream,
19
+ type RefusedStream,
20
+ type SubscriptionSession,
21
+ } from "./subscription-client";
22
+ import { createBarrierReader } from "./subscription-client";
23
+ import {
24
+ syncCircuitsShapes,
25
+ type CircuitsShapeSpec,
26
+ type CircuitsSyncHandle,
27
+ type ConvergenceBarrier,
28
+ } from "./sync-engine";
29
+
30
+ /**
31
+ * Native consistency-group orchestration (ADR-0009 decision 2 on ADR-0055's substrate).
32
+ *
33
+ * `syncCircuitsShapes` syncs ONE consistency group: K streams committed atomically. This is the
34
+ * layer above it — deriving groups from the registry, subscribing each to the control plane, and
35
+ * carrying ADR-0021's eager/lazy lifecycle. It succeeded the removed `startConfiguredSync` as its own
36
+ * module rather than a branch inside it: that one BUILT shape URLs from a base, and this one is TOLD
37
+ * its URLs by the control plane, which is the whole inversion ADR-0055 decision 10 describes — nothing
38
+ * useful was shared between the two paths above the apply layer.
39
+ *
40
+ * It is also the only layer that can RE-subscribe, which is why the mid-session recovery lives here
41
+ * (backlog 0010). A group has four lifecycle transitions and they are deliberately distinct:
42
+ *
43
+ * - **start** — subscribe, reconcile, open the streams; the group becomes ready when it catches up.
44
+ * - **restart** ({@link CircuitsGroupSyncOptions.onStreamError}) — a live read ended, so the whole
45
+ * group re-subscribes with backoff and re-opens. It touches neither `ready`, nor `startPromise`,
46
+ * nor promotion, nor the boot stamp: nothing about the group's identity or its boot changed, only
47
+ * the streams underneath it.
48
+ * - **stop** (`stopGroup`) — the group returns to dormant and un-promotes.
49
+ * - **tear down** (`unsubscribe`) — the whole runtime stops.
50
+ *
51
+ * The last two bump a per-group `generation`, and every restart re-checks the generation it captured
52
+ * after each await. That is what stops a restart parked on its backoff from resurrecting a group the
53
+ * caller has since stopped, or opening streams into a torn-down runtime.
54
+ */
55
+
56
+ /** One synced table, resolved from the registry — the native spec, with no URL in it. */
57
+ interface NativeSpec {
58
+ /** The registry key, which is also `syncCircuitsShapes`'s `tableKey`. */
59
+ key: string;
60
+ shapeKey: string;
61
+ /** Shared tier only: the scope columns, whose values a grant supplies. */
62
+ scopeColumns?: readonly string[];
63
+ consistencyGroup?: string;
64
+ subscription: "eager" | "lazy";
65
+ retention: "persistent" | "ephemeral";
66
+ }
67
+
68
+ /** One group's runtime. `session`/`handle` are null while a lazy group is still held. */
69
+ interface GroupRuntime {
70
+ groupKey: string;
71
+ specs: NativeSpec[];
72
+ subscription: "eager" | "lazy";
73
+ retention: "persistent" | "ephemeral";
74
+ session: SubscriptionSession | null;
75
+ handle: CircuitsSyncHandle | null;
76
+ /** Single-flight start, so concurrent on-demand triggers share one subscription. */
77
+ startPromise: Promise<void> | null;
78
+ ready: boolean;
79
+ resolveReady: (() => void) | null;
80
+ readyPromise: Promise<void>;
81
+ refused: RefusedStream[];
82
+ /**
83
+ * This group's boot accumulator (ADR-0034) while it is still catching up, `null` otherwise.
84
+ *
85
+ * Held here rather than only on the `startGroupForBoot` call stack because a restart that lands
86
+ * BEFORE the group is ready re-opens it, and an open with no stamp would leave the group's row in
87
+ * the boot report without a ready edge. Once `ready` the stamp is finalized, so a restart past that
88
+ * point deliberately does not pass it.
89
+ */
90
+ bootStamp: GroupBootStamp | null;
91
+ /** Single-flight restart, so K dying streams in one group cost ONE re-subscribe, not K. */
92
+ restartPromise: Promise<void> | null;
93
+ /**
94
+ * Consecutive restarts with no delivered batch between them — the backoff ladder's rung. Reset by
95
+ * any delivery, so a transient blip never inherits the cadence a long outage climbed to.
96
+ */
97
+ restartAttempt: number;
98
+ /**
99
+ * Bumped by every stop and by teardown. A restart captures it and abandons itself if it moved, so
100
+ * a re-subscribe parked on its backoff can never resurrect a group the caller stopped.
101
+ */
102
+ generation: number;
103
+ /**
104
+ * Revocations heard on a re-mint, held until the re-subscribe has CLEARED their rows.
105
+ *
106
+ * They cannot be reported when they arrive: `onRefused` promises the caller that the rows are
107
+ * already gone (ADR-0055 decision 6), and at re-mint time nothing has been cleared yet — the clear
108
+ * happens at the next subscribe, where the answer says what this subject may still read.
109
+ */
110
+ pendingRefusedNotifications: RefusedStream[];
111
+ }
112
+
113
+ export interface CircuitsGroupSyncOptions {
114
+ registry: SyncTableRegistry;
115
+ /** Base URL of the control plane — where subscribe, re-mint and the barrier live. */
116
+ controlPlaneUrl: string;
117
+ /** Base URL the edge serves streams from. */
118
+ streamBaseUrl: string;
119
+ /** The caller's own auth headers, resolved per request — the same adapter the write path uses. */
120
+ authHeaders?: () => Record<string, string> | Promise<Record<string, string>>;
121
+ metadataSchema: string;
122
+ /**
123
+ * Lazy groups whose activation persisted from a previous boot (ADR-0021), started eagerly here.
124
+ */
125
+ promotedGroups?: ReadonlySet<string>;
126
+ /**
127
+ * Boot observability (ADR-0034). Only the BOOT starts (eager + promoted) open an accumulator, so an
128
+ * on-demand lazy activation never enters a finalized report.
129
+ */
130
+ bootCollector?: BootStampCollector;
131
+ /** Fired the first time every eager/promoted group has caught up. */
132
+ onInitialSync?: () => void;
133
+ onGroupReady?: (groupKey: string) => void;
134
+ onSyncError?: (error: Error) => void;
135
+ onSyncActivity?: () => void;
136
+ /** Called when a durable lazy group is activated on demand, so the next boot can promote it. */
137
+ onLazyActivated?: (groupKey: string) => void;
138
+ /**
139
+ * Called with the scopes the control plane refused or later revoked.
140
+ *
141
+ * Fired AFTER the refused scopes' local rows have been cleared, never before. Losing entitlement
142
+ * means losing the subscription, not keeping the rows (ADR-0055 decision 6), and an app that reacts
143
+ * to this — re-rendering, prompting, navigating away — must not be handed a store that still shows
144
+ * what the subject may no longer read.
145
+ */
146
+ onRefused?: (refused: readonly RefusedStream[]) => void;
147
+ /**
148
+ * The subject's own credential was refused by the control plane (401/403), and subscribe is still
149
+ * retrying (ADR-0013). The app prompts for re-login; nothing here needs restarting, because the
150
+ * auth adapter is consulted fresh on every attempt.
151
+ *
152
+ * Distinct from `onSyncError`, which reports a fault the subject cannot act on.
153
+ */
154
+ onAuthError?: (error: ControlPlaneError) => void;
155
+ /**
156
+ * Subscribe failed for a reason the subject cannot act on — the control plane is down, degraded,
157
+ * or unreachable — and is still retrying.
158
+ *
159
+ * Separate from `onSyncError` because the two recover differently: a failed subscribe clears the
160
+ * moment a batch is delivered, while a commit failure is sticky by design (ADR-0009 decision 5) —
161
+ * reads can keep succeeding while applies keep failing.
162
+ */
163
+ onSubscribeError?: (error: Error) => void;
164
+ /**
165
+ * A live stream ended or could not be opened — a `403` that survived a re-mint, a `404`/`410` on an
166
+ * evicted stream, `Stream-Closed`, a lost connection — and the group is re-subscribing with
167
+ * backoff.
168
+ *
169
+ * Recoverable, and it clears on the next delivered batch. Distinct from `onSubscribeError` (the
170
+ * CONTROL PLANE could not be reached, so there is nothing to read from yet) and from `onSyncError`
171
+ * (a COMMIT failed, which is sticky by design because reads can keep succeeding while applies keep
172
+ * failing).
173
+ */
174
+ onStreamError?: (error: Error) => void;
175
+ live?: boolean;
176
+ /**
177
+ * Tears the whole read path down from OUTSIDE, including mid-boot.
178
+ *
179
+ * `unsubscribe()` cannot cover that window: it lives on the handle this function returns, and a boot
180
+ * whose control plane is unreachable has not returned one yet. A client stopped in that window would
181
+ * otherwise sit on a TCP connect with nothing able to cancel it — which is precisely when a stop is
182
+ * most likely, because the network being down is why the boot is still running.
183
+ */
184
+ signal?: AbortSignal;
185
+ fetch?: typeof fetch;
186
+ }
187
+
188
+ export interface CircuitsTableSyncResult {
189
+ readonly isUpToDate: boolean;
190
+ }
191
+
192
+ export interface CircuitsGroupSyncResult {
193
+ unsubscribe: () => void;
194
+ tables: Record<string, CircuitsTableSyncResult>;
195
+ /**
196
+ * Start a held lazy group. Idempotent and single-flight; resolves once it has caught up — EXCEPT
197
+ * for an already-promoted group, which resolves at once because it is durable and boot-started
198
+ * (ADR-0021 §2), so its catch-up must not gate a read.
199
+ */
200
+ ensureGroupStarted: (groupKey: string) => Promise<void>;
201
+ /**
202
+ * Tear a group's streams down and return it to dormant, so a later start re-subscribes. Also drops
203
+ * the group's promotion for this session — a desync truncates the local copy, so the group is held
204
+ * again and re-activates (and re-persists its flag) on its next reference.
205
+ */
206
+ stopGroup: (groupKey: string) => void;
207
+ groupKeyForTable: (tableKey: string) => string | undefined;
208
+ /**
209
+ * Whether the table's group is STARTED — a durable subscription for it exists, so reads of it are
210
+ * meaningful. NOT the same question as caught up, which is {@link CircuitsGroupSyncResult.isGroupReady}:
211
+ * a promoted group is started from boot even while its first subscribe is still retrying.
212
+ */
213
+ isTableStarted: (tableKey: string) => boolean;
214
+ groupReady: (groupKey: string) => Promise<void>;
215
+ isGroupReady: (groupKey: string) => boolean;
216
+ groupKeys: () => string[];
217
+ }
218
+
219
+ /**
220
+ * The scope columns a shape keys on, or undefined for the private tier.
221
+ *
222
+ * Read straight off the registry rather than inferred from a grant: a grant carries VALUES, and
223
+ * which columns they belong to is the shape's declaration. Pairing them positionally is only sound
224
+ * because both come from the same `shape.scope` ordering — the control plane compiles its predicate
225
+ * from it too, so a mismatch here would be a mismatch there.
226
+ */
227
+ function scopeColumnsOf(entry: SyncTableEntry): readonly string[] | undefined {
228
+ const scope = entry.shape?.scope;
229
+ return scope != null && scope.length > 0 ? scope : undefined;
230
+ }
231
+
232
+ function deriveSpecs(registry: SyncTableRegistry): NativeSpec[] {
233
+ const specs: NativeSpec[] = [];
234
+ for (const [key, entry] of Object.entries(registry)) {
235
+ if (entry == null || entry.mode === "writeonly") continue;
236
+ const shape = entry.shape;
237
+ if (shape === undefined) continue;
238
+ const scopeColumns = scopeColumnsOf(entry);
239
+ specs.push({
240
+ key,
241
+ shapeKey: shape.shapeKey,
242
+ ...(scopeColumns ? { scopeColumns } : {}),
243
+ ...(entry.consistencyGroup ? { consistencyGroup: entry.consistencyGroup } : {}),
244
+ subscription: entry.subscription === "lazy" ? "lazy" : "eager",
245
+ retention: entry.retention === "ephemeral" ? "ephemeral" : "persistent",
246
+ });
247
+ }
248
+ return specs;
249
+ }
250
+
251
+ /** The group key a spec belongs to: its explicit group, else its own shapeKey (a singleton). */
252
+ function groupKeyOf(spec: NativeSpec): string {
253
+ return spec.consistencyGroup ?? spec.shapeKey;
254
+ }
255
+
256
+ /**
257
+ * The scoped cache clear for one granted stream — what a must-refetch runs INSTEAD of truncating.
258
+ *
259
+ * Required, not optional, and the shared tier is why: expansion puts every scope of a shape on its
260
+ * own stream but into ONE local table, so the default `TRUNCATE` would take a co-tenant scope's rows
261
+ * with it. The clear is derived rather than authored — the scope columns come from the registry and
262
+ * the values from the grant, which is the same pairing the control plane compiled its predicate
263
+ * from.
264
+ *
265
+ * Tier ① throughout: real column objects and `eq`/`isNull`, never a spliced identifier. `NULL` needs
266
+ * `isNull` rather than `eq(col, null)` for the same reason the compiler's `scopePredicate` does —
267
+ * `col = NULL` is UNKNOWN for every row, so an `eq` here would clear nothing and silently leave the
268
+ * old scope's rows behind.
269
+ */
270
+ function scopedClear(
271
+ target: ApplyTarget,
272
+ scopeColumns: readonly string[],
273
+ scope: readonly PredicateValue[],
274
+ ): (db: ReturnType<typeof drizzleOverPg>) => Promise<void> {
275
+ const conditions: SQL[] = [];
276
+ for (const [index, name] of scopeColumns.entries()) {
277
+ const column = target.columnByName[name];
278
+ if (column === undefined) {
279
+ throw new Error(
280
+ `[pgxsinkit] shape scope column "${name}" is not a column of local table ` +
281
+ `"${getTableName(target.table)}" — the registry's scope declaration and its local projection ` +
282
+ `have diverged.`,
283
+ );
284
+ }
285
+ const value = scope[index];
286
+ conditions.push(value === null || value === undefined ? isNull(column) : eq(column, value));
287
+ }
288
+
289
+ return async (db) => {
290
+ await db.delete(target.table).where(conditions.length === 1 ? conditions[0]! : and(...conditions));
291
+ };
292
+ }
293
+
294
+ /**
295
+ * The name one READER of a stream is known by, within its group and across boots.
296
+ *
297
+ * A grant's shape key plus its scope, because neither alone identifies a reader. A shared shape fans
298
+ * out to one grant per entitled scope (ADR-0055 decision 6), so shape keys are not unique within a
299
+ * group; and the STREAM PATH is not unique either, which is the sharper of the two. Circuits
300
+ * ref-counts byte-identical shape definitions, so two distinct read projections that compile to the
301
+ * same table, columns and predicate come back as one path — keying on it dropped the second
302
+ * projection's reader outright and left its local table empty forever.
303
+ *
304
+ * Exported for the tests that pin that naming: it is also the key of a persisted cursor entry, so it
305
+ * is the thing a later subscribe matches a grant against.
306
+ */
307
+ export function logicalShapeName(shapeKey: string, scope?: readonly PredicateValue[]): string {
308
+ return scope === undefined ? shapeKey : `${shapeKey}@${JSON.stringify(scope)}`;
309
+ }
310
+
311
+ /**
312
+ * Turn one group's grants into the shape map `syncCircuitsShapes` takes.
313
+ *
314
+ * Keyed by {@link logicalShapeName} — the reader's identity, not the stream's. When the engine hands
315
+ * two logical shapes ONE deduplicated stream, they become two readers of that stream: each opens its
316
+ * own read, applies into its own table, and persists its own offset. That is a second read of bytes
317
+ * the engine only stores once, and it is the right trade for a rare configuration — the alternative
318
+ * is a projection that silently never populates.
319
+ */
320
+ function shapesFromGrants(
321
+ registry: SyncTableRegistry,
322
+ specsByShapeKey: Map<string, NativeSpec>,
323
+ granted: readonly GrantedStream[],
324
+ ): Record<string, CircuitsShapeSpec> {
325
+ const shapes: Record<string, CircuitsShapeSpec> = {};
326
+ for (const grant of granted) {
327
+ const spec = specsByShapeKey.get(grant.shapeKey);
328
+ if (spec === undefined) continue;
329
+ const target = resolveApplyTarget(registry, spec.key);
330
+ shapes[logicalShapeName(grant.shapeKey, grant.scope)] = {
331
+ streamUrl: grant.streamUrl,
332
+ tableKey: spec.key,
333
+ identity: { shapeKey: grant.shapeKey, ...(grant.scope ? { scope: grant.scope } : {}) },
334
+ ...(spec.scopeColumns && grant.scope
335
+ ? { onMustRefetch: scopedClear(target, spec.scopeColumns, grant.scope) }
336
+ : {}),
337
+ };
338
+ }
339
+ return shapes;
340
+ }
341
+
342
+ /**
343
+ * Read the convergence barrier once per in-flight window, however many groups ask.
344
+ *
345
+ * The barrier is engine-global (ADR-0056 decision 3), so K groups aligning at boot would otherwise
346
+ * make K identical round trips within milliseconds of each other. Only the IN-FLIGHT read is shared
347
+ * — nothing is cached past it — so this dedups a stampede without introducing any staleness the
348
+ * control plane's own cache does not already account for.
349
+ */
350
+ function shareBarrierReads(read: () => Promise<ConvergenceBarrier>): () => Promise<ConvergenceBarrier> {
351
+ let inFlight: Promise<ConvergenceBarrier> | null = null;
352
+ return () => {
353
+ if (inFlight) return inFlight;
354
+ inFlight = read().finally(() => {
355
+ inFlight = null;
356
+ });
357
+ return inFlight;
358
+ };
359
+ }
360
+
361
+ /**
362
+ * Exponential backoff for a failing subscribe, capped so a long outage still retries promptly once
363
+ * it clears. The first retry is immediate-ish, because the overwhelmingly common case is a token
364
+ * that a refresh already fixed by the time we ask again.
365
+ */
366
+ function subscribeBackoffMs(attempt: number): number {
367
+ return Math.min(SUBSCRIBE_RETRY_BASE_MS * 2 ** attempt, SUBSCRIBE_RETRY_MAX_MS);
368
+ }
369
+
370
+ const SUBSCRIBE_RETRY_BASE_MS = 250;
371
+ const SUBSCRIBE_RETRY_MAX_MS = 10_000;
372
+
373
+ export async function startCircuitsSync(
374
+ pg: PGliteInterface,
375
+ options: CircuitsGroupSyncOptions,
376
+ ): Promise<CircuitsGroupSyncResult> {
377
+ const specs = deriveSpecs(options.registry);
378
+ // A LOCAL, MUTABLE copy: promotion is durable state the caller persisted, but this runtime can drop
379
+ // a group out of it — `stopGroup` returns a promoted group to held for the rest of this session.
380
+ const promoted = new Set(options.promotedGroups ?? []);
381
+
382
+ const groups = new Map<string, GroupRuntime>();
383
+ const groupKeyByTable = new Map<string, string>();
384
+ for (const spec of specs) {
385
+ const groupKey = groupKeyOf(spec);
386
+ groupKeyByTable.set(spec.key, groupKey);
387
+ const existing = groups.get(groupKey);
388
+ if (existing) {
389
+ existing.specs.push(spec);
390
+ continue;
391
+ }
392
+ let resolveReady: (() => void) | null = null;
393
+ const readyPromise = new Promise<void>((resolve) => {
394
+ resolveReady = resolve;
395
+ });
396
+ groups.set(groupKey, {
397
+ groupKey,
398
+ specs: [spec],
399
+ // Members of a group agree on timing and retention (registry-validated), so the first
400
+ // member's value is the group's.
401
+ subscription: spec.subscription,
402
+ retention: spec.retention,
403
+ session: null,
404
+ handle: null,
405
+ startPromise: null,
406
+ ready: false,
407
+ resolveReady,
408
+ readyPromise,
409
+ refused: [],
410
+ bootStamp: null,
411
+ restartPromise: null,
412
+ restartAttempt: 0,
413
+ generation: 0,
414
+ pendingRefusedNotifications: [],
415
+ });
416
+ }
417
+
418
+ /**
419
+ * Aborts in-flight control-plane requests on teardown — the other half of the same problem the
420
+ * `teardown` promise solves. A subscribe sitting on a TCP connect to an unreachable host can take
421
+ * minutes to fail on its own, and `stop()` waits for the boot tail.
422
+ */
423
+ const controlPlaneRequests = new AbortController();
424
+
425
+ const readBarrier = shareBarrierReads(
426
+ createBarrierReader({
427
+ controlPlaneUrl: options.controlPlaneUrl,
428
+ ...(options.authHeaders ? { authHeaders: options.authHeaders } : {}),
429
+ signal: controlPlaneRequests.signal,
430
+ ...(options.fetch ? { fetch: options.fetch } : {}),
431
+ }),
432
+ );
433
+
434
+ let torn = false;
435
+ let initialSyncSignalled = false;
436
+
437
+ /**
438
+ * Resolved by `unsubscribe`, so a retry parked on its backoff wakes immediately on teardown.
439
+ *
440
+ * Not a nicety: `stop()` awaits the boot tail, and the tail awaits these starts, so a sleep that
441
+ * only checks `torn` on the far side would hold a teardown open for a whole backoff window — up to
442
+ * ten seconds per group, on every stop of an offline client.
443
+ */
444
+ let signalTorn!: () => void;
445
+ const teardown = new Promise<void>((resolve) => {
446
+ signalTorn = resolve;
447
+ });
448
+
449
+ // The BOOT set, snapshotted here: every eager group plus every group a previous boot promoted. A
450
+ // later `stopGroup` un-promotes its group in `promoted` but must not rewrite what boot started, so
451
+ // this stays a plain array captured before the boot loop — it also fixes what initial-sync waits on.
452
+ const eagerKeys = [...groups.values()]
453
+ .filter((group) => group.subscription === "eager" || promoted.has(group.groupKey))
454
+ .map((group) => group.groupKey);
455
+
456
+ function signalInitialSyncIfReady(): void {
457
+ if (initialSyncSignalled || torn) return;
458
+ if (!eagerKeys.every((key) => groups.get(key)?.ready === true)) return;
459
+ initialSyncSignalled = true;
460
+ options.onInitialSync?.();
461
+ }
462
+
463
+ function markReady(group: GroupRuntime): void {
464
+ if (group.ready) return;
465
+ group.ready = true;
466
+ group.resolveReady?.();
467
+ options.onGroupReady?.(group.groupKey);
468
+ signalInitialSyncIfReady();
469
+ }
470
+
471
+ /**
472
+ * Subscribe one group, retrying until it succeeds or the runtime is torn down.
473
+ *
474
+ * Retrying rather than failing is ADR-0013's requirement carried onto the native path: a client
475
+ * whose JWT expired between boots must surface `auth-needed` and resume the moment a fresh one
476
+ * works, with no restart. Failing the start instead would leave the app holding a client that
477
+ * never syncs again, which is the exact wedge that ADR predates.
478
+ *
479
+ * The same loop covers an outage. A 503 from the control plane and a dead socket are both "not
480
+ * now, try again"; only the STATUS differs, and only because a stale credential is the one failure
481
+ * the subject can personally fix.
482
+ *
483
+ * `generation` is the group generation the caller captured. A subscribe retrying for a group that
484
+ * has since been stopped has nothing left to subscribe FOR, so the loop ends with it rather than
485
+ * hammering a control plane on behalf of a dead group.
486
+ */
487
+ async function subscribeWithRetry(
488
+ group: GroupRuntime,
489
+ generation: number,
490
+ onFirstAttempt?: () => void,
491
+ ): Promise<SubscriptionSession | null> {
492
+ let reportedFirstAttempt = false;
493
+ const reportAttempt = () => {
494
+ if (reportedFirstAttempt) return;
495
+ reportedFirstAttempt = true;
496
+ onFirstAttempt?.();
497
+ };
498
+ const abandoned = () => torn || group.generation !== generation;
499
+
500
+ for (let attempt = 0; !abandoned(); attempt += 1) {
501
+ try {
502
+ const session = await openSubscriptionSession(
503
+ {
504
+ controlPlaneUrl: options.controlPlaneUrl,
505
+ streamBaseUrl: options.streamBaseUrl,
506
+ ...(options.authHeaders ? { authHeaders: options.authHeaders } : {}),
507
+ signal: controlPlaneRequests.signal,
508
+ ...(options.fetch ? { fetch: options.fetch } : {}),
509
+ // Held, not reported. A revoked scope's rows are still on disk at this instant — they are
510
+ // cleared at the re-subscribe this revocation triggers — and `onRefused` may only fire
511
+ // once they are gone. The restart is what turns "the control plane says you lost this"
512
+ // into "and it is no longer in your store".
513
+ onRevoked: (revoked) => {
514
+ group.refused.push(...revoked);
515
+ group.pendingRefusedNotifications.push(...revoked);
516
+ scheduleRestart(group, new Error("[pgxsinkit] stream grants revoked on re-mint"));
517
+ },
518
+ },
519
+ group.specs.map((spec) => ({ shapeKey: spec.shapeKey })),
520
+ );
521
+ if (abandoned()) {
522
+ reportAttempt();
523
+ session.close();
524
+ return null;
525
+ }
526
+ // Deliberately no `reportAttempt()` here. A subscribe that SUCCEEDED holds the boot for the
527
+ // rest of the start, so a boot that reached the control plane still comes back with its
528
+ // groups streaming — the release below is only for the case where it could not.
529
+ return session;
530
+ } catch (error) {
531
+ if (abandoned()) {
532
+ reportAttempt();
533
+ return null;
534
+ }
535
+ if (error instanceof ControlPlaneError && error.isAuthFailure) {
536
+ options.onAuthError?.(error);
537
+ } else {
538
+ options.onSubscribeError?.(error instanceof Error ? error : new Error(String(error)));
539
+ }
540
+ // The first failure releases the boot: it keeps retrying in the background, but an offline
541
+ // client must still reach `localReadReady` rather than waiting on a control plane that may
542
+ // be down for hours.
543
+ reportAttempt();
544
+ await sleepUntil(subscribeBackoffMs(attempt));
545
+ }
546
+ }
547
+ reportAttempt();
548
+ return null;
549
+ }
550
+
551
+ /** Sleep, but wake at once on teardown — and leave no timer behind either way. */
552
+ function sleepUntil(ms: number): Promise<void> {
553
+ return new Promise<void>((resolve) => {
554
+ const timer = setTimeout(resolve, ms);
555
+ void teardown.then(() => {
556
+ clearTimeout(timer);
557
+ resolve();
558
+ });
559
+ });
560
+ }
561
+
562
+ /**
563
+ * Clear what this subject may no longer read, BEFORE anything is synced or reported ready.
564
+ *
565
+ * ADR-0055 decision 6: losing entitlement means losing the subscription — "truncate that scope and
566
+ * unsubscribe". The live half of that is a 403 surviving a re-mint (ADR-0056 decision 7), but a
567
+ * revocation that lands while the client is OFFLINE has no 403 to deliver: the next boot simply
568
+ * subscribes and is granted less. Nothing else in the start path notices. `shapesFromGrants` only
569
+ * ever covers what WAS granted, and a group granted nothing at all takes the ready branch straight
570
+ * over the previous session's rows.
571
+ *
572
+ * So the check lives at subscribe, because the subscribe answer is the single authoritative
573
+ * statement of what this subject may read right now. A persisted reader the answer does not name is
574
+ * exactly a revocation discovered late, and the cursor is the only thing that still remembers it —
575
+ * hence the shape key and scope persisted alongside the offset.
576
+ *
577
+ * Deliberately NOT the handle check. A shape that is still granted but on a different stream is
578
+ * `syncCircuitsShapes`'s must-refetch (ADR-0056 decision 6/7): it re-snapshots in the same
579
+ * transaction the new rows land in, and nothing here touches it. This one answers the other
580
+ * question — whether the reader should exist at all.
581
+ *
582
+ * Returns what it cleared, because a clear nobody is told about is half a revocation. The control
583
+ * plane's own `denied`/`revoked` lists only cover what it was ASKED about; a scope it has simply
584
+ * stopped enumerating produces no entry anywhere, so without this the rows would vanish and the app
585
+ * would never learn which scope it lost. The caller folds these into the one `onRefused` call it
586
+ * makes after this returns — after the clear, as that callback's contract requires.
587
+ */
588
+ async function reconcilePersistedShapes(
589
+ group: GroupRuntime,
590
+ granted: readonly GrantedStream[],
591
+ ): Promise<RefusedStream[]> {
592
+ const sessionScoped = group.retention === "ephemeral";
593
+ const state = await getSubscriptionState({
594
+ pg,
595
+ metadataSchema: options.metadataSchema,
596
+ subscriptionKey: group.groupKey,
597
+ sessionScoped,
598
+ });
599
+ if (state === null) return [];
600
+
601
+ const stillGranted = new Set(granted.map((grant) => logicalShapeName(grant.shapeKey, grant.scope)));
602
+ const specsByShapeKey = new Map(group.specs.map((spec) => [spec.shapeKey, spec]));
603
+
604
+ const surviving: Record<string, ShapeSubscriptionState> = {};
605
+ const stale: { spec: NativeSpec; persisted: ShapeSubscriptionState }[] = [];
606
+ for (const [shapeName, persisted] of Object.entries(state.shape_metadata)) {
607
+ if (stillGranted.has(shapeName)) {
608
+ surviving[shapeName] = persisted;
609
+ continue;
610
+ }
611
+ // An entry naming a shape this group no longer declares is a REGISTRY change, and that is
612
+ // ADR-0006's rebuild rather than this path — it drops the whole store, so clearing rows here
613
+ // would be both redundant and a guess at which table they were in. The entry itself is dropped
614
+ // with the rest of the stale set: nothing can ever resume it.
615
+ const spec = specsByShapeKey.get(persisted.shapeKey);
616
+ if (spec === undefined) continue;
617
+ stale.push({ spec, persisted });
618
+ }
619
+
620
+ if (stale.length === 0) return [];
621
+
622
+ await pg.transaction(async (tx) => {
623
+ // Tier ③ (ADR-0028 allow-list): the sync-origin GUC the apply trigger reads, set exactly as the
624
+ // engine's own commit sets it — this clear is streamed server truth reversing itself, not a
625
+ // local write. GUCs have no tier-①/② builder form.
626
+ await tx.exec(`SET LOCAL ${options.metadataSchema}.syncing = true;`);
627
+ const db = drizzleOverPg(tx);
628
+
629
+ for (const { spec, persisted } of stale) {
630
+ const target = resolveApplyTarget(options.registry, spec.key);
631
+ if (spec.scopeColumns && persisted.scope) {
632
+ // Shared tier: co-tenant scopes live in this same table, so only this scope's rows go.
633
+ await scopedClear(target, spec.scopeColumns, persisted.scope)(db);
634
+ } else {
635
+ // Private tier: a scope-less shape is always its table's sole occupant (`resolveTableSharing`
636
+ // in sync-engine refuses co-tenancy without a scoped clear), so the table IS the shape's
637
+ // rows. Tier ②: TRUNCATE has no Drizzle builder, so the table object is interpolated rather
638
+ // than its name spliced.
639
+ await db.execute(sql`TRUNCATE ${target.table}`);
640
+ }
641
+ }
642
+
643
+ // The cursor is rewritten in the SAME transaction as the clear, or a crash between them leaves a
644
+ // resume token for rows that are gone.
645
+ if (Object.keys(surviving).length === 0) {
646
+ await deleteSubscriptionState({
647
+ pg: tx,
648
+ metadataSchema: options.metadataSchema,
649
+ subscriptionKey: group.groupKey,
650
+ });
651
+ } else {
652
+ await updateSubscriptionState({
653
+ pg: tx,
654
+ metadataSchema: options.metadataSchema,
655
+ subscriptionKey: group.groupKey,
656
+ sessionScoped,
657
+ shapeMetadata: surviving,
658
+ // `last_lsn` has no native meaning (ADR-0056) — written as the same constant the engine's
659
+ // commit writes, until the vestigial column is dropped.
660
+ lastLsn: BigInt(0),
661
+ });
662
+ }
663
+ });
664
+
665
+ return stale.map(({ persisted }) => ({
666
+ shapeKey: persisted.shapeKey,
667
+ ...(persisted.scope ? { scope: persisted.scope } : {}),
668
+ reason: "no longer granted at subscribe",
669
+ }));
670
+ }
671
+
672
+ /**
673
+ * Subscribe one group and open its streams — the whole of a group's connected state, in one place
674
+ * because start and RESTART must do exactly the same thing.
675
+ *
676
+ * One session PER GROUP rather than one for the whole client. ADR-0055 decision 6's batching
677
+ * property is about SCOPES — "a subject with K scopes refreshes in one request per window" — and
678
+ * expansion keeps every scope of a shape inside the one group that declared it, so that property
679
+ * is preserved here. What one-per-group buys is that a group's lifecycle and its session's are
680
+ * the same object: activation opens one, `stopGroup` closes one, and no group can hold a grant
681
+ * alive for a group that has stopped.
682
+ *
683
+ * The generation captured on entry is re-checked after every await: a stop or a teardown that
684
+ * lands mid-open has already closed whatever this group held, and finishing the open would hand it
685
+ * back a session and a set of streams nobody asked for.
686
+ *
687
+ * Throws if the streams could not be opened. Both callers answer that with a backoff and another
688
+ * attempt — see {@link scheduleRestart} — because "the edge is not answering" is a condition that
689
+ * ends by itself.
690
+ */
691
+ async function openGroup(
692
+ group: GroupRuntime,
693
+ bootStamp?: GroupBootStamp,
694
+ onFirstAttempt?: () => void,
695
+ ): Promise<void> {
696
+ const generation = group.generation;
697
+ const abandoned = () => torn || group.generation !== generation;
698
+ const specsByShapeKey = new Map(group.specs.map((spec) => [spec.shapeKey, spec]));
699
+
700
+ const session = await subscribeWithRetry(group, generation, onFirstAttempt);
701
+ if (session === null) return;
702
+ if (abandoned()) {
703
+ session.close();
704
+ return;
705
+ }
706
+
707
+ group.session = session;
708
+ group.refused.push(...session.refused);
709
+
710
+ // Before EITHER branch below: the zero-grants branch reports ready immediately, and it must not
711
+ // report ready over rows the subject lost while this client was offline.
712
+ const cleared = await reconcilePersistedShapes(group, session.granted);
713
+ if (abandoned()) return;
714
+ group.refused.push(...cleared);
715
+
716
+ notifyRefused(group, session.refused, cleared);
717
+
718
+ const shapes = shapesFromGrants(options.registry, specsByShapeKey, session.granted);
719
+ if (Object.keys(shapes).length === 0) {
720
+ // Nothing was granted. The group is "ready" in the only sense available to it — there is
721
+ // nothing to wait for — and saying so is what stops a boot hanging on an entitlement the
722
+ // subject simply does not hold.
723
+ bootStamp?.markReady();
724
+ markReady(group);
725
+ return;
726
+ }
727
+
728
+ const handle = await syncCircuitsShapes({
729
+ pg,
730
+ registry: options.registry,
731
+ key: group.groupKey,
732
+ metadataSchema: options.metadataSchema,
733
+ sessionScoped: group.retention === "ephemeral",
734
+ ...(bootStamp ? { bootStamp } : {}),
735
+ shapes,
736
+ token: () => session.token(),
737
+ onTokenRejected: async () => session.refresh(),
738
+ readBarrier,
739
+ ...(options.fetch ? { fetch: options.fetch } : {}),
740
+ ...(options.live !== undefined ? { live: options.live } : {}),
741
+ ...(options.onSyncError ? { onSyncError: options.onSyncError } : {}),
742
+ onSyncActivity: () => {
743
+ // A delivered batch ends the fault the ladder was climbing, so the next one starts at the
744
+ // bottom again: a blip an hour from now must not inherit an outage's ten-second cadence.
745
+ group.restartAttempt = 0;
746
+ options.onSyncActivity?.();
747
+ },
748
+ // The mid-session half of ADR-0056 decision 7 (backlog 0010). A read that ends under `live`
749
+ // has no way back on its own — the engine is handed URLs, not a subscription — so the whole
750
+ // group re-subscribes here. A NORMAL end under `live: false` is not that: a one-shot hydration
751
+ // finishing is the success case, and restarting it would loop forever.
752
+ onStreamEnd: (shapeName, error) => {
753
+ if (options.live === false && error === null) return;
754
+ scheduleRestart(group, error ?? new Error(`[pgxsinkit] stream "${shapeName}" closed by the server`));
755
+ },
756
+ onInitialSync: () => {
757
+ // Stamp readyAtMs and freeze the accumulator at the group's ready edge, so later live traffic
758
+ // never mutates a finalized report.
759
+ bootStamp?.markReady();
760
+ markReady(group);
761
+ },
762
+ });
763
+
764
+ if (abandoned()) {
765
+ handle.unsubscribe();
766
+ session.close();
767
+ return;
768
+ }
769
+ group.handle = handle;
770
+ }
771
+
772
+ /**
773
+ * Tell the caller what this group lost, ONCE, and only after the rows are gone.
774
+ *
775
+ * Three sources converge here and they are not interchangeable: scopes the control plane refused at
776
+ * this subscribe, scopes it revoked on an earlier re-mint (held since — see
777
+ * {@link GroupRuntime.pendingRefusedNotifications}), and readers the reconcile CLEARED because the
778
+ * subscribe answer no longer names them. The third is the one nothing else reports.
779
+ *
780
+ * A cleared reader the control plane already named is not repeated: the control plane's reason says
781
+ * WHY the subject lost it, which is strictly more informative than "no longer granted", and a
782
+ * caller counting entries should see one per lost reader rather than two.
783
+ */
784
+ function notifyRefused(
785
+ group: GroupRuntime,
786
+ refused: readonly RefusedStream[],
787
+ cleared: readonly RefusedStream[],
788
+ ): void {
789
+ const announced = [...group.pendingRefusedNotifications, ...refused];
790
+ group.pendingRefusedNotifications = [];
791
+ const named = new Set(announced.map((entry) => logicalShapeName(entry.shapeKey, entry.scope)));
792
+ const entries = [
793
+ ...announced,
794
+ ...cleared.filter((entry) => !named.has(logicalShapeName(entry.shapeKey, entry.scope))),
795
+ ];
796
+ if (entries.length > 0) options.onRefused?.(entries);
797
+ }
798
+
799
+ /**
800
+ * Re-subscribe a group whose streams stopped, after a backoff — the recovery half of ADR-0056
801
+ * decision 7 (backlog 0010).
802
+ *
803
+ * The WHOLE GROUP re-subscribes, not the one dead shape, and that is deliberate: the subscribe
804
+ * answer is the single authoritative statement of what this subject may read, and the reconcile
805
+ * that runs on it is what clears a scope that has since been revoked. Re-opening one stream would
806
+ * recover liveness while leaving both of those unasked.
807
+ *
808
+ * Single-flight per group (K streams of one group die together on a lost connection, and they need
809
+ * ONE re-subscribe), generation-guarded, and it deliberately touches nothing about the group's
810
+ * identity: not `ready`, not `startPromise`, not promotion, not the boot stamp. A restart is
811
+ * neither a boot nor a stop — the group never stopped being this group.
812
+ */
813
+ function scheduleRestart(group: GroupRuntime, cause: Error): void {
814
+ if (torn || group.restartPromise !== null) return;
815
+ const generation = group.generation;
816
+
817
+ options.onStreamError?.(cause);
818
+ // Down before the backoff, not after: a dead stream still holds a connection and its token thunk
819
+ // still fires, and the re-subscribe below is going to replace both.
820
+ group.handle?.unsubscribe();
821
+ group.session?.close();
822
+ group.handle = null;
823
+ group.session = null;
824
+
825
+ group.restartPromise = (async () => {
826
+ let failure: Error | null = null;
827
+ await sleepUntil(subscribeBackoffMs(group.restartAttempt++));
828
+ if (!torn && group.generation === generation) {
829
+ try {
830
+ // Still catching up: the boot stamp rides the re-open, or this group's boot-report row never
831
+ // gets a ready edge. Past `ready` the stamp is finalized and must not be handed back.
832
+ await openGroup(group, group.ready ? undefined : (group.bootStamp ?? undefined));
833
+ } catch (error) {
834
+ failure = error instanceof Error ? error : new Error(String(error));
835
+ }
836
+ }
837
+ // The latch is released BEFORE the next attempt is scheduled, or that attempt would see a
838
+ // restart still in flight and drop itself — leaving a group that is neither reading nor
839
+ // recovering. The generation is the identity check: only one restart can exist per generation
840
+ // (this latch is why), and a stop that moved it has already cleared the latch itself, so
841
+ // clearing it here would only clobber a newer owner's.
842
+ if (group.generation === generation) group.restartPromise = null;
843
+ // The streams could not be re-opened. Same ladder, so an edge that stays down is retried at the
844
+ // capped 10 s cadence until it answers, rather than being abandoned after one try.
845
+ if (failure !== null && !torn && group.generation === generation) scheduleRestart(group, failure);
846
+ })();
847
+ }
848
+
849
+ /**
850
+ * Start one group: open it, and if the streams could not be opened, keep trying rather than failing.
851
+ *
852
+ * An edge that is down at boot is the same condition as an edge that dies mid-session, and the
853
+ * subscribe retry loop already takes that view of the control plane. A start that threw instead
854
+ * would leave the app holding a group that never syncs again even though the network came back
855
+ * seconds later — the ADR-0013 wedge, one layer down. The group is started-and-recovering: its
856
+ * `ready` stays pending, `onStreamError` says why, and the ladder in {@link scheduleRestart} runs.
857
+ */
858
+ async function startGroup(
859
+ group: GroupRuntime,
860
+ onFirstAttempt?: () => void,
861
+ bootStamp?: GroupBootStamp,
862
+ ): Promise<void> {
863
+ try {
864
+ await openGroup(group, bootStamp, onFirstAttempt);
865
+ } catch (error) {
866
+ if (torn) return;
867
+ scheduleRestart(group, error instanceof Error ? error : new Error(String(error)));
868
+ }
869
+ }
870
+
871
+ async function ensureGroupStarted(groupKey: string): Promise<void> {
872
+ const group = groups.get(groupKey);
873
+ if (group === undefined) return;
874
+
875
+ /**
876
+ * A PROMOTED group is already durable and already boot-started, so a reference to it must not
877
+ * wait for anything.
878
+ *
879
+ * ADR-0021 §2: activation is permanent — a `lazy + persistent` group that was activated once
880
+ * "joins the normal eager-persistent set", and subsequent boots subscribe it eagerly and resume
881
+ * it like any other durable table. Boot did exactly that (`startGroupForBoot`), but that start
882
+ * only resolves once a subscribe SUCCEEDS. Awaiting it here would make a read of a promoted
883
+ * relation block on the network — and an offline reopen, the very state promotion exists to
884
+ * serve, would never get past it even though every row is on disk and readable NOW.
885
+ *
886
+ * This is the same deal eager relations already get: their reads never pass through this
887
+ * activation choke point at all, and their catch-up is a background concern. Nothing is hidden
888
+ * by returning early — catch-up stays separately visible through `isGroupReady`/`groupReady`
889
+ * (what the React hooks' `hydrating` reports), and the retry loop is still running.
890
+ */
891
+ if (promoted.has(groupKey) && group.startPromise != null) return;
892
+
893
+ if (group.startPromise) return group.startPromise;
894
+
895
+ const wasHeld = group.subscription === "lazy" && !promoted.has(groupKey);
896
+ group.startPromise = startGroup(group).catch((error: unknown) => {
897
+ // A failed start must not be remembered as started: clearing the latch lets a later reference
898
+ // try again rather than resolving instantly against a group that never subscribed.
899
+ group.startPromise = null;
900
+ throw error;
901
+ });
902
+ await group.startPromise;
903
+ if (wasHeld && group.retention === "persistent") options.onLazyActivated?.(groupKey);
904
+ await group.readyPromise;
905
+ }
906
+
907
+ /**
908
+ * Stop a group and return it to dormant.
909
+ *
910
+ * The generation bump is what makes that stick. A restart may be parked on its backoff right now,
911
+ * holding a captured generation and a plan to re-subscribe; moving the generation is how it learns,
912
+ * on the far side of every await, that the group it was recovering no longer wants to be recovered.
913
+ * Without it a stopped group would quietly come back streaming a few hundred milliseconds later.
914
+ */
915
+ function stopGroup(groupKey: string): void {
916
+ const group = groups.get(groupKey);
917
+ if (group === undefined) return;
918
+ group.generation += 1;
919
+ group.restartPromise = null;
920
+ group.restartAttempt = 0;
921
+ group.pendingRefusedNotifications = [];
922
+ group.handle?.unsubscribe();
923
+ group.session?.close();
924
+ group.handle = null;
925
+ group.session = null;
926
+ group.startPromise = null;
927
+ group.ready = false;
928
+ group.refused = [];
929
+ // A stop ends this group's boot generation, so a later activation must not re-open against a
930
+ // stamp whose report was finalized on the previous run.
931
+ group.bootStamp = null;
932
+ // Stopping a group also revokes its PROMOTION for the rest of this session (ADR-0021 §2): a
933
+ // desync truncates the local copy, so the durable-and-readable premise the promotion fast path
934
+ // rests on no longer holds. The group is HELD again — its next reference goes through the normal
935
+ // activation path, where `wasHeld` is true once more and `onLazyActivated` re-persists the flag.
936
+ promoted.delete(groupKey);
937
+ // A stopped group must be able to become pending again, or a later activation would resolve its
938
+ // readiness instantly against the previous run's settled promise.
939
+ group.readyPromise = new Promise<void>((resolve) => {
940
+ group.resolveReady = resolve;
941
+ });
942
+ }
943
+
944
+ /**
945
+ * Tear the whole read path down: stop retrying, abort in-flight requests, drop every stream.
946
+ *
947
+ * `torn` alone would do for the restart ladder — every guard tests it — but the generation moves
948
+ * too, so a restart holding a stale generation abandons itself for the same reason a stopped
949
+ * group's does, rather than for a second reason that has to be kept in step with this one.
950
+ */
951
+ function tearDown(): void {
952
+ torn = true;
953
+ signalTorn();
954
+ controlPlaneRequests.abort();
955
+ for (const group of groups.values()) {
956
+ group.generation += 1;
957
+ group.handle?.unsubscribe();
958
+ group.session?.close();
959
+ }
960
+ }
961
+
962
+ // Wired BEFORE the boot loop, so a stop that lands while the first subscribe is still in flight
963
+ // reaches the same teardown the returned handle would.
964
+ if (options.signal) {
965
+ if (options.signal.aborted) tearDown();
966
+ else options.signal.addEventListener("abort", tearDown, { once: true });
967
+ }
968
+
969
+ /**
970
+ * Start one eager group for BOOT, and wait only as far as its first subscribe attempt.
971
+ *
972
+ * Two things this deliberately does not wait for. Not the catch-up — `bootSettled` means sync START
973
+ * done (ADR-0041), and a client that blocked boot on catch-up would make every cold start as slow as
974
+ * its slowest shape. And not a SUCCESSFUL subscribe — an unreachable control plane retries in the
975
+ * background, so an offline boot still reaches `localReadReady` with `ready` correctly left pending,
976
+ * rather than hanging until the network returns.
977
+ */
978
+ async function startGroupForBoot(groupKey: string): Promise<void> {
979
+ const group = groups.get(groupKey);
980
+ if (group === undefined) return;
981
+ if (group.startPromise) return group.startPromise;
982
+
983
+ let markAttempted!: () => void;
984
+ const firstAttempt = new Promise<void>((resolve) => {
985
+ markAttempted = resolve;
986
+ });
987
+ const bootStamp = options.bootCollector?.beginGroup(groupKey, group.specs.length);
988
+ // On the runtime as well as the call stack: a pre-ready restart re-opens the group and needs it.
989
+ group.bootStamp = bootStamp ?? null;
990
+ const started = startGroup(group, markAttempted, bootStamp).catch((error: unknown) => {
991
+ // A failed start must not be remembered as started: clearing the latch lets a later reference
992
+ // try again rather than resolving instantly against a group that never subscribed.
993
+ group.startPromise = null;
994
+ throw error;
995
+ });
996
+ group.startPromise = started;
997
+ // Boot is released by whichever comes first: the start settling, or the retry loop reporting that
998
+ // its first attempt failed and it is now retrying in the background.
999
+ void started.then(markAttempted, markAttempted);
1000
+ // A start that fails PAST the boot release has no caller left to throw at, so it is reported here
1001
+ // or it is lost. `onSyncError` rather than `onSubscribeError` because this is not the retried
1002
+ // path: subscribe already succeeded, something after it did not, and nothing will try again.
1003
+ void started.catch((error: unknown) => {
1004
+ if (torn) return;
1005
+ options.onSyncError?.(error instanceof Error ? error : new Error(String(error)));
1006
+ });
1007
+ await firstAttempt;
1008
+ }
1009
+
1010
+ // Boot: every eager group, plus any lazy group a previous boot promoted. Started concurrently —
1011
+ // they are independent consistency groups, and serializing them would make boot the sum of their
1012
+ // subscribes rather than the slowest.
1013
+ await Promise.all(eagerKeys.map((groupKey) => startGroupForBoot(groupKey)));
1014
+
1015
+ const tables: Record<string, CircuitsTableSyncResult> = {};
1016
+ for (const spec of specs) {
1017
+ const groupKey = groupKeyOf(spec);
1018
+ Object.defineProperty(tables, spec.key, {
1019
+ enumerable: true,
1020
+ get: () => ({ isUpToDate: groups.get(groupKey)?.handle?.isUpToDate === true }),
1021
+ });
1022
+ }
1023
+
1024
+ return {
1025
+ unsubscribe: tearDown,
1026
+ tables,
1027
+ ensureGroupStarted,
1028
+ stopGroup,
1029
+ groupKeyForTable: (tableKey) => groupKeyByTable.get(tableKey),
1030
+ isTableStarted: (tableKey) => {
1031
+ const groupKey = groupKeyByTable.get(tableKey);
1032
+ if (groupKey === undefined) return false;
1033
+ const group = groups.get(groupKey);
1034
+ if (group === undefined) return false;
1035
+ // A promoted group counts as started from the moment boot kicked its start off, without waiting
1036
+ // for the subscribe to land: its table is durable and populated, which is what "started" asks.
1037
+ // Catching up is `ready`/`isGroupReady`'s question, and it is deliberately not asked here.
1038
+ if (promoted.has(groupKey) && group.startPromise != null) return true;
1039
+ return group.ready;
1040
+ },
1041
+ groupReady: async (groupKey) => {
1042
+ await (groups.get(groupKey)?.readyPromise ?? Promise.resolve());
1043
+ },
1044
+ isGroupReady: (groupKey) => groups.get(groupKey)?.ready === true,
1045
+ groupKeys: () => [...groups.keys()],
1046
+ };
1047
+ }