@pgxsinkit/server 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.
@@ -33,7 +33,7 @@ export declare function resolveApplyFunctionSchema(functionSchema: string | unde
33
33
  * (ADR-0018). It is a hash of the exact generated DDL body, so it shifts on any registry-shape
34
34
  * change AND on any change to how the applier emits SQL (e.g. a @pgxsinkit/server upgrade) — the
35
35
  * two drift classes a bare signature check cannot see. It does NOT depend on TS-side row-filter /
36
- * customWhere logic, which never enters the apply function (that shapes the read proxy, not writes).
36
+ * customPredicate logic, which never enters the apply function (that shapes reads, not writes).
37
37
  */
38
38
  export declare function expectedApplyFingerprint(registry: SyncTableRegistry, options?: ApplyFunctionRenderOptions): string;
39
39
  export declare function buildPlpgsqlBatchFunctionDdl(registry: SyncTableRegistry, options?: ApplyFunctionRenderOptions): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pgxsinkit/server",
3
- "version": "0.2.6",
3
+ "version": "0.3.0",
4
4
  "keywords": [
5
5
  "tanstack-intent"
6
6
  ],
@@ -31,7 +31,7 @@
31
31
  "build": "bun --cwd ../.. run build:public-packages"
32
32
  },
33
33
  "dependencies": {
34
- "@pgxsinkit/contracts": "0.2.6"
34
+ "@pgxsinkit/contracts": "0.3.0"
35
35
  },
