@pgxsinkit/contracts 0.2.7 → 0.5.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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/dist/apply-strategy.d.ts +13 -1
  3. package/dist/apply-strategy.d.ts.map +1 -1
  4. package/dist/config.d.ts +256 -87
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/convergence-model.d.ts +2 -2
  7. package/dist/convergence-model.d.ts.map +1 -1
  8. package/dist/event-stream.d.ts +1 -1
  9. package/dist/fingerprint.d.ts +31 -11
  10. package/dist/fingerprint.d.ts.map +1 -1
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +480 -202
  14. package/dist/index.js.map +16 -14
  15. package/dist/predicate.d.ts +162 -0
  16. package/dist/predicate.d.ts.map +1 -0
  17. package/dist/projection.d.ts +2 -2
  18. package/dist/projection.d.ts.map +1 -1
  19. package/dist/registry-diff.d.ts.map +1 -1
  20. package/dist/registry-invariant.d.ts +26 -14
  21. package/dist/registry-invariant.d.ts.map +1 -1
  22. package/dist/registry.d.ts +74 -48
  23. package/dist/registry.d.ts.map +1 -1
  24. package/dist/sql-role-guard.d.ts +1 -1
  25. package/dist/stream-envelope.d.ts +84 -0
  26. package/dist/stream-envelope.d.ts.map +1 -0
  27. package/dist/supabase-rls.d.ts +32 -36
  28. package/dist/supabase-rls.d.ts.map +1 -1
  29. package/package.json +3 -2
  30. package/skills/registry-authoring/SKILL.md +185 -185
  31. package/skills/registry-authoring/references/storage-engine-and-build.md +29 -0
  32. package/src/apply-strategy.ts +23 -4
  33. package/src/config.ts +340 -116
  34. package/src/convergence-model.ts +2 -2
  35. package/src/event-stream.ts +1 -1
  36. package/src/fingerprint.ts +76 -14
  37. package/src/index.ts +2 -0
  38. package/src/predicate.ts +274 -0
  39. package/src/projection.ts +6 -2
  40. package/src/registry-diff.ts +15 -4
  41. package/src/registry-invariant.ts +34 -19
  42. package/src/registry.ts +324 -78
  43. package/src/sql-role-guard.ts +1 -1
  44. package/src/stream-envelope.ts +91 -0
  45. package/src/supabase-rls.ts +76 -74
@@ -2,28 +2,28 @@
2
2
  name: registry-authoring
3
3
  description: >-
4
4
  Load when defining or changing a pgxsinkit sync registry with @pgxsinkit/contracts —
5
- defineSyncRegistry / defineSyncTable, sync modes, managed fields, conflict policy, filters, RLS.
6
- Teaches the rules that throw or fail closed if missed: every readwrite table needs a
7
- server-version managed field plus a conflictPolicy (no default), authClaim/nowMicroseconds fields are
8
- server-assigned and rejected in client payloads, enum columns must be cast to text, read filter and RLS
9
- policy must derive from one predicate, and the apply function is provisioned by the pgxsinkit-generate
10
- CLI as a drizzle-kit migration. Covers per-client mode projection (ADR-0025,
11
- asReadonly + assertReadContractPreserved) and Event-stream registration (ADR-0053): the streams key,
12
- defineEventStream, name limits at module eval, claimPath identity stamping, compatibility-bound payload
13
- evolution, and streams riding the lock/diff but never the fingerprint. Load before authoring a registry,
14
- adding a table, registering an Event stream, or wiring RLS.
5
+ defineSyncRegistry/defineSyncTable, sync modes, managed fields, conflict policy, filters, RLS.
6
+ Teaches the rules that throw or fail closed: every readwrite table needs a server-version managed field
7
+ plus a conflictPolicy (no default), authClaim/nowMicroseconds fields are server-assigned and rejected in
8
+ client payloads, a read filter is a predicate AST from the p.* builders over Drizzle columns (one
9
+ restricting nothing is refused) deriving from the RLS policy's own predicate, and the apply function
10
+ comes from the pgxsinkit-generate CLI as a drizzle-kit migration. Covers per-client mode projection
11
+ (asReadonly + assertReadContractPreserved) and Event-stream registration (ADR-0053): defineEventStream,
12
+ name limits, claimPath identity stamping, compatible-only payload evolution, and streams riding the
13
+ lock/diff but never the fingerprint. Load before authoring a registry, adding a table, registering an
14
+ Event stream, or wiring RLS.
15
15
  metadata:
16
16
  type: core
17
17
  library: "@pgxsinkit/contracts"
18
- library_version: "0.2.7"
18
+ library_version: "0.5.0"
19
19
  source: https://pgxsinkit.github.io/start/getting-started/
20
20
  ---
21
21
 
22
22
  # Authoring a pgxsinkit registry
23
23
 
24
- The registry (`defineSyncRegistry` over `defineSyncTable`) is the single source of truth both paths read
25
- from — the read proxy and the write apply function are generated from it, so getting the registry right
26
- is what keeps read and write authorization from drifting.
24
+ The registry (`defineSyncRegistry` over `defineSyncTable`) is the single source of truth both paths read from
25
+ — the read path's shapes (compiled by the control plane at subscribe) and the write apply function are derived
26
+ from it, so getting it right is what keeps read and write authorization from drifting.
27
27
 
28
28
  ## Writable tables have two hard requirements (or it throws)
29
29
 
@@ -56,14 +56,13 @@ widgets: defineSyncTable({
56
56
  }),
