@pgxsinkit/client 0.1.50 → 0.1.53

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 (54) hide show
  1. package/dist/error-chain.d.ts +9 -0
  2. package/dist/error-chain.d.ts.map +1 -0
  3. package/dist/export-dump.d.ts.map +1 -1
  4. package/dist/index.d.ts +66 -13
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +284 -82
  7. package/dist/index.js.map +21 -19
  8. package/dist/local-tables.d.ts +6 -0
  9. package/dist/local-tables.d.ts.map +1 -1
  10. package/dist/schema.d.ts +18 -1
  11. package/dist/schema.d.ts.map +1 -1
  12. package/dist/shape-sync.d.ts +6 -0
  13. package/dist/shape-sync.d.ts.map +1 -1
  14. package/dist/sync/apply.d.ts +12 -1
  15. package/dist/sync/apply.d.ts.map +1 -1
  16. package/dist/sync/index.d.ts +1 -1
  17. package/dist/sync/index.d.ts.map +1 -1
  18. package/dist/sync/metadata-tables.d.ts +16 -0
  19. package/dist/sync/metadata-tables.d.ts.map +1 -1
  20. package/dist/sync/subscription-state.d.ts +10 -2
  21. package/dist/sync/subscription-state.d.ts.map +1 -1
  22. package/dist/sync/tags.d.ts +16 -4
  23. package/dist/sync/tags.d.ts.map +1 -1
  24. package/dist/sync/types.d.ts +12 -0
  25. package/dist/sync/types.d.ts.map +1 -1
  26. package/dist/worker/attach-sync-client.d.ts +4 -1
  27. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  28. package/dist/worker/define-sync-worker.d.ts +41 -0
  29. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  30. package/dist/worker/live-query-manager.d.ts.map +1 -1
  31. package/dist/worker/live-query-params-guard.d.ts +14 -0
  32. package/dist/worker/live-query-params-guard.d.ts.map +1 -0
  33. package/dist/worker/protocol.d.ts +17 -1
  34. package/dist/worker/protocol.d.ts.map +1 -1
  35. package/package.json +2 -2
  36. package/skills/core/SKILL.md +6 -2
  37. package/skills/operating/SKILL.md +28 -5
  38. package/src/error-chain.ts +26 -0
  39. package/src/export-dump.ts +5 -1
  40. package/src/index.ts +175 -41
  41. package/src/local-tables.ts +7 -0
  42. package/src/schema.ts +22 -4
  43. package/src/shape-sync.ts +11 -0
  44. package/src/sync/apply.ts +164 -26
  45. package/src/sync/index.ts +45 -8
  46. package/src/sync/metadata-tables.ts +41 -0
  47. package/src/sync/subscription-state.ts +29 -4
  48. package/src/sync/tags.ts +34 -9
  49. package/src/sync/types.ts +12 -0
  50. package/src/worker/attach-sync-client.ts +119 -20
  51. package/src/worker/define-sync-worker.ts +112 -2
  52. package/src/worker/live-query-manager.ts +6 -0
  53. package/src/worker/live-query-params-guard.ts +57 -0
  54. package/src/worker/protocol.ts +28 -0
package/src/sync/apply.ts CHANGED
@@ -2,10 +2,10 @@
2
2
  // Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
3
3
  import type { ChangeMessage, Row } from "@electric-sql/client";
4
4
  import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
5
- import { and, eq, fillPlaceholders, sql } from "drizzle-orm";
5
+ import { and, eq, fillPlaceholders, type SQL, sql } from "drizzle-orm";
6
6
  import { getTableConfig, type PgColumn } from "drizzle-orm/pg-core";
7
7
 
8
- import { quoteIdentifier } from "@pgxsinkit/contracts";
8
+ import { quoteIdentifier, type SyncColumnType } from "@pgxsinkit/contracts";
9
9
 
10
10
  import type { ApplyTarget } from "../local-tables";
11
11
  import { generateCopyData } from "./copy";
@@ -38,6 +38,54 @@ function targetColumn(target: ApplyTarget, name: string): PgColumn {
38
38
  return column;
39
39
  }
40
40
 
