@pgxsinkit/client 0.1.50 → 0.1.53

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 (54) hide show
  1. package/dist/error-chain.d.ts +9 -0
  2. package/dist/error-chain.d.ts.map +1 -0
  3. package/dist/export-dump.d.ts.map +1 -1
  4. package/dist/index.d.ts +66 -13
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +284 -82
  7. package/dist/index.js.map +21 -19
  8. package/dist/local-tables.d.ts +6 -0
  9. package/dist/local-tables.d.ts.map +1 -1
  10. package/dist/schema.d.ts +18 -1
  11. package/dist/schema.d.ts.map +1 -1
  12. package/dist/shape-sync.d.ts +6 -0
  13. package/dist/shape-sync.d.ts.map +1 -1
  14. package/dist/sync/apply.d.ts +12 -1
  15. package/dist/sync/apply.d.ts.map +1 -1
  16. package/dist/sync/index.d.ts +1 -1
  17. package/dist/sync/index.d.ts.map +1 -1
  18. package/dist/sync/metadata-tables.d.ts +16 -0
  19. package/dist/sync/metadata-tables.d.ts.map +1 -1
  20. package/dist/sync/subscription-state.d.ts +10 -2
  21. package/dist/sync/subscription-state.d.ts.map +1 -1
  22. package/dist/sync/tags.d.ts +16 -4
  23. package/dist/sync/tags.d.ts.map +1 -1
  24. package/dist/sync/types.d.ts +12 -0
  25. package/dist/sync/types.d.ts.map +1 -1
  26. package/dist/worker/attach-sync-client.d.ts +4 -1
  27. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  28. package/dist/worker/define-sync-worker.d.ts +41 -0
  29. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  30. package/dist/worker/live-query-manager.d.ts.map +1 -1
  31. package/dist/worker/live-query-params-guard.d.ts +14 -0
  32. package/dist/worker/live-query-params-guard.d.ts.map +1 -0
  33. package/dist/worker/protocol.d.ts +17 -1
  34. package/dist/worker/protocol.d.ts.map +1 -1
  35. package/package.json +2 -2
  36. package/skills/core/SKILL.md +6 -2
  37. package/skills/operating/SKILL.md +28 -5
  38. package/src/error-chain.ts +26 -0
  39. package/src/export-dump.ts +5 -1
  40. package/src/index.ts +175 -41
  41. package/src/local-tables.ts +7 -0
  42. package/src/schema.ts +22 -4
  43. package/src/shape-sync.ts +11 -0
  44. package/src/sync/apply.ts +164 -26
  45. package/src/sync/index.ts +45 -8
  46. package/src/sync/metadata-tables.ts +41 -0
  47. package/src/sync/subscription-state.ts +29 -4
  48. package/src/sync/tags.ts +34 -9
  49. package/src/sync/types.ts +12 -0
  50. package/src/worker/attach-sync-client.ts +119 -20
  51. package/src/worker/define-sync-worker.ts +112 -2
  52. package/src/worker/live-query-manager.ts +6 -0
  53. package/src/worker/live-query-params-guard.ts +57 -0
  54. package/src/worker/protocol.ts +28 -0
@@ -13,7 +13,7 @@ description: >-
13
13
  metadata:
14
14
  type: task
15
15
  library: "@pgxsinkit/client"
16
- library_version: "0.1.50"
16
+ library_version: "0.1.53"
17
17
  source: https://pgxsinkit.github.io/start/operating-in-production/
18
18
  ---
19
19
 
@@ -108,10 +108,17 @@ main-thread) — so worker mode is never a hard dependency.
108
108
  **Two-file pattern.** A worker entry (bundled as a worker) calls `defineSyncWorker({ registry, electricUrl,
109
109
  writeUrl, … })` at module top level — the registry is CODE, _imported_ by the worker file, never cloned/
110
110
  serialized in. The tab calls `attachSyncClient({ worker, registry, getToken })`, which returns the same
111
- client shape as `createSyncClient` (write API, Drizzle read BUILDING on the tab, live rows,
111
+ client shape as `createSyncClient` (write API, one-shot Drizzle reads, live rows,
112
112
  `ready`/`status`/`stop`) plus `notifyAuthChanged` and `setOnline`, proxied to the shared engine. One-shot
113
- `query`/`queryRaw` and local `pglite`/`ensureSynced`/`destroy` are NOT proxied (they throw) — reactive live
114
- rows are the read path in worker mode. The lazy lifecycle methods ARE proxied, but the engine is SHARED:
113
+ reads (`query`/`queryRow`/`queryRaw`/`queryRawRow`) compile on the tab and cross the bridge as ONE guarded
114
+ round trip — the worker runs the read gate + lazy-group guard, then Drizzle's own mapping runs back on the
115
+ tab, so results match the in-process client exactly. A bare awaited `client.drizzle` builder is ALSO
116
+ guarded here (the in-process unguarded escape hatch has no attach equivalent), and
117
+ `client.drizzle.transaction()` throws (no tab-local store). `ensureSynced` is proxied (additive,
118
+ idempotent); `isSynced` throws — it is a SYNCHRONOUS activation-started peek the tab's cached catch-up
119
+ readiness cannot answer (use `groupReady` for catch-up, `ensureSynced` to activate). Local
120
+ `pglite`/`destroy`/`dropReadCache` are NOT proxied — no tab-local store, and
121
+ store lifecycle on a shared engine is every-tab blast radius. The lazy lifecycle methods ARE proxied, but the engine is SHARED:
115
122
  `desync(tableKey)` from one tab reverts the consistency group for EVERY attached tab (desync's group-wide
116
123
  revert is engine-wide here — the footgun). For an ephemeral delivery window use `discardEphemeral(tableKey)`
117
124
  instead — the scoped, multi-tab-safe finalize (drops the ephemeral rows, reverts to dormant, refuses a
@@ -121,7 +128,10 @@ per-delivery-session and single-consumer. The exception is the INSPECTION surfac
121
128
  attach client), it runs raw against the local store — bypasses the journal/overlay, any write stays local
122
129
  and never converges — so it is not an app-data read path. `replAdapter(client)` shapes it into the
123
130
  `{ query, exec }` duck `@electric-sql/pglite-repl` needs (`client.pglite` stays unavailable). A worker file can bake multiple role variants and pick per attach via
124
- `resolveRegistry(role)` + the tab's `role` (the board's admin/member registries; the spare needs it).
131
+ `resolveRegistry(role)` + the tab's `role` (the board's admin/member registries; the spare needs it). The
132
+ worker entry can also pass the app-level schema prepare hooks `prepareLocalDbBeforeSchema` / `prepareLocalDb`
133
+ (app migrations, indexes, views) — same semantics as in-process, run in the worker around the registry schema
134
+ exec; they are worker-entry (not attach) options because a hook is a function and cannot cross the bridge.
125
135
 
