@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/schema.ts CHANGED
@@ -14,8 +14,6 @@ import {
14
14
  type SyncTableRegistry,
15
15
  } from "@pgxsinkit/contracts";
16
16
 
17
- import { buildClearShapeTagsSql, shapeTableId } from "./sync/tags";
18
-
19
17
  /** Internal fully-qualified projection used within schema generation. */
20
18
  interface ResolvedProjection {
21
19
  syncedTable: string;
@@ -73,6 +71,17 @@ export const LOCAL_META_TABLE = "pgxsinkit_local_meta";
73
71
  * `next_retry_at_us` is in the future is skipped by batch assembly. NULL = eligible now.
74
72
  * - `last_reason` — the most recent server `deferred` reason, kept on the row it belongs to (never a
75
73
  * second, retention-bearing verdict table — ADR-0053 rejects that).
74
+ * - `acked_at_us` — the **acked ledger** stamp (ADR-0060): when the server accepted the event, or NULL
75
+ * while it is still PENDING a verdict. NULL is the pending predicate — everything the library means by
76
+ * "pending" reads `acked_at_us IS NULL` (the drain signal, batch assembly, `diagnostics().outbox`, the
77
+ * non-forced `destroy()` refusal), so a stamped row is never re-posted and never keeps the lane
78
+ * "non-empty". It is stamped instead of deleted only when the client configures
79
+ * `events.ackedRetentionMs > 0`; at the default `0` an `acked` verdict deletes the row immediately and
80
+ * this column is never non-NULL. **For a best-guess view it is the grace ledger**: an `acked` row has
81
+ * been accepted but NOT yet folded by the server's consumer, and the folded aggregate has not yet synced
82
+ * back down — so a composition may keep counting an acked row until its own synced row's stamp passes
83
+ * `acked_at_us`, or until the retention elapses and the sweep deletes it. That dip is the whole reason
84
+ * the column exists.
76
85
  */
77
86
  export const OUTBOX_TABLE = "pgxsinkit_outbox";
78
87
 
@@ -161,15 +170,27 @@ function localMetaBootstrapStatements(localSchema: string): string[] {
161
170
  }
162
171
 
163
172
  /**
164
- * The **Outbox** DDL (ADR-0053 decision 2) — its sequence, table, and the two indexes that serve it. Emitted
165
- * unconditionally in the durable stream (never gated on `registry.streams`): the shape is stream-independent
166
- * and the table must exist before the first `appendEvent`, which may be the first thing an app does after a
167
- * registry gains its first Event stream. See {@link OUTBOX_TABLE} for the column contract.
173
+ * The **Outbox** DDL (ADR-0053 decision 2) — its sequence, table, and the three indexes that serve it.
174
+ * Emitted unconditionally in the durable stream (never gated on `registry.streams`): the shape is
175
+ * stream-independent and the table must exist before the first `appendEvent`, which may be the first thing
176
+ * an app does after a registry gains its first Event stream. See {@link OUTBOX_TABLE} for the column
177
+ * contract.
178
+ *
179
+ * **CREATE-only, deliberately** (ADR-0060): these are `IF NOT EXISTS` statements, so a store provisioned
180
+ * before a column existed does NOT gain it — there is no ALTER path and no adoption. A store predating
181
+ * `acked_at_us` is reset at the consumer's cutover, per this library's greenfield rule.
168
182
  *
169
- * Two indexes, one per access pattern:
183
+ * Three indexes, one per access pattern:
170
184
  * - `(stream, seq)` serves the APP's `WHERE stream = ?` best-guess-view queries in append order;
171
185
  * - `(next_retry_at_us, seq)` serves BATCH ASSEMBLY — ordered by `seq` across all streams, skipping rows
172
- * whose deferred backoff has not elapsed.
186
+ * whose deferred backoff has not elapsed;
187
+ * - `(acked_at_us, seq)` serves BOTH halves of the acked ledger (ADR-0060) with one index: the pending
188
+ * predicate `acked_at_us IS NULL ORDER BY seq` that every "pending" read now carries (assembly, the
189
+ * drain signal), and the retention sweep's `acked_at_us <= now - retention`. A partial index on `seq`
190
+ * `WHERE acked_at_us IS NULL` would serve the pending side slightly more tightly and leave the SWEEP
191
+ * with no index at all — it targets exactly the rows such an index excludes, which in a ledger-enabled
192
+ * store are most of the table. Leading on `acked_at_us` keeps both as range scans, and `seq` second
193
+ * keeps assembly's ordering free of a sort.
173
194
  */
174
195
  function outboxStatements(localSchema: string): string[] {
175
196
  const outboxTable = qualifyIdentifier(localSchema, OUTBOX_TABLE);
@@ -187,9 +208,11 @@ function outboxStatements(localSchema: string): string[] {
187
208
  "attempt_count INTEGER NOT NULL DEFAULT 0",
188
209
  "next_retry_at_us BIGINT",
189
210
  "last_reason TEXT",
211
+ "acked_at_us BIGINT",
190
212
  ].join(",\n ")}\n);`,
191
213
  renderCreateIndexStatement(outboxTable, `${OUTBOX_TABLE}_stream_seq_idx`, ["stream", "seq"]),
192
214
  renderCreateIndexStatement(outboxTable, `${OUTBOX_TABLE}_retry_seq_idx`, ["next_retry_at_us", "seq"]),
215
+ renderCreateIndexStatement(outboxTable, `${OUTBOX_TABLE}_acked_seq_idx`, ["acked_at_us", "seq"]),
193
216
  ];
194
217
  }
195
218
 
@@ -221,11 +244,13 @@ function buildEntryClusterStatements(entry: SyncTableEntry, tableKey: string, lo
221
244
  const temp = ephemeral ? "TEMP " : "";
222
245
 
223
246
  const projection = getClientProjection(entry, tableKey, objectSchema);
224
- const columns = getProjectedColumns(entry).map(({ column }) => column);
247
+ const projectedColumns = getProjectedColumns(entry);
248
+ const columns = projectedColumns.map(({ column }) => column);
225
249
  const syncedTablePrimaryKeyColumns = getLocalSyncPrimaryKeyColumns(entry);
226
250
  const baseColumnsSql = buildTableColumnSql(columns, syncedTablePrimaryKeyColumns, localSchema);
227
251
 
228
252
  statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.syncedTable} (\n ${baseColumnsSql}\n);`);
253
+ statements.push(...buildLocalIndexStatements(entry, projection.syncedTable, projectedColumns));
229
254
 
230
255
  if (entry.mode === "readonly") {
231
256
  return statements;
@@ -336,8 +361,8 @@ function buildEntryClusterStatements(entry: SyncTableEntry, tableKey: string, lo
336
361
  );
337
362
 
338
363
  // Trigger: automatically clear overlay + journal entries when the sync
339
- // echo arrives. Fires on INSERT/UPDATE (new data from Electric) and DELETE
340
- // (row removed on server, synced back via Electric).
364
+ // echo arrives. Fires on INSERT/UPDATE (new data down the read path) and
365
+ // DELETE (row removed on the server, streamed back down the read path).
341
366
  const pkMatchSql = (alias: string) =>
342
367
  primaryKeyColumns
343
368
  .map((col) => `"${alias}"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`)
@@ -571,7 +596,6 @@ function buildReadModelViewSql(
571
596
  throw new Error(`overlay table is required for writable table ${projection.syncedTable}`);
572
597
  }
573
598
 
574
- const pkMatch = buildPrimaryKeyMatch(entry.primaryKey.columns);
575
599
  const syncedLocalUpdatedExpression = columnNames.includes("updated_at_us") ? "t.updated_at_us" : "CAST(0 AS BIGINT)";
576
600
 
577
601
  return [
@@ -587,14 +611,98 @@ function buildReadModelViewSql(
587
611
  ` 'synced' AS overlay_kind,`,
588
612
  ` ${syncedLocalUpdatedExpression} AS local_updated_at_us`,
589
613
  `FROM ${projection.syncedTable} AS t`,
590
- "WHERE NOT EXISTS (",
591
- " SELECT 1",
592
- ` FROM ${projection.overlayTable} AS o`,
593
- ` WHERE ${pkMatch}`,
594
- ")",
614
+ ...buildOverlayNonMembershipTest(entry.primaryKey.columns, projection.overlayTable),
595
615
  ].join("\n");
596
616
  }
597
617
 
618
+ /**
619
+ * Render the entry's OPT-IN `clientProjection.localIndexes` on its synced table (never on the overlay,
620
+ * never on the journal) through the same {@link renderCreateIndexStatement} core the journal indexes use,
621
+ * so every index this generator emits has one statement shape.
622
+ *
623
+ * Only what a consumer declared: a synced table's SERVER indexes are deliberately not mirrored (they serve
624
+ * server loads and routinely cover columns the client projection omits), so the local store carries the
625
+ * primary key plus exactly these. A column may be named by DB column name or by Drizzle property key — the
626
+ * either/or the primary-key specs accept — and is resolved to the DB column name here; the registry has
627
+ * already refused an unknown column, an omitted one, and a duplicate index name, so a name that fails to
628
+ * resolve at this point is a generator bug, not a consumer error.
629
+ */
630
+ function buildLocalIndexStatements(
631
+ entry: SyncTableEntry,
632
+ syncedTable: string,
633
+ projectedColumns: ReturnType<typeof getProjectedColumns>,
634
+ ): string[] {
635
+ const localIndexes = entry.clientProjection?.localIndexes ?? [];
636
+ if (localIndexes.length === 0) {
637
+ return [];
638
+ }
639
+
640
+ const columnNameByKey = new Map<string, string>();
641
+ for (const { propertyKey, columnName } of projectedColumns) {
642
+ columnNameByKey.set(propertyKey, columnName);
643
+ columnNameByKey.set(columnName, columnName);
644
+ }
645
+
646
+ return localIndexes.map((index) => {
647
+ const columnExpressions = index.columns.map((column) => {
648
+ const columnName = columnNameByKey.get(column);
649
+ if (!columnName) {
650
+ throw new Error(
651
+ `local index ${index.name} on ${syncedTable} names column ${column}, which is not a projected column`,
652
+ );
653
+ }
654
+ return maybeQuoteIdentifier(columnName);
655
+ });
656
+ return renderCreateIndexStatement(syncedTable, maybeQuoteIdentifier(index.name), columnExpressions, {
657
+ ...(index.unique === true ? { unique: true } : {}),
658
+ });
659
+ });
660
+ }
661
+
662
+ /**
663
+ * The synced branch's "this row is not shadowed by the overlay" test, as a NOT IN over the overlay's
664
+ * primary key — **a plan choice, not a style one**, and the one place the read model's cost is decided.
665
+ *
666
+ * The obvious form (`NOT EXISTS (SELECT 1 FROM overlay o WHERE o.pk = t.pk)`, and its `LEFT JOIN … IS
667
+ * NULL` twin) leaves the shape to the planner, and the planner gets it wrong in the overlay's NORMAL
668
+ * state. An overlay that is physically empty AND has been analysed reports `relpages = 0, reltuples = 0`,
669
+ * so `estimate_rel_size` skips its never-vacuumed 10-page floor and costs a scan of it at **0.00** — a
670
+ * free inner relation, which makes a `Nested Loop Anti Join` look cheapest. The executor then RESCANS the
671
+ * empty overlay once per synced row (`loops = <rowcount>`), and the rescan is not free: on 100k synced rows
672
+ * read through the view, that form measures ~180-260 ms against ~95-145 ms for a hash anti join
673
+ * (`tests/unit/read-model-overlay-plan` logs both per run), and a consumer measured 224 ms of a 270 ms
674
+ * selection sitting in that node. No index fixes it — the
675
+ * overlay's PRIMARY KEY already IS an index, and an index scan cannot beat a 0.00-cost seq scan; an
676
+ * `ANALYZE` does not fix it either, it is what CAUSES it (a never-analysed overlay gets the 10-page floor
677
+ * and plans as a hash anti join).
678
+ *
679
+ * `NOT IN` takes the choice away: the subquery is uncorrelated, so Postgres evaluates it ONCE into a
680
+ * hashed SubPlan and each synced row is a hash probe — measured ~95-215 ms in that same pathological state
681
+ * (roughly half the nested loop, machine-load dependent), 106 ms with no statistics at all, and 60 ms (vs
682
+ * 196 ms) for a composite key. The one cost is the tail:
683
+ * above roughly `hash_mem / (pk width + 24)` rows — order 150k pending overlay rows at the default 4 MB —
684
+ * the planner stops hashing and the SubPlan becomes a per-row rescan, which IS quadratic. That trade is
685
+ * taken deliberately: the overlay holds only rows with an unflushed local mutation, so tens of thousands
686
+ * is already an app in trouble, while "empty and analysed" is the steady state of every read-mostly table.
687
+ * (`EXPLAIN` tells the two apart: `hashed SubPlan` vs a bare `SubPlan`.)
688
+ *
689
+ * The NULL trap that normally disqualifies `NOT IN` cannot fire here: both sides are PRIMARY KEY columns
690
+ * of tables this generator emits (the overlay carries the same key as the synced table), so neither side
691
+ * can be NULL and `NOT IN` is exactly equivalent to the `NOT EXISTS` it replaces.
692
+ */
693
+ function buildOverlayNonMembershipTest(primaryKeyColumns: string[], overlayTable: string): string[] {
694
+ const key =
695
+ primaryKeyColumns.length === 1
696
+ ? `t.${primaryKeyColumns[0]}`
697
+ : `(${primaryKeyColumns.map((column) => `t.${column}`).join(", ")})`;
698
+ return [
699
+ `WHERE ${key} NOT IN (`,
700
+ ` SELECT ${primaryKeyColumns.map((column) => `o.${column}`).join(", ")}`,
701
+ ` FROM ${overlayTable} AS o`,
702
+ ")",
703
+ ];
704
+ }
705
+
598
706
  function buildTableColumnSql(columns: TableColumn[], primaryKeyColumns: string[], localSchema: string) {
599
707
  return [
600
708
  ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumns, localSchema)),
@@ -621,7 +729,7 @@ function buildTableColumnSql(columns: TableColumn[], primaryKeyColumns: string[]
621
729
  * takes the UNqualified relation name (the TEMP keyword places it in `pg_temp`; a `CREATE TEMP TABLE
622
730
  * pg_temp.x` target is not portable). Same relation/index NAMES as the durable form: an index name lives
623
731
  * per schema, so the durable (metadata-schema) and session (`pg_temp`) indexes coexist without collision
624
- * (probed on real PGlite).
732
+ * (probed on real pgwasm).
625
733
  *
626
734
  * CAVEAT — the `temp` flag only bares the RELATION name; `buildTableColumnSql` below still receives
627
735
  * `schemaName` and would qualify any ENUM column type into THAT schema. That is correct only because the
@@ -984,10 +1092,6 @@ function readArrayDimensions(column: TableColumn) {
984
1092
  return arrayColumn.dimensions ?? 0;
985
1093
  }
986
1094
 
987
- function buildPrimaryKeyMatch(primaryKeyColumns: string[]) {
988
- return primaryKeyColumns.map((column) => `o.${column} = t.${column}`).join(" AND ");
989
- }
990
-
991
1095
  function getClientProjection(entry: SyncTableEntry, tableKey: string, localSchema: string): ResolvedProjection {
992
1096
  const projection = baseProjection(entry, tableKey);
993
1097
  const syncedTableName = projection.syncedTable ?? tableKey;
@@ -1136,12 +1240,5 @@ export function buildDesyncTableSql<TRegistry extends SyncTableRegistry>(
1136
1240
  }
1137
1241
  }
1138
1242
 
1139
- // ADR-0023 Slice 2: a desync reverts the relation to dormant and deletes its subscription, so the next
1140
- // activation re-streams from scratch — drop this shape's tag-set too, or it would orphan tags for rows
1141
- // that never come back. The key matches what the engine writes (`shapeTableId(shape.schema, table)`):
1142
- // for ephemeral the engine passes no schema (→ `public`), exactly this `objectSchema`.
1143
- const syncedTableNameRaw = baseProjection(entry, tableKey).syncedTable ?? tableKey;
1144
- statements.push(buildClearShapeTagsSql(shapeTableId(objectSchema, syncedTableNameRaw)));
1145
-
1146
1243
  return `${statements.join("\n")}\n`;
1147
1244
  }
package/src/store-boot.ts CHANGED
@@ -26,13 +26,15 @@
26
26
  // 10b/11. The returned {@link StoreBootResolution.verdict} tells the caller a candidate is uncommitted and
27
27
  // needs that barrier.
28
28
 
29
- import { createOpfsEffects, type OpfsEffectsDeps } from "./opfs-effects";
29
+ import { createOpfsEffects, isOpfsRootUnavailableError, type OpfsEffectsDeps } from "./opfs-effects";
30
30
  import { beginFreshCandidate, resumeDeletion } from "./store-lifecycle";
31
31
  import {
32
32
  classifyStoreBoot,
33
+ clearOpfsDeletionPending,
33
34
  deleteStoreMetaRecord,
34
35
  idbStoreExists as defaultIdbStoreExists,
35
36
  META_STORE_UNAVAILABLE,
37
+ readOpfsDeletionPending,
36
38
  readStoreMetaRecord,
37
39
  type StoreBootVerdict,
38
40
  type StoreMetaDeps,
@@ -51,7 +53,7 @@ export type ResolvedStorageBackend = "opfs-repacked" | "idbfs" | "filesystem" |
51
53
 
52
54
  /** The outcome of {@link resolveStoreBoot}: the URL to open the store at, its backend, and the boot verdict. */
53
55
  export interface StoreBootResolution {
54
- /** The PGlite dataDir URL, always assembled by {@link resolveStoreDataDir} (the one URL assembler). */
56
+ /** The pgwasm dataDir URL, always assembled by {@link resolveStoreDataDir} (the one URL assembler). */
55
57
  dataDir: string;
56
58
  /** The resolved backend, for diagnostics. */
57
59
  storageBackend: ResolvedStorageBackend;
@@ -109,9 +111,9 @@ function resolveDeleteSurface(meta?: StoreMetaDeps): IdbDeleteSurface | undefine
109
111
  }
110
112
 
111
113
  /**
112
- * Delete-if-present the PGlite idb database for a store (`indexedDB.deleteDatabase`), backend-agnostic and
114
+ * Delete-if-present the pgwasm idb database for a store (`indexedDB.deleteDatabase`), backend-agnostic and
113
115
  * idempotent: absent counts as deleted, while a real failure rejects. The database name comes
114
- * ONLY from {@link storeIndexedDbDatabaseName} (store-path's sole owner of PGlite's `/pglite/` naming).
116
+ * ONLY from {@link storeIndexedDbDatabaseName} (store-path's sole route to pgwasm's IndexedDB naming).
115
117
  */
116
118
  function deleteIdbDatabase(storePath: string, meta?: StoreMetaDeps): Promise<void> {
117
119
  const idb = resolveDeleteSurface(meta);
@@ -221,6 +223,39 @@ export function committedStoreUnreachableFromWire(detail: unknown): CommittedSto
221
223
  return new CommittedStoreUnreachableError(candidate.storePath);
222
224
  }
223
225
 
226
+ /** The outcome of {@link settlePendingOpfsDeletion}. */
227
+ export type PendingOpfsDeletionOutcome = "none" | "settled" | "still-pending";
228
+
229
+ /**
230
+ * Settle an "OPFS deletion pending" marker (ADR-0036 amendment, 2026-09-28) — the FIRST thing every browser boot
231
+ * does, before any classification or open. A store destroyed in a context that could not open OPFS at all left
232
+ * its OPFS store directory and commitment sentinel (if it ever had them) behind, with the marker as the durable
233
+ * obligation. When this boot can reach OPFS it deletes the sentinel, then the store directory (under the
234
+ * store's ownership lock), and only then clears the marker — so a leftover sentinel never reaches the classifier
235
+ * as "no record + sentinel" (`repair-record-then-open-committed`, which would reopen destroyed data). When it
236
+ * still cannot reach OPFS (the namespace is unobservable, or the root rejects mid-settlement) the marker stays
237
+ * and the boot proceeds: such a context cannot open an OPFS store anyway.
238
+ *
239
+ * An unreadable marker propagates ({@link StoreMetaUnreadableError}) — never read as "no marker".
240
+ */
241
+ export async function settlePendingOpfsDeletion(
242
+ storePath: string,
243
+ deps?: ResolveStoreBootOptions["deps"],
244
+ ): Promise<PendingOpfsDeletionOutcome> {
245
+ if (!(await readOpfsDeletionPending(storePath, deps?.meta))) return "none";
246
+ const effects = createOpfsEffects(storePath, deps?.opfs);
247
+ if ((await effects.observeCommitmentNamespace()) === "unobservable") return "still-pending";
248
+ try {
249
+ await effects.deleteSentinel();
250
+ await effects.deleteStoreDirectory();
251
+ } catch (error) {
252
+ if (isOpfsRootUnavailableError(error)) return "still-pending";
253
+ throw error;
254
+ }
255
+ await clearOpfsDeletionPending(storePath, deps?.meta);
256
+ return "settled";
257
+ }
258
+
224
259
  /**
225
260
  * The PRE-MINT meta gate every probe-denied (no OPFS sync access) browser boot passes through — one bounded
226
261
  * meta read serving both of the record's claims such a boot must honour, before any replacement IDB store is
@@ -246,13 +281,27 @@ export function committedStoreUnreachableFromWire(detail: unknown): CommittedSto
246
281
  *
247
282
  * An UNREADABLE record propagates ({@link StoreMetaUnreadableError}) — a failed meta read is an error, never
248
283
  * "no record" (invariant 12).
284
+ *
285
+ * A pending OPFS deletion is settled first when this home can reach OPFS asynchronously
286
+ * ({@link settlePendingOpfsDeletion}; it runs alongside the record read, which it does not touch).
287
+ *
288
+ * **An interrupted destroy whose OPFS side is already pending** (ADR-0036 amendment, 2026-09-28): a `deleting`
289
+ * record in a scope whose commitment namespace is unobservable is normally refused (sentinel removal cannot be
290
+ * confirmed). When the "OPFS deletion pending" marker for this identity still stands, the destroy got past its
291
+ * marker step, so the OPFS side is already durably deferred to the next OPFS-capable boot: this boot finishes
292
+ * the IndexedDB side (the idb database, then the meta record — destroy's own order), leaves the marker, and
293
+ * proceeds as a fresh boot. Returns `false` (no authority is published; the fresh boot is recordless). Without
294
+ * the marker (interrupted before the marker step) the refusal stands.
249
295
  */
250
296
  export async function resolveDeniedBootAuthority(
251
297
  storePath: string,
252
298
  deps?: ResolveStoreBootOptions["deps"],
253
299
  ): Promise<boolean> {
254
300
  const meta = deps?.meta;
255
- const record = await readStoreMetaRecord(storePath, meta);
301
+ const [record, pendingOpfsDeletion] = await Promise.all([
302
+ readStoreMetaRecord(storePath, meta),
303
+ settlePendingOpfsDeletion(storePath, deps),
304
+ ]);
256
305
  if (record === META_STORE_UNAVAILABLE) return false;
257
306
  // The committed refusal rides THIS read — a no-grant boot never gets a second look at the record, and the
258
307
  // hazard (an empty idb sibling minted over a committed store) is decided by exactly this phase.
@@ -265,6 +314,14 @@ export async function resolveDeniedBootAuthority(
265
314
  // cannot be observed, sentinel deletion cannot be confirmed. Keep the recorded phase authoritative and fail
266
315
  // closed rather than publish a conflicting replacement.
267
316
  if ((await effects.observeCommitmentNamespace()) === "unobservable") {
317
+ // ADR-0036 amendment (2026-09-28): a `deleting` store whose marker still stands was interrupted AFTER the
318
+ // marker step, so its OPFS side is already recorded as pending — finish the IndexedDB side of the destroy
319
+ // (keeping the marker) and boot fresh. Without the marker the recorded phase stays authoritative.
320
+ if (phase === "deleting" && pendingOpfsDeletion === "still-pending") {
321
+ await deleteIdbDatabase(storePath, meta);
322
+ await deleteStoreMetaRecord(storePath, meta);
323
+ return false;
324
+ }
268
325
  throw new Error(
269
326
  `[pgxsinkit] cannot settle ${JSON.stringify(storePath)} for an IDB boot (record phase ` +
270
327
  `${JSON.stringify(phase)}): the OPFS commitment namespace is unobservable in this scope, so sentinel ` +
@@ -288,7 +345,9 @@ export async function resolveDeniedBootAuthority(
288
345
  * no meta machinery).
289
346
  * - **non-browser** (no idb, no opfs handles) → `file://` passthrough, no classification (the filesystem
290
347
  * backend has no meta machinery either).
291
- * - **browser** → read the meta record ({@link readStoreMetaRecord}; {@link StoreMetaUnreadableError}
348
+ * - **browser** → settle any pending OPFS deletion FIRST ({@link settlePendingOpfsDeletion} — alongside the first
349
+ * meta read, which it does not touch, and before any observation, classification or open), then read the meta
350
+ * record ({@link readStoreMetaRecord}; {@link StoreMetaUnreadableError}
292
351
  * propagates = fail closed, invariant 12), map {@link META_STORE_UNAVAILABLE} to a provable absence
293
352
  * (no idb ⇒ no record and no existing idb store), observe the commitment namespace and the recordless idb fact,
294
353
  * classify, and execute:
@@ -360,11 +419,16 @@ export async function resolveStoreBoot(storePath: string, opts: ResolveStoreBoot
360
419
  return { dataDir: idbDataDir, storageBackend: "idbfs", verdict };
361
420
  };
362
421
 
422
+ // ADR-0036 amendment (2026-09-28): a store destroyed where OPFS could not be opened has its OPFS side pending.
423
+ // Settle it before anything below observes, classifies or opens; it touches OPFS and the marker only, so it
424
+ // overlaps the first meta read instead of adding a serial IndexedDB round trip to every boot.
425
+ const pendingOpfsDeletion = settlePendingOpfsDeletion(storePath, opts.deps);
426
+
363
427
  // The two record-clearing verdicts loop; every other verdict returns. Cleared record → a terminal verdict.
364
428
  for (let iteration = 0; iteration < MAX_DELETION_RECLASSIFY; iteration += 1) {
365
429
  // A failed meta read is an ERROR, never "no record" (invariant 12): StoreMetaUnreadableError propagates
366
430
  // here and fails the boot closed.
367
- const metaResult = await readStoreMetaRecord(storePath, meta);
431
+ const [metaResult] = await Promise.all([readStoreMetaRecord(storePath, meta), pendingOpfsDeletion]);
368
432
  // META_STORE_UNAVAILABLE means IndexedDB is entirely absent — a no-idb scope cannot hold a record, so
369
433
  // absence is PROVABLE (record undefined) and there can be no existing idb store either (idbStoreExists
370
434
  // false). Faithful to store-meta's documented mapping.
@@ -0,0 +1,37 @@
1
+ import { type StorageBuild, StorageBuildMismatchError, type StoreBuildCheckSite } from "@pgxsinkit/contracts";
2
+ import type { BuildIdentity } from "@pgxsinkit/pgwasm";
3
+
4
+ /**
5
+ * The supplied-build check (ADR-0063). A store's Postgres build is code — a `PostgresBuild` a site supplies,
6
+ * or the build an adopted instance reports as `pg.build` — never the declared string. The registry's
7
+ * `storage.build` (default `"c"`) must name it:
8
+ *
9
+ * - before any mint, against the build the site supplies (the `createSyncClient` boot, the worker's
10
+ * provision and spare mints, a `createPgwasmClient` with a declaration threaded to it);
11
+ * - on every adopted instance, against `pg.build` (`pgwasmInstance`, `precreatedPgwasm`, a worker
12
+ * `createStore` result).
13
+ *
14
+ * A mismatch throws {@link StorageBuildMismatchError} before any store is touched. Declaring `pgrust` and
15
+ * supplying no build is a mismatch too: the default build is `cBuild`.
16
+ */
17
+ export function assertStoreBuild(declared: StorageBuild, supplied: BuildIdentity, site: StoreBuildCheckSite): void {
18
+ if (supplied.name !== declared) throw new StorageBuildMismatchError(declared, supplied.name, site);
19
+ }
20
+
21
+ /**
22
+ * The typed build refusals (ADR-0063): the declared build is not the supplied one, or the data directory or
23
+ * backup was made by another build or data format, or its marker is unreadable. Matched by `name`, which is
24
+ * stable across bundle copies and the worker bridge. None of them is transient, so an open that failed with
25
+ * one is never retried.
26
+ */
27
+ const STORE_BUILD_REFUSALS: ReadonlySet<string> = new Set([
28
+ "StorageBuildMismatchError",
29
+ "BuildMismatchError",
30
+ "DataFormatMismatchError",
31
+ "BuildMarkerUnreadableError",
32
+ ]);
33
+
34
+ /** Is `error` a typed build refusal ({@link STORE_BUILD_REFUSALS}), which a retry cannot change? */
35
+ export function isStoreBuildRefusal(error: unknown): boolean {
36
+ return error instanceof Error && STORE_BUILD_REFUSALS.has(error.name);
37
+ }
@@ -0,0 +1,94 @@
1
+ import type { PgwasmClient } from "./index";
2
+
3
+ // ── The DECLARED store engine (ADR-0050 addendum 2026-09-08) ─────────────────────────────────────
4
+ //
5
+ // A store's storage declaration may name an ENGINE: `storage.engine = { module: <module URL> }`. When it
6
+ // does, THAT module mints the store instead of the toolkit's own `createPgwasmClient` — so an application
7
+ // can drive a different PostgreSQL-shaped engine, one that lives outside this repo, without a line of
8
+ // engine-specific code in the toolkit. Nothing here knows, names or imports any particular engine: the
9
+ // module URL is the entire surface.
10
+ //
11
+ // The contract is the toolkit's own `createStore` seam (ADR-0036), unchanged and unextended — the module's
12
+ // DEFAULT export, or failing that a named `createStore`:
13
+ //
14
+ // (storePath: string, backendOverride?: "memory") => Promise<PgwasmClient>
15
+ //
16
+ // `storePath` is a plain store NAME, never a storage URL. The handle comes back and is used exactly as a
17
+ // `createPgwasmClient` one is, so it must carry the whole `PgwasmClient` surface the engine touches — `live`
18
+ // included. Everything the seam does not pass, the module owns: its own assets (derivable from
19
+ // `import.meta.url`; there is no asset base and there will not be one), its own storage layout under the
20
+ // store path, and its own environment requirements (a threaded engine that needs a cross-origin-isolated
21
+ // page, or a scope with no main thread, refuses to construct from inside the module, loudly).
22
+ //
23
+ // Both failure modes are LOUD and specific — an unloadable URL and a module with no callable export are the
24
+ // two ways a declared module goes wrong, and either one silently falling back to the built-in store would
25
+ // report a healthy engine for one that never ran.
26
+
27
+ /** The one function the declared engine trades in — the toolkit's `createStore` option (ADR-0036). */
28
+ export type StoreEngineFactory = (storePath: string, backendOverride?: "memory") => Promise<PgwasmClient>;
29
+
30
+ /** How a scope loads a module URL: the dynamic `import()` in a browser scope, a stub in a unit test. */
31
+ export type StoreEngineModuleLoader = (url: string) => Promise<unknown>;
32
+
33
+ /**
34
+ * The default loader: a runtime-valued dynamic `import()`.
35
+ *
36
+ * `@vite-ignore` because the URL is a value, naming a module OUTSIDE any bundle — a bundler that tried to
37
+ * resolve or pre-bundle it would either fail the build or, worse, inline a stale copy.
38
+ */
39
+ const importStoreEngineModule: StoreEngineModuleLoader = (url) => import(/* @vite-ignore */ url);
40
+
41
+ /**
42
+ * Import one store-engine module URL and take its factory: the default export, else a named `createStore`.
43
+ *
44
+ * @param module the declared `storage.engine.module` — an absolute or origin-relative module URL.
45
+ * @param load how to import it; defaults to a dynamic `import()` in the calling scope.
46
+ */
47
+ export async function loadStoreEngineFactory(
48
+ module: string,
49
+ load: StoreEngineModuleLoader = importStoreEngineModule,
50
+ ): Promise<StoreEngineFactory> {
51
+ let loaded: unknown;
52
+ try {
53
+ loaded = await load(module);
54
+ } catch (cause) {
55
+ throw new Error(
56
+ `[pgxsinkit] the declared store engine "${module}" could not be imported. \`storage.engine.module\` ` +
57
+ `must be a module URL THIS scope can import — same-origin, or cross-origin with CORS and (under ` +
58
+ `cross-origin isolation) Cross-Origin-Resource-Policy: cross-origin.`,
59
+ { cause },
60
+ );
61
+ }
62
+ const exports = (loaded ?? {}) as { default?: unknown; createStore?: unknown };
63
+ const factory = typeof exports.default === "function" ? exports.default : exports.createStore;
64
+ if (typeof factory !== "function") {
65
+ throw new Error(
66
+ `[pgxsinkit] the declared store engine "${module}" exports no store factory. Expected a default ` +
67
+ `export (or a named \`createStore\`) of ` +
68
+ `\`(storePath: string, backendOverride?: "memory") => Promise<PgwasmClient>\`.`,
69
+ );
70
+ }
71
+ return factory as StoreEngineFactory;
72
+ }
73
+
74
+ /**
75
+ * A per-scope resolver that loads each declared engine module ONCE and reuses it for every later mint.
76
+ *
77
+ * The memo keeps the REJECTION too: a failed load stays failed for the scope's lifetime, so every later
78
+ * mint reports the same loud error instead of quietly succeeding on the built-in engine (a declared engine
79
+ * that half-ran is a worse outcome than one that never started). Keyed by module URL, so a scope that is
80
+ * somehow asked for two engines gets two loads and no cross-talk.
81
+ */
82
+ export function createStoreEngineResolver(
83
+ load: StoreEngineModuleLoader = importStoreEngineModule,
84
+ ): (module: string) => Promise<StoreEngineFactory> {
85
+ const loading = new Map<string, Promise<StoreEngineFactory>>();
86
+ return (module) => {
87
+ let pending = loading.get(module);
88
+ if (pending === undefined) {
89
+ pending = loadStoreEngineFactory(module, load);
90
+ loading.set(module, pending);
91
+ }
92
+ return pending;
93
+ };
94
+ }
@@ -3,7 +3,7 @@
3
3
  // over the plan's crash tables. CONTEXT § "Language — engine placement" terms used exactly: "Commitment
4
4
  // marker", "Destructive lifecycle".
5
5
  //
6
- // EFFECT-INJECTED BY CONSTRUCTION. None of these machines touches IndexedDB, OPFS, or PGlite: every side
6
+ // EFFECT-INJECTED BY CONSTRUCTION. None of these machines touches IndexedDB, OPFS, or pgwasm: every side
7
7
  // effect is a method on an injected effects object. Plan step 10 wires the REAL effects (the meta record IO
8
8
  // from `store-meta.ts`, the OPFS namespace builders from `store-path.ts`, the live engine's `strictSync()`);
9
9
  // unit tests inject fakes and simulate a crash by making one effect throw, then re-run the resume path from