41
+ /**
42
+ * True when any of `colNames` is a GENERATED ALWAYS identity column on the target table. Drizzle-orm's
43
+ * insert builder EXCLUDES a generated-always identity column from the rendered INSERT even when the value
44
+ * is supplied (its type error points at `.overridingSystemValue()`), so a plain `.values()` would silently
45
+ * drop such a column — fatal for a GENERATED ALWAYS identity PK (the synced row loses its key and dies on
46
+ * NOT NULL). Detected from the Drizzle column metadata (`generatedIdentity.type === "always"`, mirroring
47
+ * drizzle's own `shouldDisableInsert`). `byDefault` identity is deliberately NOT matched: drizzle already
48
+ * renders those, so the OVERRIDING clause is neither needed nor wanted for them.
49
+ */
50
+ function hasGeneratedIdentityColumn(target: ApplyTarget, colNames: readonly string[]): boolean {
51
+ return colNames.some((name) => {
52
+ const column = target.columnByName[name] as (PgColumn & { generatedIdentity?: { type?: string } }) | undefined;
53
+ return column?.generatedIdentity !== undefined && column.generatedIdentity.type !== "byDefault";
54
+ });
55
+ }
56
+
57
+ /**
58
+ * `db.insert(target.table)`, upgraded to `INSERT … OVERRIDING SYSTEM VALUE` when the applied columns carry
59
+ * a GENERATED ALWAYS identity column ({@link hasGeneratedIdentityColumn}). For a synced cache the SERVER's
60
+ * identity values are authoritative — the local row must carry the server id verbatim, never a
61
+ * locally-generated one — so OVERRIDING SYSTEM VALUE is the semantically correct clause (and it makes
62
+ * drizzle re-include the column it would otherwise drop). Tables without a generated column get a plain
63
+ * insert, so the clause is emitted only where it is required. (The local synced table renders the identity
64
+ * PK as a PLAIN column — the generator emits `getSQLType()` with no identity clause — and PGlite accepts
65
+ * OVERRIDING SYSTEM VALUE against a plain column as a no-op, so this is safe there too.)
66
+ */
67
+ function insertInto(db: ReturnType<typeof drizzleOverPg>, target: ApplyTarget, colNames: readonly string[]) {
68
+ const builder = db.insert(target.table);
69
+ return hasGeneratedIdentityColumn(target, colNames) ? builder.overridingSystemValue() : builder;
70
+ }
71
+
72
+ /**
73
+ * The SQL cast type for a synced column inside a `json_to_recordset` record definition (or a `::` cast).
74
+ * A base/array type is used verbatim ({@link SyncColumnType} contracts `sqlType` to be cast-usable); an
75
+ * ENUM column's `sqlType` is the enum TYPE NAME — a user identifier — so it must be identifier-quoted (an
76
+ * unquoted mixed-case enum name folds to lowercase and fails to resolve) and schema-qualified into the
77
+ * SAME schema the local-schema generator creates the enum in (the synced table's own schema), so the cast
78
+ * resolves without depending on search_path. `[]` is appended for an array column, as for base types.
79
+ */
80
+ function castTypeFor(column: SyncColumnType, tableSchema: string | undefined): string {
81
+ const base = column.isEnum
82
+ ? tableSchema
83
+ ? `${quoteIdentifier(tableSchema)}.${quoteIdentifier(column.sqlType)}`
84
+ : quoteIdentifier(column.sqlType)
85
+ : column.sqlType;
86
+ return `${base}${column.isArray ? "[]" : ""}`;
87
+ }
88
+
41
89
  export interface ApplyMessageToTableOptions {
42
90
  pg: PGliteInterface | Transaction;
43
91
  target: ApplyTarget;
@@ -52,9 +100,25 @@ export async function applyMessageToTable({ pg, target, message, debug }: ApplyM
52
100
  switch (message.headers.operation) {
53
101
  case "insert": {
54
102
  if (debug) console.log("inserting", data);
55
- // Apply exactly what Electric sent: an `insert` is a new row (post-truncate or first send), so
56
- // it is a plain INSERT. A genuine primary-key collision must surface, never be silently upserted.
57
- return await db.insert(target.table).values(toDriverRow(target, data) as never);
103
+ const columns = Object.keys(data);
104
+ const insert = insertInto(db, target, columns).values(toDriverRow(target, data) as never);
105
+ if (target.applyMode === "upsert") {
106
+ // ADR-0045 declared exception: this table legitimately receives locally-derived provisional rows
107
+ // (e.g. written by a local trigger), so the server's authoritative CDC insert is applied
108
+ // idempotently — same semantics as `applyUpsertsToTable` — rather than colliding on the pk.
109
+ const { conflictTarget, conflictSet, nonPkColumns } = upsertConflictSpec(target, columns);
110
+ if (nonPkColumns.length > 0) {
111
+ return await insert.onConflictDoUpdate({ target: conflictTarget, set: conflictSet as never });
112
+ }
113
+ // Target the pk explicitly so a pk-only conflict is a no-op ONLY on the primary key.
114
+ return await insert.onConflictDoNothing({ target: conflictTarget });
115
+ }
116
+ // Default (`applyMode: "insert"`): apply exactly what Electric sent as a plain INSERT — an `insert`
117
+ // is a new row (post-truncate or first send). A genuine primary-key collision must surface, never
118
+ // be silently upserted (ADR-0014), UNLESS the table declared `applyMode: "upsert"` (handled above).
119
+ // `insertInto` adds OVERRIDING SYSTEM VALUE when the row carries a GENERATED ALWAYS identity column,
120
+ // so the server's authoritative id is preserved rather than silently dropped by the builder.
121
+ return await insert;
58
122
  }
59
123
 
60
124
  case "update": {
@@ -107,8 +171,7 @@ function renderInsert(
107
171
  const placeholderRows = Array.from({ length: rowCount }, (_, r) =>
108
172
  Object.fromEntries(colNames.map((name, ci) => [target.propertyKeyByName[name]!, sql.placeholder(`${r}_${ci}`)])),
109
173
  );
110
- const rendered = db
111
- .insert(target.table)
174
+ const rendered = insertInto(db, target, colNames)
112
175
  .values(placeholderRows as never)
113
176
  .toSQL();
114
177
  const value = { sqlText: rendered.sql, params: rendered.params as unknown[] };
@@ -249,6 +312,29 @@ export async function applyInsertsToTable({ pg, target, messages, debug }: BulkA
249
312
  if (debug) console.log(`Inserted ${messages.length} rows using INSERT`);
250
313
  }
251
314
 
315
+ /**
316
+ * The `ON CONFLICT (pk)` upsert spec for a keyed apply — shared by {@link applyUpsertsToTable} (ADR-0024
317
+ * move-ins / snapshot-acceptance) and the per-message `applyMode: "upsert"` CDC-insert path (ADR-0045),
318
+ * so the two can never drift on conflict semantics. The conflict target is the primary-key columns; the
319
+ * conflict SET refreshes every non-pk column to `excluded.<col>` (the standard conflict pseudo-relation,
320
+ * authored via `sql.identifier` so the column stays a quoted BARE identifier, not table-qualified). A
321
+ * pk-only table yields an empty `nonPkColumns` — the caller then uses `DO NOTHING` targeted at the pk
322
+ * (never a bare `ON CONFLICT DO NOTHING`, which would swallow conflicts on any unique constraint).
323
+ */
324
+ function upsertConflictSpec(
325
+ target: ApplyTarget,
326
+ columns: readonly string[],
327
+ ): { conflictTarget: PgColumn[]; conflictSet: Record<string, unknown>; nonPkColumns: string[] } {
328
+ const pkSet = new Set(target.primaryKey);
329
+ const nonPkColumns = columns.filter((column) => !pkSet.has(column));
330
+ const conflictTarget = target.primaryKey.map((column) => targetColumn(target, column));
331
+ const conflictSet: Record<string, unknown> = {};
332
+ for (const column of nonPkColumns) {
333
+ conflictSet[target.propertyKeyByName[column]!] = sql`excluded.${sql.identifier(column)}`;
334
+ }
335
+ return { conflictTarget, conflictSet, nonPkColumns };
336
+ }
337
+
252
338
  /**
253
339
  * Bulk **upsert** for tagged-subquery move-in rows (ADR-0024). A move-in is an existing row ENTERING the
254
340
  * shape — unlike a CDC `insert` (a brand-new row) it may already be present locally via an independent
@@ -267,17 +353,7 @@ export async function applyUpsertsToTable({ pg, target, messages, debug }: BulkK
267
353
  if (!firstRow) return;
268
354
 
269
355
  const columns = Object.keys(firstRow);
270
- const pkSet = new Set(primaryKey);
271
- const nonPkColumns = columns.filter((column) => !pkSet.has(column));
272
-
273
- const conflictTarget = primaryKey.map((column) => targetColumn(target, column));
274
- // `DO UPDATE SET col = excluded.col` for every non-pk column; `excluded.<col>` is the standard
275
- // conflict pseudo-relation reference, authored via `sql.identifier` so the column stays a quoted bare
276
- // identifier (not table-qualified). A pk-only table has nothing to refresh → `DO NOTHING`.
277
- const conflictSet: Record<string, unknown> = {};
278
- for (const column of nonPkColumns) {
279
- conflictSet[target.propertyKeyByName[column]!] = sql`excluded.${sql.identifier(column)}`;
280
- }
356
+ const { conflictTarget, conflictSet, nonPkColumns } = upsertConflictSpec(target, columns);
281
357
 
282
358
  const perRow = columns.length;
283
359
  const rowsPerBatch = Math.max(1, Math.floor(MAX_INSERT_PARAMS / perRow));
@@ -285,7 +361,9 @@ export async function applyUpsertsToTable({ pg, target, messages, debug }: BulkK
285
361
 
286
362
  for (let i = 0; i < data.length; i += rowsPerBatch) {
287
363
  const batch = data.slice(i, i + rowsPerBatch).map((row) => toDriverRow(target, row));
288
- const insert = db.insert(target.table).values(batch as never);
364
+ // A move-in row carries the server's authoritative values incl. any GENERATED ALWAYS identity PK, so
365
+ // `insertInto` adds OVERRIDING SYSTEM VALUE where needed (same hazard as the CDC/bulk insert paths).
366
+ const insert = insertInto(db, target, columns).values(batch as never);
289
367
  if (nonPkColumns.length > 0) {
290
368
  await insert.onConflictDoUpdate({ target: conflictTarget, set: conflictSet as never });
291
369
  } else {
@@ -312,13 +390,49 @@ interface JsonRecordsetColumn {
312
390
  */
313
391
  function jsonRecordsetColumns(target: ApplyTarget, firstRow: Row<unknown>): JsonRecordsetColumn[] {
314
392
  const present = (name: string) => Object.prototype.hasOwnProperty.call(firstRow, name);
393
+ const { schema } = getTableConfig(target.table);
315
394
  return target.columnTypes
316
395
  .filter((column) => present(column.name))
317
- .map((column) => ({ name: column.name, castType: `${column.sqlType}${column.isArray ? "[]" : ""}` }));
396
+ .map((column) => ({ name: column.name, castType: castTypeFor(column, schema) }));
397
+ }
398
+
399
+ /**
400
+ * The `ON CONFLICT (pk)` clause for the json-recordset upsert path (ADR-0045 initial-load tier) — the
401
+ * tier-② mirror of {@link upsertConflictSpec}, authored entirely as interpolated `sql.identifier`
402
+ * fragments (no raw identifier text): the conflict target is `target.primaryKey`, and the SET list
403
+ * refreshes every non-pk recordset column to `excluded.<col>`. A pk-only table has nothing to refresh →
404
+ * `DO NOTHING` targeted at the pk (never a bare `ON CONFLICT DO NOTHING`, which would swallow conflicts on
405
+ * any unique constraint — same rule as `upsertConflictSpec`).
406
+ */
407
+ function jsonConflictClause(target: ApplyTarget, columns: JsonRecordsetColumn[]): SQL {
408
+ const pkSet = new Set(target.primaryKey);
409
+ const nonPkColumns = columns.map((column) => column.name).filter((name) => !pkSet.has(name));
410
+ const conflictTarget = sql.join(
411
+ target.primaryKey.map((name) => sql`${sql.identifier(name)}`),
412
+ sql`, `,
413
+ );
414
+ if (nonPkColumns.length === 0) {
415
+ return sql`ON CONFLICT (${conflictTarget}) DO NOTHING`;
416
+ }
417
+ const setList = sql.join(
418
+ nonPkColumns.map((name) => sql`${sql.identifier(name)} = excluded.${sql.identifier(name)}`),
419
+ sql`, `,
420
+ );
421
+ return sql`ON CONFLICT (${conflictTarget}) DO UPDATE SET ${setList}`;
318
422
  }
319
423
 
320
- export async function applyMessagesToTableWithJson({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {
321
- if (debug) console.log("applying messages with json_to_recordset");
424
+ /**
425
+ * Shared `json_to_recordset` bulk-apply engine for the initial-load tier — one statement, ONE bound param
426
+ * per 10k-row batch (the ADR-0014 remedy for the batched-INSERT param bound). `conflict` is `undefined`
427
+ * for the strict CDC insert ({@link applyMessagesToTableWithJson}) and the `ON CONFLICT (pk)` clause for
428
+ * the ADR-0045 upsert form ({@link applyUpsertsToTableWithJson}); both share the recordDef and batching so
429
+ * the two can never drift.
430
+ */
431
+ async function applyMessagesToTableWithJsonImpl(
432
+ { pg, target, messages, debug }: BulkApplyMessagesToTableOptions,
433
+ conflict: SQL | undefined,
434
+ ) {
435
+ if (debug) console.log(`applying messages with json_to_recordset${conflict ? " (upsert)" : ""}`);
322
436
 
323
437
  const data: Row<unknown>[] = messages.map((message) => message.value);
324
438
  const firstRow = data[0];
@@ -331,23 +445,46 @@ export async function applyMessagesToTableWithJson({ pg, target, messages, debug
331
445
  // param (`sql.param` binds the raw JS array unchanged, exactly as the old `[batch]` did — critically,
332
446
  // NOT `JSON.stringify`, which would throw on the bigints this path carries). The `x(col type, …)`
333
447
  // record definition is raw text: `json_to_recordset`'s grammar requires bare column identifiers and
334
- // type names there, which no tier-①/② builder expresses.
448
+ // type names there, which no tier-①/② builder expresses. The optional ON CONFLICT clause, in contrast,
449
+ // is a fully tier-② `sql.identifier` fragment (see {@link jsonConflictClause}).
335
450
  const recordDef = columns.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(", ");
451
+ const conflictClause = conflict ? sql` ${conflict}` : sql``;
336
452
  const db = drizzleOverPg(pg);
337
453
 
338
454
  const max = 10_000;
339
455
  for (let i = 0; i < data.length; i += max) {
340
456
  const batch = data.slice(i, i + max);
341
457
  await db.execute(
342
- sql`INSERT INTO ${targetTable} SELECT x.* from json_to_recordset(${sql.param(batch)}) as x(${sql.raw(recordDef)})`,
458
+ sql`INSERT INTO ${targetTable} SELECT x.* from json_to_recordset(${sql.param(batch)}) as x(${sql.raw(recordDef)})${conflictClause}`,
343
459
  );
344
460
  }
345
461
 
346
462
  if (debug) {
347
- console.log(`Inserted ${messages.length} rows using json_to_recordset`);
463
+ console.log(`${conflict ? "Upserted" : "Inserted"} ${messages.length} rows using json_to_recordset`);
348
464
  }
349
465
  }
350
466
 
467
+ export async function applyMessagesToTableWithJson(options: BulkApplyMessagesToTableOptions) {
468
+ return applyMessagesToTableWithJsonImpl(options, undefined);
469
+ }
470
+
471
+ /**
472
+ * The `json_to_recordset` **upsert** applier — the ADR-0045 initial-load tier for an `applyMode: "upsert"`
473
+ * table. Identical bulk shape to {@link applyMessagesToTableWithJson} (one statement, one bound param per
474
+ * batch) but with the `ON CONFLICT (pk) DO UPDATE`/`DO NOTHING` clause appended, so a snapshot for a table
475
+ * that already holds locally-derived provisional rows applies idempotently without the 23505 collision the
476
+ * strict path would raise. This is the bulk CEILING for upsert-mode tables: COPY (the faster tier) has no
477
+ * conflict clause, so the initial path downgrades a COPY-eligible upsert table to json rather than
478
+ * param-bound `applyUpsertsToTable` (~31k bound params/statement for a wide table — the very cost this
479
+ * path avoids).
480
+ */
481
+ export async function applyUpsertsToTableWithJson(options: BulkApplyMessagesToTableOptions) {
482
+ const firstRow = options.messages[0]?.value;
483
+ if (!firstRow) return;
484
+ const columns = jsonRecordsetColumns(options.target, firstRow);
485
+ return applyMessagesToTableWithJsonImpl(options, jsonConflictClause(options.target, columns));
486
+ }
487
+
351
488
  /**
352
489
  * Each column mapped to its Postgres `udt_name` for the COPY serializer, which needs it only to
353
490
  * disambiguate `json`/`jsonb` (whose parsed values are indistinguishable from SQL arrays/objects by
@@ -418,12 +555,13 @@ const JSON_RECORDSET_BATCH = 10_000;
418
555
  */
419
556
  function recordsetColumnCasts(target: ApplyTarget, columnNames: string[]): JsonRecordsetColumn[] {
420
557
  const byName = new Map(target.columnTypes.map((column) => [column.name, column]));
558
+ const { schema } = getTableConfig(target.table);
421
559
  return columnNames.map((name) => {
422
560
  const column = byName.get(name);
423
561
  if (!column) {
424
562
  throw new Error(`recordsetColumnCasts: no registered type for column ${JSON.stringify(name)}`);
425
563
  }
426
- return { name, castType: `${column.sqlType}${column.isArray ? "[]" : ""}` };
564
+ return { name, castType: castTypeFor(column, schema) };
427
565
  });
428
566
  }
429
567
 
package/src/sync/index.ts CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  applyMessagesToTableWithCopy,
21
21
  applyMessagesToTableWithJson,
22
22
  applyUpsertsToTable,
23
+ applyUpsertsToTableWithJson,
23
24
  } from "./apply";
24
25
  import { drizzleOverPg } from "./drizzle-executor";
25
26
  import {
@@ -163,6 +164,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
163
164
  key,
164
165
  registry,
165
166
  shapes,
167
+ sessionScoped = false,
166
168
  initialInsertMethod,
167
169
  onInitialSync,
168
170
  onError,
@@ -224,6 +226,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
224
226
  pg,
225
227
  metadataSchema,
226
228
  subscriptionKey: key,
229
+ sessionScoped,
227
230
  });
228
231
  if (debug && subState) {
229
232
  console.log("resuming from subscription state", subState);
@@ -436,7 +439,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
436
439
  }
437
440
  // The re-snapshot rebuilds tags from scratch, so drop this shape's stale tag-set too
438
441
  // (ADR-0023 Slice 2: a must-refetch/​rebuild must not leave orphan tags).
439
- await clearShapeTags({ pg: tx, metadataSchema, shapeTable });
442
+ await clearShapeTags({ pg: tx, metadataSchema, shapeTable, sessionScoped });
440
443
  }
441
444
 
442
445
  // ADR-0024: this shape's buffered move-in snapshot rows (a row ENTERING the shape). Their
@@ -451,6 +454,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
451
454
  shapeTable,
452
455
  messages: moveInMessages,
453
456
  primaryKey: target.primaryKey,
457
+ sessionScoped,
454
458
  });
455
459
  }
456
460
 
@@ -463,6 +467,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
463
467
  shapeTable,
464
468
  messages: initialMessages,
465
469
  primaryKey: target.primaryKey,
470
+ sessionScoped,
466
471
  });
467
472
 
468
473
  // ADR-0024: apply the move-in rows idempotently BEFORE the change fold, so a same-commit
@@ -495,12 +500,33 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
495
500
  messages = remainingMessages;
496
501
 
497
502
  if (initialInserts.length > 0) {
498
- await insertMethods[shapeMethod]({
499
- pg: tx,
500
- target,
501
- messages: initialInserts,
502
- debug,
503
- });
503
+ if (target.applyMode === "upsert") {
504
+ // ADR-0045: the initial bulk-insert fast path's appliers (json/copy/insert) are all
505
+ // plain-INSERT appliers with no conflict clause. A local trigger can already have created
506
+ // rows before this snapshot applies — even on a fresh store, because another table's
507
+ // apply in the same catch-up can fire the trigger — so route through an idempotent
508
+ // upsert applier instead, keeping the `useInsert` bookkeeping identical. A json- or
509
+ // COPY-classified table takes the set-based `json_to_recordset` upsert (COPY itself has
510
+ // no ON CONFLICT clause, so json is the bulk ceiling — and it keeps the performance a
511
+ // param-bound `applyUpsertsToTable` would lose on a large snapshot). A table classified
512
+ // `insert` is so BECAUSE a column is not json-safe — it must take the batched-VALUES
513
+ // upsert, never the json cast.
514
+ const applyInitialUpserts =
515
+ shapeMethod === "insert" ? applyUpsertsToTable : applyUpsertsToTableWithJson;
516
+ await applyInitialUpserts({
517
+ pg: tx,
518
+ target,
519
+ messages: initialInserts,
520
+ debug,
521
+ });
522
+ } else {
523
+ await insertMethods[shapeMethod]({
524
+ pg: tx,
525
+ target,
526
+ messages: initialInserts,
527
+ debug,
528
+ });
529
+ }
504
530
 
505
531
  useInsert.set(shapeName, true);
506
532
  }
@@ -525,11 +551,13 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
525
551
  });
