@pgxsinkit/client 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 (153) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +81 -0
  4. package/README.md +11 -3
  5. package/dist/boot-report.d.ts +11 -8
  6. package/dist/boot-report.d.ts.map +1 -1
  7. package/dist/circuits/envelope-to-change.d.ts +39 -0
  8. package/dist/circuits/envelope-to-change.d.ts.map +1 -0
  9. package/dist/circuits/group-sync.d.ts +123 -0
  10. package/dist/circuits/group-sync.d.ts.map +1 -0
  11. package/dist/circuits/shape-group.d.ts +77 -0
  12. package/dist/circuits/shape-group.d.ts.map +1 -0
  13. package/dist/circuits/stream-inbox.d.ts +126 -0
  14. package/dist/circuits/stream-inbox.d.ts.map +1 -0
  15. package/dist/circuits/stream-source.d.ts +96 -0
  16. package/dist/circuits/stream-source.d.ts.map +1 -0
  17. package/dist/circuits/subscription-client.d.ts +143 -0
  18. package/dist/circuits/subscription-client.d.ts.map +1 -0
  19. package/dist/circuits/sync-engine.d.ts +131 -0
  20. package/dist/circuits/sync-engine.d.ts.map +1 -0
  21. package/dist/debug.d.ts +0 -10
  22. package/dist/debug.d.ts.map +1 -1
  23. package/dist/event-lane.d.ts +32 -1
  24. package/dist/event-lane.d.ts.map +1 -1
  25. package/dist/export-data.d.ts +3 -3
  26. package/dist/export-dump.d.ts +9 -9
  27. package/dist/export-dump.d.ts.map +1 -1
  28. package/dist/export-store.d.ts +13 -13
  29. package/dist/index.d.ts +237 -113
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +7037 -6665
  32. package/dist/index.js.map +46 -43
  33. package/dist/local-store.d.ts +1 -1
  34. package/dist/local-store.d.ts.map +1 -1
  35. package/dist/local-tables.d.ts +59 -1
  36. package/dist/local-tables.d.ts.map +1 -1
  37. package/dist/mutation.d.ts +2 -2
  38. package/dist/mutation.d.ts.map +1 -1
  39. package/dist/mutations-api.d.ts.map +1 -1
  40. package/dist/opfs-effects.d.ts +30 -2
  41. package/dist/opfs-effects.d.ts.map +1 -1
  42. package/dist/schema.d.ts +12 -1
  43. package/dist/schema.d.ts.map +1 -1
  44. package/dist/store-boot.d.ts +30 -2
  45. package/dist/store-boot.d.ts.map +1 -1
  46. package/dist/store-build.d.ts +19 -0
  47. package/dist/store-build.d.ts.map +1 -0
  48. package/dist/store-engine.d.ts +22 -0
  49. package/dist/store-engine.d.ts.map +1 -0
  50. package/dist/store-meta.d.ts +29 -3
  51. package/dist/store-meta.d.ts.map +1 -1
  52. package/dist/store-ownership-lock.d.ts +33 -0
  53. package/dist/store-ownership-lock.d.ts.map +1 -0
  54. package/dist/store-path.d.ts +40 -28
  55. package/dist/store-path.d.ts.map +1 -1
  56. package/dist/sync/apply.d.ts +17 -25
  57. package/dist/sync/apply.d.ts.map +1 -1
  58. package/dist/sync/copy.d.ts +84 -8
  59. package/dist/sync/copy.d.ts.map +1 -1
  60. package/dist/sync/drizzle-executor.d.ts +4 -4
  61. package/dist/sync/drizzle-executor.d.ts.map +1 -1
  62. package/dist/sync/fold.d.ts +40 -0
  63. package/dist/sync/fold.d.ts.map +1 -0
  64. package/dist/sync/metadata-tables.d.ts +25 -1
  65. package/dist/sync/metadata-tables.d.ts.map +1 -1
  66. package/dist/sync/subscription-state.d.ts +26 -7
  67. package/dist/sync/subscription-state.d.ts.map +1 -1
  68. package/dist/sync/types.d.ts +9 -129
  69. package/dist/sync/types.d.ts.map +1 -1
  70. package/dist/testing.d.ts +1 -1
  71. package/dist/testing.js +4 -3
  72. package/dist/testing.js.map +4 -4
  73. package/dist/worker/attach-sync-client.d.ts +27 -14
  74. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  75. package/dist/worker/define-sync-worker.d.ts +52 -19
  76. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  77. package/dist/worker/engine-control.d.ts +53 -0
  78. package/dist/worker/engine-control.d.ts.map +1 -1
  79. package/dist/worker/live-query-manager.d.ts +3 -3
  80. package/dist/worker/live-query-manager.d.ts.map +1 -1
  81. package/dist/worker/live-query-params-guard.d.ts +5 -5
  82. package/dist/worker/protocol.d.ts +26 -7
  83. package/dist/worker/protocol.d.ts.map +1 -1
  84. package/package.json +11 -9
  85. package/skills/core/SKILL.md +145 -63
  86. package/skills/operating/SKILL.md +221 -221
  87. package/skills/operating/references/postgres-builds.md +48 -0
  88. package/src/boot-report.ts +13 -12
  89. package/src/circuits/envelope-to-change.ts +211 -0
  90. package/src/circuits/group-sync.ts +1047 -0
  91. package/src/circuits/shape-group.ts +158 -0
  92. package/src/circuits/stream-inbox.ts +225 -0
  93. package/src/circuits/stream-source.ts +191 -0
  94. package/src/circuits/subscription-client.ts +353 -0
  95. package/src/circuits/sync-engine.ts +643 -0
  96. package/src/debug.ts +1 -85
  97. package/src/event-lane.ts +132 -14
  98. package/src/export-data.ts +4 -4
  99. package/src/export-dump.ts +24 -28
  100. package/src/export-store.ts +17 -17
  101. package/src/index.ts +797 -544
  102. package/src/lazy-guard.ts +1 -1
  103. package/src/live-rows-sql.ts +1 -1
  104. package/src/local-store.ts +2 -2
  105. package/src/local-tables.ts +76 -5
  106. package/src/mutation.ts +9 -8
  107. package/src/mutations-api.ts +2 -2
  108. package/src/opfs-effects.ts +74 -10
  109. package/src/schema.ts +126 -29
  110. package/src/store-boot.ts +71 -7
  111. package/src/store-build.ts +37 -0
  112. package/src/store-engine.ts +94 -0
  113. package/src/store-lifecycle.ts +1 -1
  114. package/src/store-meta.ts +155 -4
  115. package/src/store-ownership-lock.ts +109 -0
  116. package/src/store-path.ts +56 -40
  117. package/src/sync/apply.ts +104 -156
  118. package/src/sync/copy.ts +116 -21
  119. package/src/sync/drizzle-executor.ts +13 -14
  120. package/src/sync/fold.ts +94 -0
  121. package/src/sync/metadata-tables.ts +43 -2
  122. package/src/sync/subscription-state.ts +28 -10
  123. package/src/sync/types.ts +13 -141
  124. package/src/testing.ts +4 -4
  125. package/src/worker/attach-sync-client.ts +150 -57
  126. package/src/worker/define-sync-worker.ts +325 -87
  127. package/src/worker/engine-control.ts +89 -0
  128. package/src/worker/engine-router.ts +1 -1
  129. package/src/worker/live-query-fingerprint.ts +4 -4
  130. package/src/worker/live-query-manager.ts +12 -12
  131. package/src/worker/live-query-params-guard.ts +10 -10
  132. package/src/worker/protocol.ts +38 -7
  133. package/dist/read-stream-stall.d.ts +0 -54
  134. package/dist/read-stream-stall.d.ts.map +0 -1
  135. package/dist/shape-sync.d.ts +0 -207
  136. package/dist/shape-sync.d.ts.map +0 -1
  137. package/dist/sync/index.d.ts +0 -32
  138. package/dist/sync/index.d.ts.map +0 -1
  139. package/dist/sync/nudge.d.ts +0 -49
  140. package/dist/sync/nudge.d.ts.map +0 -1
  141. package/dist/sync/shape-inbox.d.ts +0 -215
  142. package/dist/sync/shape-inbox.d.ts.map +0 -1
  143. package/dist/sync/tags.d.ts +0 -142
  144. package/dist/sync/tags.d.ts.map +0 -1
  145. package/dist/sync-auth.d.ts +0 -53
  146. package/dist/sync-auth.d.ts.map +0 -1
  147. package/src/read-stream-stall.ts +0 -102
  148. package/src/shape-sync.ts +0 -533
  149. package/src/sync/index.ts +0 -1124
  150. package/src/sync/nudge.ts +0 -110
  151. package/src/sync/shape-inbox.ts +0 -566
  152. package/src/sync/tags.ts +0 -390
  153. package/src/sync-auth.ts +0 -117
