@pgxsinkit/client 0.2.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +2 -1
  2. package/dist/boot-report.d.ts +5 -2
  3. package/dist/boot-report.d.ts.map +1 -1
  4. package/dist/circuits/envelope-to-change.d.ts +35 -0
  5. package/dist/circuits/envelope-to-change.d.ts.map +1 -0
  6. package/dist/circuits/group-sync.d.ts +123 -0
  7. package/dist/circuits/group-sync.d.ts.map +1 -0
  8. package/dist/circuits/shape-group.d.ts +77 -0
  9. package/dist/circuits/shape-group.d.ts.map +1 -0
  10. package/dist/circuits/stream-inbox.d.ts +126 -0
  11. package/dist/circuits/stream-inbox.d.ts.map +1 -0
  12. package/dist/circuits/stream-source.d.ts +90 -0
  13. package/dist/circuits/stream-source.d.ts.map +1 -0
  14. package/dist/circuits/subscription-client.d.ts +143 -0
  15. package/dist/circuits/subscription-client.d.ts.map +1 -0
  16. package/dist/circuits/sync-engine.d.ts +131 -0
  17. package/dist/circuits/sync-engine.d.ts.map +1 -0
  18. package/dist/debug.d.ts +0 -10
  19. package/dist/debug.d.ts.map +1 -1
  20. package/dist/export-dump.d.ts.map +1 -1
  21. package/dist/index.d.ts +47 -19
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +6258 -6443
  24. package/dist/index.js.map +26 -26
  25. package/dist/local-tables.d.ts +1 -1
  26. package/dist/local-tables.d.ts.map +1 -1
  27. package/dist/schema.d.ts.map +1 -1
  28. package/dist/sync/apply.d.ts +13 -21
  29. package/dist/sync/apply.d.ts.map +1 -1
  30. package/dist/sync/copy.d.ts +8 -8
  31. package/dist/sync/fold.d.ts +40 -0
  32. package/dist/sync/fold.d.ts.map +1 -0
  33. package/dist/sync/metadata-tables.d.ts +25 -1
  34. package/dist/sync/metadata-tables.d.ts.map +1 -1
  35. package/dist/sync/subscription-state.d.ts +21 -2
  36. package/dist/sync/subscription-state.d.ts.map +1 -1
  37. package/dist/sync/types.d.ts +9 -129
  38. package/dist/sync/types.d.ts.map +1 -1
  39. package/dist/testing.js +3 -3
  40. package/dist/testing.js.map +2 -2
  41. package/dist/worker/attach-sync-client.d.ts +3 -1
  42. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  43. package/dist/worker/define-sync-worker.d.ts +17 -1
  44. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  45. package/dist/worker/engine-control.d.ts +53 -0
  46. package/dist/worker/engine-control.d.ts.map +1 -1
  47. package/package.json +4 -5
  48. package/skills/core/SKILL.md +72 -55
  49. package/skills/operating/SKILL.md +120 -120
  50. package/src/boot-report.ts +4 -3
  51. package/src/circuits/envelope-to-change.ts +102 -0
  52. package/src/circuits/group-sync.ts +1047 -0
  53. package/src/circuits/shape-group.ts +158 -0
  54. package/src/circuits/stream-inbox.ts +225 -0
  55. package/src/circuits/stream-source.ts +165 -0
  56. package/src/circuits/subscription-client.ts +353 -0
  57. package/src/circuits/sync-engine.ts +641 -0
  58. package/src/debug.ts +1 -85
  59. package/src/export-dump.ts +3 -2
  60. package/src/index.ts +290 -273
  61. package/src/lazy-guard.ts +1 -1
  62. package/src/local-tables.ts +9 -2
  63. package/src/schema.ts +2 -11
  64. package/src/sync/apply.ts +72 -110
  65. package/src/sync/copy.ts +15 -15
  66. package/src/sync/fold.ts +94 -0
  67. package/src/sync/metadata-tables.ts +42 -1
  68. package/src/sync/subscription-state.ts +21 -3
  69. package/src/sync/types.ts +13 -141
  70. package/src/testing.ts +2 -2
  71. package/src/worker/attach-sync-client.ts +8 -1
  72. package/src/worker/define-sync-worker.ts +122 -13
  73. package/src/worker/engine-control.ts +89 -0
  74. package/dist/read-stream-stall.d.ts +0 -54
  75. package/dist/read-stream-stall.d.ts.map +0 -1
  76. package/dist/shape-sync.d.ts +0 -207
  77. package/dist/shape-sync.d.ts.map +0 -1
  78. package/dist/sync/index.d.ts +0 -32
  79. package/dist/sync/index.d.ts.map +0 -1
  80. package/dist/sync/nudge.d.ts +0 -49
  81. package/dist/sync/nudge.d.ts.map +0 -1
  82. package/dist/sync/shape-inbox.d.ts +0 -215
  83. package/dist/sync/shape-inbox.d.ts.map +0 -1
  84. package/dist/sync/tags.d.ts +0 -142
  85. package/dist/sync/tags.d.ts.map +0 -1
  86. package/dist/sync-auth.d.ts +0 -53
  87. package/dist/sync-auth.d.ts.map +0 -1
  88. package/src/read-stream-stall.ts +0 -102
  89. package/src/shape-sync.ts +0 -533
  90. package/src/sync/index.ts +0 -1124
  91. package/src/sync/nudge.ts +0 -110
  92. package/src/sync/shape-inbox.ts +0 -566
  93. package/src/sync/tags.ts +0 -390
  94. package/src/sync-auth.ts +0 -117