526
552
  }
527
553
  if (folded.inserts.length > 0) {
528
- if (snapshotModeAtPeek.get(shapeName)) {
554
+ if (snapshotModeAtPeek.get(shapeName) || target.applyMode === "upsert") {
529
555
  // Snapshot-acceptance mode (post-reset re-snapshot / pre-first-lsn): the racing recovery
530
556
  // loops can re-deliver these exact snapshot rows, possibly in a later commit after this
531
557
  // shape's TRUNCATE flag has been consumed — so apply them idempotently (upsert), the same
532
558
  // posture as a move-in, rather than failing the commit on a PK collision.
559
+ // ADR-0045: a table declaring `applyMode: "upsert"` also folds its CDC inserts through the
560
+ // idempotent applier, because a local trigger may already have created the provisional row.
533
561
  await applyUpsertsToTable({
534
562
  pg: tx,
535
563
  target,
@@ -567,6 +595,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
567
595
  target,
568
596
  patternSets,
569
597
  debug,
598
+ sessionScoped,
570
599
  });
571
600
  }
572
601
  }
@@ -576,6 +605,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
576
605
  pg: tx,
577
606
  metadataSchema,
578
607
  subscriptionKey: key,
608
+ sessionScoped,
579
609
  shapeMetadata: Object.fromEntries(
580
610
  Object.keys(shapes).map((shapeName) => {
581
611
  const stream = getShapeStream(shapeName);
@@ -1024,6 +1054,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
1024
1054
  },
1025
1055
  },
1026
1056
  key: options.shapeKey,
1057
+ ...(options.sessionScoped ? { sessionScoped: options.sessionScoped } : {}),
1027
1058
  onInitialSync: options.onInitialSync,
1028
1059
  onError: options.onError,
1029
1060
  onSyncError: options.onSyncError,
@@ -1047,6 +1078,12 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
1047
1078
  };
1048
1079
 
1049
1080
  const deleteSubscription = async (key: string) => {
1081
+ // ADR-0042: the scope-blind delete now also touches `pg_temp.subscriptions_metadata`, which does NOT
1082
+ // exist until the (per-engine, memoized) metadata migration has run — so a warm-store reset that fires
1083
+ // before any group started (nothing else triggered `initMetadataTables` yet) would hit 42P01. Ensure the
1084
+ // provisioning first; the promise is memoized/idempotent, so on the normal path (a group already
1085
+ // started) this is a no-op await on the resolved init promise.
1086
+ await initMetadataTables();
1050
1087
  await deleteSubscriptionState({
1051
1088
  pg,
1052
1089
  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
  }