@@ -1,34 +1,38 @@
1
1
  ---
2
2
  name: core
3
3
  description: >-
4
- Load when writing or reviewing code that uses @pgxsinkit/* (client, server, contracts, react) — the
5
- offline-first sync toolkit for the Postgres -> ElectricSQL -> PGlite read path and the client -> write
6
- API -> Postgres write path. Teaches the mental model the source does not make obvious: the two sync
7
- paths are separate and asymmetric, there is exactly one write path (an in-database apply function, not
8
- per-table CRUD), a third non-sync Event lane carries append-only facts, the Electric subquery flag is
9
- mandatory and fails closed, local PGlite schema is not full DDL parity, writable tables must declare a
10
- conflict policy plus managed fields, ordinary writes self-activate their lazy group, and authenticated
11
- groups must not activate before claims exist. Load this before wiring sync, defining a registry, adding
12
- an Event stream, or debugging "writes don't appear" / "an acked write stays pending" / "no rows stream"
13
- / "a removed member still sees rows".
4
+ Load when writing or reviewing code that uses @pgxsinkit/* — the offline-first sync toolkit for the
5
+ Postgres -> Circuits engine -> durable-streams -> pgwasm read path and the client -> write API ->
6
+ Postgres write path. Teaches the model the source does not make obvious: the two sync paths are
7
+ separate and asymmetric, exactly one write path (an in-database apply function, not per-table CRUD), a
8
+ non-sync Event lane carries append-only facts, a client asks the control plane for its streams
9
+ (controlPlaneUrl + streamBaseUrl, both or neither) and reads fail closed twice — 401 control plane, 403
10
+ edge — local pgwasm schema is not full DDL parity, writable tables must declare a conflict policy plus
11
+ managed fields, ordinary writes self-activate their lazy group, and authenticated groups must not
12
+ activate before claims exist. Load before wiring sync, defining a registry, adding an Event stream, or
13
+ debugging "writes don't appear" / "an acked write stays pending" / "no rows stream" / "a removed
14
+ member still sees rows".
14
15
  metadata:
15
16
  type: core
16
17
  library: "@pgxsinkit/client"
17
- library_version: "0.2.7"
18
+ library_version: "0.5.0"
18
19
  source: https://pgxsinkit.github.io/llms-full.txt
19
20
  ---
20
21
 
21
22
  # Using pgxsinkit correctly
22
23
 
23
24
  pgxsinkit is a **toolkit**, not a database, a framework, or the demo app. The `@pgxsinkit/*` packages
24
- are the product: `contracts` (the registry + shared types), `server` (the write API + Electric shape
25
- proxy), `client` (local PGlite store + mutation runtime + convergence), and `react` (hooks). A consumer
26
- installs these and wires them; they do not "run pgxsinkit".
25
+ are the product: `contracts` (the registry + shared types), `server` (the write API, the read path's
26
+ **control plane**, and the **stream edge**), `client` (local pgwasm store + mutation runtime +
27
+ convergence), and `react` (hooks). A consumer installs these and wires them; they do not "run pgxsinkit".
27
28
 
28
29
  ## The one idea everything else follows from: two separate, asymmetric sync paths
29
30
 
30
- - **Read path:** Postgres → ElectricSQL → a server-side shape **proxy** (ownership-filtered) → local
31
- **PGlite**. Reads are served from PGlite.
31
+ - **Read path:** Postgres → the **Circuits engine** (ingests logical replication and maintains the shapes
32
+ the control plane creates) → **durable-streams** → the **edge** (token-gated) → local **pgwasm**. The
33
+ client does not
34
+ construct a stream URL: it subscribes through the **control plane**, which decides which streams that
35
+ subject may read and hands back their paths. Reads are served from the local pgwasm store.
32
36
  - **Write path:** client stages an optimistic local write → flushes a batch to the **write API** → one
33
37
  **in-database apply function** (`pgxsinkit_apply_mutations`) applies it under RLS → Postgres.
34
38
 
@@ -36,10 +40,10 @@ Those two are the **sync rail**, and almost everything below is about it. Beside
36
40
  deliberately non-sync lane — the **Event lane** — for data that was never sync state (see below). So the
37
41
  accurate count is two sync paths plus one event lane, not three paths.
38
42
 
39
- **Writes do not travel back to the writer through Electric.** The loop closes through Postgres: your
40
- write lands in Postgres, then streams back to _every_ subscriber (including you) as a normal Electric
41
- change, which clears the optimistic overlay. Do not look for a write to "come back" on the write
42
- channel, and do not try to write through Electric — Electric is read-only here.
43
+ **Writes do not travel back to the writer on the write channel.** The loop closes through Postgres: your
44
+ write lands in Postgres, then streams back to _every_ subscriber (including you) as an ordinary read-path
45
+ change, which clears the optimistic overlay. Do not look for a write to "come back" on the write channel,
46
+ and do not try to write down the read path — it is read transport only.
43
47
 
44
48
  ## There is exactly one write path
45
49
 
@@ -59,6 +63,48 @@ acked row **retires without a synced echo** (nothing local ever converges for it
59
63
  and throws at enqueue on an optimistic route. Never seed a phantom base row to satisfy `update` for an
60
64
  invisible target — that row + its overlay would linger forever behind the echo barrier; use `updateBlind`.
61
65
 
66
+ **Tables pgxsinkit does not manage are the one exception — and they never converge.** If your app owns a
67
+ LOCAL-ONLY relation the registry knows nothing about (a definition cache, a personal dictionary, a scratch
68
+ index), the write path above does not apply to it: there is no journal row, no overlay and no server to ack
69
+ it. Write it through the inspection surface — `rawExec(sql)` for a one-off, and `rawTransaction(statements)`
70
+ when several statements must land together:
71
+
72
+ ```ts
73
+ // Atomic replace of a local-only cache entry. One local transaction, all-or-nothing, one Results per
74
+ // statement; a throw rolls the whole list back, and `[]` resolves without opening a transaction at all.
75
+ const [, inserted] = await client.rawTransaction([
76
+ { sql: "delete from my_local_cache where key = $1", params: [key] },
77
+ { sql: "insert into my_local_cache (key, body) values ($1, $2) returning key", params: [key, body] },
78
+ ]);
79
+ ```
80
+
81
+ **Bulk-load a chunk with COPY, not an INSERT per row.** A statement may carry the COPY TEXT bytes of a
82
+ `COPY … FROM '/dev/blob'` — the same loader the sync applier uses on synced tables. Build the pair with
83
+ `buildCopyFromBlobStatement` (it renders the statement from the REAL Drizzle table object and serializes the
84
+ rows from ONE column list, so they cannot drift); `json`/`jsonb` values go in **parsed**, with the column's
85
+ `udt_name` in `udtNames`:
86
+
87
+ ```ts
88
+ // 1000 fetched rows → ONE statement, atomically replacing the chunk. `rawQuery(sql, [], { blob })` is the
89
+ // same load with no transaction around it.
90
+ const copy = buildCopyFromBlobStatement({
91
+ table: definitionCache, // a real drizzle pgTable your app owns — never a hand-written name
92
+ columns: ["id", "headword", "entry"],
93
+ rows: chunk, // keyed by DB column name; `entry` is a parsed object, not JSON text
94
+ udtNames: { entry: "jsonb" },
95
+ });
96
+ await client.rawTransaction([{ sql: "delete from definition_cache where id = any($1)", params: [ids] }, copy]);
97
+ // On a worker-attached client `copy.blob` is now DETACHED (transferred, not copied) — serialize a fresh
98
+ // chunk per call; never reuse the buffer.
99
+ ```
100
+
101
+ It is identical on the in-process and worker-attached client — the whole list crosses the bridge in ONE RPC
102
+ and the transaction opens and closes inside the worker — so a tab with no local store of its own gets the same
103
+ atomicity, rather than atomicity depending on where the engine happens to live. What it writes stays local
104
+ and will NEVER converge, so it is never a shortcut for a synced table: those still go through
105
+ `mutate` / `tables.*`. (Create such tables in `prepareLocalDbBeforeSchema` / `prepareLocalDbAfterSchema`, and
106
+ remember a `destroy()` or a backend change takes them with it.)
107
+
62
108
  ## The third lane: Event streams are NOT the write path
63
109
 
64
110
  High-volume, append-only client facts — "viewed this", interaction logs, review grades — are never edited,
@@ -86,10 +132,16 @@ appendEvent() → Outbox (durable, local-only) → flush → POST /api/events
86
132
  - The client-side surfaces are `onOutboxStatus` (drain signal) and `onEventLaneReport` (per-pass verdicts:
87
133
  `acked` / `refused` / `rejected` / `deferred`, of which only `deferred` is non-terminal). Flush cadence
88
134
  and batch caps are client config (`events`), never registry.
135
+ - **Composing a best-guess view? Pending is `acked_at_us IS NULL`, not "the row exists".** `acked` means
136
+ ENQUEUED, not folded — the consumer has not handled it and its result has not synced back down — so a
137
+ composition that drops the event at the ack dips for that whole window. `events.ackedRetentionMs > 0`
138
+ (default `0` = delete on ack) keeps an acked row, stamped, as a grace ledger you count until your own
139
+ synced aggregate accounts for it. A retained row is NOT pending anywhere: not on the drain signal, not
140
+ re-sent, not on `diagnostics()`, not blocking `destroy()`.
89
141
 
90
142
  ## Reading the local store: base table vs overlay view
91
143
 
92
- Reads run against local PGlite through the client, not hand-written SQL. For a **pure-Drizzle** read, pass
144
+ Reads run against the local pgwasm store through the client, not hand-written SQL. For a **pure-Drizzle** read, pass
93
145
  the builder callback directly to `client.query((c) => …)` (the guarded read): pgxsinkit scans the compiled
94
146
  SQL and activates + awaits every `lazy` relation the query touches (FROM, JOIN, subquery, WHERE) before it
95
147
  runs — nothing to declare. `client.query` resolves to the **rows array directly** (not `{ rows }`). Inside
@@ -100,17 +152,18 @@ first-row-or-null variants. (Reactive equivalents: `useLiveDrizzleRows` for pure
100
152
  `useLiveQueryRaw({ use, build })` for raw fragments.)
101
153
 
102
154
  **Auth-gated lazy groups.** A query that references one lazy relation activates its **whole consistency
103
- group** with the claims available to that shape request. If the row filter returns `DENY_ALL` without a
104
- user claim, do not let an authenticated-only query run while auth is unresolved: gate it (`ready: false`
105
- in the React hooks) until the session exists. Making the group eager is not an equivalent fix — it can
106
- open the same anonymous subscription during boot. A later auth notification can rotate/refetch the shape,
107
- but the intended path is to activate it once with the correct claims. Activating a claims-denied group
155
+ group**, subscribing with the claims available at that moment. If the row filter returns
156
+ `DENY_ALL_PREDICATE` without a user claim, do not let an authenticated-only query run while auth is
157
+ unresolved: gate it (`ready: false` in the React hooks) until the session exists. Making the group eager
158
+ is not an equivalent fix — it can open the same anonymous subscription during boot. The control plane
159
+ declines a denied shape outright, so the group settles "ready" with nothing granted and stays empty;
160
+ activate it once with the correct claims instead. Activating a claims-denied group
108
161
  with no auth token now emits a `console.warn` naming the group, so an accidental anonymous activation is
109
162
  visible rather than silent.
110
163
 
111
164
  Writes self-activate. An ordinary optimistic create/update/delete on a lazy `readwrite` entry activates
112
165
  its group automatically at enqueue (a write is a reference, and a reference activates), so the Postgres
113
- commit can echo through Electric and retire the acknowledged journal row — no manual activator query is
166
+ commit can echo down the read path and retire the acknowledged journal row — no manual activator query is
114
167
  needed. Because that activation uses the claims available when the write runs, an authenticated-only group
115
168
  still should not be written before the session exists (gate the write on auth, same as a read).
116
169
  `updateBlind` is the deliberate exception: it has no overlay, does not activate its group, and retires on
@@ -129,7 +182,7 @@ redundant `use` (autofixable), the two things the types can't. (oxlint `jsPlugin
129
182
  (not-yet-synced) writes on top of the synced base rows. Read it from the entry's **`.view`**
130
183
  (`registry.<name>.view`) — **not** its `.table`. Selecting the base `.table` of a readwrite entry
131
184
  silently omits the writer's own pending writes, so a just-issued create/edit/delete will not appear
132
- locally until it round-trips through Postgres and streams back via Electric.
185
+ locally until it round-trips through Postgres and streams back down the read path.
133
186
 
134
187
  ```ts
135
188
  // readonly entry → base table
@@ -140,7 +193,7 @@ const reportView = registry.report.view!; // `.view` is populated only for readw
140
193
  client.query((c) => c.drizzle.select({ id: reportView.id, status: reportView.status }).from(reportView));
141
194
  ```
142
195
 
143
- This is the read-side twin of "writes return through Electric": your optimistic write is visible
196
+ This is the read-side twin of "writes return down the read path": your optimistic write is visible
144
197
  immediately **only because you read the overlay view**; the base table catches up when Postgres streams the
145
198
  committed row back. (`c.views.<name>` is the client's accessor for the same overlay views; the entry's
146
199
  `.view` object is the direct handle. Type note: `.view` is typed as optional on a `SyncTableEntry`, so a
@@ -174,11 +227,10 @@ directly (a test, a perf harness, a diagnostic), not a replacement for it.
174
227
 
175
228
  ## Non-negotiables (each fails closed or throws)
176
229
 
177
- 1. **The Electric subquery flag is mandatory.** Run Electric with
178
- `ELECTRIC_FEATURE_FLAGS=allow_subqueries,tagged_subqueries`. Without it, sync **fails closed** — no
179
- rows stream — which looks like a bug but is a missing flag. On **managed Electric Cloud** the flag is
180
- activated per source by Electric staff on request (no self-serve toggle yet; default-on intended) —
181
- ask Electric to enable subqueries for your source, or self-host Electric with the flag.
230
+ 1. **The read path is two URLs, both or neither.** `createSyncClient` / `defineSyncWorker` take
231
+ `controlPlaneUrl` (subscribe, stream-token re-mint, the convergence barrier) **and** `streamBaseUrl`
232
+ (the edge that serves durable-streams reads). They are separate deployments — the edge belongs on its
233
+ own origin, because the cache key is the URL — so supplying one without the other **throws** at boot.
182
234
  2. **Writable tables have two hard requirements.** `defineSyncRegistry` throws unless every `readwrite`
183
235
  table declares **both** a server-version managed field (a `nowMicroseconds`-on-update column,
184
236
  conventionally `updated_at_us`, that optimistic convergence keys on) **and** a `conflictPolicy`
@@ -187,9 +239,14 @@ directly (a test, a perf harness, a diagnostic), not a replacement for it.
187
239
  3. **Managed fields are server-assigned.** Fields stamped by `authClaim` (a verified claim at a JSON path —
188
240
  `["sub"]` is the old `auth.uid()` owner idiom) / `nowMicroseconds` are set by the apply function; the
189
241
  write API **rejects** a client payload that includes them. Never send them.
190
- 4. **Enum columns in a shape `where` must be cast to `text`** — `"role"::text = 'manager'`, not
191
- `"role" = 'manager'`. The column stays an enum everywhere else. This is because **Electric**, not
192
- Postgres, evaluates the shape filter.
242
+ 4. **Read authorization fails closed in two places, and they mean different things.** The control plane
243
+ answers **401** when the deployment's `resolveAuthClaims` yields no `sub` (the client reports
244
+ `auth-needed` and keeps retrying for a fresh token — an expired JWT is retryable, not a refusal); the
245
+ edge answers **403** for a stream token that expired or names a scope the subject no longer holds — the
246
+ client re-mints once, and a second rejection is read as revocation, so it truncates that scope and
247
+ unsubscribes. A `rowFilter` that restricts nothing —
248
+ no `customPredicate` and no `columns` allow-list — is **refused at definition time** rather than
249
+ quietly compiled into a shape with no subject test.
193
250
 
194
251
  ## Authorization runs in two engines — derive both from one predicate
195
252
 
@@ -198,61 +255,86 @@ engines, so the subject is referenced two ways:
198
255
 
199
256
  - **Write path — RLS in Postgres:** policies use `auth.uid()` / `current_setting('request.jwt.claims')`;
200
257
  the applier sets the claims before applying a batch.
201
- - **Read path — the shape `rowFilter`:** the proxy builds the Electric `where` and **Electric** runs it, so
202
- a `customWhere` returns a Drizzle `SQL` fragment — reference columns through `c()` (bare, as Electric
203
- needs) and bind `claims.sub` as a `$n` param (no hand-escaping); enum cast to `text`; `DENY_ALL` blocks
204
- all rows.
258
+ - **Read path — the shape `rowFilter`:** the **control plane** compiles the filter once, at shape creation,
259
+ and posts it to the engine — so `customPredicate` returns a **predicate AST**, not SQL text. Author it
260
+ with the `p.*` builders over real Drizzle columns (`p.eq`, `p.and`/`p.or`/`p.not`, `p.in` +
261
+ `p.subquery`); `null` bypasses filtering (every row) and `DENY_ALL_PREDICATE` denies. There is no string
262
+ to escape and no grammar to satisfy, and comparisons are checked against the column's own TypeScript
263
+ type — a mistyped enum label or a `jsonb`/`Date` column with no scalar wire form is a compile error.
205
264
 
206
265
  Use `buildSupabaseOwnerOrAdminNativePolicies` / `buildSupabaseMembershipNativePolicies` for the common
207
266
  owner/membership shapes — they take **Drizzle columns**, so call them in `defineSyncTable`'s `extras`
208
267
  callback; compose your own from `pgPolicy` + Drizzle operators for anything beyond them (e.g. collaborative
209
- any-member writes). Build the read filter and the RLS policy from the same Drizzle columns so they cannot
210
- drift.
268
+ any-member writes). Each ships its read-path mirror (`buildOwnerOrAdminShapePredicate`,
269
+ `buildMembershipShapePredicate`, `buildGrantScopeAccessShapePredicate`), so build the read filter and the
270
+ RLS policy from the same Drizzle columns and they cannot drift.
211
271
 
212
272
  ## Membership changes converge the local store — both ways, even offline
213
273
 
214
- A subquery (membership) read filter is reactive in **both** directions, against a running client with no
215
- re-subscribe: granting a membership **materialises** the container's rows in the member's local PGlite;
216
- revoking one **evicts** them (a row reachable through a second membership survives until its last grant is
217
- gone). This holds **live and across an offline gap** — a client disconnected when the membership changed
218
- converges on reconnect (the resume replays it), so a revoked member's read access never lingers offline.
219
- Observe it on the live subscription or a normal resume, not by re-probing a shape at `offset=-1`.
274
+ A subquery (membership) read filter — `p.in(col, p.subquery(…))` — is reactive in **both** directions,
275
+ against a running client with no re-subscribe: granting a membership **materialises** the container's rows
276
+ in the member's local store; revoking one **evicts** them (a row reachable through a second membership
277
+ survives until its last grant is gone). The engine **states** each side rather than implying it: the wire
278
+ carries `upsert | delete`, so a row leaving your shape arrives as an explicit `delete` envelope. This holds
279
+ **live and across an offline gap** — a client disconnected when the membership changed converges on
280
+ reconnect (it resumes from its per-stream offset and replays what it missed), so a revoked member's read
281
+ access never lingers offline. Observe it on the live subscription or a normal resume, not by re-reading a
282
+ stream from the start.
220
283
 
221
- ## Local PGlite schema is not full DDL parity
284
+ ## The local pgwasm schema is not full DDL parity
222
285
 
223
286
  The local store generates enums, tables, the overlay, the journal, and convergence triggers — **not**
224
287
  RLS, arbitrary triggers/functions, or managed-field defaults, and it does not enforce CHECK / FK /
225
288
  UNIQUE the way Postgres does. Treat Postgres as the source of truth for integrity; do not assume a
226
- constraint that holds server-side also holds in PGlite.
289
+ constraint that holds server-side also holds in the local store.
290
+
291
+ **Indexes are opt-in too.** A synced table gets its primary key's index and nothing else — the server's
292
+ indexes are deliberately not mirrored (they serve server loads and often cover projected-away columns).
293
+ A client read that needs an index declares it on the entry as
294
+ `clientProjection.localIndexes: [{ name, columns, unique? }]` (plain btree over projected columns,
295
+ validated at registry-build time). Index what the app actually scans — a due-window over a large synced
296
+ table is the usual first case — and nothing else; every index costs write time on each applied batch.
297
+
298
+ ## What a synced value looks like on the way in
299
+
300
+ The wire carries every non-int/float/bool cell as **Postgres output text** (json, arrays, timestamps,
301
+ uuid, numeric, bytea). The client parses exactly one family of it, once, at the wire boundary: a scalar
302
+ `json`/`jsonb` column becomes a JS value before any apply tier sees it, so the local column holds the
303
+ document — `jsonb_typeof` = `object`, not `string`. Array columns (json arrays included) stay in
304
+ Postgres's array literal and are handed straight back to Postgres. You read objects back out of the local store
305
+ either way; if you ever see a JSON **string** in a `jsonb` column, that is a double-encode bug, not the
306
+ shape of the data.
227
307
 
228
308
  ## Common mistakes
229
309
 
230
- - Expecting an optimistic write to echo back on the write channel — it returns through Electric.
231
- - Forgetting the Electric subquery flag, then debugging "no rows" as a code bug.
310
+ - Expecting an optimistic write to echo back on the write channel — it returns down the read path.
311
+ - Configuring `controlPlaneUrl` without `streamBaseUrl` (or the reverse) — it throws; they are two
312
+ deployments, and the edge belongs on its own origin.
232
313
  - Omitting `conflictPolicy` (throws) or sending a managed field in a write payload (rejected).
233
- - Comparing an enum without `::text` in a shape filter.
314
+ - Declaring a `rowFilter` that restricts nothing (no `customPredicate`, no `columns`) — refused at
315
+ definition time, because the compiled shape would carry no subject test.
234
316
  - Writing directly to Postgres tables / building per-table CRUD instead of using the one write path.
235
317
  - Reading a **readwrite** entry from its base `.table` instead of its `.view` overlay, so your own
236
318
  optimistic writes do not appear locally until they round-trip through Postgres.
237
319
  - Activating an authenticated lazy group before auth resolves — reading OR writing while claims are
238
- unresolved activates the group against anonymous claims (now flagged by a console warning), leaving the
239
- shape empty until a later rotation/refetch.
240
- - Assuming PGlite enforces every Postgres constraint.
320
+ unresolved subscribes against anonymous claims (now flagged by a console warning), and the control plane
321
+ grants nothing, so the group stays empty until it is desynced and referenced again.
322
+ - Assuming the local store enforces every Postgres constraint.
241
323
  - Assuming a revoked member keeps their synced rows offline — membership changes converge both ways,
242
324
  live and on resume.
243
- - Passing a PGlite storage URL (`idb://…`, `memory://…`) as `storePath` — the contract is a plain
325
+ - Passing a storage URL (`idb://…`, `memory://…`) as `storePath` — the contract is a plain
244
326
  name and schemes throw; the backend is derived (ADR-0036).
245
327
 
246
328
  ## Naming the local store
247
329
 
248
- `createSyncClient`/`createClientPGlite` take a **plain `storePath`** (e.g. `"my-app-store"`), never a
330
+ `createSyncClient`/`createPgwasmClient` take a **plain `storePath`** (e.g. `"my-app-store"`), never a
249
331
  storage URL — the backend is derived, not named: a capability-proven browser engine home uses the
250
332
  constant-handle OPFS-repacked backend, fixed worker mode and browser fallbacks use IndexedDB, and bun/Node
251
333
  uses the filesystem; anything containing `://` throws `InvalidStorePathError`. Memory-backed stores are
252
334
  deliberately not expressible in the production API (pgxsinkit's retention + journal durability assume a
253
335
  persisted store): in TESTS, spread `memoryStoreForTests("name")` from `@pgxsinkit/client/testing` into the
254
- options; a caller-owned `pgliteInstance` that is provably non-persistent (a bare `new PGlite()`, or
255
- `memory://`) is refused with `NonPersistentStoreError` unless a testing acknowledgment is spread alongside.
336
+ options; a caller-owned `pgwasmInstance` that is provably non-persistent (a memory store, or a filesystem that
337
+ declares `persistent: false`; a custom filesystem that declares nothing is accepted) is refused with `NonPersistentStoreError` unless a testing acknowledgment is spread alongside.
256
338
  Separately from persistence, the store's flush **timing** is `durability`, declared once on the registry
257
339
  (`storage.durability`, default `"relaxed"`) — never a per-open, per-tab, or minting-surface option. Its
258
340
  physical behavior is backend-specific: idb detaches its whole-snapshot flush, while OPFS-repacked keeps the
@@ -264,8 +346,8 @@ Backups, the SQL exports, and `restoreFrom` are there too.
264
346
 
265
347
  ## Where to look
266
348
 
267
- - Concepts: the two paths, read path, write path, Electric subqueries, local-schema DDL parity, and
268
- timestamps (microsecond BIGINT, decimal strings across the boundary).
349
+ - Concepts: the two paths, read path, write path, local-schema DDL parity, and timestamps (microsecond
350
+ BIGINT, decimal strings across the boundary).
269
351
  - For the Event lane in full — the Outbox, verdicts, backpressure, the delivery contract and the limits —
270
352
  read <https://pgxsinkit.github.io/concepts/event-lane/>, then load the skill for the half you are
271
353
  writing: `operating` (@pgxsinkit/client) for the Outbox surfaces and flush tuning, `deploying`