@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.
@@ -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.6"
18
+ library_version: "0.3.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
 
@@ -79,19 +79,20 @@ produce), so pgxsinkit DDL matches plain-Postgres inline-PK DDL and drizzle-kit
79
79
  - **Rejected:** a table-level `primaryKey(...)` through `extras`/`policies`, and more than one column-level
80
80
  `.primaryKey()` — declare composite keys via the `primaryKey` option instead.
81
81
 
82
- ## `applyMode` — CDC insert-apply policy (default stays strict)
82
+ ## `applyMode` — the **backfill** conflict policy (default stays strict)
83
83
 
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.
84
+ `applyMode` no longer chooses how steady-state changes apply (ADR-0058). The engine's wire vocabulary is
85
+ `upsert | delete` — an `upsert` states a row's value without claiming it is new — so **every** streamed change
86
+ applies as `INSERT … ON CONFLICT (pk) DO UPDATE`, whatever this says. What survives is the **initial load**: a
87
+ fresh subscription or a post-must-refetch re-snapshot lands on a table assumed empty, which is what lets it
88
+ use COPY or a plain multi-row INSERT, neither of which can express `ON CONFLICT`.
90
89
 
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.
90
+ **`"insert"` (default)** keeps that fast path, so a row already sitting there surfaces as a real precondition
91
+ failure. **Use `"upsert"` only** when the emptiness assumption does not hold — this table legitimately
92
+ receives locally-**derived** provisional rows (a local trigger on another synced table writes a row here that
93
+ the server independently creates too) that a backfill could land on top of. It then takes the
94
+ conflict-tolerant applier, at the cost of the faster path. Declare the exception where it lives; never weaken
95
+ the default repo-wide.
95
96
 
96
97
  ## Managed fields are server-assigned — never send them
97
98
 
@@ -128,31 +129,32 @@ that is not a writable (projected) column splits into exactly two cases:
128
129
  The rule that follows: **write a server-only (omitted) column outside the sync rail** — a server-side
129
130
  `UPDATE`, a trigger, or a managed field (`governance.managedFields`); the route rejects it in a payload.
130
131
 
131
- ## Read-path filtering: `customWhere` runs in Electric, not Postgres
132
+ ## Read-path filtering: `customPredicate` compiles to a predicate AST, not SQL
132
133
 
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.
134
+ A table's `shape.rowFilter.customPredicate` is compiled by the **control plane** at shape creation — once per
135
+ (shape, subject), not per request — and posted to the Circuits engine as a **predicate AST**. No SQL text is
136
+ involved: build the predicate with the `p.*` builders over the table's **real Drizzle columns**, and
137
+ request-derived values ride as typed JSON scalars.
137
138
 
138
139
  ```ts
139
- function widgetsReadFilter(claims) {
140
+ function widgetsReadFilter(claims: JwtClaims): Predicate | null {
140
141
  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
142
+ if (!claims.sub) return DENY_ALL_PREDICATE; // the deny-all sentinel (no rows visible)
143
+ return p.eq(widgets.ownerId, claims.sub);
143
144
  }
144
145
  ```
145
146
 
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.
147
+ The builders are `p.eq`/`p.ne`/`p.lt`/`p.lte`/`p.gt`/`p.gte`, `p.like`/`p.notLike`, `p.isNull`/`p.isNotNull`,
148
+ `p.and`/`p.or`/`p.not`, and `p.in`/`p.notIn` over a `p.subquery` (below) — namespaced so they never collide
149
+ with `drizzle-orm`'s `eq`/`and`/`or`. Every comparison is checked against the column's own TypeScript type, so
150
+ a mistyped enum label, a `null` against a NOT NULL column, or a `jsonb`/`Date` column with no scalar wire form
151
+ is a **compile error**. **No `::text` casts** — values are typed JSON scalars; render a `Date` as the column
152
+ stores it and pass the string.
151
153
 
152
154
  **Inline (all-in-one `defineSyncTable`) — `rowFilter` as a function of the columns.** The example above
153
155
  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()`:
156
+ does not exist yet — so give `shape.rowFilter` a **function of the built columns** (the typed columns `extras`
157
+ gets) rather than falling back to column-name strings:
156
158
 
157
159
  ```ts
