@pgxsinkit/client 0.1.49 → 0.1.51

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 (51) hide show
  1. package/dist/boot-report.d.ts +76 -0
  2. package/dist/boot-report.d.ts.map +1 -1
  3. package/dist/index.d.ts +56 -3
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1106 -312
  6. package/dist/index.js.map +19 -18
  7. package/dist/local-store.d.ts +58 -0
  8. package/dist/local-store.d.ts.map +1 -1
  9. package/dist/local-tables.d.ts +340 -0
  10. package/dist/local-tables.d.ts.map +1 -1
  11. package/dist/mutation.d.ts +36 -0
  12. package/dist/mutation.d.ts.map +1 -1
  13. package/dist/mutations-api.d.ts +82 -0
  14. package/dist/mutations-api.d.ts.map +1 -0
  15. package/dist/schema.d.ts +80 -1
  16. package/dist/schema.d.ts.map +1 -1
  17. package/dist/shape-sync.d.ts +6 -0
  18. package/dist/shape-sync.d.ts.map +1 -1
  19. package/dist/sync/index.d.ts +1 -1
  20. package/dist/sync/index.d.ts.map +1 -1
  21. package/dist/sync/metadata-tables.d.ts +16 -0
  22. package/dist/sync/metadata-tables.d.ts.map +1 -1
  23. package/dist/sync/subscription-state.d.ts +10 -2
  24. package/dist/sync/subscription-state.d.ts.map +1 -1
  25. package/dist/sync/tags.d.ts +16 -4
  26. package/dist/sync/tags.d.ts.map +1 -1
  27. package/dist/sync/types.d.ts +12 -0
  28. package/dist/sync/types.d.ts.map +1 -1
  29. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  30. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  31. package/dist/worker/protocol.d.ts +44 -1
  32. package/dist/worker/protocol.d.ts.map +1 -1
  33. package/package.json +2 -2
  34. package/skills/core/SKILL.md +1 -1
  35. package/skills/operating/SKILL.md +1 -1
  36. package/src/boot-report.ts +108 -0
  37. package/src/index.ts +555 -136
  38. package/src/local-store.ts +150 -3
  39. package/src/local-tables.ts +49 -1
  40. package/src/mutation.ts +256 -15
  41. package/src/mutations-api.ts +310 -0
  42. package/src/schema.ts +428 -197
  43. package/src/shape-sync.ts +11 -0
  44. package/src/sync/index.ts +14 -1
  45. package/src/sync/metadata-tables.ts +41 -0
  46. package/src/sync/subscription-state.ts +29 -4
  47. package/src/sync/tags.ts +34 -9
  48. package/src/sync/types.ts +12 -0
  49. package/src/worker/attach-sync-client.ts +114 -5
  50. package/src/worker/define-sync-worker.ts +65 -4
  51. package/src/worker/protocol.ts +38 -1