36
36
  "peerDependencies": {
37
37
  "drizzle-orm": "1.0.0-rc.4"
@@ -1,21 +1,21 @@
1
1
  ---
2
2
  name: deploying
3
3
  description: >-
4
- Load when deploying the @pgxsinkit/server write API and Electric shape proxy onto Bun, Deno, Supabase
5
- Edge Functions, or Cloudflare Workers. Covers the runtime-portable fetch handler, the three steps a
6
- non-Bun edge runtime needs (bundle for Deno with node: builtins, strip the function-name path prefix,
7
- resolve claims in resolveAuthClaims), the deny-by-default apply-function ACL and --grant-execute-to
8
- (ADR-0054), splitting write and sync into two functions, setting the worker
9
- timeout above Electric's ~25s long-poll, and cache-control:no-store on a same-origin shape proxy. Also
10
- covers the Event lane (ADR-0053): the auto-mounted /api/events route, the eventGate hook, the pgmq
11
- prerequisite and pgxsinkit-generate --events queue DDL, and the consumer runner (defineEventConsumer) as a
12
- long-lived Bun process never deployed serverless — plus its bounded drainOnce mode for platforms with no
13
- long-lived compute (scheduled invocation + onEventsEnqueued nudge). Load before deploying the server or
14
- running an event consumer.
4
+ Load when deploying the @pgxsinkit/server write API, the read path's control plane, and the stream
5
+ edge onto Bun, Deno, Supabase Edge Functions, or Cloudflare Workers. Covers the runtime-portable
6
+ fetch handler, the three steps a non-Bun edge runtime needs (bundle for Deno with node: builtins,
7
+ strip the function-name path prefix, resolve claims in resolveAuthClaims), the deny-by-default
8
+ apply-function ACL and --grant-execute-to (ADR-0054), and splitting write, control plane, and edge
9
+ into three functions — the edge on its own origin, because the cache key is the URL (ADR-0055), plus
10
+ the Access-Control-Expose-Headers that mount must set or the client hot-loops.
11
+ Also covers the Event lane (ADR-0053): the /api/events route, the eventGate hook, the pgmq
12
+ prerequisite and pgxsinkit-generate --events queue DDL, and defineEventConsumer as a long-lived Bun
13
+ process never deployed serverless — plus its bounded drainOnce mode for platforms with no
14
+ long-lived compute (scheduled invocation + onEventsEnqueued nudge).
15
15
  metadata:
16
16
  type: task
17
17
  library: "@pgxsinkit/server"
18
- library_version: "0.2.6"
18
+ library_version: "0.3.0"
19
19
  source: https://pgxsinkit.github.io/start/deploying-the-server/
20
20
  ---
21
21
 
@@ -50,28 +50,59 @@ Deno.serve((request) => {
50
50
  });
51
51
  ```
52
52
 
53
- The **read** path needs no rewrite: `proxyElectricShapeRequest` keys off the query string, not the path.
53
+ Both read functions need the same strip: the control plane routes on `/sync/v1/*` and the edge on
54
+ `/v1/stream/*`, so each needs its own function-name prefix removed before the path is recognized.
54
55
 
55
56
  ## 3. Resolve claims from the platform JWT in `resolveAuthClaims`
56
57
 
57
58
  `verify_jwt` is a gateway concept; the portable move is to verify the token yourself and return its
58
- claims (or `null` to fail closed — the proxy then blocks all rows and the write route rejects). A GoTrue
59
- access token is already `JwtClaims`-shaped (`sub`, top-level `role`, `app_metadata`), so return it
60
- directly after verifying. The applier reads `role` to switch the RLS actor; the read proxy reads `sub` +
61
- `app_metadata.roles` for the row filter. Both paths share this one adapter, so authorization cannot
62
- drift.
59
+ claims (or `null` to fail closed — the write route rejects, and the control plane answers **401**). A
60
+ GoTrue access token is already `JwtClaims`-shaped (`sub`, top-level `role`, `app_metadata`), so return it
61
+ directly after verifying. The applier reads `role` to switch the RLS actor; the control plane reads `sub`
63
62
 
64
- ## Read vs write as two functions (a deployment choice)
63
+ - `app_metadata.roles` to build the row filter and to bind the minted stream token to that subject. Both
64
+ paths share this one adapter, so authorization cannot drift.
65
65
 
66
- - **write** — `createSyncServer({ registry, db, resolveAuthClaims })` **without** `electricUrl` registers
67
- only the mutation route; wrap with the path rewrite above.
68
- - **sync** — call `proxyElectricShapeRequest(request, claims, { registry, electricUrl })` directly. No
69
- rewrite. **Set the function's idle/wall-clock timeout above Electric's bounded long-poll (~25s)** so a
70
- live subscription is not recycled mid-cycle. If it is a **same-origin proxy with no CDN**, force
71
- `cache-control: no-store` on the response, or a rotated shape handle serves stale and the client loops
72
- on 409s.
66
+ **Return `null`, never a claims object with no `sub`.** Unauthenticated is not a denial: a subscriber told
67
+ "not entitled" truncates its scope and unsubscribes, so an expired JWT has to present as a retryable 401
68
+ and not as a per-subscription refusal. The control plane enforces this — it 401s when `resolveAuthClaims`
69
+ yields no `sub` — because a stream token with no subject would name a bearer that no revocation reaches.
70
+
71
+ ## Three functions: write, control plane, edge
73
72
 
74
- Both import the same registry and share `resolveAuthClaims`, which keeps the two ingress points honest.
73
+ - **write** — `createSyncServer({ registry, db, resolveAuthClaims })` **without** `readPath` registers
74
+ only the mutation route; wrap with the path rewrite above.
75
+ - **control plane** (`sync`) — `createSyncServer({ registry, resolveAuthClaims, readPath: { engine, key } })`
76
+ serves `/sync/v1/subscribe`, `/sync/v1/refresh`, `/sync/v1/release` (a closing subscription hands its
77
+ engine shape claims back), and `/sync/v1/barrier`. It answers per-subject
78
+ questions and mints stream tokens, so it is **never cacheable**: force `cache-control: no-store`. Its
79
+ upstream is the Circuits engine's control API, which must not be client-reachable.
80
+ - **edge** (`stream`) — `createStreamGate({ key, registry, durableStreamsUrl })` mounted at `/v1/stream`.
81
+ It needs **no claims resolver and no database**: the stream token IS the authorization, which is what
82
+ lets this half scale and cache independently. It does need the same `registry` the control plane uses —
83
+ that is how it knows which shapes declare a `serverProjection.rowTransform` and must be rewritten per
84
+ read (answered `private, no-store`, JSON long-poll only); every other shape is proxied untouched.
85
+
86
+ **Put the edge on its own origin.** The cache key is the URL, so the surface a CDN may share between
87
+ subscribers has to be addressable apart from the one that answers per-subject questions. Same-origin
88
+ mounting forecloses ever putting a CDN in front of the shared tier without also caching the private one.
89
+
90
+ **Because it is a separate origin, the edge mount MUST expose the stream headers:
91
+ `Access-Control-Expose-Headers: <STREAM_READ_EXPOSED_HEADERS>` on the actual (non-preflight) response.**
92
+ Export that constant from `@pgxsinkit/server` and join it — do not retype the list. CORS lets script read
93
+ only a short safelist of response headers, and every header durable-streams answers with is outside it, so
94
+ a cross-origin browser gets a response whose stream headers are simply _not there_. The ds client steers
95
+ its whole read loop off them (`Stream-Next-Offset`, `Stream-Cursor`, `Stream-Closed`,
96
+ `Stream-Up-To-Date`), so stripped of them it never learns an offset, never switches to a live long poll,
97
+ and re-requests `offset=-1` in a hot loop — hundreds of requests per second per shape, with no error
98
+ raised on either side. `createStreamGate` cannot do this for you: it forwards the upstream response's
99
+ headers, and an exposure list means nothing without the `Access-Control-Allow-Origin` decision that only
100
+ the mount makes. **Do not rely on the gateway.** A permissive `expose_headers: "*"` at istio/envoy makes
101
+ the mount look correct behind that one deployment and hot-loop everywhere else.
102
+
103
+ The control plane and the edge share the stream-token signing key, and nothing else. Both read functions
104
+ import the same registry as the write function and share `resolveAuthClaims`, which keeps the ingress
105
+ points honest.
75
106
 
76
107
  ## The apply function verifies itself; the `deployment` profile tunes startup (ADR-0030)
77
108
 
@@ -282,8 +313,9 @@ const { delivered, deadLettered, empty } = await consumer.drainOnce({ budgetMs:
282
313
  per request: the mutation route reports `preTxMs` (parse/validation), `txOpenMs` (the driver's LAZY
283
314
  connection establishment + BEGIN — invisible to every other timer, and where a serverless worker's
284
315
  connect cost lands), `authMs` (resolveAuthClaims), `applyMs` (the apply call), `totalMs`, and `status`;
285
- the shape proxy reports `table`/`live`/`offset`, `upstreamMs` (the Electric fetch — for live long-polls,
286
- the hold), and `totalMs`. Pair it with the client's `__pgxsinkitDebug` rail (`operating` skill,
316
+ the event route reports its own ingest phases. The read path emits no timing line — the control plane is
317
+ a short per-subscribe call and the edge is a byte proxy, so their cost is visible as routing latency
318
+ rather than as phases. Pair it with the client's `__pgxsinkitDebug` rail (`operating` skill,
287
319
  `@pgxsinkit/client`): client-observed minus server `totalMs` is routing + network, and the phase fields
288
320
  attribute the rest. Read the split BEFORE changing anything — every latency class below was found this way.
289
321
 
@@ -300,13 +332,14 @@ unaffected because the preflight responses echo requested headers). The long hop
300
332
  client→function, instead of per statement — measured: function `totalMs` 3,050 → 191.
301
333
 
302
334
  The pin is **per-function, and only right for DB-bound ones.** The mutation ingress (`board-write`) is
303
- DB-bound and wins from it. A **read proxy** (`board-sync`) is NOT: its upstream is Electric Cloud's
304
- globally-distributed CDN, so pinning it to the database's region drags every catch-up hop away from a
305
- distant caller — ~2 intercontinental round trips (~1.2s) versus ~300ms unpinned near the caller, while
306
- the function itself is lean (`totalMs − upstreamMs` ≈ 2–3ms). So keep read proxies **unpinned** (follow
307
- the caller) and put the region header in `writeRequestHeaders`, never the shared `requestHeaders`.
308
-
309
- A browser also opens **one long-poll connection per synced shape**, so over HTTP/1.1 the ~6-per-origin
335
+ DB-bound and wins from it. The read halves are NOT: the control plane's upstream is the engine and the
336
+ edge's is durable-streams, neither of which is the database, and the edge in particular wants to sit near
337
+ the CALLER so catch-up bytes take the short hop. So put the region header in `writeRequestHeaders`, never
338
+ the shared `requestHeaders`, and leave the read functions following the caller. (The Electric-era numbers
339
+ that used to sit here measured a CDN-fronted shape proxy and do not transfer — measure this topology
340
+ before tuning it.)
341
+
342
+ A browser also opens **one live connection per synced stream**, so over HTTP/1.1 the ~6-per-origin
310
343
  cap starves writes — serve the gateway over **HTTP/2**. The JWKS/warming recipe and the connection-budget
311
344
  detail live in the `operating` skill.
312
345
 
@@ -348,7 +381,10 @@ detail live in the `operating` skill.
348
381
  - Shipping toolkit source to Deno without bundling, or leaving builtins un-prefixed (not `node:*`).
349
382
  - Forgetting to strip the function-name prefix, so `/write/api/mutations` 404s.
350
383
  - Verifying the JWT only at the gateway instead of in `resolveAuthClaims` (non-portable).
351
- - A sync function timeout below Electric's ~25s long-poll (constant read-path reconnects).
352
- - Omitting `cache-control: no-store` on a same-origin shape proxy.
384
+ - Mounting the edge on the control plane's origin, so the cacheable and uncacheable surfaces share a
385
+ cache key.
386
+ - Omitting `cache-control: no-store` on the control plane.
387
+ - Returning a claims object with no `sub` instead of `null`, turning an expired JWT into a scope
388
+ truncation instead of a retryable 401.
353
389
 
354
390
  Full prose: <https://pgxsinkit.github.io/start/deploying-the-server/>.
@@ -0,0 +1,301 @@
1
+ import { getTableConfig } from "drizzle-orm/pg-core";
2
+
3
+ import {
4
+ conjoinPredicates,
5
+ DENY_ALL_PREDICATE,
6
+ isAndPredicate,
7
+ isIsNullPredicate,
8
+ isLeafPredicate,
9
+ readShapeTier,
10
+ type JwtClaims,
11
+ type Predicate,
12
+ type PredicateValue,
13
+ type ShapeSpec,
14
+ type SyncTableEntry,
15
+ type SyncTableRegistry,
16
+ } from "@pgxsinkit/contracts";
17
+
18
+ import type { CreateShapeRequest } from "./wire";
19
+
20
+ /** What a client asks the control plane for: a declared shape, plus the inputs its tier consumes. */
21
+ export interface ShapeRequest {
22
+ /** The shape's unique identity, exactly as declared. Never a table name the client chose. */
23
+ shapeKey: string;
24
+ /** Verified claims. The private tier's only subject input; the shared tier never sees them. */
25
+ claims: JwtClaims | null;
26
+ /**
27
+ * SHARED TIER — the scope values, positionally matching the shape's declared `scope` columns.
28
+ * `null` is a legal value and compiles to `IS NULL`, so an absent element and a null one are
29
+ * different things: arity is checked strictly rather than padded.
30
+ */
31
+ scope?: readonly PredicateValue[];
32
+ /** Deployment-supplied runtime params, handed to `rowFilter.customPredicate` as its second argument. */
33
+ params?: Record<string, unknown>;
34
+ }
35
+
36
+ /**
37
+ * The outcome of compiling a request. A denial is a first-class result rather than an exception
38
+ * because it is an ordinary, expected outcome — an anonymous caller, a subject with no membership —
39
+ * and because the caller's response to it (no handle, no shape, 403) is the same for every reason.
40
+ */
41
+ export type CompiledShapeRequest =
42
+ | { outcome: "create"; tier: "shared" | "private"; request: CreateShapeRequest }
43
+ | { outcome: "deny"; reason: string };
44
+
45
+ /**
46
+ * Resolve the entry a request selects by its **`shapeKey`** — not by table name, since several
47
+ * shapes (a read projection and its owner) legitimately read one physical table under distinct keys.
48
+ * Schema qualification is significant. Returns undefined when nothing declares that key, and the
49
+ * caller fails closed.
50
+ */
51
+ export function resolveEntryByShapeKey(registry: SyncTableRegistry, shapeKey: string): SyncTableEntry | undefined {
52
+ return Object.values(registry).find((entry) => entry?.shape?.shapeKey === shapeKey);
53
+ }
54
+
55
+ /**
56
+ * The physical table the engine reads.
57
+ *
58
+ * Circuits introspects `information_schema` with `table_schema = 'public'` and keys its tables by
59
+ * bare name, so a schema-qualified registry target has no engine-side spelling. Rather than send a
60
+ * name that would 404 deep inside shape creation, refuse here with the reason — a real limitation of
61
+ * the engine, tracked against the fork, not something the control plane can paper over.
62
+ */
63
+ function resolveShapeTarget(shape: ShapeSpec): { table: string } | { refusal: string } {
64
+ const target = shape.physicalTable ?? shape.tableName;
65
+ if (!target.includes(".")) return { table: target };
66
+ const [schema] = target.split(".");
67
+ if (schema === "public") return { table: target.slice("public.".length) };
68
+ return {
69
+ refusal:
70
+ `shape "${shape.shapeKey}" reads "${target}", but the engine introspects the public schema ` +
71
+ `only and names tables bare — a non-public target has no shape it can be created under.`,
72
+ };
73
+ }
74
+
75
+ /**
76
+ * The columns the ENGINE emits onto the stream, or undefined for the whole row.
77
+ *
78
+ * Not the same set as the columns the CLIENT receives, and the difference is load-bearing. Read off
79
+ * `shape.rowFilter.columns` when the registry declares one — which for a read projection is the
80
+ * client keep-set PLUS its `serverOnlyColumns` — otherwise off `localTable`, so a shape with no
81
+ * allow-list emits exactly what the local schema declares.
82
+ *
83
+ * `serverOnlyColumns` therefore ARE emitted by the engine, deliberately: an egress
84
+ * `serverProjection.rowTransform` has to READ them, and the engine is the only thing that can fetch
85
+ * them. They come off the wire at the stream edge, which strips every rewritten row back to the local
86
+ * table's columns AFTER the transform has run (`createStreamGate`, ADR-0055 decision 5). So the
87
+ * ordering hazard between rewriting and omission is ANSWERED — transform first, strip second, in one
88
+ * place — rather than dissolved: this function must not "helpfully" narrow the allow-list to the
89
+ * client keep-set, because that would starve the transform of its inputs and fail it open.
90
+ */
91
+ function emittedColumns(entry: SyncTableEntry): string[] | undefined {
92
+ const explicit = entry.shape?.rowFilter?.columns;
93
+ if (explicit != null && explicit.length > 0) return [...explicit];
94
+ if (entry.clientProjection?.omitColumns == null) return undefined;
95
+ return getTableConfig(entry.localTable).columns.map((column) => column.name);
96
+ }
97
+
98
+ /**
99
+ * Compile a shape request into the engine's `POST /shapes` body, or a denial.
100
+ *
101
+ * The whole predicate is built here, in the control plane, from the registry — nothing predicate
102
+ * shaped arrives on the wire. That is strictly stronger than the proxy's "discard the client's
103
+ * `where`": there is no `where` on the wire to discard, so no parameter parsing to get right and no
104
+ * grammar for a client to probe.
105
+ */
106
+ export function compileShapeRequest(registry: SyncTableRegistry, request: ShapeRequest): CompiledShapeRequest {
107
+ const entry = resolveEntryByShapeKey(registry, request.shapeKey);
108
+ const shape = entry?.shape;
109
+ if (entry == null || shape == null) {
110
+ return { outcome: "deny", reason: `no shape declares shapeKey "${request.shapeKey}"` };
111
+ }
112
+
113
+ const target = resolveShapeTarget(shape);
114
+ if ("refusal" in target) return { outcome: "deny", reason: target.refusal };
115
+
116
+ const tier = readShapeTier(shape);
117
+ const subject =
118
+ tier === "shared" ? scopePredicate(shape, request.scope) : privatePredicate(shape, request.claims, request.params);
119
+ if ("refusal" in subject) return { outcome: "deny", reason: subject.refusal };
120
+
121
+ const where = conjoinPredicates(subject.predicate, shape.where);
122
+
123
+ const narrowing = assertLocalPrimaryKeyIsPinned(entry, where);
124
+ if (narrowing != null) return { outcome: "deny", reason: narrowing };
125
+
126
+ const columns = emittedColumns(entry);
127
+
128
+ return {
129
+ outcome: "create",
130
+ tier,
131
+ request: {
132
+ table: target.table,
133
+ ...(where !== undefined ? { where } : {}),
134
+ ...(columns !== undefined ? { columns } : {}),
135
+ },
136
+ };
137
+ }
138
+
139
+ /**
140
+ * The shared tier's predicate: an `AND` of equalities over the declared scope columns, generated —
141
+ * never authored. Every property the tier depends on comes from that generation. Two shapes of a
142
+ * family cannot overlap, because a row carries one value per scope column. Two subscribers holding
143
+ * the same scope values produce byte-identical requests, which is what lets Circuits collapse them
144
+ * onto one stream and what makes the resulting stream cacheable at all.
145
+ */
146
+ function scopePredicate(
147
+ shape: ShapeSpec,
148
+ values: readonly PredicateValue[] | undefined,
149
+ ): { predicate: Predicate | undefined } | { refusal: string } {
150
+ const columns = shape.scope ?? [];
151
+ if (values == null) {
152
+ return { refusal: `shape "${shape.shapeKey}" is shared-tier and requires ${columns.length} scope value(s)` };
153
+ }
154
+ if (values.length !== columns.length) {
155
+ return {
156
+ refusal:
157
+ `shape "${shape.shapeKey}" takes ${columns.length} scope value(s) ` +
158
+ `(${columns.join(", ")}) but got ${values.length}`,
159
+ };
160
+ }
161
+
162
+ const equalities = columns.map((col, index): Predicate => {
163
+ const value = values[index]!;
164
+ // NULL is a scope value like any other, and `col = NULL` is UNKNOWN for every row — so the one
165
+ // that would silently match nothing is the one that has to become `IS NULL`.
166
+ return value === null ? { col, isNull: true } : { col, op: "eq", value };
167
+ });
168
+
169
+ return { predicate: conjoinPredicates(...equalities) };
170
+ }
171
+
172
+ /**
173
+ * Every column pinned to exactly one value by a predicate's **top-level conjunction**.
174
+ *
175
+ * Conservative on purpose: only `col = value` and `col IS NULL` conjuncts pin, and only where they
176
+ * sit in the outermost `AND` chain. A branch under `OR` or `NOT` admits more than one value for its
177
+ * column by construction, and an `IN (subquery)` admits as many as the subquery returns — none of
178
+ * those pin, so none are collected.
179
+ */
180
+ function pinnedColumns(node: Predicate | undefined, into: Set<string> = new Set()): Set<string> {
181
+ if (node == null) return into;
182
+ if (isAndPredicate(node)) {
183
+ for (const child of node.and) pinnedColumns(child, into);
184
+ return into;
185
+ }
186
+ if (isIsNullPredicate(node)) {
187
+ into.add(node.col);
188
+ return into;
189
+ }
190
+ if (isLeafPredicate(node) && node.op === "eq") {
191
+ into.add(node.col);
192
+ }
193
+ return into;
194
+ }
195
+
196
+ /**
197
+ * Refuse a `clientProjection.localPrimaryKey` that narrows the server key without the predicate
198
+ * pinning what it drops.
199
+ *
200
+ * The second of the two checks replacing ADR-0014's primary-key collision tripwire, and the one case
201
+ * where a collision was never machinery at all. Narrowing is the point of `localPrimaryKey` — server
202
+ * key `(owner_id, card_id)` becomes local key `(card_id)` because the caller only ever syncs their
203
+ * own rows — and it is sound *exactly when* the shape's predicate admits one value for every dropped
204
+ * column. Pinned, two server rows can never collapse onto one local key. Unpinned, they can, and the
205
+ * client would silently keep whichever arrived last: under a plain INSERT that surfaced as a PK
206
+ * collision, and under `upsert` it does not surface at all.
207
+ *
208
+ * Checked here rather than at `defineSyncTable` because the predicate is claims-dependent: what pins
209
+ * `owner_id` is the subject fused into it, which does not exist until a real caller subscribes. The
210
+ * refusal is therefore per-subscription, and lands at the same place and in the same form as every
211
+ * other compile denial.
212
+ */
213
+ function assertLocalPrimaryKeyIsPinned(entry: SyncTableEntry, where: Predicate | undefined): string | null {
214
+ const localKey = entry.clientProjection?.localPrimaryKey?.columns;
215
+ if (localKey == null || localKey.length === 0) return null;
216
+
217
+ const localKeySet = new Set<string>(localKey);
218
+ const dropped = entry.primaryKey.columns.filter((column) => !localKeySet.has(column));
219
+ if (dropped.length === 0) return null;
220
+
221
+ const pinned = pinnedColumns(where);
222
+ const unpinned = dropped.filter((column) => !pinned.has(column));
223
+ if (unpinned.length === 0) return null;
224
+
225
+ return (
226
+ `shape "${entry.shape!.shapeKey}" declares clientProjection.localPrimaryKey ` +
227
+ `(${localKey.join(", ")}), dropping ${unpinned.join(", ")} from the server primary key ` +
228
+ `(${entry.primaryKey.columns.join(", ")}) — but this caller's predicate does not pin ` +
229
+ `${unpinned.length === 1 ? "that column" : "those columns"} to a single value, so two server rows ` +
230
+ `could collapse onto one local key. Pin it with a top-level equality in the shape's rowFilter (or ` +
231
+ `its scope), or widen localPrimaryKey to include it.`
232
+ );
233
+ }
234
+
235
+ /** The private tier's predicate: the registry's own claims-fused filter, or a denial. */
236
+ function privatePredicate(
237
+ shape: ShapeSpec,
238
+ claims: JwtClaims | null,
239
+ params: Record<string, unknown> | undefined,
240
+ ): { predicate: Predicate | undefined } | { refusal: string } {
241
+ const filter = shape.rowFilter?.customPredicate;
242
+ if (filter == null) return { predicate: undefined };
243
+
244
+ const resolved = filter(claims ?? {}, params);
245
+ // Reference identity: a denied subject gets no shape at
246
+ // all rather than an empty one, so nothing is created and nothing has to be torn down later.
247
+ if (resolved === DENY_ALL_PREDICATE) {
248
+ return { refusal: `shape "${shape.shapeKey}" denies this caller` };
249
+ }
250
+ return { predicate: resolved ?? undefined };
251
+ }
252
+
253
+ /**
254
+ * Canonical JSON: object keys sorted, `undefined` members dropped, array order preserved.
255
+ *
256
+ * Emitted as a string directly rather than by rebuilding an object and handing it to
257
+ * `JSON.stringify`, because a rebuilt object's key order is not entirely ours to choose — a JS engine
258
+ * enumerates integer-like keys numerically ahead of insertion order, so a sorted rebuild is only
259
+ * *usually* serialized in the order it was sorted into. Writing the bytes here removes the
260
+ * "usually".
261
+ *
262
+ * Array order IS significant and is kept: `columns` is a projection whose order the engine sees, and
263
+ * an `and`/`or` chain's operand order is part of the predicate as sent.
264
+ */
265
+ function canonicalJson(value: unknown): string {
266
+ if (value === null || typeof value !== "object") return JSON.stringify(value ?? null);
267
+ if (Array.isArray(value)) return `[${value.map((member) => canonicalJson(member ?? null)).join(",")}]`;
268
+ const entries = Object.entries(value as Record<string, unknown>)
269
+ .filter(([, member]) => member !== undefined)
270
+ .sort(([left], [right]) => (left < right ? -1 : 1));
271
+ return `{${entries.map(([key, member]) => `${JSON.stringify(key)}:${canonicalJson(member)}`).join(",")}}`;
272
+ }
273
+
274
+ /**
275
+ * A content fingerprint of a compiled shape request — SHA-256 over its canonical JSON, lowercase hex.
276
+ *
277
+ * CANONICAL because the input is not a literal an author wrote: a predicate reaches here through
278
+ * `rowFilter.customPredicate`, whose closure may assemble `{ col, op, value }` in whatever order its
279
+ * branches happen to take, and `p.and(a, b)` on one path may nest where another flattens. Two
280
+ * compiles that MEAN the same thing must fingerprint the same, or the equality below degrades into a
281
+ * test of how the author's code was written on the day.
282
+ *
283
+ * This is an AUTHORIZATION equality check, not a cache key. Two requests fingerprinting the same are
284
+ * the same shape to the engine — same table, same predicate, same projection — so a subject whose
285
+ * recompiled shape still fingerprints as the one their grant names is still authorized for exactly
286
+ * the stream that grant points at. A collision is therefore not a performance regression, it is an
287
+ * authorization one, which is why this is a cryptographic digest and not a cheap hash.
288
+ *
289
+ * Used by the re-mint path (ADR-0055 decision 6) to re-authorize a private-tier grant against the
290
+ * subject's current claims. Never sent to the engine, which knows nothing about it.
291
+ */
292
+ export async function fingerprintShapeRequest(request: CreateShapeRequest): Promise<string> {
293
+ const canonical = canonicalJson({
294
+ table: request.table,
295
+ where: request.where,
296
+ columns: request.columns,
297
+ changesOnly: request.changesOnly,
298
+ });
299
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical));
300
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
301
+ }