158
160
  defineSyncTable({
@@ -160,50 +162,52 @@ defineSyncTable({
160
162
  makeColumns: () => ({ id: uuid("id").primaryKey(), ownerId: uuid("owner_id") }),
161
163
  shape: {
162
164
  rowFilter: (columns) => ({
163
- customWhere: (claims) => (claims.sub ? sql`${c(columns.ownerId)} = ${claims.sub}` : DENY_ALL),
165
+ customPredicate: (claims) => (claims.sub ? p.eq(columns.ownerId, claims.sub) : DENY_ALL_PREDICATE),
164
166
  }),
165
167
  },
166
168
  });
167
169
  ```
168
170
 
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.
171
+ The column callback is the only authoring form. **Say deny explicitly:** a `customPredicate` returning `null`
172
+ means _no filter — every row visible_, so an owner filter returning `null` for "no claim" exposes every row.
173
+ `DENY_ALL_PREDICATE` is the deny, recognised by reference: the control plane declines to create the shape at
174
+ all, so a denied subject holds no stream. It must also be **pure** (called per shape creation, and probed with
175
+ empty claims to detect claims-dependence), and a `rowFilter` restricting nothing — no `customPredicate`, no
176
+ `columns` allow-list — **throws at definition time** rather than compiling to a shape with no subject test.
172
177
 
173
- ## Cross-table filters: compose a self-contained subquery from the typed columns, never a string
178
+ ## Cross-table filters: `p.subquery` over another table's column
174
179
 
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):
180
+ A **membership fan-out** — "sync a row only if the subject belongs to its container" — is a `customPredicate`
181
+ whose test is a **subquery over another table**. `p.subquery(projectedColumn, where?)` names the inner set by
182
+ the column it projects, so there is no table name to get wrong and no way to project a column that table does
183
+ not have. Factor it into a helper the read filter and any narrower variant share (the read-path twin of the
184
+ membership RLS predicate):
180
185
 
181
186
  ```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}`;
187
+ // Uncorrelated by construction: the inner `where` reads the membership table's own columns only.
188
+ function memberContainers(subject: string): SubqueryRef<string> {
189
+ return p.subquery(membership.containerId, p.eq(membership.memberId, subject));
185
190
  }
186
191
 
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)})`;
192
+ function widgetsReadFilter(claims: JwtClaims): Predicate {
193
+ if (!claims.sub) return DENY_ALL_PREDICATE; // no claim → deny (NOT null, which would expose every row)
194
+ return p.in(widgets.containerId, memberContainers(claims.sub));
190
195
  }
191
196
  ```
192
197
 
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.
198
+ What the AST form buys: columns stay rename-safe and existence-checked, the projected column's type rides on
199
+ the `SubqueryRef` so `p.in` refuses an outer column it cannot be compared with, and the engine maintains the
200
+ inner set **incrementally and shares it across every shape referencing the same subquery** — an
201
+ entitlement-shaped membership costs one index, not one per shape. Two constraints: `IN` is **single-column**
202
+ (no composite `(a, b) IN (…)`), and the subquery stays **uncorrelated** — its `where` never references the
203
+ outer row. Combine with the function form when the table is defined all-in-one: the row's own column comes
204
+ from `(columns) => …`, the foreign table is imported built.
201
205
 
202
206
  ## RLS: derive read and write from the same Drizzle columns
203
207
 
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):
208
+ Authorization runs in two engines (Postgres RLS for writes, the shape predicate the Circuits engine
209
+ evaluates for reads). Build both from the **same Drizzle columns**, so a rename or typo can never make a
210
+ row readable-but-unwritable (or vice versa):
207
211
 
208
212
  - Common shapes: `buildSupabaseOwnerOrAdminNativePolicies({ role, ownerColumn })` and
209
213
  `buildSupabaseMembershipNativePolicies({ role, containerColumn, membershipTable, … })`. They take **real
@@ -217,17 +221,19 @@ versa):
217
221
  SECURITY DEFINER membership helper, a `current_setting('request.jwt.claims')` admin check), and inline that
218
222
  predicate rather than referencing a not-yet-created function. For "compare OLD vs NEW" rules RLS cannot
219
223
  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)`.
224
+ - **Do not hand-write the read half — every policy family ships its read-path mirror.** The sync engine
225
+ cannot read RLS, so the shape predicate re-derives the same visible set in JS from the same declaration:
226
+ `buildOwnershipShapePredicate`, `buildOwnerOrAdminShapePredicate` (admin → `null`, mirroring the policy's
227
+ bypass branch), `buildMembershipShapePredicate` (pass the **same** options object you gave the policy
228
+ builder), and `buildGrantScopeAccessShapePredicate` (bypass grant → `null` too; bare
229
+ `resolveGrantScopeIds` + `buildGrantScopeShapePredicate` cannot see it). Each takes the column plus the
230
+ claims; return it straight from `customPredicate` — they deny with `DENY_ALL_PREDICATE`, so the filter
231
+ probes claims-dependent.
232
+ - Two mirror properties: they cover **SELECT only** (write-gate branches stay with the
233
+ INSERT/UPDATE/DELETE policies), and the two surfaces express containment in **different forms on
234
+ purpose** — RLS emits `= ANY(ARRAY(select …))` for the InitPlan/index-scan discipline, the read half a
235
+ first-class `p.in` over a `p.subquery` the engine maintains incrementally and shares between shapes. (A
236
+ grant set lives in the JWT, not a table, so that mirror is an `OR` of equalities instead.)
231
237
 
232
238
  Give drizzle-kit `entities: { roles: { provider: "supabase" } }` in `drizzle.config.ts` so the Supabase roles
233
239
  (`authenticated`/`anon`/`service_role`/…) are treated as externally managed — referenced in a policy's `to:`,
@@ -287,12 +293,12 @@ assertReadContractPreserved(authoritativeRegistry, teacherRegistry, { label: "te
287
293
  assertReadContractPreserved(authoritativeRegistry, learnerRegistry, { label: "learner" });
288
294
  ```
289
295
 
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).
296
+ - **Run the server (apply function + control plane) off the authoritative registry** — the generated apply
297
+ function emits a branch per table and stamps managed fields / reject-if-stale from the entry's write
298
+ contract, so it must see the writable entry. A claims-branching `customPredicate` then serves every client.
299
+ - A projection may differ **only** in write capability and lifecycle (`subscription`/`retention`/group), never
300
+ in the read contract — `assertReadContractPreserved` enforces it (it cannot see the `customPredicate` body,
301
+ so bump `rowFilter.revision` on a logic change).
296
302
  - The full registry fingerprint differs between the writable and readonly variants — expected and fine:
297
303
  it is client-local (guards each client's own store rebuild) and the server never sees it.
298
304
 
@@ -309,54 +315,43 @@ export const assessmentDefinition = defineSyncTable({ tableName: "assessment_def
309
315
  export const assessmentDefinitionAdminSummary = defineReadProjection(assessmentDefinition, {
310
316
  as: "assessment_definition_admin_summary", // distinct local table + shapeKey
311
317
  columns: ["offeringId", "assessmentType", "title", "state"], // typed subset of owner keys; PK always kept
312
- rowFilter: (c) => ({ customWhere: adminOrgFilter(c.offeringId), revision: "admin-summary-1" }),
318
+ rowFilter: (c) => ({ customPredicate: adminOrgFilter(c.offeringId), revision: "admin-summary-1" }),
313
319
  });
314
320
  ```
315
321
 
316
322
  - It **owns no table**: its `table` IS the owner's, so nothing new is migrated and nothing leaks into a
317
323
  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.
324
+ - `columns` is a typed subset of the owner's keys; the local table carries the owner's real per-column types
325
+ restricted to those keys, so a row typechecks by property key with no casts. The PK is always kept **at
326
+ runtime** but the type is a safe **under-claim** — list a PK column in `columns` to read it typed. The
327
+ subset becomes the shape's **emitted** column set, so an omitted (heavy) column is **never streamed**.
328
+ - The physical table is **derived** from the owner — you never name a source string. The `rowFilter`
329
+ callback receives the OWNER's full columns: the engine matches on columns the shape does not emit, so the
330
+ predicate may reference a column the subset omits.
331
+ - It is **readonly**; register it under its own key in the authoritative registry and in the reading client's.
332
+ RLS for its reads lives on the **owner** (a projection adds no DDL), so its `customPredicate` must be a
333
+ subset of what that RLS allows. The control plane resolves each shape by `shapeKey`, so owner and
334
+ projection coexist over one physical table.
335
+
336
+ ### Redacting projection: keep the secret out of the row, not out of the response
337
+
338
+ **Prefer redacting in Postgres.** Model a "window" over a keyed table as SCHEMA where you can: compute the
339
+ redacted value into its own column (generated or trigger-maintained), sync THAT, and split the projections by
340
+ predicate on the control flag — the flag never reaches the client and the raw value never enters storage.
341
+
342
+ `serverProjection` (an egress `rowTransform`) is the escape hatch when the decision is per-row and cannot be
343
+ pre-computed. It runs **at the stream edge**, per request: the edge rewrites every row of the JSON long-poll
344
+ body, then strips each row to the client keep-set — which takes `serverOnlyColumns` (fetched so the transform
345
+ can read them) off the wire. Costs, confined to shapes that declare one: `claims` are `{ sub }` only (richer
346
+ claims belong in `rowFilter.customPredicate`); the shape is private-tier (`scope` + `rowTransform` is refused)
347
+ and answered `cache-control: private, no-store`; JSON long-poll only — an SSE read gets `406`.
348
+
349
+ Guards fire at definition time: `serverOnlyColumns` requires BOTH `serverProjection.rowTransform` and
350
+ `columns`, disjoint from `columns` and the PK. **No inheritance — enforced:** `defineReadProjection` THROWS
351
+ when the owner declares a `rowTransform` unless the projection states its own (usually the same fn, plus
352
+ `serverOnlyColumns` for its control flags) or opts out with the literal `serverProjection: "unredacted"` —
353
+ only after confirming the kept columns leak nothing. `"unredacted"` over a transform-less owner is itself
354
+ rejected, so a stale opt-out cannot pre-authorize a leak the owner gains later.
360
355
 
361
356
  ## Classify rows and assert registry invariants (ADR-0052)
362
357
 
@@ -374,9 +369,9 @@ assertRegistryInvariant(registry, {
374
369
  name: "team-scoped rows are invisible to an anonymous caller",
375
370
  appliesTo: ["team-scoped"], // classes (or a predicate); an undeclared class / zero matches throws
376
371
  claimsFixtures: { anonymous: {}, member: { sub: memberId }, admin: adminClaims },
377
- holds: ({ fixtureName, renderedWhere, renderedPolicies }) =>
372
+ holds: ({ fixtureName, readPredicate, renderedPolicies }) =>
378
373
  fixtureName !== "anonymous" ||
379
- (renderedWhere?.where === "false" && renderedPolicies.every((p) => p.using !== "true")) ||
374
+ (deniesAllRows(readPredicate) && renderedPolicies.every((policy) => policy.using !== "true")) ||
380
375
  "anonymous is not denied on one of the two surfaces", // reported as `entry (fixture): reason`
381
376
  });
382
377
  ```
@@ -384,13 +379,14 @@ assertRegistryInvariant(registry, {
384
379
  So a table added next month cannot inherit the obligation invisibly (omit `rowClasses` and `rowClass` is
385
380
  unconstrained, as the bare registry-map form always is). Projections carry the class (`asReadonly`,
386
381
  `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.
382
+ RESOLVED artifacts — `readPredicate` is the entry's `customPredicate` output for those claims, exactly what
383
+ the control plane compiles into the shape (`null` = unfiltered), `renderedPolicies` the table's RLS as inline
384
+ SQL — so one predicate covers both surfaces and ALL failing cells aggregate into one error. Match on STRUCTURE
385
+ (`deniesAllRows`, the `isXPredicate` guards), never a rendered string. `rowClass` is authoring metadata,
386
+ deliberately in NEITHER fingerprint (classifying never wipes a cache); the **lock** carries it, so losing a
387
+ class is a `risky` diff. It complements `RowFilterSpec.revision`: only `revision` makes a `customPredicate`
388
+ logic change move the fingerprint (rebuilding the cache, resetting the subscription), while the assertion
389
+ renders that logic — for the fixtures you hand it, and no others.
394
390
 
395
391
  ## Storage declaration: `storage.backend` and `storage.durability` (browser stores)
396
392
 
@@ -413,18 +409,21 @@ It scopes the **browser** store only; Node mints stay `file://` and export clone
413
409
 
414
410
  ## Consistency groups: scope them to the joined cluster
415
411
 
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:
412
+ `consistencyGroup` binds tables into one subscription that commits **atomically at boot and catch-up
413
+ alignment** — a reader never sees one grouped table advanced past another for a transaction the group caught
414
+ up on. Each member is its own stream; the group commits when **every** member's most recent response asserted
415
+ up-to-date (offsets are per-stream, so the gate is that predicate, plus the engine barrier on each alignment
416
+ generation's first commit). Live deliveries commit per response, so two halves of one transaction can land a
417
+ few milliseconds apart — a documented window (backlog 0014), not a guarantee. Default is none — a per-table
418
+ singleton committing on its own. Three scoping rules:
419
419
 
420
420
  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
421
+ rendered joined (FK parent + children); that is what the atomic commit protects. If the app otherwise
422
422
  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.
423
+ 2. **Quiet members are affordable.** Every `204` long-poll timeout re-asserts up-to-date, so a rarely-written
424
+ reference table never holds its group behind a stale watermark — keep lookup tables in their natural group.
425
+ 3. **Don't group "everything".** A group commits at the pace of its slowest member; unrelated clusters go
426
+ in separate groups or stay singletons.
428
427
 
429
428
  All members of a group must agree on `subscription`, `retention`, `writeMode` (or the registry rejects it).
430
429
 
@@ -478,8 +477,9 @@ export const registry = defineSyncRegistry({
478
477
  - Trying to write an `omitColumns` (server-only) column from a client payload — the write route
479
478
  **400-rejects** it (an unknown typo is instead silently dropped, surfaced by a per-process `console.warn`);
480
479
  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.
480
+ - In a `customPredicate`: returning `null` for "no claim" (that is _every row_ — return `DENY_ALL_PREDICATE`),
481
+ a `rowFilter` that restricts nothing (throws), a correlated `p.subquery`, or SQL text where a `p.*` builder
482
+ 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/>.