57
57
  ```
58
58
 
59
- **Column types don't constrain sync.** The read-path backfill picks a bulk-insert tier (COPY / JSON /
60
- per-row `INSERT`) statically from a table's Drizzle column types; enum columns and `GENERATED ALWAYS AS
61
- IDENTITY` primary keys are fully supported (labels round-trip through COPY/JSON, a synced identity PK keeps
62
- the server's value via `OVERRIDING SYSTEM VALUE`), so never avoid them for sync's sake. **Array columns are
63
- supported at ONE dimension** (`uuid("source_ids").array()`) on both paths: a write sends a JSON array, `[]`
64
- stores an empty array and JSON `null` stores NULL, element order preserved. Everything else about arrays
65
- fails at GENERATE time, named — `.array("[][]")` (multi-dimensional), an array PK column, and an array
66
- `managedFields` target (both strategies stamp one scalar).
59
+ **Column types don't constrain sync.** The read-path backfill picks a bulk-insert tier (COPY / JSON / per-row
60
+ `INSERT`) statically from a table's Drizzle column types; enum columns and `GENERATED ALWAYS AS IDENTITY` primary
61
+ keys are fully supported (labels round-trip through COPY/JSON, a synced identity PK keeps the server's value via
62
+ `OVERRIDING SYSTEM VALUE`), so never avoid them for sync's sake. **Array columns are supported at ONE dimension**
63
+ (`uuid("source_ids").array()`) on both paths: a write sends a JSON array, `[]` stores an empty array and JSON `null`
64
+ stores NULL, element order preserved. Everything else about arrays fails at GENERATE time, named — `.array("[][]")`
65
+ (multi-dimensional), an array PK column, and an array `managedFields` target (both strategies stamp one scalar).
67
66
 
68
67
  ## The `primaryKey` spec emits the physical PRIMARY KEY — it is the single source of truth
69
68
 
@@ -79,19 +78,19 @@ produce), so pgxsinkit DDL matches plain-Postgres inline-PK DDL and drizzle-kit
79
78
  - **Rejected:** a table-level `primaryKey(...)` through `extras`/`policies`, and more than one column-level
80
79
  `.primaryKey()` — declare composite keys via the `primaryKey` option instead.
81
80
 
82
- ## `applyMode` — CDC insert-apply policy (default stays strict)
81
+ ## `applyMode` — the **backfill** conflict policy (default stays strict)
83
82
 
84
- `applyMode` chooses how a **server CDC insert** for this table is applied on the client (ADR-0045).
85
- **`"insert"` (default)** is a plain INSERT with no conflict clause, so a genuine primary-key collision
86
- **surfaces** (the ADR-0014 invariant — a synced cache table is server-authoritative, and a duplicate insert
87
- is a real bug). **`"upsert"`** applies it idempotently as `INSERT … ON CONFLICT (pk) DO UPDATE` (or a
88
- pk-targeted `DO NOTHING` for a pk-only table), so the authoritative server row overwrites the provisional
89
- local one.
83
+ `applyMode` no longer chooses how steady-state changes apply (ADR-0058). The engine's wire vocabulary is
84
+ `upsert | delete` — an `upsert` states a row's value without claiming it is new — so **every** streamed change
85
+ applies as `INSERT … ON CONFLICT (pk) DO UPDATE`, whatever this says. What survives is the **initial load**: a fresh
86
+ subscription or a post-must-refetch re-snapshot lands on a table assumed empty, which is what lets it use COPY or a
87
+ plain multi-row INSERT, neither of which can express `ON CONFLICT`.
90
88
 
91
- **Use `"upsert"` only** when this table legitimately receives locally-**derived** provisional rows — a local
92
- trigger on another synced table writes a row here that the server independently creates too, so its CDC insert
93
- would otherwise collide (23505) and degrade the engine. It routes all three CDC-insert paths through the
94
- idempotent applier. Declare the exception where it lives; never weaken the default repo-wide.
89
+ **`"insert"` (default)** keeps that fast path, so a row already sitting there surfaces as a real precondition
90
+ failure. **Use `"upsert"` only** when the emptiness assumption does not hold — this table legitimately receives
91
+ locally-**derived** provisional rows (a local trigger on another synced table writes a row here that the server
92
+ independently creates too) that a backfill could land on top of. It then takes the conflict-tolerant applier, at the
93
+ cost of the faster path. Declare the exception where it lives; never weaken the default repo-wide.
95
94
 
96
95
  ## Managed fields are server-assigned — never send them
97
96
 
@@ -128,31 +127,39 @@ that is not a writable (projected) column splits into exactly two cases:
128
127
  The rule that follows: **write a server-only (omitted) column outside the sync rail** — a server-side
129
128
  `UPDATE`, a trigger, or a managed field (`governance.managedFields`); the route rejects it in a payload.
130
129
 
131
- ## Read-path filtering: `customWhere` runs in Electric, not Postgres
130
+ ## Local indexes are opt-in — your server's indexes are NOT mirrored
132
131
 
133
- A table's `shape.rowFilter.customWhere` builds the Electric shape `where`, which **Electric** evaluates (not
134
- Postgres) — so **return a Drizzle `SQL` fragment built from the table's columns**: reference each column
135
- through `c(column)` and embed request-derived values directly, where they become **bound `$n` params**, not
136
- hand-escaped literals.
132
+ The local store renders a synced table's primary key and nothing else: server indexes serve server loads and many
133
+ cover projected-away columns. A client read that needs one declares it — `clientProjection: { localIndexes: [{ name:
134
+ "cards_due_at_idx", columns: ["dueAt"] }] }`, an ascending btree over projected columns (`unique?` optional), refused
135
+ at registry-build time if a column is unknown or omitted or a name repeats. Index only what the **client** scans (a
136
+ due window over 100k local-store rows: ~13 ms sequential vs ~0.1 ms indexed); each index costs write time per batch.
137
+
138
+ ## Read-path filtering: `customPredicate` compiles to a predicate AST, not SQL
139
+
140
+ A table's `shape.rowFilter.customPredicate` is compiled by the **control plane** at shape creation — once per
141
+ (shape, subject), not per request — and posted to the Circuits engine as a **predicate AST**. No SQL text is
142
+ involved: build the predicate with the `p.*` builders over the table's **real Drizzle columns**, and
143
+ request-derived values ride as typed JSON scalars.
137
144
 
138
145
  ```ts
