@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
package/src/lazy-guard.ts CHANGED
@@ -55,7 +55,7 @@ function tokensForEntry(entry: SyncTableRegistry[string]): string[] {
55
55
  if (entry.readProjection) {
56
56
  // A read PROJECTION (defineReadProjection, ADR-0025) owns no physical table: its `entry.table` is the
57
57
  // OWNER's physical table, but a consumer reads it ONLY through its DISTINCT local identity
58
- // `entry.localTable` (the `as` name — where Electric syncs the projection's rows). Token that, NOT the
58
+ // `entry.localTable` (the `as` name — where the read path syncs the projection's rows). Token that, NOT the
59
59
  // owner's physical name: a read of the projection's own local table then resolves to it, while a read of
60
60
  // the owner's table resolves the OWNER entry (which carries the owner token) without falsely resolving
61
61
  // this projection. (A projection is always readonly and has no read-model view.)
@@ -2,7 +2,7 @@ import { quoteIdentifier } from "@pgxsinkit/contracts";
2
2
 
3
3
  // ─── Live-read materialization safety (ADR-0032 S2 §4) ───────────────────────────────────────────────
4
4
  //
5
- // The live-rows seam feeds the compiled SQL of a Drizzle-built select into PGlite's `live` extension,
5
+ // The live-rows seam feeds the compiled SQL of a Drizzle-built select into pgwasm's `live` extension,
6
6
  // which MATERIALISES the query (a temp view + state table it diffs against). Drizzle emits no output
7
7
  // aliases — it maps result columns positionally — so a JOIN whose tables share a column name (two
8
8
  // `title`) compiles to a SELECT with duplicate OUTPUT column names. That is legal as a plain one-shot
@@ -1,7 +1,7 @@
1
1
  import { and, eq, like, notExists, sql } from "drizzle-orm";
2
- import { drizzle } from "drizzle-orm/pglite";
3
2
 
4
3
  import { type MutationDiagnostics, type SyncTableRegistry } from "@pgxsinkit/contracts";
4
+ import { drizzle } from "@pgxsinkit/pgwasm/drizzle";
5
5
 
6
6
  import { syncDebug } from "./debug";
7
7
  import { getJournalTable, getLocalMetaTable } from "./local-tables";
@@ -219,7 +219,7 @@ function writableTableKeys(registry: SyncTableRegistry): string[] {
219
219
  * statement — but only where NOT EXISTS any `sending` row in ANY writable journal (the EXISTS-union is built
220
220
  * from the registry's journal Drizzle objects via {@link getJournalTable}). Correct regardless of JS
221
221
  * bookkeeping: a concurrent enqueue that committed a `sending` row makes the guard fail, so the marker stays
222
- * `"true"`. Returns `{ cleared }` from the statement's affected-row count (PGlite reports `affectedRows`) —
222
+ * `"true"`. Returns `{ cleared }` from the statement's affected-row count (pgwasm reports `affectedRows`) —
223
223
  * `true` when the guard passed (an existing marker row flipped/held at `"false"`), `false` when a `sending`
224
224
  * row blocked it OR no marker row exists yet. Off the boot path AND at the end of a boot recovery pass.
225
225
  *
@@ -23,6 +23,7 @@ import {
23
23
  deriveSyncColumnTypes,
24
24
  getLocalSyncedTablePrimaryKeyColumns,
25
25
  getSyncRegistrySchema,
26
+ jsonUdtName,
26
27
  type SyncColumnType,
27
28
  type SyncTableEntry,
28
29
  type SyncTableRegistry,
@@ -109,7 +110,7 @@ function buildOverlayFixedColumns() {
109
110
  /**
110
111
  * The two overlay columns the `<t>_read_model` view carries on top of the projected synced columns.
111
112
  * Read through real drizzle result mapping (a live query, not the raw `MutationDb` seam), so
112
- * `local_updated_at_us` is a `mode: "bigint"` int8 (PGlite returns it as a string at runtime) rather than
113
+ * `local_updated_at_us` is a `mode: "bigint"` int8 (pgwasm returns it as a string at runtime) rather than
113
114
  * the journal/overlay `bigintText` passthrough. Snake-case property keys so consumers reach them the same
114
115
  * way the generator names them (`view["overlay_kind"]`).
115
116
  */
@@ -151,7 +152,7 @@ const localMetaShape = pgTable(LOCAL_META_TABLE, {
151
152
  * The **Outbox**'s columns (ADR-0053 decision 2), mirroring the DDL in `schema.ts` — see {@link OUTBOX_TABLE}
152
153
  * there for the column-by-column public contract. The `_us` bigints and `seq` are the same `bigintText`
153
154
  * passthrough the journal object uses (rows come back through the raw seam UNMAPPED, so the runtime reads
154
- * them as strings); `payload` is real `jsonb` (PGlite parses it, so the flush loop gets the object back).
155
+ * them as strings); `payload` is real `jsonb` (pgwasm parses it, so the flush loop gets the object back).
155
156
  * `seq` is DEFAULTed by the sequence, so an insert omits it — hence no `.notNull()` footgun on `$inferInsert`.
156
157
  */
157
158
  function buildOutboxColumns() {
@@ -165,6 +166,7 @@ function buildOutboxColumns() {
165
166
  attemptCount: integer("attempt_count").notNull().default(0),
166
167
  nextRetryAtUs: bigintText("next_retry_at_us"),
167
168
  lastReason: text("last_reason"),
169
+ ackedAtUs: bigintText("acked_at_us"),
168
170
  };
169
171
  }
170
172
 
@@ -507,7 +509,7 @@ export function getReadModelView<TRegistry extends SyncTableRegistry, TKey exten
507
509
  * appliers need is derived once from the registry entry — the real projected synced table object, its
508
510
  * columns indexed by DB column name, the primary-key column names, and the model-derived column types —
509
511
  * so the appliers author over Drizzle objects (no name/schema strings, no `information_schema` probe).
510
- * Resolved once per shape at subscribe time; reused for every message. Electric change rows are keyed
512
+ * Resolved once per shape at subscribe time; reused for every message. Streamed change rows are keyed
511
513
  * by DB **column name**, while Drizzle DML keys by **property key**, so both indexes are carried.
512
514
  */
513
515
  export interface ApplyTarget {
@@ -519,6 +521,20 @@ export interface ApplyTarget {
519
521
  propertyKeyByName: Record<string, string>;
520
522
  /** Primary-key column NAMES, in order (from the entry, local-projection override honoured). */
521
523
  primaryKey: string[];
524
+ /**
525
+ * The SERVER primary-key column names, in declaration order — the order the engine joins stream-key
526
+ * components in (`schema.rs` `key_string`). Identical to {@link primaryKey} except under a
527
+ * `clientProjection.localPrimaryKey` narrowing, where the stream key still carries every server
528
+ * component and the local key is a subset.
529
+ */
530
+ serverPrimaryKey: string[];
531
+ /**
532
+ * Server-key components `clientProjection.localPrimaryKey` drops (subscribe-time compile refuses the
533
+ * narrowing unless the shape's predicate pins each to a single value). The engine force-includes
534
+ * every server pk component in emitted rows and keys, so the applier projects exactly these away —
535
+ * any OTHER unknown column stays a loud config error.
536
+ */
537
+ droppedKeyColumns: string[];
522
538
  /**
523
539
  * CDC insert-apply policy (ADR-0045), from the entry. `"insert"` (default) applies a CDC insert as a
524
540
  * plain INSERT so a genuine PK collision surfaces; `"upsert"` applies it idempotently (ON CONFLICT DO
@@ -527,6 +543,16 @@ export interface ApplyTarget {
527
543
  applyMode: "insert" | "upsert";
528
544
  /** Model-derived column types (`deriveSyncColumnTypes`), keyed by DB column name via `.name`. */
529
545
  columnTypes: SyncColumnType[];
546
+ /**
547
+ * DB column names of the SCALAR `json`/`jsonb` columns — the columns whose wire cell is decoded from
548
+ * JSON text to a JS value on the way in (see `envelopeToChange`). Derived from {@link columnTypes} via
549
+ * the contracts' `jsonUdtName`, once per shape at resolve time rather than per row: the decode runs on
550
+ * every cell of every backfill row, so re-deriving it there would be a per-row string normalisation.
551
+ *
552
+ * Array json columns (`json[]`/`jsonb[]`) are NOT listed — like every array column they stay in
553
+ * Postgres's `array_out` text, which every apply tier feeds back to `array_in`.
554
+ */
555
+ jsonColumns: string[];
530
556
  /**
531
557
  * Per-shape render-once cache for the batched-INSERT family (ADR-0029 D5): a rendered `{sqlText,
532
558
  * params}` per distinct (column-set, row-count), reused across batches with per-value codecs applied
@@ -535,6 +561,22 @@ export interface ApplyTarget {
535
561
  insertRenderCache: Map<string, { sqlText: string; params: unknown[] }>;
536
562
  }
537
563
 
564
+ /**
565
+ * The DB column names of the SCALAR `json`/`jsonb` columns in a resolved column-type list — the
566
+ * {@link ApplyTarget.jsonColumns} derivation, exported so the test-support target builder and any other
567
+ * ApplyTarget producer derive it the one way (through the contracts' `jsonUdtName`).
568
+ */
569
+ export function scalarJsonColumnNames(columnTypes: readonly SyncColumnType[]): string[] {
570
+ const names: string[] = [];
571
+ for (const column of columnTypes) {
572
+ const udt = jsonUdtName(column);
573
+ if (udt === "json" || udt === "jsonb") {
574
+ names.push(column.name);
575
+ }
576
+ }
577
+ return names;
578
+ }
579
+
538
580
  /**
539
581
  * Resolve a shape's {@link ApplyTarget} from its registry entry (ADR-0029 D1/D2). Called once per shape
540
582
  * at subscribe time — never per message. The single source is the registry item: identity via
@@ -553,13 +595,33 @@ export function resolveApplyTarget<TRegistry extends SyncTableRegistry, TKey ext
553
595
  columnByName[column.name] = column;
554
596
  propertyKeyByName[column.name] = propertyKey;
555
597
  }
598
+ // Both pk specs are stored verbatim (property key OR column name) — normalize each against the
599
+ // table that actually carries its columns: the local key against the projected synced table, the
600
+ // server key against the full server table (a dropped component has no local column to resolve by).
601
+ const localPrimaryKey = getLocalSyncedTablePrimaryKeyColumns(entry).map((declared) =>
602
+ columns[declared] ? columns[declared].name : declared,
603
+ );
604
+ const localPrimaryKeySet = new Set(localPrimaryKey);
605
+ const serverColumns = getColumns(entry.table as AnyPgTable) as Record<string, PgColumn>;
606
+ const serverPrimaryKey = entry.primaryKey.columns.map((declared) =>
607
+ serverColumns[declared] ? serverColumns[declared].name : declared,
608
+ );
609
+ const columnTypes = deriveSyncColumnTypes(entry);
556
610
  return {
557
611
  table: table as AnyPgTable,
558
612
  columnByName,
559
613
  propertyKeyByName,
560
- primaryKey: getLocalSyncedTablePrimaryKeyColumns(entry),
614
+ // Normalized to DB COLUMN NAMES. `defineSyncTable` accepts a primary-key spec written either way
615
+ // (property key or column name) and stores it verbatim on the entry — so on a table whose two
616
+ // differ, the un-normalized form reaches `columnByName`/`propertyKeyByName`, which are keyed by
617
+ // column name, and every update and delete throws "column not found". Resolving here, where the
618
+ // table's own columns are in hand, makes the field match what it has always claimed to be.
619
+ primaryKey: localPrimaryKey,
620
+ serverPrimaryKey,
621
+ droppedKeyColumns: serverPrimaryKey.filter((name) => !localPrimaryKeySet.has(name)),
561
622
  applyMode: entry.applyMode,
562
- columnTypes: deriveSyncColumnTypes(entry),
623
+ columnTypes,
624
+ jsonColumns: scalarJsonColumnNames(columnTypes),
563
625
  insertRenderCache: new Map(),
564
626
  };
565
627
  }
@@ -620,6 +682,15 @@ export function getAllMutationsView(_registry: SyncTableRegistry): AllMutationsV
620
682
  * Public on purpose: the table's shape is contract, so an app composing a best-guess view (pending events
621
683
  * over down-synced aggregates) authors it as tier-① Drizzle instead of hand-written SQL —
622
684
  * `client.query((c) => c.drizzle.select().from(getOutboxTable(registry)).where(eq(outbox.stream, "…")))`.
685
+ *
686
+ * **A best-guess view's pending predicate is `acked_at_us IS NULL`** (ADR-0060), not "the row is present":
687
+ * with `events.ackedRetentionMs > 0` an accepted event is STAMPED and RETAINED rather than deleted, because
688
+ * the server has only accepted it — its consumer has not folded it yet, and the folded aggregate has not
689
+ * synced back down. That retention window is the composition's **grace ledger**: keep counting an acked row
690
+ * until your own synced row's stamp passes its `acked_at_us` (or until the retention elapses and the lane's
691
+ * sweep deletes it), and the composed value stops dipping between the ack and the fold. At the default
692
+ * retention of `0` an acked row is deleted on the spot, so `acked_at_us` is never non-NULL and the predicate
693
+ * costs nothing.
623
694
  */
624
695
  export function getOutboxTable(registry: SyncTableRegistry): OutboxTable {
625
696
  const localSchema = getSyncRegistrySchema(registry);
package/src/mutation.ts CHANGED
@@ -24,7 +24,8 @@ import {
24
24
  type PgColumn,
25
25
  type PgInsertValue,
26
26
  } from "drizzle-orm/pg-core";
27
- import { drizzle } from "drizzle-orm/pglite";
27
+
28
+ import { drizzle } from "@pgxsinkit/pgwasm/drizzle";
28
29
 
29
30
  import {
30
31
  clearMutationRecoveryMarkerIfSettled,
@@ -190,7 +191,7 @@ export interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistr
190
191
  registryVersion?: string;
191
192
  /**
192
193
  * Whether pgxsinkit owns the local schema (and therefore the `pgxsinkit_local_meta` table the durable
193
- * recovery-required marker lives in). Defaults to `true`. A caller-owned `pgliteInstance` boot sets this
194
+ * recovery-required marker lives in). Defaults to `true`. A caller-owned `pgwasmInstance` boot sets this
194
195
  * `false`: the meta table may not exist, so the marker is never read/written and boot recovery runs
195
196
  * unconditionally.
196
197
  */
@@ -395,7 +396,7 @@ export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
395
396
  * runs from a consumer call ({@link recoverSending} keeps today's exact per-table semantics and never
396
397
  * touches the marker); {@link BootRecoveryOutcome} feeds the `warmBoot` BootReport fields verbatim.
397
398
  *
398
- * - `ownsMetaTable: false` (caller-owned PGlite) → unconditional recovery, marker untouched.
399
+ * - `ownsMetaTable: false` (caller-owned pgwasm) → unconditional recovery, marker untouched.
399
400
  * - `restore: true` → unconditional recovery + {@link quarantineRecovered} + self-verifying clear (marker ignored).
400
401
  * - marker `false` → skip the loop entirely.
401
402
  * - marker absent (not initialized) → one conservative recovery pass, then initialize the marker.
@@ -534,7 +535,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
534
535
  };
535
536
 
536
537
  // Whether pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` table the durable
537
- // recovery-required marker lives in). A caller-owned PGlite boot sets this false, so the marker is never
538
+ // recovery-required marker lives in). A caller-owned pgwasm boot sets this false, so the marker is never
538
539
  // touched and the SET/clear seams below are no-ops.
539
540
  const ownsMetaTable = options.ownsMetaTable ?? true;
540
541
  // Cached "this epoch has already committed the marker `true`" flag. Marker-first ordering:
@@ -608,7 +609,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
608
609
  // so relative to this synchronous check-and-reset block it is either
609
610
  // (i) BEFORE it → `markSendingInFlight > 0` here → no clear is issued at all (the FIX 1 gate); or
610
611
  // (ii) AFTER it → the sender reads `recoveryMarkerDirty === false` → it awaits
611
- // `writeMutationRecoveryRequired(true)`, and PGlite's single-connection queue serializes that upsert
612
+ // `writeMutationRecoveryRequired(true)`, and pgwasm's single-connection queue serializes that upsert
612
613
  // AFTER the already-issued clear → the marker is durably `true` again BEFORE the sender's `sending`
613
614
  // UPDATE (only issued once the marker await resolves) can commit. A crash between the rewrite and the
614
615
  // UPDATE leaves marker-`true`/no-row (conservative).
@@ -1440,7 +1441,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1440
1441
  const contexts = filterContexts(tableContexts, undefined);
1441
1442
  const tablesVisited = contexts.length;
1442
1443
 
1443
- // Caller-owned PGlite: the meta table may not exist, so never touch the marker and always recover.
1444
+ // Caller-owned pgwasm: the meta table may not exist, so never touch the marker and always recover.
1444
1445
  if (!bootOwnsMetaTable) {
1445
1446
  await runtime.recoverSending();
1446
1447
  return { skipped: false, required: true, tablesVisited, rowsRecovered: null };
@@ -3149,7 +3150,7 @@ async function reconcileTable(db: MutationDb, context: TableContext) {
3149
3150
  // (clear the overlay once the echo lands) or 'conflicted' (retire once a later write resolved it). When
3150
3151
  // none exist — the steady state of an idle entity set — all three statements below are no-ops, so skip
3151
3152
  // the whole transaction. This matters because the convergence driver runs reconcile for EVERY writable
3152
- // table on its interval (default 1.5s), and each CTE pays full PGlite plan+execute cost even against an
3153
+ // table on its interval (default 1.5s), and each CTE pays full pgwasm plan+execute cost even against an
3153
3154
  // empty journal: left unguarded it is the dominant idle-CPU cost. The real-time cleanup path is the
3154
3155
  // <table>_reconcile_on_sync trigger; this bulk pass is a fallback, so skipping it when there is nothing
3155
3156
  // to clear changes no outcome. The guard is a single existence probe over the (small, usually empty)
@@ -3302,7 +3303,7 @@ async function reconcileTable(db: MutationDb, context: TableContext) {
3302
3303
  await db.query(ackedClearQuery.sql, ackedClearQuery.params as unknown[]);
3303
3304
 
3304
3305
  // Clear acknowledged delete mutations where synced row is absent
3305
- // Single compound CTE — PGlite does not support multi-statement query().
3306
+ // Single compound CTE — pgwasm does not support multi-statement query().
3306
3307
  const clearableEntities = queryBuilder.$with("clearable_entities").as(
3307
3308
  queryBuilder
3308
3309
  .selectDistinct(
@@ -10,9 +10,9 @@
10
10
  // names.
11
11
 
12
12
  import { and, desc, eq, inArray, sql } from "drizzle-orm";
13
- import { drizzle } from "drizzle-orm/pglite";
14
13
 
15
14
  import type { MutationSummary, SyncTableName, SyncTableRegistry } from "@pgxsinkit/contracts";
15
+ import { drizzle } from "@pgxsinkit/pgwasm/drizzle";
16
16
 
17
17
  import { getAllMutationsView } from "./local-tables";
18
18
  import type { MutationDetail, MutationKind } from "./mutation";
@@ -25,7 +25,7 @@ export type MutationSummaryDetail = MutationDetail;
25
25
 
26
26
  /**
27
27
  * Build-only Drizzle (compiles to SQL via `.toSQL()`; never executes) — same mock seam mutation.ts uses.
28
- * Lazily constructed: some unit suites mock `drizzle-orm/pglite`, so `drizzle.mock` is unavailable at module
28
+ * Lazily constructed: some unit suites mock `@pgxsinkit/pgwasm/drizzle`, so `drizzle.mock` is unavailable at module
29
29
  * load; a lazy builder is only reached when a real query is actually authored (never in those mocked boots).
30
30
  */
31
31
  let queryBuilderInstance: ReturnType<typeof drizzle.mock> | undefined;
@@ -13,6 +13,7 @@
13
13
  // swallowed (deleteSentinel, deleteStoreDirectory). `observeCommitmentNamespace` never creates and never
14
14
  // throws — a root/API failure reads as `"unobservable"` (present absence is not historical proof).
15
15
 
16
+ import { withStoreOwnership, type OwnershipLocks } from "./store-ownership-lock";
16
17
  import { opfsCommitmentSentinelPath, opfsStoreDirectoryPath } from "./store-path";
17
18
 
18
19
  /**
@@ -34,15 +35,30 @@ export interface OpfsEffectsDeps {
34
35
  * `"unobservable"`, and the create effects throw (they are only reached in the opfs engine home).
35
36
  */
36
37
  getRoot?: () => Promise<DirLike>;
38
+ /**
39
+ * The Web Locks surface `deleteStoreDirectory` orders on (`store-ownership-lock.ts`). Omit in production: the
40
+ * default reads `navigator.locks` off `globalThis`; `null` (or an absent API) skips the ordering.
41
+ */
42
+ locks?: OwnershipLocks | null;
43
+ /** Bound on waiting for the store's owner to release before `deleteStoreDirectory` fails. Default 10 s. */
44
+ ownershipWaitMs?: number;
37
45
  }
38
46
 
39
47
  /** The effects surface the store-boot wiring drives (create-if-absent / delete-if-present / never-creating observe). */
40
48
  export interface OpfsEffects {
41
49
  /** Create-if-absent the commitment sentinel file at `pgxsinkit/commitments/<identity>`. */
42
50
  publishSentinel(): Promise<void>;
43
- /** Delete-if-present the commitment sentinel (`NotFoundError` swallowed). */
51
+ /**
52
+ * Delete-if-present the commitment sentinel (`NotFoundError` swallowed). A root that cannot be opened at all
53
+ * raises {@link OpfsRootUnavailableError}.
54
+ */
44
55
  deleteSentinel(): Promise<void>;
45
- /** Recursively delete-if-present the store directory `pgxsinkit/stores/<identity>` (`NotFoundError` swallowed). */
56
+ /**
57
+ * Recursively delete-if-present the store directory `pgxsinkit/stores/<identity>` (`NotFoundError` swallowed),
58
+ * under the store's ownership lock: the delete waits (bounded) until the context holding the directory's
59
+ * sync-access handles has released them, and fails with `StoreOwnershipWaitError` under a live owner. A root
60
+ * that cannot be opened at all raises {@link OpfsRootUnavailableError}.
61
+ */
46
62
  deleteStoreDirectory(): Promise<void>;
47
63
  /**
48
64
  * Never-creating walk of the commitment namespace. A root/API failure (or the API being absent) reads as
@@ -53,6 +69,29 @@ export interface OpfsEffects {
53
69
  getStoreDirectoryHandle(): Promise<unknown>;
54
70
  }
55
71
 
72
+ /**
73
+ * The OPFS root could not be opened AT ALL in this context — `navigator.storage.getDirectory()` rejected
74
+ * (WebKit's throwaway contexts reject with `UnknownError`; probably Safari private windows too). Raised only by
75
+ * the two DELETE effects, so the destruction wiring can tell "this context cannot reach OPFS" from a failure
76
+ * inside a reachable OPFS and record the OPFS side as pending instead (ADR-0036 amendment, 2026-09-28). The
77
+ * original rejection is the `cause`.
78
+ */
79
+ export class OpfsRootUnavailableError extends Error {
80
+ constructor(storePath: string, cause: unknown) {
81
+ super(
82
+ `[pgxsinkit] the OPFS root cannot be opened in this context, so the OPFS side of ${JSON.stringify(storePath)} ` +
83
+ "cannot be deleted here.",
84
+ { cause },
85
+ );
86
+ this.name = "OpfsRootUnavailableError";
87
+ }
88
+ }
89
+
90
+ /** Is this an {@link OpfsRootUnavailableError}? Name-based, so it survives duplicated module instances. */
91
+ export function isOpfsRootUnavailableError(error: unknown): boolean {
92
+ return (error as { name?: string } | null)?.name === "OpfsRootUnavailableError";
93
+ }
94
+
56
95
  /** Is this a `NotFoundError` (a missing OPFS entry) — the delete/observe "absent" signal? */
57
96
  function isNotFoundError(error: unknown): boolean {
58
97
  return (error as { name?: string } | null)?.name === "NotFoundError";
@@ -84,6 +123,19 @@ export function createOpfsEffects(storePath: string, deps?: OpfsEffectsDeps): Op
84
123
  return handle;
85
124
  }
86
125
 
126
+ // The delete effects' walk: identical, except that a REJECTING root (OPFS cannot be opened in this context at
127
+ // all) is raised as the typed {@link OpfsRootUnavailableError}, distinct from any failure inside a reachable OPFS.
128
+ async function walkDirectoriesForDelete(segments: readonly string[]): Promise<DirLike> {
129
+ let handle: DirLike;
130
+ try {
131
+ handle = await getRoot!();
132
+ } catch (error) {
133
+ throw new OpfsRootUnavailableError(storePath, error);
134
+ }
135
+ for (const segment of segments) handle = await handle.getDirectoryHandle(segment, { create: false });
136
+ return handle;
137
+ }
138
+
87
139
  // Never-creating existence check for one namespace entry; `NotFoundError` anywhere in the chain → absent.
88
140
  async function entryExists(path: readonly string[], kind: "file" | "dir"): Promise<boolean> {
89
141
  try {
@@ -117,7 +169,7 @@ export function createOpfsEffects(storePath: string, deps?: OpfsEffectsDeps): Op
117
169
  if (getRoot == null) return;
118
170
  const path = opfsCommitmentSentinelPath(storePath);
119
171
  try {
120
- const parent = await walkDirectories(path.slice(0, -1), false);
172
+ const parent = await walkDirectoriesForDelete(path.slice(0, -1));
121
173
  await parent.removeEntry(path[path.length - 1]!);
122
174
  } catch (error) {
123
175
  // Delete-if-present: a missing parent dir or a missing sentinel both count as already deleted.
@@ -128,13 +180,25 @@ export function createOpfsEffects(storePath: string, deps?: OpfsEffectsDeps): Op
128
180
  async deleteStoreDirectory(): Promise<void> {
129
181
  if (getRoot == null) return;
130
182
  const path = opfsStoreDirectoryPath(storePath);
131
- try {
132
- const parent = await walkDirectories(path.slice(0, -1), false);
133
- // Recursive: the store directory holds the four VFS-owned files; the whole leaf goes.
134
- await parent.removeEntry(path[path.length - 1]!, { recursive: true });
135
- } catch (error) {
136
- if (!isNotFoundError(error)) throw error;
137
- }
183
+ // Ordering, not retrying: the previous owner (a reloaded page's or a relocated engine's worker) may still
184
+ // hold the directory's EXCLUSIVE sync-access handles, and a `removeEntry` under them is refused. Its
185
+ // ownership lock is held until those handles are closed (or its context is gone), so take it first.
186
+ await withStoreOwnership(
187
+ storePath,
188
+ async () => {
189
+ try {
190
+ const parent = await walkDirectoriesForDelete(path.slice(0, -1));
191
+ // Recursive: the store directory holds the four VFS-owned files; the whole leaf goes.
192
+ await parent.removeEntry(path[path.length - 1]!, { recursive: true });
193
+ } catch (error) {
194
+ if (!isNotFoundError(error)) throw error;
195
+ }
196
+ },
197
+ {
198
+ ...(deps?.locks !== undefined ? { locks: deps.locks } : {}),
199
+ ...(deps?.ownershipWaitMs !== undefined ? { waitMs: deps.ownershipWaitMs } : {}),
200
+ },
201
+ );
138
202
  },
139
203
 
140
204
  async observeCommitmentNamespace(): Promise<