package/src/lazy-guard.ts CHANGED
@@ -55,7 +55,7 @@ function tokensForEntry(entry: SyncTableRegistry[string]): string[] {
55
55
  if (entry.readProjection) {
56
56
  // A read PROJECTION (defineReadProjection, ADR-0025) owns no physical table: its `entry.table` is the
57
57
  // OWNER's physical table, but a consumer reads it ONLY through its DISTINCT local identity
58
- // `entry.localTable` (the `as` name — where Electric syncs the projection's rows). Token that, NOT the
58
+ // `entry.localTable` (the `as` name — where the read path syncs the projection's rows). Token that, NOT the
59
59
  // owner's physical name: a read of the projection's own local table then resolves to it, while a read of
60
60
  // the owner's table resolves the OWNER entry (which carries the owner token) without falsely resolving
61
61
  // this projection. (A projection is always readonly and has no read-model view.)
@@ -507,7 +507,7 @@ export function getReadModelView<TRegistry extends SyncTableRegistry, TKey exten
507
507
  * appliers need is derived once from the registry entry — the real projected synced table object, its
508
508
  * columns indexed by DB column name, the primary-key column names, and the model-derived column types —
509
509
  * so the appliers author over Drizzle objects (no name/schema strings, no `information_schema` probe).
510
- * Resolved once per shape at subscribe time; reused for every message. Electric change rows are keyed
510
+ * Resolved once per shape at subscribe time; reused for every message. Streamed change rows are keyed
511
511
  * by DB **column name**, while Drizzle DML keys by **property key**, so both indexes are carried.
512
512
  */
513
513
  export interface ApplyTarget {
@@ -557,7 +557,14 @@ export function resolveApplyTarget<TRegistry extends SyncTableRegistry, TKey ext
557
557
  table: table as AnyPgTable,
558
558
  columnByName,
559
559
  propertyKeyByName,
560
- primaryKey: getLocalSyncedTablePrimaryKeyColumns(entry),
560
+ // Normalized to DB COLUMN NAMES. `defineSyncTable` accepts a primary-key spec written either way
561
+ // (property key or column name) and stores it verbatim on the entry — so on a table whose two
562
+ // differ, the un-normalized form reaches `columnByName`/`propertyKeyByName`, which are keyed by
563
+ // column name, and every update and delete throws "column not found". Resolving here, where the
564
+ // table's own columns are in hand, makes the field match what it has always claimed to be.
565
+ primaryKey: getLocalSyncedTablePrimaryKeyColumns(entry).map((declared) =>
566
+ columns[declared] ? columns[declared].name : declared,
567
+ ),
561
568
  applyMode: entry.applyMode,
562
569
  columnTypes: deriveSyncColumnTypes(entry),
563
570
  insertRenderCache: new Map(),
package/src/schema.ts CHANGED
@@ -14,8 +14,6 @@ import {
14
14
  type SyncTableRegistry,
15
15
  } from "@pgxsinkit/contracts";
16
16
 
17
- import { buildClearShapeTagsSql, shapeTableId } from "./sync/tags";
18
-
19
17
  /** Internal fully-qualified projection used within schema generation. */
20
18
  interface ResolvedProjection {
21
19
  syncedTable: string;
@@ -336,8 +334,8 @@ function buildEntryClusterStatements(entry: SyncTableEntry, tableKey: string, lo
336
334
  );
337
335
 
338
336
  // Trigger: automatically clear overlay + journal entries when the sync
339
- // echo arrives. Fires on INSERT/UPDATE (new data from Electric) and DELETE
340
- // (row removed on server, synced back via Electric).
337
+ // echo arrives. Fires on INSERT/UPDATE (new data down the read path) and
338
+ // DELETE (row removed on the server, streamed back down the read path).
341
339
  const pkMatchSql = (alias: string) =>
342
340
  primaryKeyColumns
343
341
  .map((col) => `"${alias}"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`)
@@ -1136,12 +1134,5 @@ export function buildDesyncTableSql<TRegistry extends SyncTableRegistry>(
1136
1134
  }
1137
1135
  }
1138
1136
 
1139
- // ADR-0023 Slice 2: a desync reverts the relation to dormant and deletes its subscription, so the next
1140
- // activation re-streams from scratch — drop this shape's tag-set too, or it would orphan tags for rows
1141
- // that never come back. The key matches what the engine writes (`shapeTableId(shape.schema, table)`):
1142
- // for ephemeral the engine passes no schema (→ `public`), exactly this `objectSchema`.
1143
- const syncedTableNameRaw = baseProjection(entry, tableKey).syncedTable ?? tableKey;
1144
- statements.push(buildClearShapeTagsSql(shapeTableId(objectSchema, syncedTableNameRaw)));
1145
-
1146
1137
  return `${statements.join("\n")}\n`;
1147
1138
  }
package/src/sync/apply.ts CHANGED
@@ -1,23 +1,22 @@
1
1
  // Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).
2
2
  // Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
3
- import type { ChangeMessage, Row } from "@electric-sql/client";
4
3
  import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
5
4
  import { and, eq, fillPlaceholders, type SQL, sql } from "drizzle-orm";
6
5
  import { getTableConfig, type PgColumn } from "drizzle-orm/pg-core";
7
6
 
8
- import { quoteIdentifier, type SyncColumnType } from "@pgxsinkit/contracts";
7
+ import { quoteIdentifier, type SyncChange, type SyncColumnType, type SyncRow } from "@pgxsinkit/contracts";
9
8
 
10
9
  import type { ApplyTarget } from "../local-tables";
11
10
  import { generateCopyData } from "./copy";
12
11
  import { drizzleOverPg } from "./drizzle-executor";
13
- import type { InsertChangeMessage } from "./types";
12
+ import type { UpsertChangeMessage } from "./types";
14
13
 
15
14
  /**
16
- * Re-key an Electric change row (keyed by DB **column name**) to the Drizzle **property keys** the
15
+ * Re-key a streamed change row (keyed by DB **column name**) to the Drizzle **property keys** the
17
16
  * query builder addresses columns by (ADR-0029 D1). A column absent from the local projected table is a
18
17
  * config error and surfaces, rather than silently binding to nothing.
19
18
  */
20
- function toDriverRow(target: ApplyTarget, data: Row<unknown>): Record<string, unknown> {
19
+ function toDriverRow(target: ApplyTarget, data: SyncRow): Record<string, unknown> {
21
20
  const out: Record<string, unknown> = {};
22
21
  for (const name of Object.keys(data)) {
23
22
  const propertyKey = target.propertyKeyByName[name];
@@ -89,7 +88,7 @@ function castTypeFor(column: SyncColumnType, tableSchema: string | undefined): s
89
88
  export interface ApplyMessageToTableOptions {
90
89
  pg: PGliteInterface | Transaction;
91
90
  target: ApplyTarget;
92
- message: ChangeMessage<Row<unknown>>;
91
+ message: SyncChange;
93
92
  debug: boolean;
94
93
  }
95
94
 
@@ -98,39 +97,18 @@ export async function applyMessageToTable({ pg, target, message, debug }: ApplyM
98
97
  const db = drizzleOverPg(pg);
99
98
 
100
99
  switch (message.headers.operation) {
101
- case "insert": {
102
- if (debug) console.log("inserting", data);
100
+ case "upsert": {
101
+ if (debug) console.log("upserting", data);
103
102
  const columns = Object.keys(data);
103
+ // `insertInto` adds OVERRIDING SYSTEM VALUE when the row carries a GENERATED ALWAYS identity
104
+ // column, so the server's authoritative id is preserved rather than silently dropped.
104
105
  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 });
106
+ const { conflictTarget, conflictSet, nonPkColumns } = upsertConflictSpec(target, columns);
107
+ if (nonPkColumns.length > 0) {
108
+ return await insert.onConflictDoUpdate({ target: conflictTarget, set: conflictSet as never });
115
109
  }
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;
122
- }
123
-
124
- case "update": {
125
- if (debug) console.log("updating", data);
126
- const setColumns = Object.keys(data).filter((column) => !target.primaryKey.includes(column));
127
- if (setColumns.length === 0) return;
128
- const setValues: Record<string, unknown> = {};
129
- for (const column of setColumns) setValues[target.propertyKeyByName[column]!] = data[column];
130
- return await db
131
- .update(target.table)
132
- .set(setValues as never)
133
- .where(and(...target.primaryKey.map((column) => eq(targetColumn(target, column), data[column]))));
110
+ // Target the pk explicitly so a pk-only conflict is a no-op ONLY on the primary key.
111
+ return await insert.onConflictDoNothing({ target: conflictTarget });
134
112
  }
135
113
 
136
114
  case "delete": {
@@ -145,7 +123,7 @@ export async function applyMessageToTable({ pg, target, message, debug }: ApplyM
145
123
  export interface BulkApplyMessagesToTableOptions {
146
124
  pg: PGliteInterface | Transaction;
147
125
  target: ApplyTarget;
148
- messages: InsertChangeMessage[];
126
+ messages: UpsertChangeMessage[];
149
127
  debug: boolean;
150
128
  }
151
129
 
@@ -189,7 +167,7 @@ async function executeInsertBatch(
189
167
  db: ReturnType<typeof drizzleOverPg>,
190
168
  target: ApplyTarget,
191
169
  colNames: string[],
192
- batch: Row<unknown>[],
170
+ batch: SyncRow[],
193
171
  ): Promise<void> {
194
172
  const rendered = renderInsert(db, target, colNames, batch.length);
195
173
  const values: Record<string, unknown> = {};
@@ -237,7 +215,7 @@ function getValueSize(value: unknown): number {
237
215
  }
238
216
  }
239
217
 
240
- function getRowSize(row: Row<unknown>, columns: readonly string[]): number {
218
+ function getRowSize(row: SyncRow, columns: readonly string[]): number {
241
219
  return columns.reduce((size, column) => {
242
220
  const value = row[column];
243
221
  if (value === null) return size;
@@ -266,7 +244,7 @@ function getRowSize(row: Row<unknown>, columns: readonly string[]): number {
266
244
  }
267
245
 
268
246
  export async function applyInsertsToTable({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {
269
- const data: Row<unknown>[] = messages.map((message) => message.value);
247
+ const data: SyncRow[] = messages.map((message) => message.value);
270
248
  const firstRow = data[0];
271
249
  if (!firstRow) {
272
250
  return;
@@ -274,9 +252,10 @@ export async function applyInsertsToTable({ pg, target, messages, debug }: BulkA
274
252
 
275
253
  if (debug) console.log("inserting", data);
276
254
  const columns = Object.keys(firstRow);
255
+ assertUniformColumnSet(target, columns, data, "applyInsertsToTable");
277
256
  const db = drizzleOverPg(pg);
278
257
 
279
- let currentBatch: Row<unknown>[] = [];
258
+ let currentBatch: SyncRow[] = [];
280
259
  let currentBatchSize = 0;
281
260
  let currentBatchParams = 0;
282
261
 
@@ -336,23 +315,56 @@ function upsertConflictSpec(
336
315
  }
337
316
 
338
317
  /**
339
- * Bulk **upsert** for tagged-subquery move-in rows (ADR-0024). A move-in is an existing row ENTERING the
340
- * shape — unlike a CDC `insert` (a brand-new row) it may already be present locally via an independent
341
- * grant, or be re-delivered on a resume from before the move-in's offset. So it is applied idempotently:
342
- * `INSERT … ON CONFLICT (pk) DO UPDATE` refreshes to the move-in's authoritative value (or `DO NOTHING`
343
- * for a pk-only table). The plain-`INSERT` invariant of the CDC path — a genuine PK collision must
344
- * surface ({@link applyInsertsToTable}) — is intentionally NOT used here, because for a move-in a present
345
- * row is expected, not a bug. Batched by parameter count (move-in volume is incremental, not a backfill).
318
+ * Refuse a batch whose rows do not all carry the same columns.
319
+ *
320
+ * **Every** bulk applier here takes its column list from the FIRST row and binds the rest against it,
321
+ * so a batch with mixed column sets does not fail — it writes the wrong thing, differently per tier: a
322
+ * missing column binds `DEFAULT` on the param-bound paths (overwriting a real value with the column
323
+ * default on conflict) and NULL through `json_to_recordset`, while an extra column is silently dropped
324
+ * everywhere. So all four call sites assert, including the three backfill tiers — a corrupt initial
325
+ * load is the worse outcome of the two, not the lesser one.
326
+ *
327
+ * The wire makes a mixed batch impossible: `row_to_json_cols(row, out_cols)` emits every column of the
328
+ * shape's `out_cols` on every upsert, and `out_cols` is the local table's column set. This is a cheap
329
+ * check that the guarantee still holds, kept because ADR-0058 retired the primary-key collision that
330
+ * used to be the backstop for "the apply path silently wrote something wrong". O(rows × columns),
331
+ * against per-row serialization of the same order — nothing measurable next to the work it guards.
332
+ */
333
+ function assertUniformColumnSet(target: ApplyTarget, columns: string[], rows: SyncRow[], applier: string): void {
334
+ const expected = new Set(columns);
335
+ for (const row of rows) {
336
+ const keys = Object.keys(row);
337
+ if (keys.length === expected.size && keys.every((key) => expected.has(key))) continue;
338
+ const missing = columns.filter((column) => !(column in row));
339
+ const extra = keys.filter((key) => !expected.has(key));
340
+ throw new Error(
341
+ `[pgxsinkit] ${applier}: batch for ${getTableConfig(target.table).name} ` +
342
+ `mixes column sets — every row must carry the same columns as the first ` +
343
+ `(${columns.join(", ")})${missing.length > 0 ? `; missing ${missing.join(", ")}` : ""}` +
344
+ `${extra.length > 0 ? `; unexpected ${extra.join(", ")}` : ""}`,
345
+ );
346
+ }
347
+ }
348
+
349
+ /**
350
+ * Bulk **upsert** — the applier for the wire's `upsert` verb (ADR-0058 decision 1). The engine states a
351
+ * row's new value rather than claiming anything about what preceded it, so an upsert routinely names a
352
+ * row already present locally: a subquery flip, a scope grant, a backfill replay, or a re-delivery on a
353
+ * resume from before its offset. So it is applied idempotently: `INSERT … ON CONFLICT (pk) DO UPDATE`
354
+ * refreshes to the authoritative value (or `DO NOTHING` for a pk-only table). The plain `INSERT` of the
355
+ * backfill path ({@link applyInsertsToTable}) is intentionally NOT used here, because a present row is
356
+ * expected, not a bug. Batched by parameter count (steady-state volume is incremental, not a backfill).
346
357
  */
347
358
  export async function applyUpsertsToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {
348
359
  const primaryKey = target.primaryKey;
349
360
  if (primaryKey.length === 0) throw new Error("applyUpsertsToTable requires a primary key");
350
361
 
351
- const data: Row<unknown>[] = messages.map((message) => message.value);
362
+ const data: SyncRow[] = messages.map((message) => message.value);
352
363
  const firstRow = data[0];
353
364
  if (!firstRow) return;
354
365
 
355
366
  const columns = Object.keys(firstRow);
367
+ assertUniformColumnSet(target, columns, data, "applyUpsertsToTable");
356
368
  const { conflictTarget, conflictSet, nonPkColumns } = upsertConflictSpec(target, columns);
357
369
 
358
370
  const perRow = columns.length;
@@ -388,7 +400,7 @@ interface JsonRecordsetColumn {
388
400
  * catalog probe: the types are always present, derived from the same Drizzle definitions the local
389
401
  * store was rendered from).
390
402
  */
391
- function jsonRecordsetColumns(target: ApplyTarget, firstRow: Row<unknown>): JsonRecordsetColumn[] {
403
+ function jsonRecordsetColumns(target: ApplyTarget, firstRow: SyncRow): JsonRecordsetColumn[] {
392
404
  const present = (name: string) => Object.prototype.hasOwnProperty.call(firstRow, name);
393
405
  const { schema } = getTableConfig(target.table);
394
406
  return target.columnTypes
@@ -434,12 +446,18 @@ async function applyMessagesToTableWithJsonImpl(
434
446
  ) {
435
447
  if (debug) console.log(`applying messages with json_to_recordset${conflict ? " (upsert)" : ""}`);
436
448
 
437
- const data: Row<unknown>[] = messages.map((message) => message.value);
449
+ const data: SyncRow[] = messages.map((message) => message.value);
438
450
  const firstRow = data[0];
439
451
  if (!firstRow) {
440
452
  return;
441
453
  }
442
454
  const columns = jsonRecordsetColumns(target, firstRow);
455
+ assertUniformColumnSet(
456
+ target,
457
+ columns.map((column) => column.name),
458
+ data,
459
+ "applyMessagesToTableWithJson",
460
+ );
443
461
  const targetTable = target.table;
444
462
  // Tier ② (ADR-0028): the target table is an interpolated table object and the batch is a single bound
445
463
  // param (`sql.param` binds the raw JS array unchanged, exactly as the old `[batch]` did — critically,
@@ -508,12 +526,13 @@ function copyColumnUdts(target: ApplyTarget): Record<string, string> {
508
526
  export async function applyMessagesToTableWithCopy({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {
509
527
  if (debug) console.log("applying messages with COPY");
510
528
 
511
- const data: Row<unknown>[] = messages.map((message) => message.value);
529
+ const data: SyncRow[] = messages.map((message) => message.value);
512
530
  const firstRow = data[0];
513
531
  if (!firstRow) {
514
532
  return;
515
533
  }
516
534
  const columns = Object.keys(firstRow);
535
+ assertUniformColumnSet(target, columns, data, "applyMessagesToTableWithCopy");
517
536
 
518
537
  // Serialize rows using Postgres' own COPY TEXT format — a faithful port of the backend's
519
538
  // CopyAttributeOutText / array_out routines (see ./copy) — so arrays (incl. multi-dimensional),
@@ -569,7 +588,7 @@ export interface BulkKeyedApplyOptions {
569
588
  pg: PGliteInterface | Transaction;
570
589
  target: ApplyTarget;
571
590
  /** Folded messages: for deletes the value carries the PK; for updates the PK plus merged columns. */
572
- messages: ChangeMessage<Row<unknown>>[];
591
+ messages: SyncChange[];
573
592
  debug: boolean;
574
593
  }
575
594
 
@@ -609,60 +628,3 @@ export async function applyBulkDeletesToTable({ pg, target, messages, debug }: B
609
628
 
610
629
  if (debug) console.log(`Deleted ${messages.length} rows using json_to_recordset`);
611
630
  }
612
-
613
- /**
614
- * Bulk UPDATE via `UPDATE … FROM json_to_recordset(…)` (ADR-0014 Phase 3), **grouped by the set of
615
- * non-PK columns** each row carries. Electric's default replica sends only the changed columns, so
616
- * two rows in one batch can set different columns; one `UPDATE … FROM` per distinct column-set keeps
617
- * each statement uniform. Safe from the same-PK join hazard because the fold already left one row per
618
- * PK, so no PK appears twice within a group.
619
- */
620
- export async function applyBulkUpdatesToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {
621
- const primaryKey = target.primaryKey;
622
- if (primaryKey.length === 0) throw new Error("applyBulkUpdatesToTable requires a primary key");
623
- if (messages.length === 0) return;
624
-
625
- const pkSet = new Set(primaryKey);
626
- const groups = new Map<string, { setColumns: string[]; rows: Row<unknown>[] }>();
627
- for (const message of messages) {
628
- const data = message.value;
629
- const setColumns = Object.keys(data)
630
- .filter((column) => !pkSet.has(column))
631
- .sort();
632
- // A PK-only update sets nothing — the per-row applyMessageToTable returns early on this too.
633
- if (setColumns.length === 0) continue;
634
- const groupKey = setColumns.join(" ");
635
- let group = groups.get(groupKey);
636
- if (!group) {
637
- group = { setColumns, rows: [] };
638
- groups.set(groupKey, group);
639
- }
640
- group.rows.push(Object.fromEntries([...primaryKey, ...setColumns].map((column) => [column, data[column]])));
641
- }
642
-
643
- const targetTable = target.table;
644
- const db = drizzleOverPg(pg);
645
-
646
- for (const { setColumns, rows } of groups.values()) {
647
- const casts = recordsetColumnCasts(target, [...primaryKey, ...setColumns]);
648
- const recordDef = casts.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(", ");
649
- const setClause = setColumns
650
- .map((column) => `${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)
651
- .join(", ");
652
- const whereJoin = primaryKey
653
- .map((column) => `t.${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)
654
- .join(" AND ");
655
-
656
- for (let i = 0; i < rows.length; i += JSON_RECORDSET_BATCH) {
657
- const batch = rows.slice(i, i + JSON_RECORDSET_BATCH);
658
- // Tier ② (ADR-0028), as applyBulkDeletesToTable above: interpolated target table + single bound
659
- // `sql.param` batch (raw array, not `JSON.stringify` — bigint-safe), no cast needed; the `SET` /
660
- // `x(col type, …)` record def and the alias-qualified `t.*`/`x.*` join stay raw text (grammar).
661
- await db.execute(
662
- sql`UPDATE ${targetTable} AS t SET ${sql.raw(setClause)} FROM json_to_recordset(${sql.param(batch)}) AS x(${sql.raw(recordDef)}) WHERE ${sql.raw(whereJoin)}`,
663
- );
664
- }
665
- }
666
-
667
- if (debug) console.log(`Updated ${messages.length} rows using json_to_recordset`);
668
- }
package/src/sync/copy.ts CHANGED
@@ -5,14 +5,14 @@
5
5
  * Serialization of JavaScript values into a PostgreSQL `COPY ... WITH (FORMAT
6
6
  * text)` stream.
7
7
  *
8
- * The Electric client parses the wire values it receives into native JS values
9
- * before they reach this module: `int2`/`int4`/`float4`/`float8` become
10
- * `number`, `int8` becomes `bigint`, `bool` becomes `boolean`, `json`/`jsonb`
11
- * become parsed objects/arrays, array columns become (possibly nested) JS
12
- * arrays, and every other type is left as its raw Postgres text representation
13
- * (a `string`). To feed those values back into `COPY` we have to reverse that:
14
- * turn each value into the exact text Postgres' input functions expect, then
15
- * apply the COPY framing.
8
+ * Values reach this module already decoded — the read path hands the applier
9
+ * JSON cell values, never Postgres wire text — so the runtime types it accepts
10
+ * are the decoded ones: `int2`/`int4`/`float4`/`float8` as `number`, `bool` as
11
+ * `boolean`, `json`/`jsonb` as parsed objects/arrays, array columns as
12
+ * (possibly nested) JS arrays, `int8` as `bigint`, and every other type as its
13
+ * raw Postgres text representation (a `string`). To feed those values back into
14
+ * `COPY` we have to reverse that: turn each value into the exact text Postgres'
15
+ * input functions expect, then apply the COPY framing.
16
16
  *
17
17
  * Rather than invent an escaping scheme (the previous CSV-based approach broke
18
18
  * on arrays, JSON, embedded delimiters, etc.) this is a faithful port of the
@@ -53,8 +53,8 @@ function escapeCopyText(value: string): string {
53
53
 
54
54
  /**
55
55
  * Convert a Uint8Array to Postgres `bytea` hex-format text (`\xDEADBEEF`).
56
- * Electric normally delivers `bytea` already as such a string, so this only
57
- * matters for callers using a custom parser that yields binary.
56
+ * The read path normally delivers `bytea` already as such a string, so this only
57
+ * matters for a caller whose decoder yields binary.
58
58
  */
59
59
  function byteaToText(bytes: Uint8Array): string {
60
60
  let hex = "";
@@ -107,8 +107,8 @@ function arrayToText(arr: ReadonlyArray<unknown>): string {
107
107
 
108
108
  /**
109
109
  * Convert a non-null JS value to its bare Postgres text representation (before
110
- * COPY field escaping is applied). Dispatch is on the runtime type produced by
111
- * the Electric parser. `json`/`jsonb` columns are handled ahead of this by
110
+ * COPY field escaping is applied). Dispatch is on the value's decoded runtime
111
+ * type. `json`/`jsonb` columns are handled ahead of this by
112
112
  * `serializeCopyValue` when a column type is known; reaching the object branch
113
113
  * here is the type-less fallback.
114
114
  */
@@ -135,7 +135,7 @@ function valueToText(value: unknown): string {
135
135
  return JSON.stringify(value);
136
136
  }
137
137
  default:
138
- // Should be unreachable for Electric-parsed values; be defensive.
138
+ // Should be unreachable for decoded wire values; be defensive.
139
139
  return String(value);
140
140
  }
141
141
  }
@@ -152,8 +152,8 @@ function jsonArrayToText(arr: ReadonlyArray<unknown>): string {
152
152
  }
153
153
 
154
154
  /**
155
- * Re-serialize a parsed `json`/`jsonb` value to its JSON text form. Electric
156
- * delivers these columns already run through `JSON.parse`, so the value is the
155
+ * Re-serialize a parsed `json`/`jsonb` value to its JSON text form. These columns
156
+ * arrive already run through `JSON.parse`, so the value is the
157
157
  * decoded JS value (object, array, string, number, boolean or null) and always
158
158
  * needs `JSON.stringify` to become valid JSON input again — including scalars
159
159
  * (the string `hi` must be written as `"hi"`).
@@ -0,0 +1,94 @@
1
+ import type { SyncChange, SyncRow } from "@pgxsinkit/contracts";
2
+
3
+ import type { UpsertChangeMessage } from "./types";
4
+
5
+ /**
6
+ * A drained shape batch folded to **one net operation per primary key** (ADR-0014 decision 1).
7
+ * Each PK appears in at most one of `deletes`/`upserts` — except a *re-created* PK
8
+ * (`[delete, … , upsert]`), which appears in both so the pre-existing row is cleared before the new
9
+ * one lands. The Sync applier therefore runs two bulk statements **in the order `deletes → upserts`**:
10
+ * that ordering is what makes a re-create drop local-only column state instead of inheriting it, and
11
+ * every other PK is touched by exactly one statement.
12
+ */
13
+ export interface FoldedShapeBatch {
14
+ /** PKs to delete — net-`delete` keys, plus the clearing delete of each re-created key. */
15
+ deletes: SyncChange[];
16
+ /** Full rows to upsert — net-`upsert` keys, plus each re-created key's new row. */
17
+ upserts: UpsertChangeMessage[];
18
+ }
19
+
20
+ /** Clone a representative message, overriding its row value (headers like LSN are kept). */
21
+ function withValue(template: SyncChange, value: SyncRow): UpsertChangeMessage {
22
+ return { ...template, value, headers: { ...template.headers, operation: "upsert" } };
23
+ }
24
+
25
+ /**
26
+ * Collapse an ordered run of upserts to its net row.
27
+ *
28
+ * Every engine upsert carries the complete projected row, so this degenerates to "the last one
29
+ * wins" — the merge is kept rather than a bare `at(-1)` because it stays correct if a future engine
30
+ * ever narrows an upsert to its changed columns, and costs nothing at this batch size.
31
+ */
32
+ function mergeValues(segment: SyncChange[]): SyncRow {
33
+ return Object.assign({}, ...segment.map((message) => message.value)) as SyncRow;
34
+ }
35
+
36
+ /**
37
+ * Fold a drained shape batch (ordered by LSN, one shape) to one net operation per primary key
38
+ * (ADR-0014 decision 1), so the read path can bulk-apply without the `INSERT … SELECT
39
+ * json_to_recordset(…)` same-PK join hazard (which uses **one arbitrary** matching row when the
40
+ * source holds duplicate PKs). Each PK's ops are replayed in stream order down to:
41
+ *
42
+ * - **trailing `delete`** ⇒ a single DELETE;
43
+ * - **upserts, no preceding delete** ⇒ a single UPSERT of the net row;
44
+ * - **re-created** (`[delete, … , upsert, …]`, no trailing delete) ⇒ DELETE **and** UPSERT.
45
+ *
46
+ * The clearing DELETE on a re-create is not redundant against an upsert. `ON CONFLICT DO UPDATE`
47
+ * refreshes only the columns the shape projects; a row that genuinely left and re-entered must not
48
+ * keep local-only column values from its previous life, so it is removed first.
49
+ *
50
+ * There is no `updates` bucket and no malformed-batch case, because there is no third verb: the
51
+ * engine emits `upsert | delete` and nothing else ({@link SyncOperation}). The old
52
+ * "update after delete ⇒ throw" guard checked for a stream state the vocabulary can no longer
53
+ * express.
54
+ *
55
+ * Pure and dependency-free by design (ADR-0014 / ISS-06): property-tested against the oracle
56
+ * *fold-then-bulk ≡ ordered per-row apply* over random same-PK sequences and random initial state.
57
+ */
58
+ export function foldChangeBatch(messages: SyncChange[]): FoldedShapeBatch {
59
+ const groups = new Map<string, SyncChange[]>();
60
+ for (const message of messages) {
61
+ let group = groups.get(message.key);
62
+ if (!group) {
63
+ group = [];
64
+ groups.set(message.key, group);
65
+ }
66
+ group.push(message);
67
+ }
68
+
69
+ const folded: FoldedShapeBatch = { deletes: [], upserts: [] };
70
+ for (const ops of groups.values()) {
71
+ foldKey(ops, folded);
72
+ }
73
+ return folded;
74
+ }
75
+
76
+ function foldKey(ops: SyncChange[], folded: FoldedShapeBatch): void {
77
+ const lastDeleteIndex = ops.findLastIndex((message) => message.headers.operation === "delete");
78
+
79
+ // A trailing delete is the net effect regardless of anything before it; emit one DELETE.
80
+ if (lastDeleteIndex === ops.length - 1) {
81
+ folded.deletes.push(ops[lastDeleteIndex]!);
82
+ return;
83
+ }
84
+
85
+ // The net is decided by the segment after the last delete (or the whole sequence if none), which
86
+ // is all upserts — a delete would have been the last delete.
87
+ const segment = ops.slice(lastDeleteIndex + 1);
88
+
89
+ if (lastDeleteIndex >= 0) {
90
+ // Re-created: clear the pre-existing row, then land the new one (DELETE before UPSERT).
91
+ folded.deletes.push(ops[lastDeleteIndex]!);
92
+ }
93
+ folded.upserts.push(withValue(segment[segment.length - 1]!, mergeValues(segment)));
94
+ }
@@ -2,6 +2,43 @@ import { index, jsonb, pgSchema, primaryKey, text } from "drizzle-orm/pg-core";
2
2
 
3
3
  import type { ShapeSubscriptionState } from "./subscription-state";
4
4
 
5
+ /**
6
+ * The pgxsinkit-owned metadata schema (ADR-0009 decision 6) — where the subscription cursor and the
7
+ * sync-origin GUC live. Ours, not the sync substrate's, which is why it is not named after one.
8
+ *
9
+ * The sync engine defaults its `metadataSchema` to this and `createSyncClient` never overrides it, so
10
+ * paths outside the engine can address the same relations by this constant.
11
+ */
12
+ export const DEFAULT_METADATA_SCHEMA = "pgxsinkit";
13
+
14
+ /**
15
+ * A bare, lowercase, unqualified SQL identifier: begins with a lowercase letter or underscore, then
16
+ * lowercase letters, digits, and underscores.
17
+ */
18
+ const METADATA_SCHEMA_PATTERN = /^[a-z_][a-z0-9_]*$/;
19
+
20
+ /**
21
+ * Validate the metadata schema name at engine construction. The name is interpolated RAW into two
22
+ * positions a double-quoted identifier cannot cover:
23
+ * - GUC space — `SET LOCAL <schema>.syncing` (sync/index.ts) and `SET <schema>.syncing = false`
24
+ * (the metadata migration). GUC grammar takes a `namespace.name` of bare identifiers; it does not
25
+ * accept a quoted identifier the way a table/column position does, so the name cannot be safely
26
+ * quoted there.
27
+ * - the `CREATE SCHEMA <schema>` DDL identifier position.
28
+ * Rather than trust arbitrary caller input in those raw positions, restrict the name to a bare
29
+ * lowercase identifier and reject uppercase/exotic names outright. The default "pgxsinkit" passes.
30
+ */
31
+ export function assertValidMetadataSchema(metadataSchema: string): void {
32
+ if (!METADATA_SCHEMA_PATTERN.test(metadataSchema)) {
33
+ throw new Error(
34
+ `Invalid metadataSchema ${JSON.stringify(metadataSchema)}: it must be a bare lowercase SQL ` +
35
+ `identifier matching ${String(METADATA_SCHEMA_PATTERN)}. The name is interpolated unquoted into ` +
36
+ `GUC (\`SET <schema>.syncing\`) and \`CREATE SCHEMA\` identifier positions where a quoted ` +
37
+ `identifier is not accepted, so uppercase and exotic names are rejected at construction.`,
38
+ );
39
+ }
40
+ }
41
+
5
42
  /**
6
43
  * The two metadata-store relations the sync engine provisions at boot (ADR-0028 decision 4). The
7
44
  * metadata schema name is dynamic (per-client config) but fixed at engine construction, so the tables
@@ -21,7 +58,11 @@ import type { ShapeSubscriptionState } from "./subscription-state";
21
58
  export interface MetadataTables {
22
59
  /** `<schema>.subscriptions_metadata` — one row per subscription key. */
23
60
  readonly subscriptionsMetadata: ReturnType<typeof buildSubscriptionsMetadata>;
24
- /** `<schema>.shape_row_tags` — the tagged-subquery reason-set store (ADR-0023). */
61
+ /**
62
+ * `<schema>.shape_row_tags` — the tagged-subquery reason-set store (ADR-0023), whose mechanism
63
+ * ADR-0057 retired. Still provisioned by `migrateSubscriptionMetadataTables`; nothing reads or
64
+ * writes it on the native path.
65
+ */
25
66
  readonly shapeRowTags: ReturnType<typeof buildShapeRowTags>;
26
67
  }
27
68
 
@@ -1,10 +1,9 @@
1
1
  // Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).
2
2
  // Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
3
- import type { Offset } from "@electric-sql/client";
4
3
  import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
5
4
  import { eq } from "drizzle-orm";
6
5
 
7
- import { quoteIdentifier } from "@pgxsinkit/contracts";
6
+ import { quoteIdentifier, type PredicateValue } from "@pgxsinkit/contracts";
8
7
 
9
8
  import { renderCreateTableSql } from "../schema";
10
9
  import { drizzleOverPg } from "./drizzle-executor";
@@ -19,7 +18,26 @@ export interface SubscriptionState {
19
18
 
20
19
  export interface ShapeSubscriptionState {
21
20
  handle: string;
22
- offset: Offset;
21
+ /** Opaque, per-stream, lexicographically ordered. Never compared across streams. */
22
+ offset: string;
23
+ /**
24
+ * The registry shape this entry is a reader of.
25
+ *
26
+ * Persisted so a later subscribe can say what a stored entry WAS, not merely that it exists. The
27
+ * map key is a logical shape name the client mints (shape key plus scope), which is enough to match
28
+ * an entry against a fresh grant but carries no way back to the registry — and the reconcile at
29
+ * subscribe (ADR-0055 decision 6) needs exactly that: a scope the control plane no longer grants has
30
+ * to be resolved to its spec before its rows can be cleared.
31
+ */
32
+ shapeKey: string;
33
+ /**
34
+ * Shared tier only: the scope values this reader's grant named, in the shape's declared column
35
+ * order. Absent for the private tier, whose subject arrives in the claims instead.
36
+ *
37
+ * `readonly` because a persisted tuple is a record of what was granted, never something to edit —
38
+ * which also lets a grant's own `readonly PredicateValue[]` be stored without a defensive copy.
39
+ */
40
+ scope?: readonly PredicateValue[];
23
41
  }
24
42
 
25
43
  export interface GetSubscriptionStateOptions {