126
136
  **Auth stays tab-owned (ADR-0013).** The tab pushes `{accessToken, expiresAt}` at attach and on
127
137
  `notifyAuthChanged`; the worker uses the cached token and sends a pull-request only when a request finds it
@@ -192,6 +202,19 @@ non-persistent (`dataDir` undefined — a bare `new PGlite()` — or `memory://`
192
202
  `NonPersistentStoreError` unless `testStoreAcknowledgment()` is spread alongside. For browser store GC, get
193
203
  the IndexedDB name from `storeIndexedDbDatabaseName(storePath)` — never assemble `/pglite/…` yourself.
194
204
 
205
+ **Relaxed durability is the default (ADR-0047).** On PGlite's idb backend, strict durability flushes the
206
+ whole datadir to IndexedDB **synchronously at the end of every query**, and that flush — not the SQL —
207
+ sets the local write-latency floor (~50ms+ per optimistic mutation). pgxsinkit therefore defaults
208
+ `relaxedDurability: true`: the query returns before the flush and the flush is scheduled asynchronously,
209
+ so a local write feels instant. The mode is a flat option on all three store-minting surfaces
210
+ (`createSyncClient`, `createClientPGlite`, and `defineSyncWorker` — worker-entry, not per-attach) and is
211
+ stamped on the `boot pglite.create` rail line so a boot capture shows which mode ran. Loss window: only
212
+ the writes not yet covered by a completed flush (typically the last one or two under human-rate input)
213
+ are at risk, and only on a crash before BOTH their journal rows reach the write API (~hundreds of ms
214
+ after enqueue) AND the scheduled idb flush lands — synced tables
215
+ are server-recoverable by construction, so only consumer **local-only** tables carry real risk. Opt out
216
+ with `relaxedDurability: false` if you keep unrecoverable local-only data and cannot accept that window.
217
+
195
218
  **Three exports, named by purpose, all returning `{ file, report }`** (report = phase timings + a
196
219
  `MutationDiagnostics` snapshot, BootReport-style). They work identically on the in-process client and the
197
220
  attach client (the artefact crosses the bridge as a transferred buffer):
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Flatten an error's `cause` chain into one message. Driver wrappers (drizzle's "Failed query: …")
3
+ * carry the ACTUAL database error — SQLSTATE code, message, detail — on `.cause`, so surfacing only
4
+ * `error.message` reports the query text while hiding why it failed (observed in production as a
5
+ * degraded engine whose lastError ended at "params: [object Object]"). Every place that stringifies an
6
+ * error into `status.lastError` or a bridge broadcast goes through this instead.
7
+ */
8
+ export function describeErrorChain(error: unknown, maxDepth = 5): string {
9
+ const parts: string[] = [];
10
+ let current: unknown = error;
11
+ for (let depth = 0; depth < maxDepth && current != null; depth += 1) {
12
+ const message =
13
+ current instanceof Error ? current.message : typeof current === "string" ? current : JSON.stringify(current);
14
+ const code = typeof current === "object" && "code" in current ? (current as { code?: unknown }).code : undefined;
15
+ const detail =
16
+ typeof current === "object" && "detail" in current ? (current as { detail?: unknown }).detail : undefined;
17
+ const asText = (value: unknown): string => (typeof value === "string" ? value : JSON.stringify(value));
18
+ parts.push(
19
+ [message, code != null ? `[${asText(code)}]` : undefined, detail != null ? `(${asText(detail)})` : undefined]
20
+ .filter(Boolean)
21
+ .join(" "),
22
+ );
23
+ current = current instanceof Error ? current.cause : undefined;
24
+ }
25
+ return parts.join(" ← caused by: ");
26
+ }
@@ -148,7 +148,11 @@ export async function runThrowawayCloneDump(
148
148
  const cloneDataDir = resolveStoreDataDir(nextCloneStorePath(), "memory");
149
149
  const cloneBootStartedAtMs = nowMs() - startPerf;
150
150
  const cloneBootStartPerf = nowMs();
151
- const throwaway = await PGlite.create({ dataDir: cloneDataDir, loadDataDir: dumped });
151
+ // Relaxed durability (ADR-0047): this clone is a MEMORY-backed, read-only throwaway (dumped → `pg_dump`
152
+ // → discarded), so it has no idb flush to relax — the flag is a no-op on the memory backend and is set
153
+ // purely to state intent (a throwaway never needs synchronous durability) and stay correct if the clone's
154
+ // backend ever changes.
155
+ const throwaway = await PGlite.create({ dataDir: cloneDataDir, loadDataDir: dumped, relaxedDurability: true });
152
156
  const cloneBootMs = nowMs() - cloneBootStartPerf;
153
157
 
154
158
  let sqlBytes: Uint8Array<ArrayBuffer>;
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { PGlite, type Results } from "@electric-sql/pglite";
1
+ import { PGlite, type QueryOptions, type Results } from "@electric-sql/pglite";
2
2
  import { live, type PGliteWithLive } from "@electric-sql/pglite/live";
3
3
  import type { PgliteDatabase } from "drizzle-orm/pglite";
4
4
  import { drizzle } from "drizzle-orm/pglite";
@@ -25,6 +25,7 @@ import { fingerprintRegistry, getSyncRegistrySchema, isClaimsDependentRowFilter
25
25
  import { type BootReport, type BootReportBuilder, createBootReportBuilder } from "./boot-report";
26
26
  import { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from "./convergence";
27
27
  import { syncDebug, timeAsync } from "./debug";
28
+ import { describeErrorChain } from "./error-chain";
28
29
  import { type DataExportOptions, type DataExportResult, performDataExport } from "./export-data";
29
30
  import { type DiagnosticExportOptions, type DiagnosticExportResult, performDiagnosticExport } from "./export-dump";
30
31
  import { performStoreExport, type StoreExportOptions, type StoreExportResult } from "./export-store";
@@ -276,6 +277,21 @@ export interface CreateClientPGliteOptions {
276
277
  * asset load), so it never fails the create.
277
278
  */
278
279
  bootAssets?: Promise<PgliteBootAssets>;
280
+ /**
281
+ * Relax PGlite's per-query durability (default `true`; ADR-0047) — the SINGLE resolution point for the
282
+ * default, which lives HERE and only here. On PGlite's idb backend every query otherwise ends with a
283
+ * SYNCHRONOUS flush of the whole datadir to IndexedDB, and that flush — not the query — dominates local
284
+ * write latency (a measured ~50ms+ floor per statement in a consumer). With relaxed durability a query
285
+ * returns BEFORE the flush and the flush is scheduled asynchronously, so latency reflects the query
286
+ * itself. Passed straight into `PGlite.create` and stamped onto the `boot pglite.create` rail.
287
+ *
288
+ * Loss window: only the writes not yet covered by a completed flush (typically the last one or two under human-rate input) are ever at risk, and only on a crash before
289
+ * BOTH (a) their journal rows reach the write API — which happens within ~hundreds of ms of enqueue — and
290
+ * (b) the scheduled idb flush lands. Synced tables are recoverable from the server by construction
291
+ * (ADR-0036), so relaxing their flush TIMING — not their persistence — costs nothing durable; consumer
292
+ * local-only tables carry whatever risk the consumer accepts. Opt out with `relaxedDurability: false`.
293
+ */
294
+ relaxedDurability?: boolean;
279
295
  /**
280
296
  * @internal Test-only storage-backend override (ADR-0036). `"memory"` resolves the store to a
281
297
  * scheme-selected in-memory store — the sanctioned unit-test/ephemeral lane. Never a product
@@ -329,6 +345,11 @@ export async function createClientPGlite(
329
345
  // result and the stamp measures the create itself. A rejected warm is caught to `undefined` so a failed
330
346
  // pre-warm silently falls back to PGlite's own asset loading rather than failing the boot.
331
347
  const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => undefined) : undefined;
348
+ // Relaxed durability (ADR-0047) — resolved HERE, the single default point: every store minting path
349
+ // (createSyncClient's own create, the worker's default createPglite factory, spare/prewarm mints) funnels
350
+ // through this function, so the `?? true` here is the whole toolkit's default. On idb the per-query
351
+ // synchronous flush dominates write latency; relaxing it schedules the flush asynchronously instead.
352
+ const relaxedDurability = options?.relaxedDurability ?? true;
332
353
  return (await timeAsync(
333
354
  "boot pglite.create",
334
355
  () =>
@@ -340,6 +361,7 @@ export async function createClientPGlite(
340
361
  // `electric` namespace is provisioned later, exactly as the registry-derived schema is.
341
362
  PGlite.create(dataDir, {
342
363
  ...(bootAssets ?? {}),
364
+ relaxedDurability,
343
365
  // Restore (ADR-0035 decision 6): seed the brand-new store from the backup tarball. PGlite's
344
366
  // `loadDataDir` unpacks it into the datadir being created, so the store boots ON the backup's bytes —
345
367
  // the whole synced cache, Overlay, and Mutation journal that travelled inside it. Absent on a normal
@@ -349,7 +371,9 @@ export async function createClientPGlite(
349
371
  live,
350
372
  },
351
373
  }),
352
- { dataDir: dataDirScheme },
374
+ // Stamp the resolved durability mode alongside the storage scheme so every boot-rail capture shows the
375
+ // mode the store was created under (ADR-0047 diagnosability).
376
+ { dataDir: dataDirScheme, relaxedDurability },
353
377
  // `as unknown as` because the raw store is deliberately engine-less here (only `live` is a create-time
354
378
  // extension); `createSyncClient` provisions the `electric` namespace post-create (ADR-0032 S1).
355
379
  )) as unknown as ClientPGlite;
@@ -399,6 +423,20 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
399
423
  * falls back to loading its own assets, so this is a pure best-effort accelerator.
400
424
  */
401
425
  pgliteBootAssets?: Promise<PgliteBootAssets>;
426
+ /**
427
+ * Relax PGlite's per-query durability for the client-owned store create (default `true`; ADR-0047).
428
+ * Forwarded verbatim to {@link createClientPGlite}, where the default is resolved — on the idb backend the
429
+ * per-query synchronous flush to IndexedDB dominates local write latency, so the toolkit defaults to
430
+ * relaxed (the query returns before the flush; the flush is scheduled asynchronously).
431
+ *
432
+ * Loss window: only the writes not yet covered by a completed flush (typically the last one or two under human-rate input) can be at risk, and only on a crash before
433
+ * BOTH their journal rows reach the write API (within ~hundreds of ms of enqueue) AND the scheduled idb
434
+ * flush lands. Synced tables are recoverable from the server by construction, so this relaxes flush
435
+ * TIMING, not persistence (ADR-0036); consumer local-only tables carry whatever risk the consumer
436
+ * accepts. Ignored on the {@link pgliteInstance} path (the caller owns that store's create). Opt out with
437
+ * `relaxedDurability: false`.
438
+ */
439
+ relaxedDurability?: boolean;
402
440
  resetSubscriptionKeys?: string[];
403
441
  prepareLocalDbBeforeSchema?: (pglite: ClientPGlite) => Promise<void>;
404
442
  prepareLocalDb?: (pglite: ClientPGlite) => Promise<void>;
@@ -450,15 +488,17 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
450
488
  * - **Fresh target only.** Refused with {@link RestoreTargetExistsError} if a store already exists at the
451
489
  * resolved {@link storePath} — restore never overlays a live store (that would corrupt the datadir); the
452
490
  * remedy is a deliberate {@link SyncClient.destroy} of the existing store first.
453
- * - **Always boots offline.** The engine boots with sync OFF regardless of {@link syncEnabled}/{@link autoSync}
454
- * or anything captured in the backup — no shape streams, no read fetch, no flush, no convergence passes.
455
- * Restore wins over an explicit online option (a debug-rail warning notes the override). The app inspects
456
- * {@link SyncClient.diagnostics}, releases/discards the quarantined rows, then a subsequent NORMAL boot of
457
- * the (now-persisted) store brings sync online — `loadDataDir` happens exactly once, on this restore boot.
491
+ * - **Comes online iff the recovered journal is clean (ADR-0046).** If journal recovery found NOTHING to
492
+ * quarantine — an empty recovered journal, the guaranteed-clean server-built bootstrap-artifact case — the
493
+ * restore boots ONLINE, honouring {@link syncEnabled}/{@link autoSync} exactly as a normal boot (streams,
494
+ * flush, convergence). If recovered mutations were quarantined, the boot stays OFFLINE (no shape streams,
495
+ * no read fetch, no flush): the app inspects {@link SyncClient.diagnostics}, releases/discards the
496
+ * quarantined rows, then a subsequent NORMAL boot of the (now-persisted) store brings sync online.
497
+ * `loadDataDir` happens exactly once, on this restore boot. An explicit `syncEnabled: false` keeps it offline.
458
498
  * - **Journal quarantined.** Every non-terminal recovered row (`pending`/`sending`/`failed`) is moved to
459
499
  * `quarantined` — nothing recovered from a backup auto-flushes (the write path has no `mutationId` dedupe
460
500
  * ledger, so replay is unsafe on last-write-wins tables). Release (`retryFailed`) or discard
461
- * (`discardQuarantined`) them explicitly.
501
+ * (`discardQuarantined`) them explicitly. When this pass quarantines nothing, the restore comes online (above).
462
502
  *
463
503
  * Mutually exclusive with {@link pgliteInstance} AND {@link precreatedPglite} — restore owns the store's
464
504
  * creation (`loadDataDir` is a create-time seed), so a caller-supplied instance conflicts (supplying either
@@ -843,6 +883,23 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
843
883
  rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
844
884
  /** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. */
845
885
  rawExec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
886
+ /**
887
+ * @internal The worker host's guarded one-shot read seam (ADR-0032 decision 4): {@link rawQuery} PLUS the
888
+ * ADR-0041 read gate and the ADR-0021 lazy-group guard, sharing one gate+guard core with the in-process
889
+ * `query`/`queryRaw` builder path so the two entry points can never drift on guard semantics.
890
+ * `defineSyncWorker` dispatches the `guardedQuery` RpcOp to this on its owned in-process client; the attach
891
+ * client's Drizzle-over-bridge compiles the SQL on the tab and routes the read here so the guard runs
892
+ * worker-side. Accepts the full PGlite {@link QueryOptions} (the worker re-applies drizzle's identity
893
+ * parsers here — temporal OIDs + numeric[]) plus the raw-fragment `use` list. NOT part of the app-facing
894
+ * read surface — reach for {@link query} / {@link queryRaw} instead; kept `@internal` (above) and excluded
895
+ * from the generated API docs (typedoc excludeInternal).
896
+ */
897
+ guardedRawQuery: (
898
+ sql: string,
899
+ params?: unknown[],
900
+ options?: QueryOptions,
901
+ use?: readonly SyncTableName<TRegistry>[],
902
+ ) => Promise<Results>;
846
903
  /**
847
904
  * Run a one-shot (non-live) typed **pure-Drizzle** query with the lazy-relation safety net (ADR-0021).
848
905
  * Pass the builder callback directly — pgxsinkit scans the compiled SQL and activates + awaits every
@@ -1126,18 +1183,16 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1126
1183
  );
1127
1184
  }
1128
1185
 
1129
- // Restore ALWAYS boots offline (ADR-0035 decision 6), regardless of `syncEnabled`/`autoSync` or anything
1130
- // captured in the backup: no shape streams, no read fetch, no flush, no convergence passes. The app deals
1131
- // with the quarantined journal, then a subsequent NORMAL boot brings sync online. Restore wins over an
1132
- // explicit online option — warn on the debug rail so the override is visible rather than silent.
1133
- if (restoreBoot && (options.syncEnabled === true || options.autoSync != null)) {
1134
- syncDebug("boot restore forces offline — ignoring the online sync option for this restore boot", {
1135
- syncEnabled: options.syncEnabled === true,
1136
- autoSync: options.autoSync != null,
1137
- });
1138
- }
1139
- const syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);
1140
- // ADR-0032 S4 overlap flag, computed once up front so the boot report and the prefetch gate agree.
1186
+ // Restore boots start offline and DEFER the sync-enable decision until AFTER journal recovery (ADR-0046,
1187
+ // refining ADR-0035 decision 6): a restore comes online iff recovery found NOTHING to quarantine — an empty
1188
+ // recovered journal, the guaranteed-clean server-built bootstrap-artifact case — and stays offline (today's
1189
+ // behaviour) when recovered mutations were quarantined, because a replayed write is unsafe without a dedupe
1190
+ // ledger. The decision is taken in the restore recovery block below (it needs the quarantine count) and
1191
+ // honours an explicit `syncEnabled: false`. A normal boot resolves its final value here, up front.
1192
+ let syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);
1193
+ // ADR-0032 S4 overlap flag. A restore starts `syncEnabled: false` here, so it never takes the overlap
1194
+ // prefetch path (a restore also never presents a fresh spare store); the flag stays `false` for the whole
1195
+ // boot even when the restore later comes online (which uses the sequential sync-start path, not overlap).
1141
1196
  const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
1142
1197
  // How the store presents at boot (ADR-0034 `storeKind`): a restore boot seeds a brand-new store from a
1143
1198
  // backup; otherwise the caller's fresh-store hint (the same signal as `freshStore`) marks a fresh spare;
@@ -1178,6 +1233,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1178
1233
  const createClientOptions: CreateClientPGliteOptions = {
1179
1234
  ...(options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {}),
1180
1235
  ...(backendOverride ? { backendOverride } : {}),
1236
+ // Relaxed durability (ADR-0047): forward the caller's explicit choice; `createClientPGlite` resolves the
1237
+ // `?? true` default. Passed only when set, so the default lives at exactly one point.
1238
+ ...(options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {}),
1181
1239
  // Restore (ADR-0035 decision 6): seed the fresh store from the backup via `loadDataDir`. Restore is
1182
1240
  // mutually exclusive with the BYO instance seams (checked above), so it only ever rides a client-owned
1183
1241
  // create — never the adopt paths, which leave `restoreFrom` unread.
@@ -1345,7 +1403,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1345
1403
  // letting the read cache silently diverge from the server. Sticky (see below).
1346
1404
  status.phase = "degraded";
1347
1405
  degradedReason = "commit";
1348
- status.lastError = error.message;
1406
+ // The cause chain, not just the wrapper: a drizzle "Failed query" message hides the actual
1407
+ // database error (SQLSTATE, detail) on `.cause`.
1408
+ status.lastError = describeErrorChain(error);
1349
1409
  options.onStatusChange?.(status);
1350
1410
  options.onSyncError?.(error);
1351
1411
  },
@@ -1362,7 +1422,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1362
1422
  // way then another reports the current cause (observability).
1363
1423
  status.phase = "degraded";
1364
1424
  degradedReason = "stream";
1365
- status.lastError = error.message;
1425
+ status.lastError = describeErrorChain(error);
1366
1426
  options.onStatusChange?.(status);
1367
1427
  },
1368
1428
  // Clear a recoverable status (auth-needed, or a read-stream degraded) the moment a batch is delivered
@@ -1521,6 +1581,23 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1521
1581
  // dropping the quarantined writes — unchanged from the pre-ADR-0041 recover→quarantine→reconcile order.
1522
1582
  // `localReadReady` and `writeReady` therefore coincide on a restore boot (both resolved after this point).
1523
1583
  await runBootRecoveryStage();
1584
+
1585
+ // ADR-0046: with recovery + quarantine complete, decide whether this restore comes online. The restore
1586
+ // quarantine pass parked every recovered non-terminal write (pending/sending/failed) as `quarantined`, so a
1587
+ // zero quarantined count means the backup's journal was CLEAN — the server-built bootstrap-artifact case —
1588
+ // and sync may start exactly as a normal boot would. A non-zero count keeps the boot offline (the protective
1589
+ // ADR-0035 rule, now applied only where it protects) until the app releases the rows; a subsequent normal
1590
+ // boot then brings sync online. An explicit `syncEnabled: false` is always honoured (stays offline).
1591
+ const recoveredQuarantined = (await mutationRuntime.readMutationStats()).quarantinedCount;
1592
+ if (recoveredQuarantined === 0 && options.syncEnabled !== false) {
1593
+ syncEnabled = options.syncEnabled ?? true;
1594
+ syncDebug("boot restore comes online — recovered journal was clean (nothing to quarantine)");
1595
+ } else if (recoveredQuarantined > 0) {
1596
+ syncDebug(
1597
+ "boot restore stays offline — recovered journal mutations were quarantined; release/discard them and a subsequent normal boot brings sync online",
1598
+ { quarantinedCount: recoveredQuarantined, syncEnabledOption: options.syncEnabled ?? null },
1599
+ );
1600
+ }
1524
1601
  await runReconcileStage();
1525
1602
  } else {
1526
1603
  // Normal boot (ADR-0041): reconcile is part of the local-read core and runs BEFORE recovery (which moves
@@ -1675,11 +1752,12 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1675
1752
  resolveSyncWired();
1676
1753
  };
1677
1754
 
1678
- // Restore boots offline (ADR-0035 decision 6): never stand up the convergence driver on a restore boot,
1679
- // so an `autoSync` trigger the caller passed (even an online one) drives NO flush/reconcile passes — the
1680
- // recovered journal is quarantined and must stay put until the app releases it and a normal boot goes
1681
- // online. On every other boot the driver behaves exactly as before.
1682
- if (options.autoSync && !restoreBoot) {
1755
+ // Convergence driver (ADR-0035 decision 6 / ADR-0046): a restore boot that STAYS offline (recovered journal
1756
+ // quarantined) never stands up the driver, so an `autoSync` trigger drives NO flush/reconcile passes — the
1757
+ // quarantined rows must stay put until the app releases them and a normal boot goes online. A restore that
1758
+ // came online (clean recovered journal) is treated exactly like a normal online boot and DOES get the driver.
1759
+ // On every non-restore boot the gate is unchanged (`!restoreBoot` is true regardless of `syncEnabled`).
1760
+ if (options.autoSync && (!restoreBoot || syncEnabled)) {
1683
1761
  convergenceDriver = createConvergenceDriver({
1684
1762
  client: {
1685
1763
  flush: () => mutationRuntime.flush(),
@@ -2069,19 +2147,41 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2069
2147
  return { lazyTables };
2070
2148
  };
2071
2149
 
2072
- const runGuardedQuery = async <TRows extends readonly unknown[]>(
2073
- build: GuardedQueryFn<TRegistry, TRows>,
2074
- use?: readonly SyncTableName<TRegistry>[],
2075
- ): Promise<TRows> => {
2150
+ // The single gate+guard core shared by BOTH one-shot read entry points (the in-process drizzle-builder path
2151
+ // below and the worker-reachable `guardedRawQuery`), so the read gate and lazy-group guard can never drift
2152
+ // between modes. Given the query's compiled SQL (∪ `use`): read gate first, then the lazy-group guard.
2153
+ const gateAndGuardRead = async (sql: string, use?: readonly SyncTableName<TRegistry>[]): Promise<void> => {
2076
2154
  // Read gate (ADR-0041): a query must not run against a store whose local-read core has not finished. On
2077
2155
  // the in-process client this is a settled-promise await (the client is handed out at `localReadReady`),
2078
2156
  // but it is cheap and keeps the read path safe if a caller retained a query builder across the boundary.
2079
2157
  await localReadReady;
2158
+ // Lazy-group guard (ADR-0021): scan the compiled SQL (∪ `use`) for lazy relations it reads and activate +
2159
+ // await them before the query runs, so a lazy relation is never read empty/stale.
2160
+ await prepareQuery({ sql, ...(use ? { use } : {}) });
2161
+ };
2162
+
2163
+ const runGuardedQuery = async <TRows extends readonly unknown[]>(
2164
+ build: GuardedQueryFn<TRegistry, TRows>,
2165
+ use?: readonly SyncTableName<TRegistry>[],
2166
+ ): Promise<TRows> => {
2167
+ // Building the drizzle query is pure construction (no DB I/O — it only compiles to SQL), so compile first,
2168
+ // then run the shared gate+guard on that SQL, then hand back the still-unexecuted builder (its `await`
2169
+ // executes via the local drizzle exactly as before — return shape unchanged).
2080
2170
  const builder = build(client);
2081
- await prepareQuery({ sql: builder.toSQL().sql, ...(use ? { use } : {}) });
2171
+ await gateAndGuardRead(builder.toSQL().sql, use);
2082
2172
  return builder;
2083
2173
  };
2084
2174
 
2175
+ // The worker host's guarded one-shot read (ADR-0032 decision 4) — `rawQuery` PLUS the shared gate+guard.
2176
+ // `defineSyncWorker`'s `guardedQuery` handler calls this on its owned in-process client (re-applying
2177
+ // drizzle's identity parsers — temporal OIDs + numeric[] — in `options` first, since that parser map cannot cross the bridge);
2178
+ // the attach client's Drizzle-over-bridge routes reads here. Returns the full PGlite `Results` so drizzle's
2179
+ // own result mapping runs on the tab.
2180
+ const guardedRawQuery: SyncClient<TRegistry>["guardedRawQuery"] = async (sql, params, options, use) => {
2181
+ await gateAndGuardRead(sql, use);
2182
+ return pglite.query(sql, params as unknown[] | undefined, options);
2183
+ };
2184
+
2085
2185
  // The live-query manager (ADR-0040) — the SAME module the worker uses (decision 6), so the in-process
2086
2186
  // client gets one lifecycle contract: dedup of identical concurrent subscriptions within this client,
2087
2187
  // bounded zero-subscriber keep-alive (`options.liveQueries`), and awaited teardown (decision 1 — `dispose()`
@@ -2246,6 +2346,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2246
2346
  // overlay involvement. The worker facade runs the identical call inside the worker's own client.
2247
2347
  rawQuery: (sql, params, options) => pglite.query(sql, params as unknown[] | undefined, options),
2248
2348
  rawExec: (sql, options) => pglite.exec(sql, options),
2349
+ // @internal: the guarded raw-SQL read the worker host dispatches `guardedQuery` to (ADR-0032 decision 4).
2350
+ guardedRawQuery,
2249
2351
  query: (build) => runGuardedQuery(build),
2250
2352
  queryRow: async (build) => {
2251
2353
  const rows = await runGuardedQuery(build);
@@ -2451,7 +2553,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2451
2553
  // NIT 8: surface a signal beyond the stage rejections — move the runtime to `degraded` so a consumer
2452
2554
  // watching `status`/`onStatusChange` sees the boot failed, not just an awaiter of a stage promise.
2453
2555
  status.phase = "degraded";
2454
- status.lastError = error instanceof Error ? error.message : String(error);
2556
+ status.lastError = describeErrorChain(error);
2455
2557
  options.onStatusChange?.(status);
2456
2558
  rejectWriteReady(error);
2457
2559
  rejectReady(error);
@@ -2519,22 +2621,54 @@ function buildViews<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
2519
2621
  }
2520
2622
 
2521
2623
  /**
2522
- * The tab-side READ handles a worker-attached client exposes (ADR-0032 S2): a build-only Drizzle instance
2523
- * plus the registry views. On the attach client, Drizzle is used only to COMPILE queries to SQL
2524
- * (`.toSQL()`) on the tab — execution happens in the worker via the live-rows bridge / RPC — so it is
2525
- * constructed over a stub client that is never invoked (`construct` stores the client without calling it).
2526
- * The same builders `createSyncClient` uses, so a query built on either client compiles identically.
2624
+ * The tab-side READ handles a worker-attached client exposes (ADR-0032 S2/decision 4): a Drizzle instance
2625
+ * plus the registry views. `createSyncClient`'s SAME builders, so a query built on either client compiles
2626
+ * identically. The `client` argument is the executor Drizzle runs against:
2627
+ * - Omit it (the default `{}` stub) for a BUILD-ONLY instance — Drizzle only compiles to SQL (`.toSQL()`)
2628
+ * and the stub is never invoked; used where execution happens elsewhere (e.g. the live-rows bridge).
2629
+ * - Pass a `ClientPGlite`-shaped BRIDGE executor (its `query` routes to the worker's `guardedQuery` RPC) so
2630
+ * that awaiting a builder executes through the bridge and Drizzle's own result mapping (relational/nested
2631
+ * queries included) runs on the tab — the one-shot read path `attachSyncClient` wires (ADR-0032 decision 4).
2527
2632
  */
2528
2633
  export function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(
2529
2634
  registry: TRegistry,
2530
- ): { drizzle: PgliteDatabase<RegistryRelations<TRegistry>>; views: RegistryViews<TRegistry> } {
2531
- const stubClient = {} as ClientPGlite;
2635
+ client: ClientPGlite = {} as ClientPGlite,
2636
+ ): {
2637
+ drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;
2638
+ views: RegistryViews<TRegistry>;
2639
+ /**
2640
+ * A drizzle-database FACTORY over this registry's schema (ADR-0032 decision 4): `(client) => db`, reusing
2641
+ * the schema + relations computed ONCE here so a caller can cheaply build additional per-executor databases
2642
+ * without recomputing them. `attachSyncClient` uses it to give each `queryRaw`/`queryRawRow` its OWN
2643
+ * bridge executor carrying that call's `use` — a scoped db, never a shared mutable stash (no read races).
2644
+ */
2645
+ drizzleFor: (client: ClientPGlite) => PgliteDatabase<RegistryRelations<TRegistry>>;
2646
+ } {
2647
+ const drizzleFor = buildRegistryDrizzleFactory(registry);
2532
2648
  return {
2533
- drizzle: createDrizzleDatabase(stubClient, buildSchema(registry)),
2649
+ drizzle: drizzleFor(client),
2534
2650
  views: buildViews(registry),
2651
+ drizzleFor,
2535
2652
  };
2536
2653
  }
2537
2654
 
2655
+ /**
2656
+ * Compute a registry's Drizzle schema + relations ONCE and return a `(client) => db` factory over them
2657
+ * (ADR-0032 decision 4). Splitting this out of {@link buildRegistryReadHandles} lets `attachSyncClient` build
2658
+ * one base bridge database plus a fresh per-read database (each over its own executor) without paying the
2659
+ * schema/relations construction on every read — only the `client` binding differs between them.
2660
+ */
2661
+ function buildRegistryDrizzleFactory<TRegistry extends SyncTableRegistry>(
2662
+ registry: TRegistry,
2663
+ ): (client: ClientPGlite) => PgliteDatabase<RegistryRelations<TRegistry>> {
2664
+ const relations = defineRelations(buildSchema(registry)) as RegistryRelations<TRegistry>;
2665
+ const createDatabase = drizzle as unknown as (config: {
2666
+ client: ClientPGlite;
2667
+ relations: RegistryRelations<TRegistry>;
2668
+ }) => PgliteDatabase<RegistryRelations<TRegistry>>;
2669
+ return (client) => createDatabase({ client, relations });
2670
+ }
2671
+
2538
2672
  function buildSyncConfigFromRegistry<TRegistry extends SyncTableRegistry>(
2539
2673
  registry: TRegistry,
2540
2674
  electricUrl: string,
@@ -492,6 +492,12 @@ export interface ApplyTarget {
492
492
  propertyKeyByName: Record<string, string>;
493
493
  /** Primary-key column NAMES, in order (from the entry, local-projection override honoured). */
494
494
  primaryKey: string[];
495
+ /**
496
+ * CDC insert-apply policy (ADR-0045), from the entry. `"insert"` (default) applies a CDC insert as a
497
+ * plain INSERT so a genuine PK collision surfaces; `"upsert"` applies it idempotently (ON CONFLICT DO
498
+ * UPDATE) because this table legitimately receives locally-derived provisional rows.
499
+ */
500
+ applyMode: "insert" | "upsert";
495
501
  /** Model-derived column types (`deriveSyncColumnTypes`), keyed by DB column name via `.name`. */
496
502
  columnTypes: SyncColumnType[];
497
503
  /**
@@ -525,6 +531,7 @@ export function resolveApplyTarget<TRegistry extends SyncTableRegistry, TKey ext
525
531
  columnByName,
526
532
  propertyKeyByName,
527
533
  primaryKey: getLocalSyncedTablePrimaryKeyColumns(entry),
534
+ applyMode: entry.applyMode,
528
535
  columnTypes: deriveSyncColumnTypes(entry),
529
536
  insertRenderCache: new Map(),
530
537
  };
package/src/schema.ts CHANGED
@@ -545,18 +545,36 @@ function buildTableColumnSql(columns: TableColumn[], primaryKeyColumns: string[]
545
545
  * ADR-0029 D3: the metadata-store DDL renders from its `metadata-tables.ts` pgTables through this,
546
546
  * making the pgTable the single source. The OUTPUT is tier-③-by-nature runtime DDL (schema/table
547
547
  * identifiers assembled at construction), but it is GENERATED from the model, never hand-maintained.
548
+ *
549
+ * ADR-0042: `{ temp: true }` renders the SESSION variant — `CREATE TEMP TABLE IF NOT EXISTS <bare name>`
550
+ * (+ each index `ON <bare name>`), IGNORING the pgTable's declared schema for the RELATION name. TEMP DDL
551
+ * takes the UNqualified relation name (the TEMP keyword places it in `pg_temp`; a `CREATE TEMP TABLE
552
+ * pg_temp.x` target is not portable). Same relation/index NAMES as the durable form: an index name lives
553
+ * per schema, so the durable (metadata-schema) and session (`pg_temp`) indexes coexist without collision
554
+ * (probed on real PGlite).
555
+ *
556
+ * CAVEAT — the `temp` flag only bares the RELATION name; `buildTableColumnSql` below still receives
557
+ * `schemaName` and would qualify any ENUM column type into THAT schema. That is correct only because the
558
+ * metadata pgTables (the sole callers of `{ temp: true }`) carry no enum columns. A future enum-bearing TEMP
559
+ * render would emit `<metadataSchema>.<enum>` for the column type — which is exactly what we want (enums are
560
+ * persistent DB objects living in the durable schema even for TEMP tables, ADR-0021 §3), NOT a `pg_temp`
561
+ * qualification. If this path ever renders a TEMP relation with an enum, keep the enum durable-qualified;
562
+ * do not fold the `temp` flag into the column-type schema.
548
563
  */
549
- export function renderCreateTableSql(table: AnyPgTable): string[] {
564
+ export function renderCreateTableSql(table: AnyPgTable, options: { temp?: boolean } = {}): string[] {
550
565
  const config = getTableConfig(table);
566
+ const temp = options.temp === true;
551
567
  const schemaName = config.schema ?? "public";
552
- const qualifiedTableName = qualifyIdentifier(schemaName, config.name);
568
+ // The DML paths qualify the session tables into `pg_temp`; the DDL must NOT — see the doc comment.
569
+ const tableRef = temp ? maybeQuoteIdentifier(config.name) : qualifyIdentifier(schemaName, config.name);
553
570
  const primaryKeyColumns = collectPgTablePrimaryKeyColumns(config);
554
571
  const columnSql = buildTableColumnSql(config.columns as unknown as TableColumn[], primaryKeyColumns, schemaName);
555
572
 
556
- const statements = [`CREATE TABLE IF NOT EXISTS ${qualifiedTableName} (\n ${columnSql}\n);`];
573
+ const createKeyword = temp ? "CREATE TEMP TABLE" : "CREATE TABLE";
574
+ const statements = [`${createKeyword} IF NOT EXISTS ${tableRef} (\n ${columnSql}\n);`];
557
575
 
558
576
  for (const index of config.indexes) {
559
- statements.push(renderCreateIndexSql(qualifiedTableName, index));
577
+ statements.push(renderCreateIndexSql(tableRef, index));
560
578
  }
561
579
 
562
580
  return statements;
package/src/shape-sync.ts CHANGED
@@ -296,6 +296,10 @@ export async function startConfiguredSync(
296
296
  groupKey: group.groupKey,
297
297
  specs: group.specs,
298
298
  registry: input.registry,
299
+ // ADR-0042: an ephemeral group's cursor + tags are session-scoped (stored in `pg_temp`), so a warm
300
+ // engine restart re-streams the shape from scratch rather than resuming a stale durable cursor over
301
+ // the recreated-empty TEMP cluster. The engine learns only this one storage-scope bit.
302
+ ...(group.retention === "ephemeral" ? { sessionScoped: true } : {}),
299
303
  ...(bootStamp ? { bootStamp } : {}),
300
304
  // The prefetch overlap (ADR-0032 S4) applies ONLY to the eager BOOT starts: a fresh store's eager
301
305
  // groups are genuinely new, so buffering their catch-up behind the commit gate is safe. An on-demand
@@ -400,6 +404,12 @@ interface StartGroupSyncOptions {
400
404
  groupKey: string;
401
405
  specs: ConfiguredShapeSyncSpec[];
402
406
  registry: SyncTableRegistry;
407
+ /**
408
+ * ADR-0042: the group's retention is `ephemeral`, so its sync bookkeeping (cursor + tags) is session-
409
+ * scoped — the engine stores it in `pg_temp` relations that die with the engine. Forwarded straight to
410
+ * the engine's `syncShapesToTables`; absent/`false` for a persistent group (byte-identical storage).
411
+ */
412
+ sessionScoped?: boolean;
403
413
  headers?: ExternalHeadersRecord;
404
414
  /** Fresh-store prefetch overlap gate (ADR-0032 S4) — forwarded to the engine's `syncShapesToTables`. */
405
415
  dbReady?: Promise<void>;
@@ -450,6 +460,7 @@ export async function startGroupSync(pg: SyncEnginePGlite, input: StartGroupSync
450
460
  key: input.groupKey,
451
461
  registry: input.registry,
452
462
  shapes,
463
+ ...(input.sessionScoped ? { sessionScoped: input.sessionScoped } : {}),
453
464
  ...(input.dbReady ? { dbReady: input.dbReady } : {}),
454
465
  ...(input.bootStamp ? { bootStamp: input.bootStamp } : {}),
455
466
  ...(input.onGroupInitialSync ? { onInitialSync: input.onGroupInitialSync } : {}),