139
- function widgetsReadFilter(claims) {
146
+ function widgetsReadFilter(claims: JwtClaims): Predicate | null {
140
147
  if (isAdmin(claims)) return null; // null = no filter (all rows visible)
141
- if (!claims.sub) return DENY_ALL; // sql`false` — the deny-all sentinel (no rows visible)
142
- return sql`${c(widgets.ownerId)} = ${claims.sub}`; // claims.sub is a bound $1 param
148
+ if (!claims.sub) return DENY_ALL_PREDICATE; // the deny-all sentinel (no rows visible)
149
+ return p.eq(widgets.ownerId, claims.sub);
143
150
  }
144
151
  ```
145
152
 
146
- Two Electric where-grammar rules: columns must be **plain** (unqualified) — `c()` emits the bare
147
- `"owner_id"`, never Drizzle's qualified `"widgets"."owner_id"` (Electric rejects that) — and an **enum column
148
- must be cast to text** (`${c(widgets.role)}::text = 'manager'`). Subqueries must be self-contained (not
149
- correlated). A raw **string** is the escape hatch: escape embedded values yourself with `escapeSqlLiteral`,
150
- and return `DENY_ALL` (not `"1 = 0"`) to block all rows.
153
+ The builders are `p.eq`/`p.ne`/`p.lt`/`p.lte`/`p.gt`/`p.gte`, `p.like`/`p.notLike`, `p.isNull`/`p.isNotNull`,
154
+ `p.and`/`p.or`/`p.not`, and `p.in`/`p.notIn` over a `p.subquery` (below) — namespaced so they never collide with
155
+ `drizzle-orm`'s `eq`/`and`/`or`. Every comparison is checked against the column's own TypeScript type, so a mistyped
156
+ enum label, a `null` against a NOT NULL column, or a `jsonb`/`Date` column with no scalar wire form is a **compile
157
+ error**. **No `::text` casts** — values are typed JSON scalars; render a `Date` as the column stores it, as a string.
151
158
 
152
159
  **Inline (all-in-one `defineSyncTable`) — `rowFilter` as a function of the columns.** The example above
153
160
  assumes the table is built _elsewhere_. Declaring a table and its filter in **one** call, the table object
154
- does not exist yet — so don't fall back to column-name strings: give `shape.rowFilter` a **function of the
155
- built columns** (the typed columns `extras` gets), still with `c()`:
161
+ does not exist yet — so give `shape.rowFilter` a **function of the built columns** (the typed columns `extras`
162
+ gets) rather than falling back to column-name strings:
156
163
 
157
164
  ```ts
158
165
  defineSyncTable({
@@ -160,50 +167,50 @@ defineSyncTable({
160
167
  makeColumns: () => ({ id: uuid("id").primaryKey(), ownerId: uuid("owner_id") }),
161
168
  shape: {
162
169
  rowFilter: (columns) => ({
163
- customWhere: (claims) => (claims.sub ? sql`${c(columns.ownerId)} = ${claims.sub}` : DENY_ALL),
170
+ customPredicate: (claims) => (claims.sub ? p.eq(columns.ownerId, claims.sub) : DENY_ALL_PREDICATE),
164
171
  }),
165
172
  },
166
173
  });
167
174
  ```
168
175
 
169
- The column callback is the only authoring form. **Prefer the typed fragment over the string hatch:** a
170
- `customWhere` returning `null`/`""` means _no filter — every row visible_, so an owner filter returning `null`
171
- for "no claim" silently exposes every row; the typed form makes `DENY_ALL` the obvious deny.
176
+ The column callback is the only authoring form. **Say deny explicitly:** a `customPredicate` returning `null` means
177
+ _no filter — every row visible_, so an owner filter returning `null` for "no claim" exposes every row.
178
+ `DENY_ALL_PREDICATE` is the deny, recognised by reference: the control plane declines to create the shape at all, so
179
+ a denied subject holds no stream. It must also be **pure** (called per shape creation, and probed with empty claims
180
+ to detect claims-dependence), and a `rowFilter` restricting nothing — no `customPredicate`, no `columns` allow-list
181
+ — **throws at definition time** rather than compiling to a shape with no subject test.
172
182
 
173
- ## Cross-table filters: compose a self-contained subquery from the typed columns, never a string
183
+ ## Cross-table filters: `p.subquery` over another table's column
174
184
 
175
- A **membership fan-out** — "sync a row only if the subject belongs to its container" — is a `customWhere`
176
- whose predicate is a **subquery over another table**. Author it the same typed way as an owner filter, never
177
- as a hand-built string: `c()` for every column (bare, as Electric needs), the **table object** for the
178
- `FROM`, and the subject as a **bound param**. Factor it into a helper so the read filter and any narrower
179
- variant share one definition (the read-path twin of the membership RLS predicate):
185
+ A **membership fan-out** — "sync a row only if the subject belongs to its container" — is a `customPredicate` whose
186
+ test is a **subquery over another table**. `p.subquery(projectedColumn, where?)` names the inner set by the column it
187
+ projects, so there is no table name to get wrong and no way to project a column that table does not have. Factor it
188
+ into a helper the read filter and any narrower variant share (the read-path twin of the membership RLS predicate):
180
189
 
181
190
  ```ts
182
- // Self-contained (not correlated): it gets its own FROM, so `membership`'s bare names resolve to it.
183
- function memberContainers(subject: string): SQL {
184
- return sql`select ${c(membership.containerId)} from ${membership} where ${c(membership.memberId)} = ${subject}`;
191
+ // Uncorrelated by construction: the inner `where` reads the membership table's own columns only.
192
+ function memberContainers(subject: string): SubqueryRef<string> {
193
+ return p.subquery(membership.containerId, p.eq(membership.memberId, subject));
185
194
  }
186
195
 
187
- function widgetsReadFilter(claims: JwtClaims): SQL {
188
- if (!claims.sub) return DENY_ALL; // no claim → deny (NOT null, which would expose every row)
189
- return sql`${c(widgets.containerId)} in (${memberContainers(claims.sub)})`;
196
+ function widgetsReadFilter(claims: JwtClaims): Predicate {
197
+ if (!claims.sub) return DENY_ALL_PREDICATE; // no claim → deny (NOT null, which would expose every row)
198
+ return p.in(widgets.containerId, memberContainers(claims.sub));
190
199
  }
191
200
  ```
192
201
 
193
- What the typed form buys: columns stay rename-safe and existence-checked, and the subject is a `$n` param
194
- (`params: ["…"]`), never an escaped literal — so a quote in the value can't break or inject the predicate.
195
- **Subqueries nest by interpolation** — wrap one `sql` fragment in another to narrow a fan-out: `` sql`${c(post.offeringId)} in (${memberOfferings(sub)}) and (${c(post.groupId)} is null or ${c(post.groupId)} in (${memberGroups(sub)}))` `` (each `${sub}`
196
- is its own bound param). Two constraints: the subquery must stay **self-contained**, and the subquery
197
- `where` is the **flagged Electric preview** — run Electric with `allow_subqueries,tagged_subqueries` or the
198
- shape fails closed (no rows); on managed Electric Cloud, Electric staff activate it per source on request
199
- (no self-serve toggle yet). Combine with the function form when the table is defined all-in-one: the row's
200
- own column comes from `(columns) => …`, the foreign table is imported built.
202
+ What the AST form buys: columns stay rename-safe and existence-checked, the projected column's type rides on the
203
+ `SubqueryRef` so `p.in` refuses an outer column it cannot be compared with, and the engine maintains the inner set
204
+ **incrementally and shares it across every shape referencing the same subquery** — an entitlement-shaped membership
205
+ costs one index, not one per shape. Two constraints: `IN` is **single-column** (no composite `(a, b) IN (…)`), and the
206
+ subquery stays **uncorrelated** — its `where` never references the outer row. Combine with the function form when the
207
+ table is defined all-in-one: the row's own column comes from `(columns) => …`, the foreign table is imported built.
201
208
 
202
209
  ## RLS: derive read and write from the same Drizzle columns
203
210
 
204
- Authorization runs in two engines (Postgres RLS for writes, the Electric `where` for reads). Build both from
205
- the **same Drizzle columns**, so a rename or typo can never make a row readable-but-unwritable (or vice
206
- versa):
211
+ Authorization runs in two engines (Postgres RLS for writes, the shape predicate the Circuits engine
212
+ evaluates for reads). Build both from the **same Drizzle columns**, so a rename or typo can never make a
213
+ row readable-but-unwritable (or vice versa):
207
214
 
208
215
  - Common shapes: `buildSupabaseOwnerOrAdminNativePolicies({ role, ownerColumn })` and
209
216
  `buildSupabaseMembershipNativePolicies({ role, containerColumn, membershipTable, … })`. They take **real
@@ -217,17 +224,18 @@ versa):
217
224
  SECURITY DEFINER membership helper, a `current_setting('request.jwt.claims')` admin check), and inline that
218
225
  predicate rather than referencing a not-yet-created function. For "compare OLD vs NEW" rules RLS cannot
219
226
  help (`WITH CHECK` sees only NEW, `USING` only OLD) — use a `BEFORE UPDATE` trigger.
220
- - **Do not hand-write the read half — every policy family ships its read-path mirror.** Electric cannot
221
- read RLS, so the shape `where` must re-derive the same visible set in JS, from the same declaration:
222
- `buildOwnershipShapeWhere(ownerColumn, claims.sub)`, `buildOwnerOrAdminShapeWhere(ownerColumn, claims)`
223
- (admin → `null`, i.e. no filter, mirroring the policy's bypass branch),
224
- `buildMembershipShapeWhere(columns, claims)` (pass the **same** options object you gave the policy
225
- builder — write-only fields are ignored), and `buildGrantScopeAccessShapeWhere(scopeColumn, claims, …)`
226
- (bypass grant → `null` too; bare `resolveGrantScopeIds` + `buildGrantScopeShapeWhere` cannot see it).
227
- Return each straight from `customWhere`; they deny with `DENY_ALL`, so the filter probes claims-dependent.
228
- - Two mirror properties: they cover **SELECT only** (write-gate branches stay with the INSERT/UPDATE/DELETE
229
- policies), and the two surfaces render containment in **different dialects on purpose** — RLS emits
230
- `= ANY(ARRAY(select …))` for the InitPlan/index-scan discipline, Electric plain `IN (subquery)`.
227
+ - **Do not hand-write the read half — every policy family ships its read-path mirror.** The sync engine cannot read
228
+ RLS, so the shape predicate re-derives the same visible set in JS from the same declaration:
229
+ `buildOwnershipShapePredicate`, `buildOwnerOrAdminShapePredicate` (admin → `null`, mirroring the policy's bypass
230
+ branch), `buildMembershipShapePredicate` (pass the **same** options object you gave the policy builder), and
231
+ `buildGrantScopeAccessShapePredicate` (bypass grant → `null` too; bare `resolveGrantScopeIds` +
232
+ `buildGrantScopeShapePredicate` cannot see it). Each takes the column plus the claims; return it straight from
233
+ `customPredicate` — they deny with `DENY_ALL_PREDICATE`, so the filter probes claims-dependent.
234
+ - Two mirror properties: they cover **SELECT only** (write-gate branches stay with the
235
+ INSERT/UPDATE/DELETE policies), and the two surfaces express containment in **different forms on
236
+ purpose** — RLS emits `= ANY(ARRAY(select …))` for the InitPlan/index-scan discipline, the read half a
237
+ first-class `p.in` over a `p.subquery` the engine maintains incrementally and shares between shapes. (A
238
+ grant set lives in the JWT, not a table, so that mirror is an `OR` of equalities instead.)
231
239
 
232
240
  Give drizzle-kit `entities: { roles: { provider: "supabase" } }` in `drizzle.config.ts` so the Supabase roles
233
241
  (`authenticated`/`anon`/`service_role`/…) are treated as externally managed — referenced in a policy's `to:`,
@@ -235,12 +243,12 @@ never created or dropped.
235
243
 
236
244
  ## Composition obligations: two correct policies can still break an invariant
237
245
 
238
- The registry keeps ONE table's read filter and write policy from drifting. A domain invariant usually spans
239
- several tables and rails, and no registry feature can see that composition. Worked example: an invite table's
240
- RLS grants an offering-scoped teacher INSERT; an acceptance worker then mints a membership row. Each policy
241
- is correct alone; together they violate "this offering only ever has one member". The worker's semantics are
242
- invisible to per-table declarations, so the obligation is permanently the consumer's. When you add a worker,
243
- route, or trigger that writes rows as a CONSEQUENCE of other rows:
246
+ The registry keeps ONE table's read filter and write policy from drifting. A domain invariant usually spans several
247
+ tables and rails, and no registry feature can see that composition. Worked example: an invite table's RLS grants an
248
+ offering-scoped teacher INSERT; an acceptance worker then mints a membership row. Each policy is correct alone;
249
+ together they violate "this offering only ever has one member". The worker's semantics are invisible to per-table
250
+ declarations, so the obligation is permanently the consumer's. When you add a worker, route, or trigger that writes
251
+ rows as a CONSEQUENCE of other rows:
244
252
 
245
253
  - List the invariants the OUTPUT table participates in, not just the input's — the output is where the
246
254
  violation lands — and for each ask whether the composed path enforces it or merely assumes the input row's
@@ -255,10 +263,10 @@ route, or trigger that writes rows as a CONSEQUENCE of other rows:
255
263
  ## Provision the apply function from the registry
256
264
 
257
265
  The write path applies through one in-database PL/pgSQL function, `pgxsinkit_apply_mutations`. Generate its
258
- drizzle-kit migration with the `pgxsinkit-generate` CLI (a `bin` of `@pgxsinkit/server`) and apply it through
259
- your normal migration flow; it is **deny-by-default** (see `deploying` for `--grant-execute-to`). It and the
260
- audit/version column DEFAULTs both **call** `public.pgxsinkit_clock_us()`, so the `--utilities` migration
261
- installing that clock must be **first in the chain** (hence the early-sorting name):
266
+ drizzle-kit migration with the `pgxsinkit-generate` CLI (a `bin` of `@pgxsinkit/server`) and apply it through your
267
+ normal migration flow; it is **deny-by-default** (see `deploying` for `--grant-execute-to`). It and the audit/version
268
+ column DEFAULTs both **call** `public.pgxsinkit_clock_us()`, so the `--utilities` migration installing that clock
269
+ must be **first in the chain** (hence the early-sorting name):
262
270
 
263
271
  ```bash
264
272
  bun run pgxsinkit-generate --registry ./sync-registry.ts --export registry \
@@ -269,13 +277,13 @@ bun run pgxsinkit-generate --utilities \
269
277
 
270
278
  ## Multi-client: one authoritative registry, readonly projections (ADR-0025)
271
279
 
272
- When the same table is `readwrite` for one client and `readonly` for another, `mode` is **per-client**, not
273
- a property of the table: define it **once** in an authoritative registry at its writable capability and
274
- project it per client. `mode` is baked at `defineSyncTable` time and drives the overlay/journal machinery +
275
- the `_read_model` view, so a hand-spread `{ ...entry, mode: "readonly" }` is **broken** (it keeps a view over
276
- overlay state the readonly client never creates). `asReadonly` re-derives a true readonly entry — dropping
277
- the overlay/journal projection, the view, and `conflictPolicy`/`governance`/`writeMode`, keeping columns,
278
- primary key, synced table, shape/row filter and `rowClass`.
280
+ When the same table is `readwrite` for one client and `readonly` for another, `mode` is **per-client**, not a
281
+ property of the table: define it **once** in an authoritative registry at its writable capability and project it per
282
+ client. `mode` is baked at `defineSyncTable` time and drives the overlay/journal machinery + the `_read_model` view,
283
+ so a hand-spread `{ ...entry, mode: "readonly" }` is **broken** (it keeps a view over overlay state the readonly
284
+ client never creates). `asReadonly` re-derives a true readonly entry — dropping the overlay/journal projection, the
285
+ view, and `conflictPolicy`/`governance`/`writeMode`, keeping columns, primary key, synced table, shape/row filter
286
+ and `rowClass`.
279
287
 
280
288
  ```ts
281
289
  const authoritativeRegistry = defineSyncRegistry({ posting_restriction: postingRestrictionEntry }); // readwrite
@@ -287,12 +295,12 @@ assertReadContractPreserved(authoritativeRegistry, teacherRegistry, { label: "te
287
295
  assertReadContractPreserved(authoritativeRegistry, learnerRegistry, { label: "learner" });
288
296
  ```
289
297
 
290
- - **Generate the server (apply function + proxy) from the authoritative registry** — it emits a branch per
291
- table and stamps managed fields / reject-if-stale from the entry's write contract, so it must see the
292
- writable entry. A claims-branching `customWhere` then serves every client.
293
- - A projection may differ **only** in write capability and lifecycle (`subscription`/`retention`/group),
294
- never in the read contract — `assertReadContractPreserved` enforces it (it can't see the `customWhere`
295
- body, so bump `rowFilter.revision` on a logic change).
298
+ - **Run the server (apply function + control plane) off the authoritative registry** — the generated apply
299
+ function emits a branch per table and stamps managed fields / reject-if-stale from the entry's write
300
+ contract, so it must see the writable entry. A claims-branching `customPredicate` then serves every client.
301
+ - A projection may differ **only** in write capability and lifecycle (`subscription`/`retention`/group), never
302
+ in the read contract — `assertReadContractPreserved` enforces it (it cannot see the `customPredicate` body,
303
+ so bump `rowFilter.revision` on a logic change).
296
304
  - The full registry fingerprint differs between the writable and readonly variants — expected and fine:
297
305
  it is client-local (guards each client's own store rebuild) and the server never sees it.
298
306
 
@@ -309,54 +317,43 @@ export const assessmentDefinition = defineSyncTable({ tableName: "assessment_def
309
317
  export const assessmentDefinitionAdminSummary = defineReadProjection(assessmentDefinition, {
310
318
  as: "assessment_definition_admin_summary", // distinct local table + shapeKey
311
319
  columns: ["offeringId", "assessmentType", "title", "state"], // typed subset of owner keys; PK always kept
312
- rowFilter: (c) => ({ customWhere: adminOrgFilter(c.offeringId), revision: "admin-summary-1" }),
320
+ rowFilter: (c) => ({ customPredicate: adminOrgFilter(c.offeringId), revision: "admin-summary-1" }),
313
321
  });
314
322
  ```
315
323
 
316
324
  - It **owns no table**: its `table` IS the owner's, so nothing new is migrated and nothing leaks into a
317
325
  drizzle-kit schema barrel. Only its `localTable` (named `as`) and shape are its own.
318
- - `columns` is a typed subset of the owner's keys, and the local table carries the owner's **real per-column
319
- types restricted to those keys** (Picked from the owner), so a row typechecks by property key with no
320
- casts. The PK is always kept **at runtime**, but the type is a safe **under-claim** — a PK column not in
321
- `columns` is synced yet absent from the type, so list it to read it typed. Column definitions are reused
322
- (never restated), and the subset becomes the Electric `columns` allow-list, so an omitted (heavy) column is
323
- **never fetched**, not merely stripped.
324
- - The physical Electric table is **derived** from the owner — you never name a source string. The `rowFilter`
325
- callback receives the OWNER's full columns (the `customWhere` runs in Electric on the physical table, so it
326
- may reference a column the subset omits).
327
- - It is **readonly**; put it in the authoritative registry under its own key and in the reading client's
328
- registry. RLS for its reads lives on the **owner** (a projection adds no DDL to a table it doesn't own), so
329
- its `customWhere` must be a subset of what that RLS allows. The proxy resolves each shape by its unique
330
- `shapeKey`, so owner and projection coexist over one physical table.
331
-
332
- ### Redacting projection: a secure "window" over a keyed table
333
-
334
- A projection can carry its own `serverProjection` (an egress `rowTransform`, resolved by its `shapeKey`) —
335
- e.g. stream a `jsonb` item body while stripping the answer key per row. When the transform must READ a column
336
- outside the client shape (a `keysWithheld` control flag), list it in `serverOnlyColumns`: it joins the
337
- Electric fetch allow-list (so the transform sees it) yet stays out of the client keep-set. Egress order is
338
- **transform first, then omission**.
339
-
340
- ```ts
341
- export const secureItemWindow = defineReadProjection(secureItem, {
342
- as: "secure_item_window",
343
- columns: ["payload", "metadata"], // client keep-set (PK always kept)
344
- serverProjection: {
345
- rowTransform: (row) => (row.keys_withheld === true ? { ...row, payload: stripKey(row.payload) } : row),
346
- },
347
- serverOnlyColumns: ["keysWithheld"], // fetched for the transform, never on the client wire
348
- });
349
- ```
350
-
351
- `serverOnlyColumns` requires BOTH `serverProjection.rowTransform` and `columns`, and must be disjoint from
352
- `columns` and the PK — each is a loud error. **No inheritance — enforced.** A projection does NOT inherit its owner's `serverProjection`: an inherited
353
- transform whose input column is absent from the projection's fetch list reads `undefined` and fails OPEN.
354
- Since a bare projection over a redacting owner would then egress the RAW row, `defineReadProjection` THROWS
355
- when the owner declares an egress `rowTransform` unless the projection declares its posture — its own
356
- `serverProjection` (usually the same fn) + `serverOnlyColumns`, or the explicit opt-out `serverProjection:
357
- "unredacted"` (only after confirming the kept columns leak nothing; it attaches no transform but records the
358
- raw-egress decision at the definition site). `"unredacted"` over a transform-less owner is itself rejected — a
359
- stale opt-out would pre-authorize a leak if the owner later gained one.
326
+ - `columns` is a typed subset of the owner's keys; the local table carries the owner's real per-column types
327
+ restricted to those keys, so a row typechecks by property key with no casts. The PK is always kept **at
328
+ runtime** but the type is a safe **under-claim** — list a PK column in `columns` to read it typed. The
329
+ subset becomes the shape's **emitted** column set, so an omitted (heavy) column is **never streamed**.
330
+ - The physical table is **derived** from the owner — you never name a source string. The `rowFilter`
331
+ callback receives the OWNER's full columns: the engine matches on columns the shape does not emit, so the
332
+ predicate may reference a column the subset omits.
333
+ - It is **readonly**; register it under its own key in the authoritative registry and in the reading client's.
334
+ RLS for its reads lives on the **owner** (a projection adds no DDL), so its `customPredicate` must be a
335
+ subset of what that RLS allows. The control plane resolves each shape by `shapeKey`, so owner and
336
+ projection coexist over one physical table.
337
+
338
+ ### Redacting projection: keep the secret out of the row, not out of the response
339
+
340
+ **Prefer redacting in Postgres.** Model a "window" over a keyed table as SCHEMA where you can: compute the
341
+ redacted value into its own column (generated or trigger-maintained), sync THAT, and split the projections by
342
+ predicate on the control flag — the flag never reaches the client and the raw value never enters storage.
343
+
344
+ `serverProjection` (an egress `rowTransform`) is the escape hatch when the decision is per-row and cannot be
345
+ pre-computed. It runs **at the stream edge**, per request: the edge rewrites every row of the JSON long-poll
346
+ body, then strips each row to the client keep-set — which takes `serverOnlyColumns` (fetched so the transform
347
+ can read them) off the wire. Costs, confined to shapes that declare one: `claims` are `{ sub }` only (richer
348
+ claims belong in `rowFilter.customPredicate`); the shape is private-tier (`scope` + `rowTransform` is refused)
349
+ and answered `cache-control: private, no-store`; JSON long-poll only — an SSE read gets `406`.
350
+
351
+ Guards fire at definition time: `serverOnlyColumns` requires BOTH `serverProjection.rowTransform` and
352
+ `columns`, disjoint from `columns` and the PK. **No inheritance — enforced:** `defineReadProjection` THROWS
353
+ when the owner declares a `rowTransform` unless the projection states its own (usually the same fn, plus
354
+ `serverOnlyColumns` for its control flags) or opts out with the literal `serverProjection: "unredacted"` —
355
+ only after confirming the kept columns leak nothing. `"unredacted"` over a transform-less owner is itself
356
+ rejected, so a stale opt-out cannot pre-authorize a leak the owner gains later.
360
357
 
361
358
  ## Classify rows and assert registry invariants (ADR-0052)
362
359
 
@@ -374,9 +371,9 @@ assertRegistryInvariant(registry, {
374
371
  name: "team-scoped rows are invisible to an anonymous caller",
375
372
  appliesTo: ["team-scoped"], // classes (or a predicate); an undeclared class / zero matches throws
376
373
  claimsFixtures: { anonymous: {}, member: { sub: memberId }, admin: adminClaims },
377
- holds: ({ fixtureName, renderedWhere, renderedPolicies }) =>
374
+ holds: ({ fixtureName, readPredicate, renderedPolicies }) =>
378
375
  fixtureName !== "anonymous" ||
379
- (renderedWhere?.where === "false" && renderedPolicies.every((p) => p.using !== "true")) ||
376
+ (deniesAllRows(readPredicate) && renderedPolicies.every((policy) => policy.using !== "true")) ||
380
377
  "anonymous is not denied on one of the two surfaces", // reported as `entry (fixture): reason`
381
378
  });
382
379
  ```
@@ -384,26 +381,26 @@ assertRegistryInvariant(registry, {
384
381
  So a table added next month cannot inherit the obligation invisibly (omit `rowClasses` and `rowClass` is
385
382
  unconstrained, as the bare registry-map form always is). Projections carry the class (`asReadonly`,
386
383
  `asEphemeral`; `defineReadProjection` inherits the owner's, overridable). Each cell gets that persona's
387
- RENDERED artifacts — `renderedWhere` is the proxy's own `buildRowFilterShape(…)` (`null` =
388
- unfiltered), `renderedPolicies` the table's RLS as inline SQL — so one predicate covers both surfaces, and
389
- ALL failing cells aggregate into one error. `rowClass` is authoring metadata, deliberately in NEITHER
390
- fingerprint (classifying never wipes a cache); the **lock** carries it, so losing a class is a `risky` diff.
391
- It complements `RowFilterSpec.revision`: only `revision` makes a `customWhere` logic change move the
392
- fingerprint (rebuilding the cache, resetting the subscription), while the assertion renders that logic — for
393
- the fixtures you hand it, and no others.
394
-
395
- ## Storage declaration: `storage.backend` and `storage.durability` (browser stores)
396
-
397
- The registry carries the browser store's storage contract — `SyncRegistryDefinition.storage`,
398
- `{ backend?: "opfs" | "idbfs"; durability?: "relaxed" | "strict" }`. It lives on the registry, not on a
399
- minting surface, worker entry, or attach site, because both properties follow the DATA: one declaration
384
+ RESOLVED artifacts — `readPredicate` is the entry's `customPredicate` output for those claims, exactly what
385
+ the control plane compiles into the shape (`null` = unfiltered), `renderedPolicies` the table's RLS as inline
386
+ SQL — so one predicate covers both surfaces and ALL failing cells aggregate into one error. Match on STRUCTURE
387
+ (`deniesAllRows`, the `isXPredicate` guards), never a rendered string. `rowClass` is authoring metadata,
388
+ deliberately in NEITHER fingerprint (classifying never wipes a cache); the **lock** carries it, so losing a
389
+ class is a `risky` diff. It complements `RowFilterSpec.revision`: only `revision` makes a `customPredicate`
390
+ logic change move the fingerprint (rebuilding the cache, resetting the subscription), while the assertion
391
+ renders that logic — for the fixtures you hand it, and no others.
392
+
393
+ ## Storage declaration: `storage.backend`, `durability`, `engine`, `build` (browser stores)
394
+
395
+ The registry carries the browser store's storage contract — `SyncRegistryDefinition.storage`, `{ backend?: "opfs" |
396
+ "idbfs"; durability?: "relaxed" | "strict"; engine?: { module }; build?: "c" | "pgrust" }` (`engine`, `build`:
397
+ [references/storage-engine-and-build.md](references/storage-engine-and-build.md)). It lives on the registry, not on a minting surface, worker entry, or attach site, because every property follows the DATA: one declaration
400
398
  binds every open of every store minted from that registry, so no tab can disagree with another.
401
399
 
402
- - **`backend`** (default `"opfs"`) — the normal boot everywhere: the toolkit probes OPFS sync-access at boot
403
- and runs the `opfs-repacked` engine wherever handles are granted, falling back automatically to
404
- in-SharedWorker idbfs (declared durability kept) only where the platform grants them nowhere.
405
- `backend: "idbfs"` is the one opt-out (no probe, no election). Where the engine runs is never a knob; the
406
- only decision you declare is whether to force idb.
400
+ - **`backend`** (default `"opfs"`) — the normal boot everywhere: the toolkit probes OPFS sync-access at boot and
401
+ runs the `opfs-repacked` engine wherever handles are granted, falling back automatically to in-SharedWorker idbfs
402
+ (declared durability kept) only where the platform grants them nowhere. `backend: "idbfs"` is the one opt-out (no
403
+ probe, no election). Where the engine runs is never a knob; the only decision you declare is whether to force idb.
407
404
  - **`durability`** (default `"relaxed"`) — relaxed returns the local write before the physical flush and
408
405
  schedules it asynchronously; `"strict"` awaits the flush per commit. Relaxed is right for a sync toolkit
409
406
  (the server is the source of truth, and the loss window is one recent action); declare `"strict"` only for
@@ -413,18 +410,21 @@ It scopes the **browser** store only; Node mints stay `file://` and export clone
413
410
 
414
411
  ## Consistency groups: scope them to the joined cluster
415
412
 
416
- `consistencyGroup` binds tables onto one shape stream committing **atomically** at a shared LSN frontier —
417
- a reader never sees one grouped table advanced past another for the same server transaction. Default is
418
- none (per-table singleton, independent frontier). Three scoping rules:
413
+ `consistencyGroup` binds tables into one subscription that commits **atomically at boot and catch-up
414
+ alignment** — a reader never sees one grouped table advanced past another for a transaction the group caught
415
+ up on. Each member is its own stream; the group commits when **every** member's most recent response asserted
416
+ up-to-date (offsets are per-stream, so the gate is that predicate, plus the engine barrier on each alignment
417
+ generation's first commit). Live deliveries commit per response, so two halves of one transaction can land a
418
+ few milliseconds apart — a documented window (backlog 0014), not a guarantee. Default is none — a per-table
419
+ singleton committing on its own. Three scoping rules:
419
420
 
420
421
  1. **Group the transactionally-joined cluster** — tables written together in one server transaction and
421
- rendered joined (FK parent + children); that is what the atomic frontier protects. If the app otherwise
422
+ rendered joined (FK parent + children); that is what the atomic commit protects. If the app otherwise
422
423
  needs post-ack re-reads to hide half-applied transactions, the tables belong in a group.
423
- 2. **Quiet members are affordable.** A rarely-written reference table once held its whole group for a full
424
- long-poll cycle (~41s on CDN-fronted Electric); the live-tail sibling nudge now caps that at ~one
425
- catch-up round trip per gated commit, so don't keep a lookup table out of its natural group.
426
- 3. **Don't group "everything".** Every gated commit nudges each lagging member — unrelated clusters go in
427
- separate groups or stay singletons.
424
+ 2. **Quiet members are affordable.** Every `204` long-poll timeout re-asserts up-to-date, so a rarely-written
425
+ reference table never holds its group behind a stale watermark — keep lookup tables in their natural group.
426
+ 3. **Don't group "everything".** A group commits at the pace of its slowest member; unrelated clusters go
427
+ in separate groups or stay singletons.
428
428
 
429
429
  All members of a group must agree on `subscription`, `retention`, `writeMode` (or the registry rejects it).
430
430
 
@@ -478,8 +478,8 @@ export const registry = defineSyncRegistry({
478
478
  - Trying to write an `omitColumns` (server-only) column from a client payload — the write route
479
479
  **400-rejects** it (an unknown typo is instead silently dropped, surfaced by a per-process `console.warn`);
480
480
  write them outside the sync rail (a server `UPDATE`, a trigger, or a managed field).
481
- - In a `customWhere`: comparing an enum without `::text`, qualifying a column (use `c()` for a bare ref),
482
- or hand-escaping a value into a string instead of binding it via a Drizzle `sql` fragment.
481
+ - In a `customPredicate`: returning `null` for "no claim" (that is _every row_ — return `DENY_ALL_PREDICATE`), a
482
+ `rowFilter` that restricts nothing (throws), a correlated `p.subquery`, or SQL text where a `p.*` builder exists.
483
483
  - A multi-dimensional array column, an array PK, or a managed field on an array column — each fails at
484
484
  generate time; single-dimension arrays are fully supported on both paths.
485
485
  - Letting the read filter and RLS policy diverge instead of building both from the same Drizzle columns.
@@ -495,5 +495,5 @@ export const registry = defineSyncRegistry({
495
495
  client-supplied and can lie), a non-strict object payload (the registry throws), projecting a registry
496
496
  without re-declaring `streams`, evolving a payload incompatibly, or a `.refine` change with no `revision`.
497
497
 
498
- For the surrounding model (two paths, one write path, fail-closed subquery flag), load the `core` skill
499
- from `@pgxsinkit/client`. Full prose: <https://pgxsinkit.github.io/start/getting-started/>.
498
+ For the surrounding model (two paths, one write path, the fail-closed control plane and edge), load the
499
+ `core` skill from `@pgxsinkit/client`. Full prose: <https://pgxsinkit.github.io/start/getting-started/>.
@@ -0,0 +1,29 @@
1
+ # `storage.engine` and `storage.build`
2
+
3
+ Both are part of the store's **identity**, like `backend`: one declaration binds every open of every store
4
+ minted from the registry, and changing either means minting a fresh store under a fresh path — never
5
+ reopening an existing one.
6
+
7
+ ## `storage.engine` — a different store engine
8
+
9
+ `storage: { engine: { module: "/store-engine/factory.js" } }`. `module` is an absolute or origin-relative module
10
+ URL. pgxsinkit `import()`s it in whichever scope is minting and takes its **default export** — or, failing
11
+ that, a named `createStore` — as the store factory: `(storePath: string, backendOverride?: "memory") =>
12
+ Promise<PgwasmClient>`, the same signature as `defineSyncWorker`'s `createStore` option. That module then
13
+ answers for the store instead of the built-in `createPgwasmClient`. Absent (the default) is the built-in
14
+ store. The module owns its own assets (derive them from `import.meta.url`), its storage layout under the store
15
+ path, and its environment requirements; serve it same-origin. A module that will not load, or exports no
16
+ factory, fails the mint loudly naming the module — it never falls back to the built-in store.
17
+ Full prose: <https://pgxsinkit.github.io/concepts/worker-mode/#declaring-a-different-store-engine>.
18
+
19
+ ## `storage.build` — the Postgres build
20
+
21
+ `storage: { build: "c" }`. `build` names the Postgres build that owns every store minted from the registry:
22
+ `"c"` (the default, `cBuild` from `@pgxsinkit/pgwasm-c`) or `"pgrust"`. A data directory belongs to the build
23
+ that created it, so a different build is a different store. The declaration only names the build; the app
24
+ supplies the build itself as code (the `build` option of `createSyncClient`, `defineSyncWorker` and
25
+ `createPgwasmClient`), and a supplied or adopted build that is not the declared one fails with
26
+ `StorageBuildMismatchError` before any store is touched. A bare table map declares it with
27
+ `attachSyncRegistryStorage`. It may also travel on the wire with a dynamic declaration; an explicit
28
+ disagreement between the two is a `StorageDeclarationRefusedError`. Leave it at the default unless the app
29
+ runs another build. Full prose: <https://pgxsinkit.github.io/concepts/postgres-builds/>.