@pgxsinkit/client 0.1.36 → 0.1.41

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 (64) hide show
  1. package/dist/boot-report.d.ts +134 -0
  2. package/dist/boot-report.d.ts.map +1 -0
  3. package/dist/export-data.d.ts +100 -0
  4. package/dist/export-data.d.ts.map +1 -0
  5. package/dist/export-dump.d.ts +92 -0
  6. package/dist/export-dump.d.ts.map +1 -0
  7. package/dist/export-store.d.ts +214 -0
  8. package/dist/export-store.d.ts.map +1 -0
  9. package/dist/index.d.ts +206 -13
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +1373 -8308
  12. package/dist/index.js.map +25 -131
  13. package/dist/lazy-guard.d.ts +4 -3
  14. package/dist/lazy-guard.d.ts.map +1 -1
  15. package/dist/lifecycle-slot.d.ts +31 -0
  16. package/dist/lifecycle-slot.d.ts.map +1 -0
  17. package/dist/live-rows-sql.d.ts +21 -0
  18. package/dist/live-rows-sql.d.ts.map +1 -0
  19. package/dist/mutation-state.d.ts +9 -2
  20. package/dist/mutation-state.d.ts.map +1 -1
  21. package/dist/mutation.d.ts +12 -0
  22. package/dist/mutation.d.ts.map +1 -1
  23. package/dist/schema.d.ts +33 -0
  24. package/dist/schema.d.ts.map +1 -1
  25. package/dist/shape-sync.d.ts +10 -0
  26. package/dist/shape-sync.d.ts.map +1 -1
  27. package/dist/store-path.d.ts +132 -0
  28. package/dist/store-path.d.ts.map +1 -0
  29. package/dist/sync/index.d.ts +1 -1
  30. package/dist/sync/index.d.ts.map +1 -1
  31. package/dist/sync/types.d.ts +8 -0
  32. package/dist/sync/types.d.ts.map +1 -1
  33. package/dist/testing.d.ts +27 -0
  34. package/dist/testing.d.ts.map +1 -0
  35. package/dist/testing.js +17 -0
  36. package/dist/testing.js.map +11 -0
  37. package/dist/worker/attach-sync-client.d.ts +23 -2
  38. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  39. package/dist/worker/define-sync-worker.d.ts +5 -4
  40. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  41. package/dist/worker/protocol.d.ts +89 -8
  42. package/dist/worker/protocol.d.ts.map +1 -1
  43. package/package.json +9 -4
  44. package/skills/core/SKILL.md +14 -1
  45. package/skills/operating/SKILL.md +75 -15
  46. package/src/boot-report.ts +287 -0
  47. package/src/export-data.ts +300 -0
  48. package/src/export-dump.ts +239 -0
  49. package/src/export-store.ts +309 -0
  50. package/src/index.ts +623 -82
  51. package/src/lazy-guard.ts +23 -9
  52. package/src/lifecycle-slot.ts +66 -0
  53. package/src/live-rows-sql.ts +45 -0
  54. package/src/mutation-state.ts +11 -2
  55. package/src/mutation.ts +42 -0
  56. package/src/schema.ts +120 -1
  57. package/src/shape-sync.ts +21 -0
  58. package/src/store-path.ts +249 -0
  59. package/src/sync/index.ts +11 -0
  60. package/src/sync/types.ts +9 -0
  61. package/src/testing.ts +53 -0
  62. package/src/worker/attach-sync-client.ts +101 -6
  63. package/src/worker/define-sync-worker.ts +196 -30
  64. package/src/worker/protocol.ts +110 -10
package/src/lazy-guard.ts CHANGED
@@ -25,9 +25,10 @@ export interface LazyGuardIndex {
25
25
  readonly lazyKeys: ReadonlySet<string>;
26
26
  /**
27
27
  * Per lazy key, the exact quoted reference token(s) the compiled SQL emits when reading it: the synced
28
- * table (and, for readwrite, its read-model view) as `"name"` or `"schema"."name"`. Schema-qualified
29
- * when the Drizzle object carries a schema — which makes the token collision-proof against bare
30
- * aliases/CTEs.
28
+ * table (and, for readwrite, its read-model view) as `"name"` or `"schema"."name"` — or, for a read
29
+ * PROJECTION (ADR-0025), its DISTINCT local identity (`localTable`, the `as` name) rather than the
30
+ * owner's physical table. Schema-qualified when the Drizzle object carries a schema — which makes the
31
+ * token collision-proof against bare aliases/CTEs.
31
32
  */
32
33
  readonly lazyTokens: ReadonlyMap<string, readonly string[]>;
33
34
  }
@@ -42,11 +43,24 @@ export function buildLazyGuardIndex(registry: SyncTableRegistry): LazyGuardIndex
42
43
  lazyKeys.add(key);
43
44
 
44
45
  const tokens: string[] = [];
45
- const table = getTableConfig(entry.table);
46
- tokens.push(quotedRef(table.name, table.schema));
47
- if (entry.view != null) {
48
- const view = getViewConfig(entry.view);
49
- tokens.push(quotedRef(view.name, view.schema));
46
+ if (entry.readProjection) {
47
+ // A read PROJECTION (defineReadProjection, ADR-0025) owns no physical table: its `entry.table` is the
48
+ // OWNER's physical table, but a consumer reads it ONLY through its DISTINCT local identity
49
+ // `entry.localTable` (the `as` name — where Electric syncs the projection's rows). Token that, NOT the
50
+ // owner's physical name: a read of the projection's own local table then activates it, while a read of
51
+ // the owner's table activates the OWNER entry (which carries the owner token) without falsely
52
+ // activating this projection. (A projection is always readonly and has no read-model view.)
53
+ const localTable = getTableConfig(entry.localTable);
54
+ tokens.push(quotedRef(localTable.name, localTable.schema));
55
+ } else {
56
+ // A regular entry is read through the synced base table (and, for readwrite, its read-model view);
57
+ // `entry.localTable` shares the base table's name here, so no extra token is needed.
58
+ const table = getTableConfig(entry.table);
59
+ tokens.push(quotedRef(table.name, table.schema));
60
+ if (entry.view != null) {
61
+ const view = getViewConfig(entry.view);
62
+ tokens.push(quotedRef(view.name, view.schema));
63
+ }
50
64
  }
51
65
  lazyTokens.set(key, tokens);
52
66
  }
@@ -75,7 +89,7 @@ export function findReferencedLazyKeysInSql(sql: string, index: LazyGuardIndex):
75
89
  }
76
90
 
77
91
  function sqlReferencesToken(sql: string, token: string): boolean {
78
- for (let from = 0; ; ) {
92
+ for (let from = 0; ;) {
79
93
  const at = sql.indexOf(token, from);
80
94
  if (at === -1) return false;
81
95
  // Exclude an alias occurrence: `<expr> as "token"`. Only a bare token can be an alias, so this never
@@ -0,0 +1,66 @@
1
+ // The engine lifecycle slot (ADR-0035 decision 4). A store holds ONE in-flight lifecycle operation at a
2
+ // time — the three exports plus the destructive ops `destroy()`/`discardEphemeral()`/`dropReadCache()` — so
3
+ // two blackout-class operations can never overlap and corrupt each other's view of the store. The slot does
4
+ // NOT queue: a
5
+ // second entrant while one is running is rejected immediately with a typed {@link LifecycleBusyError}
6
+ // (the ADR's deliberate choice — a fresh artefact is better served by the caller retrying than by
7
+ // stacking back-to-back operations the second could get fresher after the first settles).
8
+
9
+ /**
10
+ * Thrown when a lifecycle operation is attempted while another already holds the slot (ADR-0035). Carries
11
+ * the running operation's `label` so a caller (or a retry policy) can report exactly what it collided with.
12
+ * A distinct error type — not a bare `Error` — so callers can `instanceof`-branch a busy collision from a
13
+ * genuine operation failure.
14
+ */
15
+ export class LifecycleBusyError extends Error {
16
+ /** The label of the lifecycle operation currently holding the slot. */
17
+ readonly runningLabel: string;
18
+ /** The label of the operation that was refused. */
19
+ readonly attemptedLabel: string;
20
+
21
+ constructor(attemptedLabel: string, runningLabel: string) {
22
+ super(
23
+ `[pgxsinkit] lifecycle busy: "${attemptedLabel}" refused while "${runningLabel}" is running (ADR-0035; retry once it settles).`,
24
+ );
25
+ this.name = "LifecycleBusyError";
26
+ this.attemptedLabel = attemptedLabel;
27
+ this.runningLabel = runningLabel;
28
+ }
29
+ }
30
+
31
+ /** A single-occupancy lifecycle slot. One owner per store (`createSyncClient`); one operation at a time. */
32
+ export interface LifecycleSlot {
33
+ /**
34
+ * Run `fn` under the slot's exclusion. Rejects with a {@link LifecycleBusyError} — without invoking `fn`
35
+ * — if the slot is already occupied; otherwise holds the slot for `fn`'s lifetime and releases it in a
36
+ * `finally`, so a throwing operation never leaves the slot stuck. The occupancy check + claim run
37
+ * synchronously on entry (before the first `await`), so two calls issued in the same tick resolve
38
+ * deterministically: the first claims, the second is refused.
39
+ */
40
+ run: <T>(label: string, fn: () => Promise<T>) => Promise<T>;
41
+ /** Whether an operation currently holds the slot. */
42
+ isBusy: () => boolean;
43
+ /** The label of the operation currently holding the slot, or `null` when free. */
44
+ runningLabel: () => string | null;
45
+ }
46
+
47
+ /** Create an empty lifecycle slot (ADR-0035 decision 4). */
48
+ export function createLifecycleSlot(): LifecycleSlot {
49
+ let running: string | null = null;
50
+
51
+ return {
52
+ run: async (label, fn) => {
53
+ // Refuse before touching `fn` — a busy collision must have zero side effects on the running operation.
54
+ if (running !== null) throw new LifecycleBusyError(label, running);
55
+ // Claim synchronously (before the first `await` below) so a same-tick second entrant sees us busy.
56
+ running = label;
57
+ try {
58
+ return await fn();
59
+ } finally {
60
+ running = null;
61
+ }
62
+ },
63
+ isBusy: () => running !== null,
64
+ runningLabel: () => running,
65
+ };
66
+ }
@@ -0,0 +1,45 @@
1
+ import { quoteIdentifier } from "@pgxsinkit/contracts";
2
+
3
+ // ─── Live-read materialization safety (ADR-0032 S2 §4) ───────────────────────────────────────────────
4
+ //
5
+ // The live-rows seam feeds the compiled SQL of a Drizzle-built select into PGlite's `live` extension,
6
+ // which MATERIALISES the query (a temp view + state table it diffs against). Drizzle emits no output
7
+ // aliases — it maps result columns positionally — so a JOIN whose tables share a column name (two
8
+ // `title`) compiles to a SELECT with duplicate OUTPUT column names. That is legal as a plain one-shot
9
+ // query, but the live materialisation fails hard:
10
+ //
11
+ // column "title" specified more than once
12
+ //
13
+ // and even the plain query silently COLLAPSES the same-named columns into one value (the last one wins),
14
+ // because rows are keyed by column name. The compiled SQL cannot dedupe itself, so the seam must render
15
+ // it into a form that is safe to materialise.
16
+
17
+ /** The derived-table alias the live-rows seam wraps a materialised query under. Kept unlikely to collide. */
18
+ const LIVE_QUERY_TABLE_ALIAS = "__pgx_live";
19
+
20
+ /**
21
+ * Make a live-read SQL statement SAFE TO MATERIALISE by giving every output column a UNIQUE explicit name.
22
+ *
23
+ * `fields` is the ordered list of unique output aliases — one per output column, in the compiled SQL's
24
+ * column order (Drizzle emits columns depth-first over the select's field keys, which are unique by
25
+ * construction). The statement is wrapped in a derived table with a POSITIONAL column-alias-list:
26
+ *
27
+ * SELECT * FROM (<sql>) "__pgx_live" ("<a0>", "<a1>", …)
28
+ *
29
+ * A plain `SELECT * FROM (<sql>)` does NOT dedupe — the inner duplicate names survive — so the
30
+ * column-alias-list is what renames every output column POSITIONALLY to a distinct name. The wrapped
31
+ * query materialises cleanly, and its rows come back keyed by the aliases (so same-named source columns
32
+ * keep DISTINCT values). `SELECT *` from the aliased derived table is safe precisely because the alias
33
+ * list has already made the names unique.
34
+ *
35
+ * Returns the SQL UNCHANGED when `fields` is absent or empty — the backward-compatible path for existing
36
+ * callers (raw SQL strings, or non-colliding queries that pass no `fields`): they keep name-keyed rows
37
+ * exactly as before. Only a caller that supplies `fields` opts into alias-keyed rows.
38
+ */
39
+ export function wrapLiveQueryForMaterialization(sql: string, fields: readonly string[] | undefined): string {
40
+ if (fields == null || fields.length === 0) {
41
+ return sql;
42
+ }
43
+ const aliasList = fields.map((field) => quoteIdentifier(field)).join(", ");
44
+ return `SELECT * FROM (${sql}) ${quoteIdentifier(LIVE_QUERY_TABLE_ALIAS)} (${aliasList})`;
45
+ }
@@ -32,11 +32,20 @@ export type MutationStatus = "pending" | "sending" | "acked" | "failed" | "quara
32
32
  * - `sending -> conflicted` a stale write the reject-if-stale policy declined (ADR-0015).
33
33
  * - `sending -> rejected` a business rejection from the authoritative endpoint (ADR-0022).
34
34
  * - `sending -> pending` recoverSending re-queues an in-flight row on startup.
35
+ * - `pending -> quarantined` a RESTORE boot quarantines every non-terminal row recovered from a
36
+ * backup (ADR-0035 decision 6). A `pending` row is normally only ever claimed (`-> sending`), but a
37
+ * store restored from a backup must NOT auto-flush anything it recovered — the write path has no
38
+ * `mutationId` dedupe ledger, so replaying a recovered `pending`/`sending`/`failed` mutation is unsafe
39
+ * (silent last-write-wins reverts, create PK collisions). Restore is therefore the ONE producer of this
40
+ * edge; ordinary boots never move a `pending` row straight to `quarantined`.
35
41
  * - `failed -> pending` retryFailed re-queues a failed row.
36
- * - `failed -> quarantined` the hard max-attempts cap is reached; stop retrying.
42
+ * - `failed -> quarantined` the hard max-attempts cap is reached; stop retrying (also the restore
43
+ * quarantine of a recovered `failed` row, ADR-0035 decision 6 — the edge already existed).
37
44
  */
38
45
  export const MUTATION_TRANSITIONS = {
39
- pending: ["sending"],
46
+ // `pending -> quarantined` exists ONLY for the restore-boot quarantine (ADR-0035 decision 6); the normal
47
+ // flush path only ever claims a pending row (`-> sending`).
48
+ pending: ["sending", "quarantined"],
40
49
  sending: ["acked", "failed", "quarantined", "conflicted", "rejected", "pending"],
41
50
  failed: ["pending", "quarantined"],
42
51
  quarantined: [],
package/src/mutation.ts CHANGED
@@ -349,6 +349,18 @@ export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
349
349
  reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;
350
350
  retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
351
351
  recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;
352
+ /**
353
+ * Quarantine EVERY non-terminal journal row recovered from a backup (`pending`/`sending`/`failed` →
354
+ * `quarantined`) — the restore-boot rule (ADR-0035 decision 6). Nothing recovered from a store backup
355
+ * may ever auto-flush: the write path keeps `mutationId` in `operations_log` but never consults it, so
356
+ * there is no dedupe ledger, and a replayed mutation would silently re-apply stale values over newer
357
+ * writes on a last-write-wins table (and a replayed create collides on its PK). Terminal states
358
+ * (`acked`/`conflicted`/`rejected`) are left untouched. Run ONCE, on the restore boot only, AFTER
359
+ * `recoverSending` (which first lifts any `sending` back to `pending`); the app then inspects
360
+ * `diagnostics()` and resolves each row via `discardQuarantined` (quarantine is terminal — "release"
361
+ * means discard and re-author as a new mutation) before going online. A no-op on a clean journal.
362
+ */
363
+ quarantineRecovered: (table?: SyncTableName<TRegistry>) => Promise<void>;
352
364
  readMutationStats: (table?: SyncTableName<TRegistry>) => Promise<MutationDiagnostics>;
353
365
  readMutationDetails: (table?: SyncTableName<TRegistry>) => Promise<MutationDetail[]>;
354
366
  createOptimisticRecord: <TKey extends SyncTableName<TRegistry>>(
@@ -1225,6 +1237,36 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1225
1237
  await options.db.query(query.sql, query.params as unknown[]);
1226
1238
  }
1227
1239
  },
1240
+ quarantineRecovered: async (table) => {
1241
+ // The restore-boot quarantine (ADR-0035 decision 6): every non-terminal recovered row is parked in the
1242
+ // terminal `quarantined` state so NOTHING recovered from a backup auto-flushes (no dedupe ledger →
1243
+ // unsafe replay). `pending -> quarantined` is a restore-only edge (see mutation-state.ts); `sending`
1244
+ // and `failed` already reach quarantine. Assert all three edges up front so a future transition-table
1245
+ // change that breaks restore fails loudly here rather than silently skipping the quarantine.
1246
+ assertValidMutationTransition("pending", "quarantined");
1247
+ assertValidMutationTransition("sending", "quarantined");
1248
+ assertValidMutationTransition("failed", "quarantined");
1249
+ const contexts = filterContexts(tableContexts, table);
1250
+ const nowUs = nowMicroseconds();
1251
+
1252
+ for (const context of contexts) {
1253
+ const journal = context.tables.journal;
1254
+ const query = queryBuilder
1255
+ .update(journal)
1256
+ .set({
1257
+ status: "quarantined",
1258
+ updatedAtUs: nowUs,
1259
+ // Terminal: never retried, so clear the retry cursor and name restore as the cause on the row so
1260
+ // an inspecting app can tell a restore-quarantined write from a server-rejected one.
1261
+ nextRetryAtUs: null,
1262
+ lastError: "Quarantined on restore: recovered from a store backup, not replayed (ADR-0035).",
1263
+ conflictReason: null,
1264
+ })
1265
+ .where(inArray(journal.status, ["pending", "sending", "failed"]))
1266
+ .toSQL();
1267
+ await options.db.query(query.sql, query.params as unknown[]);
1268
+ }
1269
+ },
1228
1270
  readMutationStats: async (table) => {
1229
1271
  const contexts = filterContexts(tableContexts, table);
1230
1272
  const totals: MutationDiagnostics = {
package/src/schema.ts CHANGED
@@ -467,9 +467,20 @@ type EnumDefinition = {
467
467
  };
468
468
 
469
469
  function collectEnumDefinitions(registry: SyncTableRegistry, localSchema: string) {
470
+ return collectEnumDefinitionsFromEntries(Object.values(registry), localSchema);
471
+ }
472
+
473
+ /**
474
+ * Collect the distinct enum types referenced by a GIVEN set of registry entries (deduped by name, values
475
+ * cross-checked for conflicts, sorted for stable output). Factored out of {@link collectEnumDefinitions} so
476
+ * the Data export (ADR-0035) can emit ONLY the enums its `-t` allowlist tables reference — the whole-registry
477
+ * caller passes every entry, the data export passes just its owning persistent entries — through one honest
478
+ * implementation, never a second enum-scanning path that could drift on the conflict/sort rules.
479
+ */
480
+ function collectEnumDefinitionsFromEntries(entries: SyncTableEntry[], localSchema: string) {
470
481
  const enumDefinitionsByName = new Map<string, EnumDefinition>();
471
482
 
472
- for (const entry of Object.values(registry)) {
483
+ for (const entry of entries) {
473
484
  const columns = getProjectedColumns(entry).map(({ column }) => column);
474
485
 
475
486
  for (const column of columns) {
@@ -497,6 +508,114 @@ function collectEnumDefinitions(registry: SyncTableRegistry, localSchema: string
497
508
  return [...enumDefinitionsByName.values()].sort((left, right) => left.enumName.localeCompare(right.enumName));
498
509
  }
499
510
 
511
+ /**
512
+ * Does this entry OWN a physical, persistent synced table — i.e. is it a `-t` allowlist candidate for the
513
+ * Data export (ADR-0035 decision 1)? Two entries are excluded:
514
+ *
515
+ * - a **read PROJECTION** (`readProjection`) owns no table (its `table` is another entry's), so it must
516
+ * never be listed — it would double-target the owner's physical table;
517
+ * - an **ephemeral** entry's cluster is emitted as `pg_temp` TEMP objects (ADR-0021 §3), absent from the
518
+ * throwaway clone by construction — and a `pg_dump -t` pattern that matches NOTHING makes `pg_dump` fail,
519
+ * so an ephemeral table must not appear in the allowlist at all.
520
+ *
521
+ * Overlay/journal/meta tables, read-model/sync-state views, and reconcile functions are excluded by `-t`
522
+ * semantics automatically (they are neither the synced table nor matched by its name), so they need no
523
+ * filter here.
524
+ */
525
+ function ownsPersistentSyncedTable(entry: SyncTableEntry): boolean {
526
+ return !entry.readProjection && entry.retention !== "ephemeral";
527
+ }
528
+
529
+ /**
530
+ * The `-t` allowlist for a Data export (ADR-0035 decision 1): the schema-qualified PHYSICAL synced table
531
+ * name for every registry entry that owns one, resolved through the SAME `getClientProjection` the local
532
+ * DDL generator uses — NOT re-derived by string convention. This is deliberately the physical `syncedTable`,
533
+ * never the read-model view (whose name can carry the entry name while the table differs): `-t` must target
534
+ * the tables that hold the rows. Read-projection and ephemeral entries are excluded (see
535
+ * {@link ownsPersistentSyncedTable}).
536
+ */
537
+ export function collectDataExportSyncedTableNames<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {
538
+ const localSchema = getSyncRegistrySchema(registry);
539
+ const names: string[] = [];
540
+
541
+ for (const [tableKey, entry] of Object.entries(registry)) {
542
+ if (!ownsPersistentSyncedTable(entry)) {
543
+ continue;
544
+ }
545
+
546
+ names.push(getClientProjection(entry, tableKey, localSchema).syncedTable);
547
+ }
548
+
549
+ return names;
550
+ }
551
+
552
+ /**
553
+ * The clone-cleanup SQL a Data export runs on its THROWAWAY clone before `pg_dump -t` (ADR-0035). The
554
+ * reconcile trigger sits ON the synced table (`AFTER INSERT/UPDATE/DELETE ON <syncedTable>`), so
555
+ * `pg_dump -t <syncedTable>` pulls the trigger into the dump — but its function is pgxsinkit machinery the
556
+ * data export deliberately EXCLUDES, so the artefact would carry a trigger referencing a missing function
557
+ * and fail to load into a vanilla Postgres. Because the clone is a memory-backed throwaway we fully own, we
558
+ * drop each reconcile trigger (and its now-unreferenced function) on it first, so `-t` yields clean,
559
+ * portable tables. Overlay/journal/views/metadata are NOT captured by `-t <syncedTable>` at all (a probe
560
+ * confirmed only the table, its PK, its data, and this trigger appear), so nothing else needs dropping.
561
+ * Returns `""` when the registry declares no writable owning table.
562
+ */
563
+ export function buildDataExportCloneCleanupSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {
564
+ const localSchema = getSyncRegistrySchema(registry);
565
+ const statements: string[] = [];
566
+
567
+ for (const [tableKey, entry] of Object.entries(registry)) {
568
+ if (!ownsPersistentSyncedTable(entry) || entry.mode === "readonly") {
569
+ continue;
570
+ }
571
+
572
+ const projection = getClientProjection(entry, tableKey, localSchema);
573
+ // Drop the trigger first, then its now-unreferenced function (drop order avoids a dependency error).
574
+ statements.push(`DROP TRIGGER IF EXISTS ${projection.reconcileTrigger} ON ${projection.syncedTable};`);
575
+ statements.push(`DROP FUNCTION IF EXISTS ${projection.reconcileFunction}();`);
576
+ }
577
+
578
+ return statements.join("\n");
579
+ }
580
+
581
+ /**
582
+ * The enum DDL header for a Data export artefact (ADR-0035 decision 1). `pg_dump -t <table>` emits the
583
+ * tables but NOT the enum types their columns reference, so the portable artefact is this generated header
584
+ * concatenated ahead of the `pg_dump` output. It reuses the SAME `CREATE TYPE` generation the local-schema
585
+ * generator emits ({@link buildCreateEnumTypeSql}) — every enum wrapped in an idempotent `IF NOT EXISTS`
586
+ * guard — restricted to the enums actually referenced by the exported (owning, persistent) tables, so a
587
+ * dropped/ephemeral-only enum never bloats the artefact. When the registry uses a non-`public` schema, a
588
+ * `CREATE SCHEMA IF NOT EXISTS` precedes the types (they live in that schema, and the header runs before
589
+ * `pg_dump`'s own schema creation), so the header is self-contained against a bare Postgres. Returns `""`
590
+ * when no exported table references an enum.
591
+ */
592
+ export function buildDataExportEnumHeaderSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {
593
+ const localSchema = getSyncRegistrySchema(registry);
594
+ const exportedEntries = Object.values(registry).filter(ownsPersistentSyncedTable);
595
+ const enumDefinitions = collectEnumDefinitionsFromEntries(exportedEntries, localSchema);
596
+
597
+ if (enumDefinitions.length === 0) {
598
+ return "";
599
+ }
600
+
601
+ const statements: string[] = [
602
+ "-- Enum types referenced by the exported tables. `pg_dump -t` does not emit the enum types",
603
+ "-- its tables depend on, so pgxsinkit generates them here from the sync registry (ADR-0035).",
604
+ ];
605
+
606
+ // A non-public schema must exist before its `CREATE TYPE` runs — this header precedes pg_dump's own
607
+ // schema creation, so create it ourselves (idempotent), mirroring `generateLocalSchemaSql`.
608
+ if (localSchema !== "public") {
609
+ statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(localSchema)};`);
610
+ }
611
+
612
+ for (const enumDefinition of enumDefinitions) {
613
+ statements.push(buildCreateEnumTypeSql(enumDefinition));
614
+ }
615
+
616
+ return `${statements.join("\n")}\n`;
617
+ }
618
+
500
619
  function buildCreateEnumTypeSql(enumDefinition: EnumDefinition) {
501
620
  const typeIdentifier = qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName);
502
621
  const enumValuesSql = enumDefinition.enumValues.map((value) => quoteSqlStringLiteral(value)).join(", ");
package/src/shape-sync.ts CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  type TableSpecInput,
10
10
  } from "@pgxsinkit/contracts";
11
11
 
12
+ import type { BootStampCollector, GroupBootStamp } from "./boot-report";
12
13
  import type { SyncNamespaceObj } from "./sync";
13
14
  import { createShapeErrorHandler } from "./sync-auth";
14
15
 
@@ -103,6 +104,13 @@ export interface StartConfiguredSyncOptions {
103
104
  * without the all-eager-groups `onInitialSync` gate. The matching promise is {@link StartConfiguredSyncResult.groupReady}.
104
105
  */
105
106
  onGroupReady?: (groupKey: string) => void;
107
+ /**
108
+ * Boot observability (ADR-0034): opens a per-group accumulator (rows/requests/fetch/apply wall) for each
109
+ * EAGER + PROMOTED boot group, stamped by the engine as the group's stream chain delivers and applies. A
110
+ * lazy on-demand start gets none — so a lazily-activated-later group never enters (or mutates) the report.
111
+ * Absent → no boot instrumentation.
112
+ */
113
+ bootCollector?: BootStampCollector;
106
114
  }
107
115
 
108
116
  // The engine is reached through the `electric` namespace the client attaches post-create (ADR-0032 S1) —
@@ -278,10 +286,17 @@ export async function startConfiguredSync(
278
286
  if (group.startPromise) {
279
287
  return group.startPromise;
280
288
  }
289
+ // Boot observability (ADR-0034): open an accumulator for a BOOT group only (eager + promoted); an
290
+ // on-demand lazy start (`countsTowardBoot === false`) gets none, so it never enters the report.
291
+ const bootStamp: GroupBootStamp | undefined =
292
+ countsTowardBoot && input.bootCollector
293
+ ? input.bootCollector.beginGroup(group.groupKey, group.specs.length)
294
+ : undefined;
281
295
  group.startPromise = startGroupSync(pg, {
282
296
  groupKey: group.groupKey,
283
297
  specs: group.specs,
284
298
  registry: input.registry,
299
+ ...(bootStamp ? { bootStamp } : {}),
285
300
  // The prefetch overlap (ADR-0032 S4) applies ONLY to the eager BOOT starts: a fresh store's eager
286
301
  // groups are genuinely new, so buffering their catch-up behind the commit gate is safe. An on-demand
287
302
  // `lazy` start happens post-boot on an already-provisioned store (which may even be RESUMING persisted
@@ -299,6 +314,9 @@ export async function startConfiguredSync(
299
314
  for (const spec of group.specs) {
300
315
  input.onTableInitialSync?.(spec.key);
301
316
  }
317
+ // Boot observability (ADR-0034): stamp readyAtMs and freeze the accumulator at the group's ready edge,
318
+ // so later live traffic never mutates a finalized report.
319
+ bootStamp?.markReady();
302
320
  markGroupReady(group.groupKey);
303
321
  if (countsTowardBoot) {
304
322
  pendingBootGroups -= 1;
@@ -385,6 +403,8 @@ interface StartGroupSyncOptions {
385
403
  headers?: ExternalHeadersRecord;
386
404
  /** Fresh-store prefetch overlap gate (ADR-0032 S4) — forwarded to the engine's `syncShapesToTables`. */
387
405
  dbReady?: Promise<void>;
406
+ /** Boot observability (ADR-0034): the group's accumulator, stamped by the engine on delivery/apply. */
407
+ bootStamp?: GroupBootStamp;
388
408
  onGroupInitialSync?: () => void;
389
409
  onSyncError?: (error: Error) => void;
390
410
  onAuthError?: () => void;
@@ -431,6 +451,7 @@ export async function startGroupSync(pg: SyncEnginePGlite, input: StartGroupSync
431
451
  registry: input.registry,
432
452
  shapes,
433
453
  ...(input.dbReady ? { dbReady: input.dbReady } : {}),
454
+ ...(input.bootStamp ? { bootStamp: input.bootStamp } : {}),
434
455
  ...(input.onGroupInitialSync ? { onInitialSync: input.onGroupInitialSync } : {}),
435
456
  ...(input.onSyncError ? { onSyncError: input.onSyncError } : {}),
436
457
  ...(input.onSyncActivity ? { onSyncActivity: input.onSyncActivity } : {}),