@pgxsinkit/contracts 0.2.6 → 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.
package/src/registry.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ColumnBuilderBase, InferInsertModel, InferSelectModel } from "drizzle-orm";
1
+ import type { AnyColumn, ColumnBuilderBase, InferInsertModel, InferSelectModel } from "drizzle-orm";
2
2
  import {
3
3
  bigint,
4
4
  getTableConfig,
@@ -33,6 +33,8 @@ import {
33
33
  isStorageDurability,
34
34
  isSubscriptionTiming,
35
35
  isWriteMode,
36
+ assertShapeFilterIsEnforceable,
37
+ readShapeTier,
36
38
  RETENTIONS,
37
39
  STORAGE_BACKENDS,
38
40
  STORAGE_DURABILITIES,
@@ -64,6 +66,7 @@ import {
64
66
  isZodSchema,
65
67
  type EventStreamRegistry,
66
68
  } from "./event-stream";
69
+ import type { Predicate } from "./predicate";
67
70
 
68
71
  type PgSchemaType = ReturnType<typeof pgSchema>;
69
72
 
@@ -133,12 +136,19 @@ export interface SyncTableEntry<TTable extends AnyPgTable = AnyPgTable, TLocalTa
133
136
  mode: TableMode;
134
137
  primaryKey: PrimaryKeySpec;
135
138
  /**
136
- * CDC insert-apply policy (ADR-0045). Default `"insert"`: a server CDC `insert` is applied as a plain
137
- * INSERT, so a genuine primary-key collision surfaces (the ADR-0014 collision-surfacing invariant).
138
- * `"upsert"`: this table legitimately receives locally-derived provisional rows (e.g. written by a
139
- * local trigger from another synced table), so server CDC inserts are applied idempotently as
140
- * `INSERT … ON CONFLICT (pk) DO UPDATE` — the authoritative server row overwrites the provisional
141
- * local row instead of failing the commit. Resolved to `"insert"` when omitted.
139
+ * **Backfill** conflict policy (ADR-0045). Resolved to `"insert"` when omitted.
140
+ *
141
+ * This no longer selects how steady-state changes apply. The engine emits `upsert`, which states a
142
+ * row's value without claiming it is new, so every streamed change now applies as `INSERT … ON
143
+ * CONFLICT (pk) DO UPDATE` regardless of this setting. ADR-0014's plain-INSERT collision surfacing
144
+ * went with the `insert` verb it depended on.
145
+ *
146
+ * What survives is the **initial load**, which is a different question: a fresh subscription or a
147
+ * post-must-refetch re-snapshot lands on a table assumed empty, which is what lets it use COPY or a
148
+ * plain multi-row INSERT — neither of which can express `ON CONFLICT`. Set `"upsert"` when that
149
+ * assumption does not hold for this table, i.e. it legitimately receives locally-DERIVED provisional
150
+ * rows (e.g. a local trigger on another synced table inserts one here) that a backfill could meet.
151
+ * The backfill then takes the conflict-tolerant applier instead, at the cost of the faster path.
142
152
  */
143
153
  applyMode: "insert" | "upsert";
144
154
  /**
@@ -171,12 +181,12 @@ export interface SyncTableEntry<TTable extends AnyPgTable = AnyPgTable, TLocalTa
171
181
  */
172
182
  conflictPolicy?: ConflictPolicy;
173
183
  /**
174
- * Consistency group (ADR-0009 decision 2). Tables sharing a `consistencyGroup` are synced on one
175
- * `MultiShapeStream` and committed atomically at a shared LSN frontier, so a local reader never
176
- * sees one grouped table advanced past another for the same server transaction. Omitted → the
177
- * table is its own singleton group (independent frontier, no cross-table atomicity — the resolution
178
- * for a table that declares no group). The latency cost (a group advances only as fast as its
179
- * slowest shape) is contained to the tables that opt in.
184
+ * Consistency group (ADR-0009 decision 2). Tables sharing a `consistencyGroup` are synced as one set
185
+ * of streams and committed atomically — held until every stream reports up-to-date, then applied in
186
+ * one transaction (ADR-0056) — so a local reader never sees one grouped table advanced past another
187
+ * for the same server transaction. Omitted → the table is its own singleton group (its own stream, no
188
+ * cross-table atomicity — the resolution for a table that declares no group). The latency cost (a
189
+ * group advances only as fast as its slowest shape) is contained to the tables that opt in.
180
190
  */
181
191
  consistencyGroup?: string;
182
192
  /**
@@ -308,19 +318,41 @@ export type SyncTableInputProjection<
308
318
  /**
309
319
  * A row filter for {@link defineSyncTable}'s `shape`, authored from the table's built, typed columns.
310
320
  * Reference columns through `c(columns.x)` exactly as `extras` does with its `self` argument, so
311
- * `customWhere` builds parameterized Electric `where`s from real, rename-safe column objects instead
321
+ * `customPredicate` builds the shape's predicate from real, rename-safe column objects instead
312
322
  * of hand-written column-name strings.
313
323
  */
314
324
  export type RowFilterInput<TColumns extends Record<string, ColumnBuilderBase>> = (
315
325
  columns: PgBuildExtraConfigColumns<TColumns>,
316
326
  ) => RowFilterSpec;
317
327
 
318
- /** {@link ShapeSpecInput} whose `rowFilter` is authored from the built columns (typed by `TColumns`). */
328
+ /**
329
+ * The scope declaration for a SHARED-tier shape (ADR-0055), authored from the built, typed columns —
330
+ * the columns whose values key the shape family, in the order they parameterize it.
331
+ *
332
+ * Returning real column objects rather than names is what makes the family rename-safe: a renamed
333
+ * column moves the scope with it, where a string would have gone on naming a column that no longer
334
+ * exists and silently produced a predicate over nothing.
335
+ */
336
+ export type ScopeInput<TColumns extends Record<string, ColumnBuilderBase>> = (
337
+ columns: PgBuildExtraConfigColumns<TColumns>,
338
+ ) => readonly AnyColumn[];
339
+
340
+ /**
341
+ * The static, subscriber-independent half of a shape's native predicate, authored from the built,
342
+ * typed columns. Build it with {@link p} — `(c) => p.eq(c.published, true)`.
343
+ */
344
+ export type ShapeWhereInput<TColumns extends Record<string, ColumnBuilderBase>> = (
345
+ columns: PgBuildExtraConfigColumns<TColumns>,
346
+ ) => Predicate;
347
+
348
+ /** {@link ShapeSpecInput} whose callbacks are authored from the built columns (typed by `TColumns`). */
319
349
  export type ShapeSpecInputFor<TColumns extends Record<string, ColumnBuilderBase>> = Omit<
320
350
  ShapeSpecInput,
321
- "rowFilter"
351
+ "rowFilter" | "scope" | "where"
322
352
  > & {
323
353
  rowFilter?: RowFilterInput<TColumns>;
354
+ scope?: ScopeInput<TColumns>;
355
+ where?: ShapeWhereInput<TColumns>;
324
356
  };
325
357
 
326
358
  /**
@@ -364,14 +396,13 @@ export type SyncTableInput<
364
396
  */
365
397
  primaryKey?: string[] | { name: string; columns: string[] };
366
398
  /**
367
- * CDC insert-apply policy (ADR-0045). **Default `"insert"`** — a CDC insert is a plain INSERT, so a
368
- * genuine PK collision must surface (the ADR-0014 collision-surfacing invariant; a synced cache table
369
- * is server-authoritative and a duplicate insert is a real bug). Set `"upsert"` **only** when this
370
- * table legitimately receives locally-DERIVED provisional rows — e.g. a local trigger on another
371
- * synced table inserts a provisional row here, and the server independently creates the same row so
372
- * its CDC insert would collide (23505). With `"upsert"`, server CDC inserts are applied idempotently
373
- * as `INSERT … ON CONFLICT (pk) DO UPDATE`; the authoritative server row overwrites the provisional
374
- * local row. Declare the exception here, where it lives — do not weaken the invariant repo-wide.
399
+ * **Backfill** conflict policy (ADR-0045). **Default `"insert"`** — the initial load assumes an empty
400
+ * table (fresh subscription or post-must-refetch re-snapshot) and takes the fast path, COPY or a plain
401
+ * multi-row INSERT, neither of which can express `ON CONFLICT`. Set `"upsert"` **only** when this table
402
+ * legitimately receives locally-DERIVED provisional rows a backfill could land on top of — e.g. a local
403
+ * trigger on another synced table inserts a provisional row here, and the server independently creates
404
+ * the same row (23505). Steady-state changes are unaffected: the engine emits `upsert`, so they apply
405
+ * as `INSERT … ON CONFLICT (pk) DO UPDATE` for every table. See {@link SyncTableEntry.applyMode}.
375
406
  */
376
407
  applyMode?: "insert" | "upsert";
377
408
  /**
@@ -392,8 +423,8 @@ export type SyncTableInput<
392
423
  */
393
424
  conflictPolicy?: ConflictPolicy;
394
425
  /**
395
- * Bind this table into a consistency group (ADR-0009 decision 2): grouped tables sync on one
396
- * `MultiShapeStream` and commit atomically. Omit for the default singleton group. See
426
+ * Bind this table into a consistency group (ADR-0009 decision 2): grouped tables sync as one set of
427
+ * streams and commit atomically. Omit for the default singleton group. See
397
428
  * {@link SyncTableEntry.consistencyGroup}.
398
429
  */
399
430
  consistencyGroup?: string;
@@ -657,12 +688,13 @@ export function defineSyncTable<
657
688
  const columnLevelPkKeys = Object.entries(probeColumns)
658
689
  .filter(([, col]) => col.primary === true)
659
690
  .map(([key]) => key);
660
- const specPropertyKeys = primaryKeyColumns.map((key) => {
691
+ const toPropertyKey = (key: string, label: string) => {
661
692
  if (probeColumns[key]) return key;
662
693
  const byColumnName = Object.entries(probeColumns).find(([, col]) => col.name === key);
663
694
  if (byColumnName) return byColumnName[0];
664
- throw new Error(`[pgxsinkit] ${tableName}: primaryKey column "${key}" not found among the table's columns`);
665
- });
695
+ throw new Error(`[pgxsinkit] ${tableName}: ${label} column "${key}" not found among the table's columns`);
696
+ };
697
+ const specPropertyKeys = primaryKeyColumns.map((key) => toPropertyKey(key, "primaryKey"));
666
698
 
667
699
  if (columnLevelPkKeys.length > 1) {
668
700
  throw new Error(
@@ -719,25 +751,59 @@ export function defineSyncTable<
719
751
 
720
752
  // Resolve `shape.rowFilter` against the built typed columns so all authoring uses rename-safe
721
753
  // Drizzle column objects rather than hand-written column-name strings.
722
- const resolvedRowFilter = shape?.rowFilter?.(
723
- getColumns(table) as unknown as PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>,
724
- );
754
+ const shapeColumns = getColumns(table) as unknown as PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>;
755
+ const resolvedRowFilter = shape?.rowFilter?.(shapeColumns);
756
+ const resolvedScope = shape?.scope?.(shapeColumns).map((column) => column.name);
757
+ const resolvedWhere = shape?.where?.(shapeColumns);
725
758
  const resolvedShape: ShapeSpec | undefined =
726
759
  resolvedMode !== "writeonly" || shape != null
727
760
  ? {
728
761
  tableName: shape?.tableName ?? tableName,
729
762
  shapeKey: shape?.shapeKey ?? shape?.tableName ?? tableName,
730
- // `electricTable` is never set from input (it is not in ShapeSpecInput) — an owner reads its
763
+ // `physicalTable` is never set from input (it is not in ShapeSpecInput) — an owner reads its
731
764
  // own table. It is filled by `attachSyncRegistrySchema` (schema qualification) or by
732
765
  // `defineReadProjection` (which points a projection at the owning physical table).
733
766
  ...(resolvedRowFilter != null ? { rowFilter: resolvedRowFilter } : {}),
767
+ ...(resolvedScope != null ? { scope: resolvedScope } : {}),
768
+ ...(resolvedWhere != null ? { where: resolvedWhere } : {}),
734
769
  }
735
770
  : undefined;
736
771
 
772
+ // Read the tier for its side effect: a shape declaring both `scope` and `rowFilter` is refused
773
+ // HERE, at definition time, rather than at the first shape creation — the two are contradictory
774
+ // by construction, so there is no input for which it could later turn out to be fine.
775
+ if (resolvedShape != null) {
776
+ readShapeTier(resolvedShape);
777
+ assertShapeFilterIsEnforceable(resolvedShape);
778
+ }
779
+
737
780
  const omittedColumns = (clientProjection?.omitColumns ?? []) as TOmittedColumns;
738
781
  const projectedCols = viewColumnsForProjection(makeColumns(), omittedColumns);
782
+
783
+ // The local synced table carries its OWN primary key, mirroring exactly what the local-schema
784
+ // generator emits for it (`getLocalSyncPrimaryKeyColumns` → `buildTableColumnSql`) — including a
785
+ // `clientProjection.localPrimaryKey` narrowing, where the server's key columns may not even be
786
+ // projected. Stating it here keeps the drizzle object and the physical table in agreement; a
787
+ // localTable that claimed no key while its table had one stayed invisible only while the apply path
788
+ // was a plain INSERT plus `UPDATE … WHERE pk`, and became a 42P10 the moment anything said
789
+ // `ON CONFLICT (pk)` (ADR-0058 decision 3). Skipped when a single column already carries the flag
790
+ // itself, since drizzle would then render two primary keys.
791
+ const localPkPropertyKeys = (clientProjection?.localPrimaryKey?.columns ?? primaryKeyColumns).map((key) =>
792
+ toPropertyKey(key, "localPrimaryKey"),
793
+ );
794
+ const localPkIsColumnLevel =
795
+ localPkPropertyKeys.length === 1 && probeColumns[localPkPropertyKeys[0]!]?.primary === true;
796
+ const localExtrasFn = localPkIsColumnLevel
797
+ ? undefined
798
+ : (self: PgBuildExtraConfigColumns<Record<string, ColumnBuilderBase>>) => {
799
+ const selfCols = self as unknown as Record<string, AnyPgColumn>;
800
+ const pkColumns = localPkPropertyKeys.map((k) => selfCols[k]!) as [AnyPgColumn, ...AnyPgColumn[]];
801
+ return [pgPrimaryKey({ name: primaryKeyConstraintName, columns: pkColumns })];
802
+ };
739
803
  const localTable = (
740
- schema ? schema.table(tableName, projectedCols) : pgTable(tableName, projectedCols)
804
+ schema
805
+ ? schema.table(tableName, projectedCols, localExtrasFn as never)
806
+ : pgTable(tableName, projectedCols, localExtrasFn as never)
741
807
  ) as ProjectedLocalTable<TName, TColumns, TOmittedColumns>;
742
808
 
743
809
  const viewColumns = viewColumnsForProjection(makeColumns(), omittedColumns);
@@ -789,7 +855,7 @@ export function defineSyncTable<
789
855
  * not the jsonb), while the learner keeps reading the full table through the owner's shape.
790
856
  *
791
857
  * It is the *obvious, DRY* way to express "another shape over this table", versus the bare
792
- * `shape.electricTable` string it replaces (a footgun — config that silently un-asserts table
858
+ * `shape.physicalTable` string it replaces (a footgun — config that silently un-asserts table
793
859
  * ownership):
794
860
  *
795
861
  * - **Owns nothing.** The returned entry's `table` IS `owner.table` (the same object), so there is no
@@ -797,17 +863,17 @@ export function defineSyncTable<
797
863
  * and `shape` are its own. `readProjection` is set so generators skip it.
798
864
  * - **DRY columns.** `columns` is a typed subset of the owner's column keys; the local table is built by
799
865
  * filtering the owner's own column definitions (never restated), and the same subset becomes the
800
- * Electric `columns` allow-list so an omitted (e.g. heavy jsonb) column never crosses the wire. The
866
+ * shape's `columns` allow-list so an omitted (e.g. heavy jsonb) column never crosses the wire. The
801
867
  * primary key is always kept. Omit `columns` to sync every column.
802
- * - **Source is derived, never named.** The physical Electric target is taken from the owner — there is
803
- * no consumer-facing source field to get wrong (see {@link ShapeSpec.electricTable}).
804
- * - **Readonly.** A projection has no write path; the engine resolves an incoming shape request by its
805
- * unique `shapeKey` (= `as`) and consults the derived physical target only on egress.
868
+ * - **Source is derived, never named.** The physical source table is taken from the owner — there is
869
+ * no consumer-facing source field to get wrong (see {@link ShapeSpec.physicalTable}).
870
+ * - **Readonly.** A projection has no write path; the control plane resolves an incoming subscription by
871
+ * its unique `shapeKey` (= `as`) and consults the derived physical target when it creates the shape.
806
872
  *
807
- * The `rowFilter` callback receives the OWNER's full columns — `customWhere` runs in Electric against
873
+ * The `rowFilter` callback receives the OWNER's full columns — the predicate is evaluated against
808
874
  * the physical table, so it may reference a column the local subset omits. RLS for the projection's
809
875
  * reads lives on the OWNER's table (a projection adds no DDL to a table it does not own); its
810
- * `customWhere` must be a subset of what that RLS allows.
876
+ * `customPredicate` must be a subset of what that RLS allows.
811
877
  *
812
878
  * The `owner` may be a `defineSyncTable` entry OR an `asReadonly` of one — an `asReadonly` projection
813
879
  * preserves the full read contract (physical table, columns, primary key) and only drops the write path,
@@ -817,15 +883,16 @@ export function defineSyncTable<
817
883
  * ### Server-side egress redaction (`serverProjection` + `serverOnlyColumns`)
818
884
  *
819
885
  * A projection may carry its own `serverProjection` (a {@link ServerProjectionSpec}, typically a
820
- * `rowTransform`) — resolved by the projection's `shapeKey` and run on the proxy egress path for this
821
- * shape only. The order on egress is **transform first, then omission**: the transform runs against the
822
- * fetched row, then column omission strips this projection's omitted columns (the client keep-set is
823
- * `columns ∪ primaryKey`) before the row reaches the client wire. This lets a "secure window" over a
824
- * keyed table stream the body while stripping the keys per row.
886
+ * `rowTransform`) — resolved by the projection's `shapeKey` and run at the STREAM EDGE, per request, for
887
+ * this shape only (ADR-0055 decision 5). The order on egress is **transform first, then omission**: the
888
+ * transform runs against the fetched row, then the edge strips the row to the client keep-set
889
+ * (`columns ∪ primaryKey`) before it reaches the client wire. This lets a "secure window" over a keyed
890
+ * table stream the body while stripping the keys per row. Such a shape is private-tier by construction
891
+ * (its bytes depend on the reader) and is answered `cache-control: private, no-store`.
825
892
  *
826
893
  * `serverOnlyColumns` are owner column keys the transform must READ but that are NOT in the client shape
827
894
  * (e.g. a `keysWithheld` control flag). Such a key stays omitted from the client keep-set, yet is ADDED
828
- * to the Electric fetch allow-list — so it is fetched from Electric, visible to the transform, and then
895
+ * to the shape's `columns` allow-list — so it is fetched, visible to the transform, and then
829
896
  * stripped on egress by the same omission pass, never reaching the client. It requires a
830
897
  * `serverProjection.rowTransform` (a fetch no transform reads is dead weight) AND `columns` (with
831
898
  * `columns` omitted every column is already kept, so "server-only" is a contradiction), and must be
@@ -859,7 +926,7 @@ export function defineReadProjection<
859
926
  opts: {
860
927
  /** The projection's distinct local identity — its PGlite table name AND its `shapeKey`. */
861
928
  as: TAs;
862
- /** Column keys (of the owner) to sync locally + fetch from Electric. The PK is always kept. Omit → all. */
929
+ /** Column keys (of the owner) to sync locally + fetch on the shape. The PK is always kept. Omit → all. */
863
930
  columns?: TColumns;
864
931
  /** Row filter for this shape; the callback form receives the owner's full (physical) columns. */
865
932
  rowFilter?: (columns: TableColumnsShape<TOwnerTable>) => RowFilterSpec;
@@ -879,8 +946,8 @@ export function defineReadProjection<
879
946
  serverProjection?: ServerProjectionSpec | "unredacted";
880
947
  /**
881
948
  * Owner column keys the `serverProjection.rowTransform` must READ but which are NOT part of the client
882
- * shape (e.g. a `keysWithheld` control flag). They are added to the Electric fetch allow-list so the
883
- * transform can see them, then stripped on egress before the client wire. Requires
949
+ * shape (e.g. a `keysWithheld` control flag). They are added to the shape's `columns` allow-list so
950
+ * the transform can see them, then stripped on egress before the client wire. Requires
884
951
  * `serverProjection.rowTransform` and `columns`; must be disjoint from `columns` and the primary key.
885
952
  */
886
953
  serverOnlyColumns?: readonly TableColumnKey<TOwnerTable>[];
@@ -933,9 +1000,9 @@ export function defineReadProjection<
933
1000
  const omittedKeys = allKeys.filter((key) => !keep.has(key));
934
1001
 
935
1002
  // serverOnlyColumns — owner keys the egress rowTransform must READ but that are NOT in the client
936
- // keep-set. They stay omitted client-side (so local DDL/apply exclude them AND the proxy strips them on
937
- // egress), yet are added to the Electric fetch allow-list below so the transform can see them. Each
938
- // guard fails loud: a mis-declared server-only column would silently mis-fetch or fail open.
1003
+ // keep-set. They stay omitted client-side (so local DDL/apply exclude them AND egress strips them on
1004
+ // the way out), yet are added to the shape's `columns` allow-list below so the transform can see them.
1005
+ // Each guard fails loud: a mis-declared server-only column would silently mis-fetch or fail open.
939
1006
  // Fail-closed posture guard. A projection does NOT inherit its owner's egress `serverProjection`
940
1007
  // (see the docblock's no-inheritance caution: an inherited transform whose input column is unfetched
941
1008
  // reads `undefined` and fails OPEN — half-protection worse than none). So if the OWNER redacts on
@@ -994,7 +1061,7 @@ export function defineReadProjection<
994
1061
  if (!allKeys.includes(key)) {
995
1062
  throw new Error(
996
1063
  `defineReadProjection: projection "${opts.as}" serverOnlyColumns names "${key}", which is not a ` +
997
- `column of owner "${physicalTable}". It feeds the Electric fetch allow-list, so a typo would ` +
1064
+ `column of owner "${physicalTable}". It feeds the shape's "columns" allow-list, so a typo would ` +
998
1065
  `silently mis-fetch — name an existing owner column key.`,
999
1066
  );
1000
1067
  }
@@ -1024,15 +1091,18 @@ export function defineReadProjection<
1024
1091
  ...(opts.retention != null ? { retention: opts.retention } : {}),
1025
1092
  });
1026
1093
 
1027
- // Resolve the row filter against the OWNER's full columns (the customWhere runs in Electric on the
1094
+ // Resolve the row filter against the OWNER's full columns (the predicate is evaluated on the
1028
1095
  // physical table, so it may reference a column the subset omits).
1029
1096
  const resolvedRowFilter = opts.rowFilter?.(getColumns(owner.table) as unknown as TableColumnsShape<TOwnerTable>);
1030
1097
 
1031
- // When a subset is requested, set the Electric `columns` allow-list to the KEPT physical column names
1098
+ // When a subset is requested, set the shape's `columns` allow-list to the KEPT physical column names
1032
1099
  // so an omitted (e.g. heavy jsonb) column is never fetched over the wire — not merely stripped after.
1033
1100
  // serverOnlyColumns are added ON TOP of the kept names: a server-only column must be FETCHED (so the
1034
- // egress rowTransform can read it) even though it is omitted from the client keep-set — proxy omission
1035
- // then strips it after the transform runs. Resolve key -> physical name the same way getProjectedColumns
1101
+ // egress rowTransform can read it) even though it is omitted from the client keep-set. It is stripped
1102
+ // after the transform runs, at the STREAM EDGE — `createStreamGate` (packages/server/src/circuits/edge.ts)
1103
+ // rewrites each row of a transform shape's long-poll body and then narrows it to `entry.localTable`'s
1104
+ // columns, which is precisely this keep-set. So the column rides the engine's stream and comes off the
1105
+ // wire one hop before the client. Resolve key -> physical name the same way getProjectedColumns
1036
1106
  // does (the drizzle column's `.name`), never a hand-map. A full-width projection (no omitted keys, hence
1037
1107
  // no serverOnlyColumns — validated above) declares no allow-list at all.
1038
1108
  const ownerColumns = getColumns(owner.table) as Record<string, { name: string }>;
@@ -1051,10 +1121,14 @@ export function defineReadProjection<
1051
1121
  const shape: ShapeSpec = {
1052
1122
  tableName: opts.as,
1053
1123
  shapeKey: opts.as,
1054
- electricTable: physicalTable,
1124
+ physicalTable: physicalTable,
1055
1125
  ...(rowFilter != null ? { rowFilter } : {}),
1056
1126
  };
1057
1127
 
1128
+ // Same definition-time refusal the owning `defineSyncTable` performs: a projection's filter is a
1129
+ // filter, and one that cannot run here is the same unfiltered stream it would be there.
1130
+ assertShapeFilterIsEnforceable(shape);
1131
+
1058
1132
  // Point `table` at the owner's physical table and flag `readProjection` — that flag (not the absence of
1059
1133
  // a column factory) is what generators/appliers key on to skip owning-table work (see plpgsql-apply's
1060
1134
  // `!entry.readProjection` filter). The owner's `makeColumns` is KEPT (it rode in via `built`): since
@@ -1102,6 +1176,7 @@ export function defineSyncRegistry<const TRegistry extends { [TKey in keyof TReg
1102
1176
  validateSyncTableEntry(entry as SyncTableEntry<AnyPgTable>);
1103
1177
  }
1104
1178
  validateRegistryTableUniqueness(input.tables);
1179
+ validateRegistryShapeKeyUniqueness(input.tables);
1105
1180
  validateRegistryLifecycleGroups(input.tables);
1106
1181
  validateStorageDeclaration(input.storage);
1107
1182
  validateRowClassification(input.tables, input.rowClasses);
@@ -1127,6 +1202,7 @@ export function defineSyncRegistry<const TRegistry extends { [TKey in keyof TReg
1127
1202
  validateSyncTableEntry(entry as SyncTableEntry<AnyPgTable>);
1128
1203
  }
1129
1204
  validateRegistryTableUniqueness(input);
1205
+ validateRegistryShapeKeyUniqueness(input);
1130
1206
  validateRegistryLifecycleGroups(input);
1131
1207
 
1132
1208
  return input;
@@ -1145,7 +1221,7 @@ function localShapeIdentity(entry: SyncTableEntry<AnyPgTable>): string {
1145
1221
  * ({@link localShapeIdentity}) — the PGlite table a client reads and the `shapeKey` the proxy resolves a
1146
1222
  * request by — so two entries sharing it would collide locally (one shadows the other) and make the
1147
1223
  * shape unresolvable. A read PROJECTION over a shared physical table does NOT trip this: it carries a
1148
- * DISTINCT local identity (`as`) and points at the owning table via the derived `shape.electricTable`,
1224
+ * DISTINCT local identity (`as`) and points at the owning table via the derived `shape.physicalTable`,
1149
1225
  * so several shapes read one physical table while their local identities stay unique. Fails closed at
1150
1226
  * module-eval, for every consumer.
1151
1227
  */
@@ -1168,9 +1244,43 @@ function validateRegistryTableUniqueness(registry: SyncTableRegistry) {
1168
1244
  }
1169
1245
  }
1170
1246
 
1247
+ /**
1248
+ * A registry must not expose the same PUBLIC `shapeKey` twice. This is a DISTINCT identity from the
1249
+ * local table checked by {@link validateRegistryTableUniqueness}: `shapeKey` is what a subscription
1250
+ * request names on the wire and what the control plane resolves an entry by (`resolveEntryByShapeKey`
1251
+ * is first-match), while the local identity is the PGlite table a client reads into. They coincide by
1252
+ * default (`shapeKey` falls back to `tableName`), so the local check already covers the common case,
1253
+ * and read projections over one physical table stay legal because `as` yields a distinct value for
1254
+ * BOTH identities. The only way to collide here is an EXPLICIT `shape.shapeKey` that diverges from the
1255
+ * table name: two such entries would leave the second permanently unreachable, silently served the
1256
+ * first's shape (and therefore the first's row filter). Write-only entries carry no shape and are
1257
+ * skipped — they are not publicly requestable. Fails closed at module-eval, for every consumer.
1258
+ */
1259
+ function validateRegistryShapeKeyUniqueness(registry: SyncTableRegistry) {
1260
+ const declaredBy = new Map<string, string>();
1261
+
1262
+ for (const [key, entry] of Object.entries(registry)) {
1263
+ const shape = (entry as SyncTableEntry<AnyPgTable>).shape;
1264
+ if (shape === undefined) continue;
1265
+
1266
+ const firstKey = declaredBy.get(shape.shapeKey);
1267
+
1268
+ if (firstKey !== undefined) {
1269
+ throw new Error(
1270
+ `shapeKey "${shape.shapeKey}" is declared by two registry entries ("${firstKey}" and "${key}"): ` +
1271
+ `a duplicate shapeKey makes the second entry unreachable — the control plane resolves a ` +
1272
+ `subscription by shapeKey and would serve the first entry's shape. Give each entry a unique ` +
1273
+ `shape.shapeKey, or use defineReadProjection (a distinct "as") for a second shape over one table.`,
1274
+ );
1275
+ }
1276
+
1277
+ declaredBy.set(shape.shapeKey, key);
1278
+ }
1279
+ }
1280
+
1171
1281
  /**
1172
1282
  * ADR-0021 §4 / ADR-0022 §1–2: subscription timing, retention, and write-mode are properties of a
1173
- * **consistency group**, not a single table — a group commits atomically on one `MultiShapeStream`
1283
+ * **consistency group**, not a single table — a group's streams commit atomically together
1174
1284
  * (so it cannot be partly lazy or partly ephemeral) and a consistency group *is* the static
1175
1285
  * write-unit (so it cannot be partly pessimistic). Reject a registry whose grouped tables disagree on
1176
1286
  * any of the three. Tables without a `consistencyGroup` are their own singleton group and are
@@ -1365,10 +1475,10 @@ export function attachSyncRegistrySchema<TRegistry extends SyncTableRegistry>(re
1365
1475
  const qualifiedTableName = `${normalizedSchema}.${entry.shape.tableName}`;
1366
1476
  entry.shape = {
1367
1477
  ...entry.shape,
1368
- // A read projection sets electricTable to the owner's (bare) physical name; qualify it the same
1478
+ // A read projection sets physicalTable to the owner's (bare) physical name; qualify it the same
1369
1479
  // way the owner's own target is qualified, so both shapes hit one schema-qualified table on egress.
1370
- // An owner (no electricTable) qualifies its own tableName. An already-qualified value is left as-is.
1371
- electricTable: entry.shape.electricTable ? qualify(entry.shape.electricTable) : qualifiedTableName,
1480
+ // An owner (no physicalTable) qualifies its own tableName. An already-qualified value is left as-is.
1481
+ physicalTable: entry.shape.physicalTable ? qualify(entry.shape.physicalTable) : qualifiedTableName,
1372
1482
  ...(entry.shape.shapeKey === entry.shape.tableName ? { shapeKey: qualifiedTableName } : {}),
1373
1483
  };
1374
1484
  }
@@ -1761,6 +1871,24 @@ function validateSyncTableEntry(entry: SyncTableEntry<AnyPgTable>) {
1761
1871
  );
1762
1872
  }
1763
1873
 
1874
+ // ADR-0055 decision 5: an egress `serverProjection.rowTransform` makes the shape's bytes a function
1875
+ // of the SUBJECT — the stream edge rewrites them per request, with the subject from the stream
1876
+ // token — so the shape is private-tier BY CONSTRUCTION and cannot be served from a scope-keyed
1877
+ // shared stream. Letting the two ride together would produce exactly what `readShapeTier` refuses
1878
+ // for `scope` + `rowFilter`: a stream cached under a scope key while carrying subject-dependent
1879
+ // bytes, which is a disclosure rather than a stale row. Checked HERE rather than in `readShapeTier`
1880
+ // because the transform lives on the ENTRY (a projection attaches it after its shape is built), and
1881
+ // this is the one validation every registrable entry passes through, projections included.
1882
+ if (entry.serverProjection?.rowTransform != null && entry.shape?.scope != null) {
1883
+ throw new Error(
1884
+ `[pgxsinkit] shape "${entry.shape.shapeKey}" declares both scope and a serverProjection.rowTransform ` +
1885
+ `— an egress transform rewrites the stream's bytes per request with the reader's subject, so the ` +
1886
+ `shape is private-tier by construction (ADR-0055 decision 5) and cannot be served from a ` +
1887
+ `scope-keyed shared stream. Drop the transform and pre-compute the redaction into a column the ` +
1888
+ `shape projects, or drop scope and keep this shape private.`,
1889
+ );
1890
+ }
1891
+
1764
1892
  // ADR-0010: a writable synced table must declare a Server version — a nowMicroseconds-on-update
1765
1893
  // managed field (conventionally updated_at_us) the applier stamps and keeps strictly monotonic.
1766
1894
  // Optimistic convergence is unsound without a per-row version (the barrier would degenerate to a
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The change envelope carried on every Circuits table and shape stream.
3
+ *
4
+ * Restated rather than imported from `@electric-circuits/protocol`, for the reasons given on
5
+ * {@link Predicate}: this is the wire contract pgxsinkit commits to, the protocol package is alpha,
6
+ * and a published library should not put an alpha peer in its public types. The engine's serde
7
+ * definitions are authoritative; any divergence is a bug here.
8
+ */
9
+
10
+ /** A scalar cell value on the wire. */
11
+ export type StreamValue = string | number | boolean | null;
12
+
13
+ /** A row is a flat map of column name to value. */
14
+ export type StreamRow = Record<string, StreamValue>;
15
+
16
+ /**
17
+ * The engine's **complete** shape-stream vocabulary — two verbs, not four.
18
+ *
19
+ * `insert`/`update` are the *input* side: what the replication ingestor parses out of Postgres. They
20
+ * never reach a shape stream. Every row the engine emits goes out as `upsert` (`output.rs`
21
+ * `translate_output`/`agg_envelope`) and every eviction as key-only `delete`
22
+ * (`translate_output`/`delete_envelopes`) — the engine states the row's new value rather than
23
+ * claiming anything about what preceded it, because a shape row can enter a subscriber's view for
24
+ * reasons that are not a Postgres INSERT (a subquery flip, a scope grant, a backfill replay).
25
+ *
26
+ * Listing the input verbs here as if they might arrive is what produced a dead `"update"` branch in
27
+ * the translator and a comment asserting `upsert` was backfill-only. Both were wrong.
28
+ */
29
+ export type StreamOperation = "upsert" | "delete";
30
+
31
+ export interface StreamEnvelope {
32
+ /** The table name — the collection discriminator. */
33
+ type: string;
34
+ /** The stringified primary key. Composite keys are already joined by the engine. */
35
+ key: string;
36
+ /** Present for insert/update/upsert; **absent for delete**, which is key-only. */
37
+ value?: StreamRow;
38
+ headers: {
39
+ operation: StreamOperation;
40
+ txid?: string;
41
+ /** Stamped by the durable-streams server on read; never sent by a producer. */
42
+ offset?: string;
43
+ /**
44
+ * Postgres commit LSN (`"HI/LO"` hex), stamped by the engine on **live** shape envelopes.
45
+ *
46
+ * **Absent on backfill rows**, and absent in library (no-Postgres) mode. That absence is why
47
+ * ADR-0056 floors catch-up on the stream OFFSET rather than on this: a frontier that only some
48
+ * envelopes can advance is not a frontier.
49
+ */
50
+ lsn?: string;
51
+ /**
52
+ * Position of the change within its transaction, stamped by the replication ingestor on
53
+ * **table**-stream envelopes so the engine's own tailer can skip at-least-once duplicates.
54
+ * **Not present on shape streams**, which is what we read — recorded so nobody builds
55
+ * deduplication on a field that will never arrive.
56
+ */
57
+ seq?: number;
58
+ };
59
+ }
60
+
61
+ /** A delete envelope carries no row body, so an eviction discloses nothing but the key. */
62
+ export function isDeleteEnvelope(envelope: StreamEnvelope): boolean {
63
+ return envelope.headers.operation === "delete";
64
+ }
65
+
66
+ /**
67
+ * One change as the APPLIER consumes it, after an envelope has been resolved against its table.
68
+ *
69
+ * Distinct from {@link StreamEnvelope} on purpose. An envelope is the wire form — key-only on a
70
+ * delete, headers carrying transport metadata. This is what the apply path needs instead: a value
71
+ * that is always present (a delete's is its reconstructed primary key), and the transport metadata
72
+ * dropped.
73
+ *
74
+ * The operation set is {@link StreamOperation}'s, unchanged. The applier used to narrow the wire's
75
+ * four verbs down to three DML verbs; there are only two verbs to carry now, and inventing a DML
76
+ * distinction the engine never made is what the translator got wrong.
77
+ *
78
+ * `value` is `Record<string, unknown>` rather than {@link StreamRow} because the applier handles
79
+ * values the wire never carries — a `bigint` id kept as a string for precision, a JSON column
80
+ * arriving as a parsed object — and narrowing here would only push casts into the codecs.
81
+ */
82
+ export type SyncRow = Record<string, unknown>;
83
+
84
+ export type SyncOperation = StreamOperation;
85
+
86
+ export interface SyncChange<T extends SyncRow = SyncRow> {
87
+ /** The stringified primary key, as the stream named it. */
88
+ key: string;
89
+ value: T;
90
+ headers: { operation: SyncOperation } & Record<string, unknown>;
91
+ }