package/src/shape-sync.ts CHANGED
@@ -296,6 +296,10 @@ export async function startConfiguredSync(
296
296
  groupKey: group.groupKey,
297
297
  specs: group.specs,
298
298
  registry: input.registry,
299
+ // ADR-0042: an ephemeral group's cursor + tags are session-scoped (stored in `pg_temp`), so a warm
300
+ // engine restart re-streams the shape from scratch rather than resuming a stale durable cursor over
301
+ // the recreated-empty TEMP cluster. The engine learns only this one storage-scope bit.
302
+ ...(group.retention === "ephemeral" ? { sessionScoped: true } : {}),
299
303
  ...(bootStamp ? { bootStamp } : {}),
300
304
  // The prefetch overlap (ADR-0032 S4) applies ONLY to the eager BOOT starts: a fresh store's eager
301
305
  // groups are genuinely new, so buffering their catch-up behind the commit gate is safe. An on-demand
@@ -400,6 +404,12 @@ interface StartGroupSyncOptions {
400
404
  groupKey: string;
401
405
  specs: ConfiguredShapeSyncSpec[];
402
406
  registry: SyncTableRegistry;
407
+ /**
408
+ * ADR-0042: the group's retention is `ephemeral`, so its sync bookkeeping (cursor + tags) is session-
409
+ * scoped — the engine stores it in `pg_temp` relations that die with the engine. Forwarded straight to
410
+ * the engine's `syncShapesToTables`; absent/`false` for a persistent group (byte-identical storage).
411
+ */
412
+ sessionScoped?: boolean;
403
413
  headers?: ExternalHeadersRecord;
404
414
  /** Fresh-store prefetch overlap gate (ADR-0032 S4) — forwarded to the engine's `syncShapesToTables`. */
405
415
  dbReady?: Promise<void>;
@@ -450,6 +460,7 @@ export async function startGroupSync(pg: SyncEnginePGlite, input: StartGroupSync
450
460
  key: input.groupKey,
451
461
  registry: input.registry,
452
462
  shapes,
463
+ ...(input.sessionScoped ? { sessionScoped: input.sessionScoped } : {}),
453
464
  ...(input.dbReady ? { dbReady: input.dbReady } : {}),
454
465
  ...(input.bootStamp ? { bootStamp: input.bootStamp } : {}),
455
466
  ...(input.onGroupInitialSync ? { onInitialSync: input.onGroupInitialSync } : {}),
package/src/sync/index.ts CHANGED
@@ -163,6 +163,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
163
163
  key,
164
164
  registry,
165
165
  shapes,
166
+ sessionScoped = false,
166
167
  initialInsertMethod,
167
168
  onInitialSync,
168
169
  onError,
@@ -224,6 +225,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
224
225
  pg,
225
226
  metadataSchema,
226
227
  subscriptionKey: key,
228
+ sessionScoped,
227
229
  });
228
230
  if (debug && subState) {
229
231
  console.log("resuming from subscription state", subState);
@@ -436,7 +438,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
436
438
  }
437
439
  // The re-snapshot rebuilds tags from scratch, so drop this shape's stale tag-set too
438
440
  // (ADR-0023 Slice 2: a must-refetch/​rebuild must not leave orphan tags).
439
- await clearShapeTags({ pg: tx, metadataSchema, shapeTable });
441
+ await clearShapeTags({ pg: tx, metadataSchema, shapeTable, sessionScoped });
440
442
  }
441
443
 
442
444
  // ADR-0024: this shape's buffered move-in snapshot rows (a row ENTERING the shape). Their
@@ -451,6 +453,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
451
453
  shapeTable,
452
454
  messages: moveInMessages,
453
455
  primaryKey: target.primaryKey,
456
+ sessionScoped,
454
457
  });
455
458
  }
456
459
 
@@ -463,6 +466,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
463
466
  shapeTable,
464
467
  messages: initialMessages,
465
468
  primaryKey: target.primaryKey,
469
+ sessionScoped,
466
470
  });
467
471
 
468
472
  // ADR-0024: apply the move-in rows idempotently BEFORE the change fold, so a same-commit
@@ -567,6 +571,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
567
571
  target,
568
572
  patternSets,
569
573
  debug,
574
+ sessionScoped,
570
575
  });
571
576
  }
572
577
  }
@@ -576,6 +581,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
576
581
  pg: tx,
577
582
  metadataSchema,
578
583
  subscriptionKey: key,
584
+ sessionScoped,
579
585
  shapeMetadata: Object.fromEntries(
580
586
  Object.keys(shapes).map((shapeName) => {
581
587
  const stream = getShapeStream(shapeName);
@@ -1024,6 +1030,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
1024
1030
  },
1025
1031
  },
1026
1032
  key: options.shapeKey,
1033
+ ...(options.sessionScoped ? { sessionScoped: options.sessionScoped } : {}),
1027
1034
  onInitialSync: options.onInitialSync,
1028
1035
  onError: options.onError,
1029
1036
  onSyncError: options.onSyncError,
@@ -1047,6 +1054,12 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
1047
1054
  };
1048
1055
 
1049
1056
  const deleteSubscription = async (key: string) => {
1057
+ // ADR-0042: the scope-blind delete now also touches `pg_temp.subscriptions_metadata`, which does NOT
1058
+ // exist until the (per-engine, memoized) metadata migration has run — so a warm-store reset that fires
1059
+ // before any group started (nothing else triggered `initMetadataTables` yet) would hit 42P01. Ensure the
1060
+ // provisioning first; the promise is memoized/idempotent, so on the normal path (a group already
1061
+ // started) this is a no-op await on the resolved init promise.
1062
+ await initMetadataTables();
1050
1063
  await deleteSubscriptionState({
1051
1064
  pg,
1052
1065
  metadataSchema,
@@ -25,6 +25,16 @@ export interface MetadataTables {
25
25
  readonly shapeRowTags: ReturnType<typeof buildShapeRowTags>;
26
26
  }
27
27
 
28
+ /**
29
+ * The `pg_temp` schema name the SESSION metadata variants are built under (ADR-0042). An ephemeral
30
+ * group's sync bookkeeping (cursor + tags) is scoped to the engine session by placing it in `pg_temp`
31
+ * relations that die with the engine — the cursor's lifetime is mechanically tied to the TEMP cluster
32
+ * whose rows it indexes. `pg_temp` is a per-session alias Postgres accepts in DML qualification (probed
33
+ * on real PGlite), so the DML paths select these objects unchanged. Same relation NAMES as the durable
34
+ * variants, distinguished by schema alone (maintainer ruling).
35
+ */
36
+ const SESSION_METADATA_SCHEMA = "pg_temp";
37
+
28
38
  function buildSubscriptionsMetadata(schema: ReturnType<typeof pgSchema>) {
29
39
  return schema.table("subscriptions_metadata", {
30
40
  key: text("key").primaryKey(),
@@ -65,3 +75,34 @@ export function getMetadataTables(metadataSchema: string): MetadataTables {
65
75
  }
66
76
  return tables;
67
77
  }
78
+
79
+ let sessionCache: MetadataTables | undefined;
80
+
81
+ /**
82
+ * The (memoized) SESSION metadata-store `pgTable`s (ADR-0042) — the same relation names as the durable
83
+ * variants, built from the SAME column builders (ADR-0029 D3 single-source), but schema-qualified into
84
+ * `pg_temp` so the DML lands in the engine's session-scoped TEMP relations. No schema parameter: `pg_temp`
85
+ * is per-engine by construction, so a single memoized singleton serves every engine. The DDL that
86
+ * PROVISIONS these tables uses the unqualified `CREATE TEMP TABLE` form (the TEMP keyword places the
87
+ * relation in the session schema; a `pg_temp.x` DDL target is not portable), rendered from these SAME
88
+ * definitions via `renderCreateTableSql({ temp: true })`.
89
+ */
90
+ export function getSessionMetadataTables(): MetadataTables {
91
+ if (!sessionCache) {
92
+ const schema = pgSchema(SESSION_METADATA_SCHEMA);
93
+ sessionCache = {
94
+ subscriptionsMetadata: buildSubscriptionsMetadata(schema),
95
+ shapeRowTags: buildShapeRowTags(schema),
96
+ };
97
+ }
98
+ return sessionCache;
99
+ }
100
+
101
+ /**
102
+ * Select the durable or SESSION metadata tables (ADR-0042). `sessionScoped` groups (ephemeral retention)
103
+ * route their cursor + tag DML to the `pg_temp` variants; every other group keeps the durable tables. The
104
+ * engine learns one storage-scope bit, not the retention model.
105
+ */
106
+ export function pickMetadataTables(metadataSchema: string, sessionScoped: boolean): MetadataTables {
107
+ return sessionScoped ? getSessionMetadataTables() : getMetadataTables(metadataSchema);
108
+ }
@@ -8,7 +8,7 @@ import { quoteIdentifier } from "@pgxsinkit/contracts";
8
8
 
9
9
  import { renderCreateTableSql } from "../schema";
10
10
  import { drizzleOverPg } from "./drizzle-executor";
11
- import { getMetadataTables } from "./metadata-tables";
11
+ import { getMetadataTables, getSessionMetadataTables, pickMetadataTables } from "./metadata-tables";
12
12
  import { type Lsn, type SubscriptionKey } from "./types";
13
13
 
14
14
  export interface SubscriptionState {
@@ -26,14 +26,21 @@ export interface GetSubscriptionStateOptions {
26
26
  readonly pg: PGliteInterface | Transaction;
27
27
  readonly metadataSchema: string;
28
28
  readonly subscriptionKey: SubscriptionKey;
29
+ /**
30
+ * ADR-0042: read the SESSION (`pg_temp`) cursor instead of the durable one for an ephemeral group. On
31
+ * every engine boot the session table is empty, so a returning ephemeral group correctly reads `null`
32
+ * (a brand-new subscription) and re-streams its whole shape from scratch over the recreated TEMP cluster.
33
+ */
34
+ readonly sessionScoped?: boolean;
29
35
  }
30
36
 
31
37
  export async function getSubscriptionState({
32
38
  pg,
33
39
  metadataSchema,
34
40
  subscriptionKey,
41
+ sessionScoped = false,
35
42
  }: GetSubscriptionStateOptions): Promise<SubscriptionState | null> {
36
- const { subscriptionsMetadata } = getMetadataTables(metadataSchema);
43
+ const { subscriptionsMetadata } = pickMetadataTables(metadataSchema, sessionScoped);
37
44
  const rows = await drizzleOverPg(pg)
38
45
  .select()
39
46
  .from(subscriptionsMetadata)
@@ -74,6 +81,8 @@ export interface UpdateSubscriptionStateOptions {
74
81
  shapeMetadata: Record<string, ShapeSubscriptionState>;
75
82
  lastLsn: Lsn;
76
83
  debug?: boolean;
84
+ /** ADR-0042: persist the cursor to the SESSION (`pg_temp`) table for an ephemeral group. */
85
+ sessionScoped?: boolean;
77
86
  }
78
87
 
79
88
  export async function updateSubscriptionState({
@@ -83,12 +92,13 @@ export async function updateSubscriptionState({
83
92
  shapeMetadata,
84
93
  lastLsn,
85
94
  debug,
95
+ sessionScoped = false,
86
96
  }: UpdateSubscriptionStateOptions) {
87
97
  if (debug) {
88
98
  console.log("updating subscription state", subscriptionKey, shapeMetadata, lastLsn);
89
99
  }
90
100
 
91
- const { subscriptionsMetadata } = getMetadataTables(metadataSchema);
101
+ const { subscriptionsMetadata } = pickMetadataTables(metadataSchema, sessionScoped);
92
102
  const lastLsnText = lastLsn.toString();
93
103
  await drizzleOverPg(pg)
94
104
  .insert(subscriptionsMetadata)
@@ -106,8 +116,15 @@ export interface DeleteSubscriptionStateOptions {
106
116
  }
107
117
 
108
118
  export async function deleteSubscriptionState({ pg, metadataSchema, subscriptionKey }: DeleteSubscriptionStateOptions) {
119
+ // ADR-0042: SCOPE-BLIND delete — remove the key from BOTH the durable and the session (`pg_temp`) cursor
120
+ // tables. Idempotent (a `WHERE key = …` no-op on the table that never held it), so every existing caller —
121
+ // `desync`, `discardEphemeral`, the `"rebuilt"` all-keys reset — clears both with zero caller changes, and
122
+ // a persistent→ephemeral flip leaves no orphaned durable cursor row behind.
123
+ const db = drizzleOverPg(pg);
109
124
  const { subscriptionsMetadata } = getMetadataTables(metadataSchema);
110
- await drizzleOverPg(pg).delete(subscriptionsMetadata).where(eq(subscriptionsMetadata.key, subscriptionKey));
125
+ const session = getSessionMetadataTables();
126
+ await db.delete(subscriptionsMetadata).where(eq(subscriptionsMetadata.key, subscriptionKey));
127
+ await db.delete(session.subscriptionsMetadata).where(eq(session.subscriptionsMetadata.key, subscriptionKey));
111
128
  }
112
129
 
113
130
  export interface MigrateSubscriptionMetadataTablesOptions {
@@ -125,11 +142,19 @@ export async function migrateSubscriptionMetadataTables({
125
142
  // (schema identifier assembled at construction; the GUC has no tier-①/② form). Executed together as
126
143
  // one batch, exactly as before — same relations, same IF NOT EXISTS idempotence, same GUC default.
127
144
  const { subscriptionsMetadata, shapeRowTags } = getMetadataTables(metadataSchema);
145
+ // ADR-0042: alongside the durable relations, provision the SESSION (`pg_temp`) cursor + tag tables in the
146
+ // SAME migrate step (once per engine, memoized by the caller). Their DDL is the unqualified `CREATE TEMP
147
+ // TABLE` form rendered from the same session pgTables (single-source, ADR-0029 D3) — the TEMP keyword
148
+ // places them in `pg_temp` where the DML (schema-qualified `pg_temp.*`) reads/writes them. They die with
149
+ // the engine, so an ephemeral group's cursor lifetime is mechanically tied to the TEMP cluster it indexes.
150
+ const session = getSessionMetadataTables();
128
151
  const statements = [
129
152
  `SET ${metadataSchema}.syncing = false;`,
130
153
  `CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(metadataSchema)};`,
131
154
  ...renderCreateTableSql(subscriptionsMetadata),
132
155
  ...renderCreateTableSql(shapeRowTags),
156
+ ...renderCreateTableSql(session.subscriptionsMetadata, { temp: true }),
157
+ ...renderCreateTableSql(session.shapeRowTags, { temp: true }),
133
158
  ];
134
159
  await pg.exec(statements.join("\n"));
135
160
  }
package/src/sync/tags.ts CHANGED
@@ -8,7 +8,7 @@ import { quoteIdentifier, quoteSqlLiteral } from "@pgxsinkit/contracts";
8
8
  import type { ApplyTarget } from "../local-tables";
9
9
  import { applyBulkDeletesToTable } from "./apply";
10
10
  import { drizzleOverPg } from "./drizzle-executor";
11
- import { getMetadataTables } from "./metadata-tables";
11
+ import { getMetadataTables, getSessionMetadataTables, pickMetadataTables } from "./metadata-tables";
12
12
 
13
13
  /**
14
14
  * Electric **tagged-subquery** reconciliation (ADR-0023). A shape whose `where` contains a subquery
@@ -74,6 +74,16 @@ export function shapeRowTagsTableName(metadataSchema: string): string {
74
74
  return `${quoteIdentifier(config.schema ?? "public")}.${quoteIdentifier(config.name)}`;
75
75
  }
76
76
 
77
+ /**
78
+ * The SESSION (`pg_temp`) tag store's qualified identifier (ADR-0042), derived from the session
79
+ * `shape_row_tags` pgTable config — the same relation name, in `pg_temp`. Used by the scope-blind
80
+ * {@link buildClearShapeTagsSql} so a desync/discard clears an ephemeral shape's tags wherever they live.
81
+ */
82
+ export function shapeRowTagsSessionTableName(): string {
83
+ const config = getTableConfig(getSessionMetadataTables().shapeRowTags);
84
+ return `${quoteIdentifier(config.schema ?? "public")}.${quoteIdentifier(config.name)}`;
85
+ }
86
+
77
87
  /** The `shape_table` key for the tag store: the synced table, schema-qualified (defaults `public`). */
78
88
  export function shapeTableId(schema: string | undefined, table: string): string {
79
89
  return `${schema ?? "public"}.${table}`;
@@ -87,11 +97,16 @@ export function shapeTableId(schema: string | undefined, table: string): string
87
97
  * guarded.
88
98
  */
89
99
  export function buildClearShapeTagsSql(shapeTable: string, metadataSchema: string = DEFAULT_METADATA_SCHEMA): string {
90
- const table = shapeRowTagsTableName(metadataSchema);
91
- return `DO $$ BEGIN
92
- IF to_regclass(${quoteSqlLiteral(table)}) IS NOT NULL THEN
100
+ // ADR-0042: SCOPE-BLIND — clear the shape's tags from BOTH the durable and the session (`pg_temp`) tag
101
+ // store, each guarded independently by `to_regclass` (a desync/discard may run on a persistent table whose
102
+ // session store never existed, or standalone before any engine boot). `to_regclass('pg_temp.shape_row_tags')`
103
+ // resolves the session table via the per-session `pg_temp` alias (probed on real PGlite).
104
+ const clearOne = (table: string) => ` IF to_regclass(${quoteSqlLiteral(table)}) IS NOT NULL THEN
93
105
  DELETE FROM ${table} WHERE shape_table = ${quoteSqlLiteral(shapeTable)};
94
- END IF;
106
+ END IF;`;
107
+ return `DO $$ BEGIN
108
+ ${clearOne(shapeRowTagsTableName(metadataSchema))}
109
+ ${clearOne(shapeRowTagsSessionTableName())}
95
110
  END $$;`;
96
111
  }
97
112
 
@@ -158,6 +173,8 @@ interface TagSyncOptions {
158
173
  shapeTable: string;
159
174
  messages: ChangeMessage<Row<unknown>>[];
160
175
  primaryKey: string[];
176
+ /** ADR-0042: route the tag DML to the SESSION (`pg_temp`) store for an ephemeral group. */
177
+ sessionScoped?: boolean;
161
178
  }
162
179
 
163
180
  /**
@@ -173,8 +190,9 @@ export async function applyShapeTagSync({
173
190
  shapeTable,
174
191
  messages,
175
192
  primaryKey,
193
+ sessionScoped = false,
176
194
  }: TagSyncOptions): Promise<void> {
177
- const { shapeRowTags } = getMetadataTables(metadataSchema);
195
+ const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
178
196
  const db = drizzleOverPg(pg);
179
197
 
180
198
  for (const message of messages) {
@@ -233,8 +251,9 @@ export async function addShapeRowTags({
233
251
  shapeTable,
234
252
  messages,
235
253
  primaryKey,
254
+ sessionScoped = false,
236
255
  }: TagSyncOptions): Promise<void> {
237
- const { shapeRowTags } = getMetadataTables(metadataSchema);
256
+ const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
238
257
  const db = drizzleOverPg(pg);
239
258
 
240
259
  for (const message of messages) {
@@ -259,6 +278,8 @@ interface MoveOutOptions {
259
278
  /** One entry per buffered `move-out` event, each its own pattern set. */
260
279
  patternSets: MovePattern[][];
261
280
  debug: boolean;
281
+ /** ADR-0042: route the tag reads/evictions to the SESSION (`pg_temp`) store for an ephemeral group. */
282
+ sessionScoped?: boolean;
262
283
  }
263
284
 
264
285
  /**
@@ -274,8 +295,9 @@ export async function applyShapeMoveOut({
274
295
  target,
275
296
  patternSets,
276
297
  debug,
298
+ sessionScoped = false,
277
299
  }: MoveOutOptions): Promise<number> {
278
- const { shapeRowTags } = getMetadataTables(metadataSchema);
300
+ const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
279
301
  const db = drizzleOverPg(pg);
280
302
  const evictedPkJsons = new Set<string>();
281
303
 
@@ -355,11 +377,14 @@ export async function clearShapeTags({
355
377
  pg,
356
378
  metadataSchema,
357
379
  shapeTable,
380
+ sessionScoped = false,
358
381
  }: {
359
382
  pg: PGliteInterface | Transaction;
360
383
  metadataSchema: string;
361
384
  shapeTable: string;
385
+ /** ADR-0042: clear the SESSION (`pg_temp`) tag store for an ephemeral group's must-refetch rebuild. */
386
+ sessionScoped?: boolean;
362
387
  }): Promise<void> {
363
- const { shapeRowTags } = getMetadataTables(metadataSchema);
388
+ const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
364
389
  await drizzleOverPg(pg).delete(shapeRowTags).where(eq(shapeRowTags.shape_table, shapeTable));
365
390
  }
package/src/sync/types.ts CHANGED
@@ -51,6 +51,16 @@ export interface SyncShapesToTablesOptions {
51
51
  /** The engine's per-table spec source (ADR-0029 D1): every shape's `tableKey` resolves against it. */
52
52
  registry: SyncTableRegistry;
53
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` — every
60
+ * persistent group's storage is byte-identical to before. One storage-scope bit; the engine never learns
61
+ * the retention model.
62
+ */
63
+ sessionScoped?: boolean | undefined;
54
64
  initialInsertMethod?: InitialInsertMethod | undefined;
55
65
  onInitialSync?: (() => void) | undefined;
56
66
  /**
@@ -113,6 +123,8 @@ export interface SyncShapeToTableOptions {
113
123
  registry: SyncTableRegistry;
114
124
  tableKey: string;
115
125
  shapeKey: string | null;
126
+ /** ADR-0042: SESSION-scope this shape's cursor + tags (ephemeral retention); see {@link SyncShapesToTablesOptions.sessionScoped}. */
127
+ sessionScoped?: boolean | undefined;
116
128
  initialInsertMethod?: InitialInsertMethod | undefined;
117
129
  onInitialSync?: (() => void) | undefined;
118
130
  onError?: ((error: FetchError | Error) => void) | undefined;
@@ -25,6 +25,8 @@ import type { DiagnosticExportOptions, DiagnosticExportResult } from "../export-
25
25
  import type { StoreExportOptions, StoreExportResult } from "../export-store";
26
26
  import {
27
27
  buildRegistryReadHandles,
28
+ ClientDisposedError,
29
+ createMutationsApi,
28
30
  type LiveQueryDiagnostics,
29
31
  type LiveRowsSubscription,
30
32
  type MutationBatchItem,
@@ -166,9 +168,14 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
166
168
  // ─── Status + readiness ──────────────────────────────────────────────────────────────────────────
167
169
  const status: SyncRuntimeStatus = { phase: "booting", isRunning: false };
168
170
  let resolveReady!: () => void;
169
- const ready = new Promise<void>((resolve) => {
171
+ // FIX 2: `ready` gains a reject path so a detach BEFORE initial sync settles it (an attached client stopped
172
+ // pre-ready would otherwise leave `client.ready` / `client.start()` pending forever). Guarded below.
173
+ let rejectReady!: (error: unknown) => void;
174
+ const ready = new Promise<void>((resolve, reject) => {
170
175
  resolveReady = resolve;
176
+ rejectReady = reject;
171
177
  });
178
+ void ready.catch(() => undefined);
172
179
  let readyResolved = false;
173
180
  const readyGroups = new Set<string>();
174
181
  const groupWaiters = new Map<string, Array<() => void>>();
@@ -219,6 +226,21 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
219
226
  markGroupReady(event.groupKey);
220
227
  break;
221
228
  }
229
+ case "milestone": {
230
+ // Staged boot readiness (ADR-0041 stage 2): the engine crossed a background stage while this tab was
231
+ // attached. Idempotent with the ack's late-attach fold — whichever observes it first wins.
232
+ if (event.stage === "writeReady") settleWriteReady();
233
+ else if (event.stage === "bootSettled") settleBootSettled();
234
+ break;
235
+ }
236
+ case "milestone-error": {
237
+ // The background write/sync tail rejected a downstream stage (ADR-0041): fail the matching stage so a
238
+ // gated write / `bootSettled` awaiter fails loudly. `localReadReady` and the resolved attach are
239
+ // unaffected — the engine reached local-read readiness before the tail failed.
240
+ if (event.stage === "writeReady") failWriteReady(rebuildError(event.error));
241
+ else if (event.stage === "bootSettled") failBootSettled(rebuildError(event.error));
242
+ break;
243
+ }
222
244
  case "conflict":
223
245
  options.onConflict?.(event.details as MutationDetail[]);
224
246
  break;
@@ -263,14 +285,22 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
263
285
  switch (envelope.type) {
264
286
  case "attach-ack": {
265
287
  const ack = payload as AttachAckPayload;
266
- // A boot failure crosses in the ack's `error` (ADR-0032 FIX 1): reject the handshake so
267
- // `attachSyncClient` rejects instead of hanging forever. On success, the engine exists and the
268
- // status event that follows drives `ready`; `engineReady` covers a LATE attach whose engine already
269
- // fired its monotonic `ready` before this ack (FIX 3), so resolve `ready` straight away.
288
+ // A LOCAL-READ-CORE boot failure crosses in the ack's `error` (ADR-0032 FIX 1): reject the handshake
289
+ // so `attachSyncClient` rejects instead of hanging forever. On success, the engine reached
290
+ // `localReadReady` — resolve that stage now (the ack fires AT localReadReady, ADR-0041 Option B) and
291
+ // fold any downstream milestones/failures the tail already crossed (a late attach). `engineReady`
292
+ // covers a LATE attach whose engine already fired its monotonic `ready` before this ack (FIX 3).
270
293
  if (ack.error) {
271
294
  attachAckReject?.(rebuildError(ack.error));
272
295
  } else {
273
296
  if (ack.engineReady) markReady();
297
+ resolveLocalReadReady();
298
+ // Late-attach milestone fold: the stage may have already crossed (or failed) before this tab
299
+ // attached, in which case there is no broadcast to catch — settle it straight from the ack.
300
+ if (ack.writeReady) settleWriteReady();
301
+ if (ack.writeReadyError) failWriteReady(rebuildError(ack.writeReadyError));
302
+ if (ack.bootSettled) settleBootSettled();
303
+ if (ack.bootSettledError) failBootSettled(rebuildError(ack.bootSettledError));
274
304
  attachAckResolve?.(ack);
275
305
  }
276
306
  break;
@@ -352,6 +382,59 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
352
382
  attachAckReject = reject;
353
383
  });
354
384
 
385
+ // ADR-0041 stage 2 — staged boot readiness on the worker-attached client. The `attach-ack` fires AT the
386
+ // engine's `localReadReady` (the Option B contract), so this client resolves `attachSyncClient` there and
387
+ // `localReadReady` is settled off the ack. `writeReady`/`bootSettled` cross in the engine's background tail:
388
+ // they resolve off the `milestone` broadcast when this tab is attached as the stage fires, OR off the ack's
389
+ // late-attach fold when the stage had already fired before this tab attached — one engine crosses each stage
390
+ // once, so both routes observe the same monotonic sequence. A tail failure rejects the matching stage via
391
+ // the `milestone-error` broadcast / the ack's stage-error fold, so a gated write or a `bootSettled` awaiter
392
+ // fails loudly rather than hanging. All guarded so a rejection on an unconsumed stage is never unhandled.
393
+ let resolveLocalReadReady!: () => void;
394
+ const localReadReady = new Promise<void>((resolve) => {
395
+ resolveLocalReadReady = resolve;
396
+ });
397
+ let resolveWriteReady!: () => void;
398
+ let rejectWriteReady!: (error: unknown) => void;
399
+ const writeReady = new Promise<void>((resolve, reject) => {
400
+ resolveWriteReady = resolve;
401
+ rejectWriteReady = reject;
402
+ });
403
+ let resolveBootSettled!: () => void;
404
+ let rejectBootSettled!: (error: unknown) => void;
405
+ const bootSettled = new Promise<void>((resolve, reject) => {
406
+ resolveBootSettled = resolve;
407
+ rejectBootSettled = reject;
408
+ });
409
+ void localReadReady.catch(() => undefined);
410
+ void writeReady.catch(() => undefined);
411
+ void bootSettled.catch(() => undefined);
412
+ // Idempotent settlers — a stage may be signalled by BOTH the ack fold and a milestone event (or by a
413
+ // detach), and must settle exactly once. `localReadReady` never rejects (a local-read-core failure rejects
414
+ // the attach handshake instead, so this client is never handed out).
415
+ let writeReadySettled = false;
416
+ let bootSettledSettled = false;
417
+ const settleWriteReady = () => {
418
+ if (writeReadySettled) return;
419
+ writeReadySettled = true;
420
+ resolveWriteReady();
421
+ };
422
+ const failWriteReady = (error: unknown) => {
423
+ if (writeReadySettled) return;
424
+ writeReadySettled = true;
425
+ rejectWriteReady(error);
426
+ };
427
+ const settleBootSettled = () => {
428
+ if (bootSettledSettled) return;
429
+ bootSettledSettled = true;
430
+ resolveBootSettled();
431
+ };
432
+ const failBootSettled = (error: unknown) => {
433
+ if (bootSettledSettled) return;
434
+ bootSettledSettled = true;
435
+ rejectBootSettled(error);
436
+ };
437
+
355
438
  // ─── Detach (explicit stop AND page teardown) ──────────────────────────────────────────────────────
356
439
  // The platform fires NO close event on a SharedWorker port — a tab that simply closes would leave its
357
440
  // subscriptions (and their per-write rerun cost) alive in the worker for the worker's whole lifetime
@@ -379,6 +462,21 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
379
462
  // throw). The attach-ack is rejected too so a detach DURING boot rejects `attachSyncClient` (a no-op once
380
463
  // it has already settled).
381
464
  attachAckReject?.(detachError());
465
+ // ADR-0041 (FIX A): reject EVERY still-pending readiness STAGE with ONE typed `ClientDisposedError`, so
466
+ // `instanceof ClientDisposedError` behaves identically in worker and in-process mode (the class doc + the
467
+ // in-process client already promise the typed error on disposal). `detachError()` stays for RPC/subscription
468
+ // rejections below, where the more specific "client detached" message is useful for a data operation.
469
+ // `localReadReady` is left as-is: pre-ack it never resolved (the attach itself rejected); post-ack it already
470
+ // resolved. The `milestone-error` path is untouched — that is a genuine engine failure, not disposal.
471
+ const disposedError = new ClientDisposedError();
472
+ failWriteReady(disposedError);
473
+ failBootSettled(disposedError);
474
+ // The attached `ready` had NO reject path — a detach BEFORE initial sync would otherwise leave
475
+ // `client.ready` / `client.start()` pending forever. Settle it once with the same disposed error.
476
+ if (!readyResolved) {
477
+ readyResolved = true;
478
+ rejectReady(disposedError);
479
+ }
382
480
  for (const pending of rpcPending.values()) pending.reject(detachError());
383
481
  rpcPending.clear();
384
482
  for (const pending of initialPending.values()) pending.reject(detachError());
@@ -551,6 +649,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
551
649
  },
552
650
  ]),
553
651
  ) as SyncClient<TRegistry>["tables"],
652
+ localReadReady,
653
+ writeReady,
654
+ bootSettled,
554
655
  ready,
555
656
  status,
556
657
  start: async () => {
@@ -579,6 +680,14 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
579
680
  discardConflict: (table, entityKey) => rpc<void>("discardConflict", [table, entityKey]),
580
681
  discardQuarantined: (table, entityKey) => rpc<void>("discardQuarantined", [table, entityKey]),
581
682
  diagnostics: (table) => rpc<{ mutation: MutationDiagnostics }>("diagnostics", [table]),
683
+ // The registry-wide mutation-status API (slice 4) over the SAME factory the in-process client uses,
684
+ // wired to this facade's shared seams: the live-rows bridge (`subscribeLiveRows`) and the one-shot
685
+ // `rawQuery` RPC. No new bridge message — `client.mutations` behaves identically to the in-process client.
686
+ mutations: createMutationsApi({
687
+ registry: options.registry,
688
+ subscribeLiveRows,
689
+ query: (sql, params) => rpc<Results>("rawQuery", [sql, params]),
690
+ }),
582
691
  query: notSupported("client.query"),
583
692
  queryRow: notSupported("client.queryRow"),
584
693
  queryRaw: notSupported("client.queryRaw"),