@pgxsinkit/client 0.1.32 → 0.1.40

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 (111) hide show
  1. package/README.md +11 -0
  2. package/dist/boot-report.d.ts +134 -0
  3. package/dist/boot-report.d.ts.map +1 -0
  4. package/dist/convergence.d.ts +76 -0
  5. package/dist/convergence.d.ts.map +1 -0
  6. package/dist/debug.d.ts +34 -0
  7. package/dist/debug.d.ts.map +1 -0
  8. package/dist/export-data.d.ts +100 -0
  9. package/dist/export-data.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts +92 -0
  11. package/dist/export-dump.d.ts.map +1 -0
  12. package/dist/export-store.d.ts +214 -0
  13. package/dist/export-store.d.ts.map +1 -0
  14. package/dist/index.d.ts +615 -8
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8083 -2286
  17. package/dist/index.js.map +81 -44
  18. package/dist/lazy-guard.d.ts +59 -0
  19. package/dist/lazy-guard.d.ts.map +1 -0
  20. package/dist/lifecycle-slot.d.ts +31 -0
  21. package/dist/lifecycle-slot.d.ts.map +1 -0
  22. package/dist/live-rows-sql.d.ts +21 -0
  23. package/dist/live-rows-sql.d.ts.map +1 -0
  24. package/dist/local-store.d.ts +56 -0
  25. package/dist/local-store.d.ts.map +1 -0
  26. package/dist/local-tables.d.ts +707 -0
  27. package/dist/local-tables.d.ts.map +1 -0
  28. package/dist/mutation-state.d.ts +69 -0
  29. package/dist/mutation-state.d.ts.map +1 -0
  30. package/dist/mutation.d.ts +129 -4
  31. package/dist/mutation.d.ts.map +1 -1
  32. package/dist/schema.d.ts +82 -0
  33. package/dist/schema.d.ts.map +1 -1
  34. package/dist/shape-sync.d.ts +190 -0
  35. package/dist/shape-sync.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +132 -0
  37. package/dist/store-path.d.ts.map +1 -0
  38. package/dist/sync/apply.d.ts +51 -0
  39. package/dist/sync/apply.d.ts.map +1 -0
  40. package/dist/sync/copy.d.ts +43 -0
  41. package/dist/sync/copy.d.ts.map +1 -0
  42. package/dist/sync/drizzle-executor.d.ts +5 -0
  43. package/dist/sync/drizzle-executor.d.ts.map +1 -0
  44. package/dist/sync/index.d.ts +32 -0
  45. package/dist/sync/index.d.ts.map +1 -0
  46. package/dist/sync/metadata-tables.d.ts +131 -0
  47. package/dist/sync/metadata-tables.d.ts.map +1 -0
  48. package/dist/sync/nudge.d.ts +49 -0
  49. package/dist/sync/nudge.d.ts.map +1 -0
  50. package/dist/sync/shape-inbox.d.ts +215 -0
  51. package/dist/sync/shape-inbox.d.ts.map +1 -0
  52. package/dist/sync/subscription-state.d.ts +39 -0
  53. package/dist/sync/subscription-state.d.ts.map +1 -0
  54. package/dist/sync/tags.d.ts +130 -0
  55. package/dist/sync/tags.d.ts.map +1 -0
  56. package/dist/sync/types.d.ts +126 -0
  57. package/dist/sync/types.d.ts.map +1 -0
  58. package/dist/sync-auth.d.ts +53 -0
  59. package/dist/sync-auth.d.ts.map +1 -0
  60. package/dist/testing.d.ts +27 -0
  61. package/dist/testing.d.ts.map +1 -0
  62. package/dist/testing.js +17 -0
  63. package/dist/testing.js.map +11 -0
  64. package/dist/worker/attach-sync-client.d.ts +96 -0
  65. package/dist/worker/attach-sync-client.d.ts.map +1 -0
  66. package/dist/worker/define-sync-worker.d.ts +76 -0
  67. package/dist/worker/define-sync-worker.d.ts.map +1 -0
  68. package/dist/worker/live-diff.d.ts +44 -0
  69. package/dist/worker/live-diff.d.ts.map +1 -0
  70. package/dist/worker/protocol.d.ts +341 -0
  71. package/dist/worker/protocol.d.ts.map +1 -0
  72. package/dist/worker/token-cache.d.ts +26 -0
  73. package/dist/worker/token-cache.d.ts.map +1 -0
  74. package/oxlint-plugin.js +143 -0
  75. package/package.json +20 -7
  76. package/skills/core/SKILL.md +210 -0
  77. package/skills/operating/SKILL.md +303 -0
  78. package/src/boot-report.ts +287 -0
  79. package/src/convergence.ts +197 -0
  80. package/src/debug.ts +151 -0
  81. package/src/export-data.ts +300 -0
  82. package/src/export-dump.ts +239 -0
  83. package/src/export-store.ts +309 -0
  84. package/src/index.ts +1652 -51
  85. package/src/lazy-guard.ts +135 -0
  86. package/src/lifecycle-slot.ts +66 -0
  87. package/src/live-rows-sql.ts +45 -0
  88. package/src/local-store.ts +193 -0
  89. package/src/local-tables.ts +546 -0
  90. package/src/mutation-state.ts +99 -0
  91. package/src/mutation.ts +1910 -562
  92. package/src/schema.ts +472 -28
  93. package/src/shape-sync.ts +498 -0
  94. package/src/store-path.ts +249 -0
  95. package/src/sync/apply.ts +530 -0
  96. package/src/sync/copy.ts +206 -0
  97. package/src/sync/drizzle-executor.ts +48 -0
  98. package/src/sync/index.ts +1087 -0
  99. package/src/sync/metadata-tables.ts +67 -0
  100. package/src/sync/nudge.ts +110 -0
  101. package/src/sync/shape-inbox.ts +566 -0
  102. package/src/sync/subscription-state.ts +135 -0
  103. package/src/sync/tags.ts +365 -0
  104. package/src/sync/types.ts +141 -0
  105. package/src/sync-auth.ts +117 -0
  106. package/src/testing.ts +53 -0
  107. package/src/worker/attach-sync-client.ts +653 -0
  108. package/src/worker/define-sync-worker.ts +762 -0
  109. package/src/worker/live-diff.ts +140 -0
  110. package/src/worker/protocol.ts +425 -0
  111. package/src/worker/token-cache.ts +84 -0
@@ -0,0 +1,135 @@
1
+ import { getTableConfig, getViewConfig } from "drizzle-orm/pg-core";
2
+
3
+ import type { SyncTableRegistry } from "@pgxsinkit/contracts";
4
+
5
+ /**
6
+ * Lazy-relation safety (ADR-0021).
7
+ *
8
+ * A `lazy` relation is held out of the eager boot and only subscribed on first reference. The hazard is
9
+ * a query reading it *before* it is hydrated — which silently returns empty/stale rows. This pure,
10
+ * React-free core detects which lazy relations a query reads by scanning its **compiled** SQL, so the
11
+ * caller can activate them (and hydrate-then-run) before the query executes.
12
+ *
13
+ * Why a single SQL scan is sufficient (and why there is no Proxy / builder-AST walk): Drizzle compiles
14
+ * a query to parameterised SQL — values are bound (`$1`, `$2`), never inlined — and emits every relation
15
+ * as a **quoted** identifier (`"name"`, or `"schema"."name"` when it carries a schema). So the compiled
16
+ * SQL is ground truth: a relation the query reads must appear there by name, and the only things in the
17
+ * text are quoted identifiers, keywords and `$n` placeholders. The index is built from the *same* Drizzle
18
+ * objects that emit the SQL (`getTableConfig`/`getViewConfig`), so a token matches emission by
19
+ * construction — schema and all. See "Known limitations" in ADR-0021 for the residual edges.
20
+ */
21
+
22
+ /** Static index of a registry's lazy relations and the exact quoted tokens their reads compile to. */
23
+ export interface LazyGuardIndex {
24
+ /** Registry keys whose subscription timing is `lazy`. */
25
+ readonly lazyKeys: ReadonlySet<string>;
26
+ /**
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"` — 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.
32
+ */
33
+ readonly lazyTokens: ReadonlyMap<string, readonly string[]>;
34
+ }
35
+
36
+ /** Build the {@link LazyGuardIndex} for a registry. Cheap and pure — cache it per client. */
37
+ export function buildLazyGuardIndex(registry: SyncTableRegistry): LazyGuardIndex {
38
+ const lazyKeys = new Set<string>();
39
+ const lazyTokens = new Map<string, readonly string[]>();
40
+
41
+ for (const [key, entry] of Object.entries(registry)) {
42
+ if (entry.subscription !== "lazy") continue;
43
+ lazyKeys.add(key);
44
+
45
+ const tokens: string[] = [];
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
+ }
64
+ }
65
+ lazyTokens.set(key, tokens);
66
+ }
67
+
68
+ return { lazyKeys, lazyTokens };
69
+ }
70
+
71
+ /** The quoted identifier Drizzle emits for a relation: `"schema"."name"` when schema-qualified, else `"name"`. */
72
+ function quotedRef(name: string, schema: string | undefined): string {
73
+ return schema != null && schema.length > 0 ? `"${schema}"."${name}"` : `"${name}"`;
74
+ }
75
+
76
+ /**
77
+ * The compiled-SQL scan: the lazy registry keys whose quoted reference token appears in `sql`. Because
78
+ * the token is fully quoted it is self-delimiting (`"a"` cannot match inside `"ab"`), so a substring test
79
+ * is exact. A *bare* token sitting in alias position (`… as "name"`, which Drizzle emits for `.as("name")`)
80
+ * is excluded — the one realistic collision for a schema-less relation; a schema-qualified token cannot be
81
+ * aliased and so needs no such guard.
82
+ */
83
+ export function findReferencedLazyKeysInSql(sql: string, index: LazyGuardIndex): Set<string> {
84
+ const found = new Set<string>();
85
+ for (const [key, tokens] of index.lazyTokens) {
86
+ if (tokens.some((token) => sqlReferencesToken(sql, token))) found.add(key);
87
+ }
88
+ return found;
89
+ }
90
+
91
+ function sqlReferencesToken(sql: string, token: string): boolean {
92
+ for (let from = 0; ;) {
93
+ const at = sql.indexOf(token, from);
94
+ if (at === -1) return false;
95
+ // Exclude an alias occurrence: `<expr> as "token"`. Only a bare token can be an alias, so this never
96
+ // rejects a real (schema-qualified or FROM/JOIN) reference. Window comfortably covers Drizzle's ` as `.
97
+ if (!/\bas\s+$/i.test(sql.slice(Math.max(0, at - 16), at))) return true;
98
+ from = at + token.length;
99
+ }
100
+ }
101
+
102
+ /**
103
+ * The activation backstop (ADR-0021): throw if a query references a lazy relation that is still not
104
+ * active. Called *after* the referenced lazy relations have been activated, so in the normal path every
105
+ * scanned relation is now active and this passes. It fires only when activation could not make a
106
+ * referenced relation active (a start that failed, or a lazy relation with no consistency group) —
107
+ * converting a would-be silent empty/stale read into a loud error.
108
+ */
109
+ export function assertLazyRefsActivated(args: {
110
+ sql: string;
111
+ index: LazyGuardIndex;
112
+ isActive: (key: string) => boolean;
113
+ }): void {
114
+ const referenced = findReferencedLazyKeysInSql(args.sql, args.index);
115
+ const missing = [...referenced].filter((key) => !args.isActive(key));
116
+ if (missing.length > 0) throw new LazyRelationNotActivatedError(missing);
117
+ }
118
+
119
+ /** Thrown by the backstop ({@link assertLazyRefsActivated}) when a referenced lazy relation could not be activated. */
120
+ export class LazyRelationNotActivatedError extends Error {
121
+ /** The lazy registry keys that were referenced but could not be activated. */
122
+ readonly relations: readonly string[];
123
+
124
+ constructor(relations: readonly string[]) {
125
+ const quoted = relations.map((r) => `"${r}"`).join(", ");
126
+ super(
127
+ `[pgxsinkit] query references lazy-synced relation(s) ${quoted} that could not be activated (ADR-0021), ` +
128
+ `so it would read empty/stale data. This is usually a failed initial sync or a lazy relation with no ` +
129
+ `consistency group. Activate it explicitly — client.ensureSynced([${quoted}]) — or check the sync ` +
130
+ `status. See "Known limitations" in ADR-0021.`,
131
+ );
132
+ this.name = "LazyRelationNotActivatedError";
133
+ this.relations = relations;
134
+ }
135
+ }
@@ -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
+ }
@@ -0,0 +1,193 @@
1
+ import { eq, like } from "drizzle-orm";
2
+ import { drizzle } from "drizzle-orm/pglite";
3
+
4
+ import { type MutationDiagnostics, type SyncTableRegistry } from "@pgxsinkit/contracts";
5
+
6
+ import { getLocalMetaTable } from "./local-tables";
7
+ import type { MutationDb } from "./mutation";
8
+ import { buildWipeLocalStoreSql, generateLocalSchemaSql, REGISTRY_FINGERPRINT_KEY } from "./schema";
9
+
10
+ // Statements are AUTHORED as Drizzle builders over the meta-table object (rename-safe, typed,
11
+ // schema-qualification handled by the table object) and rendered to text+params here, because they
12
+ // EXECUTE through the caller's raw `MutationDb` seam — the one connection the mutation runtime and
13
+ // its tests own (and mock).
14
+ const metaQueryBuilder = drizzle.mock();
15
+
16
+ /**
17
+ * The fingerprint-keyed local store (ADR-0006). The registry fingerprint the local PGlite
18
+ * database was provisioned under is recorded in the local-meta table; comparing it to the
19
+ * current fingerprint on boot is how a registry change is *detected* (rather than a
20
+ * hand-bumped `idb://…-vN` suffix), which drives the drain-then-drop read-cache rebuild.
21
+ */
22
+
23
+ /** A boot-time registry-version reconciliation outcome (ADR-0006 drain-then-drop). */
24
+ export interface LocalStoreVersionEvent {
25
+ status: "rebuilt" | "deferred";
26
+ previousFingerprint: string;
27
+ nextFingerprint: string;
28
+ /** Mutations still owed to the server (pending + sending + failed + quarantined). */
29
+ owedMutations: number;
30
+ }
31
+
32
+ /** The minimal mutation-runtime surface the version reconciliation needs. */
33
+ interface VersionReconcileRuntime {
34
+ registryVersion: string;
35
+ readMutationStats: () => Promise<MutationDiagnostics>;
36
+ }
37
+
38
+ /** The registry fingerprint the local store was last provisioned under, or null if unstamped. */
39
+ export async function readStoredRegistryFingerprint(
40
+ db: MutationDb,
41
+ registry: SyncTableRegistry,
42
+ ): Promise<string | null> {
43
+ const meta = getLocalMetaTable(registry);
44
+ const query = metaQueryBuilder
45
+ .select({ value: meta.value })
46
+ .from(meta)
47
+ .where(eq(meta.key, REGISTRY_FINGERPRINT_KEY))
48
+ .limit(1)
49
+ .toSQL();
50
+ const result = await db.query<{ value: string }>(query.sql, query.params as unknown[]);
51
+
52
+ return result.rows[0]?.value ?? null;
53
+ }
54
+
55
+ /** Meta-key prefix for a persisted `lazy + persistent` group activation (ADR-0021 §2). */
56
+ const LAZY_ACTIVATION_PREFIX = "lazy_active:";
57
+
58
+ /**
59
+ * The consistency-group keys of `lazy + persistent` groups that were activated on a previous boot
60
+ * (ADR-0021 §2). On boot these are promoted into the eager subscription set, so a once-activated durable
61
+ * lazy group resumes permanently with no per-session re-evaluation. (`ephemeral` activation is never
62
+ * persisted, so it never appears here.)
63
+ */
64
+ export async function readActivatedLazyGroups(db: MutationDb, registry: SyncTableRegistry): Promise<Set<string>> {
65
+ const meta = getLocalMetaTable(registry);
66
+ const query = metaQueryBuilder
67
+ .select({ key: meta.key })
68
+ .from(meta)
69
+ .where(like(meta.key, `${LAZY_ACTIVATION_PREFIX}%`))
70
+ .toSQL();
71
+ const result = await db.query<{ key: string }>(query.sql, query.params as unknown[]);
72
+ return new Set(result.rows.map((row) => row.key.slice(LAZY_ACTIVATION_PREFIX.length)));
73
+ }
74
+
75
+ /** Upsert one meta key — the shared write shape for activations and the fingerprint stamp. */
76
+ async function upsertMetaValue(db: MutationDb, registry: SyncTableRegistry, key: string, value: string): Promise<void> {
77
+ const meta = getLocalMetaTable(registry);
78
+ const query = metaQueryBuilder
79
+ .insert(meta)
80
+ .values({ key, value })
81
+ .onConflictDoUpdate({ target: meta.key, set: { value } })
82
+ .toSQL();
83
+ await db.query(query.sql, query.params as unknown[]);
84
+ }
85
+
86
+ /** Persist a `lazy + persistent` group's activation, so the next boot promotes it to eager (ADR-0021 §2). */
87
+ export async function writeLazyGroupActivation(
88
+ db: MutationDb,
89
+ registry: SyncTableRegistry,
90
+ groupKey: string,
91
+ ): Promise<void> {
92
+ await upsertMetaValue(db, registry, `${LAZY_ACTIVATION_PREFIX}${groupKey}`, "1");
93
+ }
94
+
95
+ /** Clear a persisted lazy activation — an explicit `desync` reverts the group to dormant next boot (ADR-0021 §2). */
96
+ export async function clearLazyGroupActivation(
97
+ db: MutationDb,
98
+ registry: SyncTableRegistry,
99
+ groupKey: string,
100
+ ): Promise<void> {
101
+ const meta = getLocalMetaTable(registry);
102
+ const query = metaQueryBuilder
103
+ .delete(meta)
104
+ .where(eq(meta.key, `${LAZY_ACTIVATION_PREFIX}${groupKey}`))
105
+ .toSQL();
106
+ await db.query(query.sql, query.params as unknown[]);
107
+ }
108
+
109
+ /** Stamp the local store with the fingerprint it is now provisioned under. */
110
+ export async function writeStoredRegistryFingerprint(
111
+ db: MutationDb,
112
+ registry: SyncTableRegistry,
113
+ fingerprint: string,
114
+ ): Promise<void> {
115
+ await upsertMetaValue(db, registry, REGISTRY_FINGERPRINT_KEY, fingerprint);
116
+ }
117
+
118
+ /**
119
+ * Reconcile the local store against the current registry fingerprint (ADR-0006). A fresh
120
+ * (unstamped) store is stamped; an unchanged fingerprint is a no-op. On a change, the read
121
+ * cache is dropped and rebuilt at the new shape **only when nothing is owed locally** —
122
+ * otherwise the rebuild is deferred (and retried on a later boot) so un-flushed/quarantined
123
+ * writes are never silently dropped. The drain happens across sessions: pending writes flush
124
+ * and reconcile during normal use, and the rebuild completes once the journal is clear.
125
+ *
126
+ * An unstamped store is always treated as brand-new. There is no pre-fingerprint-store path:
127
+ * the fingerprint mechanism shipped before launch, so every store in existence was
128
+ * provisioned with it (and a stamped store's journal therefore always has `registry_version`).
129
+ */
130
+ export async function reconcileLocalStoreVersion<TRegistry extends SyncTableRegistry>(args: {
131
+ db: MutationDb;
132
+ registry: TRegistry;
133
+ runtime: VersionReconcileRuntime;
134
+ onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;
135
+ }): Promise<LocalStoreVersionEvent | null> {
136
+ const { db, registry, runtime } = args;
137
+ const stored = await readStoredRegistryFingerprint(db, registry);
138
+ const current = runtime.registryVersion;
139
+
140
+ if (stored === current) {
141
+ return null;
142
+ }
143
+
144
+ if (stored === null) {
145
+ await writeStoredRegistryFingerprint(db, registry, current);
146
+ return null;
147
+ }
148
+
149
+ return rebuildReadCacheOrDefer(args, stored);
150
+ }
151
+
152
+ /**
153
+ * The drain-then-drop core (ADR-0006): rebuild the read cache at the current shape when
154
+ * nothing is owed locally, otherwise defer so un-flushed/quarantined writes are never
155
+ * dropped (the drain completes on a later boot).
156
+ */
157
+ async function rebuildReadCacheOrDefer<TRegistry extends SyncTableRegistry>(
158
+ args: {
159
+ db: MutationDb;
160
+ registry: TRegistry;
161
+ runtime: VersionReconcileRuntime;
162
+ onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;
163
+ },
164
+ previousFingerprint: string,
165
+ ): Promise<LocalStoreVersionEvent> {
166
+ const { db, registry, runtime, onSchemaChange } = args;
167
+ const current = runtime.registryVersion;
168
+ const stats = await runtime.readMutationStats();
169
+ const owedMutations = stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount;
170
+
171
+ if (owedMutations > 0) {
172
+ const event: LocalStoreVersionEvent = {
173
+ status: "deferred",
174
+ previousFingerprint,
175
+ nextFingerprint: current,
176
+ owedMutations,
177
+ };
178
+ await onSchemaChange?.(event);
179
+ return event;
180
+ }
181
+
182
+ await db.exec(buildWipeLocalStoreSql(registry));
183
+ await db.exec(generateLocalSchemaSql(registry));
184
+ await writeStoredRegistryFingerprint(db, registry, current);
185
+ const event: LocalStoreVersionEvent = {
186
+ status: "rebuilt",
187
+ previousFingerprint,
188
+ nextFingerprint: current,
189
+ owedMutations: 0,
190
+ };
191
+ await onSchemaChange?.(event);
192
+ return